_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 |
|---|---|---|---|---|---|---|---|---|
9dca08205bd9c12be3ce2ead7851a0c1fa6a93ff00d84d1a9c17d3ef7659084a | schell/ixshader | Swizzle.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
{-# LANGUAGE LambdaCase #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RebindableSyntax #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - missing - signatures #
# OPTIONS_GHC -fno - warn - orphans #
{-# OPTIONS_GHC -fprint-explicit-kinds #-}
module Graphics.IxShader.Swizzle
( Swizzled
, swizzle
, x
, y
, z
, xy
, xz
, yz
, xyz
) where
import Data.Proxy (Proxy (..))
import Data.Singletons.TypeLits
import Prelude hiding (Read, return, (>>), (>>=))
import Graphics.IxShader.Socket as G
import Graphics.IxShader.Qualifiers as G
import Graphics.IxShader.Types as G
type family Swizzled a b where
Swizzled 1 Xvec2 = Xfloat
Swizzled 1 Xvec3 = Xfloat
Swizzled 1 Xvec4 = Xfloat
Swizzled 2 Xvec2 = Xvec2
Swizzled 2 Xvec3 = Xvec2
Swizzled 2 Xvec4 = Xvec2
Swizzled 3 Xvec2 = Error "Swizzled error: vector field selection out of range"
Swizzled 3 Xvec3 = Xvec3
Swizzled 3 Xvec4 = Xvec3
Swizzled 4 Xvec2 = Error "Swizzled error: vector field selection out of range"
Swizzled 4 Xvec3 = Error "Swizzled error: vector field selection out of range"
Swizzled 4 Xvec4 = Xvec4
type SwizzleRead a n =
(Socketed a, Socketed (ReadFrom a), Socketed (Swizzled n (ReadFrom a)))
swizzle
:: forall (n :: Nat) a.
( SwizzleRead a n
, KnownNat n
)
=> String
-> a
-> Swizzled n (ReadFrom a)
swizzle s a = socket $ concat ["("
, unSocket a
, ")." ++ take (fromIntegral $ natVal $ Proxy @n) s
]
x :: forall a.
SwizzleRead a 1
=> a
-> Swizzled 1 (ReadFrom a)
x = swizzle @1 "x"
y :: forall a.
SwizzleRead a 1
=> a
-> Swizzled 1 (ReadFrom a)
y = swizzle @1 "y"
z :: forall a.
SwizzleRead a 1
=> a
-> Swizzled 1 (ReadFrom a)
z = swizzle @1 "z"
xy :: forall a.
SwizzleRead a 2
=> a
-> Swizzled 2 (ReadFrom a)
xy = swizzle @2 "xy"
xz :: forall a.
SwizzleRead a 2
=> a
-> Swizzled 2 (ReadFrom a)
xz = swizzle @2 "xz"
yz :: forall a.
SwizzleRead a 2
=> a
-> Swizzled 2 (ReadFrom a)
yz = swizzle @2 "yz"
xyz :: forall a.
SwizzleRead a 3
=> a
-> Swizzled 3 (ReadFrom a)
xyz = swizzle @3 "xyz"
| null | https://raw.githubusercontent.com/schell/ixshader/66e5302fa24bbdc7c948a79ee2422cae688b982f/src/Graphics/IxShader/Swizzle.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeInType #
# LANGUAGE TypeOperators #
# OPTIONS_GHC -fprint-explicit-kinds # | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE RebindableSyntax #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - missing - signatures #
# OPTIONS_GHC -fno - warn - orphans #
module Graphics.IxShader.Swizzle
( Swizzled
, swizzle
, x
, y
, z
, xy
, xz
, yz
, xyz
) where
import Data.Proxy (Proxy (..))
import Data.Singletons.TypeLits
import Prelude hiding (Read, return, (>>), (>>=))
import Graphics.IxShader.Socket as G
import Graphics.IxShader.Qualifiers as G
import Graphics.IxShader.Types as G
type family Swizzled a b where
Swizzled 1 Xvec2 = Xfloat
Swizzled 1 Xvec3 = Xfloat
Swizzled 1 Xvec4 = Xfloat
Swizzled 2 Xvec2 = Xvec2
Swizzled 2 Xvec3 = Xvec2
Swizzled 2 Xvec4 = Xvec2
Swizzled 3 Xvec2 = Error "Swizzled error: vector field selection out of range"
Swizzled 3 Xvec3 = Xvec3
Swizzled 3 Xvec4 = Xvec3
Swizzled 4 Xvec2 = Error "Swizzled error: vector field selection out of range"
Swizzled 4 Xvec3 = Error "Swizzled error: vector field selection out of range"
Swizzled 4 Xvec4 = Xvec4
type SwizzleRead a n =
(Socketed a, Socketed (ReadFrom a), Socketed (Swizzled n (ReadFrom a)))
swizzle
:: forall (n :: Nat) a.
( SwizzleRead a n
, KnownNat n
)
=> String
-> a
-> Swizzled n (ReadFrom a)
swizzle s a = socket $ concat ["("
, unSocket a
, ")." ++ take (fromIntegral $ natVal $ Proxy @n) s
]
x :: forall a.
SwizzleRead a 1
=> a
-> Swizzled 1 (ReadFrom a)
x = swizzle @1 "x"
y :: forall a.
SwizzleRead a 1
=> a
-> Swizzled 1 (ReadFrom a)
y = swizzle @1 "y"
z :: forall a.
SwizzleRead a 1
=> a
-> Swizzled 1 (ReadFrom a)
z = swizzle @1 "z"
xy :: forall a.
SwizzleRead a 2
=> a
-> Swizzled 2 (ReadFrom a)
xy = swizzle @2 "xy"
xz :: forall a.
SwizzleRead a 2
=> a
-> Swizzled 2 (ReadFrom a)
xz = swizzle @2 "xz"
yz :: forall a.
SwizzleRead a 2
=> a
-> Swizzled 2 (ReadFrom a)
yz = swizzle @2 "yz"
xyz :: forall a.
SwizzleRead a 3
=> a
-> Swizzled 3 (ReadFrom a)
xyz = swizzle @3 "xyz"
|
e4f0a5dfb888558b4a86b49660113f1824dc4ba32e7d196f6e3ed41651793f0c | martijnbastiaan/sprockell | DemoRandomOrder.hs | import Sprockell.System
{-
This program demonstrates how the ordering of access to the shared memory can vary.
All the sprockells try to write their own letter to the screen at the same time.
They will all be succeed, but the order in which this happens is undefined.
-}
loopCount = 10
prog :: [Instruction]
prog = [
Const (ord 'A') RegA
, Const (ord 'a' - ord 'A') RegE
, Compute Add RegA SPID RegB -- sprockell id as ascii character (uppercase)
, Compute Add RegB RegE RegC -- (lowercase)
, Const loopCount RegD
, Const 1 RegE
, Write RegB stdio -- write uppercase letter
, Write RegC stdio -- write lowercase letter
, Compute Sub RegD RegE RegD
, Branch RegD (Rel (-3))
--, Read (Addr 0x0) -- dummy read to ensure that
, Receive RegA -- all write request are done
, EndProg
]
main = run 4 prog >> putChar '\n'
| null | https://raw.githubusercontent.com/martijnbastiaan/sprockell/503c91b85f2ff1a6d3293a6691ea9799a7693bf2/src/DemoRandomOrder.hs | haskell |
This program demonstrates how the ordering of access to the shared memory can vary.
All the sprockells try to write their own letter to the screen at the same time.
They will all be succeed, but the order in which this happens is undefined.
sprockell id as ascii character (uppercase)
(lowercase)
write uppercase letter
write lowercase letter
, Read (Addr 0x0) -- dummy read to ensure that
all write request are done | import Sprockell.System
loopCount = 10
prog :: [Instruction]
prog = [
Const (ord 'A') RegA
, Const (ord 'a' - ord 'A') RegE
, Const loopCount RegD
, Const 1 RegE
, Compute Sub RegD RegE RegD
, Branch RegD (Rel (-3))
, EndProg
]
main = run 4 prog >> putChar '\n'
|
141dff4bc723682ca12466ceb404db376de9cad2622f6b9977a0c3679c04d35d | openworkload/swm-core | wm_session.erl | -module(wm_session).
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([handle_received_call/1, handle_received_cast/1]).
-include("../lib/wm_log.hrl").
-record(mstate, {}).
%% ============================================================================
%% API
%% ============================================================================
-spec start_link([term()]) -> {ok, pid()}.
start_link(Args) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, Args, []).
%% ============================================================================
%% Callbacks
%% ============================================================================
init(Args) ->
process_flag(trap_exit, true),
MState = parse_args(Args, #mstate{}),
?LOG_INFO("Session manager has been started ~p", [MState]),
{ok, MState}.
handle_call(Msg, From, #mstate{} = MState) ->
?LOG_DEBUG("Received unknown call from ~p: ~p", [From, Msg]),
{reply, ok, MState}.
handle_cast({call, Params}, #mstate{} = MState) ->
spawn(?MODULE, handle_received_call, [Params]),
{noreply, MState};
handle_cast({cast, Params}, #mstate{} = MState) ->
spawn(?MODULE, handle_received_cast, [Params]),
{noreply, MState};
handle_cast(Msg, #mstate{} = MState) ->
?LOG_DEBUG("Received unknown cast: ~p", [Msg]),
{noreply, MState}.
handle_info(Msg, #mstate{} = MState) ->
?LOG_DEBUG("Received unknown info message: ~p", [Msg]),
{noreply, MState}.
terminate(Reason, _) ->
wm_utils:terminate_msg(?MODULE, Reason).
code_change(_, #mstate{} = MState, _) ->
{ok, MState}.
%% ============================================================================
%% Implementation functions
%% ============================================================================
parse_args([], #mstate{} = MState) ->
MState;
parse_args([{_, _} | T], #mstate{} = MState) ->
parse_args(T, MState).
handle_received_call({wm_api, Fun, {Mod, Msg}, Socket, ServerPid}) ->
?LOG_DEBUG("Direct remote call: ~p:~p", [?MODULE, Fun]),
Return =
case verify_rpc(Mod, Fun, {Mod, Msg}, Socket) of
{ok, _} ->
Result =
case Msg of
ping ->
?LOG_DEBUG("I'm pinged by ~p", [Mod]),
% Special case is needed for:
1 . optimization
2 . wm_pinger may be busy pinging other nodes
{pong, wm_state:get_current()};
_ ->
wm_utils:protected_call(Mod, Msg)
end,
?LOG_DEBUG("Direct call result: ~P", [Result, 5]),
Result;
Error ->
{error, Error}
end,
wm_tcp_server:reply(Return, Socket),
ServerPid
! replied; % only now the connection can be closed
handle_received_call({Module, Arg0, [], Socket}) ->
handle_received_call({Module, Arg0, {}, Socket});
handle_received_call({Module, Arg0, Args, Socket, ServerPid}) ->
?LOG_DEBUG("API call: module=~p, arg0=~p", [Module, Arg0]),
case verify_rpc(Module, Arg0, Args, Socket) of
{ok, _} ->
try
Msg = erlang:insert_element(1, Args, Arg0),
Result = wm_utils:protected_call(Module, Msg),
? LOG_DEBUG("Call result : ~P " , [ Result , 10 ] ) ,
wm_tcp_server:reply(Result, Socket)
catch
T:Error ->
ErrRet = {string, io_lib:format("Cannot handle RPC to ~p: ~p(~P)", [Module, Arg0, Args, 5])},
?LOG_DEBUG("RPC FAILED [CALL]: ~p:~p", [T, Error]),
wm_tcp_server:reply(ErrRet, Socket)
end;
Error ->
wm_tcp_server:reply({error, Error}, Socket)
end,
ServerPid ! replied.
handle_received_cast({Module, Arg0, Args, Tag, Addr, Socket, ServerPid}) ->
ServerPid
! replied, % release the waiting connection process
?LOG_DEBUG("API cast: ~p ~p ~P ~p ~p", [Module, Arg0, Args, 5, Tag, Addr]),
case verify_rpc(Module, Arg0, Args, Socket) of
{ok, NewArgs} ->
case wm_conf:is_my_address(Addr) of
true ->
Msg = case NewArgs of
[] ->
{Arg0};
_ ->
erlang:insert_element(1, NewArgs, Arg0)
end,
gen_server:cast(Module, Msg);
false ->
wm_rpc:cast(Module, Arg0, NewArgs, Addr)
end,
wm_tcp_server:reply(ok, Socket);
Error ->
wm_tcp_server:reply({error, Error}, Socket)
end.
verify_rpc(_, route, {StartAddr, EndAddr, RouteID, Requestor, D, Route}, _) ->
{ok, {StartAddr, EndAddr, RouteID, Requestor, D, [node() | Route]}};
verify_rpc(_, _, Msg, _) ->
{ok, Msg}.
| null | https://raw.githubusercontent.com/openworkload/swm-core/3938bff619452a51cb2340db56ee6beb634e9314/src/net/wm_session.erl | erlang | ============================================================================
API
============================================================================
============================================================================
Callbacks
============================================================================
============================================================================
Implementation functions
============================================================================
Special case is needed for:
only now the connection can be closed
release the waiting connection process | -module(wm_session).
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([handle_received_call/1, handle_received_cast/1]).
-include("../lib/wm_log.hrl").
-record(mstate, {}).
-spec start_link([term()]) -> {ok, pid()}.
start_link(Args) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, Args, []).
init(Args) ->
process_flag(trap_exit, true),
MState = parse_args(Args, #mstate{}),
?LOG_INFO("Session manager has been started ~p", [MState]),
{ok, MState}.
handle_call(Msg, From, #mstate{} = MState) ->
?LOG_DEBUG("Received unknown call from ~p: ~p", [From, Msg]),
{reply, ok, MState}.
handle_cast({call, Params}, #mstate{} = MState) ->
spawn(?MODULE, handle_received_call, [Params]),
{noreply, MState};
handle_cast({cast, Params}, #mstate{} = MState) ->
spawn(?MODULE, handle_received_cast, [Params]),
{noreply, MState};
handle_cast(Msg, #mstate{} = MState) ->
?LOG_DEBUG("Received unknown cast: ~p", [Msg]),
{noreply, MState}.
handle_info(Msg, #mstate{} = MState) ->
?LOG_DEBUG("Received unknown info message: ~p", [Msg]),
{noreply, MState}.
terminate(Reason, _) ->
wm_utils:terminate_msg(?MODULE, Reason).
code_change(_, #mstate{} = MState, _) ->
{ok, MState}.
parse_args([], #mstate{} = MState) ->
MState;
parse_args([{_, _} | T], #mstate{} = MState) ->
parse_args(T, MState).
handle_received_call({wm_api, Fun, {Mod, Msg}, Socket, ServerPid}) ->
?LOG_DEBUG("Direct remote call: ~p:~p", [?MODULE, Fun]),
Return =
case verify_rpc(Mod, Fun, {Mod, Msg}, Socket) of
{ok, _} ->
Result =
case Msg of
ping ->
?LOG_DEBUG("I'm pinged by ~p", [Mod]),
1 . optimization
2 . wm_pinger may be busy pinging other nodes
{pong, wm_state:get_current()};
_ ->
wm_utils:protected_call(Mod, Msg)
end,
?LOG_DEBUG("Direct call result: ~P", [Result, 5]),
Result;
Error ->
{error, Error}
end,
wm_tcp_server:reply(Return, Socket),
ServerPid
handle_received_call({Module, Arg0, [], Socket}) ->
handle_received_call({Module, Arg0, {}, Socket});
handle_received_call({Module, Arg0, Args, Socket, ServerPid}) ->
?LOG_DEBUG("API call: module=~p, arg0=~p", [Module, Arg0]),
case verify_rpc(Module, Arg0, Args, Socket) of
{ok, _} ->
try
Msg = erlang:insert_element(1, Args, Arg0),
Result = wm_utils:protected_call(Module, Msg),
? LOG_DEBUG("Call result : ~P " , [ Result , 10 ] ) ,
wm_tcp_server:reply(Result, Socket)
catch
T:Error ->
ErrRet = {string, io_lib:format("Cannot handle RPC to ~p: ~p(~P)", [Module, Arg0, Args, 5])},
?LOG_DEBUG("RPC FAILED [CALL]: ~p:~p", [T, Error]),
wm_tcp_server:reply(ErrRet, Socket)
end;
Error ->
wm_tcp_server:reply({error, Error}, Socket)
end,
ServerPid ! replied.
handle_received_cast({Module, Arg0, Args, Tag, Addr, Socket, ServerPid}) ->
ServerPid
?LOG_DEBUG("API cast: ~p ~p ~P ~p ~p", [Module, Arg0, Args, 5, Tag, Addr]),
case verify_rpc(Module, Arg0, Args, Socket) of
{ok, NewArgs} ->
case wm_conf:is_my_address(Addr) of
true ->
Msg = case NewArgs of
[] ->
{Arg0};
_ ->
erlang:insert_element(1, NewArgs, Arg0)
end,
gen_server:cast(Module, Msg);
false ->
wm_rpc:cast(Module, Arg0, NewArgs, Addr)
end,
wm_tcp_server:reply(ok, Socket);
Error ->
wm_tcp_server:reply({error, Error}, Socket)
end.
verify_rpc(_, route, {StartAddr, EndAddr, RouteID, Requestor, D, Route}, _) ->
{ok, {StartAddr, EndAddr, RouteID, Requestor, D, [node() | Route]}};
verify_rpc(_, _, Msg, _) ->
{ok, Msg}.
|
b8261b76a70bdfe40d5a1f8d21ee4122b0eecad37a7f858003c8f0839c9df194 | serokell/qtah | QPen.hs | This file is part of Qtah .
--
Copyright 2015 - 2018 The Qtah Authors .
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details .
--
You should have received a copy of the GNU Lesser General Public License
-- along with this program. If not, see </>.
module Graphics.UI.Qtah.Generator.Interface.Gui.QPen (
aModule,
c_QPen,
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportClass),
addReqIncludes,
classSetConversionToGc,
classSetEntityPrefix,
ident,
includeStd,
makeClass,
mkCtor,
)
import Foreign.Hoppy.Generator.Spec.ClassFeature (
ClassFeature (Assignable, Copyable, Equatable),
classAddFeatures,
)
import Foreign.Hoppy.Generator.Types (objT)
import Graphics.UI.Qtah.Generator.Interface.Gui.QColor (c_QColor)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
{-# ANN module "HLint: ignore Use camelCase" #-}
aModule =
AQtModule $
makeQtModule ["Gui", "QPen"]
[ QtExport $ ExportClass c_QPen ]
c_QPen =
addReqIncludes [includeStd "QPen"] $
classSetConversionToGc $
classAddFeatures [Assignable, Copyable, Equatable] $
classSetEntityPrefix "" $
makeClass (ident "QPen") Nothing [] $
[ mkCtor "new" []
, mkCtor "newWithColor" [objT c_QColor]
]
| null | https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Gui/QPen.hs | haskell |
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
along with this program. If not, see </>.
# ANN module "HLint: ignore Use camelCase" # | This file is part of Qtah .
Copyright 2015 - 2018 The Qtah Authors .
the Free Software Foundation , either version 3 of the License , or
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
module Graphics.UI.Qtah.Generator.Interface.Gui.QPen (
aModule,
c_QPen,
) where
import Foreign.Hoppy.Generator.Spec (
Export (ExportClass),
addReqIncludes,
classSetConversionToGc,
classSetEntityPrefix,
ident,
includeStd,
makeClass,
mkCtor,
)
import Foreign.Hoppy.Generator.Spec.ClassFeature (
ClassFeature (Assignable, Copyable, Equatable),
classAddFeatures,
)
import Foreign.Hoppy.Generator.Types (objT)
import Graphics.UI.Qtah.Generator.Interface.Gui.QColor (c_QColor)
import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule)
import Graphics.UI.Qtah.Generator.Types
aModule =
AQtModule $
makeQtModule ["Gui", "QPen"]
[ QtExport $ ExportClass c_QPen ]
c_QPen =
addReqIncludes [includeStd "QPen"] $
classSetConversionToGc $
classAddFeatures [Assignable, Copyable, Equatable] $
classSetEntityPrefix "" $
makeClass (ident "QPen") Nothing [] $
[ mkCtor "new" []
, mkCtor "newWithColor" [objT c_QColor]
]
|
f421067dbab23bdf18f869ef8f3ac5b0add58c3623d6fa2f203a04f4f79497d3 | wdebeaum/step | employee.lisp | ;;;;
;;;; W::employee
;;;;
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::employee
(SENSES
((meta-data :origin calo :entry-date 20031230 :change-date nil :wn ("employee%1:18:00") :comments html-purchasing-corpus)
(LF-PARENT ONT::employee) ;professional)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/employee.lisp | lisp |
W::employee
professional) |
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::employee
(SENSES
((meta-data :origin calo :entry-date 20031230 :change-date nil :wn ("employee%1:18:00") :comments html-purchasing-corpus)
)
)
)
))
|
aa4909c533db6132db03b32e7db5801b320d4160a2660b9f7840cc5c16a43a7e | wdebeaum/DeepSemLex | stuck.lisp | (define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(w::stuck
(SENSES
((meta-data :origin adjective-reorganization :entry-date 20170403 :change-date nil :comments nil :wn nil :comlex nil)
(lf-parent ont::not-free-val)
)
)
)))
| null | https://raw.githubusercontent.com/wdebeaum/DeepSemLex/ce0e7523dd2b1ebd42b9e88ffbcfdb0fd339aaee/trips/src/LexiconManager/Data/new/stuck.lisp | lisp | (define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL
:words (
(w::stuck
(SENSES
((meta-data :origin adjective-reorganization :entry-date 20170403 :change-date nil :comments nil :wn nil :comlex nil)
(lf-parent ont::not-free-val)
)
)
)))
| |
94b5c68d0997db31f9784033bf123cb7285784e468d5aaa97096edf6490ecd88 | vikram/lisplibraries | color.lisp | Copyright ( c ) 2007 , 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.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
;;;
$ I d : color.lisp , v 1.3 2007/09/20 17:42:03 xach Exp $
(in-package #:vecto)
(defclass color () ())
(defclass rgba-color (color)
((red
:initarg :red
:accessor red)
(green
:initarg :green
:accessor green)
(blue
:initarg :blue
:accessor blue)
(alpha
:initarg :alpha
:accessor alpha))
(:default-initargs
:red 0.0 :green 0.0 :blue 0.0 :alpha 1.0))
(defmethod copy ((color rgba-color))
(make-instance 'rgba-color
:red (red color)
:green (green color)
:blue (blue color)
:alpha (alpha color)))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/vecto-1.1/color.lisp | lisp |
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.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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.
| Copyright ( c ) 2007 , All Rights Reserved
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
$ I d : color.lisp , v 1.3 2007/09/20 17:42:03 xach Exp $
(in-package #:vecto)
(defclass color () ())
(defclass rgba-color (color)
((red
:initarg :red
:accessor red)
(green
:initarg :green
:accessor green)
(blue
:initarg :blue
:accessor blue)
(alpha
:initarg :alpha
:accessor alpha))
(:default-initargs
:red 0.0 :green 0.0 :blue 0.0 :alpha 1.0))
(defmethod copy ((color rgba-color))
(make-instance 'rgba-color
:red (red color)
:green (green color)
:blue (blue color)
:alpha (alpha color)))
|
cba0a73462a25cb74a1f649f0f368fa7a02fc09e750be43794cb77fca6d9ab71 | mbutterick/aoc-racket | 12.rkt | #lang br
(require racket/file sugar rackunit racket/set racket/bool)
(define links (for/set ([line (file->lines "12.rktd")])
(list->set (string-split line "-"))))
(define (is-downcase? loc) (equal? (string-downcase loc) loc))
(define (paths-from last-loc links [small-caves (set)])
(match last-loc
["end" '(("end"))]
[loc #:when (and small-caves (set-member? small-caves loc))
(define pruned-links
(for*/set ([previous-locs (in-value (set-remove small-caves loc))]
[link links]
#:when (set-empty? (set-intersect link previous-locs)))
link))
(paths-from last-loc pruned-links #false)]
[loc
(define next-lc-visited (cond
[(false? small-caves) #false]
[(and (is-downcase? loc) (not (equal? loc "start")))
(set-add small-caves loc)]
[else small-caves]))
(define links-with-loc (for/set ([link links]
#:when (set-member? link loc))
link))
(define remaining-links (if (or (equal? loc "start")
(and (is-downcase? loc) (not small-caves)))
(set-subtract links links-with-loc)
links))
(for*/list ([link links-with-loc]
[next-loc (in-value (set-first (set-remove link loc)))]
[path (paths-from next-loc remaining-links next-lc-visited)])
(cons loc path))]))
(check-equal? (length (paths-from "start" links #f)) 5576)
(check-equal? (length (paths-from "start" links)) 152837) | null | https://raw.githubusercontent.com/mbutterick/aoc-racket/af8752d29ecf8642dfc93bad7bed2ef2f9f62fd8/2021/12.rkt | racket | #lang br
(require racket/file sugar rackunit racket/set racket/bool)
(define links (for/set ([line (file->lines "12.rktd")])
(list->set (string-split line "-"))))
(define (is-downcase? loc) (equal? (string-downcase loc) loc))
(define (paths-from last-loc links [small-caves (set)])
(match last-loc
["end" '(("end"))]
[loc #:when (and small-caves (set-member? small-caves loc))
(define pruned-links
(for*/set ([previous-locs (in-value (set-remove small-caves loc))]
[link links]
#:when (set-empty? (set-intersect link previous-locs)))
link))
(paths-from last-loc pruned-links #false)]
[loc
(define next-lc-visited (cond
[(false? small-caves) #false]
[(and (is-downcase? loc) (not (equal? loc "start")))
(set-add small-caves loc)]
[else small-caves]))
(define links-with-loc (for/set ([link links]
#:when (set-member? link loc))
link))
(define remaining-links (if (or (equal? loc "start")
(and (is-downcase? loc) (not small-caves)))
(set-subtract links links-with-loc)
links))
(for*/list ([link links-with-loc]
[next-loc (in-value (set-first (set-remove link loc)))]
[path (paths-from next-loc remaining-links next-lc-visited)])
(cons loc path))]))
(check-equal? (length (paths-from "start" links #f)) 5576)
(check-equal? (length (paths-from "start" links)) 152837) | |
d93711a6ab3fd20f600fcf7db3aecd9af6417eed74a7bc3a8b3ec8682fc8dac9 | karimarttila/clojure | http.clj | (ns worldstat.backend.routes.http
(:require
[reitit.ring :as ring]
[reitit.coercion.malli]
[reitit.swagger :as swagger]
[reitit.ring.coercion :as coercion]
[reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.exception :as exception]
[reitit.ring.middleware.multipart :as multipart]
[reitit.ring.middleware.parameters :as parameters]
[reitit.dev.pretty :as pretty]
[reitit.ring.spec :as spec]
[ ]
[muuntaja.core :as m]
[clojure.tools.logging :as log]
[ring.util.http-response :as r]))
Test : http localhost:5522 / worldstat / api / health / ping
(defn handler [{:keys [routes]}]
(ring/ring-handler
(ring/router
routes
{:validate spec/validate ;; enable spec validation for route data
; Use this to debug middleware handling:
: reitit.middleware/transform reitit.ring.middleware.dev/print-request-diffs
:exception pretty/exception ;; pretty exceptions
:data {:coercion (reitit.coercion.malli/create) ;; malli
:muuntaja m/instance ;; default content negotiation
:middleware [;; swagger feature
swagger/swagger-feature
;; query-params & form-params
parameters/parameters-middleware
;; content-negotiation
muuntaja/format-negotiate-middleware
;; encoding response body
muuntaja/format-response-middleware
;; exception handling
(exception/create-exception-middleware
(merge
exception/default-handlers
{::exception/wrap (fn [handler ^Exception e request]
(log/error e (.getMessage e))
(handler e request))}))
;; decoding request body
muuntaja/format-request-middleware
;; coercing response bodys
coercion/coerce-response-middleware
;; coercing request parameters
coercion/coerce-request-middleware
;; multipart
multipart/multipart-middleware]}})
(ring/routes
(ring/redirect-trailing-slash-handler)
(ring/create-file-handler {:path "/worldstat", :root "target/shadow/dev/resources/public"})
(ring/create-resource-handler {:path "/worldstat"})
(ring/create-default-handler))))
| null | https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/statistics/worldstat/src/clj/worldstat/backend/routes/http.clj | clojure | enable spec validation for route data
Use this to debug middleware handling:
pretty exceptions
malli
default content negotiation
swagger feature
query-params & form-params
content-negotiation
encoding response body
exception handling
decoding request body
coercing response bodys
coercing request parameters
multipart | (ns worldstat.backend.routes.http
(:require
[reitit.ring :as ring]
[reitit.coercion.malli]
[reitit.swagger :as swagger]
[reitit.ring.coercion :as coercion]
[reitit.ring.middleware.muuntaja :as muuntaja]
[reitit.ring.middleware.exception :as exception]
[reitit.ring.middleware.multipart :as multipart]
[reitit.ring.middleware.parameters :as parameters]
[reitit.dev.pretty :as pretty]
[reitit.ring.spec :as spec]
[ ]
[muuntaja.core :as m]
[clojure.tools.logging :as log]
[ring.util.http-response :as r]))
Test : http localhost:5522 / worldstat / api / health / ping
(defn handler [{:keys [routes]}]
(ring/ring-handler
(ring/router
routes
: reitit.middleware/transform reitit.ring.middleware.dev/print-request-diffs
swagger/swagger-feature
parameters/parameters-middleware
muuntaja/format-negotiate-middleware
muuntaja/format-response-middleware
(exception/create-exception-middleware
(merge
exception/default-handlers
{::exception/wrap (fn [handler ^Exception e request]
(log/error e (.getMessage e))
(handler e request))}))
muuntaja/format-request-middleware
coercion/coerce-response-middleware
coercion/coerce-request-middleware
multipart/multipart-middleware]}})
(ring/routes
(ring/redirect-trailing-slash-handler)
(ring/create-file-handler {:path "/worldstat", :root "target/shadow/dev/resources/public"})
(ring/create-resource-handler {:path "/worldstat"})
(ring/create-default-handler))))
|
74f79c4570a1bc4598ace03b13643e14ba6821c6f353f244f2e13a70861db629 | btmura/b1 | MovingAverageLines.hs | module B1.Program.Chart.MovingAverageLines
( getVboSpecs
) where
import Graphics.Rendering.OpenGL
import B1.Data.Technicals.MovingAverage
import B1.Data.Technicals.StockData
import B1.Graphics.Rendering.OpenGL.Box
import B1.Program.Chart.Colors
import B1.Program.Chart.GraphUtils
import B1.Program.Chart.Vbo
getVboSpecs :: StockPriceData -> Box -> [VboSpec]
getVboSpecs priceData bounds =
map (uncurry (createMovingAverageVboSpec priceData bounds))
movingAverageFunctions
where
movingAverageFunctions =
[ (movingAverage25, purple3)
, (movingAverage50, yellow3)
, (movingAverage200, white3)
]
createMovingAverageVboSpec :: StockPriceData -> Box
-> (StockPriceData -> [MovingAverage]) -> Color3 GLfloat -> VboSpec
createMovingAverageVboSpec priceData bounds movingAverageFunction color =
VboSpec LineStrip size elements
where
size = getMovingAverageSize priceData movingAverageFunction
elements = getMovingAverageLines priceData bounds
movingAverageFunction color
getMovingAverageSize :: StockPriceData
-> (StockPriceData -> [MovingAverage]) -> Int
getMovingAverageSize priceData movingAverageFunction =
getLineSize $ trim $ movingAverageFunction priceData
where
trim = take $ numDailyElements priceData
getLineSize :: [a] -> Int
getLineSize list = size
where
numElements = length list
x , y , and 3 for color
size = numElements * floatsPerVertex
getMovingAverageLines :: StockPriceData -> Box
-> (StockPriceData -> [MovingAverage]) -> Color3 GLfloat -> [GLfloat]
getMovingAverageLines priceData bounds movingAverageFunction color = lineStrip
where
priceRange = getPriceRange priceData
numElements = numDailyElements priceData
values = take numElements $ movingAverageFunction priceData
percentages = map (realToFrac . heightPercentage priceRange) values
indices = [0 .. numElements - 1]
points = map (colorLineStripPoint bounds color percentages numElements)
indices
lineStrip = concat points
| null | https://raw.githubusercontent.com/btmura/b1/9cf0514ba1e03e9f4da05be9231acde07b199864/src/B1/Program/Chart/MovingAverageLines.hs | haskell | module B1.Program.Chart.MovingAverageLines
( getVboSpecs
) where
import Graphics.Rendering.OpenGL
import B1.Data.Technicals.MovingAverage
import B1.Data.Technicals.StockData
import B1.Graphics.Rendering.OpenGL.Box
import B1.Program.Chart.Colors
import B1.Program.Chart.GraphUtils
import B1.Program.Chart.Vbo
getVboSpecs :: StockPriceData -> Box -> [VboSpec]
getVboSpecs priceData bounds =
map (uncurry (createMovingAverageVboSpec priceData bounds))
movingAverageFunctions
where
movingAverageFunctions =
[ (movingAverage25, purple3)
, (movingAverage50, yellow3)
, (movingAverage200, white3)
]
createMovingAverageVboSpec :: StockPriceData -> Box
-> (StockPriceData -> [MovingAverage]) -> Color3 GLfloat -> VboSpec
createMovingAverageVboSpec priceData bounds movingAverageFunction color =
VboSpec LineStrip size elements
where
size = getMovingAverageSize priceData movingAverageFunction
elements = getMovingAverageLines priceData bounds
movingAverageFunction color
getMovingAverageSize :: StockPriceData
-> (StockPriceData -> [MovingAverage]) -> Int
getMovingAverageSize priceData movingAverageFunction =
getLineSize $ trim $ movingAverageFunction priceData
where
trim = take $ numDailyElements priceData
getLineSize :: [a] -> Int
getLineSize list = size
where
numElements = length list
x , y , and 3 for color
size = numElements * floatsPerVertex
getMovingAverageLines :: StockPriceData -> Box
-> (StockPriceData -> [MovingAverage]) -> Color3 GLfloat -> [GLfloat]
getMovingAverageLines priceData bounds movingAverageFunction color = lineStrip
where
priceRange = getPriceRange priceData
numElements = numDailyElements priceData
values = take numElements $ movingAverageFunction priceData
percentages = map (realToFrac . heightPercentage priceRange) values
indices = [0 .. numElements - 1]
points = map (colorLineStripPoint bounds color percentages numElements)
indices
lineStrip = concat points
| |
f767346846145fdf0ba66861059c76084f8958d38dbf662589cd1b9416527440 | AbstractMachinesLab/caramel | gadt.ml |
type _ term =
| Int : int -> int term
| Pair : 'a term * 'b term -> ('a * 'b) term
| Fst : ('a * 'b) term -> 'a term
| Snd : ('a * 'b) term -> 'b term
let rec eval : type a . a term -> a = function
| Int n -> n
| Pair (a, b) -> eval a, eval b
| Fst p -> fst (eval p)
| Snd p -> snd (eval p)
| null | https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/tests/test-dirs/type-enclosing/types/gadt.ml | ocaml |
type _ term =
| Int : int -> int term
| Pair : 'a term * 'b term -> ('a * 'b) term
| Fst : ('a * 'b) term -> 'a term
| Snd : ('a * 'b) term -> 'b term
let rec eval : type a . a term -> a = function
| Int n -> n
| Pair (a, b) -> eval a, eval b
| Fst p -> fst (eval p)
| Snd p -> snd (eval p)
| |
fb7b4540720d74db6731cf4dd394bedffa886b8558f75ae58e186aa792ddfea8 | lambdaisland/kaocha-cljs2 | cljs2.clj | (ns kaocha.cljs2)
| null | https://raw.githubusercontent.com/lambdaisland/kaocha-cljs2/cc9c12c6472fb411445827a399479762906ae4b4/src/kaocha/cljs2.clj | clojure | (ns kaocha.cljs2)
| |
3e40f30ee0041ab23bb31ddb58d662018a129714b1a563da0587dc26cc1de156 | gelisam/klister | Primitives.hs | # LANGUAGE BlockArguments #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
{-# OPTIONS -Wno-name-shadowing #-}
module Expander.Primitives
( -- * Declaration primitives
define
, datatype
, defineMacros
, example
, run
, group
, meta
-- * Expression primitives
, app
, integerLiteral
, stringLiteral
, bindMacro
, consListSyntax
, dataCase
, emptyListSyntax
, err
, flet
, identEqual
, identSyntax
, lambda
, letExpr
, letSyntax
, listSyntax
, integerSyntax
, stringSyntax
, makeIntroducer
, Expander.Primitives.log
, whichProblem
, pureMacro
, quote
, replaceLoc
, syntaxCase
, syntaxError
, the
, typeCase
-- * Pattern primitives
, elsePattern
-- * Module primitives
, makeModule
-- * Anywhere primitives
, makeLocalType
-- * Primitive values
, unaryIntegerPrim
, binaryIntegerPrim
, binaryIntegerPred
, binaryStringPred
-- * Helpers
, prepareVar
, baseType
, typeConstructor
, primitiveDatatype
) where
import Control.Lens hiding (List)
import Control.Monad.IO.Class
import Control.Monad.Except
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
import Data.Traversable
import Numeric.Natural
import Binding
import Core
import Datatype
import qualified Env
import Expander.DeclScope
import Expander.Monad
import Expander.Syntax
import Expander.TC
import Kind
import Module
import ModuleName
import Phase
import Scope
import ScopeSet (ScopeSet)
import qualified ScopeSet
import ShortShow
import SplitCore
import SplitType
import Syntax
import Type
import Value
----------------------------
-- Declaration primitives --
----------------------------
type DeclPrim =
DeclTreePtr -> DeclOutputScopesPtr -> Syntax -> Expand ()
type DeclExpander =
DeclTreePtr -> ScopeSet -> DeclOutputScopesPtr -> Syntax -> Expand ()
define :: DeclPrim
define dest outScopesDest stx = do
p <- currentPhase
Stx _ _ (_, varStx, expr) <- mustHaveEntries stx
postDefineScope <- freshScope $ T.pack $ "For definition at " ++ shortShow (stxLoc stx)
x <- addScope' postDefineScope <$> mustBeIdent varStx
b <- freshBinding
addDefinedBinding x b
var <- freshVar
exprDest <- liftIO $ newSplitCorePtr
bind b (EIncompleteDefn var x exprDest)
schPtr <- liftIO $ newSchemePtr
linkOneDecl dest (Define x var schPtr exprDest)
t <- inTypeBinder do
t <- tMetaVar <$> freshMeta (Just KStar)
forkExpandSyntax (ExprDest t exprDest) expr
return t
ph <- currentPhase
modifyState $ over (expanderDefTypes . at ph . non Env.empty) $
Env.insert var x schPtr
forkGeneralizeType exprDest t schPtr
linkDeclOutputScopes outScopesDest (ScopeSet.singleScopeAtPhase postDefineScope p)
datatype :: DeclPrim
datatype dest outScopesDest stx = do
Stx scs loc (_ :: Syntax, more) <- mustBeCons stx
Stx _ _ (nameAndArgs, ctorSpecs) <- mustBeCons (Syntax (Stx scs loc (List more)))
Stx _ _ (name, args) <- mustBeCons nameAndArgs
typeArgs <- for (zip [0..] args) $ \(i, a) ->
prepareTypeVar i a
sc <- freshScope $ T.pack $ "For datatype at " ++ shortShow (stxLoc stx)
let typeScopes = map (view _1) typeArgs ++ [sc]
realName <- mustBeIdent (addScope' sc name)
p <- currentPhase
d <- freshDatatype realName
let argKinds = map (view _3) typeArgs
addDatatype realName d argKinds
ctors <- for ctorSpecs \ spec -> do
Stx _ _ (cn, ctorArgs) <- mustBeCons spec
realCN <- mustBeIdent cn
ctor <- freshConstructor realCN
let ctorArgs' = [ foldr (addScope p) t typeScopes
| t <- ctorArgs
]
argTypes <- traverse (scheduleType KStar) ctorArgs'
return (realCN, ctor, argTypes)
let info =
DatatypeInfo
{ _datatypeArgKinds = argKinds
, _datatypeConstructors =
[ ctor | (_, ctor, _) <- ctors ]
}
modifyState $
set (expanderCurrentDatatypes .
at p . non Map.empty .
at d) $
Just info
forkEstablishConstructors (ScopeSet.singleScopeAtPhase sc p) outScopesDest d ctors
linkOneDecl dest (Data realName (view datatypeName d) argKinds ctors)
defineMacros :: DeclPrim
defineMacros dest outScopesDest stx = do
Stx _ _ (_, macroList) <- mustHaveEntries stx
Stx _ _ macroDefs <- mustBeList macroList
p <- currentPhase
-- 'sc' allows the newly-defined macros to generate code containing calls to
-- any of the other newly-defined macros, while 'postDefineScope' allows the
code which follows the @define - macros@ call to refer to the newly - defined
-- macros.
sc <- freshScope $ T.pack $ "For macros at " ++ shortShow (stxLoc stx)
postDefineScope <- freshScope $ T.pack $ "For macro-definition at " ++ shortShow (stxLoc stx)
macros <- for macroDefs $ \def -> do
Stx _ _ (mname, mdef) <- mustHaveEntries def
theName <- addScope' sc <$> mustBeIdent mname
b <- freshBinding
addDefinedBinding theName b
macroDest <- inEarlierPhase $
schedule (tFun1 tSyntax (tMacro tSyntax))
(addScope p sc mdef)
v <- freshMacroVar
bind b $ EIncompleteMacro v theName macroDest
return (theName, v, macroDest)
linkOneDecl dest $ DefineMacros macros
linkDeclOutputScopes outScopesDest ( ScopeSet.insertAtPhase p sc
$ ScopeSet.insertAtPhase p postDefineScope
$ ScopeSet.empty
)
example :: DeclPrim
example dest outScopesDest stx = do
Stx _ _ (_, expr) <- mustHaveEntries stx
exprDest <- liftIO $ newSplitCorePtr
sch <- liftIO newSchemePtr
linkOneDecl dest (Example (view (unSyntax . stxSrcLoc) stx) sch exprDest)
t <- inTypeBinder do
t <- tMetaVar <$> freshMeta (Just KStar)
forkExpandSyntax (ExprDest t exprDest) expr
return t
forkGeneralizeType exprDest t sch
linkDeclOutputScopes outScopesDest mempty
run :: DeclPrim
run dest outScopesDest stx = do
Stx _ _ (_, expr) <- mustHaveEntries stx
exprDest <- liftIO $ newSplitCorePtr
linkOneDecl dest (Run (stxLoc stx) exprDest)
forkExpandSyntax (ExprDest (tIO (primitiveDatatype "Unit" [])) exprDest) expr
linkDeclOutputScopes outScopesDest mempty
meta :: DeclExpander -> DeclPrim
meta expandDeclForms dest outScopesDest stx = do
(_ :: Syntax, subDecls) <- mustHaveShape stx
subDest <- newDeclTreePtr
linkOneDecl dest (Meta subDest)
inEarlierPhase $
expandDeclForms subDest mempty outScopesDest =<< addRootScope subDecls
group :: DeclExpander -> DeclPrim
group expandDeclForms dest outScopesDest stx = do
(_ :: Syntax, decls) <- mustHaveShape stx
expandDeclForms dest mempty outScopesDest decls
-- Expression primitives
type ExprPrim = Ty -> SplitCorePtr -> Syntax -> Expand ()
err :: ExprPrim
err _t dest stx = do
Stx _ _ (_, msg) <- mustHaveEntries stx
msgDest <- schedule tSyntax msg
linkExpr dest $ CoreError msgDest
the :: ExprPrim
the t dest stx = do
Stx _ _ (_, ty, expr) <- mustHaveEntries stx
saveOrigin dest (stxLoc expr)
tyDest <- scheduleType KStar ty
-- TODO add type to elaborated program? Or not?
forkAwaitingType tyDest [TypeThenUnify dest t, TypeThenExpandExpr dest expr]
letExpr :: ExprPrim
letExpr t dest stx = do
Stx _ _ (_, b, body) <- mustHaveEntries stx
Stx _ _ (x, def) <- mustHaveEntries b
(sc, x', coreX) <- prepareVar x
p <- currentPhase
psc <- phaseRoot
(defDest, xTy) <- inTypeBinder do
xt <- tMetaVar <$> freshMeta (Just KStar)
defDest <- schedule xt def
return (defDest, xt)
sch <- liftIO $ newSchemePtr
forkGeneralizeType defDest xTy sch
bodyDest <- withLocalVarType x' coreX sch $
schedule t $
addScope p psc $
addScope p sc body
linkExpr dest $ CoreLet x' coreX defDest bodyDest
flet :: ExprPrim
flet t dest stx = do
ft <- inTypeBinder $ tMetaVar <$> freshMeta (Just KStar)
xt <- inTypeBinder $ tMetaVar <$> freshMeta (Just KStar)
rt <- inTypeBinder $ tMetaVar <$> freshMeta (Just KStar)
fsch <- trivialScheme ft
xsch <- trivialScheme xt
Stx _ _ (_, b, body) <- mustHaveEntries stx
Stx _ _ (f, args, def) <- mustHaveEntries b
Stx _ _ (Identity x) <- mustHaveEntries args
(fsc, f', coreF) <- prepareVar f
(xsc, x', coreX) <- prepareVar x
p <- currentPhase
psc <- phaseRoot
defDest <- inTypeBinder $
withLocalVarType f' coreF fsch $
withLocalVarType x' coreX xsch $
schedule rt $
addScope p psc $
addScope p xsc $
addScope p fsc def
unify dest ft (tFun1 xt rt)
sch <- liftIO newSchemePtr
forkGeneralizeType defDest ft sch
bodyDest <- withLocalVarType f' coreF sch $
schedule t $
addScope p psc $
addScope p fsc body
linkExpr dest $ CoreLetFun f' coreF x' coreX defDest bodyDest
lambda :: ExprPrim
lambda t dest stx = do
Stx _ _ (_, arg, body) <- mustHaveEntries stx
Stx _ _ (Identity theArg) <- mustHaveEntries arg
(sc, arg', coreArg) <- prepareVar theArg
p <- currentPhase
psc <- phaseRoot
argT <- tMetaVar <$> freshMeta (Just KStar)
retT <- tMetaVar <$> freshMeta (Just KStar)
unify dest t (tFun1 argT retT)
sch <- trivialScheme argT
bodyDest <-
withLocalVarType arg' coreArg sch $
schedule retT $
addScope p psc $
addScope p sc body
linkExpr dest $ CoreLam arg' coreArg bodyDest
app :: ExprPrim
app t dest stx = do
argT <- tMetaVar <$> freshMeta (Just KStar)
Stx _ _ (_, fun, arg) <- mustHaveEntries stx
funDest <- schedule (tFun1 argT t) fun
argDest <- schedule argT arg
linkExpr dest $ CoreApp funDest argDest
integerLiteral :: ExprPrim
integerLiteral t dest stx = do
Stx _ _ (_, arg) <- mustHaveEntries stx
Stx _ _ i <- mustBeInteger arg
unify dest t tInteger
linkExpr dest (CoreInteger i)
saveExprType dest t
stringLiteral :: ExprPrim
stringLiteral t dest stx = do
Stx _ _ (_, arg) <- mustHaveEntries stx
Stx _ _ s <- mustBeString arg
unify dest t tString
linkExpr dest (CoreString s)
saveExprType dest t
pureMacro :: ExprPrim
pureMacro t dest stx = do
Stx _ _ (_, v) <- mustHaveEntries stx
innerT <- tMetaVar <$> freshMeta (Just KStar)
unify dest (tMacro innerT) t
argDest <- schedule innerT v
linkExpr dest $ CorePureMacro argDest
bindMacro :: ExprPrim
bindMacro t dest stx = do
a <- tMetaVar <$> freshMeta (Just KStar)
b <- tMetaVar <$> freshMeta (Just KStar)
Stx _ _ (_, act, cont) <- mustHaveEntries stx
actDest <- schedule (tMacro a) act
contDest <- schedule (tFun1 a (tMacro b)) cont
unify dest t (tMacro b)
linkExpr dest $ CoreBindMacro actDest contDest
syntaxError :: ExprPrim
syntaxError t dest stx = do
a <- tMetaVar <$> freshMeta (Just KStar)
unify dest t (tMacro a)
Stx scs srcloc (_, args) <- mustBeCons stx
Stx _ _ (msg, locs) <- mustBeCons $ Syntax $ Stx scs srcloc (List args)
msgDest <- schedule tSyntax msg
locDests <- traverse (schedule tSyntax) locs
linkExpr dest $ CoreSyntaxError (SyntaxError locDests msgDest)
identEqual :: HowEq -> ExprPrim
identEqual how t dest stx = do
unify dest t (tMacro (primitiveDatatype "Bool" []))
Stx _ _ (_, id1, id2) <- mustHaveEntries stx
newE <- CoreIdentEq how <$> schedule tSyntax id1 <*> schedule tSyntax id2
linkExpr dest newE
quote :: ExprPrim
quote t dest stx = do
unify dest t tSyntax
Stx _ _ (_, quoted) <- mustHaveEntries stx
linkExpr dest $ CoreSyntax quoted
identSyntax :: ExprPrim
identSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, someId, source) <- mustHaveEntries stx
idDest <- schedule tSyntax someId
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreIdent $ ScopedIdent idDest sourceDest
emptyListSyntax :: ExprPrim
emptyListSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, source) <- mustHaveEntries stx
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreEmpty $ ScopedEmpty sourceDest
consListSyntax :: ExprPrim
consListSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, car, cdr, source) <- mustHaveEntries stx
carDest <- schedule tSyntax car
cdrDest <- schedule tSyntax cdr
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreCons $ ScopedCons carDest cdrDest sourceDest
listSyntax :: ExprPrim
listSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, list, source) <- mustHaveEntries stx
listItems <- mustHaveShape list
listDests <- traverse (schedule tSyntax) listItems
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreList $ ScopedList listDests sourceDest
integerSyntax :: ExprPrim
integerSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, int, source) <- mustHaveEntries stx
intDest <- schedule tInteger int
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreIntegerSyntax $ ScopedInteger intDest sourceDest
stringSyntax :: ExprPrim
stringSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, str, source) <- mustHaveEntries stx
strDest <- schedule tString str
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreStringSyntax $ ScopedString strDest sourceDest
replaceLoc :: ExprPrim
replaceLoc t dest stx = do
unify dest t tSyntax
Stx _ _ (_, loc, valStx) <- mustHaveEntries stx
locDest <- schedule tSyntax loc
valStxDest <- schedule tSyntax valStx
linkExpr dest $ CoreReplaceLoc locDest valStxDest
syntaxCase :: ExprPrim
syntaxCase t dest stx = do
Stx scs loc (_ :: Syntax, args) <- mustBeCons stx
Stx _ _ (scrutinee, patterns) <- mustBeCons (Syntax (Stx scs loc (List args)))
scrutDest <- schedule tSyntax scrutinee
patternDests <- traverse (mustHaveEntries >=> expandPatternCase t) patterns
linkExpr dest $ CoreCase loc scrutDest patternDests
letSyntax :: ExprPrim
letSyntax t dest stx = do
Stx _ loc (_, macro, body) <- mustHaveEntries stx
Stx _ _ (mName, mdef) <- mustHaveEntries macro
sc <- freshScope $ T.pack $ "Scope for let-syntax at " ++ shortShow loc
m <- mustBeIdent mName
p <- currentPhase
-- Here, the binding occurrence of the macro gets the
-- fresh scope at all phases, but later, the scope is only
-- added to the correct phase in potential use sites.
-- This prevents the body of the macro (in an earlier
-- phase) from being able to refer to the macro itself.
let m' = addScope' sc m
b <- freshBinding
addLocalBinding m' b
v <- freshMacroVar
macroDest <- inEarlierPhase $ do
psc <- phaseRoot
schedule (tFun1 tSyntax (tMacro tSyntax))
(addScope (prior p) psc mdef)
forkAwaitingMacro b v m' macroDest (ExprDest t dest) (addScope p sc body)
makeIntroducer :: ExprPrim
makeIntroducer t dest stx = do
Stx _ _ (Identity mName) <- mustHaveEntries stx
_ <- mustBeIdent mName
unify dest theType t
linkExpr dest $ CoreMakeIntroducer
where
theType =
tMacro (tFun [primitiveDatatype "ScopeAction" [], tSyntax] tSyntax)
log :: ExprPrim
log t dest stx = do
unify dest (tMacro (primitiveDatatype "Unit" [])) t
Stx _ _ (_, message) <- mustHaveEntries stx
msgDest <- schedule tSyntax message
linkExpr dest $ CoreLog msgDest
whichProblem :: ExprPrim
whichProblem t dest stx = do
unify dest (tMacro (primitiveDatatype "Problem" [])) t
Stx _ _ (Identity _) <- mustHaveEntries stx
linkExpr dest CoreWhichProblem
dataCase :: ExprPrim
dataCase t dest stx = do
Stx _ loc (_, scrut, cases) <- mustBeConsCons stx
a <- tMetaVar <$> freshMeta (Just KStar)
scrutineeDest <- schedule a scrut
cases' <- traverse (mustHaveEntries >=> scheduleDataPattern t a) cases
linkExpr dest $ CoreDataCase loc scrutineeDest cases'
typeCase :: ExprPrim
typeCase t dest stx = do
Stx _ loc (_, scrut, cases) <- mustBeConsCons stx
a <- tMetaVar <$> freshMeta (Just KStar)
unify dest (tMacro a) t
scrutineeDest <- schedule tType scrut
cases' <- traverse (mustHaveEntries >=> scheduleTypePattern t) cases
linkExpr dest $ CoreTypeCase loc scrutineeDest cases'
---------------------
-- Type Primitives --
---------------------
type TypePrim =
(Kind -> SplitTypePtr -> Syntax -> Expand (), TypePatternPtr -> Syntax -> Expand ())
typeConstructor :: TypeConstructor -> [Kind] -> TypePrim
typeConstructor ctor argKinds = (implT, implP)
where
implT k dest stx = do
Stx _ _ (_, args) <- mustBeCons stx
if length args > length argKinds
then throwError $ WrongTypeArity stx ctor
(fromIntegral $ length argKinds)
(length args)
else do
let missingArgs :: [Kind]
missingArgs = drop (length args) argKinds
equateKinds stx (kFun missingArgs KStar) k
argDests <- traverse (uncurry scheduleType) (zip argKinds args)
linkType dest $ TyF ctor argDests
implP dest stx = do
Stx _ _ (_, args) <- mustBeCons stx
if length args > length argKinds
then throwError $ WrongTypeArity stx ctor
(fromIntegral $ length argKinds)
(length args)
else do
varInfo <- traverse prepareVar args
sch <- trivialScheme tType
-- FIXME kind check here
linkTypePattern dest
(TypePattern $ TyF ctor [ (varStx, var)
| (_, varStx, var) <- varInfo
])
[ (sc, n, x, sch)
| (sc, n, x) <- varInfo
]
baseType :: TypeConstructor -> TypePrim
baseType ctor = typeConstructor ctor []
-------------
-- Modules --
-------------
makeModule :: DeclExpander -> DeclTreePtr -> Syntax -> Expand ()
makeModule expandDeclForms bodyPtr stx =
view expanderModuleTop <$> getState >>=
\case
Just _ ->
error "TODO throw real error - already expanding a module"
Nothing -> do
modifyState $ set expanderModuleTop (Just bodyPtr)
(_ :: Syntax, body) <- mustHaveShape stx
outScopesDest <- newDeclOutputScopesPtr
expandDeclForms bodyPtr mempty outScopesDest body
pure ()
--------------
-- Anywhere --
--------------
-- | with-unknown-type's implementation: create a named fresh
-- unification variable for macros that only can annotate part of a
-- type.
makeLocalType :: MacroDest -> Syntax -> Expand ()
makeLocalType dest stx = do
Stx _ _ (_, binder, body) <- mustHaveEntries stx
Stx _ _ (Identity theVar) <- mustHaveEntries binder
(sc, n, b) <- varPrepHelper theVar
meta <- freshMeta Nothing
let t = TMetaVar meta
let tyImpl k tdest tstx = do
k' <- typeVarKind meta
equateKinds tstx k k'
_ <- mustBeIdent tstx
linkType tdest $ TyF t []
let patImpl _ tstx =
throwError $ NotValidType tstx
p <- currentPhase
addLocalBinding n b
bind b $ EPrimTypeMacro tyImpl patImpl
forkExpandSyntax dest (addScope p sc body)
--------------
-- Patterns --
--------------
type PatternPrim = Either (Ty, PatternPtr) TypePatternPtr -> Syntax -> Expand ()
elsePattern :: PatternPrim
elsePattern (Left (scrutTy, dest)) stx = do
Stx _ _ (_, var) <- mustHaveEntries stx
ty <- trivialScheme scrutTy
(sc, x, v) <- prepareVar var
modifyState $ set (expanderPatternBinders . at dest) $
Just $ Right (sc, x, v, ty)
linkPattern dest $ PatternVar x v
elsePattern (Right dest) stx = do
Stx _ _ (_, var) <- mustHaveEntries stx
ty <- trivialScheme tType
(sc, x, v) <- prepareVar var
linkTypePattern dest
(AnyType x v)
[(sc, x, v, ty)]
-------------
-- Helpers --
-------------
-- | Add the primitive macros that expand to datatype invocations
addDatatype :: Ident -> Datatype -> [Kind] -> Expand ()
addDatatype name dt argKinds = do
name' <- addRootScope' name
let (tyImpl, patImpl) = typeConstructor (TDatatype dt) argKinds
let val = EPrimTypeMacro tyImpl patImpl
b <- freshBinding
addDefinedBinding name' b
bind b val
expandPatternCase :: Ty -> Stx (Syntax, Syntax) -> Expand (SyntaxPattern, SplitCorePtr)
TODO match case keywords hygienically
expandPatternCase t (Stx _ _ (lhs, rhs)) = do
p <- currentPhase
sch <- trivialScheme tSyntax
case lhs of
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "ident")),
patVar])) -> do
(sc, x', var) <- prepareVar patVar
let rhs' = addScope p sc rhs
rhsDest <- withLocalVarType x' var sch $ schedule t rhs'
let patOut = SyntaxPatternIdentifier x' var
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "integer")),
patVar])) -> do
(sc, x', var) <- prepareVar patVar
let rhs' = addScope p sc rhs
strSch <- trivialScheme tInteger
rhsDest <- withLocalVarType x' var strSch $ schedule t rhs'
let patOut = SyntaxPatternInteger x' var
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "string")),
patVar])) -> do
(sc, x', var) <- prepareVar patVar
let rhs' = addScope p sc rhs
strSch <- trivialScheme tString
rhsDest <- withLocalVarType x' var strSch $ schedule t rhs'
let patOut = SyntaxPatternString x' var
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "list")),
Syntax (Stx _ _ (List vars))])) -> do
varInfo <- traverse prepareVar vars
let rhs' = foldr (addScope p) rhs [sc | (sc, _, _) <- varInfo]
rhsDest <- withLocalVarTypes [(var, vIdent, sch) | (_, vIdent, var) <- varInfo] $
schedule t rhs'
let patOut = SyntaxPatternList [(vIdent, var) | (_, vIdent, var) <- varInfo]
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "cons")),
car,
cdr])) -> do
(sc, car', carVar) <- prepareVar car
(sc', cdr', cdrVar) <- prepareVar cdr
let rhs' = addScope p sc' $ addScope p sc rhs
rhsDest <- withLocalVarTypes [(carVar, car', sch), (cdrVar, cdr', sch)] $
schedule t rhs'
let patOut = SyntaxPatternCons car' carVar cdr' cdrVar
return (patOut, rhsDest)
Syntax (Stx _ _ (List [])) -> do
rhsDest <- schedule t rhs
return (SyntaxPatternEmpty, rhsDest)
Syntax (Stx _ _ (Id "_")) -> do
rhsDest <- schedule t rhs
return (SyntaxPatternAny, rhsDest)
other ->
throwError $ UnknownPattern other
scheduleDataPattern ::
Ty -> Ty ->
Stx (Syntax, Syntax) ->
Expand (PatternPtr, SplitCorePtr)
scheduleDataPattern exprTy scrutTy (Stx _ _ (patStx, rhsStx@(Syntax (Stx _ loc _)))) = do
dest <- liftIO newPatternPtr
forkExpandSyntax (PatternDest scrutTy dest) patStx
rhsDest <- liftIO newSplitCorePtr
saveOrigin rhsDest loc
forkExpanderTask $ AwaitingPattern dest exprTy rhsDest rhsStx
return (dest, rhsDest)
scheduleTypePattern ::
Ty -> Stx (Syntax, Syntax) ->
Expand (TypePatternPtr, SplitCorePtr)
scheduleTypePattern exprTy (Stx _ _ (patStx, rhsStx@(Syntax (Stx _ loc _)))) = do
dest <- liftIO newTypePatternPtr
forkExpandSyntax (TypePatternDest dest) patStx
rhsDest <- liftIO newSplitCorePtr
saveOrigin rhsDest loc
forkExpanderTask $ AwaitingTypePattern dest exprTy rhsDest rhsStx
return (dest, rhsDest)
prepareTypeVar :: Natural -> Syntax -> Expand (Scope, Ident, Kind)
prepareTypeVar i varStx = do
(sc, α, b) <- varPrepHelper varStx
k <- KMetaVar <$> liftIO newKindVar
bind b (ETypeVar k i)
return (sc, α, k)
varPrepHelper :: Syntax -> Expand (Scope, Ident, Binding)
varPrepHelper varStx = do
sc <- freshScope $ T.pack $ "For variable " ++ shortShow varStx
x <- mustBeIdent varStx
p <- currentPhase
psc <- phaseRoot
let x' = addScope' psc $ addScope p sc x
b <- freshBinding
addLocalBinding x' b
return (sc, x', b)
prepareVar :: Syntax -> Expand (Scope, Ident, Var)
prepareVar varStx = do
(sc, x', b) <- varPrepHelper varStx
var <- freshVar
bind b (EVarMacro var)
return (sc, x', var)
primitiveDatatype :: Text -> [Ty] -> Ty
primitiveDatatype name args =
let dt = Datatype { _datatypeModule = KernelName kernelName
, _datatypeName = DatatypeName name
}
in tDatatype dt args
unaryIntegerPrim :: (Integer -> Integer) -> Value
unaryIntegerPrim f =
ValueClosure $ HO $
\(ValueInteger i) ->
ValueInteger (f i)
binaryIntegerPrim :: (Integer -> Integer -> Integer) -> Value
binaryIntegerPrim f =
ValueClosure $ HO $
\(ValueInteger i1) ->
ValueClosure $ HO $
\(ValueInteger i2) ->
ValueInteger (f i1 i2)
binaryIntegerPred :: (Integer -> Integer -> Bool) -> Value
binaryIntegerPred f =
ValueClosure $ HO $
\(ValueInteger i1) ->
ValueClosure $ HO $
\(ValueInteger i2) ->
if f i1 i2
then primitiveCtor "true" []
else primitiveCtor "false" []
binaryStringPred :: (Text -> Text -> Bool) -> Value
binaryStringPred f =
ValueClosure $ HO $
\(ValueString str1) ->
ValueClosure $ HO $
\(ValueString str2) ->
if f str1 str2
then primitiveCtor "true" []
else primitiveCtor "false" []
| null | https://raw.githubusercontent.com/gelisam/klister/795393ce4f8c17489b8ca4f855b462db409c5514/src/Expander/Primitives.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
# OPTIONS -Wno-name-shadowing #
* Declaration primitives
* Expression primitives
* Pattern primitives
* Module primitives
* Anywhere primitives
* Primitive values
* Helpers
--------------------------
Declaration primitives --
--------------------------
'sc' allows the newly-defined macros to generate code containing calls to
any of the other newly-defined macros, while 'postDefineScope' allows the
macros.
Expression primitives
TODO add type to elaborated program? Or not?
Here, the binding occurrence of the macro gets the
fresh scope at all phases, but later, the scope is only
added to the correct phase in potential use sites.
This prevents the body of the macro (in an earlier
phase) from being able to refer to the macro itself.
-------------------
Type Primitives --
-------------------
FIXME kind check here
-----------
Modules --
-----------
------------
Anywhere --
------------
| with-unknown-type's implementation: create a named fresh
unification variable for macros that only can annotate part of a
type.
------------
Patterns --
------------
-----------
Helpers --
-----------
| Add the primitive macros that expand to datatype invocations | # LANGUAGE BlockArguments #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE ViewPatterns #
module Expander.Primitives
define
, datatype
, defineMacros
, example
, run
, group
, meta
, app
, integerLiteral
, stringLiteral
, bindMacro
, consListSyntax
, dataCase
, emptyListSyntax
, err
, flet
, identEqual
, identSyntax
, lambda
, letExpr
, letSyntax
, listSyntax
, integerSyntax
, stringSyntax
, makeIntroducer
, Expander.Primitives.log
, whichProblem
, pureMacro
, quote
, replaceLoc
, syntaxCase
, syntaxError
, the
, typeCase
, elsePattern
, makeModule
, makeLocalType
, unaryIntegerPrim
, binaryIntegerPrim
, binaryIntegerPred
, binaryStringPred
, prepareVar
, baseType
, typeConstructor
, primitiveDatatype
) where
import Control.Lens hiding (List)
import Control.Monad.IO.Class
import Control.Monad.Except
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
import Data.Traversable
import Numeric.Natural
import Binding
import Core
import Datatype
import qualified Env
import Expander.DeclScope
import Expander.Monad
import Expander.Syntax
import Expander.TC
import Kind
import Module
import ModuleName
import Phase
import Scope
import ScopeSet (ScopeSet)
import qualified ScopeSet
import ShortShow
import SplitCore
import SplitType
import Syntax
import Type
import Value
type DeclPrim =
DeclTreePtr -> DeclOutputScopesPtr -> Syntax -> Expand ()
type DeclExpander =
DeclTreePtr -> ScopeSet -> DeclOutputScopesPtr -> Syntax -> Expand ()
define :: DeclPrim
define dest outScopesDest stx = do
p <- currentPhase
Stx _ _ (_, varStx, expr) <- mustHaveEntries stx
postDefineScope <- freshScope $ T.pack $ "For definition at " ++ shortShow (stxLoc stx)
x <- addScope' postDefineScope <$> mustBeIdent varStx
b <- freshBinding
addDefinedBinding x b
var <- freshVar
exprDest <- liftIO $ newSplitCorePtr
bind b (EIncompleteDefn var x exprDest)
schPtr <- liftIO $ newSchemePtr
linkOneDecl dest (Define x var schPtr exprDest)
t <- inTypeBinder do
t <- tMetaVar <$> freshMeta (Just KStar)
forkExpandSyntax (ExprDest t exprDest) expr
return t
ph <- currentPhase
modifyState $ over (expanderDefTypes . at ph . non Env.empty) $
Env.insert var x schPtr
forkGeneralizeType exprDest t schPtr
linkDeclOutputScopes outScopesDest (ScopeSet.singleScopeAtPhase postDefineScope p)
datatype :: DeclPrim
datatype dest outScopesDest stx = do
Stx scs loc (_ :: Syntax, more) <- mustBeCons stx
Stx _ _ (nameAndArgs, ctorSpecs) <- mustBeCons (Syntax (Stx scs loc (List more)))
Stx _ _ (name, args) <- mustBeCons nameAndArgs
typeArgs <- for (zip [0..] args) $ \(i, a) ->
prepareTypeVar i a
sc <- freshScope $ T.pack $ "For datatype at " ++ shortShow (stxLoc stx)
let typeScopes = map (view _1) typeArgs ++ [sc]
realName <- mustBeIdent (addScope' sc name)
p <- currentPhase
d <- freshDatatype realName
let argKinds = map (view _3) typeArgs
addDatatype realName d argKinds
ctors <- for ctorSpecs \ spec -> do
Stx _ _ (cn, ctorArgs) <- mustBeCons spec
realCN <- mustBeIdent cn
ctor <- freshConstructor realCN
let ctorArgs' = [ foldr (addScope p) t typeScopes
| t <- ctorArgs
]
argTypes <- traverse (scheduleType KStar) ctorArgs'
return (realCN, ctor, argTypes)
let info =
DatatypeInfo
{ _datatypeArgKinds = argKinds
, _datatypeConstructors =
[ ctor | (_, ctor, _) <- ctors ]
}
modifyState $
set (expanderCurrentDatatypes .
at p . non Map.empty .
at d) $
Just info
forkEstablishConstructors (ScopeSet.singleScopeAtPhase sc p) outScopesDest d ctors
linkOneDecl dest (Data realName (view datatypeName d) argKinds ctors)
defineMacros :: DeclPrim
defineMacros dest outScopesDest stx = do
Stx _ _ (_, macroList) <- mustHaveEntries stx
Stx _ _ macroDefs <- mustBeList macroList
p <- currentPhase
code which follows the @define - macros@ call to refer to the newly - defined
sc <- freshScope $ T.pack $ "For macros at " ++ shortShow (stxLoc stx)
postDefineScope <- freshScope $ T.pack $ "For macro-definition at " ++ shortShow (stxLoc stx)
macros <- for macroDefs $ \def -> do
Stx _ _ (mname, mdef) <- mustHaveEntries def
theName <- addScope' sc <$> mustBeIdent mname
b <- freshBinding
addDefinedBinding theName b
macroDest <- inEarlierPhase $
schedule (tFun1 tSyntax (tMacro tSyntax))
(addScope p sc mdef)
v <- freshMacroVar
bind b $ EIncompleteMacro v theName macroDest
return (theName, v, macroDest)
linkOneDecl dest $ DefineMacros macros
linkDeclOutputScopes outScopesDest ( ScopeSet.insertAtPhase p sc
$ ScopeSet.insertAtPhase p postDefineScope
$ ScopeSet.empty
)
example :: DeclPrim
example dest outScopesDest stx = do
Stx _ _ (_, expr) <- mustHaveEntries stx
exprDest <- liftIO $ newSplitCorePtr
sch <- liftIO newSchemePtr
linkOneDecl dest (Example (view (unSyntax . stxSrcLoc) stx) sch exprDest)
t <- inTypeBinder do
t <- tMetaVar <$> freshMeta (Just KStar)
forkExpandSyntax (ExprDest t exprDest) expr
return t
forkGeneralizeType exprDest t sch
linkDeclOutputScopes outScopesDest mempty
run :: DeclPrim
run dest outScopesDest stx = do
Stx _ _ (_, expr) <- mustHaveEntries stx
exprDest <- liftIO $ newSplitCorePtr
linkOneDecl dest (Run (stxLoc stx) exprDest)
forkExpandSyntax (ExprDest (tIO (primitiveDatatype "Unit" [])) exprDest) expr
linkDeclOutputScopes outScopesDest mempty
meta :: DeclExpander -> DeclPrim
meta expandDeclForms dest outScopesDest stx = do
(_ :: Syntax, subDecls) <- mustHaveShape stx
subDest <- newDeclTreePtr
linkOneDecl dest (Meta subDest)
inEarlierPhase $
expandDeclForms subDest mempty outScopesDest =<< addRootScope subDecls
group :: DeclExpander -> DeclPrim
group expandDeclForms dest outScopesDest stx = do
(_ :: Syntax, decls) <- mustHaveShape stx
expandDeclForms dest mempty outScopesDest decls
type ExprPrim = Ty -> SplitCorePtr -> Syntax -> Expand ()
err :: ExprPrim
err _t dest stx = do
Stx _ _ (_, msg) <- mustHaveEntries stx
msgDest <- schedule tSyntax msg
linkExpr dest $ CoreError msgDest
the :: ExprPrim
the t dest stx = do
Stx _ _ (_, ty, expr) <- mustHaveEntries stx
saveOrigin dest (stxLoc expr)
tyDest <- scheduleType KStar ty
forkAwaitingType tyDest [TypeThenUnify dest t, TypeThenExpandExpr dest expr]
letExpr :: ExprPrim
letExpr t dest stx = do
Stx _ _ (_, b, body) <- mustHaveEntries stx
Stx _ _ (x, def) <- mustHaveEntries b
(sc, x', coreX) <- prepareVar x
p <- currentPhase
psc <- phaseRoot
(defDest, xTy) <- inTypeBinder do
xt <- tMetaVar <$> freshMeta (Just KStar)
defDest <- schedule xt def
return (defDest, xt)
sch <- liftIO $ newSchemePtr
forkGeneralizeType defDest xTy sch
bodyDest <- withLocalVarType x' coreX sch $
schedule t $
addScope p psc $
addScope p sc body
linkExpr dest $ CoreLet x' coreX defDest bodyDest
flet :: ExprPrim
flet t dest stx = do
ft <- inTypeBinder $ tMetaVar <$> freshMeta (Just KStar)
xt <- inTypeBinder $ tMetaVar <$> freshMeta (Just KStar)
rt <- inTypeBinder $ tMetaVar <$> freshMeta (Just KStar)
fsch <- trivialScheme ft
xsch <- trivialScheme xt
Stx _ _ (_, b, body) <- mustHaveEntries stx
Stx _ _ (f, args, def) <- mustHaveEntries b
Stx _ _ (Identity x) <- mustHaveEntries args
(fsc, f', coreF) <- prepareVar f
(xsc, x', coreX) <- prepareVar x
p <- currentPhase
psc <- phaseRoot
defDest <- inTypeBinder $
withLocalVarType f' coreF fsch $
withLocalVarType x' coreX xsch $
schedule rt $
addScope p psc $
addScope p xsc $
addScope p fsc def
unify dest ft (tFun1 xt rt)
sch <- liftIO newSchemePtr
forkGeneralizeType defDest ft sch
bodyDest <- withLocalVarType f' coreF sch $
schedule t $
addScope p psc $
addScope p fsc body
linkExpr dest $ CoreLetFun f' coreF x' coreX defDest bodyDest
lambda :: ExprPrim
lambda t dest stx = do
Stx _ _ (_, arg, body) <- mustHaveEntries stx
Stx _ _ (Identity theArg) <- mustHaveEntries arg
(sc, arg', coreArg) <- prepareVar theArg
p <- currentPhase
psc <- phaseRoot
argT <- tMetaVar <$> freshMeta (Just KStar)
retT <- tMetaVar <$> freshMeta (Just KStar)
unify dest t (tFun1 argT retT)
sch <- trivialScheme argT
bodyDest <-
withLocalVarType arg' coreArg sch $
schedule retT $
addScope p psc $
addScope p sc body
linkExpr dest $ CoreLam arg' coreArg bodyDest
app :: ExprPrim
app t dest stx = do
argT <- tMetaVar <$> freshMeta (Just KStar)
Stx _ _ (_, fun, arg) <- mustHaveEntries stx
funDest <- schedule (tFun1 argT t) fun
argDest <- schedule argT arg
linkExpr dest $ CoreApp funDest argDest
integerLiteral :: ExprPrim
integerLiteral t dest stx = do
Stx _ _ (_, arg) <- mustHaveEntries stx
Stx _ _ i <- mustBeInteger arg
unify dest t tInteger
linkExpr dest (CoreInteger i)
saveExprType dest t
stringLiteral :: ExprPrim
stringLiteral t dest stx = do
Stx _ _ (_, arg) <- mustHaveEntries stx
Stx _ _ s <- mustBeString arg
unify dest t tString
linkExpr dest (CoreString s)
saveExprType dest t
pureMacro :: ExprPrim
pureMacro t dest stx = do
Stx _ _ (_, v) <- mustHaveEntries stx
innerT <- tMetaVar <$> freshMeta (Just KStar)
unify dest (tMacro innerT) t
argDest <- schedule innerT v
linkExpr dest $ CorePureMacro argDest
bindMacro :: ExprPrim
bindMacro t dest stx = do
a <- tMetaVar <$> freshMeta (Just KStar)
b <- tMetaVar <$> freshMeta (Just KStar)
Stx _ _ (_, act, cont) <- mustHaveEntries stx
actDest <- schedule (tMacro a) act
contDest <- schedule (tFun1 a (tMacro b)) cont
unify dest t (tMacro b)
linkExpr dest $ CoreBindMacro actDest contDest
syntaxError :: ExprPrim
syntaxError t dest stx = do
a <- tMetaVar <$> freshMeta (Just KStar)
unify dest t (tMacro a)
Stx scs srcloc (_, args) <- mustBeCons stx
Stx _ _ (msg, locs) <- mustBeCons $ Syntax $ Stx scs srcloc (List args)
msgDest <- schedule tSyntax msg
locDests <- traverse (schedule tSyntax) locs
linkExpr dest $ CoreSyntaxError (SyntaxError locDests msgDest)
identEqual :: HowEq -> ExprPrim
identEqual how t dest stx = do
unify dest t (tMacro (primitiveDatatype "Bool" []))
Stx _ _ (_, id1, id2) <- mustHaveEntries stx
newE <- CoreIdentEq how <$> schedule tSyntax id1 <*> schedule tSyntax id2
linkExpr dest newE
quote :: ExprPrim
quote t dest stx = do
unify dest t tSyntax
Stx _ _ (_, quoted) <- mustHaveEntries stx
linkExpr dest $ CoreSyntax quoted
identSyntax :: ExprPrim
identSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, someId, source) <- mustHaveEntries stx
idDest <- schedule tSyntax someId
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreIdent $ ScopedIdent idDest sourceDest
emptyListSyntax :: ExprPrim
emptyListSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, source) <- mustHaveEntries stx
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreEmpty $ ScopedEmpty sourceDest
consListSyntax :: ExprPrim
consListSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, car, cdr, source) <- mustHaveEntries stx
carDest <- schedule tSyntax car
cdrDest <- schedule tSyntax cdr
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreCons $ ScopedCons carDest cdrDest sourceDest
listSyntax :: ExprPrim
listSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, list, source) <- mustHaveEntries stx
listItems <- mustHaveShape list
listDests <- traverse (schedule tSyntax) listItems
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreList $ ScopedList listDests sourceDest
integerSyntax :: ExprPrim
integerSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, int, source) <- mustHaveEntries stx
intDest <- schedule tInteger int
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreIntegerSyntax $ ScopedInteger intDest sourceDest
stringSyntax :: ExprPrim
stringSyntax t dest stx = do
unify dest t tSyntax
Stx _ _ (_, str, source) <- mustHaveEntries stx
strDest <- schedule tString str
sourceDest <- schedule tSyntax source
linkExpr dest $ CoreStringSyntax $ ScopedString strDest sourceDest
replaceLoc :: ExprPrim
replaceLoc t dest stx = do
unify dest t tSyntax
Stx _ _ (_, loc, valStx) <- mustHaveEntries stx
locDest <- schedule tSyntax loc
valStxDest <- schedule tSyntax valStx
linkExpr dest $ CoreReplaceLoc locDest valStxDest
syntaxCase :: ExprPrim
syntaxCase t dest stx = do
Stx scs loc (_ :: Syntax, args) <- mustBeCons stx
Stx _ _ (scrutinee, patterns) <- mustBeCons (Syntax (Stx scs loc (List args)))
scrutDest <- schedule tSyntax scrutinee
patternDests <- traverse (mustHaveEntries >=> expandPatternCase t) patterns
linkExpr dest $ CoreCase loc scrutDest patternDests
letSyntax :: ExprPrim
letSyntax t dest stx = do
Stx _ loc (_, macro, body) <- mustHaveEntries stx
Stx _ _ (mName, mdef) <- mustHaveEntries macro
sc <- freshScope $ T.pack $ "Scope for let-syntax at " ++ shortShow loc
m <- mustBeIdent mName
p <- currentPhase
let m' = addScope' sc m
b <- freshBinding
addLocalBinding m' b
v <- freshMacroVar
macroDest <- inEarlierPhase $ do
psc <- phaseRoot
schedule (tFun1 tSyntax (tMacro tSyntax))
(addScope (prior p) psc mdef)
forkAwaitingMacro b v m' macroDest (ExprDest t dest) (addScope p sc body)
makeIntroducer :: ExprPrim
makeIntroducer t dest stx = do
Stx _ _ (Identity mName) <- mustHaveEntries stx
_ <- mustBeIdent mName
unify dest theType t
linkExpr dest $ CoreMakeIntroducer
where
theType =
tMacro (tFun [primitiveDatatype "ScopeAction" [], tSyntax] tSyntax)
log :: ExprPrim
log t dest stx = do
unify dest (tMacro (primitiveDatatype "Unit" [])) t
Stx _ _ (_, message) <- mustHaveEntries stx
msgDest <- schedule tSyntax message
linkExpr dest $ CoreLog msgDest
whichProblem :: ExprPrim
whichProblem t dest stx = do
unify dest (tMacro (primitiveDatatype "Problem" [])) t
Stx _ _ (Identity _) <- mustHaveEntries stx
linkExpr dest CoreWhichProblem
dataCase :: ExprPrim
dataCase t dest stx = do
Stx _ loc (_, scrut, cases) <- mustBeConsCons stx
a <- tMetaVar <$> freshMeta (Just KStar)
scrutineeDest <- schedule a scrut
cases' <- traverse (mustHaveEntries >=> scheduleDataPattern t a) cases
linkExpr dest $ CoreDataCase loc scrutineeDest cases'
typeCase :: ExprPrim
typeCase t dest stx = do
Stx _ loc (_, scrut, cases) <- mustBeConsCons stx
a <- tMetaVar <$> freshMeta (Just KStar)
unify dest (tMacro a) t
scrutineeDest <- schedule tType scrut
cases' <- traverse (mustHaveEntries >=> scheduleTypePattern t) cases
linkExpr dest $ CoreTypeCase loc scrutineeDest cases'
type TypePrim =
(Kind -> SplitTypePtr -> Syntax -> Expand (), TypePatternPtr -> Syntax -> Expand ())
typeConstructor :: TypeConstructor -> [Kind] -> TypePrim
typeConstructor ctor argKinds = (implT, implP)
where
implT k dest stx = do
Stx _ _ (_, args) <- mustBeCons stx
if length args > length argKinds
then throwError $ WrongTypeArity stx ctor
(fromIntegral $ length argKinds)
(length args)
else do
let missingArgs :: [Kind]
missingArgs = drop (length args) argKinds
equateKinds stx (kFun missingArgs KStar) k
argDests <- traverse (uncurry scheduleType) (zip argKinds args)
linkType dest $ TyF ctor argDests
implP dest stx = do
Stx _ _ (_, args) <- mustBeCons stx
if length args > length argKinds
then throwError $ WrongTypeArity stx ctor
(fromIntegral $ length argKinds)
(length args)
else do
varInfo <- traverse prepareVar args
sch <- trivialScheme tType
linkTypePattern dest
(TypePattern $ TyF ctor [ (varStx, var)
| (_, varStx, var) <- varInfo
])
[ (sc, n, x, sch)
| (sc, n, x) <- varInfo
]
baseType :: TypeConstructor -> TypePrim
baseType ctor = typeConstructor ctor []
makeModule :: DeclExpander -> DeclTreePtr -> Syntax -> Expand ()
makeModule expandDeclForms bodyPtr stx =
view expanderModuleTop <$> getState >>=
\case
Just _ ->
error "TODO throw real error - already expanding a module"
Nothing -> do
modifyState $ set expanderModuleTop (Just bodyPtr)
(_ :: Syntax, body) <- mustHaveShape stx
outScopesDest <- newDeclOutputScopesPtr
expandDeclForms bodyPtr mempty outScopesDest body
pure ()
makeLocalType :: MacroDest -> Syntax -> Expand ()
makeLocalType dest stx = do
Stx _ _ (_, binder, body) <- mustHaveEntries stx
Stx _ _ (Identity theVar) <- mustHaveEntries binder
(sc, n, b) <- varPrepHelper theVar
meta <- freshMeta Nothing
let t = TMetaVar meta
let tyImpl k tdest tstx = do
k' <- typeVarKind meta
equateKinds tstx k k'
_ <- mustBeIdent tstx
linkType tdest $ TyF t []
let patImpl _ tstx =
throwError $ NotValidType tstx
p <- currentPhase
addLocalBinding n b
bind b $ EPrimTypeMacro tyImpl patImpl
forkExpandSyntax dest (addScope p sc body)
type PatternPrim = Either (Ty, PatternPtr) TypePatternPtr -> Syntax -> Expand ()
elsePattern :: PatternPrim
elsePattern (Left (scrutTy, dest)) stx = do
Stx _ _ (_, var) <- mustHaveEntries stx
ty <- trivialScheme scrutTy
(sc, x, v) <- prepareVar var
modifyState $ set (expanderPatternBinders . at dest) $
Just $ Right (sc, x, v, ty)
linkPattern dest $ PatternVar x v
elsePattern (Right dest) stx = do
Stx _ _ (_, var) <- mustHaveEntries stx
ty <- trivialScheme tType
(sc, x, v) <- prepareVar var
linkTypePattern dest
(AnyType x v)
[(sc, x, v, ty)]
addDatatype :: Ident -> Datatype -> [Kind] -> Expand ()
addDatatype name dt argKinds = do
name' <- addRootScope' name
let (tyImpl, patImpl) = typeConstructor (TDatatype dt) argKinds
let val = EPrimTypeMacro tyImpl patImpl
b <- freshBinding
addDefinedBinding name' b
bind b val
expandPatternCase :: Ty -> Stx (Syntax, Syntax) -> Expand (SyntaxPattern, SplitCorePtr)
TODO match case keywords hygienically
expandPatternCase t (Stx _ _ (lhs, rhs)) = do
p <- currentPhase
sch <- trivialScheme tSyntax
case lhs of
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "ident")),
patVar])) -> do
(sc, x', var) <- prepareVar patVar
let rhs' = addScope p sc rhs
rhsDest <- withLocalVarType x' var sch $ schedule t rhs'
let patOut = SyntaxPatternIdentifier x' var
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "integer")),
patVar])) -> do
(sc, x', var) <- prepareVar patVar
let rhs' = addScope p sc rhs
strSch <- trivialScheme tInteger
rhsDest <- withLocalVarType x' var strSch $ schedule t rhs'
let patOut = SyntaxPatternInteger x' var
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "string")),
patVar])) -> do
(sc, x', var) <- prepareVar patVar
let rhs' = addScope p sc rhs
strSch <- trivialScheme tString
rhsDest <- withLocalVarType x' var strSch $ schedule t rhs'
let patOut = SyntaxPatternString x' var
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "list")),
Syntax (Stx _ _ (List vars))])) -> do
varInfo <- traverse prepareVar vars
let rhs' = foldr (addScope p) rhs [sc | (sc, _, _) <- varInfo]
rhsDest <- withLocalVarTypes [(var, vIdent, sch) | (_, vIdent, var) <- varInfo] $
schedule t rhs'
let patOut = SyntaxPatternList [(vIdent, var) | (_, vIdent, var) <- varInfo]
return (patOut, rhsDest)
Syntax (Stx _ _ (List [Syntax (Stx _ _ (Id "cons")),
car,
cdr])) -> do
(sc, car', carVar) <- prepareVar car
(sc', cdr', cdrVar) <- prepareVar cdr
let rhs' = addScope p sc' $ addScope p sc rhs
rhsDest <- withLocalVarTypes [(carVar, car', sch), (cdrVar, cdr', sch)] $
schedule t rhs'
let patOut = SyntaxPatternCons car' carVar cdr' cdrVar
return (patOut, rhsDest)
Syntax (Stx _ _ (List [])) -> do
rhsDest <- schedule t rhs
return (SyntaxPatternEmpty, rhsDest)
Syntax (Stx _ _ (Id "_")) -> do
rhsDest <- schedule t rhs
return (SyntaxPatternAny, rhsDest)
other ->
throwError $ UnknownPattern other
scheduleDataPattern ::
Ty -> Ty ->
Stx (Syntax, Syntax) ->
Expand (PatternPtr, SplitCorePtr)
scheduleDataPattern exprTy scrutTy (Stx _ _ (patStx, rhsStx@(Syntax (Stx _ loc _)))) = do
dest <- liftIO newPatternPtr
forkExpandSyntax (PatternDest scrutTy dest) patStx
rhsDest <- liftIO newSplitCorePtr
saveOrigin rhsDest loc
forkExpanderTask $ AwaitingPattern dest exprTy rhsDest rhsStx
return (dest, rhsDest)
scheduleTypePattern ::
Ty -> Stx (Syntax, Syntax) ->
Expand (TypePatternPtr, SplitCorePtr)
scheduleTypePattern exprTy (Stx _ _ (patStx, rhsStx@(Syntax (Stx _ loc _)))) = do
dest <- liftIO newTypePatternPtr
forkExpandSyntax (TypePatternDest dest) patStx
rhsDest <- liftIO newSplitCorePtr
saveOrigin rhsDest loc
forkExpanderTask $ AwaitingTypePattern dest exprTy rhsDest rhsStx
return (dest, rhsDest)
prepareTypeVar :: Natural -> Syntax -> Expand (Scope, Ident, Kind)
prepareTypeVar i varStx = do
(sc, α, b) <- varPrepHelper varStx
k <- KMetaVar <$> liftIO newKindVar
bind b (ETypeVar k i)
return (sc, α, k)
varPrepHelper :: Syntax -> Expand (Scope, Ident, Binding)
varPrepHelper varStx = do
sc <- freshScope $ T.pack $ "For variable " ++ shortShow varStx
x <- mustBeIdent varStx
p <- currentPhase
psc <- phaseRoot
let x' = addScope' psc $ addScope p sc x
b <- freshBinding
addLocalBinding x' b
return (sc, x', b)
prepareVar :: Syntax -> Expand (Scope, Ident, Var)
prepareVar varStx = do
(sc, x', b) <- varPrepHelper varStx
var <- freshVar
bind b (EVarMacro var)
return (sc, x', var)
primitiveDatatype :: Text -> [Ty] -> Ty
primitiveDatatype name args =
let dt = Datatype { _datatypeModule = KernelName kernelName
, _datatypeName = DatatypeName name
}
in tDatatype dt args
unaryIntegerPrim :: (Integer -> Integer) -> Value
unaryIntegerPrim f =
ValueClosure $ HO $
\(ValueInteger i) ->
ValueInteger (f i)
binaryIntegerPrim :: (Integer -> Integer -> Integer) -> Value
binaryIntegerPrim f =
ValueClosure $ HO $
\(ValueInteger i1) ->
ValueClosure $ HO $
\(ValueInteger i2) ->
ValueInteger (f i1 i2)
binaryIntegerPred :: (Integer -> Integer -> Bool) -> Value
binaryIntegerPred f =
ValueClosure $ HO $
\(ValueInteger i1) ->
ValueClosure $ HO $
\(ValueInteger i2) ->
if f i1 i2
then primitiveCtor "true" []
else primitiveCtor "false" []
binaryStringPred :: (Text -> Text -> Bool) -> Value
binaryStringPred f =
ValueClosure $ HO $
\(ValueString str1) ->
ValueClosure $ HO $
\(ValueString str2) ->
if f str1 str2
then primitiveCtor "true" []
else primitiveCtor "false" []
|
500dd324259112d0d0c535507736c35478b67d43edae0f0b93c3606f511d67c5 | RNCryptor/rncryptor-hs | StreamingDecrypter.hs | {-# LANGUAGE OverloadedStrings #-}
module Main where
import Crypto.RNCryptor.V3.Decrypt
import qualified System.IO.Streams as S
import System.Environment
import qualified Data.ByteString.Char8 as B
main :: IO ()
main = do
args <- getArgs
case args of
key:_ -> decryptStream (B.pack key) S.stdin S.stdout
_ -> putStrLn "usage: rncryptor-decrypt <key>"
| null | https://raw.githubusercontent.com/RNCryptor/rncryptor-hs/2c4fdb41646eefc1675482f2564c780a548b655c/example/StreamingDecrypter.hs | haskell | # LANGUAGE OverloadedStrings # | module Main where
import Crypto.RNCryptor.V3.Decrypt
import qualified System.IO.Streams as S
import System.Environment
import qualified Data.ByteString.Char8 as B
main :: IO ()
main = do
args <- getArgs
case args of
key:_ -> decryptStream (B.pack key) S.stdin S.stdout
_ -> putStrLn "usage: rncryptor-decrypt <key>"
|
86831282ddcfb216ea05585153fd0888ca99ef704a793fc30d975b3e42c1e254 | dryewo/cyrus | utils.clj | (ns {{namespace}}.utils)
(defn implementation-version []
(or
;; When running in a REPL
(System/getProperty "{{name}}.version")
;; When running as `java -jar ...`
(-> (eval '{{package}}.core) .getPackage .getImplementationVersion)))
| null | https://raw.githubusercontent.com/dryewo/cyrus/880c842e0baa11887854ec3d912c044a2a500449/resources/leiningen/new/cyrus/src/_namespace_/utils.clj | clojure | When running in a REPL
When running as `java -jar ...` | (ns {{namespace}}.utils)
(defn implementation-version []
(or
(System/getProperty "{{name}}.version")
(-> (eval '{{package}}.core) .getPackage .getImplementationVersion)))
|
359d80df10fe108e713c7d322f2a054e2736de5913117401dabd397e1695dd93 | raml-org/api-modeling-framework | runner.cljs | (ns api-modeling-framework.runner
(:require [doo.runner :refer-macros [doo-tests]]
[api-modeling-framework.tck]
[api-modeling-framework.integration-test]
[api-modeling-framework.utils-test]
[api-modeling-framework.parser.syntax.yaml-test]
[api-modeling-framework.parser.syntax.json-test]
[api-modeling-framework.parser.document.jsonld-test]
[api-modeling-framework.parser.domain.jsonld-test]
[api-modeling-framework.parser.domain.raml-test]
[api-modeling-framework.parser.domain.openapi-test]
[api-modeling-framework.generators.document.jsonld-test]
[api-modeling-framework.generators.document.raml-test]
[api-modeling-framework.generators.domain.jsonld-test]
[api-modeling-framework.generators.domain.openapi-test]
[api-modeling-framework.generators.domain.raml-test]
[api-modeling-framework.generators.document.openapi-test]
[api-modeling-framework.model.document-test]
[api-modeling-framework.core-test]
[api-modeling-framework.parser.domain.common-test]
))
(doo-tests 'api-modeling-framework.tck
'api-modeling-framework.integration-test
'api-modeling-framework.utils-test
'api-modeling-framework.parser.syntax.yaml-test
'api-modeling-framework.parser.syntax.json-test
'api-modeling-framework.model.document-test
'api-modeling-framework.generators.document.jsonld-test
'api-modeling-framework.parser.document.jsonld-test
'api-modeling-framework.parser.domain.jsonld-test
'api-modeling-framework.parser.domain.raml-test
'api-modeling-framework.parser.domain.openapi-test
'api-modeling-framework.generators.domain.jsonld-test
'api-modeling-framework.generators.domain.openapi-test
'api-modeling-framework.generators.domain.raml-test
'api-modeling-framework.generators.document.raml-test
'api-modeling-framework.generators.document.openapi-test
'api-modeling-framework.core-test
'api-modeling-framework.parser.domain.common-test
)
| null | https://raw.githubusercontent.com/raml-org/api-modeling-framework/34bb3b6c3e3f91b775e27f8e389e04eb2c36beb7/test/api_modeling_framework/runner.cljs | clojure | (ns api-modeling-framework.runner
(:require [doo.runner :refer-macros [doo-tests]]
[api-modeling-framework.tck]
[api-modeling-framework.integration-test]
[api-modeling-framework.utils-test]
[api-modeling-framework.parser.syntax.yaml-test]
[api-modeling-framework.parser.syntax.json-test]
[api-modeling-framework.parser.document.jsonld-test]
[api-modeling-framework.parser.domain.jsonld-test]
[api-modeling-framework.parser.domain.raml-test]
[api-modeling-framework.parser.domain.openapi-test]
[api-modeling-framework.generators.document.jsonld-test]
[api-modeling-framework.generators.document.raml-test]
[api-modeling-framework.generators.domain.jsonld-test]
[api-modeling-framework.generators.domain.openapi-test]
[api-modeling-framework.generators.domain.raml-test]
[api-modeling-framework.generators.document.openapi-test]
[api-modeling-framework.model.document-test]
[api-modeling-framework.core-test]
[api-modeling-framework.parser.domain.common-test]
))
(doo-tests 'api-modeling-framework.tck
'api-modeling-framework.integration-test
'api-modeling-framework.utils-test
'api-modeling-framework.parser.syntax.yaml-test
'api-modeling-framework.parser.syntax.json-test
'api-modeling-framework.model.document-test
'api-modeling-framework.generators.document.jsonld-test
'api-modeling-framework.parser.document.jsonld-test
'api-modeling-framework.parser.domain.jsonld-test
'api-modeling-framework.parser.domain.raml-test
'api-modeling-framework.parser.domain.openapi-test
'api-modeling-framework.generators.domain.jsonld-test
'api-modeling-framework.generators.domain.openapi-test
'api-modeling-framework.generators.domain.raml-test
'api-modeling-framework.generators.document.raml-test
'api-modeling-framework.generators.document.openapi-test
'api-modeling-framework.core-test
'api-modeling-framework.parser.domain.common-test
)
| |
63ad2ee3301d26f7c6d87cffe27538985e35a576a27ad06005523cae314fce00 | ftomassetti/civs | project.clj | (defproject civs "0.2.4-SNAPSHOT"
:description "A simulator of civilizations evolution"
:url ""
:license {:name "Apache License v 2.0"
:url "/"}
:dependencies [
[org.clojure/clojure "1.6.0"]
[com.github.lands/lands-java-lib "0.3-SNAPSHOT"]
[org.clojure/math.combinatorics "0.0.8"]
[org.clojure/tools.cli "0.3.1"]
[com.velisco/tagged "0.3.0"]
[org.clojure/data.fressian "0.2.0"] ]
:scm git
:main ^:skip-aot civs.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}}
:repositories {"sonartype snapshots" ""}
:test-selectors {:default (complement :acceptance)
:acceptance :acceptance
:all (constantly true)})
| null | https://raw.githubusercontent.com/ftomassetti/civs/dc76bfff4241f67d4bc1081de3947a725ea75c39/project.clj | clojure | (defproject civs "0.2.4-SNAPSHOT"
:description "A simulator of civilizations evolution"
:url ""
:license {:name "Apache License v 2.0"
:url "/"}
:dependencies [
[org.clojure/clojure "1.6.0"]
[com.github.lands/lands-java-lib "0.3-SNAPSHOT"]
[org.clojure/math.combinatorics "0.0.8"]
[org.clojure/tools.cli "0.3.1"]
[com.velisco/tagged "0.3.0"]
[org.clojure/data.fressian "0.2.0"] ]
:scm git
:main ^:skip-aot civs.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}}
:repositories {"sonartype snapshots" ""}
:test-selectors {:default (complement :acceptance)
:acceptance :acceptance
:all (constantly true)})
| |
7ba6f98292c23588f648baedd4f318ade8b78475bbdfa04ec437fdf2346c3aba | chetmurthy/ensemble | bypassr.mli | (**************************************************************)
(* BYPASS: Optimized bypass router *)
Author : , 3/97
(**************************************************************)
val f : unit -> (Trans.rank -> Trans.seqno -> Iovecl.t -> unit) Route.t
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/route/bypassr.mli | ocaml | ************************************************************
BYPASS: Optimized bypass router
************************************************************ | Author : , 3/97
val f : unit -> (Trans.rank -> Trans.seqno -> Iovecl.t -> unit) Route.t
|
7f207aeeb8a76c4a5613a5376a00892dc473c17cb9e4e2df1cb13aa21e17b925 | aeternity/mnesia_rocksdb | mnesia_rocksdb_app.erl | -*- mode : erlang ; erlang - indent - level : 4 ; indent - tabs - mode : nil -*-
%%----------------------------------------------------------------
Copyright ( c ) 2013 - 2016 Klarna AB
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%----------------------------------------------------------------
-module(mnesia_rocksdb_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%% ===================================================================
%% Application callbacks
%% ===================================================================
start(_StartType, _StartArgs) ->
mnesia_rocksdb_sup:start_link().
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/aeternity/mnesia_rocksdb/b0bf4b6b9c68b35e37df0fb56a8b5c6417d20e54/src/mnesia_rocksdb_app.erl | erlang | ----------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
----------------------------------------------------------------
Application callbacks
===================================================================
Application callbacks
=================================================================== | -*- mode : erlang ; erlang - indent - level : 4 ; indent - tabs - mode : nil -*-
Copyright ( c ) 2013 - 2016 Klarna AB
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(mnesia_rocksdb_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
mnesia_rocksdb_sup:start_link().
stop(_State) ->
ok.
|
311037ba656833a8efdbb9cc802ce889cbce6d53242649deb2f762299cd065d1 | theodormoroianu/SecondYearCourses | HaskellChurch_20210415163846.hs | {-# LANGUAGE RankNTypes #-}
module HaskellChurch where
A boolean is any way to choose between two alternatives
newtype CBool = CBool {cIf :: forall t. t -> t -> t}
An instance to show as regular Booleans
instance Show CBool where
show b = "cBool " <> show (cIf b True False)
The boolean constant true always chooses the first alternative
cTrue :: CBool
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: CBool
cFalse = undefined
cBool :: Bool -> CBool
cBool True = cTrue
cBool False = cFalse
--The boolean negation switches the alternatives
cNot :: CBool -> CBool
cNot = undefined
--The boolean conjunction can be built as a conditional
(&&:) :: CBool -> CBool -> CBool
(&&:) = undefined
infixr 3 &&:
--The boolean disjunction can be built as a conditional
(||:) :: CBool -> CBool -> CBool
(||:) = undefined
infixr 2 ||:
-- a pair is a way to compute something based on the values
-- contained within the pair.
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
An instance to show CPairs as regular pairs .
instance (Show a, Show b) => Show (CPair a b) where
show p = "cPair " <> show (cOn p (,))
builds a pair out of two values as an object which , when given
--a function to be applied on the values, it will apply it on them.
cPair :: a -> b -> CPair a b
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: CPair a b -> a
cFst = undefined
second projection
cSnd :: CPair a b -> b
cSnd = undefined
-- A natural number is any way to iterate a function s a number of times
-- over an initial value z
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
-- An instance to show CNats as regular natural numbers
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
--0 will iterate the function s 0 times over z, producing z
c0 :: CNat
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat
c1 = undefined
--Successor n either
- applies s one more time in addition to what n does
-- - iterates s n times over (s z)
cS :: CNat -> CNat
cS = undefined
--Addition of m and n is done by iterating s n times over m
(+:) :: CNat -> CNat -> CNat
(+:) = undefined
infixl 6 +:
--Multiplication of m and n can be done by composing n and m
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
--Exponentiation of m and n can be done by applying n to m
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
--Testing whether a value is 0 can be done through iteration
-- using a function constantly false and an initial value true
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: CNat -> CNat
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
-- of the predeccesor function
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
-- arithmetic
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
-- m is less than (or equal to) n if when substracting n from m we get 0
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
-- equality on naturals can be defined my means of comparisons
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
--Fun with arithmetic and pairs
--Define factorial. You can iterate over a pair to contain the current index and so far factorial
cFactorial :: CNat -> CNat
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: CNat -> CNat
cFibonacci = undefined
--Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
--hint repeated substraction, iterated for at most m times.
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = undefined
-- a list is a way to aggregate a sequence of elements given an aggregation function and an initial value.
newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b }
make CList an instance of Foldable
instance Foldable CList where
--An instance to show CLists as regular lists.
instance (Show a) => Show (CList a) where
show l = "cList " <> (show $ toList l)
-- The empty list is that which when aggregated it will always produce the initial value
cNil :: CList a
cNil = undefined
-- Adding an element to a list means that, when aggregating the list, the newly added
-- element will be aggregated with the result obtained by aggregating the remainder of the list
(.:) :: a -> CList a -> CList a
(.:) = undefined
we can obtain a CList from a regular list by folding the list
cList :: [a] -> CList a
cList = undefined
builds a CList of CNats corresponding to a list of Integers
cNatList :: [Integer] -> CList CNat
cNatList = undefined
-- sums the elements in the list
cSum :: CList CNat -> CNat
cSum = undefined
cIsNil :: CList a -> CBool
cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue
churchHead :: Term
churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cHead :: CList a -> a -> a
cHead = \l d -> cFoldR l (\x _ -> x) d
churchTail :: Term
churchTail = lam "l" (churchFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ churchNil $$ churchNil)
))
cTail :: CList a -> CList a
cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil)
cLength :: CList a -> CNat
cLength = \l -> cFoldR l (\_ n -> cS n) 0
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b)
divmod m n = divmod' (0, 0)
where
divmod' (x, y)
| x' <= m = divmod' (x', succ y)
| otherwise = (y, m - x)
where x' = x + n
divmod' m n =
if n == 0 then (0, m)
else
Function.fix
(\f p ->
(\x' ->
if x' > 0 then f ((,) (succ (fst p)) x')
else if (<=) n (snd p) then ((,) (succ (fst p)) 0)
else p)
((-) (snd p) n))
(0, m)
churchDivMod' :: Term
churchDivMod' = lams ["m", "n"]
(churchIs0 $$ v "n"
$$ (churchPair $$ church0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(churchIs0 $$ v "x"
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "p")
$$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0)
$$ v "p"
)
$$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x"))
)
$$ (churchSub $$ (churchSnd $$ v "p") $$ v "n")
)
$$ (churchPair $$ church0 $$ v "m")
)
)
churchSudan :: Term
churchSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(churchIs0 $$ v "n"
$$ (churchPlus $$ v "x" $$ v "y")
$$ (churchIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (churchPred $$ v "n")
$$ v "fnpy"
$$ (churchPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y"))
)
)
))
churchAckermann :: Term
churchAckermann = fix $$ lam "A" (lams ["m", "n"]
(churchIs0 $$ v "m"
$$ (churchS $$ v "n")
$$ (churchIs0 $$ v "n"
$$ (v "A" $$ (churchPred $$ v "m") $$ church1)
$$ (v "A" $$ (churchPred $$ v "m")
$$ (v "A" $$ v "m" $$ (churchPred $$ v "n")))
)
)
)
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/HaskellChurch_20210415163846.hs | haskell | # LANGUAGE RankNTypes #
The boolean negation switches the alternatives
The boolean conjunction can be built as a conditional
The boolean disjunction can be built as a conditional
a pair is a way to compute something based on the values
contained within the pair.
a function to be applied on the values, it will apply it on them.
A natural number is any way to iterate a function s a number of times
over an initial value z
An instance to show CNats as regular natural numbers
0 will iterate the function s 0 times over z, producing z
Successor n either
- iterates s n times over (s z)
Addition of m and n is done by iterating s n times over m
Multiplication of m and n can be done by composing n and m
Exponentiation of m and n can be done by applying n to m
Testing whether a value is 0 can be done through iteration
using a function constantly false and an initial value true
of the predeccesor function
arithmetic
m is less than (or equal to) n if when substracting n from m we get 0
equality on naturals can be defined my means of comparisons
Fun with arithmetic and pairs
Define factorial. You can iterate over a pair to contain the current index and so far factorial
Given m and n, compute q and r satisfying m = q * n + r. If n is not 0 then r should be less than n.
hint repeated substraction, iterated for at most m times.
a list is a way to aggregate a sequence of elements given an aggregation function and an initial value.
An instance to show CLists as regular lists.
The empty list is that which when aggregated it will always produce the initial value
Adding an element to a list means that, when aggregating the list, the newly added
element will be aggregated with the result obtained by aggregating the remainder of the list
sums the elements in the list | module HaskellChurch where
A boolean is any way to choose between two alternatives
newtype CBool = CBool {cIf :: forall t. t -> t -> t}
An instance to show as regular Booleans
instance Show CBool where
show b = "cBool " <> show (cIf b True False)
The boolean constant true always chooses the first alternative
cTrue :: CBool
cTrue = undefined
The boolean constant false always chooses the second alternative
cFalse :: CBool
cFalse = undefined
cBool :: Bool -> CBool
cBool True = cTrue
cBool False = cFalse
cNot :: CBool -> CBool
cNot = undefined
(&&:) :: CBool -> CBool -> CBool
(&&:) = undefined
infixr 3 &&:
(||:) :: CBool -> CBool -> CBool
(||:) = undefined
infixr 2 ||:
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
An instance to show CPairs as regular pairs .
instance (Show a, Show b) => Show (CPair a b) where
show p = "cPair " <> show (cOn p (,))
builds a pair out of two values as an object which , when given
cPair :: a -> b -> CPair a b
cPair = undefined
first projection uses the function selecting first component on a pair
cFst :: CPair a b -> a
cFst = undefined
second projection
cSnd :: CPair a b -> b
cSnd = undefined
newtype CNat = CNat { cFor :: forall t. (t -> t) -> t -> t }
instance Show CNat where
show n = show $ cFor n (1 +) (0 :: Integer)
c0 :: CNat
c0 = undefined
1 is the the function s iterated 1 times over z , that is , z
c1 :: CNat
c1 = undefined
- applies s one more time in addition to what n does
cS :: CNat -> CNat
cS = undefined
(+:) :: CNat -> CNat -> CNat
(+:) = undefined
infixl 6 +:
(*:) :: CNat -> CNat -> CNat
(*:) = \n m -> CNat $ cFor n . cFor m
infixl 7 *:
(^:) :: CNat -> CNat -> CNat
(^:) = \m n -> CNat $ cFor n (cFor m)
infixr 8 ^:
cIs0 :: CNat -> CBool
cIs0 = \n -> cFor n (\_ -> cFalse) cTrue
Predecessor ( evaluating to 0 for 0 ) can be defined iterating
over pairs , starting from an initial value ( 0 , 0 )
cPred :: CNat -> CNat
cPred = undefined
substraction from m n ( evaluating to 0 if m < n ) is repeated application
(-:) :: CNat -> CNat -> CNat
(-:) = \m n -> cFor n cPred m
Transform a value into a CNat ( should yield c0 for nums < = 0 )
cNat :: (Ord p, Num p) => p -> CNat
cNat n = undefined
We can define an instance Num CNat which will allow us to see any
integer constant as a CNat ( e.g. 12 : : CNat ) and also use regular
instance Num CNat where
(+) = (+:)
(*) = (*:)
(-) = (-:)
abs = id
signum n = cIf (cIs0 n) 0 1
fromInteger = cNat
(<=:) :: CNat -> CNat -> CBool
(<=:) = undefined
infix 4 <=:
(>=:) :: CNat -> CNat -> CBool
(>=:) = \m n -> n <=: m
infix 4 >=:
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
(==:) :: CNat -> CNat -> CBool
(==:) = undefined
cFactorial :: CNat -> CNat
cFactorial = undefined
Define Fibonacci . You can iterate over a pair to contain two consecutive numbers in the sequence
cFibonacci :: CNat -> CNat
cFibonacci = undefined
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = undefined
newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b }
make CList an instance of Foldable
instance Foldable CList where
instance (Show a) => Show (CList a) where
show l = "cList " <> (show $ toList l)
cNil :: CList a
cNil = undefined
(.:) :: a -> CList a -> CList a
(.:) = undefined
we can obtain a CList from a regular list by folding the list
cList :: [a] -> CList a
cList = undefined
builds a CList of CNats corresponding to a list of Integers
cNatList :: [Integer] -> CList CNat
cNatList = undefined
cSum :: CList CNat -> CNat
cSum = undefined
cIsNil :: CList a -> CBool
cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue
churchHead :: Term
churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cHead :: CList a -> a -> a
cHead = \l d -> cFoldR l (\x _ -> x) d
churchTail :: Term
churchTail = lam "l" (churchFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ churchNil $$ churchNil)
))
cTail :: CList a -> CList a
cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil)
cLength :: CList a -> CNat
cLength = \l -> cFoldR l (\_ n -> cS n) 0
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b)
divmod m n = divmod' (0, 0)
where
divmod' (x, y)
| x' <= m = divmod' (x', succ y)
| otherwise = (y, m - x)
where x' = x + n
divmod' m n =
if n == 0 then (0, m)
else
Function.fix
(\f p ->
(\x' ->
if x' > 0 then f ((,) (succ (fst p)) x')
else if (<=) n (snd p) then ((,) (succ (fst p)) 0)
else p)
((-) (snd p) n))
(0, m)
churchDivMod' :: Term
churchDivMod' = lams ["m", "n"]
(churchIs0 $$ v "n"
$$ (churchPair $$ church0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(churchIs0 $$ v "x"
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "p")
$$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0)
$$ v "p"
)
$$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x"))
)
$$ (churchSub $$ (churchSnd $$ v "p") $$ v "n")
)
$$ (churchPair $$ church0 $$ v "m")
)
)
churchSudan :: Term
churchSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(churchIs0 $$ v "n"
$$ (churchPlus $$ v "x" $$ v "y")
$$ (churchIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (churchPred $$ v "n")
$$ v "fnpy"
$$ (churchPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y"))
)
)
))
churchAckermann :: Term
churchAckermann = fix $$ lam "A" (lams ["m", "n"]
(churchIs0 $$ v "m"
$$ (churchS $$ v "n")
$$ (churchIs0 $$ v "n"
$$ (v "A" $$ (churchPred $$ v "m") $$ church1)
$$ (v "A" $$ (churchPred $$ v "m")
$$ (v "A" $$ v "m" $$ (churchPred $$ v "n")))
)
)
)
|
a173c792b6379c0b12efa8a1757c3987a7c857191668a1b41deded4d74dcf741 | noss/ifastcgi | ifastcgi.erl | -module(ifastcgi).
-compile(export_all).
%% API
-define(MASTER, ifastcgi_master).
add_server(Name, Port, Callback, Args) ->
Timeout = 120000,
gen_server:call(?MASTER,
{add_server, self(), Name, Port,
{Callback, Args}},
Timeout).
del_server(Name) ->
gen_server:call(?MASTER, {del_server, Name}).
which_servers() ->
gen_server:call(?MASTER, which_servers).
info_server(ServerName) ->
gen_server:call(?MASTER, {info, ServerName}).
| null | https://raw.githubusercontent.com/noss/ifastcgi/9971c7c349f614c926eb133b90fe5f037700366c/src/ifastcgi.erl | erlang | API | -module(ifastcgi).
-compile(export_all).
-define(MASTER, ifastcgi_master).
add_server(Name, Port, Callback, Args) ->
Timeout = 120000,
gen_server:call(?MASTER,
{add_server, self(), Name, Port,
{Callback, Args}},
Timeout).
del_server(Name) ->
gen_server:call(?MASTER, {del_server, Name}).
which_servers() ->
gen_server:call(?MASTER, which_servers).
info_server(ServerName) ->
gen_server:call(?MASTER, {info, ServerName}).
|
98ea080f25ccb033c5f142fd0ebc2efeb6b945171862695cd0db88d7e1a9327d | alesaccoia/festival_flinger | voices.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;
Centre for Speech Technology Research ; ;
University of Edinburgh , UK ; ;
;;; Copyright (c) 1996,1997 ;;
All Rights Reserved . ; ;
;;; ;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;
;;; this software and its documentation without restriction, including ;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;
;;; permit persons to whom this work is furnished to do so, subject to ;;
;;; the following conditions: ;;
;;; 1. The code must retain the above copyright notice, this list of ;;
;;; conditions and the following disclaimer. ;;
;;; 2. Any modifications must be clearly marked as such. ;;
3 . Original authors ' names are not deleted . ; ;
;;; 4. The authors' names are not used to endorse or promote products ;;
;;; derived from this software without specific prior written ;;
;;; permission. ;;
;;; ;;
;;; THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;
;;; SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;
;;; THIS SOFTWARE. ;;
;;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Preapre to access voices. Searches down a path of places.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define current-voice nil
"current-voice
The name of the current voice.")
;; The path to search for voices is created from the load-path with
;; an extra list of directories appended.
(defvar system-voice-path '( )
"system-voice-path
Additional directory not near the load path where voices can be
found, this can be redefined in lib/sitevars.scm if desired.")
(defvar system-voice-path-multisyn '( )
"system-voice-path-multisyn
Additional directory not near the load path where multisyn voices can be
found, this can be redefined in lib/sitevars.scm if desired.")
(defvar voice-path
(remove-duplicates
(append (mapcar (lambda (d) (path-append d "voices/")) load-path)
(mapcar (lambda (d) (path-as-directory d)) system-voice-path)
))
"voice-path
List of places to look for voices. If not set it is initialised from
load-path by appending \"voices/\" to each directory with
system-voice-path appended.")
(defvar voice-path-multisyn
(remove-duplicates
(append (mapcar (lambda (d) (path-append d "voices-multisyn/")) load-path)
(mapcar (lambda (d) (path-as-directory d)) system-voice-path-multisyn)
))
"voice-path-multisyn
List of places to look for multisyn voices. If not set it is initialised from
load-path by appending \"voices-multisyn/\" to each directory with
system-voice-path-multisyn appended.")
;; Declaration of voices. When we declare a voice we record the
;; directory and set up an autoload for the vocie-selecting function
(defvar voice-locations ()
"voice-locations
Association list recording where voices were found.")
(defvar voice-location-trace nil
"voice-location-trace
Set t to print voice locations as they are found")
(define (voice-location name dir doc)
"(voice-location NAME DIR DOCSTRING)
Record the location of a voice. Called for each voice found on voice-path.
Can be called in site-init or .festivalrc for additional voices which
exist elsewhere."
(let ((func_name (intern (string-append "voice_" name)))
)
(set! name (intern name))
(set! voice-locations (cons (cons name dir) voice-locations))
(eval (list 'autoload func_name (path-append dir "festvox/" name) doc))
(if voice-location-trace
(format t "Voice: %s %s\n" name dir)
)
)
)
(define (voice-location-multisyn name rootname dir doc)
"(voice-location NAME ROOTNAME DIR DOCSTRING)
Record the location of a voice. Called for each voice found on voice-path.
Can be called in site-init or .festivalrc for additional voices which
exist elsewhere."
(let ((func_name (intern (string-append "voice_" name)))
)
(set! name (intern name))
(set! voice-locations (cons (cons name dir) voice-locations))
(eval (list 'autoload func_name (path-append dir "festvox/" rootname) doc))
(if voice-location-trace
(format t "Voice: %s %s\n" name dir)
)
)
)
(define (current_voice_reset)
"(current_voice_reset)
This function is called at the start of defining any new voice.
It is design to allow the previous voice to reset any global
values it has messed with. If this variable value is nil then
the function wont be called.")
(define (voice_reset)
"(voice_reset)
This resets all variables back to acceptable values that may affect
voice generation. This function should always be called at the
start of any function defining a voice. In addition to reseting
standard variables the function current_voice_reset will be called.
This should always be set by the voice definition function (even
if it does nothing). This allows voice specific changes to be reset
when a new voice is selection. Unfortunately I can't force this
to be used."
(Parameter.set 'Duration_Stretch 1.0)
(set! after_synth_hooks default_after_synth_hooks)
;; The follow are reset to allow existing voices to continue
;; to work, new voices should be setting these explicitly
(Parameter.set 'Token_Method 'Token_English)
(Parameter.set 'POS_Method Classic_POS)
(Parameter.set 'Phrasify_Method Classic_Phrasify)
(Parameter.set 'Word_Method Classic_Word)
(Parameter.set 'Pause_Method Classic_Pauses)
(Parameter.set 'PostLex_Method Classic_PostLex)
(set! diphone_module_hooks nil)
(set! UniSyn_module_hooks nil)
(if current_voice_reset
(current_voice_reset))
(set! current_voice_reset nil)
)
(defvar Voice_descriptions nil
"Internal variable containing list of voice descriptions as
decribed by proclaim_voice.")
(define (proclaim_voice name description)
"(proclaim_voice NAME DESCRIPTION)
Describe a voice to the systen. NAME should be atomic name, that
conventionally will have voice_ prepended to name the basic selection
function. OPTIONS is an assoc list of feature and value and must
have at least features for language, gender, dialect and
description. The first there of these are atomic, while the description
is a text string describing the voice."
(let ((voxdesc (assoc name Voice_descriptions)))
(if voxdesc
(set-car! (cdr voxdesc) description)
(set! Voice_descriptions
(cons (list name description) Voice_descriptions))))
)
(define (voice.description name)
"(voice.description NAME)
Output description of named voice. If the named voice is not yet loaded
it is loaded."
(let ((voxdesc (assoc name Voice_descriptions))
(cv current-voice))
(if (null voxdesc)
(unwind-protect
(begin
(voice.select name)
(voice.select cv) ;; switch back to current voice
(set! voxdesc (assoc name Voice_descriptions)))))
(if voxdesc
voxdesc
(begin
(format t "SIOD: unknown voice %s\n" name)
nil))))
(define (voice.select name)
"(voice.select NAME)
Call function to set up voice NAME. This is normally done by
prepending voice_ to NAME and call it as a function."
(eval (list (intern (string-append "voice_" name)))))
(define (voice.describe name)
"(voice.describe NAME)
Describe voice NAME by saying its description. Unfortunately although
it would be nice to say that voice's description in the voice itself
its not going to work cross language. So this just uses the current
voice. So here we assume voices describe themselves in English
which is pretty anglo-centric, shitsurei shimasu."
(let ((voxdesc (voice.description name)))
(let ((desc (car (cdr (assoc 'description (car (cdr voxdesc)))))))
(cond
(desc (tts_text desc nil))
(voxdesc
(SayText
(format nil "A voice called %s exist but it has no description"
name)))
(t
(SayText
(format nil "There is no voice called %s defined" name)))))))
(define (voice.list)
"(voice.list)
List of all (potential) voices in the system. This checks the voice-location
list of potential voices found be scanning the voice-path at start up time.
These names can be used as arguments to voice.description and
voice.describe."
(mapcar car voice-locations))
;; Voices are found on the voice-path if they are in directories of the form
;; DIR/LANGUAGE/NAME
(define (search-for-voices)
"(search-for-voices)
Search down voice-path to locate voices."
(let ((dirs voice-path)
(dir nil)
languages language
voices voicedir voice
)
(while dirs
(set! dir (car dirs))
(setq languages (directory-entries dir t))
(while languages
(set! language (car languages))
(set! voices (directory-entries (path-append dir language) t))
(while voices
(set! voicedir (car voices))
(set! voice (path-basename voicedir))
(if (string-matches voicedir ".*\\..*")
nil
(voice-location
voice
(path-as-directory (path-append dir language voicedir))
"voice found on path")
)
(set! voices (cdr voices))
)
(set! languages (cdr languages))
)
(set! dirs (cdr dirs))
)
)
)
A single file is allowed to define multiple multisyn voices , so this has
been adapted for this . thinks this is just evil , but could n't think
;; of a better way.
(define (search-for-voices-multisyn)
"(search-for-voices-multisyn)
Search down multisyn voice-path to locate multisyn voices."
(let ((dirs voice-path-multisyn)
(dir nil)
languages language
voices voicedir voice voice-list
)
(while dirs
(set! dir (car dirs))
(set! languages (directory-entries dir t))
(while languages
(set! language (car languages))
(set! voices (directory-entries (path-append dir language) t))
(while voices
(set! voicedir (car voices))
(set! voice (path-basename voicedir))
(if (string-matches voicedir ".*\\..*")
nil
(begin
;; load the voice definition file, but don't evaluate it!
(set! voice-def-file (load (path-append dir language voicedir "festvox"
(string-append voicedir ".scm")) t))
;; now find the "proclaim_voice" lines and register these voices.
(mapcar
(lambda (line)
(if (string-matches (car line) "proclaim_voice")
(voice-location-multisyn (intern (cadr (cadr line))) voicedir (path-append dir language voicedir) "registerd multisyn voice")))
voice-def-file)
))
(set! voices (cdr voices)))
(set! languages (cdr languages)))
(set! dirs (cdr dirs)))))
(search-for-voices)
(search-for-voices-multisyn)
We select the default voice from a list of possibilities . One of these
;; had better exist in every installation.
(define (no_voice_error)
(format t "\nWARNING\n")
(format t "No default voice found in %l\n" voice-path)
(format t "either no voices unpacked or voice-path is wrong\n")
(format t "Scheme interpreter will work, but there is no voice to speak with.\n")
(format t "WARNING\n\n"))
(defvar voice_default 'no_voice_error
"voice_default
A variable whose value is a function name that is called on start up to
the default voice. [see Site initialization]")
(defvar default-voice-priority-list
'(kal_diphone
cmu_us_slt_cg
cmu_us_rms_cg
cmu_us_bdl_cg
cmu_us_jmk_cg
cmu_us_awb_cg
; restricted license ( lexicon )
; restricted license ( lexicon )
; restricted license ( lexicon )
cstr_us_awb_arctic_multisyn
ked_diphone
don_diphone
rab_diphone
en1_mbrola
us1_mbrola
us2_mbrola
us3_mbrola
gsw_diphone ;; not publically distributed
el_diphone
)
"default-voice-priority-list
List of voice names. The first of them available becomes the default voice.")
(let ((voices default-voice-priority-list)
voice)
(while (and voices (eq voice_default 'no_voice_error))
(set! voice (car voices))
(if (assoc voice voice-locations)
(set! voice_default (intern (string-append "voice_" voice)))
)
(set! voices (cdr voices))
)
)
(provide 'voices)
| null | https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/lib/voices.scm | scheme |
;;
;
;
Copyright (c) 1996,1997 ;;
;
;;
Permission is hereby granted, free of charge, to use and distribute ;;
this software and its documentation without restriction, including ;;
without limitation the rights to use, copy, modify, merge, publish, ;;
distribute, sublicense, and/or sell copies of this work, and to ;;
permit persons to whom this work is furnished to do so, subject to ;;
the following conditions: ;;
1. The code must retain the above copyright notice, this list of ;;
conditions and the following disclaimer. ;;
2. Any modifications must be clearly marked as such. ;;
;
4. The authors' names are not used to endorse or promote products ;;
derived from this software without specific prior written ;;
permission. ;;
;;
THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;
SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;
;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;
THIS SOFTWARE. ;;
;;
Preapre to access voices. Searches down a path of places.
The path to search for voices is created from the load-path with
an extra list of directories appended.
Declaration of voices. When we declare a voice we record the
directory and set up an autoload for the vocie-selecting function
The follow are reset to allow existing voices to continue
to work, new voices should be setting these explicitly
switch back to current voice
Voices are found on the voice-path if they are in directories of the form
DIR/LANGUAGE/NAME
of a better way.
load the voice definition file, but don't evaluate it!
now find the "proclaim_voice" lines and register these voices.
had better exist in every installation.
restricted license ( lexicon )
restricted license ( lexicon )
restricted license ( lexicon )
not publically distributed |
(define current-voice nil
"current-voice
The name of the current voice.")
(defvar system-voice-path '( )
"system-voice-path
Additional directory not near the load path where voices can be
found, this can be redefined in lib/sitevars.scm if desired.")
(defvar system-voice-path-multisyn '( )
"system-voice-path-multisyn
Additional directory not near the load path where multisyn voices can be
found, this can be redefined in lib/sitevars.scm if desired.")
(defvar voice-path
(remove-duplicates
(append (mapcar (lambda (d) (path-append d "voices/")) load-path)
(mapcar (lambda (d) (path-as-directory d)) system-voice-path)
))
"voice-path
List of places to look for voices. If not set it is initialised from
load-path by appending \"voices/\" to each directory with
system-voice-path appended.")
(defvar voice-path-multisyn
(remove-duplicates
(append (mapcar (lambda (d) (path-append d "voices-multisyn/")) load-path)
(mapcar (lambda (d) (path-as-directory d)) system-voice-path-multisyn)
))
"voice-path-multisyn
List of places to look for multisyn voices. If not set it is initialised from
load-path by appending \"voices-multisyn/\" to each directory with
system-voice-path-multisyn appended.")
(defvar voice-locations ()
"voice-locations
Association list recording where voices were found.")
(defvar voice-location-trace nil
"voice-location-trace
Set t to print voice locations as they are found")
(define (voice-location name dir doc)
"(voice-location NAME DIR DOCSTRING)
Record the location of a voice. Called for each voice found on voice-path.
Can be called in site-init or .festivalrc for additional voices which
exist elsewhere."
(let ((func_name (intern (string-append "voice_" name)))
)
(set! name (intern name))
(set! voice-locations (cons (cons name dir) voice-locations))
(eval (list 'autoload func_name (path-append dir "festvox/" name) doc))
(if voice-location-trace
(format t "Voice: %s %s\n" name dir)
)
)
)
(define (voice-location-multisyn name rootname dir doc)
"(voice-location NAME ROOTNAME DIR DOCSTRING)
Record the location of a voice. Called for each voice found on voice-path.
Can be called in site-init or .festivalrc for additional voices which
exist elsewhere."
(let ((func_name (intern (string-append "voice_" name)))
)
(set! name (intern name))
(set! voice-locations (cons (cons name dir) voice-locations))
(eval (list 'autoload func_name (path-append dir "festvox/" rootname) doc))
(if voice-location-trace
(format t "Voice: %s %s\n" name dir)
)
)
)
(define (current_voice_reset)
"(current_voice_reset)
This function is called at the start of defining any new voice.
It is design to allow the previous voice to reset any global
values it has messed with. If this variable value is nil then
the function wont be called.")
(define (voice_reset)
"(voice_reset)
This resets all variables back to acceptable values that may affect
voice generation. This function should always be called at the
start of any function defining a voice. In addition to reseting
standard variables the function current_voice_reset will be called.
This should always be set by the voice definition function (even
if it does nothing). This allows voice specific changes to be reset
when a new voice is selection. Unfortunately I can't force this
to be used."
(Parameter.set 'Duration_Stretch 1.0)
(set! after_synth_hooks default_after_synth_hooks)
(Parameter.set 'Token_Method 'Token_English)
(Parameter.set 'POS_Method Classic_POS)
(Parameter.set 'Phrasify_Method Classic_Phrasify)
(Parameter.set 'Word_Method Classic_Word)
(Parameter.set 'Pause_Method Classic_Pauses)
(Parameter.set 'PostLex_Method Classic_PostLex)
(set! diphone_module_hooks nil)
(set! UniSyn_module_hooks nil)
(if current_voice_reset
(current_voice_reset))
(set! current_voice_reset nil)
)
(defvar Voice_descriptions nil
"Internal variable containing list of voice descriptions as
decribed by proclaim_voice.")
(define (proclaim_voice name description)
"(proclaim_voice NAME DESCRIPTION)
Describe a voice to the systen. NAME should be atomic name, that
conventionally will have voice_ prepended to name the basic selection
function. OPTIONS is an assoc list of feature and value and must
have at least features for language, gender, dialect and
description. The first there of these are atomic, while the description
is a text string describing the voice."
(let ((voxdesc (assoc name Voice_descriptions)))
(if voxdesc
(set-car! (cdr voxdesc) description)
(set! Voice_descriptions
(cons (list name description) Voice_descriptions))))
)
(define (voice.description name)
"(voice.description NAME)
Output description of named voice. If the named voice is not yet loaded
it is loaded."
(let ((voxdesc (assoc name Voice_descriptions))
(cv current-voice))
(if (null voxdesc)
(unwind-protect
(begin
(voice.select name)
(set! voxdesc (assoc name Voice_descriptions)))))
(if voxdesc
voxdesc
(begin
(format t "SIOD: unknown voice %s\n" name)
nil))))
(define (voice.select name)
"(voice.select NAME)
Call function to set up voice NAME. This is normally done by
prepending voice_ to NAME and call it as a function."
(eval (list (intern (string-append "voice_" name)))))
(define (voice.describe name)
"(voice.describe NAME)
Describe voice NAME by saying its description. Unfortunately although
it would be nice to say that voice's description in the voice itself
its not going to work cross language. So this just uses the current
voice. So here we assume voices describe themselves in English
which is pretty anglo-centric, shitsurei shimasu."
(let ((voxdesc (voice.description name)))
(let ((desc (car (cdr (assoc 'description (car (cdr voxdesc)))))))
(cond
(desc (tts_text desc nil))
(voxdesc
(SayText
(format nil "A voice called %s exist but it has no description"
name)))
(t
(SayText
(format nil "There is no voice called %s defined" name)))))))
(define (voice.list)
"(voice.list)
List of all (potential) voices in the system. This checks the voice-location
list of potential voices found be scanning the voice-path at start up time.
These names can be used as arguments to voice.description and
voice.describe."
(mapcar car voice-locations))
(define (search-for-voices)
"(search-for-voices)
Search down voice-path to locate voices."
(let ((dirs voice-path)
(dir nil)
languages language
voices voicedir voice
)
(while dirs
(set! dir (car dirs))
(setq languages (directory-entries dir t))
(while languages
(set! language (car languages))
(set! voices (directory-entries (path-append dir language) t))
(while voices
(set! voicedir (car voices))
(set! voice (path-basename voicedir))
(if (string-matches voicedir ".*\\..*")
nil
(voice-location
voice
(path-as-directory (path-append dir language voicedir))
"voice found on path")
)
(set! voices (cdr voices))
)
(set! languages (cdr languages))
)
(set! dirs (cdr dirs))
)
)
)
A single file is allowed to define multiple multisyn voices , so this has
been adapted for this . thinks this is just evil , but could n't think
(define (search-for-voices-multisyn)
"(search-for-voices-multisyn)
Search down multisyn voice-path to locate multisyn voices."
(let ((dirs voice-path-multisyn)
(dir nil)
languages language
voices voicedir voice voice-list
)
(while dirs
(set! dir (car dirs))
(set! languages (directory-entries dir t))
(while languages
(set! language (car languages))
(set! voices (directory-entries (path-append dir language) t))
(while voices
(set! voicedir (car voices))
(set! voice (path-basename voicedir))
(if (string-matches voicedir ".*\\..*")
nil
(begin
(set! voice-def-file (load (path-append dir language voicedir "festvox"
(string-append voicedir ".scm")) t))
(mapcar
(lambda (line)
(if (string-matches (car line) "proclaim_voice")
(voice-location-multisyn (intern (cadr (cadr line))) voicedir (path-append dir language voicedir) "registerd multisyn voice")))
voice-def-file)
))
(set! voices (cdr voices)))
(set! languages (cdr languages)))
(set! dirs (cdr dirs)))))
(search-for-voices)
(search-for-voices-multisyn)
We select the default voice from a list of possibilities . One of these
(define (no_voice_error)
(format t "\nWARNING\n")
(format t "No default voice found in %l\n" voice-path)
(format t "either no voices unpacked or voice-path is wrong\n")
(format t "Scheme interpreter will work, but there is no voice to speak with.\n")
(format t "WARNING\n\n"))
(defvar voice_default 'no_voice_error
"voice_default
A variable whose value is a function name that is called on start up to
the default voice. [see Site initialization]")
(defvar default-voice-priority-list
'(kal_diphone
cmu_us_slt_cg
cmu_us_rms_cg
cmu_us_bdl_cg
cmu_us_jmk_cg
cmu_us_awb_cg
cstr_us_awb_arctic_multisyn
ked_diphone
don_diphone
rab_diphone
en1_mbrola
us1_mbrola
us2_mbrola
us3_mbrola
el_diphone
)
"default-voice-priority-list
List of voice names. The first of them available becomes the default voice.")
(let ((voices default-voice-priority-list)
voice)
(while (and voices (eq voice_default 'no_voice_error))
(set! voice (car voices))
(if (assoc voice voice-locations)
(set! voice_default (intern (string-append "voice_" voice)))
)
(set! voices (cdr voices))
)
)
(provide 'voices)
|
be2723a678fb600d560493bcc434502cc46fdd1980126398a304fbdbb8b7f80b | janestreet/jane-street-build-server | config.mli | open Build_pkg_common.Std
type t [@@deriving sexp]
val create : base_dir:string -> opam_switch:Opam_switch.t -> t
(** Base directory, everything happens inside *)
val base_dir : t -> string
(** Opam_switch used by this opam installation. *)
val opam_switch : t -> Opam_switch.t
| null | https://raw.githubusercontent.com/janestreet/jane-street-build-server/7dd5dacfae33a361ba10ea93c8b9b21a9ce812ef/server/config.mli | ocaml | * Base directory, everything happens inside
* Opam_switch used by this opam installation. | open Build_pkg_common.Std
type t [@@deriving sexp]
val create : base_dir:string -> opam_switch:Opam_switch.t -> t
val base_dir : t -> string
val opam_switch : t -> Opam_switch.t
|
2f0006eda5871b433ca0bd95debf1348249acfba0b80ce2ce75221cab4cb5c69 | BranchTaken/Hemlock | u128.mli | * 128 - bit unsigned integer type .
See { ! module : ConvertIntf } for documentation on conversion functions .
See {!module:ConvertIntf} for documentation on conversion functions. *)
open RudimentsInt0
type t = u128
include IntwIntf.SFU with type t := t
val trunc_of_zint: Zint.t -> t
val extend_to_zint: t -> Zint.t
val narrow_of_zint_opt: Zint.t -> t option
val narrow_of_zint_hlt: Zint.t -> t
val trunc_of_nat: Nat.t -> t
val extend_to_nat: t -> Nat.t
val narrow_of_nat_opt: Nat.t -> t option
val narrow_of_nat_hlt: Nat.t -> t
val trunc_of_i512: I512.t -> t
val extend_to_i512: t -> I512.t
val narrow_of_i512_opt: I512.t -> t option
val narrow_of_i512_hlt: I512.t -> t
val trunc_of_u512: U512.t -> t
val extend_to_u512: t -> U512.t
val narrow_of_u512_opt: U512.t -> t option
val narrow_of_u512_hlt: U512.t -> t
val trunc_of_i256: I256.t -> t
val extend_to_i256: t -> I256.t
val narrow_of_i256_opt: I256.t -> t option
val narrow_of_i256_hlt: I256.t -> t
val trunc_of_u256: U256.t -> t
val extend_to_u256: t -> U256.t
val narrow_of_u256_opt: U256.t -> t option
val narrow_of_u256_hlt: U256.t -> t
val bits_of_i128: I128.t -> t
val bits_to_i128: t -> I128.t
val like_of_i128_opt: I128.t -> t option
val like_to_i128_opt: t -> I128.t option
val like_of_i128_hlt: I128.t -> t
val like_to_i128_hlt: t -> I128.t
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/53da5c0d9cf0c94d58b4391735d917518eec67fa/bootstrap/src/basis/u128.mli | ocaml | * 128 - bit unsigned integer type .
See { ! module : ConvertIntf } for documentation on conversion functions .
See {!module:ConvertIntf} for documentation on conversion functions. *)
open RudimentsInt0
type t = u128
include IntwIntf.SFU with type t := t
val trunc_of_zint: Zint.t -> t
val extend_to_zint: t -> Zint.t
val narrow_of_zint_opt: Zint.t -> t option
val narrow_of_zint_hlt: Zint.t -> t
val trunc_of_nat: Nat.t -> t
val extend_to_nat: t -> Nat.t
val narrow_of_nat_opt: Nat.t -> t option
val narrow_of_nat_hlt: Nat.t -> t
val trunc_of_i512: I512.t -> t
val extend_to_i512: t -> I512.t
val narrow_of_i512_opt: I512.t -> t option
val narrow_of_i512_hlt: I512.t -> t
val trunc_of_u512: U512.t -> t
val extend_to_u512: t -> U512.t
val narrow_of_u512_opt: U512.t -> t option
val narrow_of_u512_hlt: U512.t -> t
val trunc_of_i256: I256.t -> t
val extend_to_i256: t -> I256.t
val narrow_of_i256_opt: I256.t -> t option
val narrow_of_i256_hlt: I256.t -> t
val trunc_of_u256: U256.t -> t
val extend_to_u256: t -> U256.t
val narrow_of_u256_opt: U256.t -> t option
val narrow_of_u256_hlt: U256.t -> t
val bits_of_i128: I128.t -> t
val bits_to_i128: t -> I128.t
val like_of_i128_opt: I128.t -> t option
val like_to_i128_opt: t -> I128.t option
val like_of_i128_hlt: I128.t -> t
val like_to_i128_hlt: t -> I128.t
| |
d4c3451a745ad308ef640268dd38d3afac1789d7b0c87f0ffd0dbae09cd14302 | rob7hunter/leftparen | validate.scm | #lang scheme/base
;; form validation
(require "util.scm"
"record.scm"
"contract-lp.ss")
(provide validate
;; field-validate (via contract)
)
;; constructs a fn suitable for passing in to the #:validate keyword of a form call
;; the fn : rec -> content
;;
;; Usage ex: (validate (field-validate 'name string?)
;; (field-validate 'age (lambda (n) (and (integer? n) (>= n 13)))))
;;
(define (validate . validation-fns)
(lambda (rec)
(let ((errors (filter-map (lambda (f) (f rec)) validation-fns)))
(if (empty? errors)
#f
(string-join errors "\n")))))
;;
;; field-validate
;;
(provide/contract (field-validate (->* (symbol?)
((or/c #f (-> any/c any/c))
#:msg-fn (-> any/c string?))
(-> rec? (or/c #f string?)))))
;;
(define (field-validate field-name
(pred #f)
#:msg-fn (msg-fn (lambda (bad-val)
(format "'~A' is an invalid value for field ~A."
field-name bad-val))))
(lambda (rec)
(aif (rec-prop rec field-name)
(if pred
(if (pred it)
#f
(msg-fn it))
#f)
(format "Missing field '~A'." field-name))))
| null | https://raw.githubusercontent.com/rob7hunter/leftparen/169c896bda989b6a049fe49253a04d6f8b62402b/validate.scm | scheme | form validation
field-validate (via contract)
constructs a fn suitable for passing in to the #:validate keyword of a form call
the fn : rec -> content
Usage ex: (validate (field-validate 'name string?)
(field-validate 'age (lambda (n) (and (integer? n) (>= n 13)))))
field-validate
| #lang scheme/base
(require "util.scm"
"record.scm"
"contract-lp.ss")
(provide validate
)
(define (validate . validation-fns)
(lambda (rec)
(let ((errors (filter-map (lambda (f) (f rec)) validation-fns)))
(if (empty? errors)
#f
(string-join errors "\n")))))
(provide/contract (field-validate (->* (symbol?)
((or/c #f (-> any/c any/c))
#:msg-fn (-> any/c string?))
(-> rec? (or/c #f string?)))))
(define (field-validate field-name
(pred #f)
#:msg-fn (msg-fn (lambda (bad-val)
(format "'~A' is an invalid value for field ~A."
field-name bad-val))))
(lambda (rec)
(aif (rec-prop rec field-name)
(if pred
(if (pred it)
#f
(msg-fn it))
#f)
(format "Missing field '~A'." field-name))))
|
5a4d4b78261924e595f33c642a13f05780d3b257d6e477ae532307591402d8e8 | kappelmann/engaging-large-scale-functional-programming | Exercise07.hs | module Exercise07 where
import Data.List
import Data.Ord
type Graph = [[Integer]]
(#) :: Graph -> Graph -> Graph
(#) = (++)
emptyGraph :: Graph
emptyGraph = []
isTree :: ([Integer], [(Integer,Integer)]) -> Bool
isTree ([],[]) = True
isTree g | graphRemoved == g = False
| otherwise = isTree graphRemoved
where
removeEnds (ns, es) = (nodes, edges)
where
nodes = filter (\n -> (foldl (\s (e1,e2) -> if e1 == n || e2 == n then s+1 else s) 0 es) > 1) ns
edges = filter (\(e1, e2) -> e1 `elem` nodes && e2 `elem` nodes) es
graphRemoved = removeEnds g
constructMinGraph :: Integer -> ([Integer], [(Integer, Integer)]) -> [(Integer, Integer)] -> ([Integer], [(Integer, Integer)])
constructMinGraph 0 g _ = g
constructMinGraph n (ns, es) (ne:nes)
| isTree constructedTree = constructMinGraph (n-1) constructedTree nes
| otherwise = constructMinGraph n (ns,es) nes
where
constructedTree = (ns, ne : es)
parseList :: String -> Integer -> [Integer]
parseList [] x = [x]
parseList (' ':s) x = x : parseList s 0
parseList (i:s) x = parseList s ((read [i] :: Integer) + 10*x)
parseNLists :: Integer -> IO [[Integer]]
parseNLists n = sequence [do
line <- getLine
return $ parseList line 0
|x<-[0..n-1]]
printGraph :: [(Integer, Integer)] -> IO ()
printGraph [] = return ()
printGraph (e : es) = do
putStr (show (snd e + 1))
putStr " "
putStrLn (show (fst e + 1))
printGraph es
main :: IO ()
main = do
nString <- getLine
let n = read nString :: Integer
lss <- parseNLists n
let es = smallestEdge $ toGraph n 0 lss
printGraph $ snd $ constructMinGraph (n-1) ([0..(n-1)], []) es
toGraph :: Integer -> Integer -> [[Integer]] -> [(Integer, Integer, Integer)]
toGraph maxN n _ | n == maxN = []
toGraph maxN n (xs : xss) =[ (w,to, n) | (to, w) <- zip [(n+1)..(maxN-1)] (drop (fromInteger (n+1)) xs)] ++ toGraph maxN (n+1) xss
smallestEdge :: [(Integer, Integer, Integer)] -> [(Integer, Integer)]
smallestEdge = map (\(w,f,t) -> (f,t)) . sortBy (comparing first)
where first (a,_,_) = a
| null | https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/8ed2c056fbd611f1531230648497cb5436d489e4/resources/contest/example_data/07/uploads/teamhaskel1337/Exercise07.hs | haskell | module Exercise07 where
import Data.List
import Data.Ord
type Graph = [[Integer]]
(#) :: Graph -> Graph -> Graph
(#) = (++)
emptyGraph :: Graph
emptyGraph = []
isTree :: ([Integer], [(Integer,Integer)]) -> Bool
isTree ([],[]) = True
isTree g | graphRemoved == g = False
| otherwise = isTree graphRemoved
where
removeEnds (ns, es) = (nodes, edges)
where
nodes = filter (\n -> (foldl (\s (e1,e2) -> if e1 == n || e2 == n then s+1 else s) 0 es) > 1) ns
edges = filter (\(e1, e2) -> e1 `elem` nodes && e2 `elem` nodes) es
graphRemoved = removeEnds g
constructMinGraph :: Integer -> ([Integer], [(Integer, Integer)]) -> [(Integer, Integer)] -> ([Integer], [(Integer, Integer)])
constructMinGraph 0 g _ = g
constructMinGraph n (ns, es) (ne:nes)
| isTree constructedTree = constructMinGraph (n-1) constructedTree nes
| otherwise = constructMinGraph n (ns,es) nes
where
constructedTree = (ns, ne : es)
parseList :: String -> Integer -> [Integer]
parseList [] x = [x]
parseList (' ':s) x = x : parseList s 0
parseList (i:s) x = parseList s ((read [i] :: Integer) + 10*x)
parseNLists :: Integer -> IO [[Integer]]
parseNLists n = sequence [do
line <- getLine
return $ parseList line 0
|x<-[0..n-1]]
printGraph :: [(Integer, Integer)] -> IO ()
printGraph [] = return ()
printGraph (e : es) = do
putStr (show (snd e + 1))
putStr " "
putStrLn (show (fst e + 1))
printGraph es
main :: IO ()
main = do
nString <- getLine
let n = read nString :: Integer
lss <- parseNLists n
let es = smallestEdge $ toGraph n 0 lss
printGraph $ snd $ constructMinGraph (n-1) ([0..(n-1)], []) es
toGraph :: Integer -> Integer -> [[Integer]] -> [(Integer, Integer, Integer)]
toGraph maxN n _ | n == maxN = []
toGraph maxN n (xs : xss) =[ (w,to, n) | (to, w) <- zip [(n+1)..(maxN-1)] (drop (fromInteger (n+1)) xs)] ++ toGraph maxN (n+1) xss
smallestEdge :: [(Integer, Integer, Integer)] -> [(Integer, Integer)]
smallestEdge = map (\(w,f,t) -> (f,t)) . sortBy (comparing first)
where first (a,_,_) = a
| |
708d1e560b80e27bdaad31df2fa8c77bbdbbcb68bc487638ade973f7b1bc2761 | synrc/nitro | element_fieldset.erl | -module(element_fieldset).
-author('Vladimir Galunshchikov').
-include_lib("nitro/include/nitro.hrl").
-compile(export_all).
render_element(Record) when Record#fieldset.show_if==false -> [<<>>];
render_element(Record) ->
List = [
%global
{<<"accesskey">>, Record#fieldset.accesskey},
{<<"class">>, Record#fieldset.class},
{<<"contenteditable">>, case Record#fieldset.contenteditable of true -> "true"; false -> "false"; _ -> [] end},
{<<"contextmenu">>, Record#fieldset.contextmenu},
{<<"dir">>, case Record#fieldset.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end},
{<<"draggable">>, case Record#fieldset.draggable of true -> "true"; false -> "false"; _ -> [] end},
{<<"dropzone">>, Record#fieldset.dropzone},
{<<"hidden">>, case Record#fieldset.hidden of "hidden" -> "hidden"; _ -> [] end},
{<<"id">>, Record#fieldset.id},
{<<"lang">>, Record#fieldset.lang},
{<<"spellcheck">>, case Record#fieldset.spellcheck of true -> "true"; false -> "false"; _ -> [] end},
{<<"style">>, Record#fieldset.style},
{<<"tabindex">>, Record#fieldset.tabindex},
{<<"title">>, Record#fieldset.title},
{<<"translate">>, case Record#fieldset.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end},
% spec
{<<"disabled">>, if Record#fieldset.disabled == true -> "disabled"; true -> [] end},
{<<"form">>,Record#fieldset.form},
{<<"name">>,Record#fieldset.name} | Record#fieldset.data_fields
],
wf_tags:emit_tag(
<<"fieldset">>,
[
case Record#fieldset.legend of
[] -> [];
B -> wf_tags:emit_tag(<<"legend">>, nitro:render(B), [])
end,
nitro:render(case Record#fieldset.body of [] -> []; B -> B end)
],
List). | null | https://raw.githubusercontent.com/synrc/nitro/753b543626add2c014584546ec50870808a2eb90/src/elements/form/element_fieldset.erl | erlang | global
spec | -module(element_fieldset).
-author('Vladimir Galunshchikov').
-include_lib("nitro/include/nitro.hrl").
-compile(export_all).
render_element(Record) when Record#fieldset.show_if==false -> [<<>>];
render_element(Record) ->
List = [
{<<"accesskey">>, Record#fieldset.accesskey},
{<<"class">>, Record#fieldset.class},
{<<"contenteditable">>, case Record#fieldset.contenteditable of true -> "true"; false -> "false"; _ -> [] end},
{<<"contextmenu">>, Record#fieldset.contextmenu},
{<<"dir">>, case Record#fieldset.dir of "ltr" -> "ltr"; "rtl" -> "rtl"; "auto" -> "auto"; _ -> [] end},
{<<"draggable">>, case Record#fieldset.draggable of true -> "true"; false -> "false"; _ -> [] end},
{<<"dropzone">>, Record#fieldset.dropzone},
{<<"hidden">>, case Record#fieldset.hidden of "hidden" -> "hidden"; _ -> [] end},
{<<"id">>, Record#fieldset.id},
{<<"lang">>, Record#fieldset.lang},
{<<"spellcheck">>, case Record#fieldset.spellcheck of true -> "true"; false -> "false"; _ -> [] end},
{<<"style">>, Record#fieldset.style},
{<<"tabindex">>, Record#fieldset.tabindex},
{<<"title">>, Record#fieldset.title},
{<<"translate">>, case Record#fieldset.contenteditable of "yes" -> "yes"; "no" -> "no"; _ -> [] end},
{<<"disabled">>, if Record#fieldset.disabled == true -> "disabled"; true -> [] end},
{<<"form">>,Record#fieldset.form},
{<<"name">>,Record#fieldset.name} | Record#fieldset.data_fields
],
wf_tags:emit_tag(
<<"fieldset">>,
[
case Record#fieldset.legend of
[] -> [];
B -> wf_tags:emit_tag(<<"legend">>, nitro:render(B), [])
end,
nitro:render(case Record#fieldset.body of [] -> []; B -> B end)
],
List). |
b1c56d05171e7223969d080ce55220b5b7dd2bd91cd8a566fa1f99160338c2bb | archaelus/erlirc | irc_user.erl | %%%-------------------------------------------------------------------
Geoff Ca nt
@author nt < >
%% @version {@vsn}, {@date} {@time}
%% @doc
%% @end
%%%-------------------------------------------------------------------
-module(irc_user).
-include_lib("irc.hrl").
%% API
-export([gproc_name/1,
gproc_name/2]).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
( ) - >
%% @doc
%% @end
gproc_name(#user{net=Net,nick=Nick}) when is_list(Net), is_list(Nick) ->
gproc:name({irc_user, Net, Nick}).
gproc_name(Net, Nick) when is_list(Net), is_list(Nick) ->
gproc:name({irc_user, Net, Nick}).
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/archaelus/erlirc/b922b2004f0f9f58a6ccf8fe71313190dee081c6/src/irc_user.erl | erlang | -------------------------------------------------------------------
@version {@vsn}, {@date} {@time}
@doc
@end
-------------------------------------------------------------------
API
====================================================================
API
====================================================================
--------------------------------------------------------------------
@doc
@end
====================================================================
==================================================================== | Geoff Ca nt
@author nt < >
-module(irc_user).
-include_lib("irc.hrl").
-export([gproc_name/1,
gproc_name/2]).
( ) - >
gproc_name(#user{net=Net,nick=Nick}) when is_list(Net), is_list(Nick) ->
gproc:name({irc_user, Net, Nick}).
gproc_name(Net, Nick) when is_list(Net), is_list(Nick) ->
gproc:name({irc_user, Net, Nick}).
Internal functions
|
4fb9444e2d73e8ed4bfd760c14456284b59bffe8d168d523816803c1f8c5e3ed | mmottl/aifad | c45_io.ml |
AIFAD - Automated Induction of Functions over
Author :
email :
WWW :
Copyright ( C ) 2002 Austrian Research Institute for Artificial Intelligence
Copyright ( C ) 2003-
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 .
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. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
AIFAD - Automated Induction of Functions over Algebraic Datatypes
Author: Markus Mottl
email:
WWW:
Copyright (C) 2002 Austrian Research Institute for Artificial Intelligence
Copyright (C) 2003- Markus Mottl
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
open Printf
open Pcre
open Utils
open Algdt_types
open Algdt_utils
open Model_data
open Data_io
module StrSet = Set.Make (struct type t = string let compare = compare end)
let hash_size = 541
let flags = [`DOTALL] (* makes matching faster *)
let comma_rex = regexp ~flags "\\s*(?:,|\\.)\\s*"
let def_rex = regexp ~flags "^(\\w+):\\s*(\\w+(?:\\s*,\\s*\\w+)*)\\s*\\.\\s*$"
let read_c45_spec names =
let failwith msg = failwith (sprintf "read_c45_spec:%s: %s" names msg) in
let var_set = ref StrSet.empty in
let var_lst = ref [] in
let n_lines_ref = ref 1 in
let rev_pat_lst = ref [] in
let target_attr_lst =
do_open_in names (fun names_ic ->
let target_line = input_line names_ic in
foreach_line ~ic:names_ic
(fun line ->
incr n_lines_ref;
match extract ~full_match:false ~rex:def_rex line with
| [| name; "continuous" |] ->
eprintf
"read_c45_spec: \
ignoring variable %s in line (data column): %s:%d\n"
name
names
!n_lines_ref;
flush stderr;
rev_pat_lst := "[^,]+" :: !rev_pat_lst
| [| name; rhs |] ->
if StrSet.mem name !var_set then
failwith ("variable appears twice: " ^ name);
var_set := StrSet.add name !var_set;
let attrs = split ~rex:comma_rex rhs in
var_lst := (name, Array.of_list attrs) :: !var_lst;
let pat = ["("; String.concat "|" attrs; "|\\?)"] in
rev_pat_lst := String.concat "" pat :: !rev_pat_lst
| _ -> assert false (* impossible *));
let lix = String.length target_line - 1 in
let target_line = String.sub target_line 0 lix in
let target_attr_lst = split ~rex:comma_rex target_line in
if target_attr_lst = [] then failwith "no target attributes"
else target_attr_lst) in
let input_pat = String.concat "," (List.rev !rev_pat_lst) in
let target_attrs = Array.of_list target_attr_lst in
let target_pat_lst = ["("; String.concat "|" target_attr_lst; "|\\?)"] in
let target_pat = String.concat "" target_pat_lst in
let data_pat =
if input_pat = "" then target_pat
else String.concat "," [ input_pat; target_pat ] in
let tp_names = Array.of_list (List.rev !var_lst) in
tp_names, target_attrs, data_pat, input_pat
let make_start_prod_el n = TpVal (n + 1)
let target_attr_name = "__target"
let missing = "Missing__"
let value = "Value__"
let __maybe_sample = "__maybe_sample"
let __sample = "__sample"
let maybe_ = "maybe_"
let calc_dispec_info mv (tp_names, _, _, _) =
let n_vars = Array.length tp_names in
match mv with
| Ignore ->
let n_vars1 = n_vars + 1 in
let dtp_tbl = Array.make n_vars1 "" in
let dcnstr_tbl = Array.make n_vars1 [||] in
let dtp_htbl = Hashtbl.create hash_size in
let dcnstr_htbl = Hashtbl.create hash_size in
let dtp = ProdEls (Array.init n_vars make_start_prod_el) in
let dispec = Array.make n_vars1 (Prod dtp) in
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
dtp_tbl.(tp) <- tp_name;
dcnstr_tbl.(tp) <- attrs;
Hashtbl.add dtp_htbl tp_name tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) cnstr in
Array.iteri acti_cnstrs attrs;
dispec.(tp) <- Sums (Array.make (Array.length attrs) IAtom) in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
| MProb ->
let n_vars1 = n_vars + 1 in
let n_vars2 = n_vars1 + 1 in
let dtp_tbl = Array.make n_vars2 "" in
dtp_tbl.(n_vars1) <- __maybe_sample;
let dcnstr_tbl = Array.make n_vars2 [||] in
dcnstr_tbl.(n_vars1) <- [| missing; value; |];
let dtp_htbl = Hashtbl.create hash_size in
Hashtbl.add dtp_htbl __maybe_sample n_vars1;
let dcnstr_htbl = Hashtbl.create hash_size in
Hashtbl.add dcnstr_htbl (n_vars1, missing) 0;
Hashtbl.add dcnstr_htbl (n_vars1, value) 1;
let dispec = Array.make n_vars2 (Prod (TpVal n_vars1)) in
let attr_prod = Array.init n_vars make_start_prod_el in
dispec.(n_vars1) <- Sums [| IAtom; IStrct (ProdEls attr_prod); |];
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
dtp_tbl.(tp) <- tp_name;
dcnstr_tbl.(tp) <- attrs;
Hashtbl.add dtp_htbl tp_name tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) cnstr in
Array.iteri acti_cnstrs attrs;
dispec.(tp) <- Sums (Array.make (Array.length attrs) IAtom) in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
| Flat ->
let n_vars1 = n_vars + 1 in
let dtp_tbl = Array.make n_vars1 "" in
dtp_tbl.(n_vars) <- __sample;
let dcnstr_tbl = Array.make n_vars1 [||] in
let dtp_htbl = Hashtbl.create hash_size in
Hashtbl.add dtp_htbl __sample n_vars;
let dcnstr_htbl = Hashtbl.create hash_size in
let dtp = ProdEls (Array.init n_vars make_start_prod_el) in
let dispec = Array.make n_vars1 (Prod dtp) in
let attr_prod = Array.init n_vars make_start_prod_el in
dispec.(n_vars) <- Prod (ProdEls attr_prod);
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
dtp_tbl.(tp) <- tp_name;
dcnstr_tbl.(tp) <- Array.append [| missing |] attrs;
Hashtbl.add dtp_htbl tp_name tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) (cnstr + 1) in
Array.iteri acti_cnstrs attrs;
Hashtbl.add dcnstr_htbl (tp, missing) 0;
dispec.(tp) <- Sums (Array.make (Array.length attrs + 1) IAtom) in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
| LiftAll ->
let n_vars2 = n_vars * 2 in
let n_vars21 = n_vars2 + 1 in
let n_vars1 = n_vars + 1 in
let dtp_tbl = Array.make n_vars21 "" in
let dcnstr_tbl = Array.make n_vars21 [| missing; value; |] in
dcnstr_tbl.(0) <- [||];
let dtp_htbl = Hashtbl.create hash_size in
let dcnstr_htbl = Hashtbl.create hash_size in
for tp = n_vars1 to n_vars2 do
Hashtbl.add dcnstr_htbl (tp, missing) 0;
Hashtbl.add dcnstr_htbl (tp, value) 1;
done;
let dtp = ProdEls (Array.init n_vars (fun n -> TpVal (n + n_vars1))) in
let dispec = Array.make n_vars21 (Prod dtp) in
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
let sample_tp = tp + n_vars in
dtp_tbl.(tp) <- tp_name;
let sample_tp_name = maybe_ ^ tp_name in
dtp_tbl.(sample_tp) <- sample_tp_name;
dcnstr_tbl.(tp) <- attrs;
Hashtbl.add dtp_htbl tp_name tp;
Hashtbl.add dtp_htbl sample_tp_name sample_tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) cnstr in
Array.iteri acti_cnstrs attrs;
dispec.(tp) <- Sums (Array.make (Array.length attrs) IAtom);
dispec.(sample_tp) <- Sums [| IAtom; IStrct (TpVal tp); |] in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
let calc_cispec_info (_, target_attrs, _, _) =
let ctp_htbl = Hashtbl.create 1 in
Hashtbl.add ctp_htbl target_attr_name 1;
let ccnstr_htbl = Hashtbl.create 13 in
let acti cnstr attr = Hashtbl.add ccnstr_htbl (1, attr) cnstr in
Array.iteri acti target_attrs;
let cispec =
[| Prod (TpVal 1); Sums (Array.make (Array.length target_attrs) IAtom) |] in
{
tp_tbl = [| ""; target_attr_name |];
cnstr_tbl = [| [||]; target_attrs |];
tp_htbl = ctp_htbl;
cnstr_htbl = ccnstr_htbl;
ispec = cispec;
}
let calc_vars n_samples n_vars dcnstr_tbl target_attrs rows =
let dvars =
Array.init n_vars (fun ix ->
let tp = ix + 1 in
{
tp = tp;
samples = Array.make n_samples dummy_fdsum;
histo = Array.make (Array.length dcnstr_tbl.(tp)) 0;
}) in
let csamples = Array.make n_samples dummy_fdsum in
let chisto = Array.make (Array.length target_attrs) 0 in
let cvars = [| { tp = 1; samples = csamples; histo = chisto; } |] in
let n_samples_1 = n_samples - 1 in
List.iteri
(fun ix (sample, ccnstr) ->
let sample_ix = n_samples_1 - ix in
csamples.(sample_ix) <- FDAtom ccnstr;
chisto.(ccnstr) <- chisto.(ccnstr) + 1;
let acti var_ix { samples = dsamples; histo = dhisto } =
let dcnstr = sample.(var_ix) in
dhisto.(dcnstr) <- dhisto.(dcnstr) + 1;
dsamples.(sample_ix) <- FDAtom dcnstr in
Array.iteri acti dvars)
rows;
dvars, cvars
let read_c45_data (tp_names, target_attrs, pat, _ as c45_spec) mv ic =
let rex = regexp ~flags pat in
let { cnstr_tbl = dcnstr_tbl; cnstr_htbl = dcnstr_htbl } as dispec_info =
calc_dispec_info mv c45_spec in
let { cnstr_htbl = ccnstr_htbl } as cispec_info =
calc_cispec_info c45_spec in
let n_lines_ref = ref 1 in
let n_samples_ref = ref 0 in
let n_vars = Array.length tp_names in
let n_vars_1 = n_vars - 1 in
match mv with
| Ignore ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
let sample = Array.make n_vars 0 in (* MV = 0! *)
for ix = 0 to n_vars_1 do
sample.(ix) <- Hashtbl.find dcnstr_htbl (ix + 1, string_row.(ix))
done;
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
rows_ref := (sample, target_attr) :: !rows_ref;
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf "invalid data line (maybe missing value?): %d\n" !n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let dvars, cvars =
calc_vars !n_samples_ref n_vars dcnstr_tbl target_attrs !rows_ref in
dispec_info, dvars, cispec_info, cvars
| MProb ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
let sample = Array.make n_vars dummy_fdsum in
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
(try
for ix = 0 to n_vars_1 do
let attr = string_row.(ix) in
if attr = "?" then raise Exit
else
sample.(ix) <- FDAtom (Hashtbl.find dcnstr_htbl (ix + 1, attr))
done;
rows_ref := (Some sample, target_attr) :: !rows_ref;
with Exit -> rows_ref := (None, target_attr) :: !rows_ref);
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf
"invalid data line (maybe missing value in target?): %d\n"
!n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let n_samples = !n_samples_ref in
let n_samples_1 = n_samples - 1 in
let { samples = dsamples; histo = dhisto } as dvar =
{
tp = n_vars + 1;
samples = Array.make n_samples dummy_fdsum; (* dummy_fdsum = MV! *)
histo = [| 0; 0; |]
} in
let dvars = [| dvar |] in
let csamples = Array.make n_samples dummy_fdsum in
let chisto = Array.make (Array.length target_attrs) 0 in
let cvars = [| { tp = 1; samples = csamples; histo = chisto; } |] in
List.iteri
(fun ix (maybe_sample, ccnstr) ->
let sample_ix = n_samples_1 - ix in
csamples.(sample_ix) <- FDAtom ccnstr;
chisto.(ccnstr) <- chisto.(ccnstr) + 1;
match maybe_sample with
| None -> dhisto.(0) <- dhisto.(0) + 1
| Some sample ->
dhisto.(1) <- dhisto.(1) + 1;
dsamples.(sample_ix) <- FDStrct (1, sample))
!rows_ref;
dispec_info, dvars, cispec_info, cvars
| Flat ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
let sample = Array.make n_vars 0 in (* MV = 0! *)
for ix = 0 to n_vars_1 do
let attr = string_row.(ix) in
if attr <> "?" then
sample.(ix) <- Hashtbl.find dcnstr_htbl (ix + 1, attr)
done;
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
rows_ref := (sample, target_attr) :: !rows_ref;
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf
"invalid data line (maybe missing value in target?): %d\n"
!n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let dvars, cvars =
calc_vars !n_samples_ref n_vars dcnstr_tbl target_attrs !rows_ref in
dispec_info, dvars, cispec_info, cvars
| LiftAll ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
let sample =
Array.make n_vars dummy_fdsum in (* dummy_fdsum = MV! *)
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
for ix = 0 to n_vars_1 do
let attr = string_row.(ix) in
if attr <> "?" then
let data = FDAtom (Hashtbl.find dcnstr_htbl (ix + 1, attr)) in
sample.(ix) <- FDStrct (1, [| data |])
done;
rows_ref := (sample, target_attr) :: !rows_ref;
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf
"invalid data line (maybe missing value in target?): %d\n"
!n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let n_samples = !n_samples_ref in
let n_samples_1 = n_samples - 1 in
let dvars =
let n_vars1 = n_vars + 1 in
Array.init n_vars (fun ix ->
{
tp = ix + n_vars1;
samples = Array.make n_samples dummy_fdsum;
histo = [| 0; 0 |];
}) in
let csamples = Array.make n_samples dummy_fdsum in
let chisto = Array.make (Array.length target_attrs) 0 in
let cvars = [| { tp = 1; samples = csamples; histo = chisto; } |] in
List.iteri
(fun ix (sample, ccnstr) ->
let sample_ix = n_samples_1 - ix in
csamples.(sample_ix) <- FDAtom ccnstr;
chisto.(ccnstr) <- chisto.(ccnstr) + 1;
let acti var_ix { samples = dsamples; histo = dhisto } =
let fdsum = sample.(var_ix) in
let dcnstr = fdsum_cnstr fdsum in
dhisto.(dcnstr) <- dhisto.(dcnstr) + 1;
dsamples.(sample_ix) <- fdsum in
Array.iteri acti dvars)
!rows_ref;
dispec_info, dvars, cispec_info, cvars
(* Read C4.5-rhs-data *)
let target_rex = regexp ~flags:[`DOTALL] "(?:^|.*,)(\\w+)\\s*$"
let read_rhs ic cnstr_htbl =
try
let strs = extract ~full_match:false ~rex:target_rex (input_line ic) in
Some [| FDAtom (Hashtbl.find cnstr_htbl (1, strs.(0))) |]
with End_of_file -> None
| null | https://raw.githubusercontent.com/mmottl/aifad/b06786f5cd60992548405078a903ee3d962ea969/src/c45_io.ml | ocaml | makes matching faster
impossible
MV = 0!
dummy_fdsum = MV!
MV = 0!
dummy_fdsum = MV!
Read C4.5-rhs-data |
AIFAD - Automated Induction of Functions over
Author :
email :
WWW :
Copyright ( C ) 2002 Austrian Research Institute for Artificial Intelligence
Copyright ( C ) 2003-
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 .
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. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA
AIFAD - Automated Induction of Functions over Algebraic Datatypes
Author: Markus Mottl
email:
WWW:
Copyright (C) 2002 Austrian Research Institute for Artificial Intelligence
Copyright (C) 2003- Markus Mottl
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
open Printf
open Pcre
open Utils
open Algdt_types
open Algdt_utils
open Model_data
open Data_io
module StrSet = Set.Make (struct type t = string let compare = compare end)
let hash_size = 541
let comma_rex = regexp ~flags "\\s*(?:,|\\.)\\s*"
let def_rex = regexp ~flags "^(\\w+):\\s*(\\w+(?:\\s*,\\s*\\w+)*)\\s*\\.\\s*$"
let read_c45_spec names =
let failwith msg = failwith (sprintf "read_c45_spec:%s: %s" names msg) in
let var_set = ref StrSet.empty in
let var_lst = ref [] in
let n_lines_ref = ref 1 in
let rev_pat_lst = ref [] in
let target_attr_lst =
do_open_in names (fun names_ic ->
let target_line = input_line names_ic in
foreach_line ~ic:names_ic
(fun line ->
incr n_lines_ref;
match extract ~full_match:false ~rex:def_rex line with
| [| name; "continuous" |] ->
eprintf
"read_c45_spec: \
ignoring variable %s in line (data column): %s:%d\n"
name
names
!n_lines_ref;
flush stderr;
rev_pat_lst := "[^,]+" :: !rev_pat_lst
| [| name; rhs |] ->
if StrSet.mem name !var_set then
failwith ("variable appears twice: " ^ name);
var_set := StrSet.add name !var_set;
let attrs = split ~rex:comma_rex rhs in
var_lst := (name, Array.of_list attrs) :: !var_lst;
let pat = ["("; String.concat "|" attrs; "|\\?)"] in
rev_pat_lst := String.concat "" pat :: !rev_pat_lst
let lix = String.length target_line - 1 in
let target_line = String.sub target_line 0 lix in
let target_attr_lst = split ~rex:comma_rex target_line in
if target_attr_lst = [] then failwith "no target attributes"
else target_attr_lst) in
let input_pat = String.concat "," (List.rev !rev_pat_lst) in
let target_attrs = Array.of_list target_attr_lst in
let target_pat_lst = ["("; String.concat "|" target_attr_lst; "|\\?)"] in
let target_pat = String.concat "" target_pat_lst in
let data_pat =
if input_pat = "" then target_pat
else String.concat "," [ input_pat; target_pat ] in
let tp_names = Array.of_list (List.rev !var_lst) in
tp_names, target_attrs, data_pat, input_pat
let make_start_prod_el n = TpVal (n + 1)
let target_attr_name = "__target"
let missing = "Missing__"
let value = "Value__"
let __maybe_sample = "__maybe_sample"
let __sample = "__sample"
let maybe_ = "maybe_"
let calc_dispec_info mv (tp_names, _, _, _) =
let n_vars = Array.length tp_names in
match mv with
| Ignore ->
let n_vars1 = n_vars + 1 in
let dtp_tbl = Array.make n_vars1 "" in
let dcnstr_tbl = Array.make n_vars1 [||] in
let dtp_htbl = Hashtbl.create hash_size in
let dcnstr_htbl = Hashtbl.create hash_size in
let dtp = ProdEls (Array.init n_vars make_start_prod_el) in
let dispec = Array.make n_vars1 (Prod dtp) in
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
dtp_tbl.(tp) <- tp_name;
dcnstr_tbl.(tp) <- attrs;
Hashtbl.add dtp_htbl tp_name tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) cnstr in
Array.iteri acti_cnstrs attrs;
dispec.(tp) <- Sums (Array.make (Array.length attrs) IAtom) in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
| MProb ->
let n_vars1 = n_vars + 1 in
let n_vars2 = n_vars1 + 1 in
let dtp_tbl = Array.make n_vars2 "" in
dtp_tbl.(n_vars1) <- __maybe_sample;
let dcnstr_tbl = Array.make n_vars2 [||] in
dcnstr_tbl.(n_vars1) <- [| missing; value; |];
let dtp_htbl = Hashtbl.create hash_size in
Hashtbl.add dtp_htbl __maybe_sample n_vars1;
let dcnstr_htbl = Hashtbl.create hash_size in
Hashtbl.add dcnstr_htbl (n_vars1, missing) 0;
Hashtbl.add dcnstr_htbl (n_vars1, value) 1;
let dispec = Array.make n_vars2 (Prod (TpVal n_vars1)) in
let attr_prod = Array.init n_vars make_start_prod_el in
dispec.(n_vars1) <- Sums [| IAtom; IStrct (ProdEls attr_prod); |];
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
dtp_tbl.(tp) <- tp_name;
dcnstr_tbl.(tp) <- attrs;
Hashtbl.add dtp_htbl tp_name tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) cnstr in
Array.iteri acti_cnstrs attrs;
dispec.(tp) <- Sums (Array.make (Array.length attrs) IAtom) in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
| Flat ->
let n_vars1 = n_vars + 1 in
let dtp_tbl = Array.make n_vars1 "" in
dtp_tbl.(n_vars) <- __sample;
let dcnstr_tbl = Array.make n_vars1 [||] in
let dtp_htbl = Hashtbl.create hash_size in
Hashtbl.add dtp_htbl __sample n_vars;
let dcnstr_htbl = Hashtbl.create hash_size in
let dtp = ProdEls (Array.init n_vars make_start_prod_el) in
let dispec = Array.make n_vars1 (Prod dtp) in
let attr_prod = Array.init n_vars make_start_prod_el in
dispec.(n_vars) <- Prod (ProdEls attr_prod);
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
dtp_tbl.(tp) <- tp_name;
dcnstr_tbl.(tp) <- Array.append [| missing |] attrs;
Hashtbl.add dtp_htbl tp_name tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) (cnstr + 1) in
Array.iteri acti_cnstrs attrs;
Hashtbl.add dcnstr_htbl (tp, missing) 0;
dispec.(tp) <- Sums (Array.make (Array.length attrs + 1) IAtom) in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
| LiftAll ->
let n_vars2 = n_vars * 2 in
let n_vars21 = n_vars2 + 1 in
let n_vars1 = n_vars + 1 in
let dtp_tbl = Array.make n_vars21 "" in
let dcnstr_tbl = Array.make n_vars21 [| missing; value; |] in
dcnstr_tbl.(0) <- [||];
let dtp_htbl = Hashtbl.create hash_size in
let dcnstr_htbl = Hashtbl.create hash_size in
for tp = n_vars1 to n_vars2 do
Hashtbl.add dcnstr_htbl (tp, missing) 0;
Hashtbl.add dcnstr_htbl (tp, value) 1;
done;
let dtp = ProdEls (Array.init n_vars (fun n -> TpVal (n + n_vars1))) in
let dispec = Array.make n_vars21 (Prod dtp) in
let acti_defs ix (tp_name, attrs) =
let tp = ix + 1 in
let sample_tp = tp + n_vars in
dtp_tbl.(tp) <- tp_name;
let sample_tp_name = maybe_ ^ tp_name in
dtp_tbl.(sample_tp) <- sample_tp_name;
dcnstr_tbl.(tp) <- attrs;
Hashtbl.add dtp_htbl tp_name tp;
Hashtbl.add dtp_htbl sample_tp_name sample_tp;
let acti_cnstrs cnstr cnstr_name =
Hashtbl.add dcnstr_htbl (tp, cnstr_name) cnstr in
Array.iteri acti_cnstrs attrs;
dispec.(tp) <- Sums (Array.make (Array.length attrs) IAtom);
dispec.(sample_tp) <- Sums [| IAtom; IStrct (TpVal tp); |] in
Array.iteri acti_defs tp_names;
{
tp_tbl = dtp_tbl;
cnstr_tbl = dcnstr_tbl;
tp_htbl = dtp_htbl;
cnstr_htbl = dcnstr_htbl;
ispec = dispec;
}
let calc_cispec_info (_, target_attrs, _, _) =
let ctp_htbl = Hashtbl.create 1 in
Hashtbl.add ctp_htbl target_attr_name 1;
let ccnstr_htbl = Hashtbl.create 13 in
let acti cnstr attr = Hashtbl.add ccnstr_htbl (1, attr) cnstr in
Array.iteri acti target_attrs;
let cispec =
[| Prod (TpVal 1); Sums (Array.make (Array.length target_attrs) IAtom) |] in
{
tp_tbl = [| ""; target_attr_name |];
cnstr_tbl = [| [||]; target_attrs |];
tp_htbl = ctp_htbl;
cnstr_htbl = ccnstr_htbl;
ispec = cispec;
}
let calc_vars n_samples n_vars dcnstr_tbl target_attrs rows =
let dvars =
Array.init n_vars (fun ix ->
let tp = ix + 1 in
{
tp = tp;
samples = Array.make n_samples dummy_fdsum;
histo = Array.make (Array.length dcnstr_tbl.(tp)) 0;
}) in
let csamples = Array.make n_samples dummy_fdsum in
let chisto = Array.make (Array.length target_attrs) 0 in
let cvars = [| { tp = 1; samples = csamples; histo = chisto; } |] in
let n_samples_1 = n_samples - 1 in
List.iteri
(fun ix (sample, ccnstr) ->
let sample_ix = n_samples_1 - ix in
csamples.(sample_ix) <- FDAtom ccnstr;
chisto.(ccnstr) <- chisto.(ccnstr) + 1;
let acti var_ix { samples = dsamples; histo = dhisto } =
let dcnstr = sample.(var_ix) in
dhisto.(dcnstr) <- dhisto.(dcnstr) + 1;
dsamples.(sample_ix) <- FDAtom dcnstr in
Array.iteri acti dvars)
rows;
dvars, cvars
let read_c45_data (tp_names, target_attrs, pat, _ as c45_spec) mv ic =
let rex = regexp ~flags pat in
let { cnstr_tbl = dcnstr_tbl; cnstr_htbl = dcnstr_htbl } as dispec_info =
calc_dispec_info mv c45_spec in
let { cnstr_htbl = ccnstr_htbl } as cispec_info =
calc_cispec_info c45_spec in
let n_lines_ref = ref 1 in
let n_samples_ref = ref 0 in
let n_vars = Array.length tp_names in
let n_vars_1 = n_vars - 1 in
match mv with
| Ignore ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
for ix = 0 to n_vars_1 do
sample.(ix) <- Hashtbl.find dcnstr_htbl (ix + 1, string_row.(ix))
done;
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
rows_ref := (sample, target_attr) :: !rows_ref;
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf "invalid data line (maybe missing value?): %d\n" !n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let dvars, cvars =
calc_vars !n_samples_ref n_vars dcnstr_tbl target_attrs !rows_ref in
dispec_info, dvars, cispec_info, cvars
| MProb ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
let sample = Array.make n_vars dummy_fdsum in
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
(try
for ix = 0 to n_vars_1 do
let attr = string_row.(ix) in
if attr = "?" then raise Exit
else
sample.(ix) <- FDAtom (Hashtbl.find dcnstr_htbl (ix + 1, attr))
done;
rows_ref := (Some sample, target_attr) :: !rows_ref;
with Exit -> rows_ref := (None, target_attr) :: !rows_ref);
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf
"invalid data line (maybe missing value in target?): %d\n"
!n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let n_samples = !n_samples_ref in
let n_samples_1 = n_samples - 1 in
let { samples = dsamples; histo = dhisto } as dvar =
{
tp = n_vars + 1;
histo = [| 0; 0; |]
} in
let dvars = [| dvar |] in
let csamples = Array.make n_samples dummy_fdsum in
let chisto = Array.make (Array.length target_attrs) 0 in
let cvars = [| { tp = 1; samples = csamples; histo = chisto; } |] in
List.iteri
(fun ix (maybe_sample, ccnstr) ->
let sample_ix = n_samples_1 - ix in
csamples.(sample_ix) <- FDAtom ccnstr;
chisto.(ccnstr) <- chisto.(ccnstr) + 1;
match maybe_sample with
| None -> dhisto.(0) <- dhisto.(0) + 1
| Some sample ->
dhisto.(1) <- dhisto.(1) + 1;
dsamples.(sample_ix) <- FDStrct (1, sample))
!rows_ref;
dispec_info, dvars, cispec_info, cvars
| Flat ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
for ix = 0 to n_vars_1 do
let attr = string_row.(ix) in
if attr <> "?" then
sample.(ix) <- Hashtbl.find dcnstr_htbl (ix + 1, attr)
done;
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
rows_ref := (sample, target_attr) :: !rows_ref;
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf
"invalid data line (maybe missing value in target?): %d\n"
!n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let dvars, cvars =
calc_vars !n_samples_ref n_vars dcnstr_tbl target_attrs !rows_ref in
dispec_info, dvars, cispec_info, cvars
| LiftAll ->
let rows_ref = ref [] in
foreach_line ~ic (fun line ->
try
let string_row = extract ~full_match:false ~rex line in
let sample =
let target_attr = Hashtbl.find ccnstr_htbl (1, string_row.(n_vars)) in
for ix = 0 to n_vars_1 do
let attr = string_row.(ix) in
if attr <> "?" then
let data = FDAtom (Hashtbl.find dcnstr_htbl (ix + 1, attr)) in
sample.(ix) <- FDStrct (1, [| data |])
done;
rows_ref := (sample, target_attr) :: !rows_ref;
incr n_lines_ref;
incr n_samples_ref;
with Not_found ->
eprintf
"invalid data line (maybe missing value in target?): %d\n"
!n_lines_ref;
incr n_lines_ref);
close_in ic;
flush stderr;
let n_samples = !n_samples_ref in
let n_samples_1 = n_samples - 1 in
let dvars =
let n_vars1 = n_vars + 1 in
Array.init n_vars (fun ix ->
{
tp = ix + n_vars1;
samples = Array.make n_samples dummy_fdsum;
histo = [| 0; 0 |];
}) in
let csamples = Array.make n_samples dummy_fdsum in
let chisto = Array.make (Array.length target_attrs) 0 in
let cvars = [| { tp = 1; samples = csamples; histo = chisto; } |] in
List.iteri
(fun ix (sample, ccnstr) ->
let sample_ix = n_samples_1 - ix in
csamples.(sample_ix) <- FDAtom ccnstr;
chisto.(ccnstr) <- chisto.(ccnstr) + 1;
let acti var_ix { samples = dsamples; histo = dhisto } =
let fdsum = sample.(var_ix) in
let dcnstr = fdsum_cnstr fdsum in
dhisto.(dcnstr) <- dhisto.(dcnstr) + 1;
dsamples.(sample_ix) <- fdsum in
Array.iteri acti dvars)
!rows_ref;
dispec_info, dvars, cispec_info, cvars
let target_rex = regexp ~flags:[`DOTALL] "(?:^|.*,)(\\w+)\\s*$"
let read_rhs ic cnstr_htbl =
try
let strs = extract ~full_match:false ~rex:target_rex (input_line ic) in
Some [| FDAtom (Hashtbl.find cnstr_htbl (1, strs.(0))) |]
with End_of_file -> None
|
26d14a7a9c656aee24006c58ee98d0f1cc1dc6449f6ef32452b3665a63ce5846 | ocaml-ppx/ocamlformat | type_and_constraint.ml | type 'a t = 'a list constraint 'a = [< `X]
| null | https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/3d1c992240f7d30bcb8151285274f44619dae197/test/passing/tests/type_and_constraint.ml | ocaml | type 'a t = 'a list constraint 'a = [< `X]
| |
c06dc64fdcc6b4ae529c45c99df14986e702595ec4cc7601770acdb3fbf62bc9 | Clojure2D/clojure2d-examples | material.clj | (ns rt4.the-next-week.ch04c.material
(:require [rt4.common :as common]
[rt4.the-next-week.ch04c.ray :as ray]
[rt4.the-next-week.ch04c.texture :as texture]
[fastmath.vector :as v]
[fastmath.core :as m]
[fastmath.random :as r])
(:import [fastmath.vector Vec3]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol MaterialProto
(scatter [material ray-in rec]))
(defrecord MaterialData [attenuation scattered])
(defrecord Lambertian [albedo]
MaterialProto
(scatter [_ ray-in rec]
(let [scatter-direction (v/add (:normal rec) (common/random-unit-vector))
attenuation (texture/value albedo (:u rec) (:v rec) (:p rec))]
(if (v/is-near-zero? scatter-direction)
(->MaterialData attenuation (ray/ray (:p rec) (:normal rec) (:time ray-in)))
(->MaterialData attenuation (ray/ray (:p rec) scatter-direction (:time ray-in)))))))
(defn lambertian [albedo]
(if (instance? Vec3 albedo)
(->Lambertian (texture/solid-color albedo))
(->Lambertian albedo)))
(defrecord Metal [albedo ^double fuzz]
MaterialProto
(scatter [_ ray-in rec]
(let [reflected (v/add (common/reflect (v/normalize (:direction ray-in)) (:normal rec))
(v/mult (common/random-in-unit-sphere) fuzz))]
(when (pos? (v/dot reflected (:normal rec)))
(->MaterialData albedo (ray/ray (:p rec) reflected (:time ray-in)))))))
(defn metal [albedo ^double fuzz]
(->Metal albedo (min fuzz 1.0)))
(def one (v/vec3 1.0 1.0 1.0))
(defn- reflectance
^double [^double cosine ^double ref-idx]
(let [r0 (m/sq (/ (- 1.0 ref-idx) (inc ref-idx)))]
(+ r0 (* (- 1.0 r0) (m/pow (- 1.0 cosine) 5.0)))))
(defrecord Dielectric [^double ir]
MaterialProto
(scatter [_ ray-in rec]
(let [refraction-ratio (if (:front-face? rec) (/ ir) ir)
unit-direction (v/normalize (:direction ray-in))
cos-theta (min (v/dot (v/sub unit-direction) (:normal rec)) 1.0)
sin-theta (m/sqrt (- 1.0 (* cos-theta cos-theta)))
cannot-refract? (pos? (dec (* refraction-ratio sin-theta)))
direction (if (or cannot-refract?
(> (reflectance cos-theta refraction-ratio) (r/drand)))
(common/reflect unit-direction (:normal rec))
(common/refract unit-direction (:normal rec) refraction-ratio))]
(->MaterialData one (ray/ray (:p rec) direction (:time ray-in))))))
(defn dielectric [ir]
(->Dielectric ir))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch04c/material.clj | clojure | (ns rt4.the-next-week.ch04c.material
(:require [rt4.common :as common]
[rt4.the-next-week.ch04c.ray :as ray]
[rt4.the-next-week.ch04c.texture :as texture]
[fastmath.vector :as v]
[fastmath.core :as m]
[fastmath.random :as r])
(:import [fastmath.vector Vec3]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol MaterialProto
(scatter [material ray-in rec]))
(defrecord MaterialData [attenuation scattered])
(defrecord Lambertian [albedo]
MaterialProto
(scatter [_ ray-in rec]
(let [scatter-direction (v/add (:normal rec) (common/random-unit-vector))
attenuation (texture/value albedo (:u rec) (:v rec) (:p rec))]
(if (v/is-near-zero? scatter-direction)
(->MaterialData attenuation (ray/ray (:p rec) (:normal rec) (:time ray-in)))
(->MaterialData attenuation (ray/ray (:p rec) scatter-direction (:time ray-in)))))))
(defn lambertian [albedo]
(if (instance? Vec3 albedo)
(->Lambertian (texture/solid-color albedo))
(->Lambertian albedo)))
(defrecord Metal [albedo ^double fuzz]
MaterialProto
(scatter [_ ray-in rec]
(let [reflected (v/add (common/reflect (v/normalize (:direction ray-in)) (:normal rec))
(v/mult (common/random-in-unit-sphere) fuzz))]
(when (pos? (v/dot reflected (:normal rec)))
(->MaterialData albedo (ray/ray (:p rec) reflected (:time ray-in)))))))
(defn metal [albedo ^double fuzz]
(->Metal albedo (min fuzz 1.0)))
(def one (v/vec3 1.0 1.0 1.0))
(defn- reflectance
^double [^double cosine ^double ref-idx]
(let [r0 (m/sq (/ (- 1.0 ref-idx) (inc ref-idx)))]
(+ r0 (* (- 1.0 r0) (m/pow (- 1.0 cosine) 5.0)))))
(defrecord Dielectric [^double ir]
MaterialProto
(scatter [_ ray-in rec]
(let [refraction-ratio (if (:front-face? rec) (/ ir) ir)
unit-direction (v/normalize (:direction ray-in))
cos-theta (min (v/dot (v/sub unit-direction) (:normal rec)) 1.0)
sin-theta (m/sqrt (- 1.0 (* cos-theta cos-theta)))
cannot-refract? (pos? (dec (* refraction-ratio sin-theta)))
direction (if (or cannot-refract?
(> (reflectance cos-theta refraction-ratio) (r/drand)))
(common/reflect unit-direction (:normal rec))
(common/refract unit-direction (:normal rec) refraction-ratio))]
(->MaterialData one (ray/ray (:p rec) direction (:time ray-in))))))
(defn dielectric [ir]
(->Dielectric ir))
| |
23bfe71a892c8c67ea102c719dd4af725e21710e3007b3c9a6e70123e75337fa | asakeron/cljs-webgl | string_name.cljs | (ns cljs-webgl.constants.string-name)
(def vendor 0x1F00)
(def renderer 0x1F01)
(def version 0x1F02)
| null | https://raw.githubusercontent.com/asakeron/cljs-webgl/f4554fbee6fbc6133a4eb0416548dabd284e735c/src/cljs/cljs_webgl/constants/string_name.cljs | clojure | (ns cljs-webgl.constants.string-name)
(def vendor 0x1F00)
(def renderer 0x1F01)
(def version 0x1F02)
| |
fd2ae751e2c2a93fb699de3622ad3ff5e7b48205b1daf5a6a072f3ff724ec8bb | notogawa/yesod-websocket-sample | Model.hs | module Model where
import Prelude
import Yesod
import Data.Text (Text)
import Database.Persist.Quasi
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- /
share [mkPersist sqlSettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
| null | https://raw.githubusercontent.com/notogawa/yesod-websocket-sample/aa3eb38339830753a26ec68e130053ea01a80ff2/Model.hs | haskell | You can define all of your database entities in the entities file.
You can find more information on persistent and how to declare entities
at:
/ | module Model where
import Prelude
import Yesod
import Data.Text (Text)
import Database.Persist.Quasi
share [mkPersist sqlSettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
|
c3429e1a1e5a899f247e266261405b196bb390167499c0cd2666f9def8adfe01 | kupl/VeriSmart-public | synthesizer.ml | open Lang
open Vlang
open MakeCfg
open Component
open Path
open InvMap
open Vocab
open Options
open VerifyUtils
open Global
let gen_conjunct ~kind : comps -> vformula list
= fun comps ->
let mvars = BatSet.to_list comps.mapvars in
let pairs = BatSet.to_list comps.mapmems in
let reads = ExpSet.to_list comps.reads in
let ivars = BatSet.to_list comps.ivars in
let avars = BatSet.to_list comps.avars in
let a_arrs = BatSet.to_list comps.a_arrs in
let a_maps = BatSet.to_list comps.a_maps in
let bvars = BatSet.to_list comps.bvars in
let ints = BigIntSet.to_list comps.ints in
let ivars_mvars = BatList.cartesian_product ivars mvars in
let ints_mvars = BatList.cartesian_product ints mvars in
let ivars_ivars = BatList.cartesian_product ivars ivars in
let ints_ivars = BatList.cartesian_product ints ivars in
let reads_ivars = BatList.cartesian_product reads ivars in
let l1 =
List.fold_left (fun acc ((x,xt),(m,mt)) ->
if is_uint256 xt then (SigmaEqual ((m,mt), VVar (x,xt)))::acc
else acc
) [] ivars_mvars in
let l2 =
List.fold_left (fun acc (n,(m,t)) ->
(SigmaEqual ((m,t), VInt n))::acc
) [] ints_mvars in
let l3 =
List.fold_left (fun acc (m,t) ->
(NoOverFlow (m,t))::acc
) [] mvars in
let l4 = (* x[y] = z *)
List.fold_left (fun acc (r, (x,xt)) ->
if xt = get_typ_vexp r then (VBinRel (VEq, r, VVar (x,xt)))::acc
else acc
) [] reads_ivars in
let l5 = (* x = y *)
List.fold_left (fun acc ((x,xt),(y,yt)) ->
if xt=yt then (VBinRel (VEq, VVar (x,xt), VVar (y,yt)))::acc
else acc
) [] ivars_ivars in
let l6 = (* x >= y *)
List.fold_left (fun acc ((x,xt),(y,yt)) ->
if xt=yt then (VBinRel (VGeq, VVar (x,xt), VVar (y,yt)))::acc
else acc
) [] ivars_ivars in
let l7 = (* x >= n *)
List.fold_left (fun acc (n, (y,t)) ->
(VBinRel (VGeq, VVar (y,t), VInt n))::acc
) [] ints_ivars in
let l8 = (* n = x *)
List.fold_left (fun acc (n, (y,t)) ->
(VBinRel (VEq, VVar (y,t), VInt n))::acc
) [] ints_ivars in
let l9 = (* n >= x *)
List.fold_left (fun acc (n, (y,t)) ->
(VBinRel (VGeq, VInt n, VVar (y,t)))::acc
) [] ints_ivars in
let l10 = (* @TU[addr] = True *)
List.fold_left (fun acc (x,t) ->
(VBinRel (VEq, Read (VVar trust_map, VVar (x,t)), VCond VTrue))::acc
) [] avars in
let l11 =
List.fold_left (fun acc arr ->
let bv = ("@i", EType (UInt 256)) in
(ForAll ([bv], VBinRel (VEq, Read (VVar trust_map, Read (VVar arr, VVar bv)), VCond VTrue)))::acc
) [] a_arrs in
let l12 =
List.fold_left (fun acc map ->
let bv = ("@i", EType Address) in
let owner_trust = VBinRel (VEq, Read (VVar trust_map, VVar bv), VCond VTrue) in
let parent_trust = VBinRel (VEq, Read (VVar trust_map, Read (VVar map, VVar bv)), VCond VTrue) in
(ForAll ([bv], Imply (VNot (VBinRel (VEq, Read (VVar map, VVar bv), VInt BatBig_int.zero)),
VAnd (owner_trust, parent_trust))))::acc
) [] a_maps in
let l13 =
List.fold_left (fun acc map ->
(UntrustSum (invest_sum, map))::acc
) [] mvars in
let l14 =
List.fold_left (fun acc (s,mem) ->
(UntrustSum2 (invest_sum, s, mem))::acc
) [] pairs in
let l15 =
List.fold_left (fun acc (x,t) ->
(VBinRel (VEq, VVar (x,t), VCond VTrue))::acc
) [] bvars in
let l16 =
List.fold_left (fun acc (x,t) ->
(VBinRel (VEq, VVar (x,t), VCond VFalse))::acc
) [] bvars in
let l17 = if List.length bvars > 0 then [VFalse] else [] in
match kind with
| "tran" -> l1@l2@l3@l4@l5@l6@l7@l8@l9@l10@l11@l12@l13@l14
(* [] *)
| "loop" -> l1@l2@l3@l4@l5@l6@l7@l8@l9@l10@l11@l12@l13@l14@l15@l16
(* [] *)
| "ext" -> l1@l2@l3@l4@l5@l6@l7@l8@l9@l10@l11@l12@l13@l14@l15@l16
| "ext_loop" -> l15@l16@l17
(* l17 *)
| "ext_view_pure_loop" -> l15@l16
| "pre" -> l15@l16
| _ -> assert false
let next ~kind : comps -> InvMap.key -> InvMap.t -> InvMap.t list
= fun comps key invmap ->
let old_f = InvMap.find key invmap in
List.fold_left (fun acc f ->
let new_f = Simplification.simplify (VAnd (old_f,f)) in
(InvMap.add key new_f invmap)::acc
) [] (gen_conjunct ~kind:kind comps)
let next_tran = next ~kind:"tran"
let next_loop = next ~kind:"loop"
let next_ext = next ~kind:"ext"
let next_ext_loop = next ~kind:"ext_loop"
let next_ext_loop2 = next ~kind:"ext_view_pure_loop"
let next_spec : comps -> SpecMap.key -> SpecMap.t -> SpecMap.t list
= fun comps key specmap ->
let (old_pre,old_post) = SpecMap.find key specmap in
List.fold_left (fun acc f ->
let new_pre = Simplification.simplify (VAnd (old_pre,f)) in
let new_post = VFalse in
(SpecMap.add key (new_pre,new_post) specmap)::acc
) [] (gen_conjunct ~kind:"pre" comps)
let collect_comps_g : Global.t -> Path2.t -> comps
= fun global path ->
let fk = Path2.get_fkey path in
let bp = Path2.get_bp path in
let cfg = Lang.get_cfg (FuncMap.find fk global.fmap) in
let comps_bp = collect_bp global bp cfg in
let lst = List.filter (fun ((cname,fname,_),_) ->
BatString.equal cname !Options.main_contract
&& BatString.equal cname fname
) (BatMap.bindings global.fmap) in
let _ = assert (List.length lst = 1) in
let cnstr = snd (List.hd lst) in
let comps_cnstr = collect_f global cnstr in
{mapvars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.mapvars;
mapmems = BatSet.union comps_cnstr.mapmems comps_bp.mapmems;
reads = ExpSet.filter (fun ve ->
let set1 = BatSet.map fst (free_ve ve) in
let set2 = BatSet.map fst (BatSet.of_list global.gvars) in
BatSet.subset set1 set2
) comps_cnstr.reads;
ivars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.ivars;
avars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.avars;
a_arrs = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.a_arrs;
a_maps = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.a_maps;
bvars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.bvars;
ints = BigIntSet.union comps_cnstr.ints comps_bp.ints}
let refine_tran : Global.t -> PathSet2.t -> InvMap.t -> InvMap.t list
= fun global paths invmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let (hd, last) = (BatList.hd nodes, BatList.last nodes) in
let func = FuncMap.find fk global.fmap in
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
match ctx with
| None ->
if (is_public_func func || is_external_func func) && (is_entry hd || is_exit last) then
let cands = next_tran comps_g (Plain trans_node) invmap in
cands @ acc
else acc
| Some ctx -> acc
) paths []
let refine_loop : Global.t -> PathSet2.t -> InvMap.t -> InvMap.t list
= fun global paths invmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let (hd, last) = (BatList.hd nodes, BatList.last nodes) in
let func = FuncMap.find fk global.fmap in
let cfg = get_cfg func in
let comps_l = collect_bp global nodes cfg in
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
let extern_node_exists = List.exists (fun n -> is_external_call_node n cfg) nodes in
match ctx with
| None ->
let cand1 = if is_loophead hd cfg then next_loop comps_l (Plain hd) invmap
else [] in
let cand2 = if is_loophead last cfg && extern_node_exists then next_loop comps_g (Plain last) invmap
else if is_loophead last cfg then next_loop comps_g (Plain last) invmap
else [] in
cand1 @ cand2 @ acc
| Some ctx when ctx = Lang.extern_node ->
let cand1 = if is_loophead hd cfg && is_view_pure_f func then next_ext_loop2 comps_g (Ctx (ctx,hd)) invmap
else if is_loophead hd cfg then next_ext_loop comps_g (Ctx (ctx,hd)) invmap
else [] in
let cand2 = if is_loophead hd cfg && is_view_pure_f func then next_ext_loop2 comps_g (Ctx (ctx,hd)) invmap
else if is_loophead last cfg && extern_node_exists then next_ext_loop comps_l (Ctx (ctx,last)) invmap
else if is_loophead last cfg then next_ext_loop comps_g (Ctx (ctx,last)) invmap
else [] in
cand1 @ cand2 @ acc
| _ -> acc
) paths []
let refine_ext : Global.t -> PathSet2.t -> InvMap.t -> InvMap.t list
= fun global paths invmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let (hd, last) = (BatList.hd nodes, BatList.last nodes) in
let func = FuncMap.find fk global.fmap in
let cfg = get_cfg func in
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
match ctx with
| None ->
let cands1 =
if (is_public_func func || is_external_func func) && is_external_call_node hd cfg then
next_ext comps_g (Plain Lang.extern_node) invmap
else [] in
let cands2 =
if (is_public_func func || is_external_func func) && is_external_call_node last cfg then
next_ext comps_g (Plain Lang.extern_node) invmap
else [] in
cands1 @ cands2 @ acc
| Some ctx when ctx = Lang.extern_node ->
let cands =
if (is_public_func func || is_external_func func) && (is_entry hd || is_exit last) then
next_ext comps_g (Plain ctx) invmap
else [] in
cands @ acc
| _ -> acc
) paths []
(* make formulas to 'true' except for some specialized formulas *)
let rec special_only : vformula -> vformula
= fun vf ->
match vf with
| VAnd (f1,f2) -> VAnd (special_only f1, special_only f2)
| SigmaEqual _ | NoOverFlow _ | UntrustSum _ | UntrustSum2 _
| ForAll _ | VBinRel (VEq,Read (VVar ("@TU",_),_),_) -> vf
| VOr _ | Imply _ -> assert false
| _ -> VTrue
let rec make_locks_to_true : vformula -> vformula
= fun vf ->
match vf with
| VBinRel (VEq,VVar _,VCond VTrue)
| VBinRel (VEq,VVar _,VCond VFalse) -> VTrue
| VAnd (f1,f2) -> VAnd (make_locks_to_true f1, make_locks_to_true f2)
| VOr _ | Imply _ -> assert false
| _ -> vf
let rec make_locals_to_true : Global.t -> vformula -> vformula
= fun global vf ->
match vf with
| VAnd (f1,f2) -> VAnd (make_locals_to_true global f1, make_locals_to_true global f2)
| VOr _ | Imply _ -> assert false
| _ ->
if BatSet.for_all (fun x -> List.mem x global.gvars || List.mem (fst x) global_ghost_var_names) (free_vf vf) then vf
else VTrue
let sync' all_cutpoints ext_lhs all_lhs target_lhs target_ext_lhs : Global.t -> InvMap.t -> InvMap.t
= fun global invmap ->
let invmap = (* loop inv => tran inv (excluding local, locks) *)
BatSet.fold (fun cp acc ->
let loop_inv = InvMap.find cp acc in
let trans_inv = InvMap.find (Plain Lang.trans_node) acc in (* trans_inv may be updated at each iteration *)
InvMap.add (Plain trans_node) (VAnd (make_locals_to_true global (make_locks_to_true loop_inv), trans_inv)) acc
) all_lhs invmap in
tran inv = > loop inv , extern inv , extern loop inv
let trans_inv = InvMap.find (Plain Lang.trans_node) invmap in
BatSet.fold (fun cp acc ->
InvMap.add cp (VAnd (trans_inv, InvMap.find cp invmap)) acc
) all_cutpoints invmap in
extern loop inv = > extern inv
if BatSet.is_empty global.extcalls then invmap
else
BatSet.fold (fun cp acc ->
let ext_loopinv = InvMap.find cp invmap in
let extern_inv = InvMap.find (Plain Lang.extern_node) acc in
InvMap.add (Plain Lang.extern_node) (VAnd (extern_inv, ext_loopinv)) acc
) ext_lhs invmap in
let invmap = (* extern inv => tran inv (excluding locks), extern loop inv *)
if BatSet.is_empty global.extcalls then invmap
else
let extern_inv = InvMap.find (Plain extern_node) invmap in
let invmap = InvMap.add (Plain trans_node)
(VAnd (make_locals_to_true global (special_only extern_inv), InvMap.find (Plain trans_node) invmap))
invmap in
BatSet.fold (fun cp acc ->
InvMap.add cp (VAnd (extern_inv, InvMap.find cp invmap)) acc
) (BatSet.union ext_lhs target_lhs) invmap in
let invmap = (* extern inv with locks => extern loop inv as false *)
if BatSet.is_empty global.extcalls then invmap
else
let extern_inv = InvMap.find (Plain Lang.extern_node) invmap in
BatSet.fold (fun cp acc ->
if contain_lock extern_inv then InvMap.add cp VFalse acc
else acc
) target_ext_lhs invmap in
invmap
let sync : Global.t -> InvMap.t -> InvMap.t list
= fun global invmap ->
let lhs = BatSet.map (fun l -> Plain l) global.lhs_main in
let lhs2 = BatSet.map (fun l -> Plain l) global.lhs2_main in
let lhs3 = BatSet.map (fun l -> Plain l) global.lhs3_main in
let ext_lhs = if BatSet.is_empty global.extcalls then BatSet.empty else BatSet.map (fun l -> Ctx (Lang.extern_node, l)) global.lhs_main in
let ext_lhs2 = if BatSet.is_empty global.extcalls then BatSet.empty else BatSet.map (fun l -> Ctx (Lang.extern_node, l)) global.lhs2_main in
let ext_lhs3 = if BatSet.is_empty global.extcalls then BatSet.empty else BatSet.map (fun l -> Ctx (Lang.extern_node, l)) global.lhs3_main in
let all_cutpoints = if BatSet.is_empty global.extcalls then (assert (BatSet.is_empty ext_lhs); lhs)
else BatSet.add (Plain Lang.extern_node) (BatSet.union ext_lhs lhs) in
let invmap = InvMap.simplify invmap in
let invmap1 = sync' all_cutpoints ext_lhs lhs lhs ext_lhs global invmap in
let invmap2 = sync' all_cutpoints ext_lhs lhs lhs2 ext_lhs2 global invmap in
let invmap3 = sync' all_cutpoints ext_lhs lhs lhs3 ext_lhs3 global invmap in
let invmap1 = InvMap.simplify invmap1 in
let invmap2 = InvMap.simplify invmap2 in
let invmap3 = InvMap.simplify invmap3 in
[invmap1; invmap2; invmap3]
let refine_spec : Global.t -> PathSet2.t -> SpecMap.t -> SpecMap.t list
= fun global paths specmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
let callnodes = BatSet.map fst global.callnodes in
let intersect = BatSet.intersect callnodes (BatSet.of_list nodes) in
BatSet.fold (fun n acc2 ->
(next_spec comps_g n specmap) @ acc2
) intersect acc
) paths []
let next_spec : Global.t -> PathSet2.t -> InvMap.t -> SpecMap.t -> (InvMap.t * SpecMap.t) list
= fun global paths invmap specmap ->
let trans_inv = InvMap.find (Plain Lang.trans_node) invmap in
let specmap1 = BatSet.fold (fun (cn,fk) acc -> SpecMap.add cn (trans_inv, trans_inv) acc) global.callnodes SpecMap.empty in
let specmap2 =
BatSet.fold (fun (cn,fk) acc ->
let f = FuncMap.find fk global.fmap in
if contain_extern global f then
let extern_inv = InvMap.find (Plain Lang.extern_node) invmap in
if not (contain_lock_s extern_inv (get_body f)) then
SpecMap.add cn (extern_inv, extern_inv) acc
else
SpecMap.add cn (trans_inv, trans_inv) acc
else
SpecMap.add cn (trans_inv, trans_inv) acc
) global.callnodes SpecMap.empty in
let specmaps = [specmap1;specmap2] in
List.map (fun specmap -> (invmap,specmap)) specmaps
(* generate refinements from problematic paths *)
let refine : Global.t -> PathSet2.t -> InvMap.t * SpecMap.t -> (InvMap.t * SpecMap.t) list
= fun global paths (invmap,specmap) ->
let lst =
let tran = if !Options.intra then [] else refine_tran global paths invmap in
let loop = refine_loop global paths invmap in
let ext = refine_ext global paths invmap in
tran @ loop @ ext in
let lst = BatList.unique ~eq:InvMap.equal lst in
let lst = BatList.fold_lefti (fun acc i map -> acc @ (sync global map)) [] lst in
let _ = List.iter ( fun i - > print_endline ( InvMap.to_string i ) ) lst in
let _ = assert false in
let _ = assert false in *)
let final = List.fold_left (fun acc map -> acc @ (next_spec global paths map specmap)) [] lst in
final
| null | https://raw.githubusercontent.com/kupl/VeriSmart-public/99be7ba88b61994f1ed4c0d3a8e6a6db0f790431/src/verify/synthesizer.ml | ocaml | x[y] = z
x = y
x >= y
x >= n
n = x
n >= x
@TU[addr] = True
[]
[]
l17
make formulas to 'true' except for some specialized formulas
loop inv => tran inv (excluding local, locks)
trans_inv may be updated at each iteration
extern inv => tran inv (excluding locks), extern loop inv
extern inv with locks => extern loop inv as false
generate refinements from problematic paths | open Lang
open Vlang
open MakeCfg
open Component
open Path
open InvMap
open Vocab
open Options
open VerifyUtils
open Global
let gen_conjunct ~kind : comps -> vformula list
= fun comps ->
let mvars = BatSet.to_list comps.mapvars in
let pairs = BatSet.to_list comps.mapmems in
let reads = ExpSet.to_list comps.reads in
let ivars = BatSet.to_list comps.ivars in
let avars = BatSet.to_list comps.avars in
let a_arrs = BatSet.to_list comps.a_arrs in
let a_maps = BatSet.to_list comps.a_maps in
let bvars = BatSet.to_list comps.bvars in
let ints = BigIntSet.to_list comps.ints in
let ivars_mvars = BatList.cartesian_product ivars mvars in
let ints_mvars = BatList.cartesian_product ints mvars in
let ivars_ivars = BatList.cartesian_product ivars ivars in
let ints_ivars = BatList.cartesian_product ints ivars in
let reads_ivars = BatList.cartesian_product reads ivars in
let l1 =
List.fold_left (fun acc ((x,xt),(m,mt)) ->
if is_uint256 xt then (SigmaEqual ((m,mt), VVar (x,xt)))::acc
else acc
) [] ivars_mvars in
let l2 =
List.fold_left (fun acc (n,(m,t)) ->
(SigmaEqual ((m,t), VInt n))::acc
) [] ints_mvars in
let l3 =
List.fold_left (fun acc (m,t) ->
(NoOverFlow (m,t))::acc
) [] mvars in
List.fold_left (fun acc (r, (x,xt)) ->
if xt = get_typ_vexp r then (VBinRel (VEq, r, VVar (x,xt)))::acc
else acc
) [] reads_ivars in
List.fold_left (fun acc ((x,xt),(y,yt)) ->
if xt=yt then (VBinRel (VEq, VVar (x,xt), VVar (y,yt)))::acc
else acc
) [] ivars_ivars in
List.fold_left (fun acc ((x,xt),(y,yt)) ->
if xt=yt then (VBinRel (VGeq, VVar (x,xt), VVar (y,yt)))::acc
else acc
) [] ivars_ivars in
List.fold_left (fun acc (n, (y,t)) ->
(VBinRel (VGeq, VVar (y,t), VInt n))::acc
) [] ints_ivars in
List.fold_left (fun acc (n, (y,t)) ->
(VBinRel (VEq, VVar (y,t), VInt n))::acc
) [] ints_ivars in
List.fold_left (fun acc (n, (y,t)) ->
(VBinRel (VGeq, VInt n, VVar (y,t)))::acc
) [] ints_ivars in
List.fold_left (fun acc (x,t) ->
(VBinRel (VEq, Read (VVar trust_map, VVar (x,t)), VCond VTrue))::acc
) [] avars in
let l11 =
List.fold_left (fun acc arr ->
let bv = ("@i", EType (UInt 256)) in
(ForAll ([bv], VBinRel (VEq, Read (VVar trust_map, Read (VVar arr, VVar bv)), VCond VTrue)))::acc
) [] a_arrs in
let l12 =
List.fold_left (fun acc map ->
let bv = ("@i", EType Address) in
let owner_trust = VBinRel (VEq, Read (VVar trust_map, VVar bv), VCond VTrue) in
let parent_trust = VBinRel (VEq, Read (VVar trust_map, Read (VVar map, VVar bv)), VCond VTrue) in
(ForAll ([bv], Imply (VNot (VBinRel (VEq, Read (VVar map, VVar bv), VInt BatBig_int.zero)),
VAnd (owner_trust, parent_trust))))::acc
) [] a_maps in
let l13 =
List.fold_left (fun acc map ->
(UntrustSum (invest_sum, map))::acc
) [] mvars in
let l14 =
List.fold_left (fun acc (s,mem) ->
(UntrustSum2 (invest_sum, s, mem))::acc
) [] pairs in
let l15 =
List.fold_left (fun acc (x,t) ->
(VBinRel (VEq, VVar (x,t), VCond VTrue))::acc
) [] bvars in
let l16 =
List.fold_left (fun acc (x,t) ->
(VBinRel (VEq, VVar (x,t), VCond VFalse))::acc
) [] bvars in
let l17 = if List.length bvars > 0 then [VFalse] else [] in
match kind with
| "tran" -> l1@l2@l3@l4@l5@l6@l7@l8@l9@l10@l11@l12@l13@l14
| "loop" -> l1@l2@l3@l4@l5@l6@l7@l8@l9@l10@l11@l12@l13@l14@l15@l16
| "ext" -> l1@l2@l3@l4@l5@l6@l7@l8@l9@l10@l11@l12@l13@l14@l15@l16
| "ext_loop" -> l15@l16@l17
| "ext_view_pure_loop" -> l15@l16
| "pre" -> l15@l16
| _ -> assert false
let next ~kind : comps -> InvMap.key -> InvMap.t -> InvMap.t list
= fun comps key invmap ->
let old_f = InvMap.find key invmap in
List.fold_left (fun acc f ->
let new_f = Simplification.simplify (VAnd (old_f,f)) in
(InvMap.add key new_f invmap)::acc
) [] (gen_conjunct ~kind:kind comps)
let next_tran = next ~kind:"tran"
let next_loop = next ~kind:"loop"
let next_ext = next ~kind:"ext"
let next_ext_loop = next ~kind:"ext_loop"
let next_ext_loop2 = next ~kind:"ext_view_pure_loop"
let next_spec : comps -> SpecMap.key -> SpecMap.t -> SpecMap.t list
= fun comps key specmap ->
let (old_pre,old_post) = SpecMap.find key specmap in
List.fold_left (fun acc f ->
let new_pre = Simplification.simplify (VAnd (old_pre,f)) in
let new_post = VFalse in
(SpecMap.add key (new_pre,new_post) specmap)::acc
) [] (gen_conjunct ~kind:"pre" comps)
let collect_comps_g : Global.t -> Path2.t -> comps
= fun global path ->
let fk = Path2.get_fkey path in
let bp = Path2.get_bp path in
let cfg = Lang.get_cfg (FuncMap.find fk global.fmap) in
let comps_bp = collect_bp global bp cfg in
let lst = List.filter (fun ((cname,fname,_),_) ->
BatString.equal cname !Options.main_contract
&& BatString.equal cname fname
) (BatMap.bindings global.fmap) in
let _ = assert (List.length lst = 1) in
let cnstr = snd (List.hd lst) in
let comps_cnstr = collect_f global cnstr in
{mapvars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.mapvars;
mapmems = BatSet.union comps_cnstr.mapmems comps_bp.mapmems;
reads = ExpSet.filter (fun ve ->
let set1 = BatSet.map fst (free_ve ve) in
let set2 = BatSet.map fst (BatSet.of_list global.gvars) in
BatSet.subset set1 set2
) comps_cnstr.reads;
ivars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.ivars;
avars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.avars;
a_arrs = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.a_arrs;
a_maps = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.a_maps;
bvars = BatSet.filter (fun v -> List.mem v global.gvars) comps_cnstr.bvars;
ints = BigIntSet.union comps_cnstr.ints comps_bp.ints}
let refine_tran : Global.t -> PathSet2.t -> InvMap.t -> InvMap.t list
= fun global paths invmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let (hd, last) = (BatList.hd nodes, BatList.last nodes) in
let func = FuncMap.find fk global.fmap in
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
match ctx with
| None ->
if (is_public_func func || is_external_func func) && (is_entry hd || is_exit last) then
let cands = next_tran comps_g (Plain trans_node) invmap in
cands @ acc
else acc
| Some ctx -> acc
) paths []
let refine_loop : Global.t -> PathSet2.t -> InvMap.t -> InvMap.t list
= fun global paths invmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let (hd, last) = (BatList.hd nodes, BatList.last nodes) in
let func = FuncMap.find fk global.fmap in
let cfg = get_cfg func in
let comps_l = collect_bp global nodes cfg in
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
let extern_node_exists = List.exists (fun n -> is_external_call_node n cfg) nodes in
match ctx with
| None ->
let cand1 = if is_loophead hd cfg then next_loop comps_l (Plain hd) invmap
else [] in
let cand2 = if is_loophead last cfg && extern_node_exists then next_loop comps_g (Plain last) invmap
else if is_loophead last cfg then next_loop comps_g (Plain last) invmap
else [] in
cand1 @ cand2 @ acc
| Some ctx when ctx = Lang.extern_node ->
let cand1 = if is_loophead hd cfg && is_view_pure_f func then next_ext_loop2 comps_g (Ctx (ctx,hd)) invmap
else if is_loophead hd cfg then next_ext_loop comps_g (Ctx (ctx,hd)) invmap
else [] in
let cand2 = if is_loophead hd cfg && is_view_pure_f func then next_ext_loop2 comps_g (Ctx (ctx,hd)) invmap
else if is_loophead last cfg && extern_node_exists then next_ext_loop comps_l (Ctx (ctx,last)) invmap
else if is_loophead last cfg then next_ext_loop comps_g (Ctx (ctx,last)) invmap
else [] in
cand1 @ cand2 @ acc
| _ -> acc
) paths []
let refine_ext : Global.t -> PathSet2.t -> InvMap.t -> InvMap.t list
= fun global paths invmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let (hd, last) = (BatList.hd nodes, BatList.last nodes) in
let func = FuncMap.find fk global.fmap in
let cfg = get_cfg func in
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
match ctx with
| None ->
let cands1 =
if (is_public_func func || is_external_func func) && is_external_call_node hd cfg then
next_ext comps_g (Plain Lang.extern_node) invmap
else [] in
let cands2 =
if (is_public_func func || is_external_func func) && is_external_call_node last cfg then
next_ext comps_g (Plain Lang.extern_node) invmap
else [] in
cands1 @ cands2 @ acc
| Some ctx when ctx = Lang.extern_node ->
let cands =
if (is_public_func func || is_external_func func) && (is_entry hd || is_exit last) then
next_ext comps_g (Plain ctx) invmap
else [] in
cands @ acc
| _ -> acc
) paths []
let rec special_only : vformula -> vformula
= fun vf ->
match vf with
| VAnd (f1,f2) -> VAnd (special_only f1, special_only f2)
| SigmaEqual _ | NoOverFlow _ | UntrustSum _ | UntrustSum2 _
| ForAll _ | VBinRel (VEq,Read (VVar ("@TU",_),_),_) -> vf
| VOr _ | Imply _ -> assert false
| _ -> VTrue
let rec make_locks_to_true : vformula -> vformula
= fun vf ->
match vf with
| VBinRel (VEq,VVar _,VCond VTrue)
| VBinRel (VEq,VVar _,VCond VFalse) -> VTrue
| VAnd (f1,f2) -> VAnd (make_locks_to_true f1, make_locks_to_true f2)
| VOr _ | Imply _ -> assert false
| _ -> vf
let rec make_locals_to_true : Global.t -> vformula -> vformula
= fun global vf ->
match vf with
| VAnd (f1,f2) -> VAnd (make_locals_to_true global f1, make_locals_to_true global f2)
| VOr _ | Imply _ -> assert false
| _ ->
if BatSet.for_all (fun x -> List.mem x global.gvars || List.mem (fst x) global_ghost_var_names) (free_vf vf) then vf
else VTrue
let sync' all_cutpoints ext_lhs all_lhs target_lhs target_ext_lhs : Global.t -> InvMap.t -> InvMap.t
= fun global invmap ->
BatSet.fold (fun cp acc ->
let loop_inv = InvMap.find cp acc in
InvMap.add (Plain trans_node) (VAnd (make_locals_to_true global (make_locks_to_true loop_inv), trans_inv)) acc
) all_lhs invmap in
tran inv = > loop inv , extern inv , extern loop inv
let trans_inv = InvMap.find (Plain Lang.trans_node) invmap in
BatSet.fold (fun cp acc ->
InvMap.add cp (VAnd (trans_inv, InvMap.find cp invmap)) acc
) all_cutpoints invmap in
extern loop inv = > extern inv
if BatSet.is_empty global.extcalls then invmap
else
BatSet.fold (fun cp acc ->
let ext_loopinv = InvMap.find cp invmap in
let extern_inv = InvMap.find (Plain Lang.extern_node) acc in
InvMap.add (Plain Lang.extern_node) (VAnd (extern_inv, ext_loopinv)) acc
) ext_lhs invmap in
if BatSet.is_empty global.extcalls then invmap
else
let extern_inv = InvMap.find (Plain extern_node) invmap in
let invmap = InvMap.add (Plain trans_node)
(VAnd (make_locals_to_true global (special_only extern_inv), InvMap.find (Plain trans_node) invmap))
invmap in
BatSet.fold (fun cp acc ->
InvMap.add cp (VAnd (extern_inv, InvMap.find cp invmap)) acc
) (BatSet.union ext_lhs target_lhs) invmap in
if BatSet.is_empty global.extcalls then invmap
else
let extern_inv = InvMap.find (Plain Lang.extern_node) invmap in
BatSet.fold (fun cp acc ->
if contain_lock extern_inv then InvMap.add cp VFalse acc
else acc
) target_ext_lhs invmap in
invmap
let sync : Global.t -> InvMap.t -> InvMap.t list
= fun global invmap ->
let lhs = BatSet.map (fun l -> Plain l) global.lhs_main in
let lhs2 = BatSet.map (fun l -> Plain l) global.lhs2_main in
let lhs3 = BatSet.map (fun l -> Plain l) global.lhs3_main in
let ext_lhs = if BatSet.is_empty global.extcalls then BatSet.empty else BatSet.map (fun l -> Ctx (Lang.extern_node, l)) global.lhs_main in
let ext_lhs2 = if BatSet.is_empty global.extcalls then BatSet.empty else BatSet.map (fun l -> Ctx (Lang.extern_node, l)) global.lhs2_main in
let ext_lhs3 = if BatSet.is_empty global.extcalls then BatSet.empty else BatSet.map (fun l -> Ctx (Lang.extern_node, l)) global.lhs3_main in
let all_cutpoints = if BatSet.is_empty global.extcalls then (assert (BatSet.is_empty ext_lhs); lhs)
else BatSet.add (Plain Lang.extern_node) (BatSet.union ext_lhs lhs) in
let invmap = InvMap.simplify invmap in
let invmap1 = sync' all_cutpoints ext_lhs lhs lhs ext_lhs global invmap in
let invmap2 = sync' all_cutpoints ext_lhs lhs lhs2 ext_lhs2 global invmap in
let invmap3 = sync' all_cutpoints ext_lhs lhs lhs3 ext_lhs3 global invmap in
let invmap1 = InvMap.simplify invmap1 in
let invmap2 = InvMap.simplify invmap2 in
let invmap3 = InvMap.simplify invmap3 in
[invmap1; invmap2; invmap3]
let refine_spec : Global.t -> PathSet2.t -> SpecMap.t -> SpecMap.t list
= fun global paths specmap ->
PathSet2.fold (fun (ctx,(fk,nodes)) acc ->
let comps_g = collect_comps_g global (ctx,(fk,nodes)) in
let callnodes = BatSet.map fst global.callnodes in
let intersect = BatSet.intersect callnodes (BatSet.of_list nodes) in
BatSet.fold (fun n acc2 ->
(next_spec comps_g n specmap) @ acc2
) intersect acc
) paths []
let next_spec : Global.t -> PathSet2.t -> InvMap.t -> SpecMap.t -> (InvMap.t * SpecMap.t) list
= fun global paths invmap specmap ->
let trans_inv = InvMap.find (Plain Lang.trans_node) invmap in
let specmap1 = BatSet.fold (fun (cn,fk) acc -> SpecMap.add cn (trans_inv, trans_inv) acc) global.callnodes SpecMap.empty in
let specmap2 =
BatSet.fold (fun (cn,fk) acc ->
let f = FuncMap.find fk global.fmap in
if contain_extern global f then
let extern_inv = InvMap.find (Plain Lang.extern_node) invmap in
if not (contain_lock_s extern_inv (get_body f)) then
SpecMap.add cn (extern_inv, extern_inv) acc
else
SpecMap.add cn (trans_inv, trans_inv) acc
else
SpecMap.add cn (trans_inv, trans_inv) acc
) global.callnodes SpecMap.empty in
let specmaps = [specmap1;specmap2] in
List.map (fun specmap -> (invmap,specmap)) specmaps
let refine : Global.t -> PathSet2.t -> InvMap.t * SpecMap.t -> (InvMap.t * SpecMap.t) list
= fun global paths (invmap,specmap) ->
let lst =
let tran = if !Options.intra then [] else refine_tran global paths invmap in
let loop = refine_loop global paths invmap in
let ext = refine_ext global paths invmap in
tran @ loop @ ext in
let lst = BatList.unique ~eq:InvMap.equal lst in
let lst = BatList.fold_lefti (fun acc i map -> acc @ (sync global map)) [] lst in
let _ = List.iter ( fun i - > print_endline ( InvMap.to_string i ) ) lst in
let _ = assert false in
let _ = assert false in *)
let final = List.fold_left (fun acc map -> acc @ (next_spec global paths map specmap)) [] lst in
final
|
029121d59011b34e06c30cdb5708f0b736d4b4f7c8d06293a571b4a8029b9a00 | spawnfest/eep49ers | ssl_crl_hash_dir.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2016 - 2020 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
-module(ssl_crl_hash_dir).
-include_lib("public_key/include/public_key.hrl").
-include_lib("kernel/include/logger.hrl").
-behaviour(ssl_crl_cache_api).
-export([lookup/3, select/2, fresh_crl/2]).
lookup(#'DistributionPoint'{cRLIssuer = CRLIssuer} = DP, CertIssuer, CRLDbInfo) ->
case CRLIssuer of
asn1_NOVALUE ->
%% If the distribution point extension doesn't
indicate a CRL issuer , use the certificate issuer .
select(CertIssuer, CRLDbInfo);
_ ->
CRLs = select(CRLIssuer, CRLDbInfo),
lists:filter(fun(DER) ->
public_key:pkix_match_dist_point(DER, DP)
end, CRLs)
end.
fresh_crl(#'DistributionPoint'{}, CurrentCRL) ->
CurrentCRL.
select({rdnSequence, _} = Issuer, DbHandle) ->
select([{directoryName, Issuer}], DbHandle);
select([], _) ->
[];
select([{directoryName, Issuer} | _], {_DbHandle, [{dir, Dir}]}) ->
case find_crls(public_key:pkix_normalize_name(Issuer), Dir) of
{#{reason := []}, DERs} ->
DERs;
{#{reason := [_|_]} = Report, DERs} ->
{logger, {notice, Report, ?LOCATION}, DERs};
{error, Error} ->
{logger, {error, #{description => "CRL retrival",
reason => [{cannot_find_crl, Error},
{dir, Dir}]}, ?LOCATION}, []}
end;
select([_ | Rest], CRLDbInfo) ->
select(Rest, CRLDbInfo).
find_crls(Issuer, Dir) ->
case filelib:is_dir(Dir) of
true ->
Hash = public_key:short_name_hash(Issuer),
find_crls(Issuer, Hash, Dir, 0, [], #{description => "CRL file traversal",
reason => []});
false ->
{error, not_a_directory}
end.
find_crls(Issuer, Hash, Dir, N, Acc, #{reason := Reason} = Report) ->
Filename = filename:join(Dir, Hash ++ ".r" ++ integer_to_list(N)),
case file:read_file(Filename) of
{error, enoent} ->
{Report, Acc};
{ok, Bin} ->
try maybe_parse_pem(Bin) of
DER when is_binary(DER) ->
%% Found one file. Let's see if there are more.
find_crls(Issuer, Hash, Dir, N + 1, [DER] ++ Acc, Report)
catch
error:Error ->
%% Something is wrong with the file. Report
%% it, and try the next one.
find_crls(Issuer, Hash, Dir, N + 1, Acc, Report#{reason => [{{crl_parse_error, Error},
{filename, Filename}} | Reason]})
end
end.
maybe_parse_pem(<<"-----BEGIN", _/binary>> = PEM) ->
It 's a PEM encoded file . Need to extract the DER
%% encoded data.
[{'CertificateList', DER, not_encrypted}] = public_key:pem_decode(PEM),
DER;
maybe_parse_pem(DER) when is_binary(DER) ->
%% Let's assume it's DER-encoded.
DER.
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/ssl/src/ssl_crl_hash_dir.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
If the distribution point extension doesn't
Found one file. Let's see if there are more.
Something is wrong with the file. Report
it, and try the next one.
encoded data.
Let's assume it's DER-encoded. | Copyright Ericsson AB 2016 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(ssl_crl_hash_dir).
-include_lib("public_key/include/public_key.hrl").
-include_lib("kernel/include/logger.hrl").
-behaviour(ssl_crl_cache_api).
-export([lookup/3, select/2, fresh_crl/2]).
lookup(#'DistributionPoint'{cRLIssuer = CRLIssuer} = DP, CertIssuer, CRLDbInfo) ->
case CRLIssuer of
asn1_NOVALUE ->
indicate a CRL issuer , use the certificate issuer .
select(CertIssuer, CRLDbInfo);
_ ->
CRLs = select(CRLIssuer, CRLDbInfo),
lists:filter(fun(DER) ->
public_key:pkix_match_dist_point(DER, DP)
end, CRLs)
end.
fresh_crl(#'DistributionPoint'{}, CurrentCRL) ->
CurrentCRL.
select({rdnSequence, _} = Issuer, DbHandle) ->
select([{directoryName, Issuer}], DbHandle);
select([], _) ->
[];
select([{directoryName, Issuer} | _], {_DbHandle, [{dir, Dir}]}) ->
case find_crls(public_key:pkix_normalize_name(Issuer), Dir) of
{#{reason := []}, DERs} ->
DERs;
{#{reason := [_|_]} = Report, DERs} ->
{logger, {notice, Report, ?LOCATION}, DERs};
{error, Error} ->
{logger, {error, #{description => "CRL retrival",
reason => [{cannot_find_crl, Error},
{dir, Dir}]}, ?LOCATION}, []}
end;
select([_ | Rest], CRLDbInfo) ->
select(Rest, CRLDbInfo).
find_crls(Issuer, Dir) ->
case filelib:is_dir(Dir) of
true ->
Hash = public_key:short_name_hash(Issuer),
find_crls(Issuer, Hash, Dir, 0, [], #{description => "CRL file traversal",
reason => []});
false ->
{error, not_a_directory}
end.
find_crls(Issuer, Hash, Dir, N, Acc, #{reason := Reason} = Report) ->
Filename = filename:join(Dir, Hash ++ ".r" ++ integer_to_list(N)),
case file:read_file(Filename) of
{error, enoent} ->
{Report, Acc};
{ok, Bin} ->
try maybe_parse_pem(Bin) of
DER when is_binary(DER) ->
find_crls(Issuer, Hash, Dir, N + 1, [DER] ++ Acc, Report)
catch
error:Error ->
find_crls(Issuer, Hash, Dir, N + 1, Acc, Report#{reason => [{{crl_parse_error, Error},
{filename, Filename}} | Reason]})
end
end.
maybe_parse_pem(<<"-----BEGIN", _/binary>> = PEM) ->
It 's a PEM encoded file . Need to extract the DER
[{'CertificateList', DER, not_encrypted}] = public_key:pem_decode(PEM),
DER;
maybe_parse_pem(DER) when is_binary(DER) ->
DER.
|
69c100bbddfe86fc6fb95f708e246ccd2c2214759f78fe6e6cf4c250bbcf519b | matthiasn/systems-toolbox-sente | integration_test.clj | (ns matthiasn.systems-toolbox-sente.integration-test
(:require [clojure.test :refer :all]
[matthiasn.systems-toolbox-sente.test-server :as ts]
[matthiasn.systems-toolbox-sente.test-store :as st]
[clj-webdriver.taxi :as tx]
[clojure.string :as s]))
(deftest open-page
(testing "open counter example, interact, UI should change"
(testing "click first counter thrice, should be 5"
(tx/wait-until
#(tx/exists? ".counters div:nth-of-type(1) button:nth-of-type(2)"))
(dotimes [_ 10]
(tx/click ".counters div:nth-of-type(1) button:nth-of-type(2)"))
(tx/wait-until
#(= "12" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"}))))
(is (= "12" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"}))))
(dotimes [_ 5]
(tx/click ".counters div:nth-of-type(1) button:nth-of-type(1)"))
(tx/wait-until
#(= "7" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"}))))
(is (= "7" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"})))))
(testing "add counter, click 100 times, should be 100"
(tx/wait-until #(tx/exists? ".counters button:nth-of-type(2)"))
(tx/click ".counters button:nth-of-type(2)")
(tx/wait-until
#(tx/exists? ".counters div:nth-of-type(4) button:nth-of-type(2)"))
(dotimes [_ 100]
(tx/click ".counters div:nth-of-type(4) button:nth-of-type(2)"))
(tx/wait-until
#(= "100" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"}))))
(is (= "100" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"}))))
(dotimes [_ 50]
(tx/click ".counters div:nth-of-type(4) button:nth-of-type(1)"))
(tx/wait-until
#(= "50" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"}))))
(is (= "50" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"})))))
(testing "fourth counter exists, click remove, should be gone"
(tx/wait-until #(tx/exists? ".counters div:nth-of-type(4)"))
(is (tx/find-element {:css ".counters div:nth-of-type(4)"}))
(tx/click ".counters button:nth-of-type(1)")
(tx/wait-until #(not (tx/exists? ".counters div:nth-of-type(4)")))
(is (not (tx/find-element {:css ".counters div:nth-of-type(4)"}))))
(testing "Backend store component has received all messages from frontend."
(is (= @st/state
{:cnt/inc 110, :cnt/dec 55, :cnt/add 1, :cnt/remove 1})))))
(deftest broadcast-test
(testing "broadcast message is relayed to connected client"
(ts/send-to-ws-cmp (with-meta [:broadcast/msg "broadcast message"]
{:sente-uid :broadcast}))
(let [pre-code-text #(tx/text (tx/find-element {:css "pre code"}))]
(tx/wait-until #(s/includes? (pre-code-text) "broadcast message"))
(is (s/includes? (pre-code-text) "broadcast message")))))
(use-fixtures :once ts/once-fixture)
| null | https://raw.githubusercontent.com/matthiasn/systems-toolbox-sente/edd0a8295f372063e507810c3fa92b23c0524f67/test/clj/matthiasn/systems_toolbox_sente/integration_test.clj | clojure | (ns matthiasn.systems-toolbox-sente.integration-test
(:require [clojure.test :refer :all]
[matthiasn.systems-toolbox-sente.test-server :as ts]
[matthiasn.systems-toolbox-sente.test-store :as st]
[clj-webdriver.taxi :as tx]
[clojure.string :as s]))
(deftest open-page
(testing "open counter example, interact, UI should change"
(testing "click first counter thrice, should be 5"
(tx/wait-until
#(tx/exists? ".counters div:nth-of-type(1) button:nth-of-type(2)"))
(dotimes [_ 10]
(tx/click ".counters div:nth-of-type(1) button:nth-of-type(2)"))
(tx/wait-until
#(= "12" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"}))))
(is (= "12" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"}))))
(dotimes [_ 5]
(tx/click ".counters div:nth-of-type(1) button:nth-of-type(1)"))
(tx/wait-until
#(= "7" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"}))))
(is (= "7" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(1) h1"})))))
(testing "add counter, click 100 times, should be 100"
(tx/wait-until #(tx/exists? ".counters button:nth-of-type(2)"))
(tx/click ".counters button:nth-of-type(2)")
(tx/wait-until
#(tx/exists? ".counters div:nth-of-type(4) button:nth-of-type(2)"))
(dotimes [_ 100]
(tx/click ".counters div:nth-of-type(4) button:nth-of-type(2)"))
(tx/wait-until
#(= "100" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"}))))
(is (= "100" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"}))))
(dotimes [_ 50]
(tx/click ".counters div:nth-of-type(4) button:nth-of-type(1)"))
(tx/wait-until
#(= "50" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"}))))
(is (= "50" (tx/text (tx/find-element
{:css ".counters div:nth-of-type(4) h1"})))))
(testing "fourth counter exists, click remove, should be gone"
(tx/wait-until #(tx/exists? ".counters div:nth-of-type(4)"))
(is (tx/find-element {:css ".counters div:nth-of-type(4)"}))
(tx/click ".counters button:nth-of-type(1)")
(tx/wait-until #(not (tx/exists? ".counters div:nth-of-type(4)")))
(is (not (tx/find-element {:css ".counters div:nth-of-type(4)"}))))
(testing "Backend store component has received all messages from frontend."
(is (= @st/state
{:cnt/inc 110, :cnt/dec 55, :cnt/add 1, :cnt/remove 1})))))
(deftest broadcast-test
(testing "broadcast message is relayed to connected client"
(ts/send-to-ws-cmp (with-meta [:broadcast/msg "broadcast message"]
{:sente-uid :broadcast}))
(let [pre-code-text #(tx/text (tx/find-element {:css "pre code"}))]
(tx/wait-until #(s/includes? (pre-code-text) "broadcast message"))
(is (s/includes? (pre-code-text) "broadcast message")))))
(use-fixtures :once ts/once-fixture)
| |
7e8273fbd5e6ba13a306166250d23c594fdc774a0007e0c35a786cc21c5136e0 | xapi-project/xen-api | gen_api.ml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Printf
module DT = Datamodel_types
module DU = Datamodel_utils
module OU = Ocaml_utils
module O = Ocaml_syntax
let oc = ref stdout
let print s = output_string !oc (s ^ "\n")
let between = Xapi_stdext_std.Listext.List.between
let overrides =
[
( "vm_operations_to_string_map"
, "let rpc_of_vm_operations_to_string_map x = Rpc.Dict (List.map (fun \
(x,y) -> (match rpc_of_vm_operations x with Rpc.String x -> x | _ -> \
failwith \"Marshalling error\"), Rpc.String y) x)\n"
^ "let vm_operations_to_string_map_of_rpc x = match x with Rpc.Dict l -> \
List.map (function (x,y) -> vm_operations_of_rpc (Rpc.String x), \
string_of_rpc y) l | _ -> failwith \"Unmarshalling error\"\n"
)
; ( "bond_mode"
, "let rpc_of_bond_mode x = match x with `balanceslb -> Rpc.String \
\"balance-slb\" | `activebackup -> Rpc.String \"active-backup\" | `lacp \
-> Rpc.String \"lacp\"\n"
^ "let bond_mode_of_rpc x = match x with Rpc.String \"balance-slb\" -> \
`balanceslb | Rpc.String \"active-backup\" -> `activebackup | \
Rpc.String \"lacp\" -> `lacp | _ -> failwith \"Unmarshalling error in \
bond-mode\"\n"
)
; ( "int64_to_float_map"
, "let rpc_of_int64_to_float_map x = Rpc.Dict (List.map (fun (x,y) -> \
Int64.to_string x, Rpc.Float y) x)\n"
^ "let int64_to_float_map_of_rpc x = match x with Rpc.Dict x -> List.map \
(fun (x,y) -> Int64.of_string x, float_of_rpc y) x | _ -> failwith \
\"Unmarshalling error\""
)
; ( "int64_to_int64_map"
, "let rpc_of_int64_to_int64_map x = Rpc.Dict (List.map (fun (x,y) -> \
Int64.to_string x, Rpc.Int y) x)\n"
^ "let int64_to_int64_map_of_rpc x = match x with Rpc.Dict x -> List.map \
(fun (x,y) -> Int64.of_string x, int64_of_rpc y) x | _ -> failwith \
\"Unmarshalling error\""
)
; ( "int64_to_string_set_map"
, "let rpc_of_int64_to_string_set_map x = Rpc.Dict (List.map (fun (x,y) -> \
Int64.to_string x, rpc_of_string_set y) x)\n"
^ "let int64_to_string_set_map_of_rpc x = match x with Rpc.Dict x -> \
List.map (fun (x,y) -> Int64.of_string x, string_set_of_rpc y) x | _ \
-> failwith \"Unmarshalling error\""
)
; ( "event_operation"
, "let rpc_of_event_operation x = match x with | `add -> Rpc.String \
\"add\" | `del -> Rpc.String \"del\" | `_mod -> Rpc.String \"mod\"\n"
^ "let event_operation_of_rpc x = match x with | Rpc.String \"add\" -> \
`add | Rpc.String \"del\" -> `del | Rpc.String \"mod\" -> `_mod | _ \
-> failwith \"Unmarshalling error\""
)
]
(** Generate a single type declaration for simple types (eg not containing references to record objects) *)
let gen_non_record_type tys =
let rec aux accu = function
| [] ->
accu
| DT.String :: t
| DT.Int :: t
| DT.Float :: t
| DT.Bool :: t
| DT.Record _ :: t
| DT.Map (_, DT.Record _) :: t
| DT.Option (DT.Record _) :: t
| DT.Set (DT.Record _) :: t ->
aux accu t
| (DT.Set (DT.Enum _ as e) as ty) :: t ->
aux
(sprintf "type %s = %s list [@@deriving rpc]" (OU.alias_of_ty ty)
(OU.alias_of_ty e)
:: accu
)
t
| ty :: t ->
let alias = OU.alias_of_ty ty in
if List.mem_assoc alias overrides then
aux
(sprintf "type %s = %s\n%s\n" alias (OU.ocaml_of_ty ty)
(List.assoc alias overrides)
:: accu
)
t
else
aux
(sprintf "type %s = %s [@@deriving rpc]" (OU.alias_of_ty ty)
(OU.ocaml_of_ty ty)
:: accu
)
t
in
aux [] tys
(** Generate a list of modules for each record kind *)
let gen_record_type ~with_module highapi tys =
let rec aux accu = function
| [] ->
accu
| DT.Record record :: t ->
let obj_name = OU.ocaml_of_record_name record in
let all_fields =
DU.fields_of_obj (Dm_api.get_obj_by_name highapi ~objname:record)
in
let field fld =
OU.ocaml_of_record_field (obj_name :: fld.DT.full_name)
in
let rpc_field fld =
sprintf "\"%s\"" (String.concat "_" fld.DT.full_name)
in
let map_fields fn =
String.concat "; " (List.map (fun field -> fn field) all_fields)
in
let regular_def fld =
sprintf "%s : %s" (field fld) (OU.alias_of_ty fld.DT.ty)
in
(* We treat options in records specially: if they are None, the field
will be omitted, if they are Some, the field will be present. *)
let make_of_field fld =
let field = sprintf "(x.%s)" (field fld) in
let rpc_of_fn ty = sprintf "(rpc_of_%s)" (OU.alias_of_ty ty) in
let value =
let open DT in
match fld.ty with
| Option ty ->
sprintf "(opt_map %s %s)" (rpc_of_fn ty) field
| SecretString
| String
| Int
| Float
| Bool
| DateTime
| Enum _
| Set _
| Map _
| Ref _
| Record _ ->
sprintf "(Some (%s %s))" (rpc_of_fn fld.ty) field
in
sprintf "opt_map (fun v -> (%s, v)) %s" (rpc_field fld) value
in
let get_default fld =
let default_value =
match fld.DT.ty with
| DT.Set (DT.Ref _) ->
Some (DT.VSet [])
| _ ->
fld.DT.default_value
in
match default_value with
| None ->
"None"
| Some default ->
sprintf "(Some (%s))"
(Datamodel_values.to_ocaml_string ~v2:true default)
in
let make_to_field fld =
let rpc_field = rpc_field fld in
let get_field ty =
let of_rpc_fn ty = sprintf "%s_of_rpc" (OU.alias_of_ty ty) in
sprintf "(%s (assocer %s x %s))" (of_rpc_fn ty) rpc_field
(get_default fld)
in
let value =
let open DT in
match fld.ty with
| Option ty ->
sprintf "(if List.mem_assoc %s x then Some (%s) else None)"
rpc_field (get_field ty)
| SecretString
| String
| Int
| Float
| Bool
| DateTime
| Enum _
| Set _
| Map _
| Ref _
| Record _ ->
sprintf "(%s)" (get_field fld.ty)
in
sprintf "%s = %s" (field fld) value
in
let type_t =
sprintf "type %s_t = { %s }" obj_name (map_fields regular_def)
in
let others =
if not with_module then
[]
else
[
sprintf "let rpc_of_%s_t x = Rpc.Dict (unbox_list [ %s ])"
obj_name (map_fields make_of_field)
; sprintf "let %s_t_of_rpc x = on_dict (fun x -> { %s }) x" obj_name
(map_fields make_to_field)
; sprintf
"type ref_%s_to_%s_t_map = (ref_%s * %s_t) list [@@deriving \
rpc]"
record obj_name record obj_name
; sprintf "type %s_t_set = %s_t list [@@deriving rpc]" obj_name
obj_name
; sprintf "type %s_t_option = %s_t option [@@deriving rpc]" obj_name
obj_name
; ""
]
in
aux ((type_t :: others) @ accu) t
| _ :: t ->
aux accu t
in
aux [] tys
let gen_client highapi =
List.iter (List.iter print)
(between [""]
[
[
"open API"
; "open Rpc"
; "module type RPC = sig val rpc: Rpc.t -> Rpc.t end"
; "module type IO = sig type 'a t val bind : 'a t -> ('a -> 'b t) -> \
'b t val return : 'a -> 'a t end"
; "module type AsyncQualifier = sig val async_qualifier : string end"
; ""
; "let server_failure code args = raise (Api_errors.Server_error \
(code, args))"
]
; O.Module.strings_of (Gen_client.gen_module highapi)
; [
"module Id = struct type 'a t = 'a let bind x f = f x let return x \
= x end"
; "module Client = ClientF(Id)"
]
]
)
let add_set_enums types =
List.concat
(List.map
(fun ty ->
match ty with
| DT.Enum _ ->
if List.exists (fun ty2 -> ty2 = DT.Set ty) types then
[ty]
else
[DT.Set ty; ty]
| _ ->
[ty]
)
types
)
let all_types_of highapi = DU.Types.of_objects (Dm_api.objects_of_api highapi)
* Returns a list of type sorted such that the first elements in the
list have nothing depending on them . Later elements in the list may
depend upon types earlier in the list
list have nothing depending on them. Later elements in the list may
depend upon types earlier in the list *)
let toposort_types highapi types =
let rec inner result remaining =
let rec references name = function
| DT.SecretString
| DT.String
| DT.Int
| DT.Float
| DT.Bool
| DT.DateTime
| DT.Ref _
| DT.Enum _ ->
false
| DT.Set ty ->
references name ty
| DT.Map (ty, ty') ->
references name ty || references name ty'
| DT.Record record when record = name ->
true
| DT.Record record ->
let all_fields =
DU.fields_of_obj (Dm_api.get_obj_by_name highapi ~objname:record)
in
List.exists (fun fld -> references name fld.DT.ty) all_fields
| DT.Option ty ->
references name ty
in
let ty_ref, ty_not_ref =
List.partition
(fun ty ->
match ty with
| DT.Record name ->
let referencing = List.filter (references name) remaining in
List.length referencing > 1
| _ ->
false
)
remaining
in
match ty_ref with
| [] ->
result @ ty_not_ref
| _ ->
inner (result @ ty_not_ref) ty_ref
in
let result = inner [] types in
assert (List.length result = List.length types) ;
assert (List.sort compare result = List.sort compare types) ;
result
let gen_client_types highapi =
let all_types = all_types_of highapi in
let all_types = add_set_enums all_types in
List.iter (List.iter print)
(between [""]
[
[
"type failure = (string list) [@@deriving rpc]"
; "let response_of_failure code params ="
; " Rpc.failure (rpc_of_failure (code::params))"
; "let response_of_fault code ="
; " Rpc.failure (rpc_of_failure ([\"Fault\"; code]))"
]
; ["include Rpc"; "type string_list = string list [@@deriving rpc]"]
; [
"module Ref = struct"
; " include Ref"
; " let rpc_of_t (_:'a -> Rpc.t) (x: 'a Ref.t) = rpc_of_string \
(Ref.string_of x)"
; " let t_of_rpc (_:Rpc.t -> 'a) x : 'a t = of_string (string_of_rpc \
x);"
; "end"
]
; [
"module Date = struct"
; " open Xapi_stdext_date"
; " include Date"
; " let rpc_of_iso8601 x = DateTime (Date.to_string x)"
; " let iso8601_of_rpc = function String x | DateTime x -> \
Date.of_string x | _ -> failwith \"Date.iso8601_of_rpc\""
; "end"
]
; [
"let on_dict f = function | Rpc.Dict x -> f x | _ -> failwith \
\"Expected Dictionary\""
]
; ["let opt_map f = function | None -> None | Some x -> Some (f x)"]
; [
"let unbox_list = let rec loop aux = function"
; "| [] -> List.rev aux"
; "| None :: tl -> loop aux tl"
; "| Some hd :: tl -> loop (hd :: aux) tl in"
; "loop []"
]
; [
"let assocer key map default = "
; " try"
; " List.assoc key map"
; " with Not_found ->"
; " match default with"
; " | Some d -> d"
; " | None -> failwith (Printf.sprintf \"Field %s not present in \
rpc\" key)"
]
; gen_non_record_type all_types
; gen_record_type ~with_module:true highapi
(toposort_types highapi all_types)
; O.Signature.strings_of (Gen_client.gen_signature highapi)
]
)
let gen_server highapi =
List.iter (List.iter print)
(between [""]
[
["open API"; "open Server_helpers"]
; O.Module.strings_of (Gen_server.gen_module highapi)
]
)
let gen_custom_actions highapi =
List.iter (List.iter print)
(between [""]
[
["open API"]
; O.Signature.strings_of
(Gen_empty_custom.gen_signature Gen_empty_custom.signature_name None
highapi
)
; O.Module.strings_of (Gen_empty_custom.gen_release_module highapi)
]
)
open Gen_db_actions
let gen_db_actions highapi =
let highapi_in_db =
Dm_api.filter
(fun obj -> obj.DT.in_database)
(fun _ -> true)
(fun _ -> true)
highapi
in
let all_types_in_db = all_types_of highapi_in_db in
let only_records =
List.filter (function DT.Record _ -> true | _ -> false) all_types_in_db
in
List.iter (List.iter print)
(between [""]
[
[{|[@@@ocaml.warning "-6-27-33"]|}]
; ["open API"]
; (* These records have the hidden fields inside.
This excludes records not stored in the database, which must not
have hidden fields. *)
gen_record_type ~with_module:false highapi
(toposort_types highapi only_records)
NB record types are ignored by dm_to_string and string_to_dm
O.Module.strings_of (dm_to_string all_types_in_db)
; O.Module.strings_of (string_to_dm all_types_in_db)
; O.Module.strings_of (db_action highapi_in_db)
]
@ List.map O.Module.strings_of (Gen_db_check.all highapi_in_db)
@ []
)
let gen_rbac highapi = print (Gen_rbac.gen_permissions_of_static_roles highapi)
| null | https://raw.githubusercontent.com/xapi-project/xen-api/e8c3575316226ac6324e94aa4f9e040a662e279a/ocaml/idl/ocaml_backend/gen_api.ml | ocaml | * Generate a single type declaration for simple types (eg not containing references to record objects)
* Generate a list of modules for each record kind
We treat options in records specially: if they are None, the field
will be omitted, if they are Some, the field will be present.
These records have the hidden fields inside.
This excludes records not stored in the database, which must not
have hidden fields. |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Printf
module DT = Datamodel_types
module DU = Datamodel_utils
module OU = Ocaml_utils
module O = Ocaml_syntax
let oc = ref stdout
let print s = output_string !oc (s ^ "\n")
let between = Xapi_stdext_std.Listext.List.between
let overrides =
[
( "vm_operations_to_string_map"
, "let rpc_of_vm_operations_to_string_map x = Rpc.Dict (List.map (fun \
(x,y) -> (match rpc_of_vm_operations x with Rpc.String x -> x | _ -> \
failwith \"Marshalling error\"), Rpc.String y) x)\n"
^ "let vm_operations_to_string_map_of_rpc x = match x with Rpc.Dict l -> \
List.map (function (x,y) -> vm_operations_of_rpc (Rpc.String x), \
string_of_rpc y) l | _ -> failwith \"Unmarshalling error\"\n"
)
; ( "bond_mode"
, "let rpc_of_bond_mode x = match x with `balanceslb -> Rpc.String \
\"balance-slb\" | `activebackup -> Rpc.String \"active-backup\" | `lacp \
-> Rpc.String \"lacp\"\n"
^ "let bond_mode_of_rpc x = match x with Rpc.String \"balance-slb\" -> \
`balanceslb | Rpc.String \"active-backup\" -> `activebackup | \
Rpc.String \"lacp\" -> `lacp | _ -> failwith \"Unmarshalling error in \
bond-mode\"\n"
)
; ( "int64_to_float_map"
, "let rpc_of_int64_to_float_map x = Rpc.Dict (List.map (fun (x,y) -> \
Int64.to_string x, Rpc.Float y) x)\n"
^ "let int64_to_float_map_of_rpc x = match x with Rpc.Dict x -> List.map \
(fun (x,y) -> Int64.of_string x, float_of_rpc y) x | _ -> failwith \
\"Unmarshalling error\""
)
; ( "int64_to_int64_map"
, "let rpc_of_int64_to_int64_map x = Rpc.Dict (List.map (fun (x,y) -> \
Int64.to_string x, Rpc.Int y) x)\n"
^ "let int64_to_int64_map_of_rpc x = match x with Rpc.Dict x -> List.map \
(fun (x,y) -> Int64.of_string x, int64_of_rpc y) x | _ -> failwith \
\"Unmarshalling error\""
)
; ( "int64_to_string_set_map"
, "let rpc_of_int64_to_string_set_map x = Rpc.Dict (List.map (fun (x,y) -> \
Int64.to_string x, rpc_of_string_set y) x)\n"
^ "let int64_to_string_set_map_of_rpc x = match x with Rpc.Dict x -> \
List.map (fun (x,y) -> Int64.of_string x, string_set_of_rpc y) x | _ \
-> failwith \"Unmarshalling error\""
)
; ( "event_operation"
, "let rpc_of_event_operation x = match x with | `add -> Rpc.String \
\"add\" | `del -> Rpc.String \"del\" | `_mod -> Rpc.String \"mod\"\n"
^ "let event_operation_of_rpc x = match x with | Rpc.String \"add\" -> \
`add | Rpc.String \"del\" -> `del | Rpc.String \"mod\" -> `_mod | _ \
-> failwith \"Unmarshalling error\""
)
]
let gen_non_record_type tys =
let rec aux accu = function
| [] ->
accu
| DT.String :: t
| DT.Int :: t
| DT.Float :: t
| DT.Bool :: t
| DT.Record _ :: t
| DT.Map (_, DT.Record _) :: t
| DT.Option (DT.Record _) :: t
| DT.Set (DT.Record _) :: t ->
aux accu t
| (DT.Set (DT.Enum _ as e) as ty) :: t ->
aux
(sprintf "type %s = %s list [@@deriving rpc]" (OU.alias_of_ty ty)
(OU.alias_of_ty e)
:: accu
)
t
| ty :: t ->
let alias = OU.alias_of_ty ty in
if List.mem_assoc alias overrides then
aux
(sprintf "type %s = %s\n%s\n" alias (OU.ocaml_of_ty ty)
(List.assoc alias overrides)
:: accu
)
t
else
aux
(sprintf "type %s = %s [@@deriving rpc]" (OU.alias_of_ty ty)
(OU.ocaml_of_ty ty)
:: accu
)
t
in
aux [] tys
let gen_record_type ~with_module highapi tys =
let rec aux accu = function
| [] ->
accu
| DT.Record record :: t ->
let obj_name = OU.ocaml_of_record_name record in
let all_fields =
DU.fields_of_obj (Dm_api.get_obj_by_name highapi ~objname:record)
in
let field fld =
OU.ocaml_of_record_field (obj_name :: fld.DT.full_name)
in
let rpc_field fld =
sprintf "\"%s\"" (String.concat "_" fld.DT.full_name)
in
let map_fields fn =
String.concat "; " (List.map (fun field -> fn field) all_fields)
in
let regular_def fld =
sprintf "%s : %s" (field fld) (OU.alias_of_ty fld.DT.ty)
in
let make_of_field fld =
let field = sprintf "(x.%s)" (field fld) in
let rpc_of_fn ty = sprintf "(rpc_of_%s)" (OU.alias_of_ty ty) in
let value =
let open DT in
match fld.ty with
| Option ty ->
sprintf "(opt_map %s %s)" (rpc_of_fn ty) field
| SecretString
| String
| Int
| Float
| Bool
| DateTime
| Enum _
| Set _
| Map _
| Ref _
| Record _ ->
sprintf "(Some (%s %s))" (rpc_of_fn fld.ty) field
in
sprintf "opt_map (fun v -> (%s, v)) %s" (rpc_field fld) value
in
let get_default fld =
let default_value =
match fld.DT.ty with
| DT.Set (DT.Ref _) ->
Some (DT.VSet [])
| _ ->
fld.DT.default_value
in
match default_value with
| None ->
"None"
| Some default ->
sprintf "(Some (%s))"
(Datamodel_values.to_ocaml_string ~v2:true default)
in
let make_to_field fld =
let rpc_field = rpc_field fld in
let get_field ty =
let of_rpc_fn ty = sprintf "%s_of_rpc" (OU.alias_of_ty ty) in
sprintf "(%s (assocer %s x %s))" (of_rpc_fn ty) rpc_field
(get_default fld)
in
let value =
let open DT in
match fld.ty with
| Option ty ->
sprintf "(if List.mem_assoc %s x then Some (%s) else None)"
rpc_field (get_field ty)
| SecretString
| String
| Int
| Float
| Bool
| DateTime
| Enum _
| Set _
| Map _
| Ref _
| Record _ ->
sprintf "(%s)" (get_field fld.ty)
in
sprintf "%s = %s" (field fld) value
in
let type_t =
sprintf "type %s_t = { %s }" obj_name (map_fields regular_def)
in
let others =
if not with_module then
[]
else
[
sprintf "let rpc_of_%s_t x = Rpc.Dict (unbox_list [ %s ])"
obj_name (map_fields make_of_field)
; sprintf "let %s_t_of_rpc x = on_dict (fun x -> { %s }) x" obj_name
(map_fields make_to_field)
; sprintf
"type ref_%s_to_%s_t_map = (ref_%s * %s_t) list [@@deriving \
rpc]"
record obj_name record obj_name
; sprintf "type %s_t_set = %s_t list [@@deriving rpc]" obj_name
obj_name
; sprintf "type %s_t_option = %s_t option [@@deriving rpc]" obj_name
obj_name
; ""
]
in
aux ((type_t :: others) @ accu) t
| _ :: t ->
aux accu t
in
aux [] tys
let gen_client highapi =
List.iter (List.iter print)
(between [""]
[
[
"open API"
; "open Rpc"
; "module type RPC = sig val rpc: Rpc.t -> Rpc.t end"
; "module type IO = sig type 'a t val bind : 'a t -> ('a -> 'b t) -> \
'b t val return : 'a -> 'a t end"
; "module type AsyncQualifier = sig val async_qualifier : string end"
; ""
; "let server_failure code args = raise (Api_errors.Server_error \
(code, args))"
]
; O.Module.strings_of (Gen_client.gen_module highapi)
; [
"module Id = struct type 'a t = 'a let bind x f = f x let return x \
= x end"
; "module Client = ClientF(Id)"
]
]
)
let add_set_enums types =
List.concat
(List.map
(fun ty ->
match ty with
| DT.Enum _ ->
if List.exists (fun ty2 -> ty2 = DT.Set ty) types then
[ty]
else
[DT.Set ty; ty]
| _ ->
[ty]
)
types
)
let all_types_of highapi = DU.Types.of_objects (Dm_api.objects_of_api highapi)
* Returns a list of type sorted such that the first elements in the
list have nothing depending on them . Later elements in the list may
depend upon types earlier in the list
list have nothing depending on them. Later elements in the list may
depend upon types earlier in the list *)
let toposort_types highapi types =
let rec inner result remaining =
let rec references name = function
| DT.SecretString
| DT.String
| DT.Int
| DT.Float
| DT.Bool
| DT.DateTime
| DT.Ref _
| DT.Enum _ ->
false
| DT.Set ty ->
references name ty
| DT.Map (ty, ty') ->
references name ty || references name ty'
| DT.Record record when record = name ->
true
| DT.Record record ->
let all_fields =
DU.fields_of_obj (Dm_api.get_obj_by_name highapi ~objname:record)
in
List.exists (fun fld -> references name fld.DT.ty) all_fields
| DT.Option ty ->
references name ty
in
let ty_ref, ty_not_ref =
List.partition
(fun ty ->
match ty with
| DT.Record name ->
let referencing = List.filter (references name) remaining in
List.length referencing > 1
| _ ->
false
)
remaining
in
match ty_ref with
| [] ->
result @ ty_not_ref
| _ ->
inner (result @ ty_not_ref) ty_ref
in
let result = inner [] types in
assert (List.length result = List.length types) ;
assert (List.sort compare result = List.sort compare types) ;
result
let gen_client_types highapi =
let all_types = all_types_of highapi in
let all_types = add_set_enums all_types in
List.iter (List.iter print)
(between [""]
[
[
"type failure = (string list) [@@deriving rpc]"
; "let response_of_failure code params ="
; " Rpc.failure (rpc_of_failure (code::params))"
; "let response_of_fault code ="
; " Rpc.failure (rpc_of_failure ([\"Fault\"; code]))"
]
; ["include Rpc"; "type string_list = string list [@@deriving rpc]"]
; [
"module Ref = struct"
; " include Ref"
; " let rpc_of_t (_:'a -> Rpc.t) (x: 'a Ref.t) = rpc_of_string \
(Ref.string_of x)"
; " let t_of_rpc (_:Rpc.t -> 'a) x : 'a t = of_string (string_of_rpc \
x);"
; "end"
]
; [
"module Date = struct"
; " open Xapi_stdext_date"
; " include Date"
; " let rpc_of_iso8601 x = DateTime (Date.to_string x)"
; " let iso8601_of_rpc = function String x | DateTime x -> \
Date.of_string x | _ -> failwith \"Date.iso8601_of_rpc\""
; "end"
]
; [
"let on_dict f = function | Rpc.Dict x -> f x | _ -> failwith \
\"Expected Dictionary\""
]
; ["let opt_map f = function | None -> None | Some x -> Some (f x)"]
; [
"let unbox_list = let rec loop aux = function"
; "| [] -> List.rev aux"
; "| None :: tl -> loop aux tl"
; "| Some hd :: tl -> loop (hd :: aux) tl in"
; "loop []"
]
; [
"let assocer key map default = "
; " try"
; " List.assoc key map"
; " with Not_found ->"
; " match default with"
; " | Some d -> d"
; " | None -> failwith (Printf.sprintf \"Field %s not present in \
rpc\" key)"
]
; gen_non_record_type all_types
; gen_record_type ~with_module:true highapi
(toposort_types highapi all_types)
; O.Signature.strings_of (Gen_client.gen_signature highapi)
]
)
let gen_server highapi =
List.iter (List.iter print)
(between [""]
[
["open API"; "open Server_helpers"]
; O.Module.strings_of (Gen_server.gen_module highapi)
]
)
let gen_custom_actions highapi =
List.iter (List.iter print)
(between [""]
[
["open API"]
; O.Signature.strings_of
(Gen_empty_custom.gen_signature Gen_empty_custom.signature_name None
highapi
)
; O.Module.strings_of (Gen_empty_custom.gen_release_module highapi)
]
)
open Gen_db_actions
let gen_db_actions highapi =
let highapi_in_db =
Dm_api.filter
(fun obj -> obj.DT.in_database)
(fun _ -> true)
(fun _ -> true)
highapi
in
let all_types_in_db = all_types_of highapi_in_db in
let only_records =
List.filter (function DT.Record _ -> true | _ -> false) all_types_in_db
in
List.iter (List.iter print)
(between [""]
[
[{|[@@@ocaml.warning "-6-27-33"]|}]
; ["open API"]
gen_record_type ~with_module:false highapi
(toposort_types highapi only_records)
NB record types are ignored by dm_to_string and string_to_dm
O.Module.strings_of (dm_to_string all_types_in_db)
; O.Module.strings_of (string_to_dm all_types_in_db)
; O.Module.strings_of (db_action highapi_in_db)
]
@ List.map O.Module.strings_of (Gen_db_check.all highapi_in_db)
@ []
)
let gen_rbac highapi = print (Gen_rbac.gen_permissions_of_static_roles highapi)
|
b76c324b35573780318d45f1767ceb26d11a68b3e66e66cad931fee27f5056f3 | masateruk/micro-caml | list_func.ml | let rec iter f xs =
match xs with
| [] -> ()
| x :: xs -> f x; iter f xs
let rec fold_right f xs accu =
match xs with
| [] -> accu
| x :: xs -> f x (fold_right f xs accu)
let rec map f xs =
match xs with
| [] -> []
| x :: xs -> f x :: (map f xs)
let () =
let rec suc x = x + 1 in
let rec add x y = x + y in
let xs = [11; 12; 13] in
iter print_int xs;
iter print_int (map suc xs);
print_int (fold_right add xs 0)
| null | https://raw.githubusercontent.com/masateruk/micro-caml/0c0bd066b87cf54ce33709355c422993a85a86a1/test/list_func.ml | ocaml | let rec iter f xs =
match xs with
| [] -> ()
| x :: xs -> f x; iter f xs
let rec fold_right f xs accu =
match xs with
| [] -> accu
| x :: xs -> f x (fold_right f xs accu)
let rec map f xs =
match xs with
| [] -> []
| x :: xs -> f x :: (map f xs)
let () =
let rec suc x = x + 1 in
let rec add x y = x + y in
let xs = [11; 12; 13] in
iter print_int xs;
iter print_int (map suc xs);
print_int (fold_right add xs 0)
| |
86f72fa4deec5aab6e402ce4ff20baefeb8ac68793f3c52f3969030c5169b966 | facebook/pyre-check | cfg.mli |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open Ast
open Statement
module Node : sig
type kind =
| Block of Statement.t list
| Dispatch
| Entry
| Error
| Normal
| Final
| For of For.t
| If of If.t
| Join
| Try of Try.t
| With of With.t
| While of While.t
[@@deriving compare, show, sexp]
type t [@@deriving compare, sexp]
val location_insensitive_equal : t -> t -> bool
val create : int -> kind -> Int.Set.t -> Int.Set.t -> t
val id : t -> int
val statements : t -> Statement.t list
val successors : t -> Int.Set.t
val predecessors : t -> Int.Set.t
val description : t -> string
end
(* Control flow graph of a define body. *)
type t = Node.t Int.Table.t [@@deriving show]
val entry_index : int
val normal_index : int
val exit_index : int
val to_dot
: ?precondition:(int -> string) ->
?sort_labels:bool ->
?single_line:bool ->
(int, Node.t) Hashtbl.t ->
string
val create : Define.t -> t
val node : t -> id:int -> Node.t
(* Exposed for testing only *)
val match_cases_refutable : Match.Case.t list -> bool
module MatchTranslate : sig
open Expression
val to_condition : subject:Expression.t -> case:Match.Case.t -> Expression.t
val pattern_to_condition : subject:Expression.t -> Match.Pattern.t -> Expression.t
end
| null | https://raw.githubusercontent.com/facebook/pyre-check/aa66d2798dfdc4f4a170f003b787623cf0426c55/source/analysis/cfg.mli | ocaml | Control flow graph of a define body.
Exposed for testing only |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open Ast
open Statement
module Node : sig
type kind =
| Block of Statement.t list
| Dispatch
| Entry
| Error
| Normal
| Final
| For of For.t
| If of If.t
| Join
| Try of Try.t
| With of With.t
| While of While.t
[@@deriving compare, show, sexp]
type t [@@deriving compare, sexp]
val location_insensitive_equal : t -> t -> bool
val create : int -> kind -> Int.Set.t -> Int.Set.t -> t
val id : t -> int
val statements : t -> Statement.t list
val successors : t -> Int.Set.t
val predecessors : t -> Int.Set.t
val description : t -> string
end
type t = Node.t Int.Table.t [@@deriving show]
val entry_index : int
val normal_index : int
val exit_index : int
val to_dot
: ?precondition:(int -> string) ->
?sort_labels:bool ->
?single_line:bool ->
(int, Node.t) Hashtbl.t ->
string
val create : Define.t -> t
val node : t -> id:int -> Node.t
val match_cases_refutable : Match.Case.t list -> bool
module MatchTranslate : sig
open Expression
val to_condition : subject:Expression.t -> case:Match.Case.t -> Expression.t
val pattern_to_condition : subject:Expression.t -> Match.Pattern.t -> Expression.t
end
|
36de7b999db7fe5ecfed7313cbf32a20a0a745d06aec28ef4ea1ea7a87860b6e | gwkkwg/trivial-backtrace | tests.lisp | (in-package #:trivial-backtrace-test)
(deftestsuite generates-backtrace (trivial-backtrace-test)
())
(addtest (generates-backtrace)
test-1
(let ((output nil))
(handler-case
(let ((x 1))
(let ((y (- x (expt 1024 0))))
(declare (optimize (safety 3)))
(/ 2 y)))
(error (c)
(setf output (print-backtrace c :output nil))))
(ensure (stringp output))
(ensure (plusp (length output)))))
(addtest (generates-backtrace)
generates-backtrace-to-string-stream
(let ((output nil))
(handler-case
(let ((x 1))
(let ((y (- x (expt 1024 0))))
(declare (optimize (safety 3)))
(/ 2 y)))
(error (c)
(setf output (with-output-to-string (stream)
(print-backtrace c :output nil)))))
(ensure (stringp output))
(ensure (plusp (length output)))))
| null | https://raw.githubusercontent.com/gwkkwg/trivial-backtrace/6eb65bde7229413040c81d42ea22f0e4c9c8cfc9/test/tests.lisp | lisp | (in-package #:trivial-backtrace-test)
(deftestsuite generates-backtrace (trivial-backtrace-test)
())
(addtest (generates-backtrace)
test-1
(let ((output nil))
(handler-case
(let ((x 1))
(let ((y (- x (expt 1024 0))))
(declare (optimize (safety 3)))
(/ 2 y)))
(error (c)
(setf output (print-backtrace c :output nil))))
(ensure (stringp output))
(ensure (plusp (length output)))))
(addtest (generates-backtrace)
generates-backtrace-to-string-stream
(let ((output nil))
(handler-case
(let ((x 1))
(let ((y (- x (expt 1024 0))))
(declare (optimize (safety 3)))
(/ 2 y)))
(error (c)
(setf output (with-output-to-string (stream)
(print-backtrace c :output nil)))))
(ensure (stringp output))
(ensure (plusp (length output)))))
| |
e19b985bd7c5d403a13694ee4198c94c812dbdae95760ef79ea81d28050a4b06 | tweag/linear-base | Monoid.hs | # LANGUAGE DataKinds #
# LANGUAGE DerivingVia #
{-# LANGUAGE LinearTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -Wno - orphans #
{-# OPTIONS_HADDOCK hide #-}
| This module provides linear versions of ' Monoid ' .
--
-- To learn about how these classic monoids work, go to this school of haskell
-- [post](-tour).
module Data.Monoid.Linear.Internal.Monoid
( -- * Monoid operations
Monoid (..),
mconcat,
mappend,
Can not export Data . Monoid.{First , Last } because of the name clash with Data . , Last }
)
where
import Data.Functor.Compose (Compose (Compose))
import qualified Data.Functor.Compose as Functor
import Data.Functor.Const (Const)
import Data.Functor.Identity (Identity (Identity))
import Data.Functor.Product (Product (Pair))
import qualified Data.Functor.Product as Functor
import qualified Data.Monoid as Monoid
import Data.Monoid.Linear.Internal.Semigroup
import Data.Ord (Down (Down))
import Data.Proxy (Proxy (Proxy))
import Data.Unrestricted.Linear.Internal.Consumable (Consumable)
import GHC.Types hiding (Any)
import Prelude.Linear.Internal
import Prelude (Maybe (Nothing))
import qualified Prelude
-- | A linear monoid is a linear semigroup with an identity on the binary
-- operation.
--
Laws ( same as ' Data . Monoid . Monoid ' ):
* ∀ x ∈ G , x < > = < > x = x
class Semigroup a => Monoid a where
{-# MINIMAL mempty #-}
mempty :: a
instance (Prelude.Semigroup a, Monoid a) => Prelude.Monoid (NonLinear a) where
mempty = NonLinear mempty
-- convenience redefine
mconcat :: Monoid a => [a] %1 -> a
mconcat (xs' :: [a]) = go mempty xs'
where
go :: a %1 -> [a] %1 -> a
go acc [] = acc
go acc (x : xs) = go (acc <> x) xs
mappend :: Monoid a => a %1 -> a %1 -> a
mappend = (<>)
---------------
-- Instances --
---------------
instance Prelude.Monoid (Endo a) where
mempty = Endo id
Instances below are listed in the same order as in
instance Monoid All where
mempty = All True
instance Monoid Any where
mempty = Any False
instance Monoid Ordering where
mempty = EQ
instance Monoid () where
mempty = ()
instance Monoid a => Monoid (Identity a) where
mempty = Identity mempty
instance Consumable a => Monoid (Monoid.First a) where
mempty = Monoid.First Nothing
instance Consumable a => Monoid (Monoid.Last a) where
mempty = Monoid.Last Nothing
instance Monoid a => Monoid (Down a) where
mempty = Down mempty
Can not add instance ( a , Bounded a ) = > Monoid ( a ) ; would require ( NonLinear . a , Consumable a )
Can not add instance ( a , Bounded a ) = > Monoid ( Min a ) ; would require ( NonLinear . a , Consumable a )
instance Monoid a => Monoid (Dual a) where
mempty = Dual mempty
instance Monoid (Endo a) where
mempty = Endo id
See Data . Num . Linear for instance ... = > Monoid ( Product a )
See Data . Num . Linear for instance ... = > Monoid ( Sum a )
See System . IO.Linear for instance ... = > Monoid ( IO a )
See System . IO.Resource . Internal for instance ... = > Monoid ( RIO a )
instance Semigroup a => Monoid (Maybe a) where
mempty = Nothing
See Data . List . Linear for instance ... = > Monoid [ a ]
Can not add instance Monoid a = > Monoid ( Op a b ) ; would require b
instance Monoid (Proxy a) where
mempty = Proxy
-- Cannot add instance Monoid a => Monoid (ST s a); I think that it would require a linear ST monad
Can not add instance Monoid b = > Monoid ( a - > b ) ; would require Dupable a
instance (Monoid a, Monoid b) => Monoid (a, b) where
mempty = (mempty, mempty)
instance Monoid a => Monoid (Const a b) where
mempty = mempty
See Data . Functor . Linear . Applicative for instance ... = > Monoid ( Ap f a )
-- Cannot add instance Alternative f => Monoid (Alt f a); we don't have a linear Alternative
instance (Monoid a, Monoid b, Monoid c) => Monoid (a, b, c) where
mempty = (mempty, mempty, mempty)
instance (Monoid (f a), Monoid (g a)) => Monoid (Functor.Product f g a) where
mempty = Pair mempty mempty
instance (Monoid a, Monoid b, Monoid c, Monoid d) => Monoid (a, b, c, d) where
mempty = (mempty, mempty, mempty, mempty)
instance Monoid (f (g a)) => Monoid (Functor.Compose f g a) where
mempty = Compose mempty
instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) => Monoid (a, b, c, d, e) where
mempty = (mempty, mempty, mempty, mempty, mempty)
| null | https://raw.githubusercontent.com/tweag/linear-base/3037bf9a44b3b4f22fd0fdc8670e964d97e26a4c/src/Data/Monoid/Linear/Internal/Monoid.hs | haskell | # LANGUAGE LinearTypes #
# OPTIONS_HADDOCK hide #
To learn about how these classic monoids work, go to this school of haskell
[post](-tour).
* Monoid operations
| A linear monoid is a linear semigroup with an identity on the binary
operation.
# MINIMAL mempty #
convenience redefine
-------------
Instances --
-------------
Cannot add instance Monoid a => Monoid (ST s a); I think that it would require a linear ST monad
Cannot add instance Alternative f => Monoid (Alt f a); we don't have a linear Alternative | # LANGUAGE DataKinds #
# LANGUAGE DerivingVia #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -Wno - orphans #
| This module provides linear versions of ' Monoid ' .
module Data.Monoid.Linear.Internal.Monoid
Monoid (..),
mconcat,
mappend,
Can not export Data . Monoid.{First , Last } because of the name clash with Data . , Last }
)
where
import Data.Functor.Compose (Compose (Compose))
import qualified Data.Functor.Compose as Functor
import Data.Functor.Const (Const)
import Data.Functor.Identity (Identity (Identity))
import Data.Functor.Product (Product (Pair))
import qualified Data.Functor.Product as Functor
import qualified Data.Monoid as Monoid
import Data.Monoid.Linear.Internal.Semigroup
import Data.Ord (Down (Down))
import Data.Proxy (Proxy (Proxy))
import Data.Unrestricted.Linear.Internal.Consumable (Consumable)
import GHC.Types hiding (Any)
import Prelude.Linear.Internal
import Prelude (Maybe (Nothing))
import qualified Prelude
Laws ( same as ' Data . Monoid . Monoid ' ):
* ∀ x ∈ G , x < > = < > x = x
class Semigroup a => Monoid a where
mempty :: a
instance (Prelude.Semigroup a, Monoid a) => Prelude.Monoid (NonLinear a) where
mempty = NonLinear mempty
mconcat :: Monoid a => [a] %1 -> a
mconcat (xs' :: [a]) = go mempty xs'
where
go :: a %1 -> [a] %1 -> a
go acc [] = acc
go acc (x : xs) = go (acc <> x) xs
mappend :: Monoid a => a %1 -> a %1 -> a
mappend = (<>)
instance Prelude.Monoid (Endo a) where
mempty = Endo id
Instances below are listed in the same order as in
instance Monoid All where
mempty = All True
instance Monoid Any where
mempty = Any False
instance Monoid Ordering where
mempty = EQ
instance Monoid () where
mempty = ()
instance Monoid a => Monoid (Identity a) where
mempty = Identity mempty
instance Consumable a => Monoid (Monoid.First a) where
mempty = Monoid.First Nothing
instance Consumable a => Monoid (Monoid.Last a) where
mempty = Monoid.Last Nothing
instance Monoid a => Monoid (Down a) where
mempty = Down mempty
Can not add instance ( a , Bounded a ) = > Monoid ( a ) ; would require ( NonLinear . a , Consumable a )
Can not add instance ( a , Bounded a ) = > Monoid ( Min a ) ; would require ( NonLinear . a , Consumable a )
instance Monoid a => Monoid (Dual a) where
mempty = Dual mempty
instance Monoid (Endo a) where
mempty = Endo id
See Data . Num . Linear for instance ... = > Monoid ( Product a )
See Data . Num . Linear for instance ... = > Monoid ( Sum a )
See System . IO.Linear for instance ... = > Monoid ( IO a )
See System . IO.Resource . Internal for instance ... = > Monoid ( RIO a )
instance Semigroup a => Monoid (Maybe a) where
mempty = Nothing
See Data . List . Linear for instance ... = > Monoid [ a ]
Can not add instance Monoid a = > Monoid ( Op a b ) ; would require b
instance Monoid (Proxy a) where
mempty = Proxy
Can not add instance Monoid b = > Monoid ( a - > b ) ; would require Dupable a
instance (Monoid a, Monoid b) => Monoid (a, b) where
mempty = (mempty, mempty)
instance Monoid a => Monoid (Const a b) where
mempty = mempty
See Data . Functor . Linear . Applicative for instance ... = > Monoid ( Ap f a )
instance (Monoid a, Monoid b, Monoid c) => Monoid (a, b, c) where
mempty = (mempty, mempty, mempty)
instance (Monoid (f a), Monoid (g a)) => Monoid (Functor.Product f g a) where
mempty = Pair mempty mempty
instance (Monoid a, Monoid b, Monoid c, Monoid d) => Monoid (a, b, c, d) where
mempty = (mempty, mempty, mempty, mempty)
instance Monoid (f (g a)) => Monoid (Functor.Compose f g a) where
mempty = Compose mempty
instance (Monoid a, Monoid b, Monoid c, Monoid d, Monoid e) => Monoid (a, b, c, d, e) where
mempty = (mempty, mempty, mempty, mempty, mempty)
|
4a5e876d035a1cfcd2f9496dcae7698f0a1d913dd6794af7a3f30be733cc0a01 | jacekschae/learn-reitit-course-files | test_system.clj | (ns cheffy.test-system
(:require [clojure.test :refer :all]
[integrant.repl.state :as state]
[ring.mock.request :as mock]
[muuntaja.core :as m]
[cheffy.auth0 :as auth0]
[clj-http.client :as http]))
(defn get-test-token
[email]
(->> {:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:client_id "ts5NfJYbsIZ6rvhmbKykF9TkWz0tKcGS"
:audience "-reitit-playground.eu.auth0.com/api/v2/"
:grant_type "password"
:username email
:password "s#m3R4nd0m-pass"
:scope "openid profile email"})}
(http/post "-reitit-playground.eu.auth0.com/oauth/token")
(m/decode-response-body)
:access_token))
(defn create-auth0-test-user
[{:keys [connection email password]}]
(->> {:headers {"Authorization" (str "Bearer " (auth0/get-management-token))}
:throw-exceptions false
:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:connection connection
:email email
:password password})}
(http/post "-reitit-playground.eu.auth0.com/api/v2/users")
(m/decode-response-body)))
(def token (atom nil))
(defn test-endpoint
([method uri]
(test-endpoint method uri nil))
([method uri opts]
(let [app (-> state/system :cheffy/app)
request (app (-> (mock/request method uri)
(cond-> (:auth opts) (mock/header :authorization (str "Bearer " (or @token (get-test-token ""))))
(:body opts) (mock/json-body (:body opts)))))]
(update request :body (partial m/decode "application/json")))))
(comment
(let [request (test-endpoint :get "/v1/recipes")
decoded-request (m/decode-response-body request)]
(assoc request :body decoded-request))
(test-endpoint :post "/v1/recipes" {:img "string"
:name "my name"
:prep-time 30})) | null | https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/48-auth0-refactor/test/cheffy/test_system.clj | clojure | (ns cheffy.test-system
(:require [clojure.test :refer :all]
[integrant.repl.state :as state]
[ring.mock.request :as mock]
[muuntaja.core :as m]
[cheffy.auth0 :as auth0]
[clj-http.client :as http]))
(defn get-test-token
[email]
(->> {:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:client_id "ts5NfJYbsIZ6rvhmbKykF9TkWz0tKcGS"
:audience "-reitit-playground.eu.auth0.com/api/v2/"
:grant_type "password"
:username email
:password "s#m3R4nd0m-pass"
:scope "openid profile email"})}
(http/post "-reitit-playground.eu.auth0.com/oauth/token")
(m/decode-response-body)
:access_token))
(defn create-auth0-test-user
[{:keys [connection email password]}]
(->> {:headers {"Authorization" (str "Bearer " (auth0/get-management-token))}
:throw-exceptions false
:content-type :json
:cookie-policy :standard
:body (m/encode "application/json"
{:connection connection
:email email
:password password})}
(http/post "-reitit-playground.eu.auth0.com/api/v2/users")
(m/decode-response-body)))
(def token (atom nil))
(defn test-endpoint
([method uri]
(test-endpoint method uri nil))
([method uri opts]
(let [app (-> state/system :cheffy/app)
request (app (-> (mock/request method uri)
(cond-> (:auth opts) (mock/header :authorization (str "Bearer " (or @token (get-test-token ""))))
(:body opts) (mock/json-body (:body opts)))))]
(update request :body (partial m/decode "application/json")))))
(comment
(let [request (test-endpoint :get "/v1/recipes")
decoded-request (m/decode-response-body request)]
(assoc request :body decoded-request))
(test-endpoint :post "/v1/recipes" {:img "string"
:name "my name"
:prep-time 30})) | |
f35d39e9ce441544765c1e1688e87f8f4d6a3b69102fc8352b8c9f71e456d79d | bobbypriambodo/ocaml-todo-api-example | migrate.ml | let migrate () =
print_endline "creating todos table.";
let%lwt _ =
let module Todos = Todos.Make(Db) in
let%lwt result = Todos.migrate () in
match result with
| Ok () -> print_endline "done." |> Lwt.return
| Error _e -> print_endline "error." |> Lwt.return
in
Lwt.return_unit
let () = Lwt_main.run (migrate ())
| null | https://raw.githubusercontent.com/bobbypriambodo/ocaml-todo-api-example/4b2f660a96b175066fa9cf83e999c45afca2a8dc/bin/migrate.ml | ocaml | let migrate () =
print_endline "creating todos table.";
let%lwt _ =
let module Todos = Todos.Make(Db) in
let%lwt result = Todos.migrate () in
match result with
| Ok () -> print_endline "done." |> Lwt.return
| Error _e -> print_endline "error." |> Lwt.return
in
Lwt.return_unit
let () = Lwt_main.run (migrate ())
| |
f39f863777e22102467922aa3f92cc87f499b1bb8143ce2f56b3d03fb15852c5 | joodie/flutter | html5.clj | (ns flutter.html5
"HTML5 input type support")
(defn wrap-html5-input-fields
"provide html5 input types:
:email :url :range :date :month :week :time :datetime
:datetime-local :search and :color."
[f]
(fn [type attrs name opts value]
(if (#{:email :url :range :date :month
:week :time :datetime :datetime-local
:search :color} type)
(f :input (assoc attrs :type type) name opts value)
(f type attrs name opts value))))
| null | https://raw.githubusercontent.com/joodie/flutter/336e40386ff4e79ce9243ec8690e2a62c41f80a3/src/flutter/html5.clj | clojure | (ns flutter.html5
"HTML5 input type support")
(defn wrap-html5-input-fields
"provide html5 input types:
:email :url :range :date :month :week :time :datetime
:datetime-local :search and :color."
[f]
(fn [type attrs name opts value]
(if (#{:email :url :range :date :month
:week :time :datetime :datetime-local
:search :color} type)
(f :input (assoc attrs :type type) name opts value)
(f type attrs name opts value))))
| |
971054780ec10f607e48c6017d658728859ac52d1bb6a63786fda108298e8d06 | yqrashawn/GokuRakuJoudo | froms_test.clj | (ns karabiner-configurator.froms-test
(:require
[clojure.test :as t]
[karabiner-configurator.data :refer [conf-data init-conf-data update-conf-data]]
[karabiner-configurator.froms :as sut]))
(def example-froms
{:1 {:key :d}
:2 {:key :d :modi :1}
:3 {:key :d :modi :left_command}
:4 {:key :d :modi [:left_command :right_shift]}
:5 {:key :d :modi {:mandatory [:left_command :right_shift]}}
:6 {:key :d :modi {:mandatory [:left_command :right_shift]
:optional [:caps_lock]}}
:7 {:ckey :display_brightness_decrement}
:8 {:ckey :display_brightness_decrement :modi :left_command}
:9 {:pkey :button4 :modi :left_command}
:10 {:sim [:a :b] :modi :left_command}
:11 {:sim [:a :b]
:simo {:interrupt true
:afterup [{:set ["haha" 1]}]
:dorder :insensitive}
:modi :left_command}
:12 {:key :!CSd}
:13 [{:pkey :button5} {:pkey :button2}]})
(def result
{:applications {}
:tos {}
:input-sources {}
:modifiers {:1 {:mandatory ["left_command" "right_shift"]
:optional ["any"]}}
:simlayer-threshold 250
:devices {}
:layers {}
:froms {:12 {:key_code "d"
:modifiers {:mandatory ["left_command" "left_shift"]}}
:11 {:modifiers {:mandatory ["left_command"]}
:simultaneous [{:key_code "a"}
{:key_code "b"}]
:simultaneous_options {:detect_key_down_uninterruptedly true
:key_down_order "insensitive"
:key_up_order "insensitive"
:key_up_when "any"
:to_after_key_up [{:set_variable {:name "haha" :value 1}}]}}
:10 {:modifiers {:mandatory ["left_command"]}
:simultaneous [{:key_code "a"}
{:key_code "b"}]
:simultaneous_options {:detect_key_down_uninterruptedly false
:key_down_order "insensitive"
:key_up_order "insensitive"
:key_up_when "any"}}
:4 {:modifiers {:mandatory ["left_command" "right_shift"]}
:key_code "d"}
:7 {:consumer_key_code "display_brightness_decrement"}
:1 {:key_code "d"}
:8 {:modifiers {:mandatory ["left_command"]}
:consumer_key_code "display_brightness_decrement"}
:9 {:modifiers {:mandatory ["left_command"]}
:pointing_button "button4"}
:2 {:modifiers {:mandatory ["left_command" "right_shift"]
:optional ["any"]}
:key_code "d"}
:5 {:modifiers {:mandatory ["left_command" "right_shift"]}
:key_code "d"}
:3 {:modifiers {:mandatory ["left_command"]}
:key_code "d"}
:6 {:modifiers {:mandatory ["left_command" "right_shift"]
:optional ["caps_lock"]}
:key_code "d"}
:13 {:simultaneous [{:pointing_button "button5"}
{:pointing_button "button2"}]
:simultaneous_options {:detect_key_down_uninterruptedly false
:key_down_order "insensitive"
:key_up_order "insensitive"
:key_up_when "any"}}}
:simlayers {}})
(t/deftest convert-froms
(init-conf-data)
(update-conf-data (assoc @conf-data :modifiers {:1 {:mandatory ["left_command", "right_shift"]
:optional ["any"]}}))
(t/testing
(t/is (= (:froms (sut/generate example-froms)) (:froms result)))))
| null | https://raw.githubusercontent.com/yqrashawn/GokuRakuJoudo/2295ee42923d439ec5c60bb9ff1655becfad273d/test/karabiner_configurator/froms_test.clj | clojure | (ns karabiner-configurator.froms-test
(:require
[clojure.test :as t]
[karabiner-configurator.data :refer [conf-data init-conf-data update-conf-data]]
[karabiner-configurator.froms :as sut]))
(def example-froms
{:1 {:key :d}
:2 {:key :d :modi :1}
:3 {:key :d :modi :left_command}
:4 {:key :d :modi [:left_command :right_shift]}
:5 {:key :d :modi {:mandatory [:left_command :right_shift]}}
:6 {:key :d :modi {:mandatory [:left_command :right_shift]
:optional [:caps_lock]}}
:7 {:ckey :display_brightness_decrement}
:8 {:ckey :display_brightness_decrement :modi :left_command}
:9 {:pkey :button4 :modi :left_command}
:10 {:sim [:a :b] :modi :left_command}
:11 {:sim [:a :b]
:simo {:interrupt true
:afterup [{:set ["haha" 1]}]
:dorder :insensitive}
:modi :left_command}
:12 {:key :!CSd}
:13 [{:pkey :button5} {:pkey :button2}]})
(def result
{:applications {}
:tos {}
:input-sources {}
:modifiers {:1 {:mandatory ["left_command" "right_shift"]
:optional ["any"]}}
:simlayer-threshold 250
:devices {}
:layers {}
:froms {:12 {:key_code "d"
:modifiers {:mandatory ["left_command" "left_shift"]}}
:11 {:modifiers {:mandatory ["left_command"]}
:simultaneous [{:key_code "a"}
{:key_code "b"}]
:simultaneous_options {:detect_key_down_uninterruptedly true
:key_down_order "insensitive"
:key_up_order "insensitive"
:key_up_when "any"
:to_after_key_up [{:set_variable {:name "haha" :value 1}}]}}
:10 {:modifiers {:mandatory ["left_command"]}
:simultaneous [{:key_code "a"}
{:key_code "b"}]
:simultaneous_options {:detect_key_down_uninterruptedly false
:key_down_order "insensitive"
:key_up_order "insensitive"
:key_up_when "any"}}
:4 {:modifiers {:mandatory ["left_command" "right_shift"]}
:key_code "d"}
:7 {:consumer_key_code "display_brightness_decrement"}
:1 {:key_code "d"}
:8 {:modifiers {:mandatory ["left_command"]}
:consumer_key_code "display_brightness_decrement"}
:9 {:modifiers {:mandatory ["left_command"]}
:pointing_button "button4"}
:2 {:modifiers {:mandatory ["left_command" "right_shift"]
:optional ["any"]}
:key_code "d"}
:5 {:modifiers {:mandatory ["left_command" "right_shift"]}
:key_code "d"}
:3 {:modifiers {:mandatory ["left_command"]}
:key_code "d"}
:6 {:modifiers {:mandatory ["left_command" "right_shift"]
:optional ["caps_lock"]}
:key_code "d"}
:13 {:simultaneous [{:pointing_button "button5"}
{:pointing_button "button2"}]
:simultaneous_options {:detect_key_down_uninterruptedly false
:key_down_order "insensitive"
:key_up_order "insensitive"
:key_up_when "any"}}}
:simlayers {}})
(t/deftest convert-froms
(init-conf-data)
(update-conf-data (assoc @conf-data :modifiers {:1 {:mandatory ["left_command", "right_shift"]
:optional ["any"]}}))
(t/testing
(t/is (= (:froms (sut/generate example-froms)) (:froms result)))))
| |
e5759c74c92bc422777c83a145048730a7b12429c23e11e687fc3d13ed748ea9 | mirage/ocaml-cohttp | client_timeout.ml | open Eio
open Cohttp_eio
let () =
Eio_main.run @@ fun env ->
Switch.run @@ fun sw ->
(* Increment/decrement this value to see success/failure. *)
let timeout_s = 0.01 in
Eio.Time.with_timeout env#clock timeout_s (fun () ->
let host, port = ("www.example.org", 80) in
let he = Unix.gethostbyname host in
let addr = `Tcp (Eio_unix.Ipaddr.of_unix he.h_addr_list.(0), port) in
let conn = Net.connect ~sw env#net addr in
let res = Client.get ~conn ~port env ~host "/" in
Client.read_fixed res |> Result.ok)
|> function
| Ok s -> print_string s
| Error `Timeout -> print_string "Connection timed out"
| null | https://raw.githubusercontent.com/mirage/ocaml-cohttp/db2abd0eb526f2826e036ee5d9c6f3d24aa21d25/cohttp-eio/examples/client_timeout.ml | ocaml | Increment/decrement this value to see success/failure. | open Eio
open Cohttp_eio
let () =
Eio_main.run @@ fun env ->
Switch.run @@ fun sw ->
let timeout_s = 0.01 in
Eio.Time.with_timeout env#clock timeout_s (fun () ->
let host, port = ("www.example.org", 80) in
let he = Unix.gethostbyname host in
let addr = `Tcp (Eio_unix.Ipaddr.of_unix he.h_addr_list.(0), port) in
let conn = Net.connect ~sw env#net addr in
let res = Client.get ~conn ~port env ~host "/" in
Client.read_fixed res |> Result.ok)
|> function
| Ok s -> print_string s
| Error `Timeout -> print_string "Connection timed out"
|
97139f8df8d3007795e93762ec189755ab4ddfa2ad6159ac0769b1732fd967e5 | jariazavalverde/blog | MonadExpr.hs | module MonadExpr (
Expr(..),
Parser(..),
expr
) where
import Parser ( Parser(..), sat, char )
import Data.Char ( isDigit )
import Control.Applicative ( Alternative((<|>), some) )
data Expr = K Int
| Add Expr Expr
| Mul Expr Expr
deriving Show
natural :: Parser Expr
natural = K . read <$> some (sat isDigit)
expr :: Parser Expr
expr = do x <- factor
expr' x
expr' :: Expr -> Parser Expr
expr' x = (do char '+'
y <- factor
expr' (Add x y)) <|> return x
factor :: Parser Expr
factor = do x <- term
factor' x
factor' :: Expr -> Parser Expr
factor' x = (do char '*'
y <- term
factor' (Mul x y)) <|> return x
term :: Parser Expr
term = (do char '('
x <- expr
char ')'
return x) <|> natural | null | https://raw.githubusercontent.com/jariazavalverde/blog/c8bbfc4394b077e8f9fc34593344d64f3a94153e/src/analizadores-sintacticos-monadicos/MonadExpr.hs | haskell | module MonadExpr (
Expr(..),
Parser(..),
expr
) where
import Parser ( Parser(..), sat, char )
import Data.Char ( isDigit )
import Control.Applicative ( Alternative((<|>), some) )
data Expr = K Int
| Add Expr Expr
| Mul Expr Expr
deriving Show
natural :: Parser Expr
natural = K . read <$> some (sat isDigit)
expr :: Parser Expr
expr = do x <- factor
expr' x
expr' :: Expr -> Parser Expr
expr' x = (do char '+'
y <- factor
expr' (Add x y)) <|> return x
factor :: Parser Expr
factor = do x <- term
factor' x
factor' :: Expr -> Parser Expr
factor' x = (do char '*'
y <- term
factor' (Mul x y)) <|> return x
term :: Parser Expr
term = (do char '('
x <- expr
char ')'
return x) <|> natural | |
d5a3f1a7f1fee511f0823409649890ef22e652a77cf7be24ff1348033a39573d | ros/roslisp | rosout.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Software License Agreement (BSD License)
;;
Copyright ( c ) 2008 , Willow Garage , Inc.
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with
;; or without modification, are permitted provided that the
;; following conditions are met:
;;
;; * Redistributions of source code must retain the above
;; copyright notice, this list of conditions and the
;; following disclaimer.
;; * Redistributions in binary form must reproduce the
;; above copyright notice, this list of conditions and
;; the following disclaimer in the documentation and/or
;; other materials provided with the distribution.
* Neither the name of Willow Garage , Inc. nor the names
;; of its contributors may be used to endorse or promote
;; products derived from this software without specific
;; prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS " AS IS " AND ANY EXPRESS OR
;; 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :roslisp)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Called by user
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro ros-debug (name &rest args)
"ros-debug NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :debug, output the given format string and arguments to stdout and publish on rosout if possible.
Otherwise do nothing; in particular, don't evaluate the ARGS.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :debug args))
(defmacro ros-info (name &rest args)
"ros-info NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :info, output the given format string and arguments to stdout and publish on rosout if possible.
Otherwise do nothing; in particular, don't evaluate the ARGS.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :info args))
(defmacro ros-warn (name &rest args)
"ros-warn NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :warn, output the given format string and arguments to stdout and publish on rosout if possible.
Otherwise do nothing; in particular, don't evaluate the ARGS.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :warn args))
(defmacro ros-error (name &rest args)
"ros-error NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :error, output the given format string and arguments to stdout and publish on rosout if possible.
Otherwise do nothing; in particular, don't evaluate the ARGS.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :error args))
(defmacro ros-fatal (name &rest args)
"ros-fatal NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :fatal, output the given format string and arguments to stdout and publish on rosout if possible.
Otherwise do nothing; in particular, don't evaluate the ARGS.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :fatal args))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Some standard errors that can be declared now that
;; the macros are defined
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod serialization-length ((msg t))
(ros-error roslisp "Hmm... unexpectedly asked for serialization length of ~w. Most likely because the aforementioned object was found some place where a (nonprimitive) ros message was expected." msg)
42)
| null | https://raw.githubusercontent.com/ros/roslisp/559355a8d695e34e6dedae071a9af2c065411687/src/rosout.lisp | lisp |
Software License Agreement (BSD License)
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.
of its contributors may be used to endorse or promote
products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
LOSS OF USE ,
OR BUSINESS INTERRUPTION ) HOWEVER
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.
Called by user
in particular, don't evaluate the ARGS.
in particular, don't evaluate the ARGS.
in particular, don't evaluate the ARGS.
in particular, don't evaluate the ARGS.
in particular, don't evaluate the ARGS.
Some standard errors that can be declared now that
the macros are defined
| Copyright ( c ) 2008 , Willow Garage , Inc.
* Neither the name of Willow Garage , Inc. nor the names
CONTRIBUTORS " AS IS " AND ANY EXPRESS OR
COPYRIGHT OWNER OR ANY DIRECT ,
INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :roslisp)
(defmacro ros-debug (name &rest args)
"ros-debug NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :debug, output the given format string and arguments to stdout and publish on rosout if possible.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :debug args))
(defmacro ros-info (name &rest args)
"ros-info NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :info, output the given format string and arguments to stdout and publish on rosout if possible.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :info args))
(defmacro ros-warn (name &rest args)
"ros-warn NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :warn, output the given format string and arguments to stdout and publish on rosout if possible.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :warn args))
(defmacro ros-error (name &rest args)
"ros-error NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :error, output the given format string and arguments to stdout and publish on rosout if possible.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :error args))
(defmacro ros-fatal (name &rest args)
"ros-fatal NAME [CONDITION] FORMAT-STRING . ARGS
When CONDITION is true, and the debug level of debug topic NAME is at least :fatal, output the given format string and arguments to stdout and publish on rosout if possible.
CONDITION can be omitted if the FORMAT-STRING is a literal string, in which case it defaults to t."
(rosout-msg name :fatal args))
(defmethod serialization-length ((msg t))
(ros-error roslisp "Hmm... unexpectedly asked for serialization length of ~w. Most likely because the aforementioned object was found some place where a (nonprimitive) ros message was expected." msg)
42)
|
680b6708be8215c735e1bcbb5def7cc1c48d818b4713f794004ed9efd4625c02 | crategus/cl-cffi-gtk | gdk.rgba.lisp | ;;; ----------------------------------------------------------------------------
;;; gdk.rgba.lisp
;;;
The documentation of this file is taken from the 3 Reference Manual
Version 3.24 and modified to document the Lisp binding to the GDK library .
;;; See <>. The API documentation of the Lisp binding is
available from < -cffi-gtk/ > .
;;;
Copyright ( C ) 2012 - 2021
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License for Lisp
as published by the Free Software Foundation , either version 3 of the
;;; License, or (at your option) any later version and with a preamble to
the GNU Lesser General Public License that clarifies the terms for use
;;; with Lisp programs and is referred as the LLGPL.
;;;
;;; 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 and the preamble to the Gnu Lesser
;;; General Public License. If not, see </>
;;; and <>.
;;; ----------------------------------------------------------------------------
;;;
RGBA Colors
;;;
;;; RGBA colors
;;;
;;; Types and Values
;;;
;;; GdkRGBA
;;;
;;; Functions
;;;
;;; gdk_rgba_copy
;;; gdk_rgba_free
;;; gdk_rgba_parse
;;; gdk_rgba_equal
;;; gdk_rgba_hash
;;; gdk_rgba_to_string
;;; ----------------------------------------------------------------------------
(in-package :gdk)
;;; ----------------------------------------------------------------------------
;;; GdkRGBA
;;; ----------------------------------------------------------------------------
(eval-when (:execute :load-toplevel :compile-toplevel)
(foreign-funcall "gdk_rgba_get_type" g-size))
(define-g-boxed-cstruct gdk-rgba "GdkRGBA"
(red :double :initform 0.0d0)
(green :double :initform 0.0d0)
(blue :double :initform 0.0d0)
(alpha :double :initform 0.0d0))
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba atdoc:*class-name-alias*)
"Boxed CStruct"
(documentation 'gdk-rgba 'type)
"@version{2021-1-22}
@begin{short}
The @sym{gdk-rgba} structure is used to represent a (possibly translucent)
color, in a way that is compatible with Cairo's notion of color.
@end{short}
@begin{pre}
(define-g-boxed-cstruct gdk-rgba \"GdkRGBA\"
(red :double :initform 0.0d0)
(green :double :initform 0.0d0)
(blue :double :initform 0.0d0)
(alpha :double :initform 0.0d0))
@end{pre}
@begin[code]{table}
@entry[red]{The intensity of the red channel from 0.0 to 1.0 inclusive.}
@entry[green]{The intensity of the green channel from 0.0 to 1.0 inclusive.}
@entry[blue]{The intensity of the blue channel from 0.0 to 1.0 inclusive.}
@entry[alpha]{The opacity of the color from 0.0 for completely translucent
to 1.0 for opaque.}
@end{table}
@see-slot{gdk-rgba-red}
@see-slot{gdk-rgba-green}
@see-slot{gdk-rgba-blue}
@see-slot{gdk-rgba-alpha}")
(export (boxed-related-symbols 'gdk-rgba))
;;; ----------------------------------------------------------------------------
Accessors
;;; ----------------------------------------------------------------------------
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-red atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-red 'function)
"@version{*2021-1-22}
@syntax[]{(gdk-rgba-red instance) => red}
@syntax[]{(setf (gdk-rgba-red instance) red)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[red]{a double float intensity of the red channel from 0.0 to 1.0}
@begin{short}
Accessor of the @code{red} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-green}
@see-function{gdk-rgba-blue}
@see-function{gdk-rgba-alpha}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-green atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-green 'function)
"@version{*2021-1-22}
@syntax[]{(gdk-rgba-green instance) => green}
@syntax[]{(setf (gdk-rgba-green instance) green)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[green]{a double float intensity of the green channel from 0.0
to 1.0}
@begin{short}
Accessor of the @code{green} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-red}
@see-function{gdk-rgba-blue}
@see-function{gdk-rgba-alpha}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-blue atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-blue 'function)
"@version{*2021-1-22}
@syntax[]{(gdk-rgba-blue instance) => blue}
@syntax[]{(setf (gdk-rgba-blue instance) blue)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[blue]{a double float intensity of the blue channel from 0.0 to 1.0}
@begin{short}
Accessor of the @code{blue} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-red}
@see-function{gdk-rgba-green}
@see-function{gdk-rgba-alpha}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-alpha atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-alpha 'function)
"@version{2021-1-21}
@syntax[]{(gdk-rgba-alpha instance) => alpha}
@syntax[]{(setf (gdk-rgba-alpha instance) alpha)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[alpha]{a double float opacity of the color from 0.0 for completely
translucent to 1.0 for opaque}
@begin{short}
Accessor of the @code{alpha} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-red}
@see-function{gdk-rgba-green}
@see-function{gdk-rgba-blue}")
;;; ----------------------------------------------------------------------------
gdk - rgba - new
;;; ----------------------------------------------------------------------------
(defun gdk-rgba-new (&key (red 0.0d0) (green 0.0d0) (blue 0.0d0) (alpha 0.0d0))
"@version{2021-1-22}
@argument[red]{the double float intensity of the red channel from 0.0
to 1.0 inclusive}
@argument[green]{the double float intensity of the green channel
from 0.0 to 1.0 inclusive}
@argument[blue]{the double float intensity of the blue channel from 0.0
to 1.0 inclusive}
@argument[alpha]{the double float opacity of the color from 0.0 for
completely translucent to 1.0 for opaque}
@begin{short}
Creates a @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-copy}"
(make-gdk-rgba :red (coerce red 'double-float)
:green (coerce green 'double-float)
:blue (coerce blue 'double-float)
:alpha (coerce alpha 'double-float)))
(export 'gdk-rgba-new)
;;; ----------------------------------------------------------------------------
;;; gdk_rgba_copy ()
;;; ----------------------------------------------------------------------------
(defun gdk-rgba-copy (rgba)
#+cl-cffi-gtk-documentation
"@version{2021-1-22}
@argument[rgba]{a @struct{gdk-rgba} color}
@return{A newly allocated @struct{gdk-rgba} color, with the same contents
as @arg{rgba}.}
@short{Makes a copy of a @struct{gdk-rgba} color.}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-new}"
(copy-gdk-rgba rgba))
(export 'gdk-rgba-copy)
;;; ----------------------------------------------------------------------------
;;; gdk_rgba_free ()
;;;
;;; void gdk_rgba_free (GdkRGBA *rgba);
;;;
Frees a GdkRGBA struct created with gdk_rgba_copy ( )
;;;
;;; rgba :
;;; a GdkRGBA
;;; ----------------------------------------------------------------------------
;; not needed
;;; ----------------------------------------------------------------------------
;;; gdk_rgba_parse ()
;;; ----------------------------------------------------------------------------
(defcfun ("gdk_rgba_parse" %gdk-rgba-parse) :boolean
(rgba (g-boxed-foreign gdk-rgba))
(str :string))
(defun gdk-rgba-parse (str)
#+cl-cffi-gtk-documentation
"@version{*2021-12-15}
@argument[str]{a string specifying the color}
@return{A @struct{gdk-rgba} color with the filled in values.}
@begin{short}
Parses a textual representation of a color, and returns a RGBA instance
filling in the @code{red}, @code{green}, @code{blue} and @code{alpha}
fields.
@end{short}
The string can be either one of:
@begin{itemize}
@item{A standard name taken from the X11 @code{rgb.txt} file.}
@item{A hex value in the form @code{rgb}, @code{rrggbb}, @code{rrrgggbbb}
or @code{rrrrggggbbbb}.}
@item{A RGB color in the form @code{rgb(r,g,b)}. In this case the color
will have full opacity.}
@item{A RGBA color in the form @code{rgba(r,g,b,a)}.}
@end{itemize}
Where @code{r}, @code{g}, @code{b} and @code{a} are respectively the red,
green, blue and alpha color values. In the last two cases, @code{r}, @code{g}
and @code{b} are either integers in the range 0 to 255 or precentage values
in the range 0% to 100%, and @code{a} is a floating point value in the range
0.0 to 1.0.
@begin[Example]{dictionary}
@begin{pre}
(gdk-rgba-parse \"LightGreen\")
=> #S(GDK-RGBA
:RED 0.5647058823529412d0
:GREEN 0.9333333333333333d0
:BLUE 0.5647058823529412d0
:ALPHA 1.0d0)
(gdk-rgba-parse \"#90ee90\")
=> #S(GDK-RGBA
:RED 0.5647058823529412d0
:GREEN 0.9333333333333333d0
:BLUE 0.5647058823529412d0
:ALPHA 1.0d0)
@end{pre}
@end{dictionary}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-to-string}"
(let ((rgba (make-gdk-rgba)))
(when (%gdk-rgba-parse rgba str)
rgba)))
(export 'gdk-rgba-parse)
;;; ----------------------------------------------------------------------------
;;; gdk_rgba_equal ()
;;; ----------------------------------------------------------------------------
(defcfun ("gdk_rgba_equal" gdk-rgba-equal) :boolean
#+cl-cffi-gtk-documentation
"@version{2021-1-22}
@argument[color-11]{a @struct{gdk-rgba} color}
@argument[color-2]{another @struct{gdk-rgba} color}
@return{@em{True} if the two colors compare equal.}
@short{Compares two RGBA colors.}
@see-struct{gdk-rgba}"
(color-1 (g-boxed-foreign gdk-rgba))
(color-2 (g-boxed-foreign gdk-rgba)))
(export 'gdk-rgba-equal)
;;; ----------------------------------------------------------------------------
;;; gdk_rgba_hash ()
;;; ----------------------------------------------------------------------------
(defcfun ("gdk_rgba_hash" gdk-rgba-hash) :uint
#+cl-cffi-gtk-documentation
"@version{2021-1-21}
@argument[color]{a @struct{gdk-rgba} color}
@return{An unsigned integer with the hash value for @arg{color}.}
@begin{short}
A hash function suitable for using for a hash table that stores
RGBA colors.
@end{short}
@see-struct{gdk-rgba}"
(color (g-boxed-foreign gdk-rgba)))
(export 'gdk-rgba-hash)
;;; ----------------------------------------------------------------------------
;;; gdk_rgba_to_string ()
;;; ----------------------------------------------------------------------------
(defcfun ("gdk_rgba_to_string" gdk-rgba-to-string) :string
#+cl-cffi-gtk-documentation
"@version{*2021-1-24}
@argument[color]{a @struct{gdk-rgba} color}
@return{A string with the textual specification of @arg{color}.}
@begin{short}
Returns a textual specification of @arg{color} in the form @code{rgb(r,g,b)}
or @code{rgba(r,g,b,a)}, where @code{r}, @code{g}, @code{b} and @code{a}
represent the red, green, blue and alpha values respectively.
@end{short}
@code{r}, @code{g}, and @code{b} are represented as integers in the range 0
to 255, and @code{a} is represented as a floating point value in the range
0.0 to 1.0.
These string forms are supported by the CSS3 colors module, and can be parsed
by the function @fun{gdk-rgba-parse}.
Note that this string representation may loose some precision, since @code{r},
@code{g} and @code{b} are represented as 8-bit integers. If this is a concern,
you should use a different representation.
@begin[Example]{dictionary}
@begin{pre}
(gdk-rgba-to-string (gdk-rgba-new :red 1.0))
=> \"rgba(255,0,0,0)\"
(gdk-rgba-parse *)
=> #S(GDK-RGBA :RED 1.0d0 :GREEN 0.0d0 :BLUE 0.0d0 :ALPHA 0.0d0)
@end{pre}
@end{dictionary}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-parse}"
(color (g-boxed-foreign gdk-rgba)))
(export 'gdk-rgba-to-string)
;;; --- End of file gdk.rgba.lisp ----------------------------------------------
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/gdk/gdk.rgba.lisp | lisp | ----------------------------------------------------------------------------
gdk.rgba.lisp
See <>. The API documentation of the Lisp binding is
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License for Lisp
License, or (at your option) any later version and with a preamble to
with Lisp programs and is referred as the LLGPL.
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
General Public License. If not, see </>
and <>.
----------------------------------------------------------------------------
RGBA colors
Types and Values
GdkRGBA
Functions
gdk_rgba_copy
gdk_rgba_free
gdk_rgba_parse
gdk_rgba_equal
gdk_rgba_hash
gdk_rgba_to_string
----------------------------------------------------------------------------
----------------------------------------------------------------------------
GdkRGBA
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gdk_rgba_copy ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gdk_rgba_free ()
void gdk_rgba_free (GdkRGBA *rgba);
rgba :
a GdkRGBA
----------------------------------------------------------------------------
not needed
----------------------------------------------------------------------------
gdk_rgba_parse ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gdk_rgba_equal ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gdk_rgba_hash ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gdk_rgba_to_string ()
----------------------------------------------------------------------------
--- End of file gdk.rgba.lisp ---------------------------------------------- | The documentation of this file is taken from the 3 Reference Manual
Version 3.24 and modified to document the Lisp binding to the GDK library .
available from < -cffi-gtk/ > .
Copyright ( C ) 2012 - 2021
as published by the Free Software Foundation , either version 3 of the
the GNU Lesser General Public License that clarifies the terms for use
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 and the preamble to the Gnu Lesser
RGBA Colors
(in-package :gdk)
(eval-when (:execute :load-toplevel :compile-toplevel)
(foreign-funcall "gdk_rgba_get_type" g-size))
(define-g-boxed-cstruct gdk-rgba "GdkRGBA"
(red :double :initform 0.0d0)
(green :double :initform 0.0d0)
(blue :double :initform 0.0d0)
(alpha :double :initform 0.0d0))
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba atdoc:*class-name-alias*)
"Boxed CStruct"
(documentation 'gdk-rgba 'type)
"@version{2021-1-22}
@begin{short}
The @sym{gdk-rgba} structure is used to represent a (possibly translucent)
color, in a way that is compatible with Cairo's notion of color.
@end{short}
@begin{pre}
(define-g-boxed-cstruct gdk-rgba \"GdkRGBA\"
(red :double :initform 0.0d0)
(green :double :initform 0.0d0)
(blue :double :initform 0.0d0)
(alpha :double :initform 0.0d0))
@end{pre}
@begin[code]{table}
@entry[red]{The intensity of the red channel from 0.0 to 1.0 inclusive.}
@entry[green]{The intensity of the green channel from 0.0 to 1.0 inclusive.}
@entry[blue]{The intensity of the blue channel from 0.0 to 1.0 inclusive.}
@entry[alpha]{The opacity of the color from 0.0 for completely translucent
to 1.0 for opaque.}
@end{table}
@see-slot{gdk-rgba-red}
@see-slot{gdk-rgba-green}
@see-slot{gdk-rgba-blue}
@see-slot{gdk-rgba-alpha}")
(export (boxed-related-symbols 'gdk-rgba))
Accessors
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-red atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-red 'function)
"@version{*2021-1-22}
@syntax[]{(gdk-rgba-red instance) => red}
@syntax[]{(setf (gdk-rgba-red instance) red)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[red]{a double float intensity of the red channel from 0.0 to 1.0}
@begin{short}
Accessor of the @code{red} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-green}
@see-function{gdk-rgba-blue}
@see-function{gdk-rgba-alpha}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-green atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-green 'function)
"@version{*2021-1-22}
@syntax[]{(gdk-rgba-green instance) => green}
@syntax[]{(setf (gdk-rgba-green instance) green)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[green]{a double float intensity of the green channel from 0.0
to 1.0}
@begin{short}
Accessor of the @code{green} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-red}
@see-function{gdk-rgba-blue}
@see-function{gdk-rgba-alpha}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-blue atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-blue 'function)
"@version{*2021-1-22}
@syntax[]{(gdk-rgba-blue instance) => blue}
@syntax[]{(setf (gdk-rgba-blue instance) blue)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[blue]{a double float intensity of the blue channel from 0.0 to 1.0}
@begin{short}
Accessor of the @code{blue} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-red}
@see-function{gdk-rgba-green}
@see-function{gdk-rgba-alpha}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gdk-rgba-alpha atdoc:*function-name-alias*)
"Accessor"
(documentation 'gdk-rgba-alpha 'function)
"@version{2021-1-21}
@syntax[]{(gdk-rgba-alpha instance) => alpha}
@syntax[]{(setf (gdk-rgba-alpha instance) alpha)}
@argument[instance]{a @struct{gdk-rgba} color}
@argument[alpha]{a double float opacity of the color from 0.0 for completely
translucent to 1.0 for opaque}
@begin{short}
Accessor of the @code{alpha} slot of the @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-red}
@see-function{gdk-rgba-green}
@see-function{gdk-rgba-blue}")
gdk - rgba - new
(defun gdk-rgba-new (&key (red 0.0d0) (green 0.0d0) (blue 0.0d0) (alpha 0.0d0))
"@version{2021-1-22}
@argument[red]{the double float intensity of the red channel from 0.0
to 1.0 inclusive}
@argument[green]{the double float intensity of the green channel
from 0.0 to 1.0 inclusive}
@argument[blue]{the double float intensity of the blue channel from 0.0
to 1.0 inclusive}
@argument[alpha]{the double float opacity of the color from 0.0 for
completely translucent to 1.0 for opaque}
@begin{short}
Creates a @struct{gdk-rgba} color.
@end{short}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-copy}"
(make-gdk-rgba :red (coerce red 'double-float)
:green (coerce green 'double-float)
:blue (coerce blue 'double-float)
:alpha (coerce alpha 'double-float)))
(export 'gdk-rgba-new)
(defun gdk-rgba-copy (rgba)
#+cl-cffi-gtk-documentation
"@version{2021-1-22}
@argument[rgba]{a @struct{gdk-rgba} color}
@return{A newly allocated @struct{gdk-rgba} color, with the same contents
as @arg{rgba}.}
@short{Makes a copy of a @struct{gdk-rgba} color.}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-new}"
(copy-gdk-rgba rgba))
(export 'gdk-rgba-copy)
Frees a GdkRGBA struct created with gdk_rgba_copy ( )
(defcfun ("gdk_rgba_parse" %gdk-rgba-parse) :boolean
(rgba (g-boxed-foreign gdk-rgba))
(str :string))
(defun gdk-rgba-parse (str)
#+cl-cffi-gtk-documentation
"@version{*2021-12-15}
@argument[str]{a string specifying the color}
@return{A @struct{gdk-rgba} color with the filled in values.}
@begin{short}
Parses a textual representation of a color, and returns a RGBA instance
filling in the @code{red}, @code{green}, @code{blue} and @code{alpha}
fields.
@end{short}
The string can be either one of:
@begin{itemize}
@item{A standard name taken from the X11 @code{rgb.txt} file.}
@item{A hex value in the form @code{rgb}, @code{rrggbb}, @code{rrrgggbbb}
or @code{rrrrggggbbbb}.}
@item{A RGB color in the form @code{rgb(r,g,b)}. In this case the color
will have full opacity.}
@item{A RGBA color in the form @code{rgba(r,g,b,a)}.}
@end{itemize}
Where @code{r}, @code{g}, @code{b} and @code{a} are respectively the red,
green, blue and alpha color values. In the last two cases, @code{r}, @code{g}
and @code{b} are either integers in the range 0 to 255 or precentage values
in the range 0% to 100%, and @code{a} is a floating point value in the range
0.0 to 1.0.
@begin[Example]{dictionary}
@begin{pre}
(gdk-rgba-parse \"LightGreen\")
=> #S(GDK-RGBA
:RED 0.5647058823529412d0
:GREEN 0.9333333333333333d0
:BLUE 0.5647058823529412d0
:ALPHA 1.0d0)
(gdk-rgba-parse \"#90ee90\")
=> #S(GDK-RGBA
:RED 0.5647058823529412d0
:GREEN 0.9333333333333333d0
:BLUE 0.5647058823529412d0
:ALPHA 1.0d0)
@end{pre}
@end{dictionary}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-to-string}"
(let ((rgba (make-gdk-rgba)))
(when (%gdk-rgba-parse rgba str)
rgba)))
(export 'gdk-rgba-parse)
(defcfun ("gdk_rgba_equal" gdk-rgba-equal) :boolean
#+cl-cffi-gtk-documentation
"@version{2021-1-22}
@argument[color-11]{a @struct{gdk-rgba} color}
@argument[color-2]{another @struct{gdk-rgba} color}
@return{@em{True} if the two colors compare equal.}
@short{Compares two RGBA colors.}
@see-struct{gdk-rgba}"
(color-1 (g-boxed-foreign gdk-rgba))
(color-2 (g-boxed-foreign gdk-rgba)))
(export 'gdk-rgba-equal)
(defcfun ("gdk_rgba_hash" gdk-rgba-hash) :uint
#+cl-cffi-gtk-documentation
"@version{2021-1-21}
@argument[color]{a @struct{gdk-rgba} color}
@return{An unsigned integer with the hash value for @arg{color}.}
@begin{short}
A hash function suitable for using for a hash table that stores
RGBA colors.
@end{short}
@see-struct{gdk-rgba}"
(color (g-boxed-foreign gdk-rgba)))
(export 'gdk-rgba-hash)
(defcfun ("gdk_rgba_to_string" gdk-rgba-to-string) :string
#+cl-cffi-gtk-documentation
"@version{*2021-1-24}
@argument[color]{a @struct{gdk-rgba} color}
@return{A string with the textual specification of @arg{color}.}
@begin{short}
Returns a textual specification of @arg{color} in the form @code{rgb(r,g,b)}
or @code{rgba(r,g,b,a)}, where @code{r}, @code{g}, @code{b} and @code{a}
represent the red, green, blue and alpha values respectively.
@end{short}
@code{r}, @code{g}, and @code{b} are represented as integers in the range 0
to 255, and @code{a} is represented as a floating point value in the range
0.0 to 1.0.
These string forms are supported by the CSS3 colors module, and can be parsed
by the function @fun{gdk-rgba-parse}.
Note that this string representation may loose some precision, since @code{r},
@code{g} and @code{b} are represented as 8-bit integers. If this is a concern,
you should use a different representation.
@begin[Example]{dictionary}
@begin{pre}
(gdk-rgba-to-string (gdk-rgba-new :red 1.0))
=> \"rgba(255,0,0,0)\"
(gdk-rgba-parse *)
=> #S(GDK-RGBA :RED 1.0d0 :GREEN 0.0d0 :BLUE 0.0d0 :ALPHA 0.0d0)
@end{pre}
@end{dictionary}
@see-struct{gdk-rgba}
@see-function{gdk-rgba-parse}"
(color (g-boxed-foreign gdk-rgba)))
(export 'gdk-rgba-to-string)
|
4b4ab2d1864d8e3f96539d6fa46fbca30a1a96ee69cd17c3dbb69dc281c307c6 | blindglobe/clocc | package.lisp | -*- Mode : Lisp ; Package : USER ; Syntax : COMMON - LISP ; ; Lowercase : T -*-
;;;----------------------------------------------------------------------------------+
;;; |
;;; TEXAS INSTRUMENTS INCORPORATED |
P.O. BOX 149149 |
, TEXAS 78714 - 9149 |
;;; |
Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . |
;;; |
;;; Permission is granted to any individual or institution to use, copy, modify, and |
;;; distribute this software, provided that this complete copyright and permission |
;;; notice is maintained, intact, in all copies and supporting documentation. |
;;; |
Texas Instruments Incorporated provides this software " as is " without express or |
;;; implied warranty. |
;;; |
;;;----------------------------------------------------------------------------------+
(in-package "USER")
(unless (find-package "CLIO-EXAMPLES")
(make-package "CLIO-EXAMPLES" :use '(common-lisp xlib
#-ANSI-CL clos
clue clio-open)))
| null | https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/clio/examples/package.lisp | lisp | Package : USER ; Syntax : COMMON - LISP ; ; Lowercase : T -*-
----------------------------------------------------------------------------------+
|
TEXAS INSTRUMENTS INCORPORATED |
|
|
Permission is granted to any individual or institution to use, copy, modify, and |
distribute this software, provided that this complete copyright and permission |
notice is maintained, intact, in all copies and supporting documentation. |
|
implied warranty. |
|
----------------------------------------------------------------------------------+ |
P.O. BOX 149149 |
, TEXAS 78714 - 9149 |
Copyright ( C ) 1989 , 1990 Texas Instruments Incorporated . |
Texas Instruments Incorporated provides this software " as is " without express or |
(in-package "USER")
(unless (find-package "CLIO-EXAMPLES")
(make-package "CLIO-EXAMPLES" :use '(common-lisp xlib
#-ANSI-CL clos
clue clio-open)))
|
cbdb6906f376443100bbc8a1a97f8cce9f38418eb19918cdcb551d64f69a74f7 | orthecreedence/ghostie | matrix.lisp | (in-package :ghostie-util)
(defun nanp (v)
"Make sure our matrices aren't getting infinity values."
(not (ignore-errors (mod v 360))))
(defun id-matrix (dims)
(let ((array (make-array (* dims dims) :initial-element 0.0 :element-type 'single-float)))
(dotimes (d dims)
(setf (aref array (* d (1+ dims))) 1.0))
array))
(defun mat* (m1 m2)
(let ((new (make-array 16 :initial-element 0.0 :element-type 'single-float)))
(dotimes (x 4)
(dotimes (y 4)
(let ((prod (+ (* (aref m1 (* x 4)) (aref m2 y))
(* (aref m1 (+ (* x 4) 1)) (aref m2 (+ y 4)))
(* (aref m1 (+ (* x 4) 2)) (aref m2 (+ y 8)))
(* (aref m1 (+ (* x 4) 3)) (aref m2 (+ y 12))))))
(setf (aref new (+ y (* x 4))) (coerce prod 'single-float)))))
new))
(defun m-perspective (fov aspect z-near z-far)
(let* ((xymax (* z-near (tan (* fov 0.00872664625))))
(ymin (- xymax))
(xmin (- xymax))
(width (- xymax xmin))
(height (- xymax ymin))
(depth (- z-far z-near))
(q (/ (- (+ z-far z-near)) depth))
(qn (/ (* -2 z-far z-near) depth))
(w (/ (/ (* 2 z-near) width) aspect))
(h (/ (* 2 z-near) height))
(matrix (make-array 16 :initial-element 0.0 :element-type 'single-float)))
(setf (aref matrix 0) w
(aref matrix 5) h
(aref matrix 10) q
(aref matrix 11) -1.0
(aref matrix 14) qn)
matrix))
(defun m-ortho (left right bottom top z-near z-far)
(let* ((tx (/ (+ right left) (- right left)))
(ty (/ (+ top bottom) (- top bottom)))
(tz (/ (+ z-near z-far) (- z-far z-near)))
(matrix (id-matrix 4)))
(setf (aref matrix 0) (coerce (/ 2 (- right left)) 'single-float)
(aref matrix 3) (coerce tx 'single-float)
(aref matrix 5) (coerce (/ 2 (- top bottom)) 'single-float)
(aref matrix 7) (coerce ty 'single-float)
(aref matrix 10) (coerce (/ -2 (- z-far z-near)) 'single-float)
(aref matrix 11) (coerce tz 'single-float))
matrix))
(defun m-rotate (x y z theta &key degrees)
(when (nanp theta)
(return-from m-rotate (id-matrix 4)))
(let* ((matrix (id-matrix 4))
(angle-rad (if degrees (* (mod theta 360) (/ 3.14159 180)) theta))
(x2 (* x x))
(y2 (* y y))
(z2 (* z z))
(cos (coerce (cos angle-rad) 'double-float))
(sin (coerce (sin angle-rad) 'double-float))
(icos (- 1 cos))
(icos-xy (* icos x y))
(icos-xz (* icos x z))
(icos-yz (* icos y z))
(x-sin (* x sin))
(y-sin (* y sin))
(z-sin (* z sin)))
(setf (aref matrix 0) (coerce (+ (* x2 icos) cos) 'single-float)
(aref matrix 1) (coerce (- icos-xy z-sin) 'single-float)
(aref matrix 2) (coerce (+ icos-xz y-sin) 'single-float)
(aref matrix 4) (coerce (+ icos-xy z-sin) 'single-float)
(aref matrix 5) (coerce (+ (* y2 icos) cos) 'single-float)
(aref matrix 6) (coerce (- icos-yz x-sin) 'single-float)
(aref matrix 8) (coerce (- icos-xz y-sin) 'single-float)
(aref matrix 9) (coerce (+ icos-yz x-sin) 'single-float)
(aref matrix 10) (coerce (+ (* z2 icos) cos) 'single-float))
matrix))
(defun m-scale (x y z)
(let ((matrix (id-matrix 4)))
(setf (aref matrix 0) (coerce x 'single-float)
(aref matrix 5) (coerce y 'single-float)
(aref matrix 10) (coerce z 'single-float))
matrix))
(defun m-translate (x y z)
(let ((translatrix (id-matrix 4)))
(setf (aref translatrix 12) (coerce x 'single-float)
(aref translatrix 13) (coerce y 'single-float)
(aref translatrix 14) (coerce z 'single-float))
translatrix))
| null | https://raw.githubusercontent.com/orthecreedence/ghostie/6e6f77e1f33511d5311319db4656960de1c6f668/lib/matrix.lisp | lisp | (in-package :ghostie-util)
(defun nanp (v)
"Make sure our matrices aren't getting infinity values."
(not (ignore-errors (mod v 360))))
(defun id-matrix (dims)
(let ((array (make-array (* dims dims) :initial-element 0.0 :element-type 'single-float)))
(dotimes (d dims)
(setf (aref array (* d (1+ dims))) 1.0))
array))
(defun mat* (m1 m2)
(let ((new (make-array 16 :initial-element 0.0 :element-type 'single-float)))
(dotimes (x 4)
(dotimes (y 4)
(let ((prod (+ (* (aref m1 (* x 4)) (aref m2 y))
(* (aref m1 (+ (* x 4) 1)) (aref m2 (+ y 4)))
(* (aref m1 (+ (* x 4) 2)) (aref m2 (+ y 8)))
(* (aref m1 (+ (* x 4) 3)) (aref m2 (+ y 12))))))
(setf (aref new (+ y (* x 4))) (coerce prod 'single-float)))))
new))
(defun m-perspective (fov aspect z-near z-far)
(let* ((xymax (* z-near (tan (* fov 0.00872664625))))
(ymin (- xymax))
(xmin (- xymax))
(width (- xymax xmin))
(height (- xymax ymin))
(depth (- z-far z-near))
(q (/ (- (+ z-far z-near)) depth))
(qn (/ (* -2 z-far z-near) depth))
(w (/ (/ (* 2 z-near) width) aspect))
(h (/ (* 2 z-near) height))
(matrix (make-array 16 :initial-element 0.0 :element-type 'single-float)))
(setf (aref matrix 0) w
(aref matrix 5) h
(aref matrix 10) q
(aref matrix 11) -1.0
(aref matrix 14) qn)
matrix))
(defun m-ortho (left right bottom top z-near z-far)
(let* ((tx (/ (+ right left) (- right left)))
(ty (/ (+ top bottom) (- top bottom)))
(tz (/ (+ z-near z-far) (- z-far z-near)))
(matrix (id-matrix 4)))
(setf (aref matrix 0) (coerce (/ 2 (- right left)) 'single-float)
(aref matrix 3) (coerce tx 'single-float)
(aref matrix 5) (coerce (/ 2 (- top bottom)) 'single-float)
(aref matrix 7) (coerce ty 'single-float)
(aref matrix 10) (coerce (/ -2 (- z-far z-near)) 'single-float)
(aref matrix 11) (coerce tz 'single-float))
matrix))
(defun m-rotate (x y z theta &key degrees)
(when (nanp theta)
(return-from m-rotate (id-matrix 4)))
(let* ((matrix (id-matrix 4))
(angle-rad (if degrees (* (mod theta 360) (/ 3.14159 180)) theta))
(x2 (* x x))
(y2 (* y y))
(z2 (* z z))
(cos (coerce (cos angle-rad) 'double-float))
(sin (coerce (sin angle-rad) 'double-float))
(icos (- 1 cos))
(icos-xy (* icos x y))
(icos-xz (* icos x z))
(icos-yz (* icos y z))
(x-sin (* x sin))
(y-sin (* y sin))
(z-sin (* z sin)))
(setf (aref matrix 0) (coerce (+ (* x2 icos) cos) 'single-float)
(aref matrix 1) (coerce (- icos-xy z-sin) 'single-float)
(aref matrix 2) (coerce (+ icos-xz y-sin) 'single-float)
(aref matrix 4) (coerce (+ icos-xy z-sin) 'single-float)
(aref matrix 5) (coerce (+ (* y2 icos) cos) 'single-float)
(aref matrix 6) (coerce (- icos-yz x-sin) 'single-float)
(aref matrix 8) (coerce (- icos-xz y-sin) 'single-float)
(aref matrix 9) (coerce (+ icos-yz x-sin) 'single-float)
(aref matrix 10) (coerce (+ (* z2 icos) cos) 'single-float))
matrix))
(defun m-scale (x y z)
(let ((matrix (id-matrix 4)))
(setf (aref matrix 0) (coerce x 'single-float)
(aref matrix 5) (coerce y 'single-float)
(aref matrix 10) (coerce z 'single-float))
matrix))
(defun m-translate (x y z)
(let ((translatrix (id-matrix 4)))
(setf (aref translatrix 12) (coerce x 'single-float)
(aref translatrix 13) (coerce y 'single-float)
(aref translatrix 14) (coerce z 'single-float))
translatrix))
| |
f156b3fb5e72de8675264658eaa5033040571c5c54356024d9936ed84e627ae6 | richardharrington/robotwar | handler.clj | (ns robotwar.handler
(:use [clojure.string :only [split]]
[robotwar.constants])
(:require [ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[ring.middleware.file :refer [wrap-file]]
[ring.middleware.params :refer [wrap-params]]
[ring.util.response :refer [response not-found]]
[robotwar.source-programs :as source-programs]
[robotwar.world :as world]
[robotwar.browser :as browser]
[compojure.core :refer :all]
[compojure.route :as route]))
(def game-info {:ROBOT-RADIUS ROBOT-RADIUS
:ROBOT-RANGE-X ROBOT-RANGE-X
:ROBOT-RANGE-Y ROBOT-RANGE-Y
:*GAME-SECONDS-PER-TICK* *GAME-SECONDS-PER-TICK*})
(defn parse-program-names
"takes a string parameter from the browser and returns a sequence
of program keys"
[programs-str]
(map keyword (split programs-str #"[,\s]+")))
(defn get-programs
"gets a sequence of five programs from the source-code repository."
[program-keys]
(->> program-keys
(map source-programs/programs)
(remove nil?)
(take 5)))
(defn add-game
"a function to update the games-store atom state.
It keeps a running store of games, which is added
to upon request from a browser, who is then
assigned an id number"
[{:keys [next-id games]} programs-str]
(let [program-names (parse-program-names programs-str)
programs (get-programs program-names)
world (world/init-world programs)
combined-worlds (world/build-combined-worlds world)
worlds-for-browser (browser/worlds-for-browser combined-worlds)]
{:games (merge games {next-id worlds-for-browser})
:next-id (inc next-id)}))
(defn take-drop-send
"takes the games-store atom, a game id, and a number n,
and returns a collection of the first n items from that game,
then drops those items from the game in the atom's state."
[games-store id n]
(let [coll (get-in @games-store [:games id])]
(swap! games-store #(assoc-in % [:games id] (drop n coll)))
(take n coll)))
(def games-store (atom {:next-id 0
:games {}}))
(defroutes my-routes
(GET "/worlds/:id/:n" [id n]
(response
(take-drop-send
games-store
(Integer/parseInt id)
(Integer/parseInt n))))
(GET "/program-names" []
(response
{:names (map name (keys source-programs/programs))}))
(GET "/init" {{programs "programs"} :params}
(println "in init")
(println (str programs))
(swap! games-store add-game programs)
(response {:id (:next-id @games-store)
:game-info game-info})))
;
( defn handler [ { : keys [ uri query - params request - method ] : as request } ]
; (let [route (fn [acceptable-request-method re action]
; (when (= request-method acceptable-request-method)
; (when-let [[_ & url-params] (consistently-typed-re-matches re uri)]
; (apply action url-params))))]
; (or
( route : get # " ) "
; (fn [id n]
; (response (take-drop-send
; games-store
; (Integer/parseInt id)
; (Integer/parseInt n)))))
; (route :get #"\/program-names"
; (fn []
; (response
; {:names (map name (keys source-programs/programs))})))
( route : get # " \/init "
; (fn []
; (let [programs (query-params "programs")
; next-id (:next-id @games-store)]
; (swap! games-store add-game programs)
; (response {:id next-id
; :game-info game-info}))))
; (not-found "Not Found"))))
(def app
(-> my-routes
(wrap-file "public")
(wrap-json-response)
(wrap-json-body)
(wrap-params)))
| null | https://raw.githubusercontent.com/richardharrington/robotwar/5885ecc7b26e574a405d5aa137e8a16966011594/src/robotwar/handler.clj | clojure |
(let [route (fn [acceptable-request-method re action]
(when (= request-method acceptable-request-method)
(when-let [[_ & url-params] (consistently-typed-re-matches re uri)]
(apply action url-params))))]
(or
(fn [id n]
(response (take-drop-send
games-store
(Integer/parseInt id)
(Integer/parseInt n)))))
(route :get #"\/program-names"
(fn []
(response
{:names (map name (keys source-programs/programs))})))
(fn []
(let [programs (query-params "programs")
next-id (:next-id @games-store)]
(swap! games-store add-game programs)
(response {:id next-id
:game-info game-info}))))
(not-found "Not Found")))) | (ns robotwar.handler
(:use [clojure.string :only [split]]
[robotwar.constants])
(:require [ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[ring.middleware.file :refer [wrap-file]]
[ring.middleware.params :refer [wrap-params]]
[ring.util.response :refer [response not-found]]
[robotwar.source-programs :as source-programs]
[robotwar.world :as world]
[robotwar.browser :as browser]
[compojure.core :refer :all]
[compojure.route :as route]))
(def game-info {:ROBOT-RADIUS ROBOT-RADIUS
:ROBOT-RANGE-X ROBOT-RANGE-X
:ROBOT-RANGE-Y ROBOT-RANGE-Y
:*GAME-SECONDS-PER-TICK* *GAME-SECONDS-PER-TICK*})
(defn parse-program-names
"takes a string parameter from the browser and returns a sequence
of program keys"
[programs-str]
(map keyword (split programs-str #"[,\s]+")))
(defn get-programs
"gets a sequence of five programs from the source-code repository."
[program-keys]
(->> program-keys
(map source-programs/programs)
(remove nil?)
(take 5)))
(defn add-game
"a function to update the games-store atom state.
It keeps a running store of games, which is added
to upon request from a browser, who is then
assigned an id number"
[{:keys [next-id games]} programs-str]
(let [program-names (parse-program-names programs-str)
programs (get-programs program-names)
world (world/init-world programs)
combined-worlds (world/build-combined-worlds world)
worlds-for-browser (browser/worlds-for-browser combined-worlds)]
{:games (merge games {next-id worlds-for-browser})
:next-id (inc next-id)}))
(defn take-drop-send
"takes the games-store atom, a game id, and a number n,
and returns a collection of the first n items from that game,
then drops those items from the game in the atom's state."
[games-store id n]
(let [coll (get-in @games-store [:games id])]
(swap! games-store #(assoc-in % [:games id] (drop n coll)))
(take n coll)))
(def games-store (atom {:next-id 0
:games {}}))
(defroutes my-routes
(GET "/worlds/:id/:n" [id n]
(response
(take-drop-send
games-store
(Integer/parseInt id)
(Integer/parseInt n))))
(GET "/program-names" []
(response
{:names (map name (keys source-programs/programs))}))
(GET "/init" {{programs "programs"} :params}
(println "in init")
(println (str programs))
(swap! games-store add-game programs)
(response {:id (:next-id @games-store)
:game-info game-info})))
( defn handler [ { : keys [ uri query - params request - method ] : as request } ]
( route : get # " ) "
( route : get # " \/init "
(def app
(-> my-routes
(wrap-file "public")
(wrap-json-response)
(wrap-json-body)
(wrap-params)))
|
41c248efb98342c23c528b43c2599f350282fe9a36ef4f1fec6a5ed2314aa61a | cmerrick/plainview | project.clj | (defproject plainview "0.1.0-SNAPSHOT"
:description "A toolkit for building a data pipeline from your database's binary log stream."
:url ""
:license {:name "Apache License, Version 2.0"
:url "-2.0.html"}
:repositories [["conjars" {:url ""}]]
:source-paths ["src/clj"]
:test-paths ["test/clj/"]
:java-source-paths ["src/java"]
:dependencies [[org.clojure/clojure "1.5.0"]
[open-replicator/open-replicator "1.0.5"]
[org.apache.hadoop/hadoop-core "1.1.2"]
[cascading/cascading-hadoop "2.5.3"]
[cascading/cascading-local "2.5.3"]
[cascading.gmarabout/cascading-json "0.0.3"]
[cheshire "5.3.1"]
[org.clojure/tools.cli "0.3.1"]
[midje "1.6.3"]
[amazonica "0.2.10"]
[cascalog "2.0.0"]]
:plugins [[lein-midje "3.0.1"]])
| null | https://raw.githubusercontent.com/cmerrick/plainview/388f9c0f63f1d0b4cb23bf7f5f0775d6c1e0f39c/project.clj | clojure | (defproject plainview "0.1.0-SNAPSHOT"
:description "A toolkit for building a data pipeline from your database's binary log stream."
:url ""
:license {:name "Apache License, Version 2.0"
:url "-2.0.html"}
:repositories [["conjars" {:url ""}]]
:source-paths ["src/clj"]
:test-paths ["test/clj/"]
:java-source-paths ["src/java"]
:dependencies [[org.clojure/clojure "1.5.0"]
[open-replicator/open-replicator "1.0.5"]
[org.apache.hadoop/hadoop-core "1.1.2"]
[cascading/cascading-hadoop "2.5.3"]
[cascading/cascading-local "2.5.3"]
[cascading.gmarabout/cascading-json "0.0.3"]
[cheshire "5.3.1"]
[org.clojure/tools.cli "0.3.1"]
[midje "1.6.3"]
[amazonica "0.2.10"]
[cascalog "2.0.0"]]
:plugins [[lein-midje "3.0.1"]])
| |
a95efe07d5431a6bf4ba0df54cc9364e4244ca9d813b11c9951726e1b98147ee | soegaard/pyffi | python-more-builtins.rkt | #lang racket/base
(require "structs.rkt"
"python-c-api.rkt"
"python-delayed.rkt"
"python-define-delayed.rkt"
"python-environment.rkt"
"python-evaluation.rkt"
"python-initialization.rkt"
"python-types.rkt"
"python-attributes.rkt"
"python-builtins.rkt"
"python-functions.rkt"
"python-operators.rkt"
racket/format
racket/list
racket/match)
(require (for-syntax racket/base
racket/syntax
syntax/parse))
(define (simple-proc name qualified-name
positional-parameters
keyword-parameters
#:object-type-str [object-type-str "fun"]
#:positional-excess [positional-excess #f]
#:keyword-excess [keyword-excess #f]
#:positional-types [positional-types #f]
#:keyword-types [keyword-types #f]
#:first-optional [first-optional #f]
#:result-type [result-type #f])
(define object (obj object-type-str (get qualified-name)))
(set! name (~a name)) ; allow symbol
(set! positional-parameters (map ~a positional-parameters)) ; allow symbols
(set! keyword-parameters (map ~a keyword-parameters)) ; allow symbols
(when positional-excess
(set! positional-excess (~a positional-excess))) ; allow symbol
(when keyword-excess
(set! keyword-excess (~a keyword-excess))) ; allow symbol
(unless positional-types
(set! positional-types (make-list (length positional-parameters) #f)))
(unless keyword-types
(set! keyword-types (make-list (length keyword-parameters) #f)))
(pyproc object name qualified-name
positional-parameters positional-types positional-excess
keyword-parameters keyword-types keyword-excess
first-optional result-type))
(define (simple-builtin name qualified-name
positional-parameters
keyword-parameters
#:positional-excess [positional-excess #f]
#:keyword-excess [keyword-excess #f]
#:positional-types [positional-types #f]
#:keyword-types [keyword-types #f]
#:first-optional [first-optional #f]
#:result-type [result-type #f])
(pyproc->procedure
(simple-proc name qualified-name
positional-parameters
keyword-parameters
#:object-type-str "builtins"
#:positional-excess positional-excess
#:keyword-excess keyword-excess
#:positional-types positional-types
#:keyword-types keyword-types
#:first-optional first-optional
#:result-type result-type)))
(define-delayed
(define builtins.dir
(simple-builtin 'dir 'builtins.dir
'(object) '())))
#;(define dir
(pyproc->procedure
(pyproc (obj "fun" (get 'builtins.dir)) "dir" 'builtins.dir
'("object") '(#f) #f
'() #f #f
#f #f)))
| null | https://raw.githubusercontent.com/soegaard/pyffi/52f1e06c79f9be70b2fdd29b223ae0656b3e066b/pyffi-lib/pyffi/python-more-builtins.rkt | racket | allow symbol
allow symbols
allow symbols
allow symbol
allow symbol
(define dir | #lang racket/base
(require "structs.rkt"
"python-c-api.rkt"
"python-delayed.rkt"
"python-define-delayed.rkt"
"python-environment.rkt"
"python-evaluation.rkt"
"python-initialization.rkt"
"python-types.rkt"
"python-attributes.rkt"
"python-builtins.rkt"
"python-functions.rkt"
"python-operators.rkt"
racket/format
racket/list
racket/match)
(require (for-syntax racket/base
racket/syntax
syntax/parse))
(define (simple-proc name qualified-name
positional-parameters
keyword-parameters
#:object-type-str [object-type-str "fun"]
#:positional-excess [positional-excess #f]
#:keyword-excess [keyword-excess #f]
#:positional-types [positional-types #f]
#:keyword-types [keyword-types #f]
#:first-optional [first-optional #f]
#:result-type [result-type #f])
(define object (obj object-type-str (get qualified-name)))
(when positional-excess
(when keyword-excess
(unless positional-types
(set! positional-types (make-list (length positional-parameters) #f)))
(unless keyword-types
(set! keyword-types (make-list (length keyword-parameters) #f)))
(pyproc object name qualified-name
positional-parameters positional-types positional-excess
keyword-parameters keyword-types keyword-excess
first-optional result-type))
(define (simple-builtin name qualified-name
positional-parameters
keyword-parameters
#:positional-excess [positional-excess #f]
#:keyword-excess [keyword-excess #f]
#:positional-types [positional-types #f]
#:keyword-types [keyword-types #f]
#:first-optional [first-optional #f]
#:result-type [result-type #f])
(pyproc->procedure
(simple-proc name qualified-name
positional-parameters
keyword-parameters
#:object-type-str "builtins"
#:positional-excess positional-excess
#:keyword-excess keyword-excess
#:positional-types positional-types
#:keyword-types keyword-types
#:first-optional first-optional
#:result-type result-type)))
(define-delayed
(define builtins.dir
(simple-builtin 'dir 'builtins.dir
'(object) '())))
(pyproc->procedure
(pyproc (obj "fun" (get 'builtins.dir)) "dir" 'builtins.dir
'("object") '(#f) #f
'() #f #f
#f #f)))
|
3e2cd6a2e87580a72f9e0a2fa4e5cc7d7e093f2767a3b4101363e0fb2b444955 | bennn/dissertation | run-t.rkt | #lang typed/racket
(provide
;; String
EOM
DONE
constants , regexps that match PATH , DISABLE , and ENABLE requests
PATH
DISABLE
ENABLE
;; InputPort OutputPort -> Void
;; read FROM, DISABLE, and ENABLE requests input-port, write responses to output-port, loop
run-t)
;; ===================================================================================================
(require require-typed-check)
(require/typed/check "t-view.rkt" [manage% Manage])
(require "../base/t-view-types.rkt")
(define PATH #rx"from (.*) to (.*)$")
(define DISABLE #rx"disable (.*)$")
(define ENABLE #rx"enable (.*)$")
(define DONE "done")
(define EOM "eom")
(: manage [Instance Manage])
(define manage (new manage%))
(: run-t (-> String String))
(define (run-t next)
(cond
[(regexp-match PATH next)
=> (lambda ([x : (Listof (U #f String))])
(define x2 (second x))
(define x3 (third x))
(unless (and x2 x3) (error 'run-t "invariat error"))
(send manage find x2 x3))]
[(regexp-match DISABLE next)
=> (lambda ([x : (Listof (U #f String))])
(define x2 (second x))
(unless x2 (error 'run-t "invariants"))
(status-check add-to-disabled x2))]
[(regexp-match ENABLE next)
=> (lambda ([x : (Listof (U #f String))])
(define x2 (second x))
(unless x2 (error 'run-t "invariants"))
(status-check remove-from-disabled x2))]
[else "message not understood"]))
(define-syntax-rule
(status-check remove-from-disabled enabled)
(let ([status (send manage remove-from-disabled enabled)])
(if (boolean? status)
DONE
status)))
| null | https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/scrbl/jfp-2019/benchmarks/mbta/typed/run-t.rkt | racket | String
InputPort OutputPort -> Void
read FROM, DISABLE, and ENABLE requests input-port, write responses to output-port, loop
=================================================================================================== | #lang typed/racket
(provide
EOM
DONE
constants , regexps that match PATH , DISABLE , and ENABLE requests
PATH
DISABLE
ENABLE
run-t)
(require require-typed-check)
(require/typed/check "t-view.rkt" [manage% Manage])
(require "../base/t-view-types.rkt")
(define PATH #rx"from (.*) to (.*)$")
(define DISABLE #rx"disable (.*)$")
(define ENABLE #rx"enable (.*)$")
(define DONE "done")
(define EOM "eom")
(: manage [Instance Manage])
(define manage (new manage%))
(: run-t (-> String String))
(define (run-t next)
(cond
[(regexp-match PATH next)
=> (lambda ([x : (Listof (U #f String))])
(define x2 (second x))
(define x3 (third x))
(unless (and x2 x3) (error 'run-t "invariat error"))
(send manage find x2 x3))]
[(regexp-match DISABLE next)
=> (lambda ([x : (Listof (U #f String))])
(define x2 (second x))
(unless x2 (error 'run-t "invariants"))
(status-check add-to-disabled x2))]
[(regexp-match ENABLE next)
=> (lambda ([x : (Listof (U #f String))])
(define x2 (second x))
(unless x2 (error 'run-t "invariants"))
(status-check remove-from-disabled x2))]
[else "message not understood"]))
(define-syntax-rule
(status-check remove-from-disabled enabled)
(let ([status (send manage remove-from-disabled enabled)])
(if (boolean? status)
DONE
status)))
|
7ced0e36f7783d577405e2671e3c1982a5c8b694e9c16d8b3f4a6ba97f47dd42 | runtimeverification/haskell-backend | DebugUnifyBottom.hs | # LANGUAGE NoStrict #
# LANGUAGE NoStrictData #
|
Copyright : ( c ) Runtime Verification , 2021
License : BSD-3 - Clause
Copyright : (c) Runtime Verification, 2021
License : BSD-3-Clause
-}
module Kore.Log.DebugUnifyBottom (
DebugUnifyBottom (..),
mkDebugUnifyBottom,
debugUnifyBottom,
debugUnifyBottomAndReturnBottom,
) where
import Data.Text (
Text,
)
import Kore.Internal.TermLike (
InternalVariable,
TermLike (..),
VariableName,
)
import Kore.Internal.TermLike qualified as TermLike
import Kore.Unparser (unparse)
import Log (
Entry (..),
MonadLog (..),
Severity (..),
logEntry,
)
import Logic (
MonadLogic,
)
import Prelude.Kore
import Pretty (
Pretty,
pretty,
unAnnotate,
)
import Pretty qualified
data DebugUnifyBottom = DebugUnifyBottom
{ info :: Text
, first :: TermLike VariableName
, second :: TermLike VariableName
}
deriving stock (Show, Eq)
instance Pretty DebugUnifyBottom where
pretty (DebugUnifyBottom info first second) =
Pretty.vsep
[ unAnnotate $ pretty info
, "When unifying:"
, Pretty.indent 4 . unparse $ first
, "With:"
, Pretty.indent 4 . unparse $ second
]
instance Entry DebugUnifyBottom where
entrySeverity _ = Debug
oneLineDoc _ = "DebugUnifyBottom"
helpDoc _ = "log failed unification"
mkDebugUnifyBottom ::
InternalVariable variable =>
Text ->
TermLike variable ->
TermLike variable ->
DebugUnifyBottom
mkDebugUnifyBottom info first second =
DebugUnifyBottom
info
(TermLike.mapVariables (pure $ from @_ @VariableName) first)
(TermLike.mapVariables (pure $ from @_ @VariableName) second)
debugUnifyBottom ::
MonadLog log =>
InternalVariable variable =>
Text ->
TermLike variable ->
TermLike variable ->
log ()
debugUnifyBottom info first second =
logEntry $
DebugUnifyBottom
info
(TermLike.mapVariables (pure $ from @_ @VariableName) first)
(TermLike.mapVariables (pure $ from @_ @VariableName) second)
debugUnifyBottomAndReturnBottom ::
MonadLog log =>
MonadLogic log =>
InternalVariable variable =>
Text ->
TermLike variable ->
TermLike variable ->
log a
debugUnifyBottomAndReturnBottom info first second = do
debugUnifyBottom
info
first
second
empty
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/efeb976108a0baa202844386193695564a257540/kore/src/Kore/Log/DebugUnifyBottom.hs | haskell | # LANGUAGE NoStrict #
# LANGUAGE NoStrictData #
|
Copyright : ( c ) Runtime Verification , 2021
License : BSD-3 - Clause
Copyright : (c) Runtime Verification, 2021
License : BSD-3-Clause
-}
module Kore.Log.DebugUnifyBottom (
DebugUnifyBottom (..),
mkDebugUnifyBottom,
debugUnifyBottom,
debugUnifyBottomAndReturnBottom,
) where
import Data.Text (
Text,
)
import Kore.Internal.TermLike (
InternalVariable,
TermLike (..),
VariableName,
)
import Kore.Internal.TermLike qualified as TermLike
import Kore.Unparser (unparse)
import Log (
Entry (..),
MonadLog (..),
Severity (..),
logEntry,
)
import Logic (
MonadLogic,
)
import Prelude.Kore
import Pretty (
Pretty,
pretty,
unAnnotate,
)
import Pretty qualified
data DebugUnifyBottom = DebugUnifyBottom
{ info :: Text
, first :: TermLike VariableName
, second :: TermLike VariableName
}
deriving stock (Show, Eq)
instance Pretty DebugUnifyBottom where
pretty (DebugUnifyBottom info first second) =
Pretty.vsep
[ unAnnotate $ pretty info
, "When unifying:"
, Pretty.indent 4 . unparse $ first
, "With:"
, Pretty.indent 4 . unparse $ second
]
instance Entry DebugUnifyBottom where
entrySeverity _ = Debug
oneLineDoc _ = "DebugUnifyBottom"
helpDoc _ = "log failed unification"
mkDebugUnifyBottom ::
InternalVariable variable =>
Text ->
TermLike variable ->
TermLike variable ->
DebugUnifyBottom
mkDebugUnifyBottom info first second =
DebugUnifyBottom
info
(TermLike.mapVariables (pure $ from @_ @VariableName) first)
(TermLike.mapVariables (pure $ from @_ @VariableName) second)
debugUnifyBottom ::
MonadLog log =>
InternalVariable variable =>
Text ->
TermLike variable ->
TermLike variable ->
log ()
debugUnifyBottom info first second =
logEntry $
DebugUnifyBottom
info
(TermLike.mapVariables (pure $ from @_ @VariableName) first)
(TermLike.mapVariables (pure $ from @_ @VariableName) second)
debugUnifyBottomAndReturnBottom ::
MonadLog log =>
MonadLogic log =>
InternalVariable variable =>
Text ->
TermLike variable ->
TermLike variable ->
log a
debugUnifyBottomAndReturnBottom info first second = do
debugUnifyBottom
info
first
second
empty
| |
525e8fdff3c380393cb53bfcf5f93e8eb5f13526b49e5065c9bd17bde7b8d224 | clojure-interop/google-cloud-clients | ProductSearchStub.clj | (ns com.google.cloud.vision.v1p4beta1.stub.ProductSearchStub
"Base stub class for Cloud Vision API.
This class is for advanced usage and reflects the underlying API directly."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.vision.v1p4beta1.stub ProductSearchStub]))
(defn ->product-search-stub
"Constructor."
(^ProductSearchStub []
(new ProductSearchStub )))
(defn create-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.CreateProductRequest,com.google.cloud.vision.v1p4beta1.Product>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.createProductCallable))))
(defn import-product-sets-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ImportProductSetsRequest,com.google.longrunning.Operation>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.importProductSetsCallable))))
(defn get-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.GetProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSet>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.getProductSetCallable))))
(defn list-products-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsRequest,com.google.cloud.vision.v1p4beta1.ListProductsResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsCallable))))
(defn get-operations-stub
"returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.longrunning.stub.OperationsStub`"
([^ProductSearchStub this]
(-> this (.getOperationsStub))))
(defn list-product-sets-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductSetsRequest,com.google.cloud.vision.v1p4beta1.ListProductSetsResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductSetsCallable))))
(defn import-product-sets-operation-callable
"returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallable<com.google.cloud.vision.v1p4beta1.ImportProductSetsRequest,com.google.cloud.vision.v1p4beta1.ImportProductSetsResponse,com.google.cloud.vision.v1p4beta1.BatchOperationMetadata>`"
([^ProductSearchStub this]
(-> this (.importProductSetsOperationCallable))))
(defn delete-reference-image-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.DeleteReferenceImageRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.deleteReferenceImageCallable))))
(defn create-reference-image-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.CreateReferenceImageRequest,com.google.cloud.vision.v1p4beta1.ReferenceImage>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.createReferenceImageCallable))))
(defn create-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.CreateProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSet>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.createProductSetCallable))))
(defn add-product-to-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.AddProductToProductSetRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.addProductToProductSetCallable))))
(defn get-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.GetProductRequest,com.google.cloud.vision.v1p4beta1.Product>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.getProductCallable))))
(defn list-products-in-product-set-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListProductsInProductSetPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsInProductSetPagedCallable))))
(defn list-products-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListProductsPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsPagedCallable))))
(defn remove-product-from-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.RemoveProductFromProductSetRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.removeProductFromProductSetCallable))))
(defn list-reference-images-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListReferenceImagesRequest,com.google.cloud.vision.v1p4beta1.ListReferenceImagesResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listReferenceImagesCallable))))
(defn close
""
([^ProductSearchStub this]
(-> this (.close))))
(defn list-products-in-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest,com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsInProductSetCallable))))
(defn delete-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.DeleteProductRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.deleteProductCallable))))
(defn update-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.UpdateProductRequest,com.google.cloud.vision.v1p4beta1.Product>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.updateProductCallable))))
(defn list-product-sets-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductSetsRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListProductSetsPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductSetsPagedCallable))))
(defn update-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.UpdateProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSet>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.updateProductSetCallable))))
(defn get-reference-image-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.GetReferenceImageRequest,com.google.cloud.vision.v1p4beta1.ReferenceImage>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.getReferenceImageCallable))))
(defn list-reference-images-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListReferenceImagesRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListReferenceImagesPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listReferenceImagesPagedCallable))))
(defn delete-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.DeleteProductSetRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.deleteProductSetCallable))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.vision/src/com/google/cloud/vision/v1p4beta1/stub/ProductSearchStub.clj | clojure | (ns com.google.cloud.vision.v1p4beta1.stub.ProductSearchStub
"Base stub class for Cloud Vision API.
This class is for advanced usage and reflects the underlying API directly."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.vision.v1p4beta1.stub ProductSearchStub]))
(defn ->product-search-stub
"Constructor."
(^ProductSearchStub []
(new ProductSearchStub )))
(defn create-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.CreateProductRequest,com.google.cloud.vision.v1p4beta1.Product>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.createProductCallable))))
(defn import-product-sets-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ImportProductSetsRequest,com.google.longrunning.Operation>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.importProductSetsCallable))))
(defn get-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.GetProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSet>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.getProductSetCallable))))
(defn list-products-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsRequest,com.google.cloud.vision.v1p4beta1.ListProductsResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsCallable))))
(defn get-operations-stub
"returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.longrunning.stub.OperationsStub`"
([^ProductSearchStub this]
(-> this (.getOperationsStub))))
(defn list-product-sets-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductSetsRequest,com.google.cloud.vision.v1p4beta1.ListProductSetsResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductSetsCallable))))
(defn import-product-sets-operation-callable
"returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallable<com.google.cloud.vision.v1p4beta1.ImportProductSetsRequest,com.google.cloud.vision.v1p4beta1.ImportProductSetsResponse,com.google.cloud.vision.v1p4beta1.BatchOperationMetadata>`"
([^ProductSearchStub this]
(-> this (.importProductSetsOperationCallable))))
(defn delete-reference-image-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.DeleteReferenceImageRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.deleteReferenceImageCallable))))
(defn create-reference-image-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.CreateReferenceImageRequest,com.google.cloud.vision.v1p4beta1.ReferenceImage>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.createReferenceImageCallable))))
(defn create-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.CreateProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSet>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.createProductSetCallable))))
(defn add-product-to-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.AddProductToProductSetRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.addProductToProductSetCallable))))
(defn get-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.GetProductRequest,com.google.cloud.vision.v1p4beta1.Product>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.getProductCallable))))
(defn list-products-in-product-set-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListProductsInProductSetPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsInProductSetPagedCallable))))
(defn list-products-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListProductsPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsPagedCallable))))
(defn remove-product-from-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.RemoveProductFromProductSetRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.removeProductFromProductSetCallable))))
(defn list-reference-images-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListReferenceImagesRequest,com.google.cloud.vision.v1p4beta1.ListReferenceImagesResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listReferenceImagesCallable))))
(defn close
""
([^ProductSearchStub this]
(-> this (.close))))
(defn list-products-in-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest,com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductsInProductSetCallable))))
(defn delete-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.DeleteProductRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.deleteProductCallable))))
(defn update-product-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.UpdateProductRequest,com.google.cloud.vision.v1p4beta1.Product>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.updateProductCallable))))
(defn list-product-sets-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListProductSetsRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListProductSetsPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listProductSetsPagedCallable))))
(defn update-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.UpdateProductSetRequest,com.google.cloud.vision.v1p4beta1.ProductSet>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.updateProductSetCallable))))
(defn get-reference-image-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.GetReferenceImageRequest,com.google.cloud.vision.v1p4beta1.ReferenceImage>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.getReferenceImageCallable))))
(defn list-reference-images-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.ListReferenceImagesRequest,com.google.cloud.vision.v1p4beta1.ProductSearchClient$ListReferenceImagesPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.listReferenceImagesPagedCallable))))
(defn delete-product-set-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.vision.v1p4beta1.DeleteProductSetRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProductSearchStub this]
(-> this (.deleteProductSetCallable))))
| |
71e40c90219f22c63ecbf9bbf9b0dbc9a5300aa8f06386f0afac8456d761a94e | TheoVerhelst/OverPitch | pitch_shifting.clj | (ns overpitch.pitch-shifting
(:require [overpitch.time-scaling :refer [time-scale]]
[overpitch.resampling :refer [resample]]))
(defn pitch-shift
"Pitch-shifts the input data vector by the given scale"
[input-data scale]
(resample (time-scale input-data scale) (/ 1 scale)))
| null | https://raw.githubusercontent.com/TheoVerhelst/OverPitch/645a15e74cf4a7a6d134bbe6940cb99ea2c98288/src/overpitch/pitch_shifting.clj | clojure | (ns overpitch.pitch-shifting
(:require [overpitch.time-scaling :refer [time-scale]]
[overpitch.resampling :refer [resample]]))
(defn pitch-shift
"Pitch-shifts the input data vector by the given scale"
[input-data scale]
(resample (time-scale input-data scale) (/ 1 scale)))
| |
40f1137cf7262e8c999aee80eab5cab1c4c7d860fd47885a68457940ea3afeb2 | nikodemus/SBCL | exhaust.impure.lisp | ;;;; tests of the system's ability to catch resource exhaustion problems
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
(cl:in-package :cl-user)
(load "test-util.lisp")
(load "assertoid.lisp")
(use-package "TEST-UTIL")
(use-package "ASSERTOID")
;;; Prior to sbcl-0.7.1.38, doing something like (RECURSE), even in
;;; safe code, would crash the entire Lisp process. Then the soft
;;; stack checking was introduced, which checked (in safe code) for
;;; stack exhaustion at each lambda.
;;; Post 0.7.6.1, this was rewritten to use mprotect()-based stack
;;; protection which does not require lisp code to check anything,
;;; and works at all optimization settings. However, it now signals a
;;; STORAGE-CONDITION instead of an ERROR.
(defun recurse ()
(recurse)
(recurse))
(defvar *count* 100)
;;; Base-case: detecting exhaustion
(with-test (:name (:exhaust :basic) :broken-on '(and :sunos :x86-64))
(assert (eq :exhausted
(handler-case
(recurse)
(storage-condition (c)
(declare (ignore c))
:exhausted)))))
;;; Check that non-local control transfers restore the stack
;;; exhaustion checking after unwinding -- and that previous test
;;; didn't break it.
(with-test (:name (:exhaust :non-local-control)
:broken-on '(and :sunos :x86-64)
:skipped-on :win32)
(let ((exhaust-count 0)
(recurse-count 0))
(tagbody
:retry
(handler-bind ((storage-condition (lambda (c)
(declare (ignore c))
(if (= *count* (incf exhaust-count))
(go :stop)
(go :retry)))))
(incf recurse-count)
(recurse))
:stop)
(assert (= exhaust-count recurse-count *count*))))
;;; Check that we can safely use user-provided restarts to
;;; unwind.
(with-test (:name (:exhaust :restarts)
:broken-on '(and :sunos :x86-64)
:skipped-on :win32)
(let ((exhaust-count 0)
(recurse-count 0))
(block nil
(handler-bind ((storage-condition (lambda (c)
(declare (ignore c))
(if (= *count* (incf exhaust-count))
(return)
(invoke-restart (find-restart 'ok))))))
(loop
(with-simple-restart (ok "ok")
(incf recurse-count)
(recurse)))))
(assert (= exhaust-count recurse-count *count*))))
(with-test (:name (:exhaust :binding-stack))
(let ((ok nil)
(symbols (loop repeat 1024 collect (gensym)))
(values (loop repeat 1024 collect nil)))
(gc :full t)
(labels ((exhaust-binding-stack (i)
(progv symbols values
(exhaust-binding-stack (1+ i)))))
(handler-case
(exhaust-binding-stack 0)
(sb-kernel::binding-stack-exhausted ()
(setq ok t)))
(assert ok))))
(with-test (:name (:exhaust :alien-stack)
:skipped-on '(or (not :c-stack-is-control-stack)))
(let ((ok nil))
(labels ((exhaust-alien-stack (i)
(with-alien ((integer-array (array int 500)))
(+ (deref integer-array 0)
(exhaust-alien-stack (1+ i))))))
(handler-case
(exhaust-alien-stack 0)
(sb-kernel::alien-stack-exhausted ()
(setq ok t)))
(assert ok))))
;;; OK!
| null | https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/tests/exhaust.impure.lisp | lisp | tests of the system's ability to catch resource exhaustion problems
more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
Prior to sbcl-0.7.1.38, doing something like (RECURSE), even in
safe code, would crash the entire Lisp process. Then the soft
stack checking was introduced, which checked (in safe code) for
stack exhaustion at each lambda.
Post 0.7.6.1, this was rewritten to use mprotect()-based stack
protection which does not require lisp code to check anything,
and works at all optimization settings. However, it now signals a
STORAGE-CONDITION instead of an ERROR.
Base-case: detecting exhaustion
Check that non-local control transfers restore the stack
exhaustion checking after unwinding -- and that previous test
didn't break it.
Check that we can safely use user-provided restarts to
unwind.
OK! |
This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
(cl:in-package :cl-user)
(load "test-util.lisp")
(load "assertoid.lisp")
(use-package "TEST-UTIL")
(use-package "ASSERTOID")
(defun recurse ()
(recurse)
(recurse))
(defvar *count* 100)
(with-test (:name (:exhaust :basic) :broken-on '(and :sunos :x86-64))
(assert (eq :exhausted
(handler-case
(recurse)
(storage-condition (c)
(declare (ignore c))
:exhausted)))))
(with-test (:name (:exhaust :non-local-control)
:broken-on '(and :sunos :x86-64)
:skipped-on :win32)
(let ((exhaust-count 0)
(recurse-count 0))
(tagbody
:retry
(handler-bind ((storage-condition (lambda (c)
(declare (ignore c))
(if (= *count* (incf exhaust-count))
(go :stop)
(go :retry)))))
(incf recurse-count)
(recurse))
:stop)
(assert (= exhaust-count recurse-count *count*))))
(with-test (:name (:exhaust :restarts)
:broken-on '(and :sunos :x86-64)
:skipped-on :win32)
(let ((exhaust-count 0)
(recurse-count 0))
(block nil
(handler-bind ((storage-condition (lambda (c)
(declare (ignore c))
(if (= *count* (incf exhaust-count))
(return)
(invoke-restart (find-restart 'ok))))))
(loop
(with-simple-restart (ok "ok")
(incf recurse-count)
(recurse)))))
(assert (= exhaust-count recurse-count *count*))))
(with-test (:name (:exhaust :binding-stack))
(let ((ok nil)
(symbols (loop repeat 1024 collect (gensym)))
(values (loop repeat 1024 collect nil)))
(gc :full t)
(labels ((exhaust-binding-stack (i)
(progv symbols values
(exhaust-binding-stack (1+ i)))))
(handler-case
(exhaust-binding-stack 0)
(sb-kernel::binding-stack-exhausted ()
(setq ok t)))
(assert ok))))
(with-test (:name (:exhaust :alien-stack)
:skipped-on '(or (not :c-stack-is-control-stack)))
(let ((ok nil))
(labels ((exhaust-alien-stack (i)
(with-alien ((integer-array (array int 500)))
(+ (deref integer-array 0)
(exhaust-alien-stack (1+ i))))))
(handler-case
(exhaust-alien-stack 0)
(sb-kernel::alien-stack-exhausted ()
(setq ok t)))
(assert ok))))
|
7ebdcdb663bf8eefae54cc15fa5798190f2bd37d92bf0b997f2d72875e6973ca | mbj/stratosphere | AccessRulesProperty.hs | module Stratosphere.Lightsail.Bucket.AccessRulesProperty (
AccessRulesProperty(..), mkAccessRulesProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data AccessRulesProperty
= AccessRulesProperty {allowPublicOverrides :: (Prelude.Maybe (Value Prelude.Bool)),
getObject :: (Prelude.Maybe (Value Prelude.Text))}
mkAccessRulesProperty :: AccessRulesProperty
mkAccessRulesProperty
= AccessRulesProperty
{allowPublicOverrides = Prelude.Nothing,
getObject = Prelude.Nothing}
instance ToResourceProperties AccessRulesProperty where
toResourceProperties AccessRulesProperty {..}
= ResourceProperties
{awsType = "AWS::Lightsail::Bucket.AccessRules",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AllowPublicOverrides" Prelude.<$> allowPublicOverrides,
(JSON..=) "GetObject" Prelude.<$> getObject])}
instance JSON.ToJSON AccessRulesProperty where
toJSON AccessRulesProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AllowPublicOverrides" Prelude.<$> allowPublicOverrides,
(JSON..=) "GetObject" Prelude.<$> getObject]))
instance Property "AllowPublicOverrides" AccessRulesProperty where
type PropertyType "AllowPublicOverrides" AccessRulesProperty = Value Prelude.Bool
set newValue AccessRulesProperty {..}
= AccessRulesProperty
{allowPublicOverrides = Prelude.pure newValue, ..}
instance Property "GetObject" AccessRulesProperty where
type PropertyType "GetObject" AccessRulesProperty = Value Prelude.Text
set newValue AccessRulesProperty {..}
= AccessRulesProperty {getObject = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/lightsail/gen/Stratosphere/Lightsail/Bucket/AccessRulesProperty.hs | haskell | module Stratosphere.Lightsail.Bucket.AccessRulesProperty (
AccessRulesProperty(..), mkAccessRulesProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data AccessRulesProperty
= AccessRulesProperty {allowPublicOverrides :: (Prelude.Maybe (Value Prelude.Bool)),
getObject :: (Prelude.Maybe (Value Prelude.Text))}
mkAccessRulesProperty :: AccessRulesProperty
mkAccessRulesProperty
= AccessRulesProperty
{allowPublicOverrides = Prelude.Nothing,
getObject = Prelude.Nothing}
instance ToResourceProperties AccessRulesProperty where
toResourceProperties AccessRulesProperty {..}
= ResourceProperties
{awsType = "AWS::Lightsail::Bucket.AccessRules",
supportsTags = Prelude.False,
properties = Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AllowPublicOverrides" Prelude.<$> allowPublicOverrides,
(JSON..=) "GetObject" Prelude.<$> getObject])}
instance JSON.ToJSON AccessRulesProperty where
toJSON AccessRulesProperty {..}
= JSON.object
(Prelude.fromList
(Prelude.catMaybes
[(JSON..=) "AllowPublicOverrides" Prelude.<$> allowPublicOverrides,
(JSON..=) "GetObject" Prelude.<$> getObject]))
instance Property "AllowPublicOverrides" AccessRulesProperty where
type PropertyType "AllowPublicOverrides" AccessRulesProperty = Value Prelude.Bool
set newValue AccessRulesProperty {..}
= AccessRulesProperty
{allowPublicOverrides = Prelude.pure newValue, ..}
instance Property "GetObject" AccessRulesProperty where
type PropertyType "GetObject" AccessRulesProperty = Value Prelude.Text
set newValue AccessRulesProperty {..}
= AccessRulesProperty {getObject = Prelude.pure newValue, ..} | |
192c72312709084a3742e4fa404eb75235f764784748724d33ffb8bb97dedbd2 | jeffshrager/biobike | java-parser-test.lisp | (defpackage "JAVA-PARSER-TEST"
(:use "COMMON-LISP" "TEST" "PARSER"))
(in-package "JAVA-PARSER-TEST")
(defvar *cr* (string #\return))
(defvar *lf* (string #\newline))
(defvar *crlf* (concatenate 'string *cr* *lf*))
(defvar *space* (string #\space))
(defvar *tab* (string #\tab))
(defvar *form-feed* (string #\page))
(deftest compilation-unit ()
(defparser compilation-unit-parser java-parser::compilation-unit)
(check
(compilation-unit-parser "")
(compilation-unit-parser ";;;;;")
(compilation-unit-parser "package com.javamonkey.foo;;;;;")
(compilation-unit-parser "import com.javamonkey.Foo;")
(compilation-unit-parser "import com.javamonkey.*;")
))
(deftest 3.4-line-terminators ()
(defparser line-terminator-parser java-parser::line-terminator)
(check
(line-terminator-parser *cr*)
(line-terminator-parser *lf*)
(line-terminator-parser *crlf*)
(not (line-terminator-parser (concatenate 'string *lf* *cr*)))))
(deftest 3.6-white-space ()
(defparser white-space-parser java-parser::white-space)
(check
(white-space-parser *space*)
(white-space-parser *tab*)
(white-space-parser *form-feed*)
(white-space-parser *cr*)
(white-space-parser *lf*)
(white-space-parser *crlf*)))
nyi
(deftest 3.8-identifiers ()
(defparser identifier-parser java-parser::identifier)
(check
(identifier-parser "a")
(identifier-parser "ab")
(identifier-parser "a1")
(identifier-parser "foo")
(not (identifier-parser "1a"))
(not (identifier-parser "abstract"))
(not (identifier-parser "boolean"))
(not (identifier-parser "break"))
(not (identifier-parser "byte"))
(not (identifier-parser "case"))
(not (identifier-parser "catch"))
(not (identifier-parser "char"))
(not (identifier-parser "class"))
(not (identifier-parser "const"))
(not (identifier-parser "continue"))
(not (identifier-parser "default"))
(not (identifier-parser "do"))
(not (identifier-parser "double"))
(not (identifier-parser "else"))
(not (identifier-parser "extends"))
(not (identifier-parser "final"))
(not (identifier-parser "finally"))
(not (identifier-parser "float"))
(not (identifier-parser "for"))
(not (identifier-parser "goto"))
(not (identifier-parser "if"))
(not (identifier-parser "implements"))
(not (identifier-parser "import"))
(not (identifier-parser "instanceof"))
(not (identifier-parser "int"))
(not (identifier-parser "interface"))
(not (identifier-parser "long"))
(not (identifier-parser "native"))
(not (identifier-parser "new"))
(not (identifier-parser "package"))
(not (identifier-parser "private"))
(not (identifier-parser "protected"))
(not (identifier-parser "public"))
(not (identifier-parser "return"))
(not (identifier-parser "short"))
(not (identifier-parser "static"))
(not (identifier-parser "strictfp"))
(not (identifier-parser "super"))
(not (identifier-parser "switch"))
(not (identifier-parser "synchronized"))
(not (identifier-parser "this"))
(not (identifier-parser "throw"))
(not (identifier-parser "throws"))
(not (identifier-parser "transient"))
(not (identifier-parser "try"))
(not (identifier-parser "void"))
(not (identifier-parser "volatile"))
(not (identifier-parser "while"))
(not (identifier-parser "true"))
(not (identifier-parser "false"))
(not (identifier-parser "null"))))
(deftest 3.9-keywords ()
(defparser java-keyword-parser java-parser::java-keyword)
(check
(java-keyword-parser "abstract")
(java-keyword-parser "boolean")
(java-keyword-parser "break")
(java-keyword-parser "byte")
(java-keyword-parser "case")
(java-keyword-parser "catch")
(java-keyword-parser "char")
(java-keyword-parser "class")
(java-keyword-parser "const")
(java-keyword-parser "continue")
(java-keyword-parser "default")
(java-keyword-parser "do")
(java-keyword-parser "double")
(java-keyword-parser "else")
(java-keyword-parser "extends")
(java-keyword-parser "final")
(java-keyword-parser "finally")
(java-keyword-parser "float")
(java-keyword-parser "for")
(java-keyword-parser "goto")
(java-keyword-parser "if")
(java-keyword-parser "implements")
(java-keyword-parser "import")
(java-keyword-parser "instanceof")
(java-keyword-parser "int")
(java-keyword-parser "interface")
(java-keyword-parser "long")
(java-keyword-parser "native")
(java-keyword-parser "new")
(java-keyword-parser "package")
(java-keyword-parser "private")
(java-keyword-parser "protected")
(java-keyword-parser "public")
(java-keyword-parser "return")
(java-keyword-parser "short")
(java-keyword-parser "static")
(java-keyword-parser "strictfp")
(java-keyword-parser "super")
(java-keyword-parser "switch")
(java-keyword-parser "synchronized")
(java-keyword-parser "this")
(java-keyword-parser "throw")
(java-keyword-parser "throws")
(java-keyword-parser "transient")
(java-keyword-parser "try")
(java-keyword-parser "void")
(java-keyword-parser "volatile")
(java-keyword-parser "while")
(not (java-keyword-parser "foo"))))
(deftest 3.10.1-integer-literals ()
(defparser integer-literal-parser java-parser::integer-literal)
(defparser decimal-integer-literal-parser java-parser::decimal-integer-literal)
(defparser hex-integer-literal-parser java-parser::hex-integer-literal)
(defparser octal-integer-literal-parser java-parser::octal-integer-literal)
(check
(decimal-integer-literal-parser "0")
(integer-literal-parser "0")
(decimal-integer-literal-parser "2")
(integer-literal-parser "2")
(octal-integer-literal-parser "0372")
(integer-literal-parser "0372")
(hex-integer-literal-parser "0xDadaCafe")
(integer-literal-parser "0xDadaCafe")
(decimal-integer-literal-parser "1996")
(integer-literal-parser "1996")
(hex-integer-literal-parser "0x00FF00FF")
(integer-literal-parser "0x00FF00FF")
))
nyi
(deftest 3.10.3-boolean-literals ()
(defparser boolean-literal-parser java-parser::boolean-literal)
(check
(boolean-literal-parser "true")
(boolean-literal-parser "false")))
(deftest 3.10.4-character-literals ()
(defparser character-literal-parser java-parser::character-literal)
(check
(character-literal-parser "'a'")
(character-literal-parser "'%'")
(character-literal-parser "'\\t'")
(character-literal-parser "'\\\\'")
(character-literal-parser "'\\''")
(character-literal-parser "'\\1'")
(character-literal-parser "'\\12'")
(character-literal-parser "'\\123'")
(character-literal-parser "'\\177'")))
(deftest 3.10.5-string-literals ()
(defparser string-literal-parser java-parser::string-literal)
(check
(string-literal-parser "\"\"")
(string-literal-parser "\"\\\"\"")
(string-literal-parser "\"This is a string\"")))
(deftest 3.10.6-escape-sequences ()
(defparser escape-sequence-parser java-parser::escape-sequence)
(check
(escape-sequence-parser "\\b")
(escape-sequence-parser "\\t")
(escape-sequence-parser "\\n")
(escape-sequence-parser "\\f")
(escape-sequence-parser "\\r")
(escape-sequence-parser "\\\"")
(escape-sequence-parser "\\'")
(escape-sequence-parser "\\\\")
(escape-sequence-parser "\\1")
(escape-sequence-parser "\\4")
(escape-sequence-parser "\\12")
(escape-sequence-parser "\\42")
(escape-sequence-parser "\\123")
(not (escape-sequence-parser "\\423"))))
(deftest 3.10.7-the-null-literal ()
(defparser null-literal-parser java-parser::null-literal)
(check
(null-literal-parser "null")
(not (null-literal-parser "NULL"))))
(deftest 4.2-primitive-types ()
(defparser primitive-type-parser java-parser::primitive-type)
(check
(primitive-type-parser "boolean")
(primitive-type-parser "byte")
(primitive-type-parser "short")
(primitive-type-parser "int")
(primitive-type-parser "long")
(primitive-type-parser "char")
(primitive-type-parser "float")
(primitive-type-parser "double")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Utilities
(defun tests (&optional reload)
(if reload
(utils::load-and-test "java-parser")
(test::test-package "JAVA-PARSER-TEST")))
| null | https://raw.githubusercontent.com/jeffshrager/biobike/5313ec1fe8e82c21430d645e848ecc0386436f57/BioLisp/ThirdParty/monkeylib/parser/java-parser-test.lisp | lisp | (defpackage "JAVA-PARSER-TEST"
(:use "COMMON-LISP" "TEST" "PARSER"))
(in-package "JAVA-PARSER-TEST")
(defvar *cr* (string #\return))
(defvar *lf* (string #\newline))
(defvar *crlf* (concatenate 'string *cr* *lf*))
(defvar *space* (string #\space))
(defvar *tab* (string #\tab))
(defvar *form-feed* (string #\page))
(deftest compilation-unit ()
(defparser compilation-unit-parser java-parser::compilation-unit)
(check
(compilation-unit-parser "")
(compilation-unit-parser ";;;;;")
(compilation-unit-parser "package com.javamonkey.foo;;;;;")
(compilation-unit-parser "import com.javamonkey.Foo;")
(compilation-unit-parser "import com.javamonkey.*;")
))
(deftest 3.4-line-terminators ()
(defparser line-terminator-parser java-parser::line-terminator)
(check
(line-terminator-parser *cr*)
(line-terminator-parser *lf*)
(line-terminator-parser *crlf*)
(not (line-terminator-parser (concatenate 'string *lf* *cr*)))))
(deftest 3.6-white-space ()
(defparser white-space-parser java-parser::white-space)
(check
(white-space-parser *space*)
(white-space-parser *tab*)
(white-space-parser *form-feed*)
(white-space-parser *cr*)
(white-space-parser *lf*)
(white-space-parser *crlf*)))
nyi
(deftest 3.8-identifiers ()
(defparser identifier-parser java-parser::identifier)
(check
(identifier-parser "a")
(identifier-parser "ab")
(identifier-parser "a1")
(identifier-parser "foo")
(not (identifier-parser "1a"))
(not (identifier-parser "abstract"))
(not (identifier-parser "boolean"))
(not (identifier-parser "break"))
(not (identifier-parser "byte"))
(not (identifier-parser "case"))
(not (identifier-parser "catch"))
(not (identifier-parser "char"))
(not (identifier-parser "class"))
(not (identifier-parser "const"))
(not (identifier-parser "continue"))
(not (identifier-parser "default"))
(not (identifier-parser "do"))
(not (identifier-parser "double"))
(not (identifier-parser "else"))
(not (identifier-parser "extends"))
(not (identifier-parser "final"))
(not (identifier-parser "finally"))
(not (identifier-parser "float"))
(not (identifier-parser "for"))
(not (identifier-parser "goto"))
(not (identifier-parser "if"))
(not (identifier-parser "implements"))
(not (identifier-parser "import"))
(not (identifier-parser "instanceof"))
(not (identifier-parser "int"))
(not (identifier-parser "interface"))
(not (identifier-parser "long"))
(not (identifier-parser "native"))
(not (identifier-parser "new"))
(not (identifier-parser "package"))
(not (identifier-parser "private"))
(not (identifier-parser "protected"))
(not (identifier-parser "public"))
(not (identifier-parser "return"))
(not (identifier-parser "short"))
(not (identifier-parser "static"))
(not (identifier-parser "strictfp"))
(not (identifier-parser "super"))
(not (identifier-parser "switch"))
(not (identifier-parser "synchronized"))
(not (identifier-parser "this"))
(not (identifier-parser "throw"))
(not (identifier-parser "throws"))
(not (identifier-parser "transient"))
(not (identifier-parser "try"))
(not (identifier-parser "void"))
(not (identifier-parser "volatile"))
(not (identifier-parser "while"))
(not (identifier-parser "true"))
(not (identifier-parser "false"))
(not (identifier-parser "null"))))
(deftest 3.9-keywords ()
(defparser java-keyword-parser java-parser::java-keyword)
(check
(java-keyword-parser "abstract")
(java-keyword-parser "boolean")
(java-keyword-parser "break")
(java-keyword-parser "byte")
(java-keyword-parser "case")
(java-keyword-parser "catch")
(java-keyword-parser "char")
(java-keyword-parser "class")
(java-keyword-parser "const")
(java-keyword-parser "continue")
(java-keyword-parser "default")
(java-keyword-parser "do")
(java-keyword-parser "double")
(java-keyword-parser "else")
(java-keyword-parser "extends")
(java-keyword-parser "final")
(java-keyword-parser "finally")
(java-keyword-parser "float")
(java-keyword-parser "for")
(java-keyword-parser "goto")
(java-keyword-parser "if")
(java-keyword-parser "implements")
(java-keyword-parser "import")
(java-keyword-parser "instanceof")
(java-keyword-parser "int")
(java-keyword-parser "interface")
(java-keyword-parser "long")
(java-keyword-parser "native")
(java-keyword-parser "new")
(java-keyword-parser "package")
(java-keyword-parser "private")
(java-keyword-parser "protected")
(java-keyword-parser "public")
(java-keyword-parser "return")
(java-keyword-parser "short")
(java-keyword-parser "static")
(java-keyword-parser "strictfp")
(java-keyword-parser "super")
(java-keyword-parser "switch")
(java-keyword-parser "synchronized")
(java-keyword-parser "this")
(java-keyword-parser "throw")
(java-keyword-parser "throws")
(java-keyword-parser "transient")
(java-keyword-parser "try")
(java-keyword-parser "void")
(java-keyword-parser "volatile")
(java-keyword-parser "while")
(not (java-keyword-parser "foo"))))
(deftest 3.10.1-integer-literals ()
(defparser integer-literal-parser java-parser::integer-literal)
(defparser decimal-integer-literal-parser java-parser::decimal-integer-literal)
(defparser hex-integer-literal-parser java-parser::hex-integer-literal)
(defparser octal-integer-literal-parser java-parser::octal-integer-literal)
(check
(decimal-integer-literal-parser "0")
(integer-literal-parser "0")
(decimal-integer-literal-parser "2")
(integer-literal-parser "2")
(octal-integer-literal-parser "0372")
(integer-literal-parser "0372")
(hex-integer-literal-parser "0xDadaCafe")
(integer-literal-parser "0xDadaCafe")
(decimal-integer-literal-parser "1996")
(integer-literal-parser "1996")
(hex-integer-literal-parser "0x00FF00FF")
(integer-literal-parser "0x00FF00FF")
))
nyi
(deftest 3.10.3-boolean-literals ()
(defparser boolean-literal-parser java-parser::boolean-literal)
(check
(boolean-literal-parser "true")
(boolean-literal-parser "false")))
(deftest 3.10.4-character-literals ()
(defparser character-literal-parser java-parser::character-literal)
(check
(character-literal-parser "'a'")
(character-literal-parser "'%'")
(character-literal-parser "'\\t'")
(character-literal-parser "'\\\\'")
(character-literal-parser "'\\''")
(character-literal-parser "'\\1'")
(character-literal-parser "'\\12'")
(character-literal-parser "'\\123'")
(character-literal-parser "'\\177'")))
(deftest 3.10.5-string-literals ()
(defparser string-literal-parser java-parser::string-literal)
(check
(string-literal-parser "\"\"")
(string-literal-parser "\"\\\"\"")
(string-literal-parser "\"This is a string\"")))
(deftest 3.10.6-escape-sequences ()
(defparser escape-sequence-parser java-parser::escape-sequence)
(check
(escape-sequence-parser "\\b")
(escape-sequence-parser "\\t")
(escape-sequence-parser "\\n")
(escape-sequence-parser "\\f")
(escape-sequence-parser "\\r")
(escape-sequence-parser "\\\"")
(escape-sequence-parser "\\'")
(escape-sequence-parser "\\\\")
(escape-sequence-parser "\\1")
(escape-sequence-parser "\\4")
(escape-sequence-parser "\\12")
(escape-sequence-parser "\\42")
(escape-sequence-parser "\\123")
(not (escape-sequence-parser "\\423"))))
(deftest 3.10.7-the-null-literal ()
(defparser null-literal-parser java-parser::null-literal)
(check
(null-literal-parser "null")
(not (null-literal-parser "NULL"))))
(deftest 4.2-primitive-types ()
(defparser primitive-type-parser java-parser::primitive-type)
(check
(primitive-type-parser "boolean")
(primitive-type-parser "byte")
(primitive-type-parser "short")
(primitive-type-parser "int")
(primitive-type-parser "long")
(primitive-type-parser "char")
(primitive-type-parser "float")
(primitive-type-parser "double")))
Utilities
(defun tests (&optional reload)
(if reload
(utils::load-and-test "java-parser")
(test::test-package "JAVA-PARSER-TEST")))
| |
052b3101c4617e1c4f8cdc7a5a4def8badfbdc58c80b27b6ee5ee433fb9c87de | bcc32/projecteuler-ocaml | test_distribution.ml | open! Core
open! Import
module D = Distribution.Bignum
let%test_unit "singleton" =
let d = D.singleton (module Int) 0 in
[%test_result: Bignum.t] ~expect:Bignum.one (D.find_exn d 0)
;;
let%test_unit "scale" =
Q.test D.Prob.quickcheck_generator ~f:(fun p ->
let d = D.scale (D.singleton (module Int) 0) p in
[%test_result: Bignum.t] ~expect:p (D.find_exn d 0))
;;
let%test_unit "combine" =
let d1 = D.singleton (module Int) 1 in
let d2 = D.singleton (module Int) 2 in
Q.test D.Prob.quickcheck_generator ~f:(fun p1 ->
let d = D.combine ~d1 ~d2 ~p1 in
[%test_result: Bignum.t] (D.find_exn d 1) ~expect:p1;
[%test_result: Bignum.t] (D.find_exn d 2) ~expect:Bignum.(one - p1))
;;
let%test_unit "monad laws" =
let f x = D.singleton (module Int) (x + 1) in
let g x =
let p1 = Bignum.(1 // 2) in
D.combine ~p1 ~d1:(D.singleton (module Int) x) ~d2:(D.singleton (module Int) (-x))
in
let t = D.singleton (module Int) 0 in
Q.test Int.quickcheck_generator ~f:(fun v ->
let open D.Let_syntax in
CR azeng : Add D.M(Int).t
[%test_result: D.M(Int).t] (return (module Int) v >>= f) ~expect:(f v);
[%test_result: D.M(Int).t] (return (module Int) v >>= g) ~expect:(g v);
[%test_result: D.M(Int).t] (t >>= return (module Int)) ~expect:t;
[%test_result: D.M(Int).t] (t >>= f >>= g) ~expect:(t >>= fun x -> f x >>= g);
[%test_result: D.M(Int).t] (t >>= g >>= f) ~expect:(t >>= fun x -> g x >>= f))
;;
let%test_unit "bind" =
let half = Bignum.(1 // 2) in
let fifth = Bignum.(1 // 5) in
let f x =
D.combine
~p1:half
~d1:(D.singleton (module Int) x)
~d2:(D.singleton (module Int) (x + 1))
in
let t =
D.combine ~p1:fifth ~d1:(D.singleton (module Int) 0) ~d2:(D.singleton (module Int) 1)
in
let expect =
[ (0, Bignum.(1 // 10)); (1, Bignum.(5 // 10)); (2, Bignum.(4 // 10)) ]
|> D.of_alist_exn (module Int)
in
[%test_result: D.M(Int).t] (D.bind t ~f) ~expect
;;
let%test_unit "uniform" =
Q.test
(List.gen_non_empty [%quickcheck.generator: D.M(Int).t])
~sexp_of:[%sexp_of: D.M(Int).t list]
~shrinker:[%quickcheck.shrinker: _ list]
~f:(fun ds ->
let n = List.length ds in
let d = D.uniform ds in
Map.iteri (D.to_map d) ~f:(fun ~key ~data ->
let expect =
let open Bignum.O in
List.sum
(module Bignum)
ds
~f:(fun d -> D.find d key |> Option.value ~default:Bignum.zero)
/ of_int n
in
[%test_result: Bignum.t] data ~expect))
;;
let%test_unit "uniform'" =
let gen =
let open Quickcheck.Let_syntax in
let%map xs = List.gen_non_empty Int.quickcheck_generator in
List.dedup_and_sort xs ~compare:Int.compare
in
Q.test
gen
~sexp_of:[%sexp_of: int list]
~shrinker:[%quickcheck.shrinker: int list]
~f:(fun ks ->
let t = D.uniform' (module Int) ks in
let expect =
let length = List.length ks in
let prob = Bignum.(1 // length) in
ks |> List.map ~f:(fun k -> k, prob) |> D.of_alist_exn (module Int)
in
[%test_result: D.M(Int).t] t ~expect)
;;
let%test_unit "cartesian_product" =
let gen = [%quickcheck.generator: D.M(Int).t * D.M(Int).t] in
Q.test gen ~sexp_of:[%sexp_of: D.M(Int).t * D.M(Int).t] ~f:(fun (d1, d2) ->
let d = D.cartesian_product d1 d2 in
Map.iteri (D.to_map d1) ~f:(fun ~key:k1 ~data:p1 ->
Map.iteri (D.to_map d2) ~f:(fun ~key:k2 ~data:p2 ->
[%test_result: Bignum.t] ~expect:Bignum.(p1 * p2) (D.find_exn d (k1, k2)))))
;;
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/test/test_distribution.ml | ocaml | open! Core
open! Import
module D = Distribution.Bignum
let%test_unit "singleton" =
let d = D.singleton (module Int) 0 in
[%test_result: Bignum.t] ~expect:Bignum.one (D.find_exn d 0)
;;
let%test_unit "scale" =
Q.test D.Prob.quickcheck_generator ~f:(fun p ->
let d = D.scale (D.singleton (module Int) 0) p in
[%test_result: Bignum.t] ~expect:p (D.find_exn d 0))
;;
let%test_unit "combine" =
let d1 = D.singleton (module Int) 1 in
let d2 = D.singleton (module Int) 2 in
Q.test D.Prob.quickcheck_generator ~f:(fun p1 ->
let d = D.combine ~d1 ~d2 ~p1 in
[%test_result: Bignum.t] (D.find_exn d 1) ~expect:p1;
[%test_result: Bignum.t] (D.find_exn d 2) ~expect:Bignum.(one - p1))
;;
let%test_unit "monad laws" =
let f x = D.singleton (module Int) (x + 1) in
let g x =
let p1 = Bignum.(1 // 2) in
D.combine ~p1 ~d1:(D.singleton (module Int) x) ~d2:(D.singleton (module Int) (-x))
in
let t = D.singleton (module Int) 0 in
Q.test Int.quickcheck_generator ~f:(fun v ->
let open D.Let_syntax in
CR azeng : Add D.M(Int).t
[%test_result: D.M(Int).t] (return (module Int) v >>= f) ~expect:(f v);
[%test_result: D.M(Int).t] (return (module Int) v >>= g) ~expect:(g v);
[%test_result: D.M(Int).t] (t >>= return (module Int)) ~expect:t;
[%test_result: D.M(Int).t] (t >>= f >>= g) ~expect:(t >>= fun x -> f x >>= g);
[%test_result: D.M(Int).t] (t >>= g >>= f) ~expect:(t >>= fun x -> g x >>= f))
;;
let%test_unit "bind" =
let half = Bignum.(1 // 2) in
let fifth = Bignum.(1 // 5) in
let f x =
D.combine
~p1:half
~d1:(D.singleton (module Int) x)
~d2:(D.singleton (module Int) (x + 1))
in
let t =
D.combine ~p1:fifth ~d1:(D.singleton (module Int) 0) ~d2:(D.singleton (module Int) 1)
in
let expect =
[ (0, Bignum.(1 // 10)); (1, Bignum.(5 // 10)); (2, Bignum.(4 // 10)) ]
|> D.of_alist_exn (module Int)
in
[%test_result: D.M(Int).t] (D.bind t ~f) ~expect
;;
let%test_unit "uniform" =
Q.test
(List.gen_non_empty [%quickcheck.generator: D.M(Int).t])
~sexp_of:[%sexp_of: D.M(Int).t list]
~shrinker:[%quickcheck.shrinker: _ list]
~f:(fun ds ->
let n = List.length ds in
let d = D.uniform ds in
Map.iteri (D.to_map d) ~f:(fun ~key ~data ->
let expect =
let open Bignum.O in
List.sum
(module Bignum)
ds
~f:(fun d -> D.find d key |> Option.value ~default:Bignum.zero)
/ of_int n
in
[%test_result: Bignum.t] data ~expect))
;;
let%test_unit "uniform'" =
let gen =
let open Quickcheck.Let_syntax in
let%map xs = List.gen_non_empty Int.quickcheck_generator in
List.dedup_and_sort xs ~compare:Int.compare
in
Q.test
gen
~sexp_of:[%sexp_of: int list]
~shrinker:[%quickcheck.shrinker: int list]
~f:(fun ks ->
let t = D.uniform' (module Int) ks in
let expect =
let length = List.length ks in
let prob = Bignum.(1 // length) in
ks |> List.map ~f:(fun k -> k, prob) |> D.of_alist_exn (module Int)
in
[%test_result: D.M(Int).t] t ~expect)
;;
let%test_unit "cartesian_product" =
let gen = [%quickcheck.generator: D.M(Int).t * D.M(Int).t] in
Q.test gen ~sexp_of:[%sexp_of: D.M(Int).t * D.M(Int).t] ~f:(fun (d1, d2) ->
let d = D.cartesian_product d1 d2 in
Map.iteri (D.to_map d1) ~f:(fun ~key:k1 ~data:p1 ->
Map.iteri (D.to_map d2) ~f:(fun ~key:k2 ~data:p2 ->
[%test_result: Bignum.t] ~expect:Bignum.(p1 * p2) (D.find_exn d (k1, k2)))))
;;
| |
5cd2f6044e735c1886ad15ae14e0039e80ae1e97e9cd5c7ac044754726f2ab71 | headwinds/daterangepicker | project.clj | (defproject material-ui-reagent "0.6.0"
:min-lein-version "2.5.3"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.339"]
[reagent "0.8.1"]
[re-frame "0.9.4"]
[cljs-ajax "0.7.3"]
[figwheel "0.5.16"]
[cljsjs/material-ui "1.2.1-1"]
[cljsjs/material-ui-icons "1.1.0-1"]
[cljsjs/react-select "1.2.1-1"]
[cljsjs/react-autosuggest "9.3.4-0"]
[cljsjs/moment "2.17.1-1"]
[secretary "1.2.3"]
[compojure "1.6.0"]
[ring/ring-jetty-adapter "1.6.2"]
[ring/ring-ssl "0.3.0"]
[environ "1.1.0"]]
:plugins [[environ/environ.lein "0.3.1"]
[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.16"]]
:hooks [environ.leiningen.hooks]
:uberjar-name "example.jar"
:figwheel {:repl false
:http-server-root "public"
:server-port 5000}
:profiles {:dev {:dependencies [[com.cemerick/piggieback "0.2.2"]
[figwheel-sidecar "0.5.13"]
[binaryage/devtools "0.9.4"]]
:source-paths ["src" "dev"]
:cljsbuild {:builds [{:id "dev"
:source-paths ["src"]
:figwheel true
:compiler {:main "example.core"
:preloads [devtools.preload]
:asset-path "js/out"
:output-to "resources/public/js/main.js"
:output-dir "resources/public/js/out"
:optimizations :none
:recompile-dependents true
:source-map true}}]}}
:uberjar {:env {:production true}
:source-paths ["src"]
:prep-tasks ["compile" ["cljsbuild" "once"]]
:cljsbuild {:builds [{:id "production"
:source-paths ["src"]
:jar true
:compiler {:main "example.core"
:asset-path "js/out"
:output-to "resources/public/js/main.js"
:output-dir "resources/public/js/out"
:optimizations :advanced
:pretty-print false}}]}}})
| null | https://raw.githubusercontent.com/headwinds/daterangepicker/33cf0a0f5caec4365a5de612e3912360e07520d6/ranger/project.clj | clojure | (defproject material-ui-reagent "0.6.0"
:min-lein-version "2.5.3"
:dependencies [[org.clojure/clojure "1.9.0"]
[org.clojure/clojurescript "1.10.339"]
[reagent "0.8.1"]
[re-frame "0.9.4"]
[cljs-ajax "0.7.3"]
[figwheel "0.5.16"]
[cljsjs/material-ui "1.2.1-1"]
[cljsjs/material-ui-icons "1.1.0-1"]
[cljsjs/react-select "1.2.1-1"]
[cljsjs/react-autosuggest "9.3.4-0"]
[cljsjs/moment "2.17.1-1"]
[secretary "1.2.3"]
[compojure "1.6.0"]
[ring/ring-jetty-adapter "1.6.2"]
[ring/ring-ssl "0.3.0"]
[environ "1.1.0"]]
:plugins [[environ/environ.lein "0.3.1"]
[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.16"]]
:hooks [environ.leiningen.hooks]
:uberjar-name "example.jar"
:figwheel {:repl false
:http-server-root "public"
:server-port 5000}
:profiles {:dev {:dependencies [[com.cemerick/piggieback "0.2.2"]
[figwheel-sidecar "0.5.13"]
[binaryage/devtools "0.9.4"]]
:source-paths ["src" "dev"]
:cljsbuild {:builds [{:id "dev"
:source-paths ["src"]
:figwheel true
:compiler {:main "example.core"
:preloads [devtools.preload]
:asset-path "js/out"
:output-to "resources/public/js/main.js"
:output-dir "resources/public/js/out"
:optimizations :none
:recompile-dependents true
:source-map true}}]}}
:uberjar {:env {:production true}
:source-paths ["src"]
:prep-tasks ["compile" ["cljsbuild" "once"]]
:cljsbuild {:builds [{:id "production"
:source-paths ["src"]
:jar true
:compiler {:main "example.core"
:asset-path "js/out"
:output-to "resources/public/js/main.js"
:output-dir "resources/public/js/out"
:optimizations :advanced
:pretty-print false}}]}}})
| |
26d06c957ba46a63ef182cb91f2e8a945832fa9c43cc7bf474e01eb2500437b5 | cram2/cram | discrete.lisp | ;; Discrete random variables
, Sat Nov 11 2006 - 21:51
Time - stamp : < 2014 - 12 - 26 13:18:36EST discrete.lisp >
;;
Copyright 2006 , 2007 , 2008 , 2009 , 2011 , 2012 , 2014
Distributed under the terms of the GNU General Public License
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(in-package :gsl)
(named-readtables:in-readtable :antik)
;;; /usr/include/gsl/gsl_randist.h
(defmobject discrete-random "gsl_ran_discrete"
(((dim0 probabilities) :sizet) ((grid:foreign-pointer probabilities) :pointer))
"lookup table for the discrete random number generator"
:allocator "gsl_ran_discrete_preproc"
:allocate-inputs (probabilities)
"Make a structure that contains the lookup
table for the discrete random number generator. The array probabilities contains
the probabilities of the discrete events; these array elements must all be
positive, but they needn't add up to one (so you can think of them more
generally as ``weights'')---the preprocessor will normalize appropriately.
This return value is used as an argument to #'discrete.")
(defmfun sample
((generator random-number-generator) (type (eql :discrete))
&key table)
"gsl_ran_discrete"
(((mpointer generator) :pointer) ((mpointer table) :pointer))
:definition :method
:c-return :sizet
:documentation
"Generate discrete random numbers.")
(defmfun discrete-pdf (k table)
"gsl_ran_discrete_pdf"
((k :sizet) ((mpointer table) :pointer))
:c-return :double
"The probability P[k] of observing the variable k.
Since P[k] is not stored as part of the lookup table, it must be
recomputed; this computation takes O(K), so if K is large
and you care about the original array P[k] used to create the
lookup table, then you should just keep this original array P[k]
around.")
;;; Examples and unit test
(save-test discrete
(let* ((probabilities #m(0.25d0 0.5d0 0.25d0))
(table (make-discrete-random probabilities))
(rng (make-random-number-generator +mt19937+ 0)))
(loop for i from 0 to 10
collect
(sample rng :discrete :table table)))
(let* ((probabilities #m(0.25d0 0.5d0 0.25d0))
(table (make-discrete-random probabilities)))
(discrete-pdf 1 table)))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/random/discrete.lisp | lisp | Discrete random variables
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
/usr/include/gsl/gsl_randist.h
these array elements must all be
this computation takes O(K), so if K is large
Examples and unit test | , Sat Nov 11 2006 - 21:51
Time - stamp : < 2014 - 12 - 26 13:18:36EST discrete.lisp >
Copyright 2006 , 2007 , 2008 , 2009 , 2011 , 2012 , 2014
Distributed under the terms of the GNU General Public License
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :gsl)
(named-readtables:in-readtable :antik)
(defmobject discrete-random "gsl_ran_discrete"
(((dim0 probabilities) :sizet) ((grid:foreign-pointer probabilities) :pointer))
"lookup table for the discrete random number generator"
:allocator "gsl_ran_discrete_preproc"
:allocate-inputs (probabilities)
"Make a structure that contains the lookup
table for the discrete random number generator. The array probabilities contains
positive, but they needn't add up to one (so you can think of them more
generally as ``weights'')---the preprocessor will normalize appropriately.
This return value is used as an argument to #'discrete.")
(defmfun sample
((generator random-number-generator) (type (eql :discrete))
&key table)
"gsl_ran_discrete"
(((mpointer generator) :pointer) ((mpointer table) :pointer))
:definition :method
:c-return :sizet
:documentation
"Generate discrete random numbers.")
(defmfun discrete-pdf (k table)
"gsl_ran_discrete_pdf"
((k :sizet) ((mpointer table) :pointer))
:c-return :double
"The probability P[k] of observing the variable k.
Since P[k] is not stored as part of the lookup table, it must be
and you care about the original array P[k] used to create the
lookup table, then you should just keep this original array P[k]
around.")
(save-test discrete
(let* ((probabilities #m(0.25d0 0.5d0 0.25d0))
(table (make-discrete-random probabilities))
(rng (make-random-number-generator +mt19937+ 0)))
(loop for i from 0 to 10
collect
(sample rng :discrete :table table)))
(let* ((probabilities #m(0.25d0 0.5d0 0.25d0))
(table (make-discrete-random probabilities)))
(discrete-pdf 1 table)))
|
c93c554c3d19b2c6a64bafd0bc5ad1ff45a6e42426ea81d81d0356be5e62452b | DrTom/clj-pg-types | clj_time.clj | (ns pg-types.read-column.timestamp.clj-time
(:require
[pg-types.read-column :refer :all]
[clj-time.coerce :as time-coerce]
))
(defmethod convert-column [:timestamp java.sql.Timestamp]
[_ val _ _]
(time-coerce/from-sql-time val))
(defmethod convert-column [:timestamptz java.sql.Timestamp]
[_ val _ _]
(time-coerce/from-sql-time val))
| null | https://raw.githubusercontent.com/DrTom/clj-pg-types/d847735c46b2da173fd50a6ebe492bead0d75dd5/src/pg_types/read_column/timestamp/clj_time.clj | clojure | (ns pg-types.read-column.timestamp.clj-time
(:require
[pg-types.read-column :refer :all]
[clj-time.coerce :as time-coerce]
))
(defmethod convert-column [:timestamp java.sql.Timestamp]
[_ val _ _]
(time-coerce/from-sql-time val))
(defmethod convert-column [:timestamptz java.sql.Timestamp]
[_ val _ _]
(time-coerce/from-sql-time val))
| |
69e87491a8d20d3cc721691a4931a01335b30d6fb586537e2b978040db0c56b3 | janestreet/ppx_type_directed_value | covariant.ml | open Core
let type_directed_enumerate_bool = [ true; false ]
let type_directed_enumerate_unit = [ () ]
let type_directed_enumerate_option l = None :: List.map l ~f:(fun a -> Some a)
type t =
{ f1 : bool
; f2 : bool
}
[@@deriving type_directed_enumerate]
type t_var =
| A
| B of bool * bool
[@@deriving type_directed_enumerate]
type t_poly =
| Foo
| Bar of bool
| Baz of [ `A | `B of unit option ]
[@@deriving type_directed_enumerate]
type t_empty = | [@@deriving type_directed_enumerate]
type t_record_poly =
{ foo : [ `A | `B ]
; bar : [ `C | `D ]
}
[@@deriving type_directed_enumerate]
let%test "enumerate_record" =
[%compare: _ list]
type_directed_enumerate
[ { f1 = true; f2 = true }
; { f1 = true; f2 = false }
; { f1 = false; f2 = true }
; { f1 = false; f2 = false }
]
= 0
;;
let%test "enumerate_variant" =
[%compare: _ list]
type_directed_enumerate_t_var
[ A; B (true, true); B (true, false); B (false, true); B (false, false) ]
= 0
;;
let%test "enumerate_poly" =
[%compare: _ list]
type_directed_enumerate_t_poly
[ Foo; Bar true; Bar false; Baz `A; Baz (`B None); Baz (`B (Some ())) ]
= 0
;;
let%test "enumerate_record_poly" =
[%compare: _ list]
type_directed_enumerate_t_record_poly
[ { foo = `A; bar = `C }
; { foo = `A; bar = `D }
; { foo = `B; bar = `C }
; { foo = `B; bar = `D }
]
= 0
;;
let%test "enumerate_empty" = [%compare: _ list] type_directed_enumerate_t_empty [] = 0
| null | https://raw.githubusercontent.com/janestreet/ppx_type_directed_value/f85693cc6d0ad8a9bc3bad55fed22a3d78e1fcaf/test/inline/covariant.ml | ocaml | open Core
let type_directed_enumerate_bool = [ true; false ]
let type_directed_enumerate_unit = [ () ]
let type_directed_enumerate_option l = None :: List.map l ~f:(fun a -> Some a)
type t =
{ f1 : bool
; f2 : bool
}
[@@deriving type_directed_enumerate]
type t_var =
| A
| B of bool * bool
[@@deriving type_directed_enumerate]
type t_poly =
| Foo
| Bar of bool
| Baz of [ `A | `B of unit option ]
[@@deriving type_directed_enumerate]
type t_empty = | [@@deriving type_directed_enumerate]
type t_record_poly =
{ foo : [ `A | `B ]
; bar : [ `C | `D ]
}
[@@deriving type_directed_enumerate]
let%test "enumerate_record" =
[%compare: _ list]
type_directed_enumerate
[ { f1 = true; f2 = true }
; { f1 = true; f2 = false }
; { f1 = false; f2 = true }
; { f1 = false; f2 = false }
]
= 0
;;
let%test "enumerate_variant" =
[%compare: _ list]
type_directed_enumerate_t_var
[ A; B (true, true); B (true, false); B (false, true); B (false, false) ]
= 0
;;
let%test "enumerate_poly" =
[%compare: _ list]
type_directed_enumerate_t_poly
[ Foo; Bar true; Bar false; Baz `A; Baz (`B None); Baz (`B (Some ())) ]
= 0
;;
let%test "enumerate_record_poly" =
[%compare: _ list]
type_directed_enumerate_t_record_poly
[ { foo = `A; bar = `C }
; { foo = `A; bar = `D }
; { foo = `B; bar = `C }
; { foo = `B; bar = `D }
]
= 0
;;
let%test "enumerate_empty" = [%compare: _ list] type_directed_enumerate_t_empty [] = 0
| |
620b26fa7b22d66c19bcc1d40261a15c33e993d431bf4c2ee0a0680e32367b6a | racket/typed-racket | define-new-subtype.rkt | #;
(exn-pred #rx"expected: Radians.*given: Degrees")
#lang typed/racket/base
(require "../succeed/define-new-subtype.rkt")
(sin (degrees 0))
| null | https://raw.githubusercontent.com/racket/typed-racket/1c2da7b7fc3e4b8779cdc3bd670f2e08e460ed1b/typed-racket-test/external/fail/define-new-subtype.rkt | racket | (exn-pred #rx"expected: Radians.*given: Degrees")
#lang typed/racket/base
(require "../succeed/define-new-subtype.rkt")
(sin (degrees 0))
| |
0c55dedd85c41b02cd3b47e98c813d53e048ff8d398e84fca9da521986a643d0 | crategus/cl-cffi-gtk | rtest-gtk-text-iter.lisp | (def-suite gtk-text-iter :in gtk-suite)
(in-suite gtk-text-iter)
(defvar *gtk-text-iter-sample-text*
"Weit hinten, hinter den Wortbergen, fern der Länder Vokalien und Konsonantien
leben die Blindtexte. Abgeschieden wohnen Sie in Buchstabenhausen an der Küste
des Semantik, eines großen Sprachozeans. Ein kleines Bächlein namens Duden
fließt durch ihren Ort und versorgt sie mit den nötigen Regelialien. Es ist ein
paradiesmatisches Land, in dem einem gebratene Satzteile in den Mund fliegen.
Nicht einmal von der allmächtigen Interpunktion werden die Blindtexte beherrscht
– ein geradezu unorthographisches Leben.
Eines Tages aber beschloss eine kleine Zeile Blindtext, ihr Name war Lorem
Ipsum, hinaus zu gehen in die weite Grammatik. Der große Oxmox riet ihr davon
ab, da es dort wimmele von bösen Kommata, wilden Fragezeichen und hinterhältigen
Semikola, doch das Blindtextchen ließ sich nicht beirren. Es packte seine sieben
Versalien, schob sich sein Initial in den Gürtel und machte sich auf den Weg.
Als es die ersten Hügel des Kursivgebirges erklommen hatte, warf es einen
letzten Blick zurück auf die Skyline seiner Heimatstadt Buchstabenhausen, die
Headline von Alphabetdorf und die Subline seiner eigenen Straße, der
Zeilengasse. Wehmütig lief ihm eine rhetorische Frage über die Wange, dann
setzte es seinen Weg fort.
Unterwegs traf es eine Copy. Die Copy warnte das Blindtextchen, da, wo sie
herkäme, wäre sie zigmal umgeschrieben worden und alles, was von ihrem Ursprung
noch übrig wäre, sei das Wort »und« und das Blindtextchen solle umkehren und
wieder in sein eigenes, sicheres Land zurückkehren.
Doch alles Gutzureden konnte es nicht überzeugen und so dauerte es nicht lange,
bis ihm ein paar heimtückische Werbetexter auflauerten, es mit Longe und Parole
betrunken machten und es dann in ihre Agentur schleppten, wo sie es für ihre
Projekte wieder und wieder missbrauchten. Und wenn es nicht umgeschrieben wurde,
dann benutzen Sie es immer noch.")
;;; GtkTextIter
(test gtk-text-iter-boxed
(is-true (g-type-is-a (gtype "GtkTextIter") +g-type-boxed+))
(is-true (eq 'gtk-text-iter (type-of (make-instance 'gtk-text-iter))))
(is (eq 'gobject::g-boxed-opaque-wrapper-info
(type-of (gobject::get-g-boxed-foreign-info 'gtk-text-iter))))
(is (eq 'gobject::g-boxed-opaque-wrapper-info
(type-of (gobject::get-g-boxed-foreign-info-for-gtype (gtype "GtkTextIter")))))
)
#+nil
(test gtk-text-iter-boxed.2
(let* ((buffer (make-instance 'gtk-text-buffer :text "text")))
(dotimes (i 1000000)
(gtk-text-buffer-start-iter buffer))
))
;;; gtk_text_iter_get_buffer
(test gtk-text-iter-buffer
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-start-iter buffer)))
(is (eq buffer (gtk-text-iter-buffer iter)))))
;;; gtk_text_iter_copy
;;; gtk_text_iter_assign
;;; gtk_text_iter_free
;;; gtk_text_iter_get_offset
;;; gtk_text_iter_set_offset
(test gtk-text-iter-offset
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-offset iter)))
(is (eq #\t (gtk-text-iter-char iter)))
(is (= 17 (setf (gtk-text-iter-offset iter) 17)))
(is (eq #\f (gtk-text-iter-char iter)))))
;;; gtk_text_iter_get_line
;;; gtk_text_iter_set_line
#-windows
(test gtk-text-iter-line
(let* ((buffer (make-instance 'gtk-text-buffer
:text *gtk-text-iter-sample-text*))
(iter (gtk-text-buffer-iter-at-offset buffer 100)))
(is (= 1 (gtk-text-iter-line iter)))
(is (eq #\A (gtk-text-iter-char iter)))
(is (= 5 (setf (gtk-text-iter-line iter) 5)))
(is (eq #\N (gtk-text-iter-char iter)))))
;;; gtk_text_iter_get_line_offset
;;; gtk_text_iter_set_line_offset
(test gtk-text-iter-line-offset
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-line-offset iter)))))
;;; gtk_text_iter_get_line_index
(test gtk-text-iter-line-index
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-line-index iter)))))
;;; gtk_text_iter_get_visible_line_index
(test gtk-text-iter-visible-line-index
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-visible-line-index iter)))))
;;; gtk_text_iter_get_visible_line_offset
(test gtk-text-iter-visible-line-offset
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-visible-line-offset iter)))))
;;; gtk_text_iter_get_char
(test gtk-text-iter-char
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (eql #\t (gtk-text-iter-char iter)))))
;;; gtk_text_iter_get_slice
(test gtk-text-iter-slice
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-slice start end)))))
;;; gtk_text_iter_get_text
(test gtk-text-iter-text
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-text start end)))))
;;; gtk_text_iter_get_visible_slice
(test gtk-text-iter-visible-slice
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-visible-slice start end)))))
;;; gtk_text_iter_get_visible_text
(test gtk-text-iter-visible-text
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-visible-text start end)))))
;;; gtk_text_iter_get_pixbuf
(test gtk-text-iter-pixbuf
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(gtk-text-buffer-insert-pixbuf buffer iter (make-instance 'gdk-pixbuf))
(let ((iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (eq 'gdk-pixbuf (type-of (gtk-text-iter-pixbuf iter)))))))
;;; gtk_text_iter_get_marks
(test gtk-text-iter-marks
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(gtk-text-buffer-add-mark buffer (gtk-text-mark-new nil t) iter)
(is (eq 'gtk-text-mark
(type-of (first (gtk-text-iter-marks iter)))))))
;;; gtk_text_iter_get_toggled_tags
(test gtk-text-iter-toggled-tags
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(gtk-text-tag-table-add (gtk-text-buffer-tag-table buffer)
(make-instance 'gtk-text-tag
:name "bold"
:weight 700))
(gtk-text-buffer-apply-tag buffer "bold" start end)
(is (eq 'gtk-text-tag
(type-of (first (gtk-text-iter-toggled-tags start t)))))))
;;; gtk_text_iter_get_child_anchor
#+nil
(test gtk-text-iter-child-anchor
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(gtk-text-buffer-create-child-anchor buffer iter)
(is (eq 'gtk-text-tag
(type-of (gtk-text-iter-child-anchor iter))))))
;;; gtk_text_iter_begins_tag
;;; gtk_text_iter_ends_tag
;;; gtk_text_iter_toggles_tag
;;; gtk_text_iter_has_tag
;;; gtk_text_iter_get_tags
;;; gtk_text_iter_editable
;;; gtk_text_iter_can_insert
;;; gtk_text_iter_ends_word
;;; gtk_text_iter_inside_word
;;; gtk_text_iter_starts_line
;;; gtk_text_iter_ends_line
;;; gtk_text_iter_starts_sentence
gtk_text_iter_ends_sentence
gtk_text_iter_inside_sentence
;;; gtk_text_iter_is_cursor_position
;;; gtk_text_iter_get_chars_in_line
;;; gtk_text_iter_get_bytes_in_line
;;; gtk_text_iter_get_attributes
;; FIXME: Check this more carefully. We get an error with this function.
;; The implementation of gtk-text-attributes does not work.
#+nil
(test gtk-text-iter-attributes
(let* ((buffer (make-instance 'gtk-text-buffer
:text "Some sample text for the text buffer."))
(view (gtk-text-view-new-with-buffer buffer))
(attributes (gtk-text-view-default-attributes view))
(iter (gtk-text-buffer-start-iter buffer)))
(is (typep buffer 'gtk-text-buffer))
(is (typep view 'gtk-text-view))
(is (typep attributes 'gtk-text-attributes))
(is (typep iter 'gtk-text-iter))
; (is-false (gtk-text-iter-attributes iter attributes))
; (is-false (gtk-text-iter-attributes iter (null-pointer)))
))
;;; gtk_text_iter_get_language
(test gtk-text-iter-language
(let* ((buffer (make-instance 'gtk-text-buffer
:text "Some sample text for the text buffer."))
(iter (gtk-text-buffer-start-iter buffer)))
(is (typep (gtk-text-iter-language iter) 'pango-language))))
;;; gtk_text_iter_is_end
;;; gtk_text_iter_is_start
;;; gtk_text_iter_forward_char
;;; gtk_text_iter_forward_chars
;;; gtk_text_iter_backward_chars
;;; gtk_text_iter_forward_line
;;; gtk_text_iter_backward_line
;;; gtk_text_iter_forward_lines
;;; gtk_text_iter_backward_lines
;;; gtk_text_iter_forward_word_ends
;;; gtk_text_iter_backward_word_starts
;;; gtk_text_iter_forward_word_end
gtk_text_iter_backward_word_start
;;; gtk_text_iter_forward_cursor_position
;;; gtk_text_iter_backward_cursor_position
;;; gtk_text_iter_forward_cursor_positions
;;; gtk_text_iter_backward_cursor_positions
;;; gtk_text_iter_backward_sentence_start
;;; gtk_text_iter_backward_sentence_starts
;;; gtk_text_iter_forward_sentence_end
gtk_text_iter_forward_sentence_ends
;;; gtk_text_iter_forward_visible_word_ends
;;; gtk_text_iter_backward_visible_word_starts
;;; gtk_text_iter_forward_visible_word_end
;;; gtk_text_iter_backward_visible_word_start
;;; gtk_text_iter_forward_visible_cursor_position
;;; gtk_text_iter_backward_visible_cursor_position
;;; gtk_text_iter_forward_visible_cursor_positions
;;; gtk_text_iter_backward_visible_cursor_positions
;;; gtk_text_iter_forward_visible_line
;;; gtk_text_iter_backward_visible_line
;;; gtk_text_iter_forward_visible_lines
;;; gtk_text_iter_backward_visible_lines
;;; gtk_text_iter_set_line_index
;;; gtk_text_iter_set_visible_line_index
;;; gtk_text_iter_set_visible_line_offset
;;; gtk_text_iter_forward_to_end
;;; gtk_text_iter_forward_to_line_end
;;; gtk_text_iter_forward_to_tag_toggle
;;; gtk_text_iter_backward_to_tag_toggle
gtk_text_iter_backward_find_char
;;;
;;; GtkTextSearchFlags
;;;
gtk_text_iter_backward_search
;;; gtk_text_iter_equal
;;; gtk_text_iter_compare
;;; gtk_text_iter_in_range
gtk_text_iter_order
2021 - 10 - 19
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/7f5a09f78d8004a71efa82794265f2587fff98ab/test/rtest-gtk-text-iter.lisp | lisp | GtkTextIter
gtk_text_iter_get_buffer
gtk_text_iter_copy
gtk_text_iter_assign
gtk_text_iter_free
gtk_text_iter_get_offset
gtk_text_iter_set_offset
gtk_text_iter_get_line
gtk_text_iter_set_line
gtk_text_iter_get_line_offset
gtk_text_iter_set_line_offset
gtk_text_iter_get_line_index
gtk_text_iter_get_visible_line_index
gtk_text_iter_get_visible_line_offset
gtk_text_iter_get_char
gtk_text_iter_get_slice
gtk_text_iter_get_text
gtk_text_iter_get_visible_slice
gtk_text_iter_get_visible_text
gtk_text_iter_get_pixbuf
gtk_text_iter_get_marks
gtk_text_iter_get_toggled_tags
gtk_text_iter_get_child_anchor
gtk_text_iter_begins_tag
gtk_text_iter_ends_tag
gtk_text_iter_toggles_tag
gtk_text_iter_has_tag
gtk_text_iter_get_tags
gtk_text_iter_editable
gtk_text_iter_can_insert
gtk_text_iter_ends_word
gtk_text_iter_inside_word
gtk_text_iter_starts_line
gtk_text_iter_ends_line
gtk_text_iter_starts_sentence
gtk_text_iter_is_cursor_position
gtk_text_iter_get_chars_in_line
gtk_text_iter_get_bytes_in_line
gtk_text_iter_get_attributes
FIXME: Check this more carefully. We get an error with this function.
The implementation of gtk-text-attributes does not work.
(is-false (gtk-text-iter-attributes iter attributes))
(is-false (gtk-text-iter-attributes iter (null-pointer)))
gtk_text_iter_get_language
gtk_text_iter_is_end
gtk_text_iter_is_start
gtk_text_iter_forward_char
gtk_text_iter_forward_chars
gtk_text_iter_backward_chars
gtk_text_iter_forward_line
gtk_text_iter_backward_line
gtk_text_iter_forward_lines
gtk_text_iter_backward_lines
gtk_text_iter_forward_word_ends
gtk_text_iter_backward_word_starts
gtk_text_iter_forward_word_end
gtk_text_iter_forward_cursor_position
gtk_text_iter_backward_cursor_position
gtk_text_iter_forward_cursor_positions
gtk_text_iter_backward_cursor_positions
gtk_text_iter_backward_sentence_start
gtk_text_iter_backward_sentence_starts
gtk_text_iter_forward_sentence_end
gtk_text_iter_forward_visible_word_ends
gtk_text_iter_backward_visible_word_starts
gtk_text_iter_forward_visible_word_end
gtk_text_iter_backward_visible_word_start
gtk_text_iter_forward_visible_cursor_position
gtk_text_iter_backward_visible_cursor_position
gtk_text_iter_forward_visible_cursor_positions
gtk_text_iter_backward_visible_cursor_positions
gtk_text_iter_forward_visible_line
gtk_text_iter_backward_visible_line
gtk_text_iter_forward_visible_lines
gtk_text_iter_backward_visible_lines
gtk_text_iter_set_line_index
gtk_text_iter_set_visible_line_index
gtk_text_iter_set_visible_line_offset
gtk_text_iter_forward_to_end
gtk_text_iter_forward_to_line_end
gtk_text_iter_forward_to_tag_toggle
gtk_text_iter_backward_to_tag_toggle
GtkTextSearchFlags
gtk_text_iter_equal
gtk_text_iter_compare
gtk_text_iter_in_range | (def-suite gtk-text-iter :in gtk-suite)
(in-suite gtk-text-iter)
(defvar *gtk-text-iter-sample-text*
"Weit hinten, hinter den Wortbergen, fern der Länder Vokalien und Konsonantien
leben die Blindtexte. Abgeschieden wohnen Sie in Buchstabenhausen an der Küste
des Semantik, eines großen Sprachozeans. Ein kleines Bächlein namens Duden
fließt durch ihren Ort und versorgt sie mit den nötigen Regelialien. Es ist ein
paradiesmatisches Land, in dem einem gebratene Satzteile in den Mund fliegen.
Nicht einmal von der allmächtigen Interpunktion werden die Blindtexte beherrscht
– ein geradezu unorthographisches Leben.
Eines Tages aber beschloss eine kleine Zeile Blindtext, ihr Name war Lorem
Ipsum, hinaus zu gehen in die weite Grammatik. Der große Oxmox riet ihr davon
ab, da es dort wimmele von bösen Kommata, wilden Fragezeichen und hinterhältigen
Semikola, doch das Blindtextchen ließ sich nicht beirren. Es packte seine sieben
Versalien, schob sich sein Initial in den Gürtel und machte sich auf den Weg.
Als es die ersten Hügel des Kursivgebirges erklommen hatte, warf es einen
letzten Blick zurück auf die Skyline seiner Heimatstadt Buchstabenhausen, die
Headline von Alphabetdorf und die Subline seiner eigenen Straße, der
Zeilengasse. Wehmütig lief ihm eine rhetorische Frage über die Wange, dann
setzte es seinen Weg fort.
Unterwegs traf es eine Copy. Die Copy warnte das Blindtextchen, da, wo sie
herkäme, wäre sie zigmal umgeschrieben worden und alles, was von ihrem Ursprung
noch übrig wäre, sei das Wort »und« und das Blindtextchen solle umkehren und
wieder in sein eigenes, sicheres Land zurückkehren.
Doch alles Gutzureden konnte es nicht überzeugen und so dauerte es nicht lange,
bis ihm ein paar heimtückische Werbetexter auflauerten, es mit Longe und Parole
betrunken machten und es dann in ihre Agentur schleppten, wo sie es für ihre
Projekte wieder und wieder missbrauchten. Und wenn es nicht umgeschrieben wurde,
dann benutzen Sie es immer noch.")
(test gtk-text-iter-boxed
(is-true (g-type-is-a (gtype "GtkTextIter") +g-type-boxed+))
(is-true (eq 'gtk-text-iter (type-of (make-instance 'gtk-text-iter))))
(is (eq 'gobject::g-boxed-opaque-wrapper-info
(type-of (gobject::get-g-boxed-foreign-info 'gtk-text-iter))))
(is (eq 'gobject::g-boxed-opaque-wrapper-info
(type-of (gobject::get-g-boxed-foreign-info-for-gtype (gtype "GtkTextIter")))))
)
#+nil
(test gtk-text-iter-boxed.2
(let* ((buffer (make-instance 'gtk-text-buffer :text "text")))
(dotimes (i 1000000)
(gtk-text-buffer-start-iter buffer))
))
(test gtk-text-iter-buffer
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-start-iter buffer)))
(is (eq buffer (gtk-text-iter-buffer iter)))))
(test gtk-text-iter-offset
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-offset iter)))
(is (eq #\t (gtk-text-iter-char iter)))
(is (= 17 (setf (gtk-text-iter-offset iter) 17)))
(is (eq #\f (gtk-text-iter-char iter)))))
#-windows
(test gtk-text-iter-line
(let* ((buffer (make-instance 'gtk-text-buffer
:text *gtk-text-iter-sample-text*))
(iter (gtk-text-buffer-iter-at-offset buffer 100)))
(is (= 1 (gtk-text-iter-line iter)))
(is (eq #\A (gtk-text-iter-char iter)))
(is (= 5 (setf (gtk-text-iter-line iter) 5)))
(is (eq #\N (gtk-text-iter-char iter)))))
(test gtk-text-iter-line-offset
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-line-offset iter)))))
(test gtk-text-iter-line-index
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-line-index iter)))))
(test gtk-text-iter-visible-line-index
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-visible-line-index iter)))))
(test gtk-text-iter-visible-line-offset
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (= 12 (gtk-text-iter-visible-line-offset iter)))))
(test gtk-text-iter-char
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (eql #\t (gtk-text-iter-char iter)))))
(test gtk-text-iter-slice
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-slice start end)))))
(test gtk-text-iter-text
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-text start end)))))
(test gtk-text-iter-visible-slice
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-visible-slice start end)))))
(test gtk-text-iter-visible-text
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(is (equal "text" (gtk-text-iter-visible-text start end)))))
(test gtk-text-iter-pixbuf
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(gtk-text-buffer-insert-pixbuf buffer iter (make-instance 'gdk-pixbuf))
(let ((iter (gtk-text-buffer-iter-at-offset buffer 12)))
(is (eq 'gdk-pixbuf (type-of (gtk-text-iter-pixbuf iter)))))))
(test gtk-text-iter-marks
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(gtk-text-buffer-add-mark buffer (gtk-text-mark-new nil t) iter)
(is (eq 'gtk-text-mark
(type-of (first (gtk-text-iter-marks iter)))))))
(test gtk-text-iter-toggled-tags
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(start (gtk-text-buffer-iter-at-offset buffer 12))
(end (gtk-text-buffer-iter-at-offset buffer 16)))
(gtk-text-tag-table-add (gtk-text-buffer-tag-table buffer)
(make-instance 'gtk-text-tag
:name "bold"
:weight 700))
(gtk-text-buffer-apply-tag buffer "bold" start end)
(is (eq 'gtk-text-tag
(type-of (first (gtk-text-iter-toggled-tags start t)))))))
#+nil
(test gtk-text-iter-child-anchor
(let* ((buffer (make-instance 'gtk-text-buffer
:text
"Some sample text for the text buffer."))
(iter (gtk-text-buffer-iter-at-offset buffer 12)))
(gtk-text-buffer-create-child-anchor buffer iter)
(is (eq 'gtk-text-tag
(type-of (gtk-text-iter-child-anchor iter))))))
gtk_text_iter_ends_sentence
gtk_text_iter_inside_sentence
#+nil
(test gtk-text-iter-attributes
(let* ((buffer (make-instance 'gtk-text-buffer
:text "Some sample text for the text buffer."))
(view (gtk-text-view-new-with-buffer buffer))
(attributes (gtk-text-view-default-attributes view))
(iter (gtk-text-buffer-start-iter buffer)))
(is (typep buffer 'gtk-text-buffer))
(is (typep view 'gtk-text-view))
(is (typep attributes 'gtk-text-attributes))
(is (typep iter 'gtk-text-iter))
))
(test gtk-text-iter-language
(let* ((buffer (make-instance 'gtk-text-buffer
:text "Some sample text for the text buffer."))
(iter (gtk-text-buffer-start-iter buffer)))
(is (typep (gtk-text-iter-language iter) 'pango-language))))
gtk_text_iter_backward_word_start
gtk_text_iter_forward_sentence_ends
gtk_text_iter_backward_find_char
gtk_text_iter_backward_search
gtk_text_iter_order
2021 - 10 - 19
|
6b6bca49043cf3ca992fd109fd66c162e7afe78dafde664f220a18ae34a7f737 | conscell/hugs-android | Tree.hs | -----------------------------------------------------------------------------
-- |
-- Module : Data.Tree
Copyright : ( c ) The University of Glasgow 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Multi-way trees (/aka/ rose trees) and forests.
--
-----------------------------------------------------------------------------
module Data.Tree(
Tree(..), Forest,
* Two - dimensional drawing
drawTree, drawForest,
-- * Extraction
flatten, levels,
-- * Building trees
unfoldTree, unfoldForest,
unfoldTreeM, unfoldForestM,
unfoldTreeM_BF, unfoldForestM_BF,
) where
import Control.Applicative (Applicative(..), (<$>))
import Control.Monad
import Data.Monoid (Monoid(..))
import Data.Sequence (Seq, empty, singleton, (<|), (|>), fromList,
ViewL(..), ViewR(..), viewl, viewr)
import Data.Foldable (Foldable(foldMap), toList)
import Data.Traversable (Traversable(traverse))
import Data.Typeable
-- | Multi-way trees, also known as /rose trees/.
data Tree a = Node {
rootLabel :: a, -- ^ label value
^ zero or more child trees
}
deriving (Eq, Read, Show)
type Forest a = [Tree a]
treeTc = mkTyCon "Tree"; instance Typeable1 Tree where { typeOf1 _ = mkTyConApp treeTc [] }; instance Typeable a => Typeable (Tree a) where { typeOf = typeOfDefault }
instance Functor Tree where
fmap f (Node x ts) = Node (f x) (map (fmap f) ts)
instance Traversable Tree where
traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts
instance Foldable Tree where
foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts
-- | Neat 2-dimensional drawing of a tree.
drawTree :: Tree String -> String
drawTree = unlines . draw
-- | Neat 2-dimensional drawing of a forest.
drawForest :: Forest String -> String
drawForest = unlines . map drawTree
draw :: Tree String -> [String]
draw (Node x ts0) = x : drawSubTrees ts0
where drawSubTrees [] = []
drawSubTrees [t] =
"|" : shift "`- " " " (draw t)
drawSubTrees (t:ts) =
"|" : shift "+- " "| " (draw t) ++ drawSubTrees ts
shift first other = zipWith (++) (first : repeat other)
-- | The elements of a tree in pre-order.
flatten :: Tree a -> [a]
flatten t = squish t []
where squish (Node x ts) xs = x:Prelude.foldr squish xs ts
-- | Lists of nodes at each level of the tree.
levels :: Tree a -> [[a]]
levels t = map (map rootLabel) $
takeWhile (not . null) $
iterate (concatMap subForest) [t]
-- | Build a tree from a seed value
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
unfoldTree f b = let (a, bs) = f b in Node a (unfoldForest f bs)
-- | Build a forest from a list of seed values
unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
unfoldForest f = map (unfoldTree f)
| Monadic tree builder , in depth - first order
unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM f b = do
(a, bs) <- f b
ts <- unfoldForestM f bs
return (Node a ts)
| Monadic forest builder , in depth - first order
unfoldForestM :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM f = Prelude.mapM (unfoldTreeM f)
| Monadic tree builder , in breadth - first order ,
-- using an algorithm adapted from
-- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
by , /ICFP'00/.
unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b)
where getElement xs = case viewl xs of
x :< _ -> x
EmptyL -> error "unfoldTreeM_BF"
| Monadic forest builder , in breadth - first order ,
-- using an algorithm adapted from
-- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
by , /ICFP'00/.
unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList
-- takes a sequence (queue) of seeds
-- produces a sequence (reversed queue) of trees of the same length
unfoldForestQ :: Monad m => (b -> m (a, [b])) -> Seq b -> m (Seq (Tree a))
unfoldForestQ f aQ = case viewl aQ of
EmptyL -> return empty
a :< aQ -> do
(b, as) <- f a
tQ <- unfoldForestQ f (Prelude.foldl (|>) aQ as)
let (tQ', ts) = splitOnto [] as tQ
return (Node b ts <| tQ')
where splitOnto :: [a'] -> [b'] -> Seq a' -> (Seq a', [a'])
splitOnto as [] q = (q, as)
splitOnto as (_:bs) q = case viewr q of
q' :> a -> splitOnto (a:as) bs q'
EmptyR -> error "unfoldForestQ"
| null | https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/packages/base/Data/Tree.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Tree
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
Portability : portable
Multi-way trees (/aka/ rose trees) and forests.
---------------------------------------------------------------------------
* Extraction
* Building trees
| Multi-way trees, also known as /rose trees/.
^ label value
| Neat 2-dimensional drawing of a tree.
| Neat 2-dimensional drawing of a forest.
| The elements of a tree in pre-order.
| Lists of nodes at each level of the tree.
| Build a tree from a seed value
| Build a forest from a list of seed values
using an algorithm adapted from
/Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
using an algorithm adapted from
/Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
takes a sequence (queue) of seeds
produces a sequence (reversed queue) of trees of the same length | Copyright : ( c ) The University of Glasgow 2002
module Data.Tree(
Tree(..), Forest,
* Two - dimensional drawing
drawTree, drawForest,
flatten, levels,
unfoldTree, unfoldForest,
unfoldTreeM, unfoldForestM,
unfoldTreeM_BF, unfoldForestM_BF,
) where
import Control.Applicative (Applicative(..), (<$>))
import Control.Monad
import Data.Monoid (Monoid(..))
import Data.Sequence (Seq, empty, singleton, (<|), (|>), fromList,
ViewL(..), ViewR(..), viewl, viewr)
import Data.Foldable (Foldable(foldMap), toList)
import Data.Traversable (Traversable(traverse))
import Data.Typeable
data Tree a = Node {
^ zero or more child trees
}
deriving (Eq, Read, Show)
type Forest a = [Tree a]
treeTc = mkTyCon "Tree"; instance Typeable1 Tree where { typeOf1 _ = mkTyConApp treeTc [] }; instance Typeable a => Typeable (Tree a) where { typeOf = typeOfDefault }
instance Functor Tree where
fmap f (Node x ts) = Node (f x) (map (fmap f) ts)
instance Traversable Tree where
traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts
instance Foldable Tree where
foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts
drawTree :: Tree String -> String
drawTree = unlines . draw
drawForest :: Forest String -> String
drawForest = unlines . map drawTree
draw :: Tree String -> [String]
draw (Node x ts0) = x : drawSubTrees ts0
where drawSubTrees [] = []
drawSubTrees [t] =
"|" : shift "`- " " " (draw t)
drawSubTrees (t:ts) =
"|" : shift "+- " "| " (draw t) ++ drawSubTrees ts
shift first other = zipWith (++) (first : repeat other)
flatten :: Tree a -> [a]
flatten t = squish t []
where squish (Node x ts) xs = x:Prelude.foldr squish xs ts
levels :: Tree a -> [[a]]
levels t = map (map rootLabel) $
takeWhile (not . null) $
iterate (concatMap subForest) [t]
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
unfoldTree f b = let (a, bs) = f b in Node a (unfoldForest f bs)
unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
unfoldForest f = map (unfoldTree f)
| Monadic tree builder , in depth - first order
unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM f b = do
(a, bs) <- f b
ts <- unfoldForestM f bs
return (Node a ts)
| Monadic forest builder , in depth - first order
unfoldForestM :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM f = Prelude.mapM (unfoldTreeM f)
| Monadic tree builder , in breadth - first order ,
by , /ICFP'00/.
unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b)
where getElement xs = case viewl xs of
x :< _ -> x
EmptyL -> error "unfoldTreeM_BF"
| Monadic forest builder , in breadth - first order ,
by , /ICFP'00/.
unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList
unfoldForestQ :: Monad m => (b -> m (a, [b])) -> Seq b -> m (Seq (Tree a))
unfoldForestQ f aQ = case viewl aQ of
EmptyL -> return empty
a :< aQ -> do
(b, as) <- f a
tQ <- unfoldForestQ f (Prelude.foldl (|>) aQ as)
let (tQ', ts) = splitOnto [] as tQ
return (Node b ts <| tQ')
where splitOnto :: [a'] -> [b'] -> Seq a' -> (Seq a', [a'])
splitOnto as [] q = (q, as)
splitOnto as (_:bs) q = case viewr q of
q' :> a -> splitOnto (a:as) bs q'
EmptyR -> error "unfoldForestQ"
|
ebf8157de127ca6b9563f01b14a41a5d0f3e02a91d9d73034d405d5753c6ab15 | cryptosense/pkcs11 | p11_driver.ml | open P11
exception CKR of RV.t
let () =
Printexc.register_printer (function
| CKR s -> Some (RV.to_string s)
| _ -> None)
module type S = sig
val initialize : unit -> unit
val initialize_nss : params:Pkcs11.Nss_initialize_arg.u -> unit
val finalize : unit -> unit
val get_info : unit -> Info.t
val get_slot : Slot.t -> (Slot_id.t, string) result
val get_slot_list : bool -> Slot_id.t list
val get_slot_info : slot:Slot_id.t -> Slot_info.t
val get_token_info : slot:Slot_id.t -> Token_info.t
val get_mechanism_list : slot:Slot_id.t -> Mechanism_type.t list
val get_mechanism_info :
slot:Slot_id.t -> Mechanism_type.t -> Mechanism_info.t
val init_token : slot:Slot_id.t -> pin:string -> label:string -> unit
val init_PIN : Session_handle.t -> pin:string -> unit
val set_PIN : Session_handle.t -> oldpin:string -> newpin:string -> unit
val open_session : slot:Slot_id.t -> flags:Flags.t -> Session_handle.t
val close_session : Session_handle.t -> unit
val close_all_sessions : slot:Slot_id.t -> unit
val get_session_info : Session_handle.t -> Session_info.t
val login : Session_handle.t -> User_type.t -> string -> unit
val logout : Session_handle.t -> unit
val create_object : Session_handle.t -> Template.t -> Object_handle.t
val copy_object :
Session_handle.t -> Object_handle.t -> Template.t -> Object_handle.t
val destroy_object : Session_handle.t -> Object_handle.t -> unit
val get_attribute_value :
Session_handle.t -> Object_handle.t -> Attribute_types.t -> Template.t
* May request several attributes at the same time .
val get_attribute_value' :
Session_handle.t -> Object_handle.t -> Attribute_types.t -> Template.t
* Will request attributes one by one .
val get_attribute_value_optimized :
Attribute_types.t
-> [`Optimized of Session_handle.t -> Object_handle.t -> Template.t]
val set_attribute_value :
Session_handle.t -> Object_handle.t -> Template.t -> unit
val find_objects :
?max_size:int -> Session_handle.t -> Template.t -> Object_handle.t list
val encrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val multipart_encrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_encrypt_chunck : Session_handle.t -> Data.t -> Data.t
val multipart_encrypt_final : Session_handle.t -> Data.t
val multipart_encrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t list -> Data.t
val decrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val multipart_decrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_decrypt_chunck : Session_handle.t -> Data.t -> Data.t
val multipart_decrypt_final : Session_handle.t -> Data.t
val multipart_decrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t list -> Data.t
val sign :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val sign_recover :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val multipart_sign_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_sign_chunck : Session_handle.t -> Data.t -> unit
val multipart_sign_final : Session_handle.t -> Data.t
val multipart_sign :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t list -> Data.t
val verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> data:Data.t
-> signature:Data.t
-> unit
val verify_recover :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> signature:Data.t
-> Data.t
val multipart_verify_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_verify_chunck : Session_handle.t -> Data.t -> unit
val multipart_verify_final : Session_handle.t -> Data.t -> unit
val multipart_verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t
-> unit
val generate_key :
Session_handle.t -> Mechanism.t -> Template.t -> Object_handle.t
val generate_key_pair :
Session_handle.t
-> Mechanism.t
-> Template.t
-> Template.t
-> Object_handle.t * Object_handle.t
val wrap_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Object_handle.t
-> Data.t
val unwrap_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t
-> Template.t
-> Object_handle.t
val derive_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Template.t
-> Object_handle.t
val digest : Session_handle.t -> Mechanism.t -> Data.t -> Data.t
end
module Wrap_low_level_bindings (X : Pkcs11.LOW_LEVEL_BINDINGS) = struct
module Intermediate_level = Pkcs11.Wrap_low_level_bindings (X)
open Intermediate_level
type 'a t = 'a
let return x = x
let ( >>= ) x f = f x
let check_ckr rv x =
let rv = Pkcs11.CK_RV.view rv in
if RV.equal rv RV.CKR_OK then
x
else
raise (CKR rv)
let check_ckr_unit rv =
let rv = Pkcs11.CK_RV.view rv in
if not (RV.equal rv RV.CKR_OK) then raise (CKR rv)
let ( >>? ) rv f =
let rv = Pkcs11.CK_RV.view rv in
if RV.equal rv RV.CKR_OK then
f ()
else
raise (CKR rv)
let initialize : unit -> unit t =
fun () ->
let rv = c_Initialize None in
check_ckr_unit rv
let initialize_nss : params:string -> unit t =
fun ~params ->
let args = Pkcs11.Nss_initialize_arg.make params in
let rv = c_Initialize (Some args) in
check_ckr_unit rv
let finalize : unit -> unit t =
fun () ->
let rv = c_Finalize () in
check_ckr_unit rv
let get_info : unit -> Info.t t =
fun () ->
let (rv, info) = c_GetInfo () in
check_ckr rv info
let get_slot_list : bool -> Slot_id.t list t =
fun token_present ->
let slot_list = Pkcs11_slot_list.create () in
c_GetSlotList token_present slot_list >>? fun () ->
Pkcs11_slot_list.allocate slot_list;
c_GetSlotList token_present slot_list >>? fun () ->
return (Pkcs11_slot_list.view slot_list)
let get_slot_info : slot:Slot_id.t -> Slot_info.t t =
fun ~slot ->
let (rv, info) = c_GetSlotInfo ~slot in
check_ckr rv info
let get_token_info : slot:Slot_id.t -> Token_info.t t =
fun ~slot ->
let (rv, info) = c_GetTokenInfo ~slot in
check_ckr rv info
let findi_option p l =
let rec go i = function
| [] -> None
| x :: _ when p i x -> Some x
| _ :: xs -> go (i + 1) xs
in
go 0 l
let trimmed_eq a b =
let open P11_helpers in
trim_and_quote a = trim_and_quote b
let find_slot slot_desc i slot =
let open Slot in
match slot_desc with
| Id id -> Slot_id.equal slot @@ Unsigned.ULong.of_int id
| Index idx -> idx = i
| Description s ->
let {Slot_info.slotDescription; _} = get_slot_info ~slot in
trimmed_eq slotDescription s
| Label s ->
let {Token_info.label; _} = get_token_info ~slot in
trimmed_eq label s
let invalid_slot_msg slot =
let (slot_type, value) = Slot.to_string slot in
Printf.sprintf "No %s matches %s." slot_type value
let get_slot slot =
let slot_list = get_slot_list false in
let predicate = find_slot slot in
match findi_option predicate slot_list with
| Some s -> Ok s
| None -> Error (invalid_slot_msg slot)
let get_mechanism_list : slot:Slot_id.t -> Mechanism_type.t list t =
fun ~slot ->
let l = Pkcs11.Mechanism_list.create () in
c_GetMechanismList ~slot l >>? fun () ->
Pkcs11.Mechanism_list.allocate l;
c_GetMechanismList ~slot l >>? fun () ->
return (Pkcs11.Mechanism_list.view l)
let get_mechanism_info :
slot:Slot_id.t -> Mechanism_type.t -> Mechanism_info.t t =
fun ~slot mech ->
let (rv, info) =
c_GetMechanismInfo ~slot (Pkcs11.CK_MECHANISM_TYPE.make mech)
in
check_ckr rv info
let init_token : slot:Slot_id.t -> pin:string -> label:string -> unit t =
fun ~slot ~pin ~label -> check_ckr_unit (c_InitToken ~slot ~pin ~label)
let init_PIN : Session_handle.t -> pin:string -> unit t =
fun hSession ~pin -> check_ckr_unit (c_InitPIN hSession pin)
let set_PIN : Session_handle.t -> oldpin:string -> newpin:string -> unit t =
fun hSession ~oldpin ~newpin ->
check_ckr_unit (c_SetPIN hSession ~oldpin ~newpin)
let open_session : slot:Slot_id.t -> flags:Flags.t -> Session_handle.t t =
fun ~slot ~flags ->
let (rv, hs) = c_OpenSession ~slot ~flags in
check_ckr rv hs
let close_session : Session_handle.t -> unit t =
fun hSession -> check_ckr_unit (c_CloseSession hSession)
let close_all_sessions : slot:Slot_id.t -> unit t =
fun ~slot -> check_ckr_unit (c_CloseAllSessions ~slot)
let get_session_info : Session_handle.t -> Session_info.t t =
fun hSession ->
let (rv, info) = c_GetSessionInfo hSession in
check_ckr rv info
let login : Session_handle.t -> User_type.t -> string -> unit t =
fun hSession usertype pin ->
let usertype = Pkcs11.CK_USER_TYPE.make usertype in
check_ckr_unit (c_Login hSession usertype pin)
let logout : Session_handle.t -> unit t =
fun hSession -> check_ckr_unit (c_Logout hSession)
let create_object : Session_handle.t -> Template.t -> Object_handle.t t =
fun hSession template ->
let (rv, hObj) = c_CreateObject hSession (Pkcs11.Template.make template) in
check_ckr rv hObj
let copy_object :
Session_handle.t -> Object_handle.t -> Template.t -> Object_handle.t t =
fun hSession hObj template ->
let (rv, hObj') =
c_CopyObject hSession hObj (Pkcs11.Template.make template)
in
check_ckr rv hObj'
let destroy_object : Session_handle.t -> Object_handle.t -> unit t =
fun hSession hObj -> check_ckr_unit (c_DestroyObject hSession hObj)
let get_attribute_value
hSession
(hObject : Object_handle.t)
(query : Attribute_types.t) : Template.t t =
let query =
List.map
(fun (Attribute_type.Pack x) ->
Pkcs11.CK_ATTRIBUTE.create (Pkcs11.CK_ATTRIBUTE_TYPE.make x))
query
in
let query : Pkcs11.Template.t = Pkcs11.Template.of_list query in
c_GetAttributeValue hSession hObject query >>? fun () ->
Pkcs11.Template.allocate query;
c_GetAttributeValue hSession hObject query >>? fun () ->
return (Pkcs11.Template.view query)
let get_attribute_value' hSession hObject query : Template.t t =
List.fold_left
(fun acc attribute ->
try
let attr = get_attribute_value hSession hObject [attribute] in
attr @ acc
with
| CKR _ -> acc)
[] query
|> List.rev
|> return
module CKA_map = Map.Make (struct
type t = Attribute_type.pack
let compare = Attribute_type.compare_pack
end)
let get_attribute_value_optimized tracked_attributes =
TODO : have one score table per device / per slot / per session ?
let results : (int * int) CKA_map.t ref = ref CKA_map.empty in
let count = ref 0 in
let get_results attribute_type =
try CKA_map.find attribute_type !results with
| Not_found -> (0, 0)
in
let incr_failures (attribute_type : Attribute_type.pack) =
let (successes, failures) = get_results attribute_type in
results := CKA_map.add attribute_type (successes, failures + 1) !results
in
let incr_successes (attribute_type : Attribute_type.pack) =
let (successes, failures) = get_results attribute_type in
results := CKA_map.add attribute_type (1 + successes, failures) !results
in
let can_group attribute_type =
Group only if the failure rate is less than 1 % .
let (_, failures) = get_results attribute_type in
failures * 100 / !count < 1
in
`Optimized
(fun session handle ->
let rec ask_one_by_one acc attributes =
match attributes with
| [] -> acc (* Order does not matter. *)
| head :: tail -> (
try
let value = get_attribute_value session handle [head] in
incr_successes head;
ask_one_by_one (value @ acc) tail
with
| CKR _ ->
incr_failures head;
ask_one_by_one acc tail)
in
incr count;
let (group, singles) = List.partition can_group tracked_attributes in
Try to ask attributes which work most of the time all at once .
If it failed , revert to one - by - one mode .
If it failed, revert to one-by-one mode. *)
let group_template =
try
let r = get_attribute_value session handle group in
List.iter incr_successes group;
r
with
| CKR _ -> ask_one_by_one [] group
in
Complete the template with other attributes , the ones which fail
often and which we always ask one by one .
often and which we always ask one by one. *)
ask_one_by_one group_template singles)
let set_attribute_value
hSession
(hObject : Object_handle.t)
(query : Attribute.pack list) : unit t =
let query =
List.map (fun (Attribute.Pack x) -> Pkcs11.CK_ATTRIBUTE.make x) query
|> Pkcs11.Template.of_list
in
c_SetAttributeValue hSession hObject query >>? fun () -> return ()
(* Do not call c_FindObjectFinal. *)
let rec find_all acc hSession ~max_size =
let (rv, l) = c_FindObjects hSession ~max_size in
check_ckr rv l >>= fun l ->
if l <> [] then
find_all (List.rev_append l acc) hSession ~max_size
else
return @@ List.rev acc
let find_objects :
?max_size:int -> Session_handle.t -> Template.t -> Object_handle.t list t
=
fun ?(max_size = 5) hSession template ->
let template = Pkcs11.Template.make template in
c_FindObjectsInit hSession template >>? fun () ->
find_all [] hSession ~max_size >>= fun l ->
let rv = c_FindObjectsFinal hSession in
check_ckr_unit rv >>= fun () -> return l
let encrypt hSession mech hObject plain : Data.t =
let mech = Pkcs11.CK_MECHANISM.make mech in
c_EncryptInit hSession mech hObject >>? fun () ->
let plain = Pkcs11.Data.of_string plain in
let cipher = Pkcs11.Data.create () in
c_Encrypt hSession ~src:plain ~tgt:cipher >>? fun () ->
let () = Pkcs11.Data.allocate cipher in
c_Encrypt hSession ~src:plain ~tgt:cipher >>? fun () ->
return (Pkcs11.Data.to_string cipher)
let multipart_encrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hObject ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_EncryptInit hSession mech hObject >>? return
let multipart_encrypt_chunck hSession plain : Data.t =
let plain = Pkcs11.Data.of_string plain in
let cipher = Pkcs11.Data.create () in
c_EncryptUpdate hSession plain cipher >>? fun () ->
let () = Pkcs11.Data.allocate cipher in
c_EncryptUpdate hSession plain cipher >>? fun () ->
return (Pkcs11.Data.to_string cipher)
let multipart_encrypt_final : Session_handle.t -> Data.t =
fun hSession ->
let cipher = Pkcs11.Data.create () in
c_EncryptFinal hSession cipher >>? fun () ->
let () = Pkcs11.Data.allocate cipher in
c_EncryptFinal hSession cipher >>? fun () ->
return (Pkcs11.Data.to_string cipher)
let multipart_encrypt :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t =
fun hSession mech hKey parts ->
multipart_encrypt_init hSession mech hKey;
let cipher =
List.map (fun x -> multipart_encrypt_chunck hSession x) parts
|> String.concat ""
in
let lastPart = multipart_encrypt_final hSession in
cipher ^ lastPart
let decrypt hSession mech hObject cipher : Data.t =
let mech = Pkcs11.CK_MECHANISM.make mech in
c_DecryptInit hSession mech hObject >>? fun () ->
let cipher = Pkcs11.Data.of_string cipher in
let plain = Pkcs11.Data.create () in
c_Decrypt hSession ~src:cipher ~tgt:plain >>? fun () ->
let () = Pkcs11.Data.allocate plain in
c_Decrypt hSession ~src:cipher ~tgt:plain >>? fun () ->
return (Pkcs11.Data.to_string plain)
let multipart_decrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hObject ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_DecryptInit hSession mech hObject >>? return
let multipart_decrypt_chunck hSession cipher : Data.t =
let cipher = Pkcs11.Data.of_string cipher in
let plain = Pkcs11.Data.create () in
c_DecryptUpdate hSession cipher plain >>? fun () ->
let () = Pkcs11.Data.allocate plain in
c_DecryptUpdate hSession cipher plain >>? fun () ->
return (Pkcs11.Data.to_string plain)
let multipart_decrypt_final : Session_handle.t -> Data.t =
fun hSession ->
let plain = Pkcs11.Data.create () in
c_DecryptFinal hSession plain >>? fun () ->
let () = Pkcs11.Data.allocate plain in
c_DecryptFinal hSession plain >>? fun () ->
return (Pkcs11.Data.to_string plain)
let multipart_decrypt :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t =
fun hSession mech hKey parts ->
multipart_decrypt_init hSession mech hKey;
let plain =
List.map (fun x -> multipart_decrypt_chunck hSession x) parts
|> String.concat ""
in
let lastPart = multipart_decrypt_final hSession in
plain ^ lastPart
let sign :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t =
fun hSession mech hKey plain ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_SignInit hSession mech hKey >>? fun () ->
let plain = Pkcs11.Data.of_string plain in
let signature = Pkcs11.Data.create () in
c_Sign hSession ~src:plain ~tgt:signature >>? fun () ->
let () = Pkcs11.Data.allocate signature in
c_Sign hSession ~src:plain ~tgt:signature >>? fun () ->
return (Pkcs11.Data.to_string signature)
let sign_recover :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t =
fun hSession mech hKey plain ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_SignRecoverInit hSession mech hKey >>? fun () ->
let plain = Pkcs11.Data.of_string plain in
let signature = Pkcs11.Data.create () in
c_SignRecover hSession ~src:plain ~tgt:signature >>? fun () ->
let () = Pkcs11.Data.allocate signature in
c_SignRecover hSession ~src:plain ~tgt:signature >>? fun () ->
return (Pkcs11.Data.to_string signature)
let multipart_sign_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hKey ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_SignInit hSession mech hKey >>? return
let multipart_sign_chunck : Session_handle.t -> Data.t -> unit t =
fun hSession part ->
let part = Pkcs11.Data.of_string part in
c_SignUpdate hSession part >>? return
let multipart_sign_final : Session_handle.t -> Data.t =
fun hSession ->
let signature = Pkcs11.Data.create () in
c_SignFinal hSession signature >>? fun () ->
let () = Pkcs11.Data.allocate signature in
c_SignFinal hSession signature >>? fun () ->
return (Pkcs11.Data.to_string signature)
let multipart_sign :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t =
fun hSession mech hKey parts ->
multipart_sign_init hSession mech hKey >>= fun () ->
List.iter (multipart_sign_chunck hSession) parts >>= fun () ->
multipart_sign_final hSession
let verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> data:Data.t
-> signature:Data.t
-> unit t =
fun hSession mech hKey ~data ~signature ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_VerifyInit hSession mech hKey >>? fun () ->
let signed = Pkcs11.Data.of_string data in
let signature = Pkcs11.Data.of_string signature in
c_Verify hSession ~signed ~signature >>? fun () -> return ()
let verify_recover :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> signature:string
-> Data.t =
fun hSession mech hKey ~signature ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_VerifyRecoverInit hSession mech hKey >>? fun () ->
let signature = Pkcs11.Data.of_string signature in
let signed = Pkcs11.Data.create () in
c_VerifyRecover hSession ~signature ~signed >>? fun () ->
let () = Pkcs11.Data.allocate signed in
c_VerifyRecover hSession ~signature ~signed >>? fun () ->
return (Pkcs11.Data.to_string signed)
let multipart_verify_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hKey ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_VerifyInit hSession mech hKey >>? return
let multipart_verify_chunck : Session_handle.t -> Data.t -> unit =
fun hSession part ->
let part = Pkcs11.Data.of_string part in
c_VerifyUpdate hSession part >>? return
let multipart_verify_final : Session_handle.t -> Data.t -> unit t =
fun hSession signature ->
let signature = Pkcs11.Data.of_string signature in
c_VerifyFinal hSession signature >>? return
let multipart_verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t
-> unit t =
fun hSession mech hKey parts signature ->
multipart_verify_init hSession mech hKey >>= fun () ->
List.iter (multipart_verify_chunck hSession) parts >>= fun () ->
multipart_verify_final hSession signature
let generate_key :
Session_handle.t -> Mechanism.t -> Template.t -> Object_handle.t t =
fun hSession mech template ->
let template = Pkcs11.Template.make template in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, obj) = c_GenerateKey hSession mech template in
check_ckr rv obj
(* returns [public,private] *)
let generate_key_pair :
Session_handle.t
-> Mechanism.t
-> Template.t
-> Template.t
-> (Object_handle.t * Object_handle.t) t =
fun hSession mech public privat ->
let public = Pkcs11.Template.make public in
let privat = Pkcs11.Template.make privat in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, pub, priv) = c_GenerateKeyPair hSession mech ~public ~privat in
check_ckr rv (pub, priv)
let wrap_key hSession mech wrapping_key (key : Object_handle.t) : string t =
let mech = Pkcs11.CK_MECHANISM.make mech in
let wrapped_key = Pkcs11.Data.create () in
c_WrapKey hSession mech ~wrapping_key ~key ~wrapped_key >>? fun () ->
let () = Pkcs11.Data.allocate wrapped_key in
c_WrapKey hSession mech ~wrapping_key ~key ~wrapped_key >>? fun () ->
return (Pkcs11.Data.to_string wrapped_key)
let unwrap_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> string
-> Template.t
-> Object_handle.t t =
fun hSession mech unwrapping_key wrapped_key template ->
let wrapped_key = Pkcs11.Data.of_string wrapped_key in
let template = Pkcs11.Template.make template in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, obj) =
c_UnwrapKey hSession mech ~unwrapping_key ~wrapped_key template
in
check_ckr rv obj
let derive_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Template.t
-> Object_handle.t t =
fun hSession mech obj template ->
let template = Pkcs11.Template.make template in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, obj') = c_DeriveKey hSession mech obj template in
check_ckr rv obj'
let digest session mechanism input =
let low_mechanism = Pkcs11.CK_MECHANISM.make mechanism in
c_DigestInit session low_mechanism >>? fun () ->
let low_input = Pkcs11.Data.of_string input in
let low_output = Pkcs11.Data.create () in
c_Digest session low_input low_output >>? fun () ->
let () = Pkcs11.Data.allocate low_output in
c_Digest session low_input low_output >>? fun () ->
let output = Pkcs11.Data.to_string low_output in
return output
end
type t = (module S)
let initialize (module S : S) = S.initialize ()
let initialize_nss (module S : S) = S.initialize_nss
let finalize (module S : S) = S.finalize ()
let get_info (module S : S) = S.get_info ()
let get_slot (module S : S) = S.get_slot
let get_slot_list (module S : S) = S.get_slot_list
let get_slot_info (module S : S) = S.get_slot_info
let get_token_info (module S : S) = S.get_token_info
let get_mechanism_list (module S : S) = S.get_mechanism_list
let get_mechanism_info (module S : S) = S.get_mechanism_info
let init_token (module S : S) = S.init_token
let init_PIN (module S : S) = S.init_PIN
let set_PIN (module S : S) = S.set_PIN
let open_session (module S : S) = S.open_session
let close_session (module S : S) = S.close_session
let close_all_sessions (module S : S) = S.close_all_sessions
let get_session_info (module S : S) = S.get_session_info
let login (module S : S) = S.login
let logout (module S : S) = S.logout
let create_object (module S : S) = S.create_object
let copy_object (module S : S) = S.copy_object
let destroy_object (module S : S) = S.destroy_object
let get_attribute_value (module S : S) = S.get_attribute_value
let get_attribute_value' (module S : S) = S.get_attribute_value'
let get_attribute_value_optimized (module S : S) =
S.get_attribute_value_optimized
let set_attribute_value (module S : S) = S.set_attribute_value
let find_objects (module S : S) = S.find_objects
let encrypt (module S : S) = S.encrypt
let multipart_encrypt_init (module S : S) = S.multipart_encrypt_init
let multipart_encrypt_chunck (module S : S) = S.multipart_encrypt_chunck
let multipart_encrypt_final (module S : S) = S.multipart_encrypt_final
let multipart_encrypt (module S : S) = S.multipart_encrypt
let decrypt (module S : S) = S.decrypt
let multipart_decrypt_init (module S : S) = S.multipart_decrypt_init
let multipart_decrypt_chunck (module S : S) = S.multipart_decrypt_chunck
let multipart_decrypt_final (module S : S) = S.multipart_decrypt_final
let multipart_decrypt (module S : S) = S.multipart_decrypt
let sign (module S : S) = S.sign
let sign_recover (module S : S) = S.sign_recover
let multipart_sign_init (module S : S) = S.multipart_sign_init
let multipart_sign_chunck (module S : S) = S.multipart_sign_chunck
let multipart_sign_final (module S : S) = S.multipart_sign_final
let multipart_sign (module S : S) = S.multipart_sign
let verify (module S : S) = S.verify
let verify_recover (module S : S) = S.verify_recover
let multipart_verify_init (module S : S) = S.multipart_verify_init
let multipart_verify_chunck (module S : S) = S.multipart_verify_chunck
let multipart_verify_final (module S : S) = S.multipart_verify_final
let multipart_verify (module S : S) = S.multipart_verify
let generate_key (module S : S) = S.generate_key
let generate_key_pair (module S : S) = S.generate_key_pair
let wrap_key (module S : S) = S.wrap_key
let unwrap_key (module S : S) = S.unwrap_key
let derive_key (module S : S) = S.derive_key
let digest (module S : S) = S.digest
let load_driver ?log_calls ?on_unknown ?load_mode dll =
let module Implem = (val Pkcs11.load_driver ?log_calls ?on_unknown ?load_mode
dll : Pkcs11.LOW_LEVEL_BINDINGS)
in
(module Wrap_low_level_bindings (Implem) : S)
| null | https://raw.githubusercontent.com/cryptosense/pkcs11/93c39c7a31c87f68f0beabf75ef90d85a782a983/driver/p11_driver.ml | ocaml | Order does not matter.
Do not call c_FindObjectFinal.
returns [public,private] | open P11
exception CKR of RV.t
let () =
Printexc.register_printer (function
| CKR s -> Some (RV.to_string s)
| _ -> None)
module type S = sig
val initialize : unit -> unit
val initialize_nss : params:Pkcs11.Nss_initialize_arg.u -> unit
val finalize : unit -> unit
val get_info : unit -> Info.t
val get_slot : Slot.t -> (Slot_id.t, string) result
val get_slot_list : bool -> Slot_id.t list
val get_slot_info : slot:Slot_id.t -> Slot_info.t
val get_token_info : slot:Slot_id.t -> Token_info.t
val get_mechanism_list : slot:Slot_id.t -> Mechanism_type.t list
val get_mechanism_info :
slot:Slot_id.t -> Mechanism_type.t -> Mechanism_info.t
val init_token : slot:Slot_id.t -> pin:string -> label:string -> unit
val init_PIN : Session_handle.t -> pin:string -> unit
val set_PIN : Session_handle.t -> oldpin:string -> newpin:string -> unit
val open_session : slot:Slot_id.t -> flags:Flags.t -> Session_handle.t
val close_session : Session_handle.t -> unit
val close_all_sessions : slot:Slot_id.t -> unit
val get_session_info : Session_handle.t -> Session_info.t
val login : Session_handle.t -> User_type.t -> string -> unit
val logout : Session_handle.t -> unit
val create_object : Session_handle.t -> Template.t -> Object_handle.t
val copy_object :
Session_handle.t -> Object_handle.t -> Template.t -> Object_handle.t
val destroy_object : Session_handle.t -> Object_handle.t -> unit
val get_attribute_value :
Session_handle.t -> Object_handle.t -> Attribute_types.t -> Template.t
* May request several attributes at the same time .
val get_attribute_value' :
Session_handle.t -> Object_handle.t -> Attribute_types.t -> Template.t
* Will request attributes one by one .
val get_attribute_value_optimized :
Attribute_types.t
-> [`Optimized of Session_handle.t -> Object_handle.t -> Template.t]
val set_attribute_value :
Session_handle.t -> Object_handle.t -> Template.t -> unit
val find_objects :
?max_size:int -> Session_handle.t -> Template.t -> Object_handle.t list
val encrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val multipart_encrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_encrypt_chunck : Session_handle.t -> Data.t -> Data.t
val multipart_encrypt_final : Session_handle.t -> Data.t
val multipart_encrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t list -> Data.t
val decrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val multipart_decrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_decrypt_chunck : Session_handle.t -> Data.t -> Data.t
val multipart_decrypt_final : Session_handle.t -> Data.t
val multipart_decrypt :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t list -> Data.t
val sign :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val sign_recover :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t
val multipart_sign_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_sign_chunck : Session_handle.t -> Data.t -> unit
val multipart_sign_final : Session_handle.t -> Data.t
val multipart_sign :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t list -> Data.t
val verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> data:Data.t
-> signature:Data.t
-> unit
val verify_recover :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> signature:Data.t
-> Data.t
val multipart_verify_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit
val multipart_verify_chunck : Session_handle.t -> Data.t -> unit
val multipart_verify_final : Session_handle.t -> Data.t -> unit
val multipart_verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t
-> unit
val generate_key :
Session_handle.t -> Mechanism.t -> Template.t -> Object_handle.t
val generate_key_pair :
Session_handle.t
-> Mechanism.t
-> Template.t
-> Template.t
-> Object_handle.t * Object_handle.t
val wrap_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Object_handle.t
-> Data.t
val unwrap_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t
-> Template.t
-> Object_handle.t
val derive_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Template.t
-> Object_handle.t
val digest : Session_handle.t -> Mechanism.t -> Data.t -> Data.t
end
module Wrap_low_level_bindings (X : Pkcs11.LOW_LEVEL_BINDINGS) = struct
module Intermediate_level = Pkcs11.Wrap_low_level_bindings (X)
open Intermediate_level
type 'a t = 'a
let return x = x
let ( >>= ) x f = f x
let check_ckr rv x =
let rv = Pkcs11.CK_RV.view rv in
if RV.equal rv RV.CKR_OK then
x
else
raise (CKR rv)
let check_ckr_unit rv =
let rv = Pkcs11.CK_RV.view rv in
if not (RV.equal rv RV.CKR_OK) then raise (CKR rv)
let ( >>? ) rv f =
let rv = Pkcs11.CK_RV.view rv in
if RV.equal rv RV.CKR_OK then
f ()
else
raise (CKR rv)
let initialize : unit -> unit t =
fun () ->
let rv = c_Initialize None in
check_ckr_unit rv
let initialize_nss : params:string -> unit t =
fun ~params ->
let args = Pkcs11.Nss_initialize_arg.make params in
let rv = c_Initialize (Some args) in
check_ckr_unit rv
let finalize : unit -> unit t =
fun () ->
let rv = c_Finalize () in
check_ckr_unit rv
let get_info : unit -> Info.t t =
fun () ->
let (rv, info) = c_GetInfo () in
check_ckr rv info
let get_slot_list : bool -> Slot_id.t list t =
fun token_present ->
let slot_list = Pkcs11_slot_list.create () in
c_GetSlotList token_present slot_list >>? fun () ->
Pkcs11_slot_list.allocate slot_list;
c_GetSlotList token_present slot_list >>? fun () ->
return (Pkcs11_slot_list.view slot_list)
let get_slot_info : slot:Slot_id.t -> Slot_info.t t =
fun ~slot ->
let (rv, info) = c_GetSlotInfo ~slot in
check_ckr rv info
let get_token_info : slot:Slot_id.t -> Token_info.t t =
fun ~slot ->
let (rv, info) = c_GetTokenInfo ~slot in
check_ckr rv info
let findi_option p l =
let rec go i = function
| [] -> None
| x :: _ when p i x -> Some x
| _ :: xs -> go (i + 1) xs
in
go 0 l
let trimmed_eq a b =
let open P11_helpers in
trim_and_quote a = trim_and_quote b
let find_slot slot_desc i slot =
let open Slot in
match slot_desc with
| Id id -> Slot_id.equal slot @@ Unsigned.ULong.of_int id
| Index idx -> idx = i
| Description s ->
let {Slot_info.slotDescription; _} = get_slot_info ~slot in
trimmed_eq slotDescription s
| Label s ->
let {Token_info.label; _} = get_token_info ~slot in
trimmed_eq label s
let invalid_slot_msg slot =
let (slot_type, value) = Slot.to_string slot in
Printf.sprintf "No %s matches %s." slot_type value
let get_slot slot =
let slot_list = get_slot_list false in
let predicate = find_slot slot in
match findi_option predicate slot_list with
| Some s -> Ok s
| None -> Error (invalid_slot_msg slot)
let get_mechanism_list : slot:Slot_id.t -> Mechanism_type.t list t =
fun ~slot ->
let l = Pkcs11.Mechanism_list.create () in
c_GetMechanismList ~slot l >>? fun () ->
Pkcs11.Mechanism_list.allocate l;
c_GetMechanismList ~slot l >>? fun () ->
return (Pkcs11.Mechanism_list.view l)
let get_mechanism_info :
slot:Slot_id.t -> Mechanism_type.t -> Mechanism_info.t t =
fun ~slot mech ->
let (rv, info) =
c_GetMechanismInfo ~slot (Pkcs11.CK_MECHANISM_TYPE.make mech)
in
check_ckr rv info
let init_token : slot:Slot_id.t -> pin:string -> label:string -> unit t =
fun ~slot ~pin ~label -> check_ckr_unit (c_InitToken ~slot ~pin ~label)
let init_PIN : Session_handle.t -> pin:string -> unit t =
fun hSession ~pin -> check_ckr_unit (c_InitPIN hSession pin)
let set_PIN : Session_handle.t -> oldpin:string -> newpin:string -> unit t =
fun hSession ~oldpin ~newpin ->
check_ckr_unit (c_SetPIN hSession ~oldpin ~newpin)
let open_session : slot:Slot_id.t -> flags:Flags.t -> Session_handle.t t =
fun ~slot ~flags ->
let (rv, hs) = c_OpenSession ~slot ~flags in
check_ckr rv hs
let close_session : Session_handle.t -> unit t =
fun hSession -> check_ckr_unit (c_CloseSession hSession)
let close_all_sessions : slot:Slot_id.t -> unit t =
fun ~slot -> check_ckr_unit (c_CloseAllSessions ~slot)
let get_session_info : Session_handle.t -> Session_info.t t =
fun hSession ->
let (rv, info) = c_GetSessionInfo hSession in
check_ckr rv info
let login : Session_handle.t -> User_type.t -> string -> unit t =
fun hSession usertype pin ->
let usertype = Pkcs11.CK_USER_TYPE.make usertype in
check_ckr_unit (c_Login hSession usertype pin)
let logout : Session_handle.t -> unit t =
fun hSession -> check_ckr_unit (c_Logout hSession)
let create_object : Session_handle.t -> Template.t -> Object_handle.t t =
fun hSession template ->
let (rv, hObj) = c_CreateObject hSession (Pkcs11.Template.make template) in
check_ckr rv hObj
let copy_object :
Session_handle.t -> Object_handle.t -> Template.t -> Object_handle.t t =
fun hSession hObj template ->
let (rv, hObj') =
c_CopyObject hSession hObj (Pkcs11.Template.make template)
in
check_ckr rv hObj'
let destroy_object : Session_handle.t -> Object_handle.t -> unit t =
fun hSession hObj -> check_ckr_unit (c_DestroyObject hSession hObj)
let get_attribute_value
hSession
(hObject : Object_handle.t)
(query : Attribute_types.t) : Template.t t =
let query =
List.map
(fun (Attribute_type.Pack x) ->
Pkcs11.CK_ATTRIBUTE.create (Pkcs11.CK_ATTRIBUTE_TYPE.make x))
query
in
let query : Pkcs11.Template.t = Pkcs11.Template.of_list query in
c_GetAttributeValue hSession hObject query >>? fun () ->
Pkcs11.Template.allocate query;
c_GetAttributeValue hSession hObject query >>? fun () ->
return (Pkcs11.Template.view query)
let get_attribute_value' hSession hObject query : Template.t t =
List.fold_left
(fun acc attribute ->
try
let attr = get_attribute_value hSession hObject [attribute] in
attr @ acc
with
| CKR _ -> acc)
[] query
|> List.rev
|> return
module CKA_map = Map.Make (struct
type t = Attribute_type.pack
let compare = Attribute_type.compare_pack
end)
let get_attribute_value_optimized tracked_attributes =
TODO : have one score table per device / per slot / per session ?
let results : (int * int) CKA_map.t ref = ref CKA_map.empty in
let count = ref 0 in
let get_results attribute_type =
try CKA_map.find attribute_type !results with
| Not_found -> (0, 0)
in
let incr_failures (attribute_type : Attribute_type.pack) =
let (successes, failures) = get_results attribute_type in
results := CKA_map.add attribute_type (successes, failures + 1) !results
in
let incr_successes (attribute_type : Attribute_type.pack) =
let (successes, failures) = get_results attribute_type in
results := CKA_map.add attribute_type (1 + successes, failures) !results
in
let can_group attribute_type =
Group only if the failure rate is less than 1 % .
let (_, failures) = get_results attribute_type in
failures * 100 / !count < 1
in
`Optimized
(fun session handle ->
let rec ask_one_by_one acc attributes =
match attributes with
| head :: tail -> (
try
let value = get_attribute_value session handle [head] in
incr_successes head;
ask_one_by_one (value @ acc) tail
with
| CKR _ ->
incr_failures head;
ask_one_by_one acc tail)
in
incr count;
let (group, singles) = List.partition can_group tracked_attributes in
Try to ask attributes which work most of the time all at once .
If it failed , revert to one - by - one mode .
If it failed, revert to one-by-one mode. *)
let group_template =
try
let r = get_attribute_value session handle group in
List.iter incr_successes group;
r
with
| CKR _ -> ask_one_by_one [] group
in
Complete the template with other attributes , the ones which fail
often and which we always ask one by one .
often and which we always ask one by one. *)
ask_one_by_one group_template singles)
let set_attribute_value
hSession
(hObject : Object_handle.t)
(query : Attribute.pack list) : unit t =
let query =
List.map (fun (Attribute.Pack x) -> Pkcs11.CK_ATTRIBUTE.make x) query
|> Pkcs11.Template.of_list
in
c_SetAttributeValue hSession hObject query >>? fun () -> return ()
let rec find_all acc hSession ~max_size =
let (rv, l) = c_FindObjects hSession ~max_size in
check_ckr rv l >>= fun l ->
if l <> [] then
find_all (List.rev_append l acc) hSession ~max_size
else
return @@ List.rev acc
let find_objects :
?max_size:int -> Session_handle.t -> Template.t -> Object_handle.t list t
=
fun ?(max_size = 5) hSession template ->
let template = Pkcs11.Template.make template in
c_FindObjectsInit hSession template >>? fun () ->
find_all [] hSession ~max_size >>= fun l ->
let rv = c_FindObjectsFinal hSession in
check_ckr_unit rv >>= fun () -> return l
let encrypt hSession mech hObject plain : Data.t =
let mech = Pkcs11.CK_MECHANISM.make mech in
c_EncryptInit hSession mech hObject >>? fun () ->
let plain = Pkcs11.Data.of_string plain in
let cipher = Pkcs11.Data.create () in
c_Encrypt hSession ~src:plain ~tgt:cipher >>? fun () ->
let () = Pkcs11.Data.allocate cipher in
c_Encrypt hSession ~src:plain ~tgt:cipher >>? fun () ->
return (Pkcs11.Data.to_string cipher)
let multipart_encrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hObject ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_EncryptInit hSession mech hObject >>? return
let multipart_encrypt_chunck hSession plain : Data.t =
let plain = Pkcs11.Data.of_string plain in
let cipher = Pkcs11.Data.create () in
c_EncryptUpdate hSession plain cipher >>? fun () ->
let () = Pkcs11.Data.allocate cipher in
c_EncryptUpdate hSession plain cipher >>? fun () ->
return (Pkcs11.Data.to_string cipher)
let multipart_encrypt_final : Session_handle.t -> Data.t =
fun hSession ->
let cipher = Pkcs11.Data.create () in
c_EncryptFinal hSession cipher >>? fun () ->
let () = Pkcs11.Data.allocate cipher in
c_EncryptFinal hSession cipher >>? fun () ->
return (Pkcs11.Data.to_string cipher)
let multipart_encrypt :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t =
fun hSession mech hKey parts ->
multipart_encrypt_init hSession mech hKey;
let cipher =
List.map (fun x -> multipart_encrypt_chunck hSession x) parts
|> String.concat ""
in
let lastPart = multipart_encrypt_final hSession in
cipher ^ lastPart
let decrypt hSession mech hObject cipher : Data.t =
let mech = Pkcs11.CK_MECHANISM.make mech in
c_DecryptInit hSession mech hObject >>? fun () ->
let cipher = Pkcs11.Data.of_string cipher in
let plain = Pkcs11.Data.create () in
c_Decrypt hSession ~src:cipher ~tgt:plain >>? fun () ->
let () = Pkcs11.Data.allocate plain in
c_Decrypt hSession ~src:cipher ~tgt:plain >>? fun () ->
return (Pkcs11.Data.to_string plain)
let multipart_decrypt_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hObject ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_DecryptInit hSession mech hObject >>? return
let multipart_decrypt_chunck hSession cipher : Data.t =
let cipher = Pkcs11.Data.of_string cipher in
let plain = Pkcs11.Data.create () in
c_DecryptUpdate hSession cipher plain >>? fun () ->
let () = Pkcs11.Data.allocate plain in
c_DecryptUpdate hSession cipher plain >>? fun () ->
return (Pkcs11.Data.to_string plain)
let multipart_decrypt_final : Session_handle.t -> Data.t =
fun hSession ->
let plain = Pkcs11.Data.create () in
c_DecryptFinal hSession plain >>? fun () ->
let () = Pkcs11.Data.allocate plain in
c_DecryptFinal hSession plain >>? fun () ->
return (Pkcs11.Data.to_string plain)
let multipart_decrypt :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t =
fun hSession mech hKey parts ->
multipart_decrypt_init hSession mech hKey;
let plain =
List.map (fun x -> multipart_decrypt_chunck hSession x) parts
|> String.concat ""
in
let lastPart = multipart_decrypt_final hSession in
plain ^ lastPart
let sign :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t =
fun hSession mech hKey plain ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_SignInit hSession mech hKey >>? fun () ->
let plain = Pkcs11.Data.of_string plain in
let signature = Pkcs11.Data.create () in
c_Sign hSession ~src:plain ~tgt:signature >>? fun () ->
let () = Pkcs11.Data.allocate signature in
c_Sign hSession ~src:plain ~tgt:signature >>? fun () ->
return (Pkcs11.Data.to_string signature)
let sign_recover :
Session_handle.t -> Mechanism.t -> Object_handle.t -> Data.t -> Data.t =
fun hSession mech hKey plain ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_SignRecoverInit hSession mech hKey >>? fun () ->
let plain = Pkcs11.Data.of_string plain in
let signature = Pkcs11.Data.create () in
c_SignRecover hSession ~src:plain ~tgt:signature >>? fun () ->
let () = Pkcs11.Data.allocate signature in
c_SignRecover hSession ~src:plain ~tgt:signature >>? fun () ->
return (Pkcs11.Data.to_string signature)
let multipart_sign_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hKey ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_SignInit hSession mech hKey >>? return
let multipart_sign_chunck : Session_handle.t -> Data.t -> unit t =
fun hSession part ->
let part = Pkcs11.Data.of_string part in
c_SignUpdate hSession part >>? return
let multipart_sign_final : Session_handle.t -> Data.t =
fun hSession ->
let signature = Pkcs11.Data.create () in
c_SignFinal hSession signature >>? fun () ->
let () = Pkcs11.Data.allocate signature in
c_SignFinal hSession signature >>? fun () ->
return (Pkcs11.Data.to_string signature)
let multipart_sign :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t =
fun hSession mech hKey parts ->
multipart_sign_init hSession mech hKey >>= fun () ->
List.iter (multipart_sign_chunck hSession) parts >>= fun () ->
multipart_sign_final hSession
let verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> data:Data.t
-> signature:Data.t
-> unit t =
fun hSession mech hKey ~data ~signature ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_VerifyInit hSession mech hKey >>? fun () ->
let signed = Pkcs11.Data.of_string data in
let signature = Pkcs11.Data.of_string signature in
c_Verify hSession ~signed ~signature >>? fun () -> return ()
let verify_recover :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> signature:string
-> Data.t =
fun hSession mech hKey ~signature ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_VerifyRecoverInit hSession mech hKey >>? fun () ->
let signature = Pkcs11.Data.of_string signature in
let signed = Pkcs11.Data.create () in
c_VerifyRecover hSession ~signature ~signed >>? fun () ->
let () = Pkcs11.Data.allocate signed in
c_VerifyRecover hSession ~signature ~signed >>? fun () ->
return (Pkcs11.Data.to_string signed)
let multipart_verify_init :
Session_handle.t -> Mechanism.t -> Object_handle.t -> unit t =
fun hSession mech hKey ->
let mech = Pkcs11.CK_MECHANISM.make mech in
c_VerifyInit hSession mech hKey >>? return
let multipart_verify_chunck : Session_handle.t -> Data.t -> unit =
fun hSession part ->
let part = Pkcs11.Data.of_string part in
c_VerifyUpdate hSession part >>? return
let multipart_verify_final : Session_handle.t -> Data.t -> unit t =
fun hSession signature ->
let signature = Pkcs11.Data.of_string signature in
c_VerifyFinal hSession signature >>? return
let multipart_verify :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Data.t list
-> Data.t
-> unit t =
fun hSession mech hKey parts signature ->
multipart_verify_init hSession mech hKey >>= fun () ->
List.iter (multipart_verify_chunck hSession) parts >>= fun () ->
multipart_verify_final hSession signature
let generate_key :
Session_handle.t -> Mechanism.t -> Template.t -> Object_handle.t t =
fun hSession mech template ->
let template = Pkcs11.Template.make template in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, obj) = c_GenerateKey hSession mech template in
check_ckr rv obj
let generate_key_pair :
Session_handle.t
-> Mechanism.t
-> Template.t
-> Template.t
-> (Object_handle.t * Object_handle.t) t =
fun hSession mech public privat ->
let public = Pkcs11.Template.make public in
let privat = Pkcs11.Template.make privat in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, pub, priv) = c_GenerateKeyPair hSession mech ~public ~privat in
check_ckr rv (pub, priv)
let wrap_key hSession mech wrapping_key (key : Object_handle.t) : string t =
let mech = Pkcs11.CK_MECHANISM.make mech in
let wrapped_key = Pkcs11.Data.create () in
c_WrapKey hSession mech ~wrapping_key ~key ~wrapped_key >>? fun () ->
let () = Pkcs11.Data.allocate wrapped_key in
c_WrapKey hSession mech ~wrapping_key ~key ~wrapped_key >>? fun () ->
return (Pkcs11.Data.to_string wrapped_key)
let unwrap_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> string
-> Template.t
-> Object_handle.t t =
fun hSession mech unwrapping_key wrapped_key template ->
let wrapped_key = Pkcs11.Data.of_string wrapped_key in
let template = Pkcs11.Template.make template in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, obj) =
c_UnwrapKey hSession mech ~unwrapping_key ~wrapped_key template
in
check_ckr rv obj
let derive_key :
Session_handle.t
-> Mechanism.t
-> Object_handle.t
-> Template.t
-> Object_handle.t t =
fun hSession mech obj template ->
let template = Pkcs11.Template.make template in
let mech = Pkcs11.CK_MECHANISM.make mech in
let (rv, obj') = c_DeriveKey hSession mech obj template in
check_ckr rv obj'
let digest session mechanism input =
let low_mechanism = Pkcs11.CK_MECHANISM.make mechanism in
c_DigestInit session low_mechanism >>? fun () ->
let low_input = Pkcs11.Data.of_string input in
let low_output = Pkcs11.Data.create () in
c_Digest session low_input low_output >>? fun () ->
let () = Pkcs11.Data.allocate low_output in
c_Digest session low_input low_output >>? fun () ->
let output = Pkcs11.Data.to_string low_output in
return output
end
type t = (module S)
let initialize (module S : S) = S.initialize ()
let initialize_nss (module S : S) = S.initialize_nss
let finalize (module S : S) = S.finalize ()
let get_info (module S : S) = S.get_info ()
let get_slot (module S : S) = S.get_slot
let get_slot_list (module S : S) = S.get_slot_list
let get_slot_info (module S : S) = S.get_slot_info
let get_token_info (module S : S) = S.get_token_info
let get_mechanism_list (module S : S) = S.get_mechanism_list
let get_mechanism_info (module S : S) = S.get_mechanism_info
let init_token (module S : S) = S.init_token
let init_PIN (module S : S) = S.init_PIN
let set_PIN (module S : S) = S.set_PIN
let open_session (module S : S) = S.open_session
let close_session (module S : S) = S.close_session
let close_all_sessions (module S : S) = S.close_all_sessions
let get_session_info (module S : S) = S.get_session_info
let login (module S : S) = S.login
let logout (module S : S) = S.logout
let create_object (module S : S) = S.create_object
let copy_object (module S : S) = S.copy_object
let destroy_object (module S : S) = S.destroy_object
let get_attribute_value (module S : S) = S.get_attribute_value
let get_attribute_value' (module S : S) = S.get_attribute_value'
let get_attribute_value_optimized (module S : S) =
S.get_attribute_value_optimized
let set_attribute_value (module S : S) = S.set_attribute_value
let find_objects (module S : S) = S.find_objects
let encrypt (module S : S) = S.encrypt
let multipart_encrypt_init (module S : S) = S.multipart_encrypt_init
let multipart_encrypt_chunck (module S : S) = S.multipart_encrypt_chunck
let multipart_encrypt_final (module S : S) = S.multipart_encrypt_final
let multipart_encrypt (module S : S) = S.multipart_encrypt
let decrypt (module S : S) = S.decrypt
let multipart_decrypt_init (module S : S) = S.multipart_decrypt_init
let multipart_decrypt_chunck (module S : S) = S.multipart_decrypt_chunck
let multipart_decrypt_final (module S : S) = S.multipart_decrypt_final
let multipart_decrypt (module S : S) = S.multipart_decrypt
let sign (module S : S) = S.sign
let sign_recover (module S : S) = S.sign_recover
let multipart_sign_init (module S : S) = S.multipart_sign_init
let multipart_sign_chunck (module S : S) = S.multipart_sign_chunck
let multipart_sign_final (module S : S) = S.multipart_sign_final
let multipart_sign (module S : S) = S.multipart_sign
let verify (module S : S) = S.verify
let verify_recover (module S : S) = S.verify_recover
let multipart_verify_init (module S : S) = S.multipart_verify_init
let multipart_verify_chunck (module S : S) = S.multipart_verify_chunck
let multipart_verify_final (module S : S) = S.multipart_verify_final
let multipart_verify (module S : S) = S.multipart_verify
let generate_key (module S : S) = S.generate_key
let generate_key_pair (module S : S) = S.generate_key_pair
let wrap_key (module S : S) = S.wrap_key
let unwrap_key (module S : S) = S.unwrap_key
let derive_key (module S : S) = S.derive_key
let digest (module S : S) = S.digest
let load_driver ?log_calls ?on_unknown ?load_mode dll =
let module Implem = (val Pkcs11.load_driver ?log_calls ?on_unknown ?load_mode
dll : Pkcs11.LOW_LEVEL_BINDINGS)
in
(module Wrap_low_level_bindings (Implem) : S)
|
7827d7bf8c3a431969f511c6e13e8386c97e217f0aea229debbafb9798bc9da8 | crategus/cl-cffi-gtk | text-view-insert.lisp | Text View Insert ( 2021 - 6 - 4 )
(in-package :gtk-example)
(defvar *text-for-example-text-view-insert*
"<html>
<head><title>Title</title></head>
<body>
<h1>Heading</h1>
")
(defun get-this-tag (iter buffer)
(let* ((start-tag (gtk-text-iter-copy iter))
end-tag)
(and (gtk-text-iter-find-char start-tag #'alpha-char-p)
(setq end-tag (gtk-text-iter-copy start-tag))
(gtk-text-iter-find-char end-tag
(lambda (ch) (not (alphanumericp ch))))
(gtk-text-buffer-get-text buffer start-tag end-tag nil))))
(defun closing-tag-p (iter)
(let ((slash (gtk-text-iter-copy iter)))
(gtk-text-iter-forward-char slash)
(eql (gtk-text-iter-char slash) #\/)))
(defun example-text-view-insert ()
(within-main-loop
(let ((window (make-instance 'gtk-window
:title "Example Text View Insert"
:type :toplevel
:default-width 350
:default-height 200))
(textview (make-instance 'gtk-text-view
:top-margin 6
:left-margin 6
:right-margin 6))
(button-make-item (make-instance 'gtk-button
:label "Make List Item"
:margin 3))
(button-close-tag (make-instance 'gtk-button
:label "Insert Close Tag"
:margin 3))
(hbox (make-instance 'gtk-box
:orientation :horizontal))
(vbox (make-instance 'gtk-box
:orientation :vertical)))
(g-signal-connect window "destroy"
(lambda (widget)
(declare (ignore widget))
(leave-gtk-main)))
(g-signal-connect button-make-item "clicked"
(lambda (widget)
(declare (ignore widget))
(let* ((buffer (gtk-text-view-buffer textview))
(cursor (gtk-text-buffer-mark buffer "insert"))
(bound (gtk-text-buffer-mark buffer "selection_bound")))
(if (gtk-text-buffer-has-selection buffer)
;; Insert text before and after the selection
(progn
;; Insert start tag
(let ((iter (gtk-text-buffer-iter-at-mark buffer cursor)))
(gtk-text-buffer-insert buffer "<li>" :position iter))
;; Insert end tag
(let ((mark (gtk-text-mark-new nil t))
(iter (gtk-text-buffer-iter-at-mark buffer bound)))
;; Add the anonymous mark with right gravity
(gtk-text-buffer-add-mark buffer mark iter)
;; Do the insertion at the position of the mark
(let ((end (gtk-text-buffer-iter-at-mark buffer mark)))
(gtk-text-buffer-insert buffer "</li>" :position end))
;; Reselect the previous selection
(let ((iter1 (gtk-text-buffer-iter-at-mark buffer cursor))
(iter2 (gtk-text-buffer-iter-at-mark buffer mark)))
(gtk-text-buffer-select-range buffer iter1 iter2))
;; Delete the mark
(gtk-text-buffer-delete-mark buffer mark)))
;; Insert at start and end of current line
(let ((iter (gtk-text-buffer-iter-at-mark buffer cursor)))
;; Move to the start of the line
(setf (gtk-text-iter-line-offset iter) 0)
(gtk-text-buffer-insert buffer "<li>" :position iter)
;; Move to the end of the line
(gtk-text-iter-forward-to-line-end iter)
(gtk-text-buffer-insert buffer "</li>" :position iter)
;; Place cursor and selection and the end of the line
(gtk-text-iter-forward-to-line-end iter)
(gtk-text-buffer-select-range buffer iter iter))))))
(g-signal-connect button-close-tag "clicked"
(lambda (widget)
(declare (ignore widget))
(let* ((buffer (gtk-text-view-buffer textview))
(cursor (gtk-text-buffer-mark buffer "insert"))
(iter (gtk-text-buffer-iter-at-mark buffer cursor)))
(do ((stack '()))
((not (gtk-text-iter-find-char iter
(lambda (ch) (eq ch #\<))
:direction :backward)))
(let ((tag (get-this-tag iter buffer)))
(if (closing-tag-p iter)
(push tag stack)
(let ((tag-in-stack (pop stack)))
(when (not tag-in-stack)
(gtk-text-buffer-insert buffer
(format nil "</~a>" tag))
(return)))))))))
(setf (gtk-text-buffer-text (gtk-text-view-buffer textview))
*text-for-example-text-view-insert*)
;; Pack and show the widgets
(gtk-box-pack-start vbox textview)
(gtk-box-pack-start hbox button-make-item)
(gtk-box-pack-start hbox button-close-tag)
(gtk-box-pack-start vbox hbox :expand nil)
(gtk-container-add window vbox)
(gtk-widget-show-all window))))
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/b613a266a5f8e7f477b66a33d4df84fbed3dc7bc/demo/gtk-example/text-view-insert.lisp | lisp | Insert text before and after the selection
Insert start tag
Insert end tag
Add the anonymous mark with right gravity
Do the insertion at the position of the mark
Reselect the previous selection
Delete the mark
Insert at start and end of current line
Move to the start of the line
Move to the end of the line
Place cursor and selection and the end of the line
Pack and show the widgets | Text View Insert ( 2021 - 6 - 4 )
(in-package :gtk-example)
(defvar *text-for-example-text-view-insert*
"<html>
<head><title>Title</title></head>
<body>
<h1>Heading</h1>
")
(defun get-this-tag (iter buffer)
(let* ((start-tag (gtk-text-iter-copy iter))
end-tag)
(and (gtk-text-iter-find-char start-tag #'alpha-char-p)
(setq end-tag (gtk-text-iter-copy start-tag))
(gtk-text-iter-find-char end-tag
(lambda (ch) (not (alphanumericp ch))))
(gtk-text-buffer-get-text buffer start-tag end-tag nil))))
(defun closing-tag-p (iter)
(let ((slash (gtk-text-iter-copy iter)))
(gtk-text-iter-forward-char slash)
(eql (gtk-text-iter-char slash) #\/)))
(defun example-text-view-insert ()
(within-main-loop
(let ((window (make-instance 'gtk-window
:title "Example Text View Insert"
:type :toplevel
:default-width 350
:default-height 200))
(textview (make-instance 'gtk-text-view
:top-margin 6
:left-margin 6
:right-margin 6))
(button-make-item (make-instance 'gtk-button
:label "Make List Item"
:margin 3))
(button-close-tag (make-instance 'gtk-button
:label "Insert Close Tag"
:margin 3))
(hbox (make-instance 'gtk-box
:orientation :horizontal))
(vbox (make-instance 'gtk-box
:orientation :vertical)))
(g-signal-connect window "destroy"
(lambda (widget)
(declare (ignore widget))
(leave-gtk-main)))
(g-signal-connect button-make-item "clicked"
(lambda (widget)
(declare (ignore widget))
(let* ((buffer (gtk-text-view-buffer textview))
(cursor (gtk-text-buffer-mark buffer "insert"))
(bound (gtk-text-buffer-mark buffer "selection_bound")))
(if (gtk-text-buffer-has-selection buffer)
(progn
(let ((iter (gtk-text-buffer-iter-at-mark buffer cursor)))
(gtk-text-buffer-insert buffer "<li>" :position iter))
(let ((mark (gtk-text-mark-new nil t))
(iter (gtk-text-buffer-iter-at-mark buffer bound)))
(gtk-text-buffer-add-mark buffer mark iter)
(let ((end (gtk-text-buffer-iter-at-mark buffer mark)))
(gtk-text-buffer-insert buffer "</li>" :position end))
(let ((iter1 (gtk-text-buffer-iter-at-mark buffer cursor))
(iter2 (gtk-text-buffer-iter-at-mark buffer mark)))
(gtk-text-buffer-select-range buffer iter1 iter2))
(gtk-text-buffer-delete-mark buffer mark)))
(let ((iter (gtk-text-buffer-iter-at-mark buffer cursor)))
(setf (gtk-text-iter-line-offset iter) 0)
(gtk-text-buffer-insert buffer "<li>" :position iter)
(gtk-text-iter-forward-to-line-end iter)
(gtk-text-buffer-insert buffer "</li>" :position iter)
(gtk-text-iter-forward-to-line-end iter)
(gtk-text-buffer-select-range buffer iter iter))))))
(g-signal-connect button-close-tag "clicked"
(lambda (widget)
(declare (ignore widget))
(let* ((buffer (gtk-text-view-buffer textview))
(cursor (gtk-text-buffer-mark buffer "insert"))
(iter (gtk-text-buffer-iter-at-mark buffer cursor)))
(do ((stack '()))
((not (gtk-text-iter-find-char iter
(lambda (ch) (eq ch #\<))
:direction :backward)))
(let ((tag (get-this-tag iter buffer)))
(if (closing-tag-p iter)
(push tag stack)
(let ((tag-in-stack (pop stack)))
(when (not tag-in-stack)
(gtk-text-buffer-insert buffer
(format nil "</~a>" tag))
(return)))))))))
(setf (gtk-text-buffer-text (gtk-text-view-buffer textview))
*text-for-example-text-view-insert*)
(gtk-box-pack-start vbox textview)
(gtk-box-pack-start hbox button-make-item)
(gtk-box-pack-start hbox button-close-tag)
(gtk-box-pack-start vbox hbox :expand nil)
(gtk-container-add window vbox)
(gtk-widget-show-all window))))
|
9d49129ed244a80c5b191237e2fb0fa551ac009bbdb3d4715fbe44716a4d0b9f | ocaml-flambda/ocaml-jst | polling_insertion.ml | (* TEST
modules = "polling.c"
compare_programs = "false"
* poll-insertion
** arch64
*** native
*)
This set of tests examine poll insertion behaviour . We do this by requesting
and checking the number of minor collections at various points to determine
whether a poll was correctly added . There are some subtleties because
[ caml_empty_minor_heap ] will not increment the minor_collections stat if
nothing has been allocated on the minor heap , so we sometimes need to
add an allocation before we call [ request_minor_gc ] . The [ minor_gcs ]
function returns the number of minor collections so far without allocating .
41 ) ) is used wherever we want to do an
allocation in order to use some minor heap so the minor collections stat is
incremented .
42 ) ) is used wherever we want an allocation
for the purposes of testing whether a poll would be elided or not .
and checking the number of minor collections at various points to determine
whether a poll was correctly added. There are some subtleties because
[caml_empty_minor_heap] will not increment the minor_collections stat if
nothing has been allocated on the minor heap, so we sometimes need to
add an allocation before we call [request_minor_gc]. The [minor_gcs]
function returns the number of minor collections so far without allocating.
ignore(Sys.opaque_identity(ref 41)) is used wherever we want to do an
allocation in order to use some minor heap so the minor collections stat is
incremented.
ignore(Sys.opaque_identity(ref 42)) is used wherever we want an allocation
for the purposes of testing whether a poll would be elided or not.
*)
external request_minor_gc : unit -> unit = "request_minor_gc"
external minor_gcs : unit -> int = "minor_gcs"
(* This function tests that polls are added to loops *)
let polls_added_to_loops () =
let minors_before = minor_gcs () in
request_minor_gc ();
for a = 0 to 1 do
ignore (Sys.opaque_identity 42)
done;
let minors_now = minor_gcs () in
assert (minors_before < minors_now)
(* This function should have no prologue poll but will have
one in the loop. *)
let func_with_added_poll_because_loop () =
We do two loop iterations so that the poll is triggered whether
in poll - at - top or poll - at - bottom mode .
in poll-at-top or poll-at-bottom mode. *)
for a = 0 to Sys.opaque_identity(1) do
ignore (Sys.opaque_identity 42)
done
[@@inline never]
let func_with_no_prologue_poll () =
(* this function does not have indirect or 'forward' tail call nor
does it call a synthesised function with suppressed polls. *)
ignore(Sys.opaque_identity(minor_gcs ()))
[@@inline never]
let prologue_polls_in_functions () =
ignore(Sys.opaque_identity(ref 41));
let minors_before = minor_gcs () in
request_minor_gc ();
func_with_added_poll_because_loop ();
let minors_now = minor_gcs () in
assert (minors_before < minors_now);
ignore(Sys.opaque_identity(ref 41));
let minors_before = minor_gcs () in
request_minor_gc ();
func_with_no_prologue_poll ();
let minors_now = minor_gcs () in
assert (minors_before = minors_now)
These next functions test that polls are not added to functions that
unconditionally allocate .
[ allocating_func ] allocates unconditionally
[ allocating_func_if ] allocates unconditionally but does so
on two separate branches
unconditionally allocate.
[allocating_func] allocates unconditionally
[allocating_func_if] allocates unconditionally but does so
on two separate branches *)
let allocating_func minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
(* No poll yet *)
ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
(* Polled at alloc *)
[@@inline never]
let allocating_func_if minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
(* No poll yet *)
if minors_before > 0 then ignore (Sys.opaque_identity (ref 42))
else ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
(* Polled at alloc *)
[@@inline never]
let allocating_func_nested_ifs minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
(* No poll yet *)
if Sys.opaque_identity(minors_before) > 0 then
if Sys.opaque_identity(minors_before) > 1 then
ignore (Sys.opaque_identity (ref 42))
else
ignore (Sys.opaque_identity (ref 42))
else
if Sys.opaque_identity(minors_before) < 5 then
ignore (Sys.opaque_identity (ref 42))
else
ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
(* Polled at alloc *)
[@@inline never]
let allocating_func_match minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
(* No poll yet *)
match minors_before with
| 0 -> ignore (Sys.opaque_identity (ref 42))
| _ -> ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
(* Polled at alloc *)
[@@inline never]
let polls_not_added_unconditionally_allocating_functions () =
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func minors_before;
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func_if minors_before;
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func_nested_ifs minors_before;
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func_match minors_before
(* This function tests that polls are not added to the back edge of
where loop bodies allocate unconditionally *)
let polls_not_added_to_allocating_loops () =
let current_minors = ref (minor_gcs ()) in
request_minor_gc ();
for a = 0 to 1 do
(* Since the loop body allocates there should be no poll points *)
let minors_now = minor_gcs () in
assert(minors_now = !current_minors);
ignore(Sys.opaque_identity(ref 42));
let minors_now2 = minor_gcs () in
assert(minors_now+1 = minors_now2);
current_minors := minors_now2;
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ()
done
(* this next set of functions tests that self tail recursive functions
have polls added correctly *)
let rec self_rec_func n =
match n with
| 0 -> 0
| _ ->
begin
let n1 = Sys.opaque_identity(n-1) in
(self_rec_func[@tailcall]) n1
end
let polls_added_to_self_recursive_functions () =
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(self_rec_func 2);
let minors_after = minor_gcs () in
should be at least one minor gc from polls in self_rec_func
assert(minors_before+1 = minors_after)
this pair of mutually recursive functions is to test that a poll is
correctly placed in the first one compiled
correctly placed in the first one compiled *)
let rec mut_rec_func_even d =
match d with
| 0 -> 0
| _ -> mut_rec_func_odd (d-1)
and mut_rec_func_odd d =
mut_rec_func_even (d-1)
and mut_rec_func d =
match d with
| n when n mod 2 == 0
-> mut_rec_func_even n
| n -> mut_rec_func_odd n
let polls_added_to_mutually_recursive_functions () =
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(mut_rec_func 3);
let minors_after = minor_gcs () in
should be at least one minor gc from polls in mut_rec_func
assert(minors_before < minors_after)
this is to test that indirect tail calls ( which might result in a self
call ) have polls inserted in them .
These correspond to Itailcall_ind at Mach
call) have polls inserted in them.
These correspond to Itailcall_ind at Mach *)
let do_indirect_tail_call f n =
f (n-1)
[@@inline never]
let polls_added_to_indirect_tail_calls () =
let f = fun n -> n+1 in
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(do_indirect_tail_call f 3);
let minors_after = minor_gcs () in
should be at one minor gc from the poll in do_indirect_tail_call
assert(minors_before+1 = minors_after)
this is to test that indirect non - tail calls do not have a poll placed
in them . These correspond to Icall_ind at Mach
in them. These correspond to Icall_ind at Mach *)
let do_indirect_call f n =
n * f (n-1)
[@@inline never]
let polls_not_added_to_indirect_calls () =
let f = fun n -> n+1 in
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(do_indirect_call f 3);
let minors_after = minor_gcs () in
should be at one minor gc from the poll in do_indirect_tail_call
assert(minors_before = minors_after)
this set of functions tests that we do n't poll for immediate
( non - tail ) calls . These correspond to Icall_imm at Mach
(non-tail) calls. These correspond to Icall_imm at Mach *)
let call_func1 n =
Sys.opaque_identity(n-1)
[@@inline never]
let call_func2 n =
n * (call_func1 (Sys.opaque_identity(n+1)))
[@@inline never]
let polls_not_added_to_immediate_calls () =
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(call_func1 100);
let minors_after = minor_gcs () in
(* should be no minor collections *)
assert(minors_before = minors_after)
let[@inline never][@local never] app minors_before f x y =
let minors_after_prologue = minor_gcs () in
assert(minors_before+1 = minors_after_prologue);
request_minor_gc ();
f x y
let polls_not_added_in_caml_apply () =
let minors_before = minor_gcs() in
request_minor_gc();
ignore(Sys.opaque_identity(app minors_before (fun x y -> x * y) 5 4));
let minors_after = minor_gcs() in
assert(minors_before+1 = minors_after)
let () =
ignore(Sys.opaque_identity(ref 41));
polls_added_to_loops (); (* relies on there being some minor heap usage *)
ignore(Sys.opaque_identity(ref 41));
prologue_polls_in_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_added_to_self_recursive_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_added_to_mutually_recursive_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_added_to_indirect_tail_calls ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_to_indirect_calls ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_to_immediate_calls ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_unconditionally_allocating_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_to_allocating_loops ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_in_caml_apply ()
| null | https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/testsuite/tests/asmcomp/polling_insertion.ml | ocaml | TEST
modules = "polling.c"
compare_programs = "false"
* poll-insertion
** arch64
*** native
This function tests that polls are added to loops
This function should have no prologue poll but will have
one in the loop.
this function does not have indirect or 'forward' tail call nor
does it call a synthesised function with suppressed polls.
No poll yet
Polled at alloc
No poll yet
Polled at alloc
No poll yet
Polled at alloc
No poll yet
Polled at alloc
This function tests that polls are not added to the back edge of
where loop bodies allocate unconditionally
Since the loop body allocates there should be no poll points
this next set of functions tests that self tail recursive functions
have polls added correctly
should be no minor collections
relies on there being some minor heap usage |
This set of tests examine poll insertion behaviour . We do this by requesting
and checking the number of minor collections at various points to determine
whether a poll was correctly added . There are some subtleties because
[ caml_empty_minor_heap ] will not increment the minor_collections stat if
nothing has been allocated on the minor heap , so we sometimes need to
add an allocation before we call [ request_minor_gc ] . The [ minor_gcs ]
function returns the number of minor collections so far without allocating .
41 ) ) is used wherever we want to do an
allocation in order to use some minor heap so the minor collections stat is
incremented .
42 ) ) is used wherever we want an allocation
for the purposes of testing whether a poll would be elided or not .
and checking the number of minor collections at various points to determine
whether a poll was correctly added. There are some subtleties because
[caml_empty_minor_heap] will not increment the minor_collections stat if
nothing has been allocated on the minor heap, so we sometimes need to
add an allocation before we call [request_minor_gc]. The [minor_gcs]
function returns the number of minor collections so far without allocating.
ignore(Sys.opaque_identity(ref 41)) is used wherever we want to do an
allocation in order to use some minor heap so the minor collections stat is
incremented.
ignore(Sys.opaque_identity(ref 42)) is used wherever we want an allocation
for the purposes of testing whether a poll would be elided or not.
*)
external request_minor_gc : unit -> unit = "request_minor_gc"
external minor_gcs : unit -> int = "minor_gcs"
let polls_added_to_loops () =
let minors_before = minor_gcs () in
request_minor_gc ();
for a = 0 to 1 do
ignore (Sys.opaque_identity 42)
done;
let minors_now = minor_gcs () in
assert (minors_before < minors_now)
let func_with_added_poll_because_loop () =
We do two loop iterations so that the poll is triggered whether
in poll - at - top or poll - at - bottom mode .
in poll-at-top or poll-at-bottom mode. *)
for a = 0 to Sys.opaque_identity(1) do
ignore (Sys.opaque_identity 42)
done
[@@inline never]
let func_with_no_prologue_poll () =
ignore(Sys.opaque_identity(minor_gcs ()))
[@@inline never]
let prologue_polls_in_functions () =
ignore(Sys.opaque_identity(ref 41));
let minors_before = minor_gcs () in
request_minor_gc ();
func_with_added_poll_because_loop ();
let minors_now = minor_gcs () in
assert (minors_before < minors_now);
ignore(Sys.opaque_identity(ref 41));
let minors_before = minor_gcs () in
request_minor_gc ();
func_with_no_prologue_poll ();
let minors_now = minor_gcs () in
assert (minors_before = minors_now)
These next functions test that polls are not added to functions that
unconditionally allocate .
[ allocating_func ] allocates unconditionally
[ allocating_func_if ] allocates unconditionally but does so
on two separate branches
unconditionally allocate.
[allocating_func] allocates unconditionally
[allocating_func_if] allocates unconditionally but does so
on two separate branches *)
let allocating_func minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
[@@inline never]
let allocating_func_if minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
if minors_before > 0 then ignore (Sys.opaque_identity (ref 42))
else ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
[@@inline never]
let allocating_func_nested_ifs minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
if Sys.opaque_identity(minors_before) > 0 then
if Sys.opaque_identity(minors_before) > 1 then
ignore (Sys.opaque_identity (ref 42))
else
ignore (Sys.opaque_identity (ref 42))
else
if Sys.opaque_identity(minors_before) < 5 then
ignore (Sys.opaque_identity (ref 42))
else
ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
[@@inline never]
let allocating_func_match minors_before =
let minors_now = minor_gcs () in
assert (minors_before = minors_now);
match minors_before with
| 0 -> ignore (Sys.opaque_identity (ref 42))
| _ -> ignore (Sys.opaque_identity (ref 42));
let minors_now2 = minor_gcs () in
assert (minors_before + 1 = minors_now2);
[@@inline never]
let polls_not_added_unconditionally_allocating_functions () =
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func minors_before;
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func_if minors_before;
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func_nested_ifs minors_before;
let minors_before = minor_gcs () in
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ();
allocating_func_match minors_before
let polls_not_added_to_allocating_loops () =
let current_minors = ref (minor_gcs ()) in
request_minor_gc ();
for a = 0 to 1 do
let minors_now = minor_gcs () in
assert(minors_now = !current_minors);
ignore(Sys.opaque_identity(ref 42));
let minors_now2 = minor_gcs () in
assert(minors_now+1 = minors_now2);
current_minors := minors_now2;
ignore(Sys.opaque_identity(ref 41));
request_minor_gc ()
done
let rec self_rec_func n =
match n with
| 0 -> 0
| _ ->
begin
let n1 = Sys.opaque_identity(n-1) in
(self_rec_func[@tailcall]) n1
end
let polls_added_to_self_recursive_functions () =
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(self_rec_func 2);
let minors_after = minor_gcs () in
should be at least one minor gc from polls in self_rec_func
assert(minors_before+1 = minors_after)
this pair of mutually recursive functions is to test that a poll is
correctly placed in the first one compiled
correctly placed in the first one compiled *)
let rec mut_rec_func_even d =
match d with
| 0 -> 0
| _ -> mut_rec_func_odd (d-1)
and mut_rec_func_odd d =
mut_rec_func_even (d-1)
and mut_rec_func d =
match d with
| n when n mod 2 == 0
-> mut_rec_func_even n
| n -> mut_rec_func_odd n
let polls_added_to_mutually_recursive_functions () =
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(mut_rec_func 3);
let minors_after = minor_gcs () in
should be at least one minor gc from polls in mut_rec_func
assert(minors_before < minors_after)
this is to test that indirect tail calls ( which might result in a self
call ) have polls inserted in them .
These correspond to Itailcall_ind at Mach
call) have polls inserted in them.
These correspond to Itailcall_ind at Mach *)
let do_indirect_tail_call f n =
f (n-1)
[@@inline never]
let polls_added_to_indirect_tail_calls () =
let f = fun n -> n+1 in
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(do_indirect_tail_call f 3);
let minors_after = minor_gcs () in
should be at one minor gc from the poll in do_indirect_tail_call
assert(minors_before+1 = minors_after)
this is to test that indirect non - tail calls do not have a poll placed
in them . These correspond to Icall_ind at Mach
in them. These correspond to Icall_ind at Mach *)
let do_indirect_call f n =
n * f (n-1)
[@@inline never]
let polls_not_added_to_indirect_calls () =
let f = fun n -> n+1 in
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(do_indirect_call f 3);
let minors_after = minor_gcs () in
should be at one minor gc from the poll in do_indirect_tail_call
assert(minors_before = minors_after)
this set of functions tests that we do n't poll for immediate
( non - tail ) calls . These correspond to Icall_imm at Mach
(non-tail) calls. These correspond to Icall_imm at Mach *)
let call_func1 n =
Sys.opaque_identity(n-1)
[@@inline never]
let call_func2 n =
n * (call_func1 (Sys.opaque_identity(n+1)))
[@@inline never]
let polls_not_added_to_immediate_calls () =
let minors_before = minor_gcs () in
request_minor_gc ();
ignore(call_func1 100);
let minors_after = minor_gcs () in
assert(minors_before = minors_after)
let[@inline never][@local never] app minors_before f x y =
let minors_after_prologue = minor_gcs () in
assert(minors_before+1 = minors_after_prologue);
request_minor_gc ();
f x y
let polls_not_added_in_caml_apply () =
let minors_before = minor_gcs() in
request_minor_gc();
ignore(Sys.opaque_identity(app minors_before (fun x y -> x * y) 5 4));
let minors_after = minor_gcs() in
assert(minors_before+1 = minors_after)
let () =
ignore(Sys.opaque_identity(ref 41));
ignore(Sys.opaque_identity(ref 41));
prologue_polls_in_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_added_to_self_recursive_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_added_to_mutually_recursive_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_added_to_indirect_tail_calls ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_to_indirect_calls ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_to_immediate_calls ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_unconditionally_allocating_functions ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_to_allocating_loops ();
ignore(Sys.opaque_identity(ref 41));
polls_not_added_in_caml_apply ()
|
f415a214361b0100adec9d5fb257e2ff82e7161b9086b4711c5eec92dcd0a221 | mattmundell/nightshade | support.lisp | ;;; Machine specific support routines needed by the file assembler.
(in-package "HPPA")
(def-vm-support-routine generate-call-sequence (name style vop)
(ecase style
(:raw
(let ((fixup (gensym "FIXUP-")))
(values
`((let ((fixup (make-fixup ',name :assembly-routine)))
(inst ldil fixup ,fixup)
(inst ble fixup lisp-heap-space ,fixup :nullify t))
(inst nop))
`((:temporary (:scs (any-reg) :from (:eval 0) :to (:eval 1))
,fixup)))))
(:full-call
(let ((temp (make-symbol "TEMP"))
(nfp-save (make-symbol "NFP-SAVE"))
(lra (make-symbol "LRA")))
(values
`((let ((lra-label (gen-label))
(cur-nfp (current-nfp-tn ,vop)))
(when cur-nfp
(store-stack-tn ,nfp-save cur-nfp))
(inst compute-lra-from-code code-tn lra-label ,temp ,lra)
(note-this-location ,vop :call-site)
(let ((fixup (make-fixup ',name :assembly-routine)))
(inst ldil fixup ,temp)
(inst be fixup lisp-heap-space ,temp :nullify t))
(emit-return-pc lra-label)
(note-this-location ,vop :single-value-return)
(move ocfp-tn csp-tn)
(inst compute-code-from-lra code-tn lra-label ,temp code-tn)
(when cur-nfp
(load-stack-tn cur-nfp ,nfp-save))))
`((:temporary (:scs (non-descriptor-reg) :from (:eval 0) :to (:eval 1))
,temp)
(:temporary (:sc descriptor-reg :offset lra-offset
:from (:eval 0) :to (:eval 1))
,lra)
(:temporary (:scs (control-stack) :offset nfp-save-offset)
,nfp-save)
(:save-p :compute-only)))))
(:none
(let ((fixup (gensym "FIXUP-")))
(values
`((let ((fixup (make-fixup ',name :assembly-routine)))
(inst ldil fixup ,fixup)
(inst be fixup lisp-heap-space ,fixup :nullify t)))
`((:temporary (:scs (any-reg) :from (:eval 0) :to (:eval 1))
,fixup)))))))
(def-vm-support-routine generate-return-sequence (style)
(ecase style
(:raw
`((inst bv lip-tn :nullify t)))
(:full-call
`((lisp-return (make-random-tn :kind :normal
:sc (sc-or-lose 'descriptor-reg)
:offset lra-offset)
:offset 1)))
(:none)))
| null | https://raw.githubusercontent.com/mattmundell/nightshade/d8abd7bd3424b95b70bed599e0cfe033e15299e0/src/assembly/hppa/support.lisp | lisp | Machine specific support routines needed by the file assembler. |
(in-package "HPPA")
(def-vm-support-routine generate-call-sequence (name style vop)
(ecase style
(:raw
(let ((fixup (gensym "FIXUP-")))
(values
`((let ((fixup (make-fixup ',name :assembly-routine)))
(inst ldil fixup ,fixup)
(inst ble fixup lisp-heap-space ,fixup :nullify t))
(inst nop))
`((:temporary (:scs (any-reg) :from (:eval 0) :to (:eval 1))
,fixup)))))
(:full-call
(let ((temp (make-symbol "TEMP"))
(nfp-save (make-symbol "NFP-SAVE"))
(lra (make-symbol "LRA")))
(values
`((let ((lra-label (gen-label))
(cur-nfp (current-nfp-tn ,vop)))
(when cur-nfp
(store-stack-tn ,nfp-save cur-nfp))
(inst compute-lra-from-code code-tn lra-label ,temp ,lra)
(note-this-location ,vop :call-site)
(let ((fixup (make-fixup ',name :assembly-routine)))
(inst ldil fixup ,temp)
(inst be fixup lisp-heap-space ,temp :nullify t))
(emit-return-pc lra-label)
(note-this-location ,vop :single-value-return)
(move ocfp-tn csp-tn)
(inst compute-code-from-lra code-tn lra-label ,temp code-tn)
(when cur-nfp
(load-stack-tn cur-nfp ,nfp-save))))
`((:temporary (:scs (non-descriptor-reg) :from (:eval 0) :to (:eval 1))
,temp)
(:temporary (:sc descriptor-reg :offset lra-offset
:from (:eval 0) :to (:eval 1))
,lra)
(:temporary (:scs (control-stack) :offset nfp-save-offset)
,nfp-save)
(:save-p :compute-only)))))
(:none
(let ((fixup (gensym "FIXUP-")))
(values
`((let ((fixup (make-fixup ',name :assembly-routine)))
(inst ldil fixup ,fixup)
(inst be fixup lisp-heap-space ,fixup :nullify t)))
`((:temporary (:scs (any-reg) :from (:eval 0) :to (:eval 1))
,fixup)))))))
(def-vm-support-routine generate-return-sequence (style)
(ecase style
(:raw
`((inst bv lip-tn :nullify t)))
(:full-call
`((lisp-return (make-random-tn :kind :normal
:sc (sc-or-lose 'descriptor-reg)
:offset lra-offset)
:offset 1)))
(:none)))
|
e48061ffa62d09887cd87b656fa965f17c179efe1cc14dcb508f296424710a4f | uim/uim | tutcode-custom.scm | ;;; tutcode-custom.scm: Customization variables for tutcode.scm
;;;
Copyright ( c ) 2003 - 2013 uim Project
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
;;; SUCH DAMAGE.
;;;;
(require "i18n.scm")
(define tutcode-im-name-label (N_ "TUT-Code"))
(define tutcode-im-short-desc (N_ "uim version of TUT-Code input method"))
(define-custom-group 'tutcode
tutcode-im-name-label
tutcode-im-short-desc)
(define-custom-group 'tutcode-dict
(N_ "TUT-Code dictionaries")
(N_ "Dictionary settings for TUT-Code"))
(define-custom-group 'tutcode-bushu
(N_ "Bushu conversion")
(N_ "Bushu conversion settings for TUT-Code"))
(define-custom-group 'tutcode-mazegaki
(N_ "Mazegaki conversion")
(N_ "Mazegaki conversion settings for TUT-Code"))
(define-custom-group 'tutcode-prediction
(N_ "Prediction")
(N_ "long description will be here."))
;;
;; dictionary
;;
(define-custom 'tutcode-dic-filename (string-append (sys-datadir)
"/tc/mazegaki.dic")
'(tutcode tutcode-dict)
'(pathname regular-file)
(N_ "Mazegaki dictionary file")
(N_ "long description will be here."))
(define-custom 'tutcode-personal-dic-filename
(string-append (or (home-directory (user-name)) "") "/.mazegaki.dic")
'(tutcode tutcode-dict)
'(pathname regular-file)
(N_ "Personal mazegaki dictionary file")
(N_ "long description will be here."))
(define-custom 'tutcode-rule-filename
(string-append (sys-pkgdatadir) "/tutcode-rule.scm")
'(tutcode)
'(pathname regular-file)
(N_ "Code table file")
(N_ "Code table name is 'filename-rule' when code table file name is 'filename.scm'."))
(define-custom 'tutcode-enable-mazegaki-learning? #t
'(tutcode tutcode-mazegaki)
'(boolean)
(N_ "Enable learning in mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-fixed-priority-count 0
'(tutcode tutcode-mazegaki)
'(integer 0 65535)
(N_ "Number of candidates to be excluded from mazegaki learning")
(N_ "long description will be here."))
(define-custom 'tutcode-use-recursive-learning? #t
'(tutcode tutcode-mazegaki)
'(boolean)
(N_ "Use recursive learning")
(N_ "long description will be here."))
(define-custom 'tutcode-use-with-vi? #f
'(tutcode)
'(boolean)
(N_ "Enable vi-cooperative mode")
(N_ "long description will be here."))
(define-custom 'tutcode-show-pending-rk? #f
'(tutcode)
'(boolean)
(N_ "Show pending key sequences")
(N_ "long description will be here."))
(define-custom 'tutcode-use-dvorak? #f
'(tutcode)
'(boolean)
(N_ "Use Dvorak keyboard")
(N_ "long description will be here."))
(define-custom 'tutcode-use-kigou2-mode? #f
'(tutcode)
'(boolean)
(N_ "Enable two stroke kigou mode")
(N_ "long description will be here."))
(define-custom 'tutcode-enable-fallback-surrounding-text? #f
'(tutcode)
'(boolean)
(N_ "Enable fallback of surrounding text API")
(N_ "long description will be here."))
(define-custom 'tutcode-keep-illegal-sequence? #f
'(tutcode)
'(boolean)
(N_ "Keep key sequence not convertible to Kanji")
(N_ "long description will be here."))
(define-custom 'tutcode-delete-leading-delimiter-on-postfix-kanji2seq? #f
'(tutcode)
'(boolean)
(N_ "Delete leading delimiter on postfix kanji to sequence conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-history-size 0
'(tutcode)
'(integer 0 65535)
(N_ "History size")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-yomi-max 10
'(tutcode tutcode-mazegaki)
'(integer 1 99)
(N_ "Maximum length of yomi for postfix mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-enable-inflection? #f
'(tutcode tutcode-mazegaki)
'(boolean)
(N_ "Enable inflection in mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-suffix-max 4
'(tutcode tutcode-mazegaki)
'(integer 1 99)
(N_ "Maximum length of yomi suffix for mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-conversion-algorithm 'tc-2.1+ml1925
'(tutcode tutcode-bushu)
(list 'choice
(list 'tc-2.1+ml1925
(N_ "tc-2.1+[tcode-ml:1925]") (N_ "tc-2.1+[tcode-ml:1925]"))
(list 'kw-yamanobe
(N_ "Kanchoku Win YAMANOBE") (N_ "Kanchoku Win YAMANOBE"))
(list 'tc-2.3.1-22.6 (N_ "tc-2.3.1-22.6") (N_ "tc-2.3.1-22.6")))
(N_ "Bushu conversion algorithm")
(N_ "long description will be here."))
(define-custom 'tutcode-use-interactive-bushu-conversion? #f
'(tutcode tutcode-bushu)
'(boolean)
(N_ "Enable interactive bushu conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-index2-filename (string-append (sys-datadir)
"/tc/bushu.index2")
'(tutcode tutcode-bushu)
'(pathname regular-file)
(N_ "bushu.index2 file")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-expand-filename (string-append (sys-datadir)
"/tc/bushu.expand")
'(tutcode tutcode-bushu)
'(pathname regular-file)
(N_ "bushu.expand file")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-help-filename ""
'(tutcode tutcode-bushu)
'(pathname regular-file)
(N_ "bushu.help file")
(N_ "long description will be here."))
;;
;; candidate window
;;
(define-custom 'tutcode-use-candidate-window? #t
'(tutcode candwin)
'(boolean)
(N_ "Use candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-use-pseudo-table-style? #f
'(tutcode candwin)
'(boolean)
(N_ "Use pseudo table style layout")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-table-layout 'qwerty-jis
'(tutcode candwin)
(list 'choice
(list 'qwerty-jis (N_ "qwerty-jis") (N_ "Qwerty JIS"))
(list 'qwerty-us (N_ "qwerty-us") (N_ "Qwerty US"))
(list 'dvorak (N_ "dvorak") (N_ "Dvorak")))
(N_ "Key layout of table style candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-commit-candidate-by-label-key 'always
'(tutcode candwin)
(list 'choice
(list 'always (N_ "always") (N_ "All keys as label key"))
(list 'havecand (N_ "which have candidate")
(N_ "Enable keys which have candidate"))
(list 'candwin (N_ "while candidate window is shown")
(N_ "Enable while candidate window is shown"))
(list 'never (N_ "never") (N_ "Never")))
(N_ "Commit candidate by heading label keys")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-op-count 5
'(tutcode candwin)
'(integer 0 99)
(N_ "Conversion key press count to show candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-kigou-mode 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for kigou mode")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-prediction 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for prediction")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-guide 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for kanji combination guide")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-history 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for history")
(N_ "long description will be here."))
(define-custom 'tutcode-use-stroke-help-window? #f
'(tutcode candwin)
'(boolean)
(N_ "Use stroke help window")
(N_ "long description will be here."))
(define-custom 'tutcode-show-stroke-help-window-on-no-input? #t
'(tutcode candwin)
'(boolean)
(N_ "Show stroke help window on no input")
(N_ "long description will be here."))
(define-custom 'tutcode-use-auto-help-window? #f
'(tutcode candwin)
'(boolean)
(N_ "Use auto help window")
(N_ "long description will be here."))
(define-custom 'tutcode-auto-help-with-real-keys? #f
'(tutcode candwin)
'(boolean)
(N_ "Show real keys on auto help window")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-use-delay? #f
'(tutcode candwin)
'(boolean)
(N_ "Use delay showing candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-mazegaki 0
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for mazegaki [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-stroke-help 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for stroke help [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-auto-help 1
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for auto help [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-completion 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for completion [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-prediction 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for prediction [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-bushu-prediction 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for bushu prediction [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-interactive-bushu 1
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for interactive bushu conversion [s]")
(N_ "long description will be here."))
;; prediction/completion
(define-custom 'tutcode-use-completion? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable completion")
(N_ "long description will be here."))
(define-custom 'tutcode-completion-chars-min 2
'(tutcode tutcode-prediction)
'(integer 0 65535)
(N_ "Minimum character length for completion")
(N_ "long description will be here."))
(define-custom 'tutcode-completion-chars-max 5
'(tutcode tutcode-prediction)
'(integer 1 65535)
(N_ "Maximum character length for completion")
(N_ "long description will be here."))
(define-custom 'tutcode-use-prediction? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable input prediction for mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-prediction-start-char-count 2
'(tutcode tutcode-prediction)
'(integer 0 65535)
(N_ "Character count to start input prediction")
(N_ "long description will be here."))
(define-custom 'tutcode-use-kanji-combination-guide? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable Kanji combination guide")
(N_ "long description will be here."))
(define-custom 'tutcode-stroke-help-with-kanji-combination-guide 'disable
'(tutcode tutcode-prediction)
(list 'choice
(list 'full (N_ "Full stroke help") (N_ "Full stroke help"))
(list 'guide-only (N_ "Guide only") (N_ "Guide only"))
(list 'disable (N_ "Disable") (N_ "Disable")))
(N_ "Show stroke help temporarily by keys in kanji combination guide")
(N_ "long description will be here."))
(define-custom 'tutcode-use-bushu-prediction? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable input prediction for bushu conversion")
(N_ "long description will be here."))
;; activity dependency
(custom-add-hook 'tutcode-mazegaki-fixed-priority-count
'custom-activity-hooks
(lambda ()
tutcode-enable-mazegaki-learning?))
(custom-add-hook 'tutcode-candidate-op-count
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-nr-candidate-max
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-nr-candidate-max-for-kigou-mode
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-nr-candidate-max-for-history
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-auto-help-with-real-keys?
'custom-activity-hooks
(lambda ()
tutcode-use-auto-help-window?))
(define (tutcode-custom-adjust-nr-candidate-max)
(if (or (eq? candidate-window-style 'table) tutcode-use-pseudo-table-style?)
(begin
(custom-set-value! 'tutcode-nr-candidate-max
(length tutcode-table-heading-label-char-list))
(custom-set-value!
'tutcode-nr-candidate-max-for-kigou-mode
(length tutcode-table-heading-label-char-list-for-kigou-mode))
(custom-set-value!
'tutcode-nr-candidate-max-for-prediction
(length tutcode-heading-label-char-list-for-prediction))
(custom-set-value!
'tutcode-nr-candidate-max-for-guide
(- (length tutcode-table-heading-label-char-list-for-kigou-mode)
(length tutcode-heading-label-char-list-for-prediction)))
(custom-set-value!
'tutcode-nr-candidate-max-for-history
(length tutcode-table-heading-label-char-list)))
(begin
(custom-set-value! 'tutcode-nr-candidate-max 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-kigou-mode 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-prediction 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-guide 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-history 10))))
(custom-add-hook 'candidate-window-style
'custom-set-hooks
tutcode-custom-adjust-nr-candidate-max)
(custom-add-hook 'tutcode-use-pseudo-table-style?
'custom-set-hooks
tutcode-custom-adjust-nr-candidate-max)
(custom-add-hook 'tutcode-candidate-window-table-layout
'custom-activity-hooks
(lambda ()
(eq? candidate-window-style 'table)))
(custom-add-hook 'tutcode-bushu-index2-filename
'custom-activity-hooks
(lambda ()
(or
tutcode-use-interactive-bushu-conversion?
(eq? tutcode-bushu-conversion-algorithm 'tc-2.3.1-22.6))))
(custom-add-hook 'tutcode-bushu-expand-filename
'custom-activity-hooks
(lambda ()
(or
tutcode-use-interactive-bushu-conversion?
(eq? tutcode-bushu-conversion-algorithm 'tc-2.3.1-22.6))))
| null | https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/scm/tutcode-custom.scm | scheme | tutcode-custom.scm: Customization variables for tutcode.scm
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
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.
dictionary
candidate window
prediction/completion
activity dependency | Copyright ( c ) 2003 - 2013 uim Project
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(require "i18n.scm")
(define tutcode-im-name-label (N_ "TUT-Code"))
(define tutcode-im-short-desc (N_ "uim version of TUT-Code input method"))
(define-custom-group 'tutcode
tutcode-im-name-label
tutcode-im-short-desc)
(define-custom-group 'tutcode-dict
(N_ "TUT-Code dictionaries")
(N_ "Dictionary settings for TUT-Code"))
(define-custom-group 'tutcode-bushu
(N_ "Bushu conversion")
(N_ "Bushu conversion settings for TUT-Code"))
(define-custom-group 'tutcode-mazegaki
(N_ "Mazegaki conversion")
(N_ "Mazegaki conversion settings for TUT-Code"))
(define-custom-group 'tutcode-prediction
(N_ "Prediction")
(N_ "long description will be here."))
(define-custom 'tutcode-dic-filename (string-append (sys-datadir)
"/tc/mazegaki.dic")
'(tutcode tutcode-dict)
'(pathname regular-file)
(N_ "Mazegaki dictionary file")
(N_ "long description will be here."))
(define-custom 'tutcode-personal-dic-filename
(string-append (or (home-directory (user-name)) "") "/.mazegaki.dic")
'(tutcode tutcode-dict)
'(pathname regular-file)
(N_ "Personal mazegaki dictionary file")
(N_ "long description will be here."))
(define-custom 'tutcode-rule-filename
(string-append (sys-pkgdatadir) "/tutcode-rule.scm")
'(tutcode)
'(pathname regular-file)
(N_ "Code table file")
(N_ "Code table name is 'filename-rule' when code table file name is 'filename.scm'."))
(define-custom 'tutcode-enable-mazegaki-learning? #t
'(tutcode tutcode-mazegaki)
'(boolean)
(N_ "Enable learning in mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-fixed-priority-count 0
'(tutcode tutcode-mazegaki)
'(integer 0 65535)
(N_ "Number of candidates to be excluded from mazegaki learning")
(N_ "long description will be here."))
(define-custom 'tutcode-use-recursive-learning? #t
'(tutcode tutcode-mazegaki)
'(boolean)
(N_ "Use recursive learning")
(N_ "long description will be here."))
(define-custom 'tutcode-use-with-vi? #f
'(tutcode)
'(boolean)
(N_ "Enable vi-cooperative mode")
(N_ "long description will be here."))
(define-custom 'tutcode-show-pending-rk? #f
'(tutcode)
'(boolean)
(N_ "Show pending key sequences")
(N_ "long description will be here."))
(define-custom 'tutcode-use-dvorak? #f
'(tutcode)
'(boolean)
(N_ "Use Dvorak keyboard")
(N_ "long description will be here."))
(define-custom 'tutcode-use-kigou2-mode? #f
'(tutcode)
'(boolean)
(N_ "Enable two stroke kigou mode")
(N_ "long description will be here."))
(define-custom 'tutcode-enable-fallback-surrounding-text? #f
'(tutcode)
'(boolean)
(N_ "Enable fallback of surrounding text API")
(N_ "long description will be here."))
(define-custom 'tutcode-keep-illegal-sequence? #f
'(tutcode)
'(boolean)
(N_ "Keep key sequence not convertible to Kanji")
(N_ "long description will be here."))
(define-custom 'tutcode-delete-leading-delimiter-on-postfix-kanji2seq? #f
'(tutcode)
'(boolean)
(N_ "Delete leading delimiter on postfix kanji to sequence conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-history-size 0
'(tutcode)
'(integer 0 65535)
(N_ "History size")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-yomi-max 10
'(tutcode tutcode-mazegaki)
'(integer 1 99)
(N_ "Maximum length of yomi for postfix mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-enable-inflection? #f
'(tutcode tutcode-mazegaki)
'(boolean)
(N_ "Enable inflection in mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-mazegaki-suffix-max 4
'(tutcode tutcode-mazegaki)
'(integer 1 99)
(N_ "Maximum length of yomi suffix for mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-conversion-algorithm 'tc-2.1+ml1925
'(tutcode tutcode-bushu)
(list 'choice
(list 'tc-2.1+ml1925
(N_ "tc-2.1+[tcode-ml:1925]") (N_ "tc-2.1+[tcode-ml:1925]"))
(list 'kw-yamanobe
(N_ "Kanchoku Win YAMANOBE") (N_ "Kanchoku Win YAMANOBE"))
(list 'tc-2.3.1-22.6 (N_ "tc-2.3.1-22.6") (N_ "tc-2.3.1-22.6")))
(N_ "Bushu conversion algorithm")
(N_ "long description will be here."))
(define-custom 'tutcode-use-interactive-bushu-conversion? #f
'(tutcode tutcode-bushu)
'(boolean)
(N_ "Enable interactive bushu conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-index2-filename (string-append (sys-datadir)
"/tc/bushu.index2")
'(tutcode tutcode-bushu)
'(pathname regular-file)
(N_ "bushu.index2 file")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-expand-filename (string-append (sys-datadir)
"/tc/bushu.expand")
'(tutcode tutcode-bushu)
'(pathname regular-file)
(N_ "bushu.expand file")
(N_ "long description will be here."))
(define-custom 'tutcode-bushu-help-filename ""
'(tutcode tutcode-bushu)
'(pathname regular-file)
(N_ "bushu.help file")
(N_ "long description will be here."))
(define-custom 'tutcode-use-candidate-window? #t
'(tutcode candwin)
'(boolean)
(N_ "Use candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-use-pseudo-table-style? #f
'(tutcode candwin)
'(boolean)
(N_ "Use pseudo table style layout")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-table-layout 'qwerty-jis
'(tutcode candwin)
(list 'choice
(list 'qwerty-jis (N_ "qwerty-jis") (N_ "Qwerty JIS"))
(list 'qwerty-us (N_ "qwerty-us") (N_ "Qwerty US"))
(list 'dvorak (N_ "dvorak") (N_ "Dvorak")))
(N_ "Key layout of table style candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-commit-candidate-by-label-key 'always
'(tutcode candwin)
(list 'choice
(list 'always (N_ "always") (N_ "All keys as label key"))
(list 'havecand (N_ "which have candidate")
(N_ "Enable keys which have candidate"))
(list 'candwin (N_ "while candidate window is shown")
(N_ "Enable while candidate window is shown"))
(list 'never (N_ "never") (N_ "Never")))
(N_ "Commit candidate by heading label keys")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-op-count 5
'(tutcode candwin)
'(integer 0 99)
(N_ "Conversion key press count to show candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-kigou-mode 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for kigou mode")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-prediction 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for prediction")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-guide 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for kanji combination guide")
(N_ "long description will be here."))
(define-custom 'tutcode-nr-candidate-max-for-history 10
'(tutcode candwin)
'(integer 1 99)
(N_ "Number of candidates in candidate window at a time for history")
(N_ "long description will be here."))
(define-custom 'tutcode-use-stroke-help-window? #f
'(tutcode candwin)
'(boolean)
(N_ "Use stroke help window")
(N_ "long description will be here."))
(define-custom 'tutcode-show-stroke-help-window-on-no-input? #t
'(tutcode candwin)
'(boolean)
(N_ "Show stroke help window on no input")
(N_ "long description will be here."))
(define-custom 'tutcode-use-auto-help-window? #f
'(tutcode candwin)
'(boolean)
(N_ "Use auto help window")
(N_ "long description will be here."))
(define-custom 'tutcode-auto-help-with-real-keys? #f
'(tutcode candwin)
'(boolean)
(N_ "Show real keys on auto help window")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-use-delay? #f
'(tutcode candwin)
'(boolean)
(N_ "Use delay showing candidate window")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-mazegaki 0
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for mazegaki [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-stroke-help 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for stroke help [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-auto-help 1
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for auto help [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-completion 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for completion [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-prediction 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for prediction [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-bushu-prediction 2
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for bushu prediction [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-candidate-window-activate-delay-for-interactive-bushu 1
'(tutcode candwin)
'(integer 0 65535)
(N_ "Delay before showing candidate window for interactive bushu conversion [s]")
(N_ "long description will be here."))
(define-custom 'tutcode-use-completion? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable completion")
(N_ "long description will be here."))
(define-custom 'tutcode-completion-chars-min 2
'(tutcode tutcode-prediction)
'(integer 0 65535)
(N_ "Minimum character length for completion")
(N_ "long description will be here."))
(define-custom 'tutcode-completion-chars-max 5
'(tutcode tutcode-prediction)
'(integer 1 65535)
(N_ "Maximum character length for completion")
(N_ "long description will be here."))
(define-custom 'tutcode-use-prediction? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable input prediction for mazegaki conversion")
(N_ "long description will be here."))
(define-custom 'tutcode-prediction-start-char-count 2
'(tutcode tutcode-prediction)
'(integer 0 65535)
(N_ "Character count to start input prediction")
(N_ "long description will be here."))
(define-custom 'tutcode-use-kanji-combination-guide? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable Kanji combination guide")
(N_ "long description will be here."))
(define-custom 'tutcode-stroke-help-with-kanji-combination-guide 'disable
'(tutcode tutcode-prediction)
(list 'choice
(list 'full (N_ "Full stroke help") (N_ "Full stroke help"))
(list 'guide-only (N_ "Guide only") (N_ "Guide only"))
(list 'disable (N_ "Disable") (N_ "Disable")))
(N_ "Show stroke help temporarily by keys in kanji combination guide")
(N_ "long description will be here."))
(define-custom 'tutcode-use-bushu-prediction? #f
'(tutcode tutcode-prediction)
'(boolean)
(N_ "Enable input prediction for bushu conversion")
(N_ "long description will be here."))
(custom-add-hook 'tutcode-mazegaki-fixed-priority-count
'custom-activity-hooks
(lambda ()
tutcode-enable-mazegaki-learning?))
(custom-add-hook 'tutcode-candidate-op-count
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-nr-candidate-max
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-nr-candidate-max-for-kigou-mode
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-nr-candidate-max-for-history
'custom-activity-hooks
(lambda ()
tutcode-use-candidate-window?))
(custom-add-hook 'tutcode-auto-help-with-real-keys?
'custom-activity-hooks
(lambda ()
tutcode-use-auto-help-window?))
(define (tutcode-custom-adjust-nr-candidate-max)
(if (or (eq? candidate-window-style 'table) tutcode-use-pseudo-table-style?)
(begin
(custom-set-value! 'tutcode-nr-candidate-max
(length tutcode-table-heading-label-char-list))
(custom-set-value!
'tutcode-nr-candidate-max-for-kigou-mode
(length tutcode-table-heading-label-char-list-for-kigou-mode))
(custom-set-value!
'tutcode-nr-candidate-max-for-prediction
(length tutcode-heading-label-char-list-for-prediction))
(custom-set-value!
'tutcode-nr-candidate-max-for-guide
(- (length tutcode-table-heading-label-char-list-for-kigou-mode)
(length tutcode-heading-label-char-list-for-prediction)))
(custom-set-value!
'tutcode-nr-candidate-max-for-history
(length tutcode-table-heading-label-char-list)))
(begin
(custom-set-value! 'tutcode-nr-candidate-max 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-kigou-mode 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-prediction 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-guide 10)
(custom-set-value! 'tutcode-nr-candidate-max-for-history 10))))
(custom-add-hook 'candidate-window-style
'custom-set-hooks
tutcode-custom-adjust-nr-candidate-max)
(custom-add-hook 'tutcode-use-pseudo-table-style?
'custom-set-hooks
tutcode-custom-adjust-nr-candidate-max)
(custom-add-hook 'tutcode-candidate-window-table-layout
'custom-activity-hooks
(lambda ()
(eq? candidate-window-style 'table)))
(custom-add-hook 'tutcode-bushu-index2-filename
'custom-activity-hooks
(lambda ()
(or
tutcode-use-interactive-bushu-conversion?
(eq? tutcode-bushu-conversion-algorithm 'tc-2.3.1-22.6))))
(custom-add-hook 'tutcode-bushu-expand-filename
'custom-activity-hooks
(lambda ()
(or
tutcode-use-interactive-bushu-conversion?
(eq? tutcode-bushu-conversion-algorithm 'tc-2.3.1-22.6))))
|
d1e528c58e81236a0ea905ab35af223adfe81a4378676d9f891d932a777af2c6 | noinia/hgeometry | Properties.hs | {-# LANGUAGE ImpredicativeTypes #-}
# LANGUAGE UnicodeSyntax #
--------------------------------------------------------------------------------
-- |
-- Module : Geometry.Properties
Copyright : ( C )
-- License : see the LICENSE file
Maintainer :
--
Defines some generic geometric properties e.g. Dimensions , NumType , and
-- Intersection types.
--
--------------------------------------------------------------------------------
module Geometry.Properties( module Data.Intersection
, Dimension
, NumType
) where
import Data.Ext
import Data.Intersection
import Data.Kind (Type)
import Data.Range
import GHC.TypeLits
-------------------------------------------------------------------------------
-- | A type family for types that are associated with a dimension. The
-- dimension is the dimension of the geometry they are embedded in.
type family Dimension t :: Nat
-- | A type family for types that have an associated numeric type.
type family NumType t :: Type
--------------------------------------------------------------------------------
type instance NumType (core :+ ext) = NumType core
type instance Dimension (core :+ ext) = Dimension core
type instance NumType [t] = NumType t
type instance NumType (Range a) = a
-- type IsAlwaysTrueFromEither a b = (VTL.RIndex b [a,b] ~ ((VTL.S VTL.Z)))
-- -- VTL.RIndex b [a,b] ~ ((VTL.S VTL.Z))(b ∈ [a,b])
-- | Convert an either to a CoRec . The type class constraint is silly , and is
-- triviall true . Somehow GHC does not see that though .
-- fromEither :: IsAlwaysTrueFromEither a b => Either a b -> CoRec Identity [a,b]
-- fromEither (Left x) = coRec x
fromEither ( Right x ) = coRec x
-- -- fromEither' :: ( RElem b [a,b] ((VTL.S VTL.Z))
-- -- ) => Either a b -> CoRec Identity [a,b]
-- fromEither' :: ( VTL.RIndex b [a,b] ~ ((VTL.S VTL.Z))
-- -- VTL.RIndex b '[b] ~ VTL.Z
-- ) => Either a b -> CoRec Identity [a,b]
-- fromEither' (Left x) = coRec x
fromEither ' ( Right x ) = coRec x
-- type family Union g h :: *
-- class IsUnionableWith g h where
-- union :: g -> h -> Union g h
| null | https://raw.githubusercontent.com/noinia/hgeometry/46084245edc2b335c809f6ebc04ff5e52731a436/hgeometry/src/Geometry/Properties.hs | haskell | # LANGUAGE ImpredicativeTypes #
------------------------------------------------------------------------------
|
Module : Geometry.Properties
License : see the LICENSE file
Intersection types.
------------------------------------------------------------------------------
-----------------------------------------------------------------------------
| A type family for types that are associated with a dimension. The
dimension is the dimension of the geometry they are embedded in.
| A type family for types that have an associated numeric type.
------------------------------------------------------------------------------
type IsAlwaysTrueFromEither a b = (VTL.RIndex b [a,b] ~ ((VTL.S VTL.Z)))
-- VTL.RIndex b [a,b] ~ ((VTL.S VTL.Z))(b ∈ [a,b])
| Convert an either to a CoRec . The type class constraint is silly , and is
triviall true . Somehow GHC does not see that though .
fromEither :: IsAlwaysTrueFromEither a b => Either a b -> CoRec Identity [a,b]
fromEither (Left x) = coRec x
-- fromEither' :: ( RElem b [a,b] ((VTL.S VTL.Z))
-- ) => Either a b -> CoRec Identity [a,b]
fromEither' :: ( VTL.RIndex b [a,b] ~ ((VTL.S VTL.Z))
-- VTL.RIndex b '[b] ~ VTL.Z
) => Either a b -> CoRec Identity [a,b]
fromEither' (Left x) = coRec x
type family Union g h :: *
class IsUnionableWith g h where
union :: g -> h -> Union g h | # LANGUAGE UnicodeSyntax #
Copyright : ( C )
Maintainer :
Defines some generic geometric properties e.g. Dimensions , NumType , and
module Geometry.Properties( module Data.Intersection
, Dimension
, NumType
) where
import Data.Ext
import Data.Intersection
import Data.Kind (Type)
import Data.Range
import GHC.TypeLits
type family Dimension t :: Nat
type family NumType t :: Type
type instance NumType (core :+ ext) = NumType core
type instance Dimension (core :+ ext) = Dimension core
type instance NumType [t] = NumType t
type instance NumType (Range a) = a
fromEither ( Right x ) = coRec x
fromEither ' ( Right x ) = coRec x
|
8815ef8e0344a78dbee8132852dda08a07e514371248cc3d38a280f67ddb5336 | ghcjs/ghcjs-dom | RTCPeerConnectionIceEvent.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.RTCPeerConnectionIceEvent
(js_getCandidate, getCandidate, getCandidateUnsafe,
getCandidateUnchecked, RTCPeerConnectionIceEvent(..),
gTypeRTCPeerConnectionIceEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"candidate\"]"
js_getCandidate ::
RTCPeerConnectionIceEvent -> IO (Nullable RTCIceCandidate)
| < -US/docs/Web/API/RTCPeerConnectionIceEvent.candidate Mozilla RTCPeerConnectionIceEvent.candidate documentation >
getCandidate ::
(MonadIO m) =>
RTCPeerConnectionIceEvent -> m (Maybe RTCIceCandidate)
getCandidate self
= liftIO (nullableToMaybe <$> (js_getCandidate self))
| < -US/docs/Web/API/RTCPeerConnectionIceEvent.candidate Mozilla RTCPeerConnectionIceEvent.candidate documentation >
getCandidateUnsafe ::
(MonadIO m, HasCallStack) =>
RTCPeerConnectionIceEvent -> m RTCIceCandidate
getCandidateUnsafe self
= liftIO
((nullableToMaybe <$> (js_getCandidate self)) >>=
maybe (Prelude.error "Nothing to return") return)
| < -US/docs/Web/API/RTCPeerConnectionIceEvent.candidate Mozilla RTCPeerConnectionIceEvent.candidate documentation >
getCandidateUnchecked ::
(MonadIO m) => RTCPeerConnectionIceEvent -> m RTCIceCandidate
getCandidateUnchecked self
= liftIO (fromJust . nullableToMaybe <$> (js_getCandidate self)) | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCPeerConnectionIceEvent.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.RTCPeerConnectionIceEvent
(js_getCandidate, getCandidate, getCandidateUnsafe,
getCandidateUnchecked, RTCPeerConnectionIceEvent(..),
gTypeRTCPeerConnectionIceEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"candidate\"]"
js_getCandidate ::
RTCPeerConnectionIceEvent -> IO (Nullable RTCIceCandidate)
| < -US/docs/Web/API/RTCPeerConnectionIceEvent.candidate Mozilla RTCPeerConnectionIceEvent.candidate documentation >
getCandidate ::
(MonadIO m) =>
RTCPeerConnectionIceEvent -> m (Maybe RTCIceCandidate)
getCandidate self
= liftIO (nullableToMaybe <$> (js_getCandidate self))
| < -US/docs/Web/API/RTCPeerConnectionIceEvent.candidate Mozilla RTCPeerConnectionIceEvent.candidate documentation >
getCandidateUnsafe ::
(MonadIO m, HasCallStack) =>
RTCPeerConnectionIceEvent -> m RTCIceCandidate
getCandidateUnsafe self
= liftIO
((nullableToMaybe <$> (js_getCandidate self)) >>=
maybe (Prelude.error "Nothing to return") return)
| < -US/docs/Web/API/RTCPeerConnectionIceEvent.candidate Mozilla RTCPeerConnectionIceEvent.candidate documentation >
getCandidateUnchecked ::
(MonadIO m) => RTCPeerConnectionIceEvent -> m RTCIceCandidate
getCandidateUnchecked self
= liftIO (fromJust . nullableToMaybe <$> (js_getCandidate self)) |
cae4a514a0d3a913a62ba426971a5a32d4936eea662e12d27b5b282f19f8804d | CardanoSolutions/ogmios | Tracers.hs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
# LANGUAGE TypeOperators #
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors #
{-# OPTIONS_HADDOCK prune #-}
-- | This module provides a way to generically define and configure multiple
-- tracers for multiple logging components.
--
-- This is useful in order to associate separate configuration (e.g. minimum
-- severity) to tracers corresponding to different parts of an application. For
-- example, in a webserver, one may imagine wanting to lower the verbosity of a
-- tracer used for all HTTP requests, but keep the database tracer at a debug
-- level.
--
-- While this is possible to do without generics, it usually requires a bit of
boilerplate and repetitions . This module makes it easy to define one - single
-- data object as a record, for representing both severities configurations and
-- concrete instantiated tracers. Type signatures are a bit frightening, but the
usage is pretty simple ( see ' Control . Tracer ' for examples )
--
module Data.Generics.Tracers
( -- * Definition
IsRecordOfTracers
, TracerDefinition (..)
, type TracerHKD
-- * Construction
, configureTracers
, defaultTracers
Internal
, SomeMsg (..)
) where
import Prelude
import GHC.Generics
import Control.Tracer
( Tracer (..), nullTracer )
import Data.Aeson
( ToJSON (..) )
import Data.Functor.Const
( Const (..) )
import Data.Functor.Contravariant
( contramap )
import Data.Kind
( Type )
import Data.Severity
( HasSeverityAnnotation (..), Severity )
-- * Definition
-- | A constraint-alias defining generic record of tracers.
type IsRecordOfTracers tracers m =
( GConfigureTracers m (Rep (tracers m MinSeverities)) (Rep (tracers m Concrete))
, Generic (tracers m MinSeverities)
, Generic (tracers m Concrete)
)
-- | A data kind to control what's defined in a generic record of tracer.
--
-- Use 'configureTracers' to turn a record of configuration into a record of
-- concrete tracers.
data TracerDefinition = Concrete | MinSeverities
-- | A high-kinded type family to make definitions of tracers more readable. For
-- example, one can define a multi-component set of tracers as such:
--
data Tracers m ( kind : : TracerDefinition ) = Tracers
-- { tracerHttp :: TracerHKD kind (Tracer m HttpLog)
, : : TracerHKD kind ( Tracer m StartLog )
-- }
type family TracerHKD (definition :: TracerDefinition) (tracer :: Type) :: Type where
TracerHKD MinSeverities tracer = Const (Maybe Severity) tracer
TracerHKD Concrete tracer = tracer
-- * Construction
| Convert a ' MinSeverities ' of tracers into a ' Concrete ' record of tracers ,
using a base opaque ' Tracer ' .
configureTracers
:: ( IsRecordOfTracers tracers m )
=> tracers m MinSeverities
-> Tracer m SomeMsg
-> tracers m Concrete
configureTracers f tr =
to . gConfigureTracers mempty tr . from $ f
class GConfigureTracers m (f :: Type -> Type) (g :: Type -> Type) where
gConfigureTracers
:: String
-> Tracer m SomeMsg
-> f (Const (Maybe Severity) tr)
-> g tr
instance GConfigureTracers m f g => GConfigureTracers m (D1 c f) (D1 c g) where
gConfigureTracers field tr = M1 . gConfigureTracers field tr . unM1
instance GConfigureTracers m f g => GConfigureTracers m (C1 c f) (C1 c g) where
gConfigureTracers field tr = M1 . gConfigureTracers field tr . unM1
instance (Selector s, GConfigureTracers m f g) => GConfigureTracers m (S1 s f) (S1 s g) where
gConfigureTracers _ tr = M1 . gConfigureTracers field tr . unM1
where
field = selName (undefined :: S1 s f a)
instance (GConfigureTracers m f0 g0, GConfigureTracers m f1 g1)
=> GConfigureTracers m (f0 :*: f1) (g0 :*: g1)
where
gConfigureTracers field tr (f0 :*: f1) =
gConfigureTracers field tr f0
:*:
gConfigureTracers field tr f1
instance (ToJSON msg, HasSeverityAnnotation msg, Applicative m)
=> GConfigureTracers m (K1 i (Const (Maybe Severity) (Tracer m msg))) (K1 i (Tracer m msg))
where
gConfigureTracers field tr = \case
K1 (Const (Just minSeverity)) ->
K1 (contramap (SomeMsg minSeverity field) tr)
K1 (Const Nothing) ->
K1 nullTracer
-- | Assign a default value to a record of tracers.
--
-- This is useful when used in conjunction with 'Const' and a record of tracer
-- severities:
--
-- defaultTracers Info == Tracers
-- { tracerHttp = Const (Just Info)
-- , tracerDb = Const (Just Info)
-- }
--
defaultTracers
:: forall tracers (m :: Type -> Type).
( Generic (tracers m MinSeverities)
, GDefaultRecord (Rep (tracers m MinSeverities))
, GDefaultRecordType (Rep (tracers m MinSeverities)) ~ Maybe Severity
)
=> Maybe Severity
-> tracers m MinSeverities
defaultTracers =
to . gDefaultRecord
-- | This generic class allows for defining a default value to a record of
-- functors wrapping some type 'a'.
class GDefaultRecord (f :: Type -> Type) where
type GDefaultRecordType f :: Type
gDefaultRecord :: GDefaultRecordType f -> f (Const (GDefaultRecordType f) b)
instance GDefaultRecord f => GDefaultRecord (D1 c f) where
type GDefaultRecordType (D1 c f) = GDefaultRecordType f
gDefaultRecord a = M1 (gDefaultRecord a)
instance GDefaultRecord f => GDefaultRecord (C1 c f) where
type GDefaultRecordType (C1 c f) = GDefaultRecordType f
gDefaultRecord a = M1 (gDefaultRecord a)
instance GDefaultRecord f => GDefaultRecord (S1 c f) where
type GDefaultRecordType (S1 c f) = GDefaultRecordType f
gDefaultRecord a = M1 (gDefaultRecord a)
instance (GDefaultRecord f, GDefaultRecord g, GDefaultRecordType f ~ GDefaultRecordType g) => GDefaultRecord (f :*: g) where
type GDefaultRecordType (f :*: g) = GDefaultRecordType f
gDefaultRecord a = gDefaultRecord a :*: gDefaultRecord a
instance GDefaultRecord (K1 i (Const a b)) where
type GDefaultRecordType (K1 i (Const a b)) = a
gDefaultRecord a = K1 (Const a)
Internal
A GADT capturing constraints as existential .
data SomeMsg where
SomeMsg
:: forall msg. (ToJSON msg, HasSeverityAnnotation msg)
=> Severity
-> String
-> msg
-> SomeMsg
| null | https://raw.githubusercontent.com/CardanoSolutions/ogmios/184bb9e9a66e30c7485482a530ad68c8851d317c/server/modules/contra-tracers/src/Data/Generics/Tracers.hs | haskell | # OPTIONS_HADDOCK prune #
| This module provides a way to generically define and configure multiple
tracers for multiple logging components.
This is useful in order to associate separate configuration (e.g. minimum
severity) to tracers corresponding to different parts of an application. For
example, in a webserver, one may imagine wanting to lower the verbosity of a
tracer used for all HTTP requests, but keep the database tracer at a debug
level.
While this is possible to do without generics, it usually requires a bit of
data object as a record, for representing both severities configurations and
concrete instantiated tracers. Type signatures are a bit frightening, but the
* Definition
* Construction
* Definition
| A constraint-alias defining generic record of tracers.
| A data kind to control what's defined in a generic record of tracer.
Use 'configureTracers' to turn a record of configuration into a record of
concrete tracers.
| A high-kinded type family to make definitions of tracers more readable. For
example, one can define a multi-component set of tracers as such:
{ tracerHttp :: TracerHKD kind (Tracer m HttpLog)
}
* Construction
| Assign a default value to a record of tracers.
This is useful when used in conjunction with 'Const' and a record of tracer
severities:
defaultTracers Info == Tracers
{ tracerHttp = Const (Just Info)
, tracerDb = Const (Just Info)
}
| This generic class allows for defining a default value to a record of
functors wrapping some type 'a'. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
# LANGUAGE TypeOperators #
# OPTIONS_GHC -fno - warn - unticked - promoted - constructors #
boilerplate and repetitions . This module makes it easy to define one - single
usage is pretty simple ( see ' Control . Tracer ' for examples )
module Data.Generics.Tracers
IsRecordOfTracers
, TracerDefinition (..)
, type TracerHKD
, configureTracers
, defaultTracers
Internal
, SomeMsg (..)
) where
import Prelude
import GHC.Generics
import Control.Tracer
( Tracer (..), nullTracer )
import Data.Aeson
( ToJSON (..) )
import Data.Functor.Const
( Const (..) )
import Data.Functor.Contravariant
( contramap )
import Data.Kind
( Type )
import Data.Severity
( HasSeverityAnnotation (..), Severity )
type IsRecordOfTracers tracers m =
( GConfigureTracers m (Rep (tracers m MinSeverities)) (Rep (tracers m Concrete))
, Generic (tracers m MinSeverities)
, Generic (tracers m Concrete)
)
data TracerDefinition = Concrete | MinSeverities
data Tracers m ( kind : : TracerDefinition ) = Tracers
, : : TracerHKD kind ( Tracer m StartLog )
type family TracerHKD (definition :: TracerDefinition) (tracer :: Type) :: Type where
TracerHKD MinSeverities tracer = Const (Maybe Severity) tracer
TracerHKD Concrete tracer = tracer
| Convert a ' MinSeverities ' of tracers into a ' Concrete ' record of tracers ,
using a base opaque ' Tracer ' .
configureTracers
:: ( IsRecordOfTracers tracers m )
=> tracers m MinSeverities
-> Tracer m SomeMsg
-> tracers m Concrete
configureTracers f tr =
to . gConfigureTracers mempty tr . from $ f
class GConfigureTracers m (f :: Type -> Type) (g :: Type -> Type) where
gConfigureTracers
:: String
-> Tracer m SomeMsg
-> f (Const (Maybe Severity) tr)
-> g tr
instance GConfigureTracers m f g => GConfigureTracers m (D1 c f) (D1 c g) where
gConfigureTracers field tr = M1 . gConfigureTracers field tr . unM1
instance GConfigureTracers m f g => GConfigureTracers m (C1 c f) (C1 c g) where
gConfigureTracers field tr = M1 . gConfigureTracers field tr . unM1
instance (Selector s, GConfigureTracers m f g) => GConfigureTracers m (S1 s f) (S1 s g) where
gConfigureTracers _ tr = M1 . gConfigureTracers field tr . unM1
where
field = selName (undefined :: S1 s f a)
instance (GConfigureTracers m f0 g0, GConfigureTracers m f1 g1)
=> GConfigureTracers m (f0 :*: f1) (g0 :*: g1)
where
gConfigureTracers field tr (f0 :*: f1) =
gConfigureTracers field tr f0
:*:
gConfigureTracers field tr f1
instance (ToJSON msg, HasSeverityAnnotation msg, Applicative m)
=> GConfigureTracers m (K1 i (Const (Maybe Severity) (Tracer m msg))) (K1 i (Tracer m msg))
where
gConfigureTracers field tr = \case
K1 (Const (Just minSeverity)) ->
K1 (contramap (SomeMsg minSeverity field) tr)
K1 (Const Nothing) ->
K1 nullTracer
defaultTracers
:: forall tracers (m :: Type -> Type).
( Generic (tracers m MinSeverities)
, GDefaultRecord (Rep (tracers m MinSeverities))
, GDefaultRecordType (Rep (tracers m MinSeverities)) ~ Maybe Severity
)
=> Maybe Severity
-> tracers m MinSeverities
defaultTracers =
to . gDefaultRecord
class GDefaultRecord (f :: Type -> Type) where
type GDefaultRecordType f :: Type
gDefaultRecord :: GDefaultRecordType f -> f (Const (GDefaultRecordType f) b)
instance GDefaultRecord f => GDefaultRecord (D1 c f) where
type GDefaultRecordType (D1 c f) = GDefaultRecordType f
gDefaultRecord a = M1 (gDefaultRecord a)
instance GDefaultRecord f => GDefaultRecord (C1 c f) where
type GDefaultRecordType (C1 c f) = GDefaultRecordType f
gDefaultRecord a = M1 (gDefaultRecord a)
instance GDefaultRecord f => GDefaultRecord (S1 c f) where
type GDefaultRecordType (S1 c f) = GDefaultRecordType f
gDefaultRecord a = M1 (gDefaultRecord a)
instance (GDefaultRecord f, GDefaultRecord g, GDefaultRecordType f ~ GDefaultRecordType g) => GDefaultRecord (f :*: g) where
type GDefaultRecordType (f :*: g) = GDefaultRecordType f
gDefaultRecord a = gDefaultRecord a :*: gDefaultRecord a
instance GDefaultRecord (K1 i (Const a b)) where
type GDefaultRecordType (K1 i (Const a b)) = a
gDefaultRecord a = K1 (Const a)
Internal
A GADT capturing constraints as existential .
data SomeMsg where
SomeMsg
:: forall msg. (ToJSON msg, HasSeverityAnnotation msg)
=> Severity
-> String
-> msg
-> SomeMsg
|
dfb4d0a1cbc7f83d4ec874c73723d8f580890c809f6172a42764587fdec10ebc | justinethier/cyclone | delay-promise.scm | TODO : support for concurrent delay and promise as implemented by Clojure
;; See: -concurrency/
(import (scheme write) (scheme base) (cyclone concurrent) (srfi 18))
(define-record-type <shared-delay>
(%make-shared-delay done result lock)
shared-delay?
(done sd:done sd:set-done!)
(value sd:value sd:set-value!) ;; Either thunk or result
(lock sd:lock sd:set-lock!))
(define (make-shared-delay thunk)
(make-shared
(%make-shared-delay #f thunk (make-mutex))))
(define (shared-delay-deref d)
(when (not (shared-delay? d))
(error "Expected future but received" d))
(mutex-lock! (sd:lock d))
(cond
((sd:done d)
(sd:value d))
(else
(sd:set-value! d
(make-shared ((sd:value d)))) ;; Exec thunk and store result
(sd:set-done! d #t)))
(mutex-unlock! (sd:lock d))
)
(define (shared-delay-realized? obj)
(let ((rv #f))
(mutex-lock! (sd:lock obj))
(set! rv (sd:done obj))
(mutex-unlock! (sd:lock obj))
rv))
(define-syntax shared-delay
(er-macro-transformer
(lambda (expr rename compare)
`(make-shared-delay (lambda () ,(cadr expr))))))
(define (test)
(write '(testing)) (newline)
'done)
(define d (shared-delay (test)))
(write (shared-delay-deref d))(newline)
(write (shared-delay-deref d))(newline)
(write (shared-delay-deref d))(newline)
;; Promises
(define-record-type <shared-promise>
(%make-shared-promise done value lock cv)
shared-promise?
(done sp:done sp:set-done!)
(value sp:value sp:set-value!)
(lock sp:lock sp:set-lock!)
(cv sp:cv sp:set-cv!))
(define (make-shared-promise)
(make-shared
(%make-shared-promise #f #f (make-mutex) (make-condition-variable))))
;; Blocks until given promise has a value, and returns that value.
(define (shared-promise-deref obj)
(when (not (shared-promise? obj))
(error "Expected shared promise but received" obj))
(mutex-lock! (sp:lock obj))
(if (sp:done obj)
(mutex-unlock! (sp:lock obj))
(mutex-unlock! (sp:lock obj) (sp:cv obj))) ;; wait until value is ready
(sp:value obj))
(define (shared-promise-realized? obj)
(let ((rv #f))
(mutex-lock! (sp:lock obj))
(set! rv (sp:done obj))
(mutex-unlock! (sp:lock obj))
rv))
;; Delivers `value` to shared promise `obj` and unblocks waiting threads.
;; Has no effect if a value has already been delivered.
(define (deliver obj value)
(when (not (shared-promise? obj))
(error "Expected shared promise but received" obj))
(mutex-lock! (sp:lock obj))
(when (not (sp:done obj))
(sp:set-value! obj (make-shared value))
(sp:set-done! obj #t))
(mutex-unlock! (sp:lock obj))
(condition-variable-broadcast! (sp:cv obj)))
(define tp (make-thread-pool 4))
(define sp (make-shared-promise))
(thread-pool-push-task! tp
(lambda ()
(thread-sleep! 1)
(deliver sp (list (+ 1 2 3)))))
(write
`(received promised value of ,(shared-promise-deref sp)))
(newline)
| null | https://raw.githubusercontent.com/justinethier/cyclone/a1c2a8f282f37ce180a5921ae26a5deb04768269/libs/cyclone/delay-promise.scm | scheme | See: -concurrency/
Either thunk or result
Exec thunk and store result
Promises
Blocks until given promise has a value, and returns that value.
wait until value is ready
Delivers `value` to shared promise `obj` and unblocks waiting threads.
Has no effect if a value has already been delivered. | TODO : support for concurrent delay and promise as implemented by Clojure
(import (scheme write) (scheme base) (cyclone concurrent) (srfi 18))
(define-record-type <shared-delay>
(%make-shared-delay done result lock)
shared-delay?
(done sd:done sd:set-done!)
(lock sd:lock sd:set-lock!))
(define (make-shared-delay thunk)
(make-shared
(%make-shared-delay #f thunk (make-mutex))))
(define (shared-delay-deref d)
(when (not (shared-delay? d))
(error "Expected future but received" d))
(mutex-lock! (sd:lock d))
(cond
((sd:done d)
(sd:value d))
(else
(sd:set-value! d
(sd:set-done! d #t)))
(mutex-unlock! (sd:lock d))
)
(define (shared-delay-realized? obj)
(let ((rv #f))
(mutex-lock! (sd:lock obj))
(set! rv (sd:done obj))
(mutex-unlock! (sd:lock obj))
rv))
(define-syntax shared-delay
(er-macro-transformer
(lambda (expr rename compare)
`(make-shared-delay (lambda () ,(cadr expr))))))
(define (test)
(write '(testing)) (newline)
'done)
(define d (shared-delay (test)))
(write (shared-delay-deref d))(newline)
(write (shared-delay-deref d))(newline)
(write (shared-delay-deref d))(newline)
(define-record-type <shared-promise>
(%make-shared-promise done value lock cv)
shared-promise?
(done sp:done sp:set-done!)
(value sp:value sp:set-value!)
(lock sp:lock sp:set-lock!)
(cv sp:cv sp:set-cv!))
(define (make-shared-promise)
(make-shared
(%make-shared-promise #f #f (make-mutex) (make-condition-variable))))
(define (shared-promise-deref obj)
(when (not (shared-promise? obj))
(error "Expected shared promise but received" obj))
(mutex-lock! (sp:lock obj))
(if (sp:done obj)
(mutex-unlock! (sp:lock obj))
(sp:value obj))
(define (shared-promise-realized? obj)
(let ((rv #f))
(mutex-lock! (sp:lock obj))
(set! rv (sp:done obj))
(mutex-unlock! (sp:lock obj))
rv))
(define (deliver obj value)
(when (not (shared-promise? obj))
(error "Expected shared promise but received" obj))
(mutex-lock! (sp:lock obj))
(when (not (sp:done obj))
(sp:set-value! obj (make-shared value))
(sp:set-done! obj #t))
(mutex-unlock! (sp:lock obj))
(condition-variable-broadcast! (sp:cv obj)))
(define tp (make-thread-pool 4))
(define sp (make-shared-promise))
(thread-pool-push-task! tp
(lambda ()
(thread-sleep! 1)
(deliver sp (list (+ 1 2 3)))))
(write
`(received promised value of ,(shared-promise-deref sp)))
(newline)
|
04ab38fd98ce4e2c595e9983b09014b0add510d747e806da64980a0c3eb0ff30 | janestreet/core | linked_queue.ml | open! Import
module Queue = Base.Linked_queue
include Queue
include Bin_prot.Utils.Make_iterable_binable1 (struct
type 'a t = 'a Queue.t
type 'a el = 'a [@@deriving bin_io]
let caller_identity =
Bin_prot.Shape.Uuid.of_string "800df9a0-4992-11e6-881d-ffe1a5c8aced"
;;
let module_name = Some "Core.Linked_queue"
let length = length
let iter = iter
(* Bin_prot reads the elements in the same order they were written out, as determined
by [iter]. So, we can ignore the index and just enqueue each element as it is read
in. *)
let init ~len ~next =
let t = create () in
for _ = 1 to len do
enqueue t (next ())
done;
t
;;
end)
| null | https://raw.githubusercontent.com/janestreet/core/b0be1daa71b662bd38ef2bb406f7b3e70d63d05f/core/src/linked_queue.ml | ocaml | Bin_prot reads the elements in the same order they were written out, as determined
by [iter]. So, we can ignore the index and just enqueue each element as it is read
in. | open! Import
module Queue = Base.Linked_queue
include Queue
include Bin_prot.Utils.Make_iterable_binable1 (struct
type 'a t = 'a Queue.t
type 'a el = 'a [@@deriving bin_io]
let caller_identity =
Bin_prot.Shape.Uuid.of_string "800df9a0-4992-11e6-881d-ffe1a5c8aced"
;;
let module_name = Some "Core.Linked_queue"
let length = length
let iter = iter
let init ~len ~next =
let t = create () in
for _ = 1 to len do
enqueue t (next ())
done;
t
;;
end)
|
d00d133b35b87e6272ae48ab9afa39e4fa26fb75af42003863b16323d2343909 | mirage/irmin | test.ml |
* Copyright ( c ) 2013 - 2022 < >
*
* 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) 2013-2022 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.
*)
let misc = [ ("misc", Test_git.(misc mem)) ]
let () =
Lwt_main.run
@@ Irmin_test.Store.run "irmin-git" ~slow:true ~misc ~sleep:Lwt_unix.sleep
[ (`Quick, Test_git.suite); (`Quick, Test_git.suite_generic) ]
| null | https://raw.githubusercontent.com/mirage/irmin/9bcce092a500e7e7e88dab3e0240091488e46abe/test/irmin-git/test.ml | ocaml |
* Copyright ( c ) 2013 - 2022 < >
*
* 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) 2013-2022 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.
*)
let misc = [ ("misc", Test_git.(misc mem)) ]
let () =
Lwt_main.run
@@ Irmin_test.Store.run "irmin-git" ~slow:true ~misc ~sleep:Lwt_unix.sleep
[ (`Quick, Test_git.suite); (`Quick, Test_git.suite_generic) ]
| |
17982b1274b684b58e74e214effd92b92930301836420697e5cdd381ddb94890 | sbelak/huri | core_test.clj | (ns huri.core-test
(:require [clojure.test :refer :all]
[huri.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/sbelak/huri/a242d9d044dfa1c03691b5362bb94fc6fba20f30/test/huri/core_test.clj | clojure | (ns huri.core-test
(:require [clojure.test :refer :all]
[huri.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| |
417193e364603519800eddf4d45a24e473b6124e82f91ea1c5f3dc2dff855bda | r0man/netcdf-clj | datafy.clj | (ns netcdf.datafy
(:require [clojure.core.protocols :refer [Datafiable]]
[clojure.datafy :refer [datafy]]))
(extend-type ucar.ma2.DataType
Datafiable
(datafy [data-type]
(keyword (str data-type))))
(extend-type ucar.nc2.Attribute
Datafiable
(datafy [attribute]
{:name (.getName attribute)
:values (mapv #(.getValue attribute %) (range (.getLength attribute)))}))
(extend-type ucar.nc2.dataset.CoordinateSystem
Datafiable
(datafy [coordinate-system]
{:name (.getName coordinate-system)
:projection (datafy (.getProjection coordinate-system))}))
(extend-type ucar.nc2.dataset.NetcdfDataset
Datafiable
(datafy [dataset]
{:convention (.getConventionUsed dataset)
:global-attributes (mapv datafy (.getGlobalAttributes dataset))
:variables (mapv datafy (.getVariables dataset))}))
(extend-type ucar.nc2.dataset.VariableDS
Datafiable
(datafy [variable]
{:coordinate-systems (mapv datafy (.getCoordinateSystems variable))
:data-type (datafy (.getDataType variable))
:dataset-location (.getDatasetLocation variable)
:description (.getDescription variable)
:dimensions (mapv datafy (.getDimensions variable))
:fill-value (.getFillValue variable)
:missing-values (.getMissingValues variable)
:name (.getName variable)
:size (.getSize variable)
:units (.getUnitsString variable)}))
(extend-type ucar.nc2.Dimension
Datafiable
(datafy [dimension]
{:length (.getLength dimension)
:name (.getName dimension)}))
(extend-type ucar.unidata.geoloc.Projection
Datafiable
(datafy [projection]
{:name (.getName projection)
:params (mapv datafy (.getProjectionParameters projection))}))
(extend-type ucar.unidata.util.Parameter
Datafiable
(datafy [parameter]
(cond-> {:name (.getName parameter)}
(.isString parameter)
(assoc :values [(.getStringValue parameter)])
(not (.isString parameter))
(assoc :values (.getNumericValues parameter)))))
| null | https://raw.githubusercontent.com/r0man/netcdf-clj/ccca7047e849ca13266ad6bbbdc003eb52d6de16/src/netcdf/datafy.clj | clojure | (ns netcdf.datafy
(:require [clojure.core.protocols :refer [Datafiable]]
[clojure.datafy :refer [datafy]]))
(extend-type ucar.ma2.DataType
Datafiable
(datafy [data-type]
(keyword (str data-type))))
(extend-type ucar.nc2.Attribute
Datafiable
(datafy [attribute]
{:name (.getName attribute)
:values (mapv #(.getValue attribute %) (range (.getLength attribute)))}))
(extend-type ucar.nc2.dataset.CoordinateSystem
Datafiable
(datafy [coordinate-system]
{:name (.getName coordinate-system)
:projection (datafy (.getProjection coordinate-system))}))
(extend-type ucar.nc2.dataset.NetcdfDataset
Datafiable
(datafy [dataset]
{:convention (.getConventionUsed dataset)
:global-attributes (mapv datafy (.getGlobalAttributes dataset))
:variables (mapv datafy (.getVariables dataset))}))
(extend-type ucar.nc2.dataset.VariableDS
Datafiable
(datafy [variable]
{:coordinate-systems (mapv datafy (.getCoordinateSystems variable))
:data-type (datafy (.getDataType variable))
:dataset-location (.getDatasetLocation variable)
:description (.getDescription variable)
:dimensions (mapv datafy (.getDimensions variable))
:fill-value (.getFillValue variable)
:missing-values (.getMissingValues variable)
:name (.getName variable)
:size (.getSize variable)
:units (.getUnitsString variable)}))
(extend-type ucar.nc2.Dimension
Datafiable
(datafy [dimension]
{:length (.getLength dimension)
:name (.getName dimension)}))
(extend-type ucar.unidata.geoloc.Projection
Datafiable
(datafy [projection]
{:name (.getName projection)
:params (mapv datafy (.getProjectionParameters projection))}))
(extend-type ucar.unidata.util.Parameter
Datafiable
(datafy [parameter]
(cond-> {:name (.getName parameter)}
(.isString parameter)
(assoc :values [(.getStringValue parameter)])
(not (.isString parameter))
(assoc :values (.getNumericValues parameter)))))
| |
9b8d60ba5fcb96a935b892a46f743f95351c4f0f51ff21842d2bba768eabc925 | maximedenes/native-coq | detyping.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Pp
open Errors
open Util
open Univ
open Names
open Term
open Declarations
open Inductive
open Inductiveops
open Environ
open Sign
open Glob_term
open Nameops
open Termops
open Namegen
open Libnames
open Nametab
open Evd
open Mod_subst
let dl = dummy_loc
(****************************************************************************)
(* Tools for printing of Cases *)
let encode_inductive r =
let indsp = global_inductive r in
let constr_lengths = mis_constr_nargs indsp in
(indsp,constr_lengths)
(* Parameterization of the translation from constr to ast *)
(* Tables for Cases printing under a "if" form, a "let" form, *)
let has_two_constructors lc =
& lc.(0 ) = 0 & lc.(1 ) = 0
let isomorphic_to_tuple lc = (Array.length lc = 1)
let encode_bool r =
let (x,lc) = encode_inductive r in
if not (has_two_constructors lc) then
user_err_loc (loc_of_reference r,"encode_if",
str "This type has not exactly two constructors.");
x
let encode_tuple r =
let (x,lc) = encode_inductive r in
if not (isomorphic_to_tuple lc) then
user_err_loc (loc_of_reference r,"encode_tuple",
str "This type cannot be seen as a tuple type.");
x
module PrintingInductiveMake =
functor (Test : sig
val encode : reference -> inductive
val member_message : std_ppcmds -> bool -> std_ppcmds
val field : string
val title : string
end) ->
struct
type t = inductive
let encode = Test.encode
let subst subst (kn, ints as obj) =
let kn' = subst_ind subst kn in
if kn' == kn then obj else
kn', ints
let printer ind = pr_global_env Idset.empty (IndRef ind)
let key = ["Printing";Test.field]
let title = Test.title
let member_message x = Test.member_message (printer x)
let synchronous = true
end
module PrintingCasesIf =
PrintingInductiveMake (struct
let encode = encode_bool
let field = "If"
let title = "Types leading to pretty-printing of Cases using a `if' form: "
let member_message s b =
str "Cases on elements of " ++ s ++
str
(if b then " are printed using a `if' form"
else " are not printed using a `if' form")
end)
module PrintingCasesLet =
PrintingInductiveMake (struct
let encode = encode_tuple
let field = "Let"
let title =
"Types leading to a pretty-printing of Cases using a `let' form:"
let member_message s b =
str "Cases on elements of " ++ s ++
str
(if b then " are printed using a `let' form"
else " are not printed using a `let' form")
end)
module PrintingIf = Goptions.MakeRefTable(PrintingCasesIf)
module PrintingLet = Goptions.MakeRefTable(PrintingCasesLet)
Flags.for printing or not wildcard and synthetisable types
open Goptions
let wildcard_value = ref true
let force_wildcard () = !wildcard_value
let _ = declare_bool_option
{ optsync = true;
optdepr = false;
optname = "forced wildcard";
optkey = ["Printing";"Wildcard"];
optread = force_wildcard;
optwrite = (:=) wildcard_value }
let synth_type_value = ref true
let synthetize_type () = !synth_type_value
let _ = declare_bool_option
{ optsync = true;
optdepr = false;
optname = "pattern matching return type synthesizability";
optkey = ["Printing";"Synth"];
optread = synthetize_type;
optwrite = (:=) synth_type_value }
let reverse_matching_value = ref true
let reverse_matching () = !reverse_matching_value
let _ = declare_bool_option
{ optsync = true;
optdepr = false;
optname = "pattern-matching reversibility";
optkey = ["Printing";"Matching"];
optread = reverse_matching;
optwrite = (:=) reverse_matching_value }
(* Auxiliary function for MutCase printing *)
(* [computable] tries to tell if the predicate typing the result is inferable*)
let computable p k =
We first remove as many lambda as the arity , then we look
if it remains a lambda for a dependent elimination . This function
works for normal eta - expanded term . For non eta - expanded or
non - normal terms , it may affirm the pred is synthetisable
because of an undetected ultimate dependent variable in the second
clause , or else , it may affirms the pred non synthetisable
because of a non normal term in the fourth clause .
A solution could be to store , in the MutCase , the eta - expanded
normal form of pred to decide if it depends on its variables
certaine , on
ne déclare pas le prédicat synthétisable ( même si la
variable pas effectivement ) parce que
sinon on perd la réciprocité de la synthèse ( qui , lui ,
engendrera )
if it remains a lambda for a dependent elimination. This function
works for normal eta-expanded term. For non eta-expanded or
non-normal terms, it may affirm the pred is synthetisable
because of an undetected ultimate dependent variable in the second
clause, or else, it may affirms the pred non synthetisable
because of a non normal term in the fourth clause.
A solution could be to store, in the MutCase, the eta-expanded
normal form of pred to decide if it depends on its variables
Lorsque le prédicat est dépendant de manière certaine, on
ne déclare pas le prédicat synthétisable (même si la
variable dépendante ne l'est pas effectivement) parce que
sinon on perd la réciprocité de la synthèse (qui, lui,
engendrera un prédicat non dépendant) *)
let sign,ccl = decompose_lam_assum p in
(rel_context_length sign = k+1)
&&
noccur_between 1 (k+1) ccl
let lookup_name_as_displayed env t s =
let rec lookup avoid n c = match kind_of_term c with
| Prod (name,_,c') ->
(match compute_displayed_name_in RenamingForGoal avoid name c' with
| (Name id,avoid') -> if id=s then Some n else lookup avoid' (n+1) c'
| (Anonymous,avoid') -> lookup avoid' (n+1) (pop c'))
| LetIn (name,_,_,c') ->
(match compute_displayed_name_in RenamingForGoal avoid name c' with
| (Name id,avoid') -> if id=s then Some n else lookup avoid' (n+1) c'
| (Anonymous,avoid') -> lookup avoid' (n+1) (pop c'))
| Cast (c,_,_) -> lookup avoid n c
| _ -> None
in lookup (ids_of_named_context (named_context env)) 1 t
let lookup_index_as_renamed env t n =
let rec lookup n d c = match kind_of_term c with
| Prod (name,_,c') ->
(match compute_displayed_name_in RenamingForGoal [] name c' with
(Name _,_) -> lookup n (d+1) c'
| (Anonymous,_) ->
if n=0 then
Some (d-1)
else if n=1 then
Some d
else
lookup (n-1) (d+1) c')
| LetIn (name,_,_,c') ->
(match compute_displayed_name_in RenamingForGoal [] name c' with
| (Name _,_) -> lookup n (d+1) c'
| (Anonymous,_) ->
if n=0 then
Some (d-1)
else if n=1 then
Some d
else
lookup (n-1) (d+1) c'
)
| Cast (c,_,_) -> lookup n d c
| _ -> if n=0 then Some (d-1) else None
in lookup n 1 t
(**********************************************************************)
(* Fragile algorithm to reverse pattern-matching compilation *)
let update_name na ((_,e),c) =
match na with
| Name _ when force_wildcard () & noccurn (list_index na e) c ->
Anonymous
| _ ->
na
let rec decomp_branch n nal b (avoid,env as e) c =
let flag = if b then RenamingForGoal else RenamingForCasesPattern in
if n=0 then (List.rev nal,(e,c))
else
let na,c,f =
match kind_of_term (strip_outer_cast c) with
| Lambda (na,_,c) -> na,c,compute_displayed_let_name_in
| LetIn (na,_,_,c) -> na,c,compute_displayed_name_in
| _ ->
Name (id_of_string "x"),(applist (lift 1 c, [mkRel 1])),
compute_displayed_name_in in
let na',avoid' = f flag avoid na c in
decomp_branch (n-1) (na'::nal) b (avoid',add_name na' env) c
let rec build_tree na isgoal e ci cl =
let mkpat n rhs pl = PatCstr(dl,(ci.ci_ind,n+1),pl,update_name na rhs) in
let cnl = ci.ci_cstr_ndecls in
List.flatten
(list_tabulate (fun i -> contract_branch isgoal e (cnl.(i),mkpat i,cl.(i)))
(Array.length cl))
and align_tree nal isgoal (e,c as rhs) = match nal with
| [] -> [[],rhs]
| na::nal ->
match kind_of_term c with
| Case (ci,p,c,cl) when c = mkRel (list_index na (snd e))
do n't contract if p dependent
computable p (ci.ci_pp_info.ind_nargs) ->
let clauses = build_tree na isgoal e ci cl in
List.flatten
(List.map (fun (pat,rhs) ->
let lines = align_tree nal isgoal rhs in
List.map (fun (hd,rest) -> pat::hd,rest) lines)
clauses)
| _ ->
let pat = PatVar(dl,update_name na rhs) in
let mat = align_tree nal isgoal rhs in
List.map (fun (hd,rest) -> pat::hd,rest) mat
and contract_branch isgoal e (cn,mkpat,b) =
let nal,rhs = decomp_branch cn [] isgoal e b in
let mat = align_tree nal isgoal rhs in
List.map (fun (hd,rhs) -> (mkpat rhs hd,rhs)) mat
(**********************************************************************)
Transform internal representation of pattern - matching into list of
(* clauses *)
let is_nondep_branch c n =
try
let sign,ccl = decompose_lam_n_assum n c in
noccur_between 1 (rel_context_length sign) ccl
with _ -> (* Not eta-expanded or not reduced *)
false
let extract_nondep_branches test c b n =
let rec strip n r = if n=0 then r else
match r with
| GLambda (_,_,_,_,t) -> strip (n-1) t
| GLetIn (_,_,_,t) -> strip (n-1) t
| _ -> assert false in
if test c n then Some (strip n b) else None
let it_destRLambda_or_LetIn_names n c =
let rec aux n nal c =
if n=0 then (List.rev nal,c) else match c with
| GLambda (_,na,_,_,c) -> aux (n-1) (na::nal) c
| GLetIn (_,na,_,c) -> aux (n-1) (na::nal) c
| _ ->
(* eta-expansion *)
let rec next l =
let x = next_ident_away (id_of_string "x") l in
(* Not efficient but unusual and no function to get free glob_vars *)
if occur_glob_constr x c then next ( x::l ) else x in
x
in
let x = next (free_glob_vars c) in
let a = GVar (dl,x) in
aux (n-1) (Name x :: nal)
(match c with
| GApp (loc,p,l) -> GApp (loc,c,l@[a])
| _ -> (GApp (dl,c,[a])))
in aux n [] c
let detype_case computable detype detype_eqns testdep avoid data p c bl =
let (indsp,st,consnargsl,k) = data in
let synth_type = synthetize_type () in
let tomatch = detype c in
let alias, aliastyp, pred=
if (not !Flags.raw_print) & synth_type & computable & Array.length bl<>0
then
Anonymous, None, None
else
match Option.map detype p with
| None -> Anonymous, None, None
| Some p ->
let nl,typ = it_destRLambda_or_LetIn_names k p in
let n,typ = match typ with
| GLambda (_,x,_,t,c) -> x, c
| _ -> Anonymous, typ in
let aliastyp =
if List.for_all ((=) Anonymous) nl then None
else Some (dl,indsp,nl) in
n, aliastyp, Some typ
in
let constructs = Array.init (Array.length bl) (fun i -> (indsp,i+1)) in
let tag =
try
if !Flags.raw_print then
RegularStyle
else if st = LetPatternStyle then
st
else if PrintingLet.active indsp then
LetStyle
else if PrintingIf.active indsp then
IfStyle
else
st
with Not_found -> st
in
match tag with
| LetStyle when aliastyp = None ->
let bl' = Array.map detype bl in
let (nal,d) = it_destRLambda_or_LetIn_names consnargsl.(0) bl'.(0) in
GLetTuple (dl,nal,(alias,pred),tomatch,d)
| IfStyle when aliastyp = None ->
let bl' = Array.map detype bl in
let nondepbrs =
array_map3 (extract_nondep_branches testdep) bl bl' consnargsl in
if array_for_all ((<>) None) nondepbrs then
GIf (dl,tomatch,(alias,pred),
Option.get nondepbrs.(0),Option.get nondepbrs.(1))
else
let eqnl = detype_eqns constructs consnargsl bl in
GCases (dl,tag,pred,[tomatch,(alias,aliastyp)],eqnl)
| _ ->
let eqnl = detype_eqns constructs consnargsl bl in
GCases (dl,tag,pred,[tomatch,(alias,aliastyp)],eqnl)
let detype_sort = function
| Prop c -> GProp c
| Type u -> GType (Some u)
type binder_kind = BProd | BLambda | BLetIn
(**********************************************************************)
(* Main detyping function *)
let detype_anonymous = ref (fun loc n -> anomaly "detype: index to an anonymous variable")
let set_detype_anonymous f = detype_anonymous := f
let rec detype (isgoal:bool) avoid env t =
match kind_of_term (collapse_appl t) with
| Rel n ->
(try match lookup_name_of_rel n env with
| Name id -> GVar (dl, id)
| Anonymous -> !detype_anonymous dl n
with Not_found ->
let s = "_UNBOUND_REL_"^(string_of_int n)
in GVar (dl, id_of_string s))
| Meta n ->
Meta in constr are not user - parsable and are mapped to Evar
GEvar (dl, n, None)
| Var id ->
(try
let _ = Global.lookup_named id in GRef (dl, VarRef id)
with _ ->
GVar (dl, id))
| Sort s -> GSort (dl,detype_sort s)
| Cast (c1,k,c2) ->
GCast(dl,detype isgoal avoid env c1, CastConv (k, detype isgoal avoid env c2))
| Prod (na,ty,c) -> detype_binder isgoal BProd avoid env na ty c
| Lambda (na,ty,c) -> detype_binder isgoal BLambda avoid env na ty c
| LetIn (na,b,_,c) -> detype_binder isgoal BLetIn avoid env na b c
| App (f,args) ->
GApp (dl,detype isgoal avoid env f,
array_map_to_list (detype isgoal avoid env) args)
| Const sp -> GRef (dl, ConstRef sp)
| Evar (ev,cl) ->
GEvar (dl, ev,
Some (List.map (detype isgoal avoid env) (Array.to_list cl)))
| Ind ind_sp ->
GRef (dl, IndRef ind_sp)
| Construct cstr_sp ->
GRef (dl, ConstructRef cstr_sp)
| Case (ci,p,c,bl) ->
let comp = computable p (ci.ci_pp_info.ind_nargs) in
detype_case comp (detype isgoal avoid env)
(detype_eqns isgoal avoid env ci comp)
is_nondep_branch avoid
(ci.ci_ind,ci.ci_pp_info.style,
ci.ci_cstr_ndecls,ci.ci_pp_info.ind_nargs)
(Some p) c bl
| Fix (nvn,recdef) -> detype_fix isgoal avoid env nvn recdef
| CoFix (n,recdef) -> detype_cofix isgoal avoid env n recdef
| NativeInt i -> GNativeInt (dl,i)
| NativeArr(t,p) -> GNativeArr(dl,detype isgoal avoid env t, Array.map (detype isgoal avoid env) p)
and detype_fix isgoal avoid env (vn,_ as nvn) (names,tys,bodies) =
let def_avoid, def_env, lfi =
Array.fold_left
(fun (avoid, env, l) na ->
let id = next_name_away na avoid in
(id::avoid, add_name (Name id) env, id::l))
(avoid, env, []) names in
let n = Array.length tys in
let v = array_map3
(fun c t i -> share_names isgoal (i+1) [] def_avoid def_env c (lift n t))
bodies tys vn in
GRec(dl,GFix (Array.map (fun i -> Some i, GStructRec) (fst nvn), snd nvn),Array.of_list (List.rev lfi),
Array.map (fun (bl,_,_) -> bl) v,
Array.map (fun (_,_,ty) -> ty) v,
Array.map (fun (_,bd,_) -> bd) v)
and detype_cofix isgoal avoid env n (names,tys,bodies) =
let def_avoid, def_env, lfi =
Array.fold_left
(fun (avoid, env, l) na ->
let id = next_name_away na avoid in
(id::avoid, add_name (Name id) env, id::l))
(avoid, env, []) names in
let ntys = Array.length tys in
let v = array_map2
(fun c t -> share_names isgoal 0 [] def_avoid def_env c (lift ntys t))
bodies tys in
GRec(dl,GCoFix n,Array.of_list (List.rev lfi),
Array.map (fun (bl,_,_) -> bl) v,
Array.map (fun (_,_,ty) -> ty) v,
Array.map (fun (_,bd,_) -> bd) v)
and share_names isgoal n l avoid env c t =
match kind_of_term c, kind_of_term t with
factorize even when not necessary to have better presentation
| Lambda (na,t,c), Prod (na',t',c') ->
let na = match (na,na') with
Name _, _ -> na
| _, Name _ -> na'
| _ -> na in
let t = detype isgoal avoid env t in
let id = next_name_away na avoid in
let avoid = id::avoid and env = add_name (Name id) env in
share_names isgoal (n-1) ((Name id,Explicit,None,t)::l) avoid env c c'
May occur for fix built interactively
| LetIn (na,b,t',c), _ when n > 0 ->
let t' = detype isgoal avoid env t' in
let b = detype isgoal avoid env b in
let id = next_name_away na avoid in
let avoid = id::avoid and env = add_name (Name id) env in
share_names isgoal n ((Name id,Explicit,Some b,t')::l) avoid env c (lift 1 t)
(* Only if built with the f/n notation or w/o let-expansion in types *)
| _, LetIn (_,b,_,t) when n > 0 ->
share_names isgoal n l avoid env c (subst1 b t)
(* If it is an open proof: we cheat and eta-expand *)
| _, Prod (na',t',c') when n > 0 ->
let t' = detype isgoal avoid env t' in
let id = next_name_away na' avoid in
let avoid = id::avoid and env = add_name (Name id) env in
let appc = mkApp (lift 1 c,[|mkRel 1|]) in
share_names isgoal (n-1) ((Name id,Explicit,None,t')::l) avoid env appc c'
(* If built with the f/n notation: we renounce to share names *)
| _ ->
if n>0 then warning "Detyping.detype: cannot factorize fix enough";
let c = detype isgoal avoid env c in
let t = detype isgoal avoid env t in
(List.rev l,c,t)
and detype_eqns isgoal avoid env ci computable constructs consnargsl bl =
try
if !Flags.raw_print or not (reverse_matching ()) then raise Exit;
let mat = build_tree Anonymous isgoal (avoid,env) ci bl in
List.map (fun (pat,((avoid,env),c)) -> (dl,[],[pat],detype isgoal avoid env c))
mat
with _ ->
Array.to_list
(array_map3 (detype_eqn isgoal avoid env) constructs consnargsl bl)
and detype_eqn isgoal avoid env constr construct_nargs branch =
let make_pat x avoid env b ids =
if force_wildcard () & noccurn 1 b then
PatVar (dl,Anonymous),avoid,(add_name Anonymous env),ids
else
let id = next_name_away_in_cases_pattern x avoid in
PatVar (dl,Name id),id::avoid,(add_name (Name id) env),id::ids
in
let rec buildrec ids patlist avoid env n b =
if n=0 then
(dl, ids,
[PatCstr(dl, constr, List.rev patlist,Anonymous)],
detype isgoal avoid env b)
else
match kind_of_term b with
| Lambda (x,_,b) ->
let pat,new_avoid,new_env,new_ids = make_pat x avoid env b ids in
buildrec new_ids (pat::patlist) new_avoid new_env (n-1) b
| LetIn (x,_,_,b) ->
let pat,new_avoid,new_env,new_ids = make_pat x avoid env b ids in
buildrec new_ids (pat::patlist) new_avoid new_env (n-1) b
Oui , il y a parfois des cast
buildrec ids patlist avoid env n c
| _ -> (* eta-expansion : n'arrivera plus lorsque tous les
termes seront construits à partir de la syntaxe Cases *)
nommage de la nouvelle variable
let new_b = applist (lift 1 b, [mkRel 1]) in
let pat,new_avoid,new_env,new_ids =
make_pat Anonymous avoid env new_b ids in
buildrec new_ids (pat::patlist) new_avoid new_env (n-1) new_b
in
buildrec [] [] avoid env construct_nargs branch
and detype_binder isgoal bk avoid env na ty c =
let flag = if isgoal then RenamingForGoal else RenamingElsewhereFor (env,c) in
let na',avoid' =
if bk = BLetIn then compute_displayed_let_name_in flag avoid na c
else compute_displayed_name_in flag avoid na c in
let r = detype isgoal avoid' (add_name na' env) c in
match bk with
| BProd -> GProd (dl, na',Explicit,detype false avoid env ty, r)
| BLambda -> GLambda (dl, na',Explicit,detype false avoid env ty, r)
| BLetIn -> GLetIn (dl, na',detype false avoid env ty, r)
let rec detype_rel_context where avoid env sign =
let where = Option.map (fun c -> it_mkLambda_or_LetIn c sign) where in
let rec aux avoid env = function
| [] -> []
| (na,b,t)::rest ->
let na',avoid' =
match where with
| None -> na,avoid
| Some c ->
if b<>None then
compute_displayed_let_name_in
(RenamingElsewhereFor (env,c)) avoid na c
else
compute_displayed_name_in
(RenamingElsewhereFor (env,c)) avoid na c in
let b = Option.map (detype false avoid env) b in
let t = detype false avoid env t in
(na',Explicit,b,t) :: aux avoid' (add_name na' env) rest
in aux avoid env (List.rev sign)
(**********************************************************************)
(* Module substitution: relies on detyping *)
let rec subst_cases_pattern subst pat =
match pat with
| PatVar _ -> pat
| PatCstr (loc,((kn,i),j),cpl,n) ->
let kn' = subst_ind subst kn
and cpl' = list_smartmap (subst_cases_pattern subst) cpl in
if kn' == kn && cpl' == cpl then pat else
PatCstr (loc,((kn',i),j),cpl',n)
let rec subst_glob_constr subst raw =
match raw with
| GRef (loc,ref) ->
let ref',t = subst_global subst ref in
if ref' == ref then raw else
detype false [] [] t
| GVar _ -> raw
| GEvar _ -> raw
| GPatVar _ -> raw
| GApp (loc,r,rl) ->
let r' = subst_glob_constr subst r
and rl' = list_smartmap (subst_glob_constr subst) rl in
if r' == r && rl' == rl then raw else
GApp(loc,r',rl')
| GLambda (loc,n,bk,r1,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GLambda (loc,n,bk,r1',r2')
| GProd (loc,n,bk,r1,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GProd (loc,n,bk,r1',r2')
| GLetIn (loc,n,r1,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GLetIn (loc,n,r1',r2')
| GCases (loc,sty,rtno,rl,branches) ->
let rtno' = Option.smartmap (subst_glob_constr subst) rtno
and rl' = list_smartmap (fun (a,x as y) ->
let a' = subst_glob_constr subst a in
let (n,topt) = x in
let topt' = Option.smartmap
(fun (loc,(sp,i),y as t) ->
let sp' = subst_ind subst sp in
if sp == sp' then t else (loc,(sp',i),y)) topt in
if a == a' && topt == topt' then y else (a',(n,topt'))) rl
and branches' = list_smartmap
(fun (loc,idl,cpl,r as branch) ->
let cpl' =
list_smartmap (subst_cases_pattern subst) cpl
and r' = subst_glob_constr subst r in
if cpl' == cpl && r' == r then branch else
(loc,idl,cpl',r'))
branches
in
if rtno' == rtno && rl' == rl && branches' == branches then raw else
GCases (loc,sty,rtno',rl',branches')
| GLetTuple (loc,nal,(na,po),b,c) ->
let po' = Option.smartmap (subst_glob_constr subst) po
and b' = subst_glob_constr subst b
and c' = subst_glob_constr subst c in
if po' == po && b' == b && c' == c then raw else
GLetTuple (loc,nal,(na,po'),b',c')
| GIf (loc,c,(na,po),b1,b2) ->
let po' = Option.smartmap (subst_glob_constr subst) po
and b1' = subst_glob_constr subst b1
and b2' = subst_glob_constr subst b2
and c' = subst_glob_constr subst c in
if c' == c & po' == po && b1' == b1 && b2' == b2 then raw else
GIf (loc,c',(na,po'),b1',b2')
| GRec (loc,fix,ida,bl,ra1,ra2) ->
let ra1' = array_smartmap (subst_glob_constr subst) ra1
and ra2' = array_smartmap (subst_glob_constr subst) ra2 in
let bl' = array_smartmap
(list_smartmap (fun (na,k,obd,ty as dcl) ->
let ty' = subst_glob_constr subst ty in
let obd' = Option.smartmap (subst_glob_constr subst) obd in
if ty'==ty & obd'==obd then dcl else (na,k,obd',ty')))
bl in
if ra1' == ra1 && ra2' == ra2 && bl'==bl then raw else
GRec (loc,fix,ida,bl',ra1',ra2')
| GSort _ -> raw
| GHole (loc,ImplicitArg (ref,i,b)) ->
let ref',_ = subst_global subst ref in
if ref' == ref then raw else
GHole (loc,InternalHole)
| GHole (loc, (BinderType _ | QuestionMark _ | CasesType | InternalHole |
TomatchTypeParameter _ | GoalEvar | ImpossibleCase | MatchingVar _)) ->
raw
| GCast (loc,r1,k) ->
(match k with
CastConv (k,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GCast (loc,r1', CastConv (k,r2'))
| CastCoerce ->
let r1' = subst_glob_constr subst r1 in
if r1' == r1 then raw else GCast (loc,r1',k))
| GNativeInt _ -> raw
| GNativeArr(loc,t,p) ->
let t' = subst_glob_constr subst t
and p' = array_smartmap (subst_glob_constr subst) p in
if t' == t && p' == p then raw else GNativeArr(loc,t',p')
Utilities to transform kernel cases to simple pattern - matching problem
let simple_cases_matrix_of_branches ind brs =
List.map (fun (i,n,b) ->
let nal,c = it_destRLambda_or_LetIn_names n b in
let mkPatVar na = PatVar (dummy_loc,na) in
let p = PatCstr (dummy_loc,(ind,i+1),List.map mkPatVar nal,Anonymous) in
let ids = map_succeed Nameops.out_name nal in
(dummy_loc,ids,[p],c))
brs
let return_type_of_predicate ind nrealargs_ctxt pred =
let nal,p = it_destRLambda_or_LetIn_names (nrealargs_ctxt+1) pred in
(List.hd nal, Some (dummy_loc, ind, List.tl nal)), Some p
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/pretyping/detyping.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
**************************************************************************
Tools for printing of Cases
Parameterization of the translation from constr to ast
Tables for Cases printing under a "if" form, a "let" form,
Auxiliary function for MutCase printing
[computable] tries to tell if the predicate typing the result is inferable
********************************************************************
Fragile algorithm to reverse pattern-matching compilation
********************************************************************
clauses
Not eta-expanded or not reduced
eta-expansion
Not efficient but unusual and no function to get free glob_vars
********************************************************************
Main detyping function
Only if built with the f/n notation or w/o let-expansion in types
If it is an open proof: we cheat and eta-expand
If built with the f/n notation: we renounce to share names
eta-expansion : n'arrivera plus lorsque tous les
termes seront construits à partir de la syntaxe Cases
********************************************************************
Module substitution: relies on detyping | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Errors
open Util
open Univ
open Names
open Term
open Declarations
open Inductive
open Inductiveops
open Environ
open Sign
open Glob_term
open Nameops
open Termops
open Namegen
open Libnames
open Nametab
open Evd
open Mod_subst
let dl = dummy_loc
let encode_inductive r =
let indsp = global_inductive r in
let constr_lengths = mis_constr_nargs indsp in
(indsp,constr_lengths)
let has_two_constructors lc =
& lc.(0 ) = 0 & lc.(1 ) = 0
let isomorphic_to_tuple lc = (Array.length lc = 1)
let encode_bool r =
let (x,lc) = encode_inductive r in
if not (has_two_constructors lc) then
user_err_loc (loc_of_reference r,"encode_if",
str "This type has not exactly two constructors.");
x
let encode_tuple r =
let (x,lc) = encode_inductive r in
if not (isomorphic_to_tuple lc) then
user_err_loc (loc_of_reference r,"encode_tuple",
str "This type cannot be seen as a tuple type.");
x
module PrintingInductiveMake =
functor (Test : sig
val encode : reference -> inductive
val member_message : std_ppcmds -> bool -> std_ppcmds
val field : string
val title : string
end) ->
struct
type t = inductive
let encode = Test.encode
let subst subst (kn, ints as obj) =
let kn' = subst_ind subst kn in
if kn' == kn then obj else
kn', ints
let printer ind = pr_global_env Idset.empty (IndRef ind)
let key = ["Printing";Test.field]
let title = Test.title
let member_message x = Test.member_message (printer x)
let synchronous = true
end
module PrintingCasesIf =
PrintingInductiveMake (struct
let encode = encode_bool
let field = "If"
let title = "Types leading to pretty-printing of Cases using a `if' form: "
let member_message s b =
str "Cases on elements of " ++ s ++
str
(if b then " are printed using a `if' form"
else " are not printed using a `if' form")
end)
module PrintingCasesLet =
PrintingInductiveMake (struct
let encode = encode_tuple
let field = "Let"
let title =
"Types leading to a pretty-printing of Cases using a `let' form:"
let member_message s b =
str "Cases on elements of " ++ s ++
str
(if b then " are printed using a `let' form"
else " are not printed using a `let' form")
end)
module PrintingIf = Goptions.MakeRefTable(PrintingCasesIf)
module PrintingLet = Goptions.MakeRefTable(PrintingCasesLet)
Flags.for printing or not wildcard and synthetisable types
open Goptions
let wildcard_value = ref true
let force_wildcard () = !wildcard_value
let _ = declare_bool_option
{ optsync = true;
optdepr = false;
optname = "forced wildcard";
optkey = ["Printing";"Wildcard"];
optread = force_wildcard;
optwrite = (:=) wildcard_value }
let synth_type_value = ref true
let synthetize_type () = !synth_type_value
let _ = declare_bool_option
{ optsync = true;
optdepr = false;
optname = "pattern matching return type synthesizability";
optkey = ["Printing";"Synth"];
optread = synthetize_type;
optwrite = (:=) synth_type_value }
let reverse_matching_value = ref true
let reverse_matching () = !reverse_matching_value
let _ = declare_bool_option
{ optsync = true;
optdepr = false;
optname = "pattern-matching reversibility";
optkey = ["Printing";"Matching"];
optread = reverse_matching;
optwrite = (:=) reverse_matching_value }
let computable p k =
We first remove as many lambda as the arity , then we look
if it remains a lambda for a dependent elimination . This function
works for normal eta - expanded term . For non eta - expanded or
non - normal terms , it may affirm the pred is synthetisable
because of an undetected ultimate dependent variable in the second
clause , or else , it may affirms the pred non synthetisable
because of a non normal term in the fourth clause .
A solution could be to store , in the MutCase , the eta - expanded
normal form of pred to decide if it depends on its variables
certaine , on
ne déclare pas le prédicat synthétisable ( même si la
variable pas effectivement ) parce que
sinon on perd la réciprocité de la synthèse ( qui , lui ,
engendrera )
if it remains a lambda for a dependent elimination. This function
works for normal eta-expanded term. For non eta-expanded or
non-normal terms, it may affirm the pred is synthetisable
because of an undetected ultimate dependent variable in the second
clause, or else, it may affirms the pred non synthetisable
because of a non normal term in the fourth clause.
A solution could be to store, in the MutCase, the eta-expanded
normal form of pred to decide if it depends on its variables
Lorsque le prédicat est dépendant de manière certaine, on
ne déclare pas le prédicat synthétisable (même si la
variable dépendante ne l'est pas effectivement) parce que
sinon on perd la réciprocité de la synthèse (qui, lui,
engendrera un prédicat non dépendant) *)
let sign,ccl = decompose_lam_assum p in
(rel_context_length sign = k+1)
&&
noccur_between 1 (k+1) ccl
let lookup_name_as_displayed env t s =
let rec lookup avoid n c = match kind_of_term c with
| Prod (name,_,c') ->
(match compute_displayed_name_in RenamingForGoal avoid name c' with
| (Name id,avoid') -> if id=s then Some n else lookup avoid' (n+1) c'
| (Anonymous,avoid') -> lookup avoid' (n+1) (pop c'))
| LetIn (name,_,_,c') ->
(match compute_displayed_name_in RenamingForGoal avoid name c' with
| (Name id,avoid') -> if id=s then Some n else lookup avoid' (n+1) c'
| (Anonymous,avoid') -> lookup avoid' (n+1) (pop c'))
| Cast (c,_,_) -> lookup avoid n c
| _ -> None
in lookup (ids_of_named_context (named_context env)) 1 t
let lookup_index_as_renamed env t n =
let rec lookup n d c = match kind_of_term c with
| Prod (name,_,c') ->
(match compute_displayed_name_in RenamingForGoal [] name c' with
(Name _,_) -> lookup n (d+1) c'
| (Anonymous,_) ->
if n=0 then
Some (d-1)
else if n=1 then
Some d
else
lookup (n-1) (d+1) c')
| LetIn (name,_,_,c') ->
(match compute_displayed_name_in RenamingForGoal [] name c' with
| (Name _,_) -> lookup n (d+1) c'
| (Anonymous,_) ->
if n=0 then
Some (d-1)
else if n=1 then
Some d
else
lookup (n-1) (d+1) c'
)
| Cast (c,_,_) -> lookup n d c
| _ -> if n=0 then Some (d-1) else None
in lookup n 1 t
let update_name na ((_,e),c) =
match na with
| Name _ when force_wildcard () & noccurn (list_index na e) c ->
Anonymous
| _ ->
na
let rec decomp_branch n nal b (avoid,env as e) c =
let flag = if b then RenamingForGoal else RenamingForCasesPattern in
if n=0 then (List.rev nal,(e,c))
else
let na,c,f =
match kind_of_term (strip_outer_cast c) with
| Lambda (na,_,c) -> na,c,compute_displayed_let_name_in
| LetIn (na,_,_,c) -> na,c,compute_displayed_name_in
| _ ->
Name (id_of_string "x"),(applist (lift 1 c, [mkRel 1])),
compute_displayed_name_in in
let na',avoid' = f flag avoid na c in
decomp_branch (n-1) (na'::nal) b (avoid',add_name na' env) c
let rec build_tree na isgoal e ci cl =
let mkpat n rhs pl = PatCstr(dl,(ci.ci_ind,n+1),pl,update_name na rhs) in
let cnl = ci.ci_cstr_ndecls in
List.flatten
(list_tabulate (fun i -> contract_branch isgoal e (cnl.(i),mkpat i,cl.(i)))
(Array.length cl))
and align_tree nal isgoal (e,c as rhs) = match nal with
| [] -> [[],rhs]
| na::nal ->
match kind_of_term c with
| Case (ci,p,c,cl) when c = mkRel (list_index na (snd e))
do n't contract if p dependent
computable p (ci.ci_pp_info.ind_nargs) ->
let clauses = build_tree na isgoal e ci cl in
List.flatten
(List.map (fun (pat,rhs) ->
let lines = align_tree nal isgoal rhs in
List.map (fun (hd,rest) -> pat::hd,rest) lines)
clauses)
| _ ->
let pat = PatVar(dl,update_name na rhs) in
let mat = align_tree nal isgoal rhs in
List.map (fun (hd,rest) -> pat::hd,rest) mat
and contract_branch isgoal e (cn,mkpat,b) =
let nal,rhs = decomp_branch cn [] isgoal e b in
let mat = align_tree nal isgoal rhs in
List.map (fun (hd,rhs) -> (mkpat rhs hd,rhs)) mat
Transform internal representation of pattern - matching into list of
let is_nondep_branch c n =
try
let sign,ccl = decompose_lam_n_assum n c in
noccur_between 1 (rel_context_length sign) ccl
false
let extract_nondep_branches test c b n =
let rec strip n r = if n=0 then r else
match r with
| GLambda (_,_,_,_,t) -> strip (n-1) t
| GLetIn (_,_,_,t) -> strip (n-1) t
| _ -> assert false in
if test c n then Some (strip n b) else None
let it_destRLambda_or_LetIn_names n c =
let rec aux n nal c =
if n=0 then (List.rev nal,c) else match c with
| GLambda (_,na,_,_,c) -> aux (n-1) (na::nal) c
| GLetIn (_,na,_,c) -> aux (n-1) (na::nal) c
| _ ->
let rec next l =
let x = next_ident_away (id_of_string "x") l in
if occur_glob_constr x c then next ( x::l ) else x in
x
in
let x = next (free_glob_vars c) in
let a = GVar (dl,x) in
aux (n-1) (Name x :: nal)
(match c with
| GApp (loc,p,l) -> GApp (loc,c,l@[a])
| _ -> (GApp (dl,c,[a])))
in aux n [] c
let detype_case computable detype detype_eqns testdep avoid data p c bl =
let (indsp,st,consnargsl,k) = data in
let synth_type = synthetize_type () in
let tomatch = detype c in
let alias, aliastyp, pred=
if (not !Flags.raw_print) & synth_type & computable & Array.length bl<>0
then
Anonymous, None, None
else
match Option.map detype p with
| None -> Anonymous, None, None
| Some p ->
let nl,typ = it_destRLambda_or_LetIn_names k p in
let n,typ = match typ with
| GLambda (_,x,_,t,c) -> x, c
| _ -> Anonymous, typ in
let aliastyp =
if List.for_all ((=) Anonymous) nl then None
else Some (dl,indsp,nl) in
n, aliastyp, Some typ
in
let constructs = Array.init (Array.length bl) (fun i -> (indsp,i+1)) in
let tag =
try
if !Flags.raw_print then
RegularStyle
else if st = LetPatternStyle then
st
else if PrintingLet.active indsp then
LetStyle
else if PrintingIf.active indsp then
IfStyle
else
st
with Not_found -> st
in
match tag with
| LetStyle when aliastyp = None ->
let bl' = Array.map detype bl in
let (nal,d) = it_destRLambda_or_LetIn_names consnargsl.(0) bl'.(0) in
GLetTuple (dl,nal,(alias,pred),tomatch,d)
| IfStyle when aliastyp = None ->
let bl' = Array.map detype bl in
let nondepbrs =
array_map3 (extract_nondep_branches testdep) bl bl' consnargsl in
if array_for_all ((<>) None) nondepbrs then
GIf (dl,tomatch,(alias,pred),
Option.get nondepbrs.(0),Option.get nondepbrs.(1))
else
let eqnl = detype_eqns constructs consnargsl bl in
GCases (dl,tag,pred,[tomatch,(alias,aliastyp)],eqnl)
| _ ->
let eqnl = detype_eqns constructs consnargsl bl in
GCases (dl,tag,pred,[tomatch,(alias,aliastyp)],eqnl)
let detype_sort = function
| Prop c -> GProp c
| Type u -> GType (Some u)
type binder_kind = BProd | BLambda | BLetIn
let detype_anonymous = ref (fun loc n -> anomaly "detype: index to an anonymous variable")
let set_detype_anonymous f = detype_anonymous := f
let rec detype (isgoal:bool) avoid env t =
match kind_of_term (collapse_appl t) with
| Rel n ->
(try match lookup_name_of_rel n env with
| Name id -> GVar (dl, id)
| Anonymous -> !detype_anonymous dl n
with Not_found ->
let s = "_UNBOUND_REL_"^(string_of_int n)
in GVar (dl, id_of_string s))
| Meta n ->
Meta in constr are not user - parsable and are mapped to Evar
GEvar (dl, n, None)
| Var id ->
(try
let _ = Global.lookup_named id in GRef (dl, VarRef id)
with _ ->
GVar (dl, id))
| Sort s -> GSort (dl,detype_sort s)
| Cast (c1,k,c2) ->
GCast(dl,detype isgoal avoid env c1, CastConv (k, detype isgoal avoid env c2))
| Prod (na,ty,c) -> detype_binder isgoal BProd avoid env na ty c
| Lambda (na,ty,c) -> detype_binder isgoal BLambda avoid env na ty c
| LetIn (na,b,_,c) -> detype_binder isgoal BLetIn avoid env na b c
| App (f,args) ->
GApp (dl,detype isgoal avoid env f,
array_map_to_list (detype isgoal avoid env) args)
| Const sp -> GRef (dl, ConstRef sp)
| Evar (ev,cl) ->
GEvar (dl, ev,
Some (List.map (detype isgoal avoid env) (Array.to_list cl)))
| Ind ind_sp ->
GRef (dl, IndRef ind_sp)
| Construct cstr_sp ->
GRef (dl, ConstructRef cstr_sp)
| Case (ci,p,c,bl) ->
let comp = computable p (ci.ci_pp_info.ind_nargs) in
detype_case comp (detype isgoal avoid env)
(detype_eqns isgoal avoid env ci comp)
is_nondep_branch avoid
(ci.ci_ind,ci.ci_pp_info.style,
ci.ci_cstr_ndecls,ci.ci_pp_info.ind_nargs)
(Some p) c bl
| Fix (nvn,recdef) -> detype_fix isgoal avoid env nvn recdef
| CoFix (n,recdef) -> detype_cofix isgoal avoid env n recdef
| NativeInt i -> GNativeInt (dl,i)
| NativeArr(t,p) -> GNativeArr(dl,detype isgoal avoid env t, Array.map (detype isgoal avoid env) p)
and detype_fix isgoal avoid env (vn,_ as nvn) (names,tys,bodies) =
let def_avoid, def_env, lfi =
Array.fold_left
(fun (avoid, env, l) na ->
let id = next_name_away na avoid in
(id::avoid, add_name (Name id) env, id::l))
(avoid, env, []) names in
let n = Array.length tys in
let v = array_map3
(fun c t i -> share_names isgoal (i+1) [] def_avoid def_env c (lift n t))
bodies tys vn in
GRec(dl,GFix (Array.map (fun i -> Some i, GStructRec) (fst nvn), snd nvn),Array.of_list (List.rev lfi),
Array.map (fun (bl,_,_) -> bl) v,
Array.map (fun (_,_,ty) -> ty) v,
Array.map (fun (_,bd,_) -> bd) v)
and detype_cofix isgoal avoid env n (names,tys,bodies) =
let def_avoid, def_env, lfi =
Array.fold_left
(fun (avoid, env, l) na ->
let id = next_name_away na avoid in
(id::avoid, add_name (Name id) env, id::l))
(avoid, env, []) names in
let ntys = Array.length tys in
let v = array_map2
(fun c t -> share_names isgoal 0 [] def_avoid def_env c (lift ntys t))
bodies tys in
GRec(dl,GCoFix n,Array.of_list (List.rev lfi),
Array.map (fun (bl,_,_) -> bl) v,
Array.map (fun (_,_,ty) -> ty) v,
Array.map (fun (_,bd,_) -> bd) v)
and share_names isgoal n l avoid env c t =
match kind_of_term c, kind_of_term t with
factorize even when not necessary to have better presentation
| Lambda (na,t,c), Prod (na',t',c') ->
let na = match (na,na') with
Name _, _ -> na
| _, Name _ -> na'
| _ -> na in
let t = detype isgoal avoid env t in
let id = next_name_away na avoid in
let avoid = id::avoid and env = add_name (Name id) env in
share_names isgoal (n-1) ((Name id,Explicit,None,t)::l) avoid env c c'
May occur for fix built interactively
| LetIn (na,b,t',c), _ when n > 0 ->
let t' = detype isgoal avoid env t' in
let b = detype isgoal avoid env b in
let id = next_name_away na avoid in
let avoid = id::avoid and env = add_name (Name id) env in
share_names isgoal n ((Name id,Explicit,Some b,t')::l) avoid env c (lift 1 t)
| _, LetIn (_,b,_,t) when n > 0 ->
share_names isgoal n l avoid env c (subst1 b t)
| _, Prod (na',t',c') when n > 0 ->
let t' = detype isgoal avoid env t' in
let id = next_name_away na' avoid in
let avoid = id::avoid and env = add_name (Name id) env in
let appc = mkApp (lift 1 c,[|mkRel 1|]) in
share_names isgoal (n-1) ((Name id,Explicit,None,t')::l) avoid env appc c'
| _ ->
if n>0 then warning "Detyping.detype: cannot factorize fix enough";
let c = detype isgoal avoid env c in
let t = detype isgoal avoid env t in
(List.rev l,c,t)
and detype_eqns isgoal avoid env ci computable constructs consnargsl bl =
try
if !Flags.raw_print or not (reverse_matching ()) then raise Exit;
let mat = build_tree Anonymous isgoal (avoid,env) ci bl in
List.map (fun (pat,((avoid,env),c)) -> (dl,[],[pat],detype isgoal avoid env c))
mat
with _ ->
Array.to_list
(array_map3 (detype_eqn isgoal avoid env) constructs consnargsl bl)
and detype_eqn isgoal avoid env constr construct_nargs branch =
let make_pat x avoid env b ids =
if force_wildcard () & noccurn 1 b then
PatVar (dl,Anonymous),avoid,(add_name Anonymous env),ids
else
let id = next_name_away_in_cases_pattern x avoid in
PatVar (dl,Name id),id::avoid,(add_name (Name id) env),id::ids
in
let rec buildrec ids patlist avoid env n b =
if n=0 then
(dl, ids,
[PatCstr(dl, constr, List.rev patlist,Anonymous)],
detype isgoal avoid env b)
else
match kind_of_term b with
| Lambda (x,_,b) ->
let pat,new_avoid,new_env,new_ids = make_pat x avoid env b ids in
buildrec new_ids (pat::patlist) new_avoid new_env (n-1) b
| LetIn (x,_,_,b) ->
let pat,new_avoid,new_env,new_ids = make_pat x avoid env b ids in
buildrec new_ids (pat::patlist) new_avoid new_env (n-1) b
Oui , il y a parfois des cast
buildrec ids patlist avoid env n c
nommage de la nouvelle variable
let new_b = applist (lift 1 b, [mkRel 1]) in
let pat,new_avoid,new_env,new_ids =
make_pat Anonymous avoid env new_b ids in
buildrec new_ids (pat::patlist) new_avoid new_env (n-1) new_b
in
buildrec [] [] avoid env construct_nargs branch
and detype_binder isgoal bk avoid env na ty c =
let flag = if isgoal then RenamingForGoal else RenamingElsewhereFor (env,c) in
let na',avoid' =
if bk = BLetIn then compute_displayed_let_name_in flag avoid na c
else compute_displayed_name_in flag avoid na c in
let r = detype isgoal avoid' (add_name na' env) c in
match bk with
| BProd -> GProd (dl, na',Explicit,detype false avoid env ty, r)
| BLambda -> GLambda (dl, na',Explicit,detype false avoid env ty, r)
| BLetIn -> GLetIn (dl, na',detype false avoid env ty, r)
let rec detype_rel_context where avoid env sign =
let where = Option.map (fun c -> it_mkLambda_or_LetIn c sign) where in
let rec aux avoid env = function
| [] -> []
| (na,b,t)::rest ->
let na',avoid' =
match where with
| None -> na,avoid
| Some c ->
if b<>None then
compute_displayed_let_name_in
(RenamingElsewhereFor (env,c)) avoid na c
else
compute_displayed_name_in
(RenamingElsewhereFor (env,c)) avoid na c in
let b = Option.map (detype false avoid env) b in
let t = detype false avoid env t in
(na',Explicit,b,t) :: aux avoid' (add_name na' env) rest
in aux avoid env (List.rev sign)
let rec subst_cases_pattern subst pat =
match pat with
| PatVar _ -> pat
| PatCstr (loc,((kn,i),j),cpl,n) ->
let kn' = subst_ind subst kn
and cpl' = list_smartmap (subst_cases_pattern subst) cpl in
if kn' == kn && cpl' == cpl then pat else
PatCstr (loc,((kn',i),j),cpl',n)
let rec subst_glob_constr subst raw =
match raw with
| GRef (loc,ref) ->
let ref',t = subst_global subst ref in
if ref' == ref then raw else
detype false [] [] t
| GVar _ -> raw
| GEvar _ -> raw
| GPatVar _ -> raw
| GApp (loc,r,rl) ->
let r' = subst_glob_constr subst r
and rl' = list_smartmap (subst_glob_constr subst) rl in
if r' == r && rl' == rl then raw else
GApp(loc,r',rl')
| GLambda (loc,n,bk,r1,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GLambda (loc,n,bk,r1',r2')
| GProd (loc,n,bk,r1,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GProd (loc,n,bk,r1',r2')
| GLetIn (loc,n,r1,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GLetIn (loc,n,r1',r2')
| GCases (loc,sty,rtno,rl,branches) ->
let rtno' = Option.smartmap (subst_glob_constr subst) rtno
and rl' = list_smartmap (fun (a,x as y) ->
let a' = subst_glob_constr subst a in
let (n,topt) = x in
let topt' = Option.smartmap
(fun (loc,(sp,i),y as t) ->
let sp' = subst_ind subst sp in
if sp == sp' then t else (loc,(sp',i),y)) topt in
if a == a' && topt == topt' then y else (a',(n,topt'))) rl
and branches' = list_smartmap
(fun (loc,idl,cpl,r as branch) ->
let cpl' =
list_smartmap (subst_cases_pattern subst) cpl
and r' = subst_glob_constr subst r in
if cpl' == cpl && r' == r then branch else
(loc,idl,cpl',r'))
branches
in
if rtno' == rtno && rl' == rl && branches' == branches then raw else
GCases (loc,sty,rtno',rl',branches')
| GLetTuple (loc,nal,(na,po),b,c) ->
let po' = Option.smartmap (subst_glob_constr subst) po
and b' = subst_glob_constr subst b
and c' = subst_glob_constr subst c in
if po' == po && b' == b && c' == c then raw else
GLetTuple (loc,nal,(na,po'),b',c')
| GIf (loc,c,(na,po),b1,b2) ->
let po' = Option.smartmap (subst_glob_constr subst) po
and b1' = subst_glob_constr subst b1
and b2' = subst_glob_constr subst b2
and c' = subst_glob_constr subst c in
if c' == c & po' == po && b1' == b1 && b2' == b2 then raw else
GIf (loc,c',(na,po'),b1',b2')
| GRec (loc,fix,ida,bl,ra1,ra2) ->
let ra1' = array_smartmap (subst_glob_constr subst) ra1
and ra2' = array_smartmap (subst_glob_constr subst) ra2 in
let bl' = array_smartmap
(list_smartmap (fun (na,k,obd,ty as dcl) ->
let ty' = subst_glob_constr subst ty in
let obd' = Option.smartmap (subst_glob_constr subst) obd in
if ty'==ty & obd'==obd then dcl else (na,k,obd',ty')))
bl in
if ra1' == ra1 && ra2' == ra2 && bl'==bl then raw else
GRec (loc,fix,ida,bl',ra1',ra2')
| GSort _ -> raw
| GHole (loc,ImplicitArg (ref,i,b)) ->
let ref',_ = subst_global subst ref in
if ref' == ref then raw else
GHole (loc,InternalHole)
| GHole (loc, (BinderType _ | QuestionMark _ | CasesType | InternalHole |
TomatchTypeParameter _ | GoalEvar | ImpossibleCase | MatchingVar _)) ->
raw
| GCast (loc,r1,k) ->
(match k with
CastConv (k,r2) ->
let r1' = subst_glob_constr subst r1 and r2' = subst_glob_constr subst r2 in
if r1' == r1 && r2' == r2 then raw else
GCast (loc,r1', CastConv (k,r2'))
| CastCoerce ->
let r1' = subst_glob_constr subst r1 in
if r1' == r1 then raw else GCast (loc,r1',k))
| GNativeInt _ -> raw
| GNativeArr(loc,t,p) ->
let t' = subst_glob_constr subst t
and p' = array_smartmap (subst_glob_constr subst) p in
if t' == t && p' == p then raw else GNativeArr(loc,t',p')
Utilities to transform kernel cases to simple pattern - matching problem
let simple_cases_matrix_of_branches ind brs =
List.map (fun (i,n,b) ->
let nal,c = it_destRLambda_or_LetIn_names n b in
let mkPatVar na = PatVar (dummy_loc,na) in
let p = PatCstr (dummy_loc,(ind,i+1),List.map mkPatVar nal,Anonymous) in
let ids = map_succeed Nameops.out_name nal in
(dummy_loc,ids,[p],c))
brs
let return_type_of_predicate ind nrealargs_ctxt pred =
let nal,p = it_destRLambda_or_LetIn_names (nrealargs_ctxt+1) pred in
(List.hd nal, Some (dummy_loc, ind, List.tl nal)), Some p
|
903995929bc30b607a40eb542e1d663c510852c45b0272cd1667c5dbab6c1e88 | haskell-opengl/OpenGLRaw | TextureObject.hs | # LANGUAGE PatternSynonyms #
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.TextureObject
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.TextureObject (
-- * Extension Support
glGetEXTTextureObject,
gl_EXT_texture_object,
-- * Enums
pattern GL_TEXTURE_1D_BINDING_EXT,
pattern GL_TEXTURE_2D_BINDING_EXT,
pattern GL_TEXTURE_3D_BINDING_EXT,
pattern GL_TEXTURE_PRIORITY_EXT,
pattern GL_TEXTURE_RESIDENT_EXT,
-- * Functions
glAreTexturesResidentEXT,
glBindTextureEXT,
glDeleteTexturesEXT,
glGenTexturesEXT,
glIsTextureEXT,
glPrioritizeTexturesEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/EXT/TextureObject.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.EXT.TextureObject
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Enums
* Functions | # LANGUAGE PatternSynonyms #
Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.EXT.TextureObject (
glGetEXTTextureObject,
gl_EXT_texture_object,
pattern GL_TEXTURE_1D_BINDING_EXT,
pattern GL_TEXTURE_2D_BINDING_EXT,
pattern GL_TEXTURE_3D_BINDING_EXT,
pattern GL_TEXTURE_PRIORITY_EXT,
pattern GL_TEXTURE_RESIDENT_EXT,
glAreTexturesResidentEXT,
glBindTextureEXT,
glDeleteTexturesEXT,
glGenTexturesEXT,
glIsTextureEXT,
glPrioritizeTexturesEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
1a69e01e1ebd8b008b5ad5df57ba62e063ff17e785b4f9596560eed6eb395f87 | facebook/duckling | Corpus.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.DE.Corpus
( corpus
, negativeCorpus
) where
import Prelude
import Data.String
import Duckling.Locale
import Duckling.Ordinal.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale DE Nothing}, testOptions, allExamples)
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext {locale = makeLocale DE Nothing}, testOptions, examples)
where
examples =
[ "1.1"
, "1.1."
]
allExamples :: [Example]
allExamples =
examples (OrdinalData 4)
[ "vierter"
, "4ter"
, "Vierter"
, "4."
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Ordinal/DE/Corpus.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Ordinal.DE.Corpus
( corpus
, negativeCorpus
) where
import Prelude
import Data.String
import Duckling.Locale
import Duckling.Ordinal.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale DE Nothing}, testOptions, allExamples)
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext {locale = makeLocale DE Nothing}, testOptions, examples)
where
examples =
[ "1.1"
, "1.1."
]
allExamples :: [Example]
allExamples =
examples (OrdinalData 4)
[ "vierter"
, "4ter"
, "Vierter"
, "4."
]
|
b66431cffa712e3909b6c93b5c366a6556018516269563265a2790d8f098c073 | marcoheisig/sealable-metaobjects | sealable-generic-function.lisp | (in-package #:sealable-metaobjects)
(defclass sealable-generic-function (sealable-metaobject-mixin generic-function)
((%sealed-domains
:initform '()
:type list
:reader sealed-domains
:writer (setf %sealed-domains)))
(:default-initargs
:method-class (find-class 'potentially-sealable-method))
(:metaclass funcallable-standard-class))
;;; Check that the supplied domain is sane.
(defmethod seal-domain
((sgf sealable-generic-function)
(domain t))
(seal-domain sgf (ensure-domain domain)))
(defmethod seal-domain :around
((sgf sealable-generic-function)
(domain domain))
;; Ensure that we don't seal any domain more than once.
(unless (find domain (sealed-domains sgf) :test #'domain-equal)
(call-next-method sgf domain)))
;;; Ensure that the generic function is sealed, and that the newly sealed
;;; domain is disjoint from other domains.
(defmethod seal-domain :before
((sgf sealable-generic-function)
(domain domain))
;; Ensure that the length of the domain matches the number of mandatory
;; arguments of the generic function.
(unless (= (domain-arity domain)
(length (generic-function-argument-precedence-order sgf)))
(error "~@<Cannot seal the domain ~S with arity ~R ~
of the generic function ~S with arity ~R.~@:>"
(mapcar #'specializer-type (domain-specializers domain))
(domain-arity domain)
(generic-function-name sgf)
(length (generic-function-argument-precedence-order sgf))))
;; Attempt to seal the supplied generic function.
(seal-generic-function sgf)
;; Ensure that the domain does not intersect any existing sealed domains.
(dolist (existing-domain (sealed-domains sgf))
(when (domain-intersectionp domain existing-domain)
(error "~@<Cannot seal the domain ~S of the generic function ~S, ~
because it intersects with the existing domain ~S.~@:>"
(mapcar #'specializer-type domain)
sgf
(mapcar #'specializer-type existing-domain)))))
;;; Add a new sealed domain.
(defmethod seal-domain
((sgf sealable-generic-function)
(domain domain))
(dolist (method (generic-function-methods sgf))
(when (domain-intersectionp (method-domain method) domain)
(unless (domain-subsetp (method-domain method) domain)
(error "~@<The method ~S with specializers ~S is only partially ~
within the sealed domain ~S.~:@>"
method
(mapcar #'specializer-type (method-specializers method))
(mapcar #'specializer-type (domain-specializers domain))))
(seal-method method)))
(setf (%sealed-domains sgf)
(cons domain (sealed-domains sgf))))
Skip the call to add - method if the list of specializers is equal to
;;; that of an existing, sealed method.
(defmethod add-method :around
((sgf sealable-generic-function)
(psm potentially-sealable-method))
(dolist (method (generic-function-methods sgf))
(when (and (method-sealed-p method)
(equal (method-specializers psm)
(method-specializers method)))
(return-from add-method psm)))
(call-next-method))
;;; Ensure that the method to be added is disjoint from all sealed domains.
(defmethod add-method :before
((sgf sealable-generic-function)
(psm potentially-sealable-method))
(dolist (domain (sealed-domains sgf))
(when (domain-intersectionp domain (method-domain psm))
(error "~@<Cannot add the method ~S with specializers ~S to ~
the sealed generic function ~S, because it intersects ~
with the existing sealed domain ~S.~:@>"
psm (method-specializers psm)
sgf (mapcar #'specializer-type (domain-specializers domain))))))
;;; Ensure that the method to be removed is disjoint from all sealed domains.
(defmethod remove-method :before
((sgf sealable-generic-function)
(psm potentially-sealable-method))
(dolist (domain (sealed-domains sgf))
(when (domain-intersectionp domain (method-domain psm))
(error "~@<Cannot remove the method ~S with specializers ~S from ~
the sealed generic function ~S, because it intersects ~
with the existing sealed domain ~S.~:@>"
psm (method-specializers psm)
sgf (mapcar #'specializer-type (domain-specializers domain))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Derived Classes
(defclass sealable-standard-generic-function
(standard-generic-function sealable-generic-function)
()
(:default-initargs
:method-class (find-class 'potentially-sealable-standard-method))
(:metaclass funcallable-standard-class))
| null | https://raw.githubusercontent.com/marcoheisig/sealable-metaobjects/e09ec97252e0844528f61abdc0c7ee256875f8ee/code/sealable-generic-function.lisp | lisp | Check that the supplied domain is sane.
Ensure that we don't seal any domain more than once.
Ensure that the generic function is sealed, and that the newly sealed
domain is disjoint from other domains.
Ensure that the length of the domain matches the number of mandatory
arguments of the generic function.
Attempt to seal the supplied generic function.
Ensure that the domain does not intersect any existing sealed domains.
Add a new sealed domain.
that of an existing, sealed method.
Ensure that the method to be added is disjoint from all sealed domains.
Ensure that the method to be removed is disjoint from all sealed domains.
Derived Classes | (in-package #:sealable-metaobjects)
(defclass sealable-generic-function (sealable-metaobject-mixin generic-function)
((%sealed-domains
:initform '()
:type list
:reader sealed-domains
:writer (setf %sealed-domains)))
(:default-initargs
:method-class (find-class 'potentially-sealable-method))
(:metaclass funcallable-standard-class))
(defmethod seal-domain
((sgf sealable-generic-function)
(domain t))
(seal-domain sgf (ensure-domain domain)))
(defmethod seal-domain :around
((sgf sealable-generic-function)
(domain domain))
(unless (find domain (sealed-domains sgf) :test #'domain-equal)
(call-next-method sgf domain)))
(defmethod seal-domain :before
((sgf sealable-generic-function)
(domain domain))
(unless (= (domain-arity domain)
(length (generic-function-argument-precedence-order sgf)))
(error "~@<Cannot seal the domain ~S with arity ~R ~
of the generic function ~S with arity ~R.~@:>"
(mapcar #'specializer-type (domain-specializers domain))
(domain-arity domain)
(generic-function-name sgf)
(length (generic-function-argument-precedence-order sgf))))
(seal-generic-function sgf)
(dolist (existing-domain (sealed-domains sgf))
(when (domain-intersectionp domain existing-domain)
(error "~@<Cannot seal the domain ~S of the generic function ~S, ~
because it intersects with the existing domain ~S.~@:>"
(mapcar #'specializer-type domain)
sgf
(mapcar #'specializer-type existing-domain)))))
(defmethod seal-domain
((sgf sealable-generic-function)
(domain domain))
(dolist (method (generic-function-methods sgf))
(when (domain-intersectionp (method-domain method) domain)
(unless (domain-subsetp (method-domain method) domain)
(error "~@<The method ~S with specializers ~S is only partially ~
within the sealed domain ~S.~:@>"
method
(mapcar #'specializer-type (method-specializers method))
(mapcar #'specializer-type (domain-specializers domain))))
(seal-method method)))
(setf (%sealed-domains sgf)
(cons domain (sealed-domains sgf))))
Skip the call to add - method if the list of specializers is equal to
(defmethod add-method :around
((sgf sealable-generic-function)
(psm potentially-sealable-method))
(dolist (method (generic-function-methods sgf))
(when (and (method-sealed-p method)
(equal (method-specializers psm)
(method-specializers method)))
(return-from add-method psm)))
(call-next-method))
(defmethod add-method :before
((sgf sealable-generic-function)
(psm potentially-sealable-method))
(dolist (domain (sealed-domains sgf))
(when (domain-intersectionp domain (method-domain psm))
(error "~@<Cannot add the method ~S with specializers ~S to ~
the sealed generic function ~S, because it intersects ~
with the existing sealed domain ~S.~:@>"
psm (method-specializers psm)
sgf (mapcar #'specializer-type (domain-specializers domain))))))
(defmethod remove-method :before
((sgf sealable-generic-function)
(psm potentially-sealable-method))
(dolist (domain (sealed-domains sgf))
(when (domain-intersectionp domain (method-domain psm))
(error "~@<Cannot remove the method ~S with specializers ~S from ~
the sealed generic function ~S, because it intersects ~
with the existing sealed domain ~S.~:@>"
psm (method-specializers psm)
sgf (mapcar #'specializer-type (domain-specializers domain))))))
(defclass sealable-standard-generic-function
(standard-generic-function sealable-generic-function)
()
(:default-initargs
:method-class (find-class 'potentially-sealable-standard-method))
(:metaclass funcallable-standard-class))
|
5f2153418af076193400393e4e0fcb8ed27109cb08fabc93862bca5906c4a500 | calyau/maxima | plotdf.lisp | plotdf.mac - Adds a function plotdf ( ) to Maxima , which draws a Direction
Field for an ordinary 1st order differential equation ,
or for a system of two autonomous 1st order equations .
;;
Copyright ( C ) 2004 , 2008 , 2011 < >
;;
;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
MA 02110 - 1301 , USA .
;;
;; See plotdf.usg (which should come together with this program) for
;; a usage summary
;;
$ I d : plotdf.lisp , v 1.12 2011 - 03 - 09 11:33:46 villate Exp $
(in-package :maxima)
parses a plotdf option into a command - line option for tcl scripts
(defun plotdf-option-to-tcl (value s1 s2)
(let (v vv)
(unless (and ($listp value)
(symbolp (setq name (second value))))
(merror
(intl:gettext
"plotdf-option-to-tcl: Expecting a symbol for the option name, found: \"~M\"") value))
(case name
(($xradius $yradius $xcenter $ycenter $tinitial $tstep)
(setq v (check-option (cdr value) #'realp "a real number" 1))
(setq value (list '(mlist) name v)))
(($width $height $nsteps $versus_t)
(setq v (check-option (cdr value) #'naturalp "a natural number" 1))
(setq value (list '(mlist) name v)))
($trajectory_at
(setq v (check-option (cdr value) #'realp "a real number" 2))
(setq value (cons '(mlist) (cons name v))))
($bbox
(setq v (check-option (cdr value) #'realp "a real number" 4))
(setq value (cons '(mlist) (cons name v))))
(($xfun $parameters $sliders $vectors $fieldlines $curves
$windowtitle $xaxislabel $yaxislabel $psfile)
(setq v (check-option (cdr value) #'stringp "a string" 1))
(setq value (list '(mlist) name v)))
($axes
(if (not (third value))
(setq value '((mlist) $axes 0))
(case (third value)
($x (setq value '((mlist) $axes "x")))
($y (setq value '((mlist) $axes "y")))
(t (setq value '((mlist) $axes "xy"))))))
($box
(if (not (third value))
(setq value '((mlist) $nobox 1))
(setq value '((mlist) $nobox 0))))
($direction
(or
(member (ensure-string (third value)) '("forward" "backward" "both") :test #'equal)
(merror
(intl:gettext
"plotdf-option-to-tcl: direction should be forward, backward or both."))))
(t (cond
((eql name s1)
(setq value (cons '(mlist) (cons '$x (cddr (check-range value))))))
((eql name s2)
(setq value (cons '(mlist) (cons '$y (cddr (check-range value))))))
(t (merror (intl:gettext "plotdf-option-to-tcl: unknown option ~M") name)))))
(setq vv (mapcar #'(lambda (a) (if (symbolp a) (ensure-string a) a)) (cdr value)))
(with-output-to-string (st)
(cond ((or (equal (first vv) "x") (equal (first vv) "y"))
(format st "-~(~a~)center " (first vv))
(format st "{~a} " (/ (+ (third vv) (second vv)) 2))
(format st "-~(~a~)radius " (first vv))
(format st "{~a}" (/ (- (third vv) (second vv)) 2)))
(t
(format st "-~(~a~) " (first vv))
(format st "{~{~a~^ ~}}" (rest vv)))))))
;; applies float(ev(expression, numer)) to an expression, and returns a string
(defun expr_to_str (fun)
(mstring (mfuncall '$float (mfuncall '$ev fun '$numer))))
;; plots the direction field for an ODE dy/dx = f(x,y), or for an autonomous
system of 2 equations dx / dt = f(x , y ) , dy / dt = g(x , y )
;;
(defun $plotdf (ode &rest options)
(let (file cmd (opts " ") (s1 '$x) (s2 '$y) vars)
(unless ($listp ode) (setf ode `((mlist) ,ode)))
;; if the variables are not x and y, their names must be given right
;; after the expression for the ode's
(when
(and (listp (car options)) (= (length (car options)) 3)
(or (symbolp (cadar options)) ($subvarp (cadar options)))
(or (symbolp (caddar options)) ($subvarp (caddar options))))
(setq s1 (cadar options))
(setq s2 (caddar options))
(setq options (cdr options)))
;; parse options and copy them to string opts
(cond (options
(dolist (v options)
(setq opts (concatenate 'string opts " "
(plotdf-option-to-tcl v s1 s2))))))
(unless (search "-xaxislabel " opts)
(setq opts (concatenate 'string opts " -xaxislabel " (ensure-string s1))))
(unless (search "-yaxislabel " opts)
(setq opts (concatenate 'string opts " -yaxislabel " (ensure-string s2))))
;; check that the expressions given contain only the axis variables
(setq vars (cdr (mfuncall '$listofvars ode)))
(unless (search "-parameters " opts)
(dolist (var vars)
(unless (or (eq var s1) (eq var s2))
(merror
(intl:gettext "plotdf: expression(s) given can only depend on ~M and ~M~%Found extra variable ~M") s1 s2 var))))
;; substitute $x by s1 and $y by s2
(defun subxy (expr)
(if (listp expr)
(mapcar #'subxy expr)
(cond ((eq expr s1) '$x) ((eq expr s2) '$y) (t expr))))
(setf ode (mapcar #'subxy ode))
;; parse the differential equation expressions
(case (length ode)
(3 (setq cmd (concatenate 'string " -dxdt \""
(expr_to_str (second ode)) "\" -dydt \""
(expr_to_str (third ode)) "\"")))
(2 (setq cmd (concatenate 'string " -dydx \""
(expr_to_str (second ode)) "\"")))
(t (merror
(intl:gettext "plotdf: first argument must be either an expression or a list with two expressions."))))
(setq file (plot-temp-file (format nil "maxout~d.xmaxima" (getpid))))
(show-open-plot
(with-output-to-string
(st)
(cond
($show_openplot (format st "plotdf ~a ~a~%" cmd opts))
(t (format st "{plotdf ~a ~a} " cmd opts))))
file)
file))
;; plot equipotential curves for a scalar field f(x,y)
(defun $ploteq (fun &rest options)
(let (file cmd mfun (opts " ") (s1 '$x) (s2 '$y))
(setf mfun `((mtimes) -1 ,fun))
;; if the variables are not x and y, their names must be given right
;; after the expression for the ode's
(when
(and (listp (car options)) (= (length (car options)) 3)
(or (symbolp (cadar options)) ($subvarp (cadar options)))
(or (symbolp (caddar options)) ($subvarp (caddar options))))
(setq s1 (cadar options))
(setq s2 (caddar options))
(setq options (cdr options)))
(defun subxy (expr)
(if (listp expr)
(mapcar #'subxy expr)
(cond ((eq expr s1) '$x) ((eq expr s2) '$y) (t expr))))
(setf mfun (mapcar #'subxy mfun))
the next two lines should take into account parameters given in the options
;; (if (delete '$y (delete '$x (rest (mfuncall '$listofvars ode))))
( merror " The equation(s ) can depend only on 2 variable which must be specified ! " ) )
(setq cmd (concatenate 'string " -dxdt \""
(expr_to_str (mfuncall '$diff mfun '$x))
"\" -dydt \""
(expr_to_str (mfuncall '$diff mfun '$y))
"\" "))
;; parse options and copy them to string opts
(cond (options
(dolist (v options)
(setq opts (concatenate 'string opts " "
(plotdf-option-to-tcl v s1 s2))))))
(unless (search "-vectors " opts)
(setq opts (concatenate 'string opts " -vectors {}")))
(unless (search "-fieldlines " opts)
(setq opts (concatenate 'string opts " -fieldlines {}")))
(unless (search "-curves " opts)
(setq opts (concatenate 'string opts " -curves {red}")))
(unless (search "-windowtitle " opts)
(setq opts (concatenate 'string opts " -windowtitle {Ploteq}")))
(unless (search "-xaxislabel " opts)
(setq opts (concatenate 'string opts " -xaxislabel " (ensure-string s1))))
(unless (search "-yaxislabel " opts)
(setq opts (concatenate 'string opts " -yaxislabel " (ensure-string s2))))
(setq file (plot-temp-file (format nil "maxout~d.xmaxima" (getpid))))
(show-open-plot
(with-output-to-string
(st)
(cond ($show_openplot (format st "plotdf ~a ~a~%" cmd opts))
(t (format st "{plotdf ~a ~a}" cmd opts))))
file)
file))
| null | https://raw.githubusercontent.com/calyau/maxima/9352a3f5c22b9b5d0b367fddeb0185c53d7f4d02/share/dynamics/plotdf.lisp | lisp |
This program is free software; you can redistribute it and/or modify
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.
along with this program; if not, write to the Free Software
See plotdf.usg (which should come together with this program) for
a usage summary
applies float(ev(expression, numer)) to an expression, and returns a string
plots the direction field for an ODE dy/dx = f(x,y), or for an autonomous
if the variables are not x and y, their names must be given right
after the expression for the ode's
parse options and copy them to string opts
check that the expressions given contain only the axis variables
substitute $x by s1 and $y by s2
parse the differential equation expressions
plot equipotential curves for a scalar field f(x,y)
if the variables are not x and y, their names must be given right
after the expression for the ode's
(if (delete '$y (delete '$x (rest (mfuncall '$listofvars ode))))
parse options and copy them to string opts | plotdf.mac - Adds a function plotdf ( ) to Maxima , which draws a Direction
Field for an ordinary 1st order differential equation ,
or for a system of two autonomous 1st order equations .
Copyright ( C ) 2004 , 2008 , 2011 < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
MA 02110 - 1301 , USA .
$ I d : plotdf.lisp , v 1.12 2011 - 03 - 09 11:33:46 villate Exp $
(in-package :maxima)
parses a plotdf option into a command - line option for tcl scripts
(defun plotdf-option-to-tcl (value s1 s2)
(let (v vv)
(unless (and ($listp value)
(symbolp (setq name (second value))))
(merror
(intl:gettext
"plotdf-option-to-tcl: Expecting a symbol for the option name, found: \"~M\"") value))
(case name
(($xradius $yradius $xcenter $ycenter $tinitial $tstep)
(setq v (check-option (cdr value) #'realp "a real number" 1))
(setq value (list '(mlist) name v)))
(($width $height $nsteps $versus_t)
(setq v (check-option (cdr value) #'naturalp "a natural number" 1))
(setq value (list '(mlist) name v)))
($trajectory_at
(setq v (check-option (cdr value) #'realp "a real number" 2))
(setq value (cons '(mlist) (cons name v))))
($bbox
(setq v (check-option (cdr value) #'realp "a real number" 4))
(setq value (cons '(mlist) (cons name v))))
(($xfun $parameters $sliders $vectors $fieldlines $curves
$windowtitle $xaxislabel $yaxislabel $psfile)
(setq v (check-option (cdr value) #'stringp "a string" 1))
(setq value (list '(mlist) name v)))
($axes
(if (not (third value))
(setq value '((mlist) $axes 0))
(case (third value)
($x (setq value '((mlist) $axes "x")))
($y (setq value '((mlist) $axes "y")))
(t (setq value '((mlist) $axes "xy"))))))
($box
(if (not (third value))
(setq value '((mlist) $nobox 1))
(setq value '((mlist) $nobox 0))))
($direction
(or
(member (ensure-string (third value)) '("forward" "backward" "both") :test #'equal)
(merror
(intl:gettext
"plotdf-option-to-tcl: direction should be forward, backward or both."))))
(t (cond
((eql name s1)
(setq value (cons '(mlist) (cons '$x (cddr (check-range value))))))
((eql name s2)
(setq value (cons '(mlist) (cons '$y (cddr (check-range value))))))
(t (merror (intl:gettext "plotdf-option-to-tcl: unknown option ~M") name)))))
(setq vv (mapcar #'(lambda (a) (if (symbolp a) (ensure-string a) a)) (cdr value)))
(with-output-to-string (st)
(cond ((or (equal (first vv) "x") (equal (first vv) "y"))
(format st "-~(~a~)center " (first vv))
(format st "{~a} " (/ (+ (third vv) (second vv)) 2))
(format st "-~(~a~)radius " (first vv))
(format st "{~a}" (/ (- (third vv) (second vv)) 2)))
(t
(format st "-~(~a~) " (first vv))
(format st "{~{~a~^ ~}}" (rest vv)))))))
(defun expr_to_str (fun)
(mstring (mfuncall '$float (mfuncall '$ev fun '$numer))))
system of 2 equations dx / dt = f(x , y ) , dy / dt = g(x , y )
(defun $plotdf (ode &rest options)
(let (file cmd (opts " ") (s1 '$x) (s2 '$y) vars)
(unless ($listp ode) (setf ode `((mlist) ,ode)))
(when
(and (listp (car options)) (= (length (car options)) 3)
(or (symbolp (cadar options)) ($subvarp (cadar options)))
(or (symbolp (caddar options)) ($subvarp (caddar options))))
(setq s1 (cadar options))
(setq s2 (caddar options))
(setq options (cdr options)))
(cond (options
(dolist (v options)
(setq opts (concatenate 'string opts " "
(plotdf-option-to-tcl v s1 s2))))))
(unless (search "-xaxislabel " opts)
(setq opts (concatenate 'string opts " -xaxislabel " (ensure-string s1))))
(unless (search "-yaxislabel " opts)
(setq opts (concatenate 'string opts " -yaxislabel " (ensure-string s2))))
(setq vars (cdr (mfuncall '$listofvars ode)))
(unless (search "-parameters " opts)
(dolist (var vars)
(unless (or (eq var s1) (eq var s2))
(merror
(intl:gettext "plotdf: expression(s) given can only depend on ~M and ~M~%Found extra variable ~M") s1 s2 var))))
(defun subxy (expr)
(if (listp expr)
(mapcar #'subxy expr)
(cond ((eq expr s1) '$x) ((eq expr s2) '$y) (t expr))))
(setf ode (mapcar #'subxy ode))
(case (length ode)
(3 (setq cmd (concatenate 'string " -dxdt \""
(expr_to_str (second ode)) "\" -dydt \""
(expr_to_str (third ode)) "\"")))
(2 (setq cmd (concatenate 'string " -dydx \""
(expr_to_str (second ode)) "\"")))
(t (merror
(intl:gettext "plotdf: first argument must be either an expression or a list with two expressions."))))
(setq file (plot-temp-file (format nil "maxout~d.xmaxima" (getpid))))
(show-open-plot
(with-output-to-string
(st)
(cond
($show_openplot (format st "plotdf ~a ~a~%" cmd opts))
(t (format st "{plotdf ~a ~a} " cmd opts))))
file)
file))
(defun $ploteq (fun &rest options)
(let (file cmd mfun (opts " ") (s1 '$x) (s2 '$y))
(setf mfun `((mtimes) -1 ,fun))
(when
(and (listp (car options)) (= (length (car options)) 3)
(or (symbolp (cadar options)) ($subvarp (cadar options)))
(or (symbolp (caddar options)) ($subvarp (caddar options))))
(setq s1 (cadar options))
(setq s2 (caddar options))
(setq options (cdr options)))
(defun subxy (expr)
(if (listp expr)
(mapcar #'subxy expr)
(cond ((eq expr s1) '$x) ((eq expr s2) '$y) (t expr))))
(setf mfun (mapcar #'subxy mfun))
the next two lines should take into account parameters given in the options
( merror " The equation(s ) can depend only on 2 variable which must be specified ! " ) )
(setq cmd (concatenate 'string " -dxdt \""
(expr_to_str (mfuncall '$diff mfun '$x))
"\" -dydt \""
(expr_to_str (mfuncall '$diff mfun '$y))
"\" "))
(cond (options
(dolist (v options)
(setq opts (concatenate 'string opts " "
(plotdf-option-to-tcl v s1 s2))))))
(unless (search "-vectors " opts)
(setq opts (concatenate 'string opts " -vectors {}")))
(unless (search "-fieldlines " opts)
(setq opts (concatenate 'string opts " -fieldlines {}")))
(unless (search "-curves " opts)
(setq opts (concatenate 'string opts " -curves {red}")))
(unless (search "-windowtitle " opts)
(setq opts (concatenate 'string opts " -windowtitle {Ploteq}")))
(unless (search "-xaxislabel " opts)
(setq opts (concatenate 'string opts " -xaxislabel " (ensure-string s1))))
(unless (search "-yaxislabel " opts)
(setq opts (concatenate 'string opts " -yaxislabel " (ensure-string s2))))
(setq file (plot-temp-file (format nil "maxout~d.xmaxima" (getpid))))
(show-open-plot
(with-output-to-string
(st)
(cond ($show_openplot (format st "plotdf ~a ~a~%" cmd opts))
(t (format st "{plotdf ~a ~a}" cmd opts))))
file)
file))
|
8f6f66fa704c0740ea5ba9e974b2346129fa2c12b436ac44971ee17581a1db7a | deadpendency/deadpendency | CheckRunCreateRequest.hs | module Common.Effect.GitHub.WriteChecks.Model.CheckRunCreateRequest
( CheckRunCreateRequest (..),
)
where
import Common.Aeson.Aeson
import Common.Model.Git.GitSha
import Common.Model.GitHub.GHAppInstallationId
import Common.Model.GitHub.GHNodeId
import Data.Aeson
data CheckRunCreateRequest = CheckRunCreateRequest
{ _headSha :: GitSha,
_name :: Text,
_repoNodeId :: GHNodeId,
_appInstallationId :: GHAppInstallationId
}
deriving stock (Eq, Show, Generic)
instance ToJSON CheckRunCreateRequest where
toJSON = genericToJSON cleanJSONOptions
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/common/src/Common/Effect/GitHub/WriteChecks/Model/CheckRunCreateRequest.hs | haskell | module Common.Effect.GitHub.WriteChecks.Model.CheckRunCreateRequest
( CheckRunCreateRequest (..),
)
where
import Common.Aeson.Aeson
import Common.Model.Git.GitSha
import Common.Model.GitHub.GHAppInstallationId
import Common.Model.GitHub.GHNodeId
import Data.Aeson
data CheckRunCreateRequest = CheckRunCreateRequest
{ _headSha :: GitSha,
_name :: Text,
_repoNodeId :: GHNodeId,
_appInstallationId :: GHAppInstallationId
}
deriving stock (Eq, Show, Generic)
instance ToJSON CheckRunCreateRequest where
toJSON = genericToJSON cleanJSONOptions
| |
cc803facd31faaff8875f72943e35566bfb5472c420422e47f005526d676598c | rd--/hsc3 | Array.hs | {- | Array variants of "Sound.Sc3.Common.Buffer".
These functions have the same names as the plain forms and are not re-exported by "Sound.Sc3.Common".
-}
module Sound.Sc3.Common.Buffer.Array where
import qualified Data.Array as A {- array -}
import qualified Sound.Sc3.Common.Buffer as Common.Buffer {- hsc3 -}
-- | 'Common.Buffer.clipAt'.
clipAt :: Int -> A.Array Int a -> a
clipAt ix c =
let (l,r) = A.bounds c
f = (A.!) c
in if ix < l then f l else if ix > r then f r else f ix
| ' C.blendAtBy ' of ' clipAt ' .
> Sound . Sc3.Common . Buffer . Array.blendAt 0 ( ( 0,2 ) [ 2,5,6 ] ) = = 2
> Sound . Sc3.Common . Buffer . Array.blendAt 0.4 ( ( 0,2 ) [ 2,5,6 ] ) = = 3.2
> Sound.Sc3.Common.Buffer.Array.blendAt 0 (A.listArray (0,2) [2,5,6]) == 2
> Sound.Sc3.Common.Buffer.Array.blendAt 0.4 (A.listArray (0,2) [2,5,6]) == 3.2
-}
blendAt :: RealFrac a => a -> A.Array Int a -> a
blendAt = Common.Buffer.blendAtBy clipAt
| ' C.resamp1 ' .
> Sound . Sc3.Common . Buffer . Array.resamp1 12 ( ( 0,3 ) [ 1,2,3,4 ] )
> Sound . Sc3.Common . Buffer . Array.resamp1 3 ( ( 0,3 ) [ 1,2,3,4 ] ) = = ( 0,2 ) [ 1,2.5,4 ]
> Sound.Sc3.Common.Buffer.Array.resamp1 12 (A.listArray (0,3) [1,2,3,4])
> Sound.Sc3.Common.Buffer.Array.resamp1 3 (A.listArray (0,3) [1,2,3,4]) == A.listArray (0,2) [1,2.5,4]
-}
resamp1 :: RealFrac n => Int -> A.Array Int n -> A.Array Int n
resamp1 n c =
let (_,r) = A.bounds c
gen = Common.Buffer.resamp1_gen n (r + 1) clipAt c
rs = map gen [0 .. n - 1]
in A.listArray (0,n - 1) rs
| null | https://raw.githubusercontent.com/rd--/hsc3/65b0ae5422dfd9c6458c5a97dfb416ab80bd7a72/Sound/Sc3/Common/Buffer/Array.hs | haskell | | Array variants of "Sound.Sc3.Common.Buffer".
These functions have the same names as the plain forms and are not re-exported by "Sound.Sc3.Common".
array
hsc3
| 'Common.Buffer.clipAt'. | module Sound.Sc3.Common.Buffer.Array where
clipAt :: Int -> A.Array Int a -> a
clipAt ix c =
let (l,r) = A.bounds c
f = (A.!) c
in if ix < l then f l else if ix > r then f r else f ix
| ' C.blendAtBy ' of ' clipAt ' .
> Sound . Sc3.Common . Buffer . Array.blendAt 0 ( ( 0,2 ) [ 2,5,6 ] ) = = 2
> Sound . Sc3.Common . Buffer . Array.blendAt 0.4 ( ( 0,2 ) [ 2,5,6 ] ) = = 3.2
> Sound.Sc3.Common.Buffer.Array.blendAt 0 (A.listArray (0,2) [2,5,6]) == 2
> Sound.Sc3.Common.Buffer.Array.blendAt 0.4 (A.listArray (0,2) [2,5,6]) == 3.2
-}
blendAt :: RealFrac a => a -> A.Array Int a -> a
blendAt = Common.Buffer.blendAtBy clipAt
| ' C.resamp1 ' .
> Sound . Sc3.Common . Buffer . Array.resamp1 12 ( ( 0,3 ) [ 1,2,3,4 ] )
> Sound . Sc3.Common . Buffer . Array.resamp1 3 ( ( 0,3 ) [ 1,2,3,4 ] ) = = ( 0,2 ) [ 1,2.5,4 ]
> Sound.Sc3.Common.Buffer.Array.resamp1 12 (A.listArray (0,3) [1,2,3,4])
> Sound.Sc3.Common.Buffer.Array.resamp1 3 (A.listArray (0,3) [1,2,3,4]) == A.listArray (0,2) [1,2.5,4]
-}
resamp1 :: RealFrac n => Int -> A.Array Int n -> A.Array Int n
resamp1 n c =
let (_,r) = A.bounds c
gen = Common.Buffer.resamp1_gen n (r + 1) clipAt c
rs = map gen [0 .. n - 1]
in A.listArray (0,n - 1) rs
|
8d1182d88cab96dae5e2fa6b40b6926f7a602d05bb26164bb11bb2c0062c7983 | factisresearch/mq-demo | SafeCopy.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE CPP #
module Mgw.Util.SafeCopy
( module Data.SafeCopy
, safeEncode, safeEncode', safeDecode, safeDecode', safeDecodeLazy
, vectorToOSMap, osMapToVector, seqToVector, vectorToSeq
, getMap, putMap
, getOSMap, putOSMap
, getSeq, putSeq
, deriveSafeCopyCtx
)
where
#include "src/macros.h"
----------------------------------------
-- LOCAL
----------------------------------------
import Mgw.Util.Seq as Seq
import Mgw.Util.OSMap (OSMap)
import Mgw.Util.Misc (eitherToFail)
import qualified Mgw.Util.OSMap as OSMap
----------------------------------------
-- SITE-PACKAGES
----------------------------------------
import Data.SafeCopy
import Data.Serialize
import qualified Data.Vector as V
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Fusion.Stream as VS
----------------------------------------
-- STDLIB
----------------------------------------
import Control.Monad (liftM)
import Data.Foldable as F
import Data.Hashable
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map.Strict as Map
import qualified Data.HashMap.Strict as HashMap
import qualified Data.HashSet as HashSet
import qualified Data.MultiSet as MultiSet
import qualified Language.Haskell.TH as TH
safeEncode :: SafeCopy a => a -> BS.ByteString
safeEncode = runPut . safePut
safeEncode' :: SafeCopy a => a -> BSL.ByteString
safeEncode' = runPutLazy . safePut
safeDecode :: (Monad m, SafeCopy a) => BS.ByteString -> m a
safeDecode bs = eitherToFail (runGet safeGet bs)
safeDecodeLazy :: (Monad m, SafeCopy a) => BSL.ByteString -> m a
safeDecodeLazy bs = eitherToFail (runGetLazy safeGet bs)
safeDecode' :: (Monad m, SafeCopy a) => BSL.ByteString -> m a
safeDecode' bsl = eitherToFail (runGetLazy safeGet bsl)
newtype OldOSMap k v = OldOSMap { unOldOSMap :: OSMap k v }
instance (Ord k, SafeCopy k, SafeCopy v) => SafeCopy (OldOSMap k v) where
putCopy _ = safeError "Should never serialize the old OSMap way."
getCopy = contain $ liftM (OldOSMap . OSMap.fromDataMap) safeGet
instance (Ord k, SafeCopy k, SafeCopy v) => SafeCopy (OSMap k v) where
version = 2
kind = extension
putCopy = contain . putOSMap
getCopy = contain getOSMap
instance (Ord k, SafeCopy k, SafeCopy v) => Migrate (OSMap k v) where
type MigrateFrom (OSMap k v) = OldOSMap k v
migrate = unOldOSMap
osMapToVector :: OSMap k v -> V.Vector (k, v)
osMapToVector = VG.unstream . OSMap.foldrWithKey (\k v -> VS.cons (k,v)) VS.empty
vectorToOSMap :: Ord k => V.Vector (k, v) -> OSMap k v
vectorToOSMap = OSMap.fromDistinctAscList . V.toList
vectorToSeq :: V.Vector a -> Seq a
vectorToSeq = V.foldl' (|>) Seq.empty
seqToVector :: Seq a -> V.Vector a
seqToVector = VG.unstream . F.foldr VS.cons VS.empty
putSeq :: SafeCopy a => Putter (Seq a)
putSeq xs =
do safePut (Seq.length xs)
putElem <- getSafePut
F.forM_ xs putElem
getSeq :: SafeCopy a => Get (Seq a)
getSeq =
do len <- safeGet
getElem <- getSafeGet
let loop !i !acc
| i == 0 = return acc
| otherwise =
do next <- getElem
loop (i - 1) (acc |> next)
loop (len :: Int) Seq.empty
putMap :: (SafeCopy a, SafeCopy b) => Putter (Map.Map a b)
putMap = putMapGen Map.size Map.foldrWithKey
getMap :: (Ord a, SafeCopy a, SafeCopy b) => Get (Map.Map a b)
getMap = getMapGen Map.insert Map.empty
putHashMap :: (SafeCopy a, SafeCopy b) => Putter (HashMap.HashMap a b)
putHashMap = putMapGen HashMap.size HashMap.foldrWithKey
getHashMap :: (Hashable a, Eq a, SafeCopy a, SafeCopy b) => Get (HashMap.HashMap a b)
getHashMap = getMapGen HashMap.insert HashMap.empty
instance (SafeCopy k, SafeCopy a, Hashable k, Eq k) => SafeCopy (HashMap.HashMap k a) where
getCopy = contain getHashMap
putCopy = contain . putHashMap
putMapGen :: (SafeCopy k, SafeCopy a)
=> (t k a -> Int)
-> (forall b . ((k -> a -> b -> b) -> b -> t k a -> b))
-> Putter (t k a)
putMapGen size foldrWithKey xs =
do safePut (size xs)
putKey <- getSafePut
putValue <- getSafePut
foldrWithKey (\k v rest -> putKey k >> putValue v >> rest) (return ()) xs
getMapGen :: (SafeCopy k, SafeCopy a)
=> (k -> a -> t k a -> t k a)
-> (t k a)
-> Get (t k a)
getMapGen insert empty =
do len <- safeGet
getKey <- getSafeGet
getValue <- getSafeGet
let loop !i !acc
| i == 0 = return acc
| otherwise =
do key <- getKey
val <- getValue
loop (i - 1) (insert key val acc)
loop (len :: Int) empty
putOSMap :: (SafeCopy a, SafeCopy b) => Putter (OSMap.OSMap a b)
putOSMap xs =
do safePut (OSMap.size xs)
putKey <- getSafePut
putValue <- getSafePut
OSMap.foldrWithKey (\k v rest -> putKey k >> putValue v >> rest) (return ()) xs
getOSMap :: (Ord a, SafeCopy a, SafeCopy b) => Get (OSMap.OSMap a b)
getOSMap =
do len <- safeGet
getKey <- getSafeGet
getValue <- getSafeGet
let loop !i !acc
| i == 0 = return acc
| otherwise =
do key <- getKey
val <- getValue
loop (i - 1) (OSMap.insert key val acc)
loop (len :: Int) OSMap.empty
instance (SafeCopy a, Hashable a, Eq a) => SafeCopy (HashSet.HashSet a) where
getCopy = contain $
do l <- safeGet
return $ HashSet.fromList l
putCopy hs = contain $ safePut (HashSet.toList hs)
instance (SafeCopy a, Ord a) => SafeCopy (MultiSet.MultiSet a) where
getCopy = contain $
do l <- safeGet
return $ MultiSet.fromList l
putCopy hs = contain $ safePut (MultiSet.toList hs)
deriveSafeCopyCtx :: Version a
-> TH.Name
-> TH.Name
-> ([TH.TypeQ] -> [TH.PredQ])
-> (TH.Q [TH.Dec])
deriveSafeCopyCtx version kindName tyName extraPreds =
do decs <- deriveSafeCopy version kindName tyName
case decs of
[TH.InstanceD ctx ty body] ->
do let args = reverse (collectArgs ty)
extras <- sequence (extraPreds (map return args))
let newCtx = ctx ++ extras
-- _ <- fail ("args: " ++ show args ++", ty: " ++ show ty)
return [TH.InstanceD newCtx ty body]
_ -> error ("Unexpected declarations returned by deriveSafeCopy: " ++ show (TH.ppr decs))
where
collectArgs :: TH.Type -> [TH.Type]
collectArgs ty =
let loop ty =
case ty of
(TH.AppT l r) ->
case l of
TH.AppT _ _ -> r : loop l
_ -> [r]
_ -> []
in case ty of
TH.AppT _ r -> loop r
_ -> []
| null | https://raw.githubusercontent.com/factisresearch/mq-demo/0efa1991ca647a86a8c22e516a7a1fb392ab4596/server/src/lib/Mgw/Util/SafeCopy.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE RankNTypes #
--------------------------------------
LOCAL
--------------------------------------
--------------------------------------
SITE-PACKAGES
--------------------------------------
--------------------------------------
STDLIB
--------------------------------------
_ <- fail ("args: " ++ show args ++", ty: " ++ show ty) | # LANGUAGE TypeFamilies #
# LANGUAGE ViewPatterns #
# LANGUAGE CPP #
module Mgw.Util.SafeCopy
( module Data.SafeCopy
, safeEncode, safeEncode', safeDecode, safeDecode', safeDecodeLazy
, vectorToOSMap, osMapToVector, seqToVector, vectorToSeq
, getMap, putMap
, getOSMap, putOSMap
, getSeq, putSeq
, deriveSafeCopyCtx
)
where
#include "src/macros.h"
import Mgw.Util.Seq as Seq
import Mgw.Util.OSMap (OSMap)
import Mgw.Util.Misc (eitherToFail)
import qualified Mgw.Util.OSMap as OSMap
import Data.SafeCopy
import Data.Serialize
import qualified Data.Vector as V
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Fusion.Stream as VS
import Control.Monad (liftM)
import Data.Foldable as F
import Data.Hashable
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map.Strict as Map
import qualified Data.HashMap.Strict as HashMap
import qualified Data.HashSet as HashSet
import qualified Data.MultiSet as MultiSet
import qualified Language.Haskell.TH as TH
safeEncode :: SafeCopy a => a -> BS.ByteString
safeEncode = runPut . safePut
safeEncode' :: SafeCopy a => a -> BSL.ByteString
safeEncode' = runPutLazy . safePut
safeDecode :: (Monad m, SafeCopy a) => BS.ByteString -> m a
safeDecode bs = eitherToFail (runGet safeGet bs)
safeDecodeLazy :: (Monad m, SafeCopy a) => BSL.ByteString -> m a
safeDecodeLazy bs = eitherToFail (runGetLazy safeGet bs)
safeDecode' :: (Monad m, SafeCopy a) => BSL.ByteString -> m a
safeDecode' bsl = eitherToFail (runGetLazy safeGet bsl)
newtype OldOSMap k v = OldOSMap { unOldOSMap :: OSMap k v }
instance (Ord k, SafeCopy k, SafeCopy v) => SafeCopy (OldOSMap k v) where
putCopy _ = safeError "Should never serialize the old OSMap way."
getCopy = contain $ liftM (OldOSMap . OSMap.fromDataMap) safeGet
instance (Ord k, SafeCopy k, SafeCopy v) => SafeCopy (OSMap k v) where
version = 2
kind = extension
putCopy = contain . putOSMap
getCopy = contain getOSMap
instance (Ord k, SafeCopy k, SafeCopy v) => Migrate (OSMap k v) where
type MigrateFrom (OSMap k v) = OldOSMap k v
migrate = unOldOSMap
osMapToVector :: OSMap k v -> V.Vector (k, v)
osMapToVector = VG.unstream . OSMap.foldrWithKey (\k v -> VS.cons (k,v)) VS.empty
vectorToOSMap :: Ord k => V.Vector (k, v) -> OSMap k v
vectorToOSMap = OSMap.fromDistinctAscList . V.toList
vectorToSeq :: V.Vector a -> Seq a
vectorToSeq = V.foldl' (|>) Seq.empty
seqToVector :: Seq a -> V.Vector a
seqToVector = VG.unstream . F.foldr VS.cons VS.empty
putSeq :: SafeCopy a => Putter (Seq a)
putSeq xs =
do safePut (Seq.length xs)
putElem <- getSafePut
F.forM_ xs putElem
getSeq :: SafeCopy a => Get (Seq a)
getSeq =
do len <- safeGet
getElem <- getSafeGet
let loop !i !acc
| i == 0 = return acc
| otherwise =
do next <- getElem
loop (i - 1) (acc |> next)
loop (len :: Int) Seq.empty
putMap :: (SafeCopy a, SafeCopy b) => Putter (Map.Map a b)
putMap = putMapGen Map.size Map.foldrWithKey
getMap :: (Ord a, SafeCopy a, SafeCopy b) => Get (Map.Map a b)
getMap = getMapGen Map.insert Map.empty
putHashMap :: (SafeCopy a, SafeCopy b) => Putter (HashMap.HashMap a b)
putHashMap = putMapGen HashMap.size HashMap.foldrWithKey
getHashMap :: (Hashable a, Eq a, SafeCopy a, SafeCopy b) => Get (HashMap.HashMap a b)
getHashMap = getMapGen HashMap.insert HashMap.empty
instance (SafeCopy k, SafeCopy a, Hashable k, Eq k) => SafeCopy (HashMap.HashMap k a) where
getCopy = contain getHashMap
putCopy = contain . putHashMap
putMapGen :: (SafeCopy k, SafeCopy a)
=> (t k a -> Int)
-> (forall b . ((k -> a -> b -> b) -> b -> t k a -> b))
-> Putter (t k a)
putMapGen size foldrWithKey xs =
do safePut (size xs)
putKey <- getSafePut
putValue <- getSafePut
foldrWithKey (\k v rest -> putKey k >> putValue v >> rest) (return ()) xs
getMapGen :: (SafeCopy k, SafeCopy a)
=> (k -> a -> t k a -> t k a)
-> (t k a)
-> Get (t k a)
getMapGen insert empty =
do len <- safeGet
getKey <- getSafeGet
getValue <- getSafeGet
let loop !i !acc
| i == 0 = return acc
| otherwise =
do key <- getKey
val <- getValue
loop (i - 1) (insert key val acc)
loop (len :: Int) empty
putOSMap :: (SafeCopy a, SafeCopy b) => Putter (OSMap.OSMap a b)
putOSMap xs =
do safePut (OSMap.size xs)
putKey <- getSafePut
putValue <- getSafePut
OSMap.foldrWithKey (\k v rest -> putKey k >> putValue v >> rest) (return ()) xs
getOSMap :: (Ord a, SafeCopy a, SafeCopy b) => Get (OSMap.OSMap a b)
getOSMap =
do len <- safeGet
getKey <- getSafeGet
getValue <- getSafeGet
let loop !i !acc
| i == 0 = return acc
| otherwise =
do key <- getKey
val <- getValue
loop (i - 1) (OSMap.insert key val acc)
loop (len :: Int) OSMap.empty
instance (SafeCopy a, Hashable a, Eq a) => SafeCopy (HashSet.HashSet a) where
getCopy = contain $
do l <- safeGet
return $ HashSet.fromList l
putCopy hs = contain $ safePut (HashSet.toList hs)
instance (SafeCopy a, Ord a) => SafeCopy (MultiSet.MultiSet a) where
getCopy = contain $
do l <- safeGet
return $ MultiSet.fromList l
putCopy hs = contain $ safePut (MultiSet.toList hs)
deriveSafeCopyCtx :: Version a
-> TH.Name
-> TH.Name
-> ([TH.TypeQ] -> [TH.PredQ])
-> (TH.Q [TH.Dec])
deriveSafeCopyCtx version kindName tyName extraPreds =
do decs <- deriveSafeCopy version kindName tyName
case decs of
[TH.InstanceD ctx ty body] ->
do let args = reverse (collectArgs ty)
extras <- sequence (extraPreds (map return args))
let newCtx = ctx ++ extras
return [TH.InstanceD newCtx ty body]
_ -> error ("Unexpected declarations returned by deriveSafeCopy: " ++ show (TH.ppr decs))
where
collectArgs :: TH.Type -> [TH.Type]
collectArgs ty =
let loop ty =
case ty of
(TH.AppT l r) ->
case l of
TH.AppT _ _ -> r : loop l
_ -> [r]
_ -> []
in case ty of
TH.AppT _ r -> loop r
_ -> []
|
93a57de5dd61636a1dd24b5bcff3ae7c3527e2bfd7c9b2a3529b22e8666d5765 | hannesm/duration | duration.ml | type t = int64
let of_us_64 m =
if m < 0L then
invalid_arg "negative" ;
if Int64.compare m 0x4189374BC6A7EDL = 1 then
invalid_arg "out of range" ;
Int64.mul 1_000L m
let of_us m = of_us_64 (Int64.of_int m)
let of_ms_64 m =
if m < 0L then
invalid_arg "negative" ;
if Int64.compare m 0x10C6F7A0B5EDL = 1 then
invalid_arg "out of range" ;
Int64.mul 1_000_000L m
let of_ms m = of_ms_64 (Int64.of_int m)
let of_sec_64 s =
if s < 0L then
invalid_arg "negative" ;
if Int64.compare s 0x44B82FA09L = 1 then
invalid_arg "out of range" ;
Int64.mul 1_000_000_000L s
let of_sec m = of_sec_64 (Int64.of_int m)
let of_min m =
if m < 0 then
invalid_arg "negative" ;
let m = Int64.of_int m in
if Int64.compare m 0x12533FE6L = 1 then
invalid_arg "out of range" ;
Int64.mul 60_000_000_000L m
let hour = 3600_000_000_000L
let of_hour h =
if h < 0 then
invalid_arg "negative" ;
let h = Int64.of_int h in
if Int64.compare h 0x4E2FFFL = 1 then
invalid_arg "out of range" ;
Int64.mul hour h
let day = Int64.mul 24L hour
let of_day d =
if d < 0 then
invalid_arg "negative" ;
let d = Int64.of_int d in
if Int64.compare d 0x341FFL = 1 then
invalid_arg "out of range" ;
Int64.mul day d
let year = Int64.mul 8766L hour
let of_year y =
if y < 0 then
invalid_arg "negative" ;
let y = Int64.of_int y in
if Int64.compare y 0x248L = 1 then
invalid_arg "out of range" ;
Int64.mul year y
let of_f f =
if f < 0. then
invalid_arg "negative" ;
if f > 18446744073.709549 then
invalid_arg "out of range" ;
let s = Int64.of_float f in
let rem = f -. (Int64.to_float s) in
let ns = Int64.of_float (rem *. 1_000_000_000.) in
Int64.(add (mul 1_000_000_000L s) ns)
let to_f t =
let pl =
if t >= 0L then
0.
else
abs_float (2. *. (Int64.to_float 0x8000000000000000L))
in
let ns = Int64.to_float t in
(ns +. pl) /. 1_000_000_000.
let to_int64 t d =
let f c = Int64.div c d in
if t < 0L then
Int64.(add (f (Int64.add t Int64.min_int)) (add (f Int64.max_int) 1L))
else
f t
let to_int t d =
let r = to_int64 t d in
if r > Int64.of_int max_int then
invalid_arg "value too big for this platform" ;
Int64.to_int r
let to_us_64 t = to_int64 t 1_000L
let to_us t = to_int t 1_000L
let to_ms_64 t = to_int64 t 1_000_000L
let to_ms t = to_int t 1_000_000L
let to_sec_64 t = to_int64 t 1_000_000_000L
let to_sec t = to_int t 1_000_000_000L
let to_min t = to_int t 60_000_000_000L
let to_hour t = to_int t hour
let to_day t = to_int t day
let to_year t = to_int t year
let fields t =
let sec = to_sec_64 t in
let left = Int64.sub t (of_sec_64 sec) in
let ms = to_ms_64 left in
let left = Int64.sub left (of_ms_64 ms) in
let us = to_us_64 left in
let ns = Int64.(sub left (of_us_64 us)) in
(sec, ms, us, ns)
let pp ppf t =
let min = to_min t in
if min > 0 then
let y = to_year t in
let left = Int64.rem t year in
let d = to_day left in
let left = Int64.rem left day in
if y > 0 then
Format.fprintf ppf "%da%dd" y d
else
let h = to_hour left in
let left = Int64.rem left hour in
if d > 0 then
Format.fprintf ppf "%dd%02dh" d h
else
let min = to_min left in
let left = Int64.sub t (of_min min) in
let sec = to_sec left in
if h > 0 then
Format.fprintf ppf "%dh%02dm" h min
else (* if m > 0 then *)
Format.fprintf ppf "%dm%02ds" min sec
below one minute
let s, ms, us, ns = fields t in
if s > 0L then
Format.fprintf ppf "%Ld.%03Lds" s ms
else if ms > 0L then
Format.fprintf ppf "%Ld.%03Ldms" ms us
else (* if us > 0 then *)
Format.fprintf ppf "%Ld.%03Ldμs" us ns
| null | https://raw.githubusercontent.com/hannesm/duration/4df04ce6f2d8cb2f798d19e1d2da3ce9246d37ec/duration.ml | ocaml | if m > 0 then
if us > 0 then | type t = int64
let of_us_64 m =
if m < 0L then
invalid_arg "negative" ;
if Int64.compare m 0x4189374BC6A7EDL = 1 then
invalid_arg "out of range" ;
Int64.mul 1_000L m
let of_us m = of_us_64 (Int64.of_int m)
let of_ms_64 m =
if m < 0L then
invalid_arg "negative" ;
if Int64.compare m 0x10C6F7A0B5EDL = 1 then
invalid_arg "out of range" ;
Int64.mul 1_000_000L m
let of_ms m = of_ms_64 (Int64.of_int m)
let of_sec_64 s =
if s < 0L then
invalid_arg "negative" ;
if Int64.compare s 0x44B82FA09L = 1 then
invalid_arg "out of range" ;
Int64.mul 1_000_000_000L s
let of_sec m = of_sec_64 (Int64.of_int m)
let of_min m =
if m < 0 then
invalid_arg "negative" ;
let m = Int64.of_int m in
if Int64.compare m 0x12533FE6L = 1 then
invalid_arg "out of range" ;
Int64.mul 60_000_000_000L m
let hour = 3600_000_000_000L
let of_hour h =
if h < 0 then
invalid_arg "negative" ;
let h = Int64.of_int h in
if Int64.compare h 0x4E2FFFL = 1 then
invalid_arg "out of range" ;
Int64.mul hour h
let day = Int64.mul 24L hour
let of_day d =
if d < 0 then
invalid_arg "negative" ;
let d = Int64.of_int d in
if Int64.compare d 0x341FFL = 1 then
invalid_arg "out of range" ;
Int64.mul day d
let year = Int64.mul 8766L hour
let of_year y =
if y < 0 then
invalid_arg "negative" ;
let y = Int64.of_int y in
if Int64.compare y 0x248L = 1 then
invalid_arg "out of range" ;
Int64.mul year y
let of_f f =
if f < 0. then
invalid_arg "negative" ;
if f > 18446744073.709549 then
invalid_arg "out of range" ;
let s = Int64.of_float f in
let rem = f -. (Int64.to_float s) in
let ns = Int64.of_float (rem *. 1_000_000_000.) in
Int64.(add (mul 1_000_000_000L s) ns)
let to_f t =
let pl =
if t >= 0L then
0.
else
abs_float (2. *. (Int64.to_float 0x8000000000000000L))
in
let ns = Int64.to_float t in
(ns +. pl) /. 1_000_000_000.
let to_int64 t d =
let f c = Int64.div c d in
if t < 0L then
Int64.(add (f (Int64.add t Int64.min_int)) (add (f Int64.max_int) 1L))
else
f t
let to_int t d =
let r = to_int64 t d in
if r > Int64.of_int max_int then
invalid_arg "value too big for this platform" ;
Int64.to_int r
let to_us_64 t = to_int64 t 1_000L
let to_us t = to_int t 1_000L
let to_ms_64 t = to_int64 t 1_000_000L
let to_ms t = to_int t 1_000_000L
let to_sec_64 t = to_int64 t 1_000_000_000L
let to_sec t = to_int t 1_000_000_000L
let to_min t = to_int t 60_000_000_000L
let to_hour t = to_int t hour
let to_day t = to_int t day
let to_year t = to_int t year
let fields t =
let sec = to_sec_64 t in
let left = Int64.sub t (of_sec_64 sec) in
let ms = to_ms_64 left in
let left = Int64.sub left (of_ms_64 ms) in
let us = to_us_64 left in
let ns = Int64.(sub left (of_us_64 us)) in
(sec, ms, us, ns)
let pp ppf t =
let min = to_min t in
if min > 0 then
let y = to_year t in
let left = Int64.rem t year in
let d = to_day left in
let left = Int64.rem left day in
if y > 0 then
Format.fprintf ppf "%da%dd" y d
else
let h = to_hour left in
let left = Int64.rem left hour in
if d > 0 then
Format.fprintf ppf "%dd%02dh" d h
else
let min = to_min left in
let left = Int64.sub t (of_min min) in
let sec = to_sec left in
if h > 0 then
Format.fprintf ppf "%dh%02dm" h min
Format.fprintf ppf "%dm%02ds" min sec
below one minute
let s, ms, us, ns = fields t in
if s > 0L then
Format.fprintf ppf "%Ld.%03Lds" s ms
else if ms > 0L then
Format.fprintf ppf "%Ld.%03Ldms" ms us
Format.fprintf ppf "%Ld.%03Ldμs" us ns
|
a0d55bc458f4e142235db736fed98e9e16c74f24cf13e970abb5a2ebfaa62811 | ghc/hsc2hs | Flags.hs |
module Flags where
import System.Console.GetOpt
data Mode
= Help
| Version
| UseConfig (ConfigM Maybe)
newtype Id a = Id { fromId :: a }
type Config = ConfigM Id
data ConfigM m = Config {
cmTemplate :: m FilePath,
cmCompiler :: m FilePath,
cmLinker :: m FilePath,
cKeepFiles :: Bool,
cNoCompile :: Bool,
cCrossCompile :: Bool,
cViaAsm :: Bool,
cCrossSafe :: Bool,
cColumn :: Bool,
cVerbose :: Bool,
cFlags :: [Flag]
}
cTemplate :: ConfigM Id -> FilePath
cTemplate c = fromId $ cmTemplate c
cCompiler :: ConfigM Id -> FilePath
cCompiler c = fromId $ cmCompiler c
cLinker :: ConfigM Id -> FilePath
cLinker c = fromId $ cmLinker c
emptyMode :: Mode
emptyMode = UseConfig $ Config {
cmTemplate = Nothing,
cmCompiler = Nothing,
cmLinker = Nothing,
cKeepFiles = False,
cNoCompile = False,
cCrossCompile = False,
cViaAsm = False,
cCrossSafe = False,
cColumn = False,
cVerbose = False,
cFlags = []
}
data Flag
= CompFlag String
| LinkFlag String
| Include String
| Define String (Maybe String)
| Output String
deriving Show
options :: [OptDescr (Mode -> Mode)]
options = [
Option ['o'] ["output"] (ReqArg (addFlag . Output) "FILE")
"name of main output file",
Option ['t'] ["template"] (ReqArg (withConfig . setTemplate) "FILE")
"template file",
Option ['c'] ["cc"] (ReqArg (withConfig . setCompiler) "PROG")
"C compiler to use",
Option ['l'] ["ld"] (ReqArg (withConfig . setLinker) "PROG")
"linker to use",
Option ['C'] ["cflag"] (ReqArg (addFlag . CompFlag) "FLAG")
"flag to pass to the C compiler",
Option ['I'] [] (ReqArg (addFlag . CompFlag . ("-I"++)) "DIR")
"passed to the C compiler",
Option ['L'] ["lflag"] (ReqArg (addFlag . LinkFlag) "FLAG")
"flag to pass to the linker",
Option ['i'] ["include"] (ReqArg (addFlag . include) "FILE")
"as if placed in the source",
Option ['D'] ["define"] (ReqArg (addFlag . define) "NAME[=VALUE]")
"as if placed in the source",
Option [] ["no-compile"] (NoArg (withConfig $ setNoCompile True))
"stop after writing *_hsc_make.c",
Option ['x'] ["cross-compile"] (NoArg (withConfig $ setCrossCompile True))
"activate cross-compilation mode",
Option [] ["via-asm"] (NoArg (withConfig $ setViaAsm True))
"use a crude asm parser to compute constants when cross compiling",
Option [] ["cross-safe"] (NoArg (withConfig $ setCrossSafe True))
"restrict .hsc directives to those supported by --cross-compile",
Option ['k'] ["keep-files"] (NoArg (withConfig $ setKeepFiles True))
"do not remove temporary files",
Option [] ["column"] (NoArg (withConfig $ setColumn True))
"annotate output with COLUMN pragmas (requires GHC 8.2)",
Option ['v'] ["verbose"] (NoArg (withConfig $ setVerbose True))
"dump commands to stderr",
Option ['?'] ["help"] (NoArg (setMode Help))
"display this help and exit",
Option ['V'] ["version"] (NoArg (setMode Version))
"output version information and exit" ]
addFlag :: Flag -> Mode -> Mode
addFlag f (UseConfig c) = UseConfig $ c { cFlags = f : cFlags c }
addFlag _ mode = mode
setMode :: Mode -> Mode -> Mode
setMode Help _ = Help
setMode _ Help = Help
setMode Version _ = Version
setMode (UseConfig {}) _ = error "setMode: UseConfig: Can't happen"
withConfig :: (ConfigM Maybe -> ConfigM Maybe) -> Mode -> Mode
withConfig f (UseConfig c) = UseConfig $ f c
withConfig _ m = m
setTemplate :: FilePath -> ConfigM Maybe -> ConfigM Maybe
setTemplate fp c = c { cmTemplate = Just fp }
setCompiler :: FilePath -> ConfigM Maybe -> ConfigM Maybe
setCompiler fp c = c { cmCompiler = Just fp }
setLinker :: FilePath -> ConfigM Maybe -> ConfigM Maybe
setLinker fp c = c { cmLinker = Just fp }
setKeepFiles :: Bool -> ConfigM Maybe -> ConfigM Maybe
setKeepFiles b c = c { cKeepFiles = b }
setNoCompile :: Bool -> ConfigM Maybe -> ConfigM Maybe
setNoCompile b c = c { cNoCompile = b }
setCrossCompile :: Bool -> ConfigM Maybe -> ConfigM Maybe
setCrossCompile b c = c { cCrossCompile = b }
setViaAsm :: Bool -> ConfigM Maybe -> ConfigM Maybe
setViaAsm b c = c { cViaAsm = b }
setCrossSafe :: Bool -> ConfigM Maybe -> ConfigM Maybe
setCrossSafe b c = c { cCrossSafe = b }
setColumn :: Bool -> ConfigM Maybe -> ConfigM Maybe
setColumn b c = c { cColumn = b }
setVerbose :: Bool -> ConfigM Maybe -> ConfigM Maybe
setVerbose v c = c { cVerbose = v }
include :: String -> Flag
include s@('\"':_) = Include s
include s@('<' :_) = Include s
include s = Include ("\""++s++"\"")
define :: String -> Flag
define s = case break (== '=') s of
(name, []) -> Define name Nothing
(name, _:value) -> Define name (Just value)
| null | https://raw.githubusercontent.com/ghc/hsc2hs/0b44990f0282755b75091838363ad4a1f4cb245d/Flags.hs | haskell |
module Flags where
import System.Console.GetOpt
data Mode
= Help
| Version
| UseConfig (ConfigM Maybe)
newtype Id a = Id { fromId :: a }
type Config = ConfigM Id
data ConfigM m = Config {
cmTemplate :: m FilePath,
cmCompiler :: m FilePath,
cmLinker :: m FilePath,
cKeepFiles :: Bool,
cNoCompile :: Bool,
cCrossCompile :: Bool,
cViaAsm :: Bool,
cCrossSafe :: Bool,
cColumn :: Bool,
cVerbose :: Bool,
cFlags :: [Flag]
}
cTemplate :: ConfigM Id -> FilePath
cTemplate c = fromId $ cmTemplate c
cCompiler :: ConfigM Id -> FilePath
cCompiler c = fromId $ cmCompiler c
cLinker :: ConfigM Id -> FilePath
cLinker c = fromId $ cmLinker c
emptyMode :: Mode
emptyMode = UseConfig $ Config {
cmTemplate = Nothing,
cmCompiler = Nothing,
cmLinker = Nothing,
cKeepFiles = False,
cNoCompile = False,
cCrossCompile = False,
cViaAsm = False,
cCrossSafe = False,
cColumn = False,
cVerbose = False,
cFlags = []
}
data Flag
= CompFlag String
| LinkFlag String
| Include String
| Define String (Maybe String)
| Output String
deriving Show
options :: [OptDescr (Mode -> Mode)]
options = [
Option ['o'] ["output"] (ReqArg (addFlag . Output) "FILE")
"name of main output file",
Option ['t'] ["template"] (ReqArg (withConfig . setTemplate) "FILE")
"template file",
Option ['c'] ["cc"] (ReqArg (withConfig . setCompiler) "PROG")
"C compiler to use",
Option ['l'] ["ld"] (ReqArg (withConfig . setLinker) "PROG")
"linker to use",
Option ['C'] ["cflag"] (ReqArg (addFlag . CompFlag) "FLAG")
"flag to pass to the C compiler",
Option ['I'] [] (ReqArg (addFlag . CompFlag . ("-I"++)) "DIR")
"passed to the C compiler",
Option ['L'] ["lflag"] (ReqArg (addFlag . LinkFlag) "FLAG")
"flag to pass to the linker",
Option ['i'] ["include"] (ReqArg (addFlag . include) "FILE")
"as if placed in the source",
Option ['D'] ["define"] (ReqArg (addFlag . define) "NAME[=VALUE]")
"as if placed in the source",
Option [] ["no-compile"] (NoArg (withConfig $ setNoCompile True))
"stop after writing *_hsc_make.c",
Option ['x'] ["cross-compile"] (NoArg (withConfig $ setCrossCompile True))
"activate cross-compilation mode",
Option [] ["via-asm"] (NoArg (withConfig $ setViaAsm True))
"use a crude asm parser to compute constants when cross compiling",
Option [] ["cross-safe"] (NoArg (withConfig $ setCrossSafe True))
"restrict .hsc directives to those supported by --cross-compile",
Option ['k'] ["keep-files"] (NoArg (withConfig $ setKeepFiles True))
"do not remove temporary files",
Option [] ["column"] (NoArg (withConfig $ setColumn True))
"annotate output with COLUMN pragmas (requires GHC 8.2)",
Option ['v'] ["verbose"] (NoArg (withConfig $ setVerbose True))
"dump commands to stderr",
Option ['?'] ["help"] (NoArg (setMode Help))
"display this help and exit",
Option ['V'] ["version"] (NoArg (setMode Version))
"output version information and exit" ]
addFlag :: Flag -> Mode -> Mode
addFlag f (UseConfig c) = UseConfig $ c { cFlags = f : cFlags c }
addFlag _ mode = mode
setMode :: Mode -> Mode -> Mode
setMode Help _ = Help
setMode _ Help = Help
setMode Version _ = Version
setMode (UseConfig {}) _ = error "setMode: UseConfig: Can't happen"
withConfig :: (ConfigM Maybe -> ConfigM Maybe) -> Mode -> Mode
withConfig f (UseConfig c) = UseConfig $ f c
withConfig _ m = m
setTemplate :: FilePath -> ConfigM Maybe -> ConfigM Maybe
setTemplate fp c = c { cmTemplate = Just fp }
setCompiler :: FilePath -> ConfigM Maybe -> ConfigM Maybe
setCompiler fp c = c { cmCompiler = Just fp }
setLinker :: FilePath -> ConfigM Maybe -> ConfigM Maybe
setLinker fp c = c { cmLinker = Just fp }
setKeepFiles :: Bool -> ConfigM Maybe -> ConfigM Maybe
setKeepFiles b c = c { cKeepFiles = b }
setNoCompile :: Bool -> ConfigM Maybe -> ConfigM Maybe
setNoCompile b c = c { cNoCompile = b }
setCrossCompile :: Bool -> ConfigM Maybe -> ConfigM Maybe
setCrossCompile b c = c { cCrossCompile = b }
setViaAsm :: Bool -> ConfigM Maybe -> ConfigM Maybe
setViaAsm b c = c { cViaAsm = b }
setCrossSafe :: Bool -> ConfigM Maybe -> ConfigM Maybe
setCrossSafe b c = c { cCrossSafe = b }
setColumn :: Bool -> ConfigM Maybe -> ConfigM Maybe
setColumn b c = c { cColumn = b }
setVerbose :: Bool -> ConfigM Maybe -> ConfigM Maybe
setVerbose v c = c { cVerbose = v }
include :: String -> Flag
include s@('\"':_) = Include s
include s@('<' :_) = Include s
include s = Include ("\""++s++"\"")
define :: String -> Flag
define s = case break (== '=') s of
(name, []) -> Define name Nothing
(name, _:value) -> Define name (Just value)
| |
f8717145502badc4dc8ea365c644b3b74424a511c48c80b345eab890284ab63d | nallen05/djula | run.lisp | djula-test::!run-compile-tokens-test | null | https://raw.githubusercontent.com/nallen05/djula/331e2d5b0c9967b636e4df22e847ac98f16f6ba9/test/2-compile-tokens-group/run.lisp | lisp | djula-test::!run-compile-tokens-test | |
0a142d70db5995b6230ec1bce1c68de64a875e42b795c521795cf81747508e4c | melange-re/melange | test_is_js.ml | let v =
#if BS then
true
#else
false
#end
let suites : Mt.pair_suites ref = ref []
let test_id = ref 0
let eq loc x y = Mt.eq_suites ~test_id ~suites loc x y
let b loc x = Mt.bool_suites ~test_id ~suites loc x;;
#if 1 then
b __LOC__ true;;
#end
#if 0 then
b __LOC__ false ;;
#end
#if 1 > 0 then
b __LOC__ true;;
#end
#if 1 < 0 then
b __LOC__ false;;
#end
#if 0 > 1 then
b __LOC__ false;;
#end
#if 0 < 1 then
b __LOC__ true;;
#end
let () = Mt.from_pair_suites __MODULE__ !suites | null | https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/test/test_is_js.ml | ocaml | let v =
#if BS then
true
#else
false
#end
let suites : Mt.pair_suites ref = ref []
let test_id = ref 0
let eq loc x y = Mt.eq_suites ~test_id ~suites loc x y
let b loc x = Mt.bool_suites ~test_id ~suites loc x;;
#if 1 then
b __LOC__ true;;
#end
#if 0 then
b __LOC__ false ;;
#end
#if 1 > 0 then
b __LOC__ true;;
#end
#if 1 < 0 then
b __LOC__ false;;
#end
#if 0 > 1 then
b __LOC__ false;;
#end
#if 0 < 1 then
b __LOC__ true;;
#end
let () = Mt.from_pair_suites __MODULE__ !suites | |
99e8b3878530eda21d896eb940d96e640e9702360c6feb727909b290f0ab83cb | boris-ci/boris | Log.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
module Boris.Core.Data.Log (
Log (..)
) where
import Boris.Prelude
import Data.Text (Text)
import Data.Time (UTCTime)
data Log =
LogEvent !UTCTime !Text
| LogEOF
deriving (Eq, Ord, Show)
| null | https://raw.githubusercontent.com/boris-ci/boris/c321187490afc889bf281442ac4ef9398b77b200/boris-core/src/Boris/Core/Data/Log.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE NoImplicitPrelude #
module Boris.Core.Data.Log (
Log (..)
) where
import Boris.Prelude
import Data.Text (Text)
import Data.Time (UTCTime)
data Log =
LogEvent !UTCTime !Text
| LogEOF
deriving (Eq, Ord, Show)
|
e90576b163a6b290ce73c75af1cc789fd9a374b718ce8bcd0c6493625bfcc680 | inconvergent/weird | canvas.lisp |
(in-package :canvas)
(defmacro -do-op ((canv size vals indfx) &body body)
(declare (symbol canv size vals indfx))
(alexandria:with-gensyms (sname)
`(let* ((,sname ,canv)
(,size (canvas-size ,sname))
(,vals (canvas-vals ,sname))
(,indfx (canvas-indfx ,sname)))
(declare (veq:fvec ,vals) (function ,indfx) (small-ind ,size)
(ignorable ,size))
(progn ,@body))))
(defmacro -square-loop ((x y n) &body body)
(declare (symbol x y n))
(alexandria:with-gensyms (nname)
`(let ((,nname ,n))
(loop for ,y of-type small-ind from 0 below ,nname
do (loop for ,x of-type small-ind from 0 below ,nname
do (progn ,@body))))))
(defstruct canvas
(size nil :type small-ind :read-only t)
(vals nil :type veq:fvec :read-only t)
(indfx nil :type function :read-only t))
(declaim (inline set-pix))
(defun set-pix (canv i j r g b)
(declare #.*opt* (veq:pn i j) (veq:ff r g b))
"set (i j) to value (r g b) where 0.0 =< r,g,b =< 1.0."
(-do-op (canv size vals indfx)
(let ((ind (funcall indfx i j)))
(declare (veq:pn ind))
(setf (aref vals ind) (max 0f0 (min 1f0 r))
(aref vals (1+ ind)) (max 0f0 (min 1f0 g))
(aref vals (+ ind 2)) (max 0f0 (min 1f0 b)))
nil)))
(declaim (inline set-gray-pix))
(defun set-gray-pix (canv i j c)
(declare #.*opt* (veq:pn i j) (veq:ff c))
"set (i j) to value c where 0.0 =< c =< 1.0."
(-do-op (canv size vals indfx)
(let ((ind (funcall indfx i j))
(c* (max 0f0 (min 1f0 c))))
(declare (veq:pn ind) (veq:ff c*))
(setf (aref vals ind) c*
(aref vals (1+ ind)) c*
(aref vals (+ ind 2)) c*)
nil)))
(defun get-size (canv) (canvas-size canv))
(defun -get-indfx (size)
(declare #.*opt* (small-ind size))
(labels ((-indfx (s x y c)
(declare #.*opt* (small-ind s x y c))
(+ c (the veq:pn
(* 3 (the veq:pn (+ x (the veq:pn (* s y))))))))
(indfx (x y &optional (c 0))
(declare (small-ind x y c))
(-indfx size x y c)))
#'indfx))
(defun make (&key (size 1000))
(declare #.*opt*)
"make square PNG canvas instance of size to."
(make-canvas
:size size :vals (veq:f3$zero (* size size)) :indfx (-get-indfx size)))
(declaim (inline -png-vals))
(defun -png-vals (indfx vals x y g)
(declare #.*opt* (function indfx) (fixnum x y) (veq:ff g) (veq:fvec vals))
(labels
((-scale-convert (v &key (s 1f0) (gamma 1f0))
(declare (veq:ff v s gamma))
(setf v (expt (abs (the veq:ff (max 0f0 (the veq:ff (/ v s))))) gamma)))
(-u8 (v)
(declare (veq:ff v))
(the fixnum (cond ((>= v 1f0) 255)
((<= v 0f0) 0)
(t (values (floor (the veq:ff (* 255f0 v)))))))))
(let ((ind (funcall indfx x y)))
(declare (veq:pn ind))
(values (-u8 (-scale-convert (aref vals ind) :gamma g))
(-u8 (-scale-convert (aref vals (1+ ind)) :gamma g))
(-u8 (-scale-convert (aref vals (+ ind 2)) :gamma g))))))
(defun -save8 (canv fn &key gamma)
(declare #.*opt*)
(-do-op (canv size vals indfx)
(let ((png (make-instance 'zpng::pixel-streamed-png :color-type :truecolor
:width size :height size)))
(with-open-file (fstream (weird:ensure-filename fn ".png")
:direction :output :if-exists :supersede
:if-does-not-exist :create :element-type '(unsigned-byte 8))
(zpng:start-png png fstream)
(-square-loop (x y size)
(weird:mvb (r g b) (-png-vals indfx vals x y gamma)
(declare (fixnum r g b))
(zpng:write-pixel (list r g b) png)))
(zpng:finish-png png)))))
(defun save (canv fn &key (gamma 1f0))
(declare (canvas canv) (veq:ff gamma))
"save as 8 bit PNG file fn with gamma."
(-save8 canv fn :gamma gamma))
| null | https://raw.githubusercontent.com/inconvergent/weird/106d154ec2cd0e4ec977c3672ba717d6305c1056/src/draw/canvas.lisp | lisp |
(in-package :canvas)
(defmacro -do-op ((canv size vals indfx) &body body)
(declare (symbol canv size vals indfx))
(alexandria:with-gensyms (sname)
`(let* ((,sname ,canv)
(,size (canvas-size ,sname))
(,vals (canvas-vals ,sname))
(,indfx (canvas-indfx ,sname)))
(declare (veq:fvec ,vals) (function ,indfx) (small-ind ,size)
(ignorable ,size))
(progn ,@body))))
(defmacro -square-loop ((x y n) &body body)
(declare (symbol x y n))
(alexandria:with-gensyms (nname)
`(let ((,nname ,n))
(loop for ,y of-type small-ind from 0 below ,nname
do (loop for ,x of-type small-ind from 0 below ,nname
do (progn ,@body))))))
(defstruct canvas
(size nil :type small-ind :read-only t)
(vals nil :type veq:fvec :read-only t)
(indfx nil :type function :read-only t))
(declaim (inline set-pix))
(defun set-pix (canv i j r g b)
(declare #.*opt* (veq:pn i j) (veq:ff r g b))
"set (i j) to value (r g b) where 0.0 =< r,g,b =< 1.0."
(-do-op (canv size vals indfx)
(let ((ind (funcall indfx i j)))
(declare (veq:pn ind))
(setf (aref vals ind) (max 0f0 (min 1f0 r))
(aref vals (1+ ind)) (max 0f0 (min 1f0 g))
(aref vals (+ ind 2)) (max 0f0 (min 1f0 b)))
nil)))
(declaim (inline set-gray-pix))
(defun set-gray-pix (canv i j c)
(declare #.*opt* (veq:pn i j) (veq:ff c))
"set (i j) to value c where 0.0 =< c =< 1.0."
(-do-op (canv size vals indfx)
(let ((ind (funcall indfx i j))
(c* (max 0f0 (min 1f0 c))))
(declare (veq:pn ind) (veq:ff c*))
(setf (aref vals ind) c*
(aref vals (1+ ind)) c*
(aref vals (+ ind 2)) c*)
nil)))
(defun get-size (canv) (canvas-size canv))
(defun -get-indfx (size)
(declare #.*opt* (small-ind size))
(labels ((-indfx (s x y c)
(declare #.*opt* (small-ind s x y c))
(+ c (the veq:pn
(* 3 (the veq:pn (+ x (the veq:pn (* s y))))))))
(indfx (x y &optional (c 0))
(declare (small-ind x y c))
(-indfx size x y c)))
#'indfx))
(defun make (&key (size 1000))
(declare #.*opt*)
"make square PNG canvas instance of size to."
(make-canvas
:size size :vals (veq:f3$zero (* size size)) :indfx (-get-indfx size)))
(declaim (inline -png-vals))
(defun -png-vals (indfx vals x y g)
(declare #.*opt* (function indfx) (fixnum x y) (veq:ff g) (veq:fvec vals))
(labels
((-scale-convert (v &key (s 1f0) (gamma 1f0))
(declare (veq:ff v s gamma))
(setf v (expt (abs (the veq:ff (max 0f0 (the veq:ff (/ v s))))) gamma)))
(-u8 (v)
(declare (veq:ff v))
(the fixnum (cond ((>= v 1f0) 255)
((<= v 0f0) 0)
(t (values (floor (the veq:ff (* 255f0 v)))))))))
(let ((ind (funcall indfx x y)))
(declare (veq:pn ind))
(values (-u8 (-scale-convert (aref vals ind) :gamma g))
(-u8 (-scale-convert (aref vals (1+ ind)) :gamma g))
(-u8 (-scale-convert (aref vals (+ ind 2)) :gamma g))))))
(defun -save8 (canv fn &key gamma)
(declare #.*opt*)
(-do-op (canv size vals indfx)
(let ((png (make-instance 'zpng::pixel-streamed-png :color-type :truecolor
:width size :height size)))
(with-open-file (fstream (weird:ensure-filename fn ".png")
:direction :output :if-exists :supersede
:if-does-not-exist :create :element-type '(unsigned-byte 8))
(zpng:start-png png fstream)
(-square-loop (x y size)
(weird:mvb (r g b) (-png-vals indfx vals x y gamma)
(declare (fixnum r g b))
(zpng:write-pixel (list r g b) png)))
(zpng:finish-png png)))))
(defun save (canv fn &key (gamma 1f0))
(declare (canvas canv) (veq:ff gamma))
"save as 8 bit PNG file fn with gamma."
(-save8 canv fn :gamma gamma))
| |
323573cfc0d08e3c5945b403c2ef707730a6bd85e466314009257720017dffe0 | esl/MongooseIM | mongoose_client_api_rooms_config.erl | -module(mongoose_client_api_rooms_config).
-behaviour(mongoose_client_api).
-export([routes/0]).
-behaviour(cowboy_rest).
-export([trails/0,
init/2,
is_authorized/2,
content_types_accepted/2,
allowed_methods/2,
from_json/2]).
-ignore_xref([from_json/2, trails/0]).
-import(mongoose_client_api, [parse_body/1, try_handle_request/3, throw_error/2]).
-import(mongoose_client_api_rooms, [get_room_jid/3, get_room_name/1, get_room_subject/1]).
-type req() :: cowboy_req:req().
-type state() :: map().
-spec routes() -> mongoose_http_handler:routes().
routes() ->
[{"/rooms/[:id]/config", ?MODULE, #{}}].
trails() ->
mongoose_client_api_rooms_config_doc:trails().
-spec init(req(), state()) -> {cowboy_rest, req(), state()}.
init(Req, Opts) ->
mongoose_client_api:init(Req, Opts).
-spec is_authorized(req(), state()) -> {true | {false, iodata()}, req(), state()}.
is_authorized(Req, State) ->
mongoose_client_api:is_authorized(Req, State).
content_types_accepted(Req, State) ->
mongoose_client_api_rooms:content_types_accepted(Req, State).
allowed_methods(Req, State) ->
{[<<"OPTIONS">>, <<"PUT">>], Req, State}.
%% @doc Called for a method of type "PUT"
-spec from_json(req(), state()) -> {true | stop, req(), state()}.
from_json(Req, State) ->
try_handle_request(Req, State, fun handle_put/2).
Internal functions
handle_put(Req, State = #{jid := UserJid}) ->
Bindings = cowboy_req:bindings(Req),
RoomJid = get_room_jid(Bindings, State, required),
Args = parse_body(Req),
Name = get_room_name(Args),
Subject = get_room_subject(Args),
Config = #{<<"roomname">> => Name, <<"subject">> => Subject},
case mod_muc_light_api:change_room_config(RoomJid, UserJid, Config) of
{ok, _} ->
{true, Req, State};
{not_room_member, Msg} ->
throw_error(denied, Msg);
{not_allowed, Msg} ->
throw_error(denied, Msg);
{room_not_found, Msg} ->
throw_error(not_found, Msg);
{validation_error, Msg} ->
throw_error(bad_request, Msg)
end.
| null | https://raw.githubusercontent.com/esl/MongooseIM/a9ee17fc6d596c4b4cccaa47782c6bfcadfd2190/src/mongoose_client_api/mongoose_client_api_rooms_config.erl | erlang | @doc Called for a method of type "PUT" | -module(mongoose_client_api_rooms_config).
-behaviour(mongoose_client_api).
-export([routes/0]).
-behaviour(cowboy_rest).
-export([trails/0,
init/2,
is_authorized/2,
content_types_accepted/2,
allowed_methods/2,
from_json/2]).
-ignore_xref([from_json/2, trails/0]).
-import(mongoose_client_api, [parse_body/1, try_handle_request/3, throw_error/2]).
-import(mongoose_client_api_rooms, [get_room_jid/3, get_room_name/1, get_room_subject/1]).
-type req() :: cowboy_req:req().
-type state() :: map().
-spec routes() -> mongoose_http_handler:routes().
routes() ->
[{"/rooms/[:id]/config", ?MODULE, #{}}].
trails() ->
mongoose_client_api_rooms_config_doc:trails().
-spec init(req(), state()) -> {cowboy_rest, req(), state()}.
init(Req, Opts) ->
mongoose_client_api:init(Req, Opts).
-spec is_authorized(req(), state()) -> {true | {false, iodata()}, req(), state()}.
is_authorized(Req, State) ->
mongoose_client_api:is_authorized(Req, State).
content_types_accepted(Req, State) ->
mongoose_client_api_rooms:content_types_accepted(Req, State).
allowed_methods(Req, State) ->
{[<<"OPTIONS">>, <<"PUT">>], Req, State}.
-spec from_json(req(), state()) -> {true | stop, req(), state()}.
from_json(Req, State) ->
try_handle_request(Req, State, fun handle_put/2).
Internal functions
handle_put(Req, State = #{jid := UserJid}) ->
Bindings = cowboy_req:bindings(Req),
RoomJid = get_room_jid(Bindings, State, required),
Args = parse_body(Req),
Name = get_room_name(Args),
Subject = get_room_subject(Args),
Config = #{<<"roomname">> => Name, <<"subject">> => Subject},
case mod_muc_light_api:change_room_config(RoomJid, UserJid, Config) of
{ok, _} ->
{true, Req, State};
{not_room_member, Msg} ->
throw_error(denied, Msg);
{not_allowed, Msg} ->
throw_error(denied, Msg);
{room_not_found, Msg} ->
throw_error(not_found, Msg);
{validation_error, Msg} ->
throw_error(bad_request, Msg)
end.
|
f247e6fb1aaaedb338339e2bac76ee6f1e0a5c8e99032c9e91a774cd40cf3dd1 | ucsd-progsys/dsolve | demo_combinations.ml | let rec len xs = match xs with
| [] -> 0
| x::xs -> 1 + len xs
let rec zip xs ys =
match xs, ys with
| [], [] -> []
| x::xs, y::ys -> (x,y)::(zip xs ys)
| [] ,_::_ -> assert (0=1); assert false
| _::_, [] -> assert (0=1); assert false
let rec clone x n =
let _ = assert (n >= 0) in
if n = 0 then [] else x::(clone x (n-1))
let rec combinations xss = match xss with
| [] ->
[[]]
| xs :: xss ->
let yss = combinations xss in
let xyss = List.map (fun x ->
List.map (fun ys ->
x :: ys
) yss
) xs in
let xyss = [ x::ys | for x in xs , ys in ] in
List.flatten xyss
let assignments xs ys =
let n = len xs in
let yss = clone ys n in
let zss = combinations yss in
List.map (zip xs) zss
let a1 = assignments ["x";"y"] [1.1; 2.2; 3.3; 4.4]
let a2 = assignments ["a"; "b"; "c"] [10; 20; 30; 40; 50]
| null | https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/proceedings-demos/demo/demo_combinations.ml | ocaml | let rec len xs = match xs with
| [] -> 0
| x::xs -> 1 + len xs
let rec zip xs ys =
match xs, ys with
| [], [] -> []
| x::xs, y::ys -> (x,y)::(zip xs ys)
| [] ,_::_ -> assert (0=1); assert false
| _::_, [] -> assert (0=1); assert false
let rec clone x n =
let _ = assert (n >= 0) in
if n = 0 then [] else x::(clone x (n-1))
let rec combinations xss = match xss with
| [] ->
[[]]
| xs :: xss ->
let yss = combinations xss in
let xyss = List.map (fun x ->
List.map (fun ys ->
x :: ys
) yss
) xs in
let xyss = [ x::ys | for x in xs , ys in ] in
List.flatten xyss
let assignments xs ys =
let n = len xs in
let yss = clone ys n in
let zss = combinations yss in
List.map (zip xs) zss
let a1 = assignments ["x";"y"] [1.1; 2.2; 3.3; 4.4]
let a2 = assignments ["a"; "b"; "c"] [10; 20; 30; 40; 50]
| |
04f5b4940acd572aa1108702c9783de6c6a611f099770d848e8ff95fd5d69704 | JeffreyBenjaminBrown/hode | Karpov.hs | by , with trivial modifications by jbb
-- -simple-imperative-language.html
# LANGUAGE ScopedTypeVariables #
module Parse where
import Control.Monad (void)
import Control.Monad.Combinators.Expr
import Data.List (intersperse)
import Data.Void (Void)
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
data BExpr
= BoolConst Bool
| Not BExpr
| BBinary BBinOp BExpr BExpr
| RBinary RBinOp AExpr AExpr
deriving (Show)
data BBinOp
= And
| Or
deriving (Show)
data RBinOp
= Greater
| Less
deriving (Show)
data AExpr
= Var String
| IntConst Integer
| Neg AExpr
| ABinary ABinOp AExpr AExpr
deriving (Show)
data ABinOp
= Add
| Subtract
| Multiply
| Divide
deriving (Show)
data Stmt
= Seq [Stmt]
| Assign String AExpr
| If BExpr Stmt Stmt
| While BExpr Stmt
| Skip
deriving (Show)
type Parser = Parsec Void String
| = =
sc :: Parser ()
sc = L.space space1 lineCmnt blockCmnt
where
lineCmnt = L.skipLineComment "//"
blockCmnt = L.skipBlockComment "/*" "*/"
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
symbol :: String -> Parser String
symbol = L.symbol sc
parens :: Parser a -> Parser a
parens = between (symbol "(") $ symbol ")"
integer :: Parser Integer
integer = lexeme L.decimal
-- | parses a semicolon
semi :: Parser String
semi = symbol ";"
reservedWord :: String -> Parser ()
reservedWord w = lexeme . try
$ string w *> notFollowedBy alphaNumChar
-- `string` backtracks upon failure
reservedWords :: [String]
reservedWords = ["if","then","else","while","do"
,"skip","true","false","not","and","or"]
identifier :: Parser String
identifier = (lexeme . try) (p >>= notReserved) where
-- without `try`, expressions like many identifier would
-- fail on such identifiers instead of just stopping.
(p :: Parser String) =
(:) <$> letterChar <*> many alphaNumChar
` (: ) : : , and
` letterChar : : , so
` (: ) < $ > letterChar : : ( String - > String )
notReserved :: String -> Parser String
notReserved x = if x `elem` reservedWords
then fail $ "keyword " ++ show x
++ " cannot be an identifier"
else return x
phrase :: Parser String -- | does not accept the empty string
phrase = concat . intersperse " " <$> some identifier
| = =
-- | The top-level parser. (The language is called "while".)
whileParser :: Parser Stmt
whileParser = between sc eof stmt
stmt :: Parser Stmt
stmt = f <$> sepBy1 stmt' semi where
if there 's only one stmt , return it without using ‘ Seq ’
f l = if length l == 1
then head l else Seq l
stmt' :: Parser Stmt
stmt' = ifStmt
<|> whileStmt
<|> skipStmt
<|> assignStmt
<|> parens stmt
ifStmt :: Parser Stmt
ifStmt = do
reservedWord "if"
cond <- bExpr
reservedWord "then"
stmt1 <- stmt
reservedWord "else"
stmt2 <- stmt
return $ If cond stmt1 stmt2
whileStmt :: Parser Stmt
whileStmt = do
reservedWord "while"
cond <- bExpr
reservedWord "do"
stmt1 <- stmt
return $ While cond stmt1
assignStmt :: Parser Stmt
assignStmt = do
var <- identifier
void $ symbol ":="
expr <- aExpr
return $ Assign var expr
skipStmt :: Parser Stmt
skipStmt = Skip <$ reservedWord "skip"
-- | = Parsing expressions
aExpr :: Parser AExpr
aExpr = makeExprParser aTerm aOperators
bExpr :: Parser BExpr
bExpr = makeExprParser bTerm bOperators
aOperators :: [[Operator Parser AExpr]]
aOperators =
[ [ Prefix $ Neg <$ symbol "-" ]
, [ InfixL $ ABinary Multiply <$ symbol "*"
, InfixL $ ABinary Divide <$ symbol "/" ]
, [ InfixL $ ABinary Add <$ symbol "+"
, InfixL $ ABinary Subtract <$ symbol "-" ]
]
bOperators :: [[Operator Parser BExpr]]
bOperators =
[ [ Prefix $ Not <$ reservedWord "not" ]
, [ InfixL $ BBinary And <$ reservedWord "and"
, InfixL $ BBinary Or <$ reservedWord "or" ]
]
aTerm :: Parser AExpr
aTerm = parens aExpr
<|> Var <$> identifier
<|> IntConst <$> integer
bTerm :: Parser BExpr
bTerm = parens bExpr
<|> BoolConst True <$ reservedWord "true"
<|> BoolConst False <$ reservedWord "false"
<|> rExpr
rExpr :: Parser BExpr
rExpr = do
a1 <- aExpr
op <- relation
a2 <- aExpr
return $ RBinary op a1 a2
relation :: Parser RBinOp
relation = Greater <$ symbol ">"
<|> Less <$ symbol "<"
main :: IO ()
main = do
input <- getContents
parseTest whileParser input
| null | https://raw.githubusercontent.com/JeffreyBenjaminBrown/hode/79a54a6796fa01570cde6903b398675c42954e62/_hiding/guidance/Karpov.hs | haskell | -simple-imperative-language.html
| parses a semicolon
`string` backtracks upon failure
without `try`, expressions like many identifier would
fail on such identifiers instead of just stopping.
| does not accept the empty string
| The top-level parser. (The language is called "while".)
| = Parsing expressions | by , with trivial modifications by jbb
# LANGUAGE ScopedTypeVariables #
module Parse where
import Control.Monad (void)
import Control.Monad.Combinators.Expr
import Data.List (intersperse)
import Data.Void (Void)
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
data BExpr
= BoolConst Bool
| Not BExpr
| BBinary BBinOp BExpr BExpr
| RBinary RBinOp AExpr AExpr
deriving (Show)
data BBinOp
= And
| Or
deriving (Show)
data RBinOp
= Greater
| Less
deriving (Show)
data AExpr
= Var String
| IntConst Integer
| Neg AExpr
| ABinary ABinOp AExpr AExpr
deriving (Show)
data ABinOp
= Add
| Subtract
| Multiply
| Divide
deriving (Show)
data Stmt
= Seq [Stmt]
| Assign String AExpr
| If BExpr Stmt Stmt
| While BExpr Stmt
| Skip
deriving (Show)
type Parser = Parsec Void String
| = =
sc :: Parser ()
sc = L.space space1 lineCmnt blockCmnt
where
lineCmnt = L.skipLineComment "//"
blockCmnt = L.skipBlockComment "/*" "*/"
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
symbol :: String -> Parser String
symbol = L.symbol sc
parens :: Parser a -> Parser a
parens = between (symbol "(") $ symbol ")"
integer :: Parser Integer
integer = lexeme L.decimal
semi :: Parser String
semi = symbol ";"
reservedWord :: String -> Parser ()
reservedWord w = lexeme . try
$ string w *> notFollowedBy alphaNumChar
reservedWords :: [String]
reservedWords = ["if","then","else","while","do"
,"skip","true","false","not","and","or"]
identifier :: Parser String
identifier = (lexeme . try) (p >>= notReserved) where
(p :: Parser String) =
(:) <$> letterChar <*> many alphaNumChar
` (: ) : : , and
` letterChar : : , so
` (: ) < $ > letterChar : : ( String - > String )
notReserved :: String -> Parser String
notReserved x = if x `elem` reservedWords
then fail $ "keyword " ++ show x
++ " cannot be an identifier"
else return x
phrase = concat . intersperse " " <$> some identifier
| = =
whileParser :: Parser Stmt
whileParser = between sc eof stmt
stmt :: Parser Stmt
stmt = f <$> sepBy1 stmt' semi where
if there 's only one stmt , return it without using ‘ Seq ’
f l = if length l == 1
then head l else Seq l
stmt' :: Parser Stmt
stmt' = ifStmt
<|> whileStmt
<|> skipStmt
<|> assignStmt
<|> parens stmt
ifStmt :: Parser Stmt
ifStmt = do
reservedWord "if"
cond <- bExpr
reservedWord "then"
stmt1 <- stmt
reservedWord "else"
stmt2 <- stmt
return $ If cond stmt1 stmt2
whileStmt :: Parser Stmt
whileStmt = do
reservedWord "while"
cond <- bExpr
reservedWord "do"
stmt1 <- stmt
return $ While cond stmt1
assignStmt :: Parser Stmt
assignStmt = do
var <- identifier
void $ symbol ":="
expr <- aExpr
return $ Assign var expr
skipStmt :: Parser Stmt
skipStmt = Skip <$ reservedWord "skip"
aExpr :: Parser AExpr
aExpr = makeExprParser aTerm aOperators
bExpr :: Parser BExpr
bExpr = makeExprParser bTerm bOperators
aOperators :: [[Operator Parser AExpr]]
aOperators =
[ [ Prefix $ Neg <$ symbol "-" ]
, [ InfixL $ ABinary Multiply <$ symbol "*"
, InfixL $ ABinary Divide <$ symbol "/" ]
, [ InfixL $ ABinary Add <$ symbol "+"
, InfixL $ ABinary Subtract <$ symbol "-" ]
]
bOperators :: [[Operator Parser BExpr]]
bOperators =
[ [ Prefix $ Not <$ reservedWord "not" ]
, [ InfixL $ BBinary And <$ reservedWord "and"
, InfixL $ BBinary Or <$ reservedWord "or" ]
]
aTerm :: Parser AExpr
aTerm = parens aExpr
<|> Var <$> identifier
<|> IntConst <$> integer
bTerm :: Parser BExpr
bTerm = parens bExpr
<|> BoolConst True <$ reservedWord "true"
<|> BoolConst False <$ reservedWord "false"
<|> rExpr
rExpr :: Parser BExpr
rExpr = do
a1 <- aExpr
op <- relation
a2 <- aExpr
return $ RBinary op a1 a2
relation :: Parser RBinOp
relation = Greater <$ symbol ">"
<|> Less <$ symbol "<"
main :: IO ()
main = do
input <- getContents
parseTest whileParser input
|
a22b62f5d6bb75ee41c30040afadd3cff83dd4fd862f18c2846677cb957fa949 | solita/mnt-teet | itemlist.cljs | (ns teet.ui.itemlist
(:require [herb.core :refer [<class]]
[reagent.core :as r]
[teet.common.common-styles :as common-styles]
[teet.localization :refer [tr]]
[teet.theme.itemlist-styles :as itemlist-styles]
[teet.theme.theme-colors :as theme-colors]
[teet.ui.buttons :as buttons]
[teet.ui.common :as common]
[teet.ui.icons :as icons]
[teet.ui.material-ui :refer [List ListItem ListItemIcon
ListItemSecondaryAction Divider
FormControlLabel Checkbox]]
[teet.ui.progress :as progress]
[teet.ui.typography :refer [Heading2 Heading3 SectionHeading DataLabel] :as typography]
[teet.ui.util :as util]
[teet.util.collection :as uc]))
(defn ListHeading
[{:keys [title subtitle action variant]
:or {variant :primary}}]
[:div {:class (<class itemlist-styles/heading variant)}
(case variant
:primary [Heading2 title]
:secondary [Heading3 title]
:tertiary [:b title])
(when action
[:div {:class (<class itemlist-styles/heading-action)}
action])
(when subtitle
[DataLabel subtitle])])
(defn ItemList
[{:keys [title subtitle variant class]
:or {variant :primary}} & children]
[:div (when class
{:class class})
(when title
[ListHeading {:title title
:subtitle subtitle
:variant variant}])
(util/with-keys children)])
(defn ProgressList
[titles items]
(let [success (count (filterv #(= (:status %) :success) items))
fails (count (filterv #(= (:status %) :fail) items))
in-progress (count (filterv #(= (:status %) :in-progress) items))]
[ItemList
titles
[:div {:style {:display :flex}}
[:div {:style {:flex 1}}
[List
{:dense false}
(for [item items]
^{:key (:name item)}
[:<>
[ListItem {:button true
:component "a"
:href (:link item)}
[ListItemIcon
(case (:status item)
:success
[icons/navigation-check {:style {:color theme-colors/success}}]
:fail
[icons/alert-error-outline {:color :error}]
[icons/content-remove])]
[SectionHeading (:name item)]
[ListItemSecondaryAction
[ListItemIcon {:style {:justify-content :flex-end}}
[icons/navigation-chevron-right {:color :secondary}]]]]
[Divider]])]]
[:div {:style {:text-align :center
:margin "0 0.5rem"}}
[progress/circle
{:radius 70 :stroke 9
:defs [[:pattern {:id "progress"
:x 0 :y 0
:width 9
:height 9
:patternUnits "userSpaceOnUse"
:patternTransform "rotate(-45 0 0)"}
[:rect {:x 0 :y 0 :width 9 :height 9 :fill theme-colors/success}]
[:line {:x1 4 :y1 0
:x2 4 :y2 9
:style {:stroke "lightgray" :stroke-width 4}}]]]
:slices [[success theme-colors/success]
[fails "red"]
[in-progress "url(#progress)"]]}]]]]))
(defn LinkList
[titles items on-click-fn]
[ItemList
titles
[:div {:style {:margin-top "1rem"}}
[:ul {:style {:list-style "none"
:margin 0
:padding 0}}
(for [item items]
^{:key (:name item)}
[:li
[common/Link {:href (:link item)
:onClick #(on-click-fn item)}
(:name item)]])]]])
(defn Item [{:keys [label]} value]
[:div
[:b (str label ": ")]
value])
(defn checkbox-item [{:keys [checked? value on-change on-mouse-enter on-mouse-leave] :as _item}]
[FormControlLabel
(uc/without-nils {:class (<class itemlist-styles/checkbox-container)
:on-mouse-enter on-mouse-enter
:on-mouse-leave on-mouse-leave
:label (r/as-element [:span
{:class (<class itemlist-styles/checkbox-label checked?)}
value])
:control (r/as-element [Checkbox {:checked checked?
:value value
:class (<class itemlist-styles/layer-checkbox)
:color :primary
:on-change on-change}])})])
(defn checkbox-list
([items] (checkbox-list {} items))
([{:keys [key on-select-all on-deselect-all actions]
:or {key :id}}
items]
[:div {:class (<class itemlist-styles/checkbox-list-contents)}
(when (and on-select-all (every? (complement :checked?) items))
[buttons/link-button {:class (<class itemlist-styles/checkbox-list-link)
:on-click on-select-all}
(tr [:common :select-all])])
(when (and on-deselect-all (some :checked? items))
[buttons/link-button {:class (<class itemlist-styles/checkbox-list-link)
:on-click on-deselect-all}
(tr [:common :deselect-all])])
(when actions
(util/with-keys
actions))
(doall
(for [item items]
^{:key (key item)}
[checkbox-item item]))]))
(defn white-link-list
[items]
[:ul {:style {:padding-left 0}}
(doall
(for [{:keys [key href on-click title selected?]} items]
^{:key key}
[:li {:class (<class itemlist-styles/white-link-item-style)}
[:a {:class (<class common-styles/white-link-style selected?)
:href href
:on-click on-click} title]]))])
(defn gray-bg-list
([list] (gray-bg-list {} list))
([{:keys [style class]
:or {style {:padding 0}}} list]
[:ul (merge {:style style}
(when class {:class class}))
(doall
(map-indexed
(fn [i {:keys [id primary-text secondary-text tertiary-text] :as _item}]
^{:key (or id i)}
[:li {:class (<class itemlist-styles/gray-bg-list-element)}
(when primary-text
[Heading3 primary-text])
(when secondary-text
[typography/Text secondary-text])
(when tertiary-text
[typography/Text tertiary-text])])
list))]))
| null | https://raw.githubusercontent.com/solita/mnt-teet/7a5124975ce1c7f3e7a7c55fe23257ca3f7b6411/app/frontend/src/cljs/teet/ui/itemlist.cljs | clojure | (ns teet.ui.itemlist
(:require [herb.core :refer [<class]]
[reagent.core :as r]
[teet.common.common-styles :as common-styles]
[teet.localization :refer [tr]]
[teet.theme.itemlist-styles :as itemlist-styles]
[teet.theme.theme-colors :as theme-colors]
[teet.ui.buttons :as buttons]
[teet.ui.common :as common]
[teet.ui.icons :as icons]
[teet.ui.material-ui :refer [List ListItem ListItemIcon
ListItemSecondaryAction Divider
FormControlLabel Checkbox]]
[teet.ui.progress :as progress]
[teet.ui.typography :refer [Heading2 Heading3 SectionHeading DataLabel] :as typography]
[teet.ui.util :as util]
[teet.util.collection :as uc]))
(defn ListHeading
[{:keys [title subtitle action variant]
:or {variant :primary}}]
[:div {:class (<class itemlist-styles/heading variant)}
(case variant
:primary [Heading2 title]
:secondary [Heading3 title]
:tertiary [:b title])
(when action
[:div {:class (<class itemlist-styles/heading-action)}
action])
(when subtitle
[DataLabel subtitle])])
(defn ItemList
[{:keys [title subtitle variant class]
:or {variant :primary}} & children]
[:div (when class
{:class class})
(when title
[ListHeading {:title title
:subtitle subtitle
:variant variant}])
(util/with-keys children)])
(defn ProgressList
[titles items]
(let [success (count (filterv #(= (:status %) :success) items))
fails (count (filterv #(= (:status %) :fail) items))
in-progress (count (filterv #(= (:status %) :in-progress) items))]
[ItemList
titles
[:div {:style {:display :flex}}
[:div {:style {:flex 1}}
[List
{:dense false}
(for [item items]
^{:key (:name item)}
[:<>
[ListItem {:button true
:component "a"
:href (:link item)}
[ListItemIcon
(case (:status item)
:success
[icons/navigation-check {:style {:color theme-colors/success}}]
:fail
[icons/alert-error-outline {:color :error}]
[icons/content-remove])]
[SectionHeading (:name item)]
[ListItemSecondaryAction
[ListItemIcon {:style {:justify-content :flex-end}}
[icons/navigation-chevron-right {:color :secondary}]]]]
[Divider]])]]
[:div {:style {:text-align :center
:margin "0 0.5rem"}}
[progress/circle
{:radius 70 :stroke 9
:defs [[:pattern {:id "progress"
:x 0 :y 0
:width 9
:height 9
:patternUnits "userSpaceOnUse"
:patternTransform "rotate(-45 0 0)"}
[:rect {:x 0 :y 0 :width 9 :height 9 :fill theme-colors/success}]
[:line {:x1 4 :y1 0
:x2 4 :y2 9
:style {:stroke "lightgray" :stroke-width 4}}]]]
:slices [[success theme-colors/success]
[fails "red"]
[in-progress "url(#progress)"]]}]]]]))
(defn LinkList
[titles items on-click-fn]
[ItemList
titles
[:div {:style {:margin-top "1rem"}}
[:ul {:style {:list-style "none"
:margin 0
:padding 0}}
(for [item items]
^{:key (:name item)}
[:li
[common/Link {:href (:link item)
:onClick #(on-click-fn item)}
(:name item)]])]]])
(defn Item [{:keys [label]} value]
[:div
[:b (str label ": ")]
value])
(defn checkbox-item [{:keys [checked? value on-change on-mouse-enter on-mouse-leave] :as _item}]
[FormControlLabel
(uc/without-nils {:class (<class itemlist-styles/checkbox-container)
:on-mouse-enter on-mouse-enter
:on-mouse-leave on-mouse-leave
:label (r/as-element [:span
{:class (<class itemlist-styles/checkbox-label checked?)}
value])
:control (r/as-element [Checkbox {:checked checked?
:value value
:class (<class itemlist-styles/layer-checkbox)
:color :primary
:on-change on-change}])})])
(defn checkbox-list
([items] (checkbox-list {} items))
([{:keys [key on-select-all on-deselect-all actions]
:or {key :id}}
items]
[:div {:class (<class itemlist-styles/checkbox-list-contents)}
(when (and on-select-all (every? (complement :checked?) items))
[buttons/link-button {:class (<class itemlist-styles/checkbox-list-link)
:on-click on-select-all}
(tr [:common :select-all])])
(when (and on-deselect-all (some :checked? items))
[buttons/link-button {:class (<class itemlist-styles/checkbox-list-link)
:on-click on-deselect-all}
(tr [:common :deselect-all])])
(when actions
(util/with-keys
actions))
(doall
(for [item items]
^{:key (key item)}
[checkbox-item item]))]))
(defn white-link-list
[items]
[:ul {:style {:padding-left 0}}
(doall
(for [{:keys [key href on-click title selected?]} items]
^{:key key}
[:li {:class (<class itemlist-styles/white-link-item-style)}
[:a {:class (<class common-styles/white-link-style selected?)
:href href
:on-click on-click} title]]))])
(defn gray-bg-list
([list] (gray-bg-list {} list))
([{:keys [style class]
:or {style {:padding 0}}} list]
[:ul (merge {:style style}
(when class {:class class}))
(doall
(map-indexed
(fn [i {:keys [id primary-text secondary-text tertiary-text] :as _item}]
^{:key (or id i)}
[:li {:class (<class itemlist-styles/gray-bg-list-element)}
(when primary-text
[Heading3 primary-text])
(when secondary-text
[typography/Text secondary-text])
(when tertiary-text
[typography/Text tertiary-text])])
list))]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.