_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
521b39314b135a3c0b09d0f2e30f4c78dca29fb39b6a417691e4bc3c67121d49
lasp-lang/lasp
lasp_storage_backend.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2014 SyncFree Consortium . All Rights Reserved . %% 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(lasp_storage_backend). -author("Christopher Meiklejohn <>"). -include("lasp.hrl"). %% Behavior -callback start_link(atom())-> {ok, store()} | ignore | {error, term()}. -callback put(store(), id(), variable()) -> ok | {error, atom()}. -callback get(store(), id()) -> {ok, variable()} | {error, not_found} | {error, atom()}. -callback update(store(), id(), function()) -> {ok, any()} | error | {error, atom()}. -callback update_all(store(), function()) -> {ok, any()} | error | {error, atom()}. -callback fold(store(), function(), term()) -> {ok, term()}. -callback reset(store()) -> ok. -behaviour(gen_server). %% API -export([start_link/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% lasp_storage_backend callbacks -export([put/3, update/3, update_all/2, get/2, reset/1, fold/3]). -record(state, {backend, store}). %%%=================================================================== %%% API %%%=================================================================== %% @doc Start and link to calling process. start_link(Identifier) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Identifier], []). %%%=================================================================== %%% lasp_storage_backend callbacks %%%=================================================================== %% @doc Write a record to the backend. put(Ref, Id, Record) -> gen_server:call(Ref, {put, Id, Record}, infinity). %% @doc In-place update given a mutation function. update(Ref, Id, Function) -> gen_server:call(Ref, {update, Id, Function}, infinity). %% @doc Update all objects given a mutation function. update_all(Ref, Function) -> gen_server:call(Ref, {update_all, Function}, infinity). %% @doc Retrieve a record from the backend. get(Ref, Id) -> gen_server:call(Ref, {get, Id}, infinity). @doc Fold operation . fold(Ref, Function, Acc) -> gen_server:call(Ref, {fold, Function, Acc}, infinity). %% @doc Reset all application state. reset(Ref) -> gen_server:call(Ref, reset, infinity). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== @private init([Identifier]) -> %% Select the appropriate backend. Backend = backend(), %% Schedule waiting threads pruning. schedule_waiting_threads_pruning(), %% Start the storage backend. case Backend:start_link(Identifier) of {ok, StorePid} -> _ = lager:info("Backend ~p initialized: ~p", [Backend, StorePid]), {ok, #state{backend=Backend, store=StorePid}}; {error, {already_started, StorePid}} -> _ = lager:info("Backend ~p initialized: ~p", [Backend, StorePid]), {ok, #state{backend=Backend, store=StorePid}}; {error, Reason} -> _ = lager:error("Failed to initialize backend ~p: ~p", [Backend, Reason]), {stop, Reason} end. %% Proxy calls to the storage instance. handle_call({get, Id}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {get, Id}, infinity), {reply, Result, State}; handle_call({put, Id, Record}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {put, Id, Record}, infinity), {reply, Result, State}; handle_call({update, Id, Function}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {update, Id, Function}, infinity), {reply, Result, State}; handle_call({update_all, Function}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {update_all, Function}, infinity), {reply, Result, State}; handle_call({fold, Function, Acc0}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {fold, Function, Acc0}, infinity), {reply, Result, State}; handle_call(reset, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, reset, infinity), {reply, Result, State}; handle_call(Msg, _From, State) -> _ = lager:warning("Unhandled call messages: ~p", [Msg]), {reply, ok, State}. @private handle_cast(Msg, State) -> _ = lager:warning("Unhandled cast messages: ~p", [Msg]), {noreply, State}. @private handle_info(waiting_threads_pruning, #state{store=Store}=State) -> Mutator = fun({Id, #dv{waiting_threads=WaitingThreads0}=Value}) -> GCFun = fun({_, _, From, _, _}) -> case is_pid(From) of true -> is_process_alive(From); false -> true end end, WaitingThreads = lists:filter(GCFun, WaitingThreads0), {Value#dv{waiting_threads=WaitingThreads}, Id} end, gen_server:call(Store, {update_all, Mutator}, infinity), %% Schedule next message. schedule_waiting_threads_pruning(), {noreply, State}; handle_info(Msg, State) -> _ = lager:warning("Unhandled info messages: ~p", [Msg]), {noreply, State}. @private terminate(_Reason, _State) -> ok. @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== -ifdef(TEST). %% @doc Use the memory backend for tests. backend() -> lasp_ets_storage_backend. -else. %% @doc Use configured backend. backend() -> lasp_config:get(storage_backend, lasp_ets_storage_backend). -endif. @private schedule_waiting_threads_pruning() -> timer:send_after(10000, waiting_threads_pruning).
null
https://raw.githubusercontent.com/lasp-lang/lasp/1701c8af77e193738dfc4ef4a5a703d205da41a1/src/lasp_storage_backend.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. ------------------------------------------------------------------- Behavior API gen_server callbacks lasp_storage_backend callbacks =================================================================== API =================================================================== @doc Start and link to calling process. =================================================================== lasp_storage_backend callbacks =================================================================== @doc Write a record to the backend. @doc In-place update given a mutation function. @doc Update all objects given a mutation function. @doc Retrieve a record from the backend. @doc Reset all application state. =================================================================== gen_server callbacks =================================================================== Select the appropriate backend. Schedule waiting threads pruning. Start the storage backend. Proxy calls to the storage instance. Schedule next message. =================================================================== =================================================================== @doc Use the memory backend for tests. @doc Use configured backend.
Copyright ( c ) 2014 SyncFree Consortium . All Rights Reserved . 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(lasp_storage_backend). -author("Christopher Meiklejohn <>"). -include("lasp.hrl"). -callback start_link(atom())-> {ok, store()} | ignore | {error, term()}. -callback put(store(), id(), variable()) -> ok | {error, atom()}. -callback get(store(), id()) -> {ok, variable()} | {error, not_found} | {error, atom()}. -callback update(store(), id(), function()) -> {ok, any()} | error | {error, atom()}. -callback update_all(store(), function()) -> {ok, any()} | error | {error, atom()}. -callback fold(store(), function(), term()) -> {ok, term()}. -callback reset(store()) -> ok. -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([put/3, update/3, update_all/2, get/2, reset/1, fold/3]). -record(state, {backend, store}). start_link(Identifier) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Identifier], []). put(Ref, Id, Record) -> gen_server:call(Ref, {put, Id, Record}, infinity). update(Ref, Id, Function) -> gen_server:call(Ref, {update, Id, Function}, infinity). update_all(Ref, Function) -> gen_server:call(Ref, {update_all, Function}, infinity). get(Ref, Id) -> gen_server:call(Ref, {get, Id}, infinity). @doc Fold operation . fold(Ref, Function, Acc) -> gen_server:call(Ref, {fold, Function, Acc}, infinity). reset(Ref) -> gen_server:call(Ref, reset, infinity). @private init([Identifier]) -> Backend = backend(), schedule_waiting_threads_pruning(), case Backend:start_link(Identifier) of {ok, StorePid} -> _ = lager:info("Backend ~p initialized: ~p", [Backend, StorePid]), {ok, #state{backend=Backend, store=StorePid}}; {error, {already_started, StorePid}} -> _ = lager:info("Backend ~p initialized: ~p", [Backend, StorePid]), {ok, #state{backend=Backend, store=StorePid}}; {error, Reason} -> _ = lager:error("Failed to initialize backend ~p: ~p", [Backend, Reason]), {stop, Reason} end. handle_call({get, Id}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {get, Id}, infinity), {reply, Result, State}; handle_call({put, Id, Record}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {put, Id, Record}, infinity), {reply, Result, State}; handle_call({update, Id, Function}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {update, Id, Function}, infinity), {reply, Result, State}; handle_call({update_all, Function}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {update_all, Function}, infinity), {reply, Result, State}; handle_call({fold, Function, Acc0}, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, {fold, Function, Acc0}, infinity), {reply, Result, State}; handle_call(reset, _From, #state{store=Store}=State) -> Result = gen_server:call(Store, reset, infinity), {reply, Result, State}; handle_call(Msg, _From, State) -> _ = lager:warning("Unhandled call messages: ~p", [Msg]), {reply, ok, State}. @private handle_cast(Msg, State) -> _ = lager:warning("Unhandled cast messages: ~p", [Msg]), {noreply, State}. @private handle_info(waiting_threads_pruning, #state{store=Store}=State) -> Mutator = fun({Id, #dv{waiting_threads=WaitingThreads0}=Value}) -> GCFun = fun({_, _, From, _, _}) -> case is_pid(From) of true -> is_process_alive(From); false -> true end end, WaitingThreads = lists:filter(GCFun, WaitingThreads0), {Value#dv{waiting_threads=WaitingThreads}, Id} end, gen_server:call(Store, {update_all, Mutator}, infinity), schedule_waiting_threads_pruning(), {noreply, State}; handle_info(Msg, State) -> _ = lager:warning("Unhandled info messages: ~p", [Msg]), {noreply, State}. @private terminate(_Reason, _State) -> ok. @private code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions -ifdef(TEST). backend() -> lasp_ets_storage_backend. -else. backend() -> lasp_config:get(storage_backend, lasp_ets_storage_backend). -endif. @private schedule_waiting_threads_pruning() -> timer:send_after(10000, waiting_threads_pruning).
c82d59005ee5b1ddd133c16b0c7450033e05d41803976e47ba43cce736cb4d75
zadean/xqerl
xqerl_config.erl
Copyright ( c ) 2018 - 2020 . SPDX - FileCopyrightText : 2022 % SPDX - License - Identifier : Apache-2.0 @doc xqerl_config Handles the configuration files for xqerl . -module(xqerl_config). %% ==================================================================== %% API functions %% ==================================================================== -export([normalize/1]). normalize(App) -> Config = application:get_all_env(App), normalize(App, Config). %% ==================================================================== Internal functions %% ==================================================================== normalize(A, [{log_file, H} | T]) -> application:set_env(A, logger, logger(H), [{persistent, true}]), normalize(A, T); normalize(A, [{code_dir, H} | T]) -> application:set_env(A, code_dir, make_absolute(H), [{persistent, true}]), normalize(A, T); normalize(A, [{data_dir, H} | T]) -> application:set_env(A, data_dir, make_absolute(H), [{persistent, true}]), normalize(A, T); normalize(A, [_ | T]) -> normalize(A, T); normalize(_, []) -> ok. make_absolute(RelFile) -> case filename:pathtype(RelFile) of absolute -> RelFile; _ -> filename:absname(RelFile) end. logger_handler(Name, Loc, Level, Domain, SingleLine, Template, Max) -> {handler, Name, logger_std_h, #{ config => #{type => Loc}, level => Level, filters => [ {filter, {fun logger_filters:domain/2, {log, equal, [Domain]}}}, {non_filter, {fun logger_filters:domain/2, {stop, not_equal, [Domain]}}} ], formatter => {logger_formatter, #{ legacy_header => false, single_line => SingleLine, template => Template, max_size => Max }} }}. logger(RelFile) -> AbsFile = make_absolute(RelFile), [ logger_handler( xqerl_handler, {file, AbsFile}, all, xqerl, true, [time, " [", level, "] ", mfa, "(", line, ") ", pid, ": ", msg, "\n"], %, 4000 ) logger_handler ( % trace_handler, standard_io, info, trace, false, % ["TRACE: ", msg, "\n"], unlimited) ].
null
https://raw.githubusercontent.com/zadean/xqerl/06c651ec832d0ac2b77bef92c1b4ab14d8da8883/src/xqerl_config.erl
erlang
==================================================================== API functions ==================================================================== ==================================================================== ==================================================================== , trace_handler, standard_io, info, trace, false, ["TRACE: ", msg, "\n"], unlimited)
Copyright ( c ) 2018 - 2020 . SPDX - FileCopyrightText : 2022 SPDX - License - Identifier : Apache-2.0 @doc xqerl_config Handles the configuration files for xqerl . -module(xqerl_config). -export([normalize/1]). normalize(App) -> Config = application:get_all_env(App), normalize(App, Config). Internal functions normalize(A, [{log_file, H} | T]) -> application:set_env(A, logger, logger(H), [{persistent, true}]), normalize(A, T); normalize(A, [{code_dir, H} | T]) -> application:set_env(A, code_dir, make_absolute(H), [{persistent, true}]), normalize(A, T); normalize(A, [{data_dir, H} | T]) -> application:set_env(A, data_dir, make_absolute(H), [{persistent, true}]), normalize(A, T); normalize(A, [_ | T]) -> normalize(A, T); normalize(_, []) -> ok. make_absolute(RelFile) -> case filename:pathtype(RelFile) of absolute -> RelFile; _ -> filename:absname(RelFile) end. logger_handler(Name, Loc, Level, Domain, SingleLine, Template, Max) -> {handler, Name, logger_std_h, #{ config => #{type => Loc}, level => Level, filters => [ {filter, {fun logger_filters:domain/2, {log, equal, [Domain]}}}, {non_filter, {fun logger_filters:domain/2, {stop, not_equal, [Domain]}}} ], formatter => {logger_formatter, #{ legacy_header => false, single_line => SingleLine, template => Template, max_size => Max }} }}. logger(RelFile) -> AbsFile = make_absolute(RelFile), [ logger_handler( xqerl_handler, {file, AbsFile}, all, xqerl, true, [time, " [", level, "] ", mfa, "(", line, ") ", pid, ": ", msg, "\n"], 4000 ) logger_handler ( ].
4d9424561fa031f2ee71ac7ca153ee0c00413b92ae5f8c05d83a5a2c6edbb6b0
TyOverby/mono
array_tests.ml
open Core open Core_bench let t1 = Bench.Test.create_indexed ~name:"ArrayCreateInt" ~args:[ 100; 200; 300; 400; 1000; 10000 ] (fun len -> Staged.stage (fun () -> for _ = 0 to 2000 do ignore (Array.create ~len 0) done)) ;; let tests = [ t1 ] let command = Bench.make_command tests
null
https://raw.githubusercontent.com/TyOverby/mono/8d6b3484d5db63f2f5472c7367986ea30290764d/vendor/janestreet-core_bench/test/array_tests.ml
ocaml
open Core open Core_bench let t1 = Bench.Test.create_indexed ~name:"ArrayCreateInt" ~args:[ 100; 200; 300; 400; 1000; 10000 ] (fun len -> Staged.stage (fun () -> for _ = 0 to 2000 do ignore (Array.create ~len 0) done)) ;; let tests = [ t1 ] let command = Bench.make_command tests
1ec14cb5a6be725c7733a1002532bdbd5260de95772a6da6bde22f9ae526e020
philnguyen/soft-contract
case-lambdas.rkt
#lang racket (define f (case-lambda [(x) x] [(x y) (+ x y)] [(x y . z) (string-join (cons (number->string x) ; don't have real `list*` yet (cons (number->string y) (map number->string z))) " + ")])) (define f1 (f 42)) (define f2 (f 43 44)) (define f3 (f 45 46 47)) (provide (contract-out [f (parametric->/c (α) (case-> [α . -> . α] [integer? . -> . integer?] [integer? integer? #:rest integer? . -> . string?]))] [f1 number?] [f2 number?] [f3 string?]))
null
https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/safe/issues/case-lambdas.rkt
racket
don't have real `list*` yet
#lang racket (define f (case-lambda [(x) x] [(x y) (+ x y)] [(x y . z) (cons (number->string y) (map number->string z))) " + ")])) (define f1 (f 42)) (define f2 (f 43 44)) (define f3 (f 45 46 47)) (provide (contract-out [f (parametric->/c (α) (case-> [α . -> . α] [integer? . -> . integer?] [integer? integer? #:rest integer? . -> . string?]))] [f1 number?] [f2 number?] [f3 string?]))
92f6b8dd2974f1540f364e10a8dff108f70f5aad2a834f815ec17f24e318d78a
mixphix/toolbox
Toolbox.hs
-- | -- Module : Data.Time.Format.Toolbox Copyright : ( c ) 2021 -- License : BSD3 (see the file LICENSE) -- Maintainer : -- -- Utility functions on top of 'Data.Time.Format'. -- -- This module re-exports the above module, so modules need only import 'Data.Time.Format.Toolbox'. module Data.Time.Format.Toolbox ( -- * Formatting mdy, ymd, shortMonthDayYear, longMonthDayYear, time24, time24s, time24ps, time12H, time12h, time12Hs, time12hs, ymd24, ymd24s, ymd24ps, ymd12H, ymd12h, ymd12Hs, parseMdy12hs, parseYmd12Hs, ymd12hs, mdy24, mdy24s, mdy24ps, mdy12H, mdy12h, mdy12Hs, mdy12hs, -- * Parsing parseMdy, parseYmd, parseShortMonthDayYear, parseLongMonthDayYear, parseTime24, parseTime24s, parseTime24ps, parseTime12H, parseTime12h, parseTime12Hs, parseTime12hs, parseYmd24, parseYmd24s, parseYmd24ps, parseYmd12H, parseYmd12h, parseYmd12hs, parseMdy24, parseMdy24s, parseMdy24ps, parseMdy12H, parseMdy12h, parseMdy12Hs, -- * Re-exports module Data.Time.Format, ) where import Data.Function.Toolbox ((.:)) import Data.String (IsString (..)) import Data.Time import Data.Time.Format -- | Format according to the 'defaultTimeLocale'. fmtdef :: (FormatTime t, IsString a) => String -> t -> a fmtdef = fromString .: formatTime defaultTimeLocale -- | Format as @MM\/DD\/YYYY@. mdy :: (FormatTime t, IsString a) => t -> a mdy = fmtdef "%m/%d/%Y" | Format as @YYYY - MM - DD@. ymd :: (FormatTime t, IsString a) => t -> a ymd = fmtdef "%F" | Format as @M DD YYYY@ where @M@ is the abbreviated name of the month and @DD@ is the day of the month zero - padded to two digits . -- > shortMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " Sep 01 1993 " shortMonthDayYear :: (FormatTime t, IsString a) => t -> a shortMonthDayYear = fmtdef "%b %0e %Y" | Format as @M DD YYYY@ where @M@ is the full name of the month and @DD@ is the unpadded day of the month . -- > longMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " September 1 , 1993 " longMonthDayYear :: (FormatTime t, IsString a) => t -> a longMonthDayYear = fmtdef "%B %-e, %Y" | Format as @hh : mm@ , where @hh@ is in the range @[00 .. 23]@. -- > time24 ( TimeOfDay 15 34 56 ) = = " 15:34 " time24 :: (FormatTime t, IsString a) => t -> a time24 = fmtdef "%R" | Format as @hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. -- > time24s ( TimeOfDay 15 34 56 ) = = " 15:34:56 " time24s :: (FormatTime t, IsString a) => t -> a time24s = fmtdef "%T" | Format as @hh : : ss(.pppppppppppp)@ , where @hh@ is in the range @[00 .. 23]@. -- > time24ps ( TimeOfDay 15 34 56.3894324564719999 ) = = " 15:34:56.389432456471 " time24ps :: (FormatTime t, IsString a) => t -> a time24ps = fmtdef "%T%Q" | Format as @hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. time12H :: (FormatTime t, IsString a) => t -> a time12H = fmtdef "%I:%M %p" | Format as @hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. time12h :: (FormatTime t, IsString a) => t -> a time12h = fmtdef "%I:%M %P" | Format as @hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. time12Hs :: (FormatTime t, IsString a) => t -> a time12Hs = fmtdef "%I:%M:%S %p" | Format as @hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. time12hs :: (FormatTime t, IsString a) => t -> a time12hs = fmtdef "%I:%M:%S %P" | Format as @YYYY - MM - DD hh : mm@ , where @hh@ is in the range @[00 .. 23]@. ymd24 :: (FormatTime t, IsString a) => t -> a ymd24 = fmtdef "%F %R" | Format as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. ymd24s :: (FormatTime t, IsString a) => t -> a ymd24s = fmtdef "%F %T" | Format as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. ymd24ps :: (FormatTime t, IsString a) => t -> a ymd24ps = fmtdef "%F %T%Q" | Format as @YYYY - MM - DD hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. ymd12H :: (FormatTime t, IsString a) => t -> a ymd12H = fmtdef "%F %I:%M %p" | Format as @YYYY - MM - DD hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. ymd12h :: (FormatTime t, IsString a) => t -> a ymd12h = fmtdef "%F %I:%M %P" | Format as @YYYY - MM - DD hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. ymd12Hs :: (FormatTime t, IsString a) => t -> a ymd12Hs = fmtdef "%F %I:%M:%S %p" | Format as @YYYY - MM - DD hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. ymd12hs :: (FormatTime t, IsString a) => t -> a ymd12hs = fmtdef "%F %I:%M:%S %P" | Format as @MM / DD / YYYY hh : mm@ , where @hh@ is in the range @[00 .. 23]@. mdy24 :: (FormatTime t, IsString a) => t -> a mdy24 = fmtdef "%m/%d/%Y %R" | Format as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. mdy24s :: (FormatTime t, IsString a) => t -> a mdy24s = fmtdef "%m/%d/%Y %T" | Format as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. mdy24ps :: (FormatTime t, IsString a) => t -> a mdy24ps = fmtdef "%m/%d/%Y %T%Q" | Format as @MM / DD / YYYY hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. mdy12H :: (FormatTime t, IsString a) => t -> a mdy12H = fmtdef "%m/%d/%Y %I:%M %p" | Format as @MM / DD / YYYY hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. mdy12h :: (FormatTime t, IsString a) => t -> a mdy12h = fmtdef "%m/%d/%Y %I:%M %P" | Format as @MM / DD / YYYY hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. mdy12Hs :: (FormatTime t, IsString a) => t -> a mdy12Hs = fmtdef "%m/%d/%Y %I:%M:%S %p" | Format as @MM / DD / YYYY hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. mdy12hs :: (FormatTime t, IsString a) => t -> a mdy12hs = fmtdef "%m/%d/%Y %I:%M:%S %P" | Parse according to the ' defaultTimeLocale ' . prsdef :: (ParseTime t) => String -> String -> Maybe t prsdef = parseTimeM False defaultTimeLocale -- | Parse as @MM\/DD\/YYYY@. parseMdy :: (ParseTime t) => String -> Maybe t parseMdy = prsdef "%m/%d/%Y" | Parse as @YYYY - MM - DD@. parseYmd :: (ParseTime t) => String -> Maybe t parseYmd = prsdef "%F" | Parse as @M DD YYYY@ where @M@ is the abbreviated name of the month and @DD@ is the day of the month zero - padded to two digits . -- > shortMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " Sep 01 1993 " parseShortMonthDayYear :: (ParseTime t) => String -> Maybe t parseShortMonthDayYear = prsdef "%b %0e %Y" | Parse as @M DD YYYY@ where @M@ is the full name of the month and @DD@ is the unpadded day of the month . -- > longMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " September 1 , 1993 " parseLongMonthDayYear :: (ParseTime t) => String -> Maybe t parseLongMonthDayYear = prsdef "%B %-e, %Y" | Parse as @hh : mm@ , where @hh@ is in the range @[00 .. 23]@. -- > time24 ( TimeOfDay 15 34 56 ) = = " 15:34 " parseTime24 :: (ParseTime t) => String -> Maybe t parseTime24 = prsdef "%R" | Parse as @hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. -- > time24s ( TimeOfDay 15 34 56 ) = = " 15:34:56 " parseTime24s :: (ParseTime t) => String -> Maybe t parseTime24s = prsdef "%T" | Parse as @hh : : ss(.pppppppppppp)@ , where @hh@ is in the range @[00 .. 23]@. -- > time24ps ( TimeOfDay 15 34 56.3894324564719999 ) = = " 15:34:56.389432456471 " parseTime24ps :: (ParseTime t) => String -> Maybe t parseTime24ps = prsdef "%T%Q" | Parse as @hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12H :: (ParseTime t) => String -> Maybe t parseTime12H = prsdef "%I:%M %p" | Parse as @hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12h :: (ParseTime t) => String -> Maybe t parseTime12h = prsdef "%I:%M %P" | Parse as @hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12Hs :: (ParseTime t) => String -> Maybe t parseTime12Hs = prsdef "%I:%M:%S %p" | Parse as @hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12hs :: (ParseTime t) => String -> Maybe t parseTime12hs = prsdef "%I:%M:%S %P" | Parse as @YYYY - MM - DD hh : mm@ , where @hh@ is in the range @[00 .. 23]@. parseYmd24 :: (ParseTime t) => String -> Maybe t parseYmd24 = prsdef "%F %R" | Parse as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseYmd24s :: (ParseTime t) => String -> Maybe t parseYmd24s = prsdef "%F %T" | Parse as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseYmd24ps :: (ParseTime t) => String -> Maybe t parseYmd24ps = prsdef "%F %T%Q" | Parse as @YYYY - MM - DD hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12H :: (ParseTime t) => String -> Maybe t parseYmd12H = prsdef "%F %I:%M %p" | Parse as @YYYY - MM - DD hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12h :: (ParseTime t) => String -> Maybe t parseYmd12h = prsdef "%F %I:%M %P" | Parse as @YYYY - MM - DD hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12Hs :: (ParseTime t) => String -> Maybe t parseYmd12Hs = prsdef "%F %I:%M:%S %p" | Parse as @YYYY - MM - DD hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12hs :: (ParseTime t) => String -> Maybe t parseYmd12hs = prsdef "%F %I:%M:%S %P" | Parse as @MM / DD / YYYY hh : mm@ , where @hh@ is in the range @[00 .. 23]@. parseMdy24 :: (ParseTime t) => String -> Maybe t parseMdy24 = prsdef "%m/%d/%Y %R" | Parse as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseMdy24s :: (ParseTime t) => String -> Maybe t parseMdy24s = prsdef "%m/%d/%Y %T" | Parse as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseMdy24ps :: (ParseTime t) => String -> Maybe t parseMdy24ps = prsdef "%m/%d/%Y %T%Q" | Parse as @MM / DD / YYYY hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12H :: (ParseTime t) => String -> Maybe t parseMdy12H = prsdef "%m/%d/%Y %I:%M %p" | Parse as @MM / DD / YYYY hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12h :: (ParseTime t) => String -> Maybe t parseMdy12h = prsdef "%m/%d/%Y %I:%M %P" | Parse as @MM / DD / YYYY hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12Hs :: (ParseTime t) => String -> Maybe t parseMdy12Hs = prsdef "%m/%d/%Y %I:%M:%S %p" | Parse as @MM / DD / YYYY hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12hs :: (ParseTime t) => String -> Maybe t parseMdy12hs = prsdef "%m/%d/%Y %I:%M:%S %P"
null
https://raw.githubusercontent.com/mixphix/toolbox/9579422c75112c3108b9cfbc34d6bea21350ca8f/src/Data/Time/Format/Toolbox.hs
haskell
| Module : Data.Time.Format.Toolbox License : BSD3 (see the file LICENSE) Maintainer : Utility functions on top of 'Data.Time.Format'. This module re-exports the above module, so modules need only import 'Data.Time.Format.Toolbox'. * Formatting * Parsing * Re-exports | Format according to the 'defaultTimeLocale'. | Format as @MM\/DD\/YYYY@. | Parse as @MM\/DD\/YYYY@.
Copyright : ( c ) 2021 module Data.Time.Format.Toolbox ( mdy, ymd, shortMonthDayYear, longMonthDayYear, time24, time24s, time24ps, time12H, time12h, time12Hs, time12hs, ymd24, ymd24s, ymd24ps, ymd12H, ymd12h, ymd12Hs, parseMdy12hs, parseYmd12Hs, ymd12hs, mdy24, mdy24s, mdy24ps, mdy12H, mdy12h, mdy12Hs, mdy12hs, parseMdy, parseYmd, parseShortMonthDayYear, parseLongMonthDayYear, parseTime24, parseTime24s, parseTime24ps, parseTime12H, parseTime12h, parseTime12Hs, parseTime12hs, parseYmd24, parseYmd24s, parseYmd24ps, parseYmd12H, parseYmd12h, parseYmd12hs, parseMdy24, parseMdy24s, parseMdy24ps, parseMdy12H, parseMdy12h, parseMdy12Hs, module Data.Time.Format, ) where import Data.Function.Toolbox ((.:)) import Data.String (IsString (..)) import Data.Time import Data.Time.Format fmtdef :: (FormatTime t, IsString a) => String -> t -> a fmtdef = fromString .: formatTime defaultTimeLocale mdy :: (FormatTime t, IsString a) => t -> a mdy = fmtdef "%m/%d/%Y" | Format as @YYYY - MM - DD@. ymd :: (FormatTime t, IsString a) => t -> a ymd = fmtdef "%F" | Format as @M DD YYYY@ where @M@ is the abbreviated name of the month and @DD@ is the day of the month zero - padded to two digits . > shortMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " Sep 01 1993 " shortMonthDayYear :: (FormatTime t, IsString a) => t -> a shortMonthDayYear = fmtdef "%b %0e %Y" | Format as @M DD YYYY@ where @M@ is the full name of the month and @DD@ is the unpadded day of the month . > longMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " September 1 , 1993 " longMonthDayYear :: (FormatTime t, IsString a) => t -> a longMonthDayYear = fmtdef "%B %-e, %Y" | Format as @hh : mm@ , where @hh@ is in the range @[00 .. 23]@. > time24 ( TimeOfDay 15 34 56 ) = = " 15:34 " time24 :: (FormatTime t, IsString a) => t -> a time24 = fmtdef "%R" | Format as @hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. > time24s ( TimeOfDay 15 34 56 ) = = " 15:34:56 " time24s :: (FormatTime t, IsString a) => t -> a time24s = fmtdef "%T" | Format as @hh : : ss(.pppppppppppp)@ , where @hh@ is in the range @[00 .. 23]@. > time24ps ( TimeOfDay 15 34 56.3894324564719999 ) = = " 15:34:56.389432456471 " time24ps :: (FormatTime t, IsString a) => t -> a time24ps = fmtdef "%T%Q" | Format as @hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. time12H :: (FormatTime t, IsString a) => t -> a time12H = fmtdef "%I:%M %p" | Format as @hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. time12h :: (FormatTime t, IsString a) => t -> a time12h = fmtdef "%I:%M %P" | Format as @hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. time12Hs :: (FormatTime t, IsString a) => t -> a time12Hs = fmtdef "%I:%M:%S %p" | Format as @hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. time12hs :: (FormatTime t, IsString a) => t -> a time12hs = fmtdef "%I:%M:%S %P" | Format as @YYYY - MM - DD hh : mm@ , where @hh@ is in the range @[00 .. 23]@. ymd24 :: (FormatTime t, IsString a) => t -> a ymd24 = fmtdef "%F %R" | Format as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. ymd24s :: (FormatTime t, IsString a) => t -> a ymd24s = fmtdef "%F %T" | Format as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. ymd24ps :: (FormatTime t, IsString a) => t -> a ymd24ps = fmtdef "%F %T%Q" | Format as @YYYY - MM - DD hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. ymd12H :: (FormatTime t, IsString a) => t -> a ymd12H = fmtdef "%F %I:%M %p" | Format as @YYYY - MM - DD hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. ymd12h :: (FormatTime t, IsString a) => t -> a ymd12h = fmtdef "%F %I:%M %P" | Format as @YYYY - MM - DD hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. ymd12Hs :: (FormatTime t, IsString a) => t -> a ymd12Hs = fmtdef "%F %I:%M:%S %p" | Format as @YYYY - MM - DD hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. ymd12hs :: (FormatTime t, IsString a) => t -> a ymd12hs = fmtdef "%F %I:%M:%S %P" | Format as @MM / DD / YYYY hh : mm@ , where @hh@ is in the range @[00 .. 23]@. mdy24 :: (FormatTime t, IsString a) => t -> a mdy24 = fmtdef "%m/%d/%Y %R" | Format as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. mdy24s :: (FormatTime t, IsString a) => t -> a mdy24s = fmtdef "%m/%d/%Y %T" | Format as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. mdy24ps :: (FormatTime t, IsString a) => t -> a mdy24ps = fmtdef "%m/%d/%Y %T%Q" | Format as @MM / DD / YYYY hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. mdy12H :: (FormatTime t, IsString a) => t -> a mdy12H = fmtdef "%m/%d/%Y %I:%M %p" | Format as @MM / DD / YYYY hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. mdy12h :: (FormatTime t, IsString a) => t -> a mdy12h = fmtdef "%m/%d/%Y %I:%M %P" | Format as @MM / DD / YYYY hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. mdy12Hs :: (FormatTime t, IsString a) => t -> a mdy12Hs = fmtdef "%m/%d/%Y %I:%M:%S %p" | Format as @MM / DD / YYYY hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. mdy12hs :: (FormatTime t, IsString a) => t -> a mdy12hs = fmtdef "%m/%d/%Y %I:%M:%S %P" | Parse according to the ' defaultTimeLocale ' . prsdef :: (ParseTime t) => String -> String -> Maybe t prsdef = parseTimeM False defaultTimeLocale parseMdy :: (ParseTime t) => String -> Maybe t parseMdy = prsdef "%m/%d/%Y" | Parse as @YYYY - MM - DD@. parseYmd :: (ParseTime t) => String -> Maybe t parseYmd = prsdef "%F" | Parse as @M DD YYYY@ where @M@ is the abbreviated name of the month and @DD@ is the day of the month zero - padded to two digits . > shortMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " Sep 01 1993 " parseShortMonthDayYear :: (ParseTime t) => String -> Maybe t parseShortMonthDayYear = prsdef "%b %0e %Y" | Parse as @M DD YYYY@ where @M@ is the full name of the month and @DD@ is the unpadded day of the month . > longMonthDayYear ( read " 1993 - 09 - 01 " : : Day ) = = " September 1 , 1993 " parseLongMonthDayYear :: (ParseTime t) => String -> Maybe t parseLongMonthDayYear = prsdef "%B %-e, %Y" | Parse as @hh : mm@ , where @hh@ is in the range @[00 .. 23]@. > time24 ( TimeOfDay 15 34 56 ) = = " 15:34 " parseTime24 :: (ParseTime t) => String -> Maybe t parseTime24 = prsdef "%R" | Parse as @hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. > time24s ( TimeOfDay 15 34 56 ) = = " 15:34:56 " parseTime24s :: (ParseTime t) => String -> Maybe t parseTime24s = prsdef "%T" | Parse as @hh : : ss(.pppppppppppp)@ , where @hh@ is in the range @[00 .. 23]@. > time24ps ( TimeOfDay 15 34 56.3894324564719999 ) = = " 15:34:56.389432456471 " parseTime24ps :: (ParseTime t) => String -> Maybe t parseTime24ps = prsdef "%T%Q" | Parse as @hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12H :: (ParseTime t) => String -> Maybe t parseTime12H = prsdef "%I:%M %p" | Parse as @hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12h :: (ParseTime t) => String -> Maybe t parseTime12h = prsdef "%I:%M %P" | Parse as @hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12Hs :: (ParseTime t) => String -> Maybe t parseTime12Hs = prsdef "%I:%M:%S %p" | Parse as @hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseTime12hs :: (ParseTime t) => String -> Maybe t parseTime12hs = prsdef "%I:%M:%S %P" | Parse as @YYYY - MM - DD hh : mm@ , where @hh@ is in the range @[00 .. 23]@. parseYmd24 :: (ParseTime t) => String -> Maybe t parseYmd24 = prsdef "%F %R" | Parse as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseYmd24s :: (ParseTime t) => String -> Maybe t parseYmd24s = prsdef "%F %T" | Parse as @YYYY - MM - DD hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseYmd24ps :: (ParseTime t) => String -> Maybe t parseYmd24ps = prsdef "%F %T%Q" | Parse as @YYYY - MM - DD hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12H :: (ParseTime t) => String -> Maybe t parseYmd12H = prsdef "%F %I:%M %p" | Parse as @YYYY - MM - DD hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12h :: (ParseTime t) => String -> Maybe t parseYmd12h = prsdef "%F %I:%M %P" | Parse as @YYYY - MM - DD hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12Hs :: (ParseTime t) => String -> Maybe t parseYmd12Hs = prsdef "%F %I:%M:%S %p" | Parse as @YYYY - MM - DD hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseYmd12hs :: (ParseTime t) => String -> Maybe t parseYmd12hs = prsdef "%F %I:%M:%S %P" | Parse as @MM / DD / YYYY hh : mm@ , where @hh@ is in the range @[00 .. 23]@. parseMdy24 :: (ParseTime t) => String -> Maybe t parseMdy24 = prsdef "%m/%d/%Y %R" | Parse as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseMdy24s :: (ParseTime t) => String -> Maybe t parseMdy24s = prsdef "%m/%d/%Y %T" | Parse as @MM / DD / YYYY hh : : ss@ , where @hh@ is in the range @[00 .. 23]@. parseMdy24ps :: (ParseTime t) => String -> Maybe t parseMdy24ps = prsdef "%m/%d/%Y %T%Q" | Parse as @MM / DD / YYYY hh : ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12H :: (ParseTime t) => String -> Maybe t parseMdy12H = prsdef "%m/%d/%Y %I:%M %p" | Parse as @MM / DD / YYYY hh : ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12h :: (ParseTime t) => String -> Maybe t parseMdy12h = prsdef "%m/%d/%Y %I:%M %P" | Parse as @MM / DD / YYYY hh : : ss ( AM|PM)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12Hs :: (ParseTime t) => String -> Maybe t parseMdy12Hs = prsdef "%m/%d/%Y %I:%M:%S %p" | Parse as @MM / DD / YYYY hh : : ss ( am|pm)@ , where @hh@ is in the range @[01 .. 12]@. parseMdy12hs :: (ParseTime t) => String -> Maybe t parseMdy12hs = prsdef "%m/%d/%Y %I:%M:%S %P"
a1fe46a5feb90a91a295a5fd9cc1be5d81bdd01799dae6c7825a93e261424e1b
chef/chef-server
chefreq.erl
-module(chefreq). -compile([export_all, nowarn_export_all]). -include_lib("eunit/include/eunit.hrl"). main([Path]) -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, Path, <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). bad_time([Path]) -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, Path, <<"GET">>), Headers1 = lists:keyreplace("X-Ops-Timestamp", 1, Headers0, {"X-Ops-Timestamp", "2011-06-21T19:06:35Z"}), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers1], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). missing([Path]) -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, Path, <<"GET">>), Headers1 = lists:keydelete("X-Ops-Timestamp", 1, Headers0), Headers2 = lists:keydelete("X-Ops-Content-Hash", 1, Headers1), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers2], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). bad_query() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/userprimary/search/role?q=a[b", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). bad_start() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/userprimary/search/role?q=ab&start=abc", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). user_not_in_org() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/knifetest-org/search/role?q=ab&start=abc", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). no_user() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth-xxx-yyy", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/userprimary/search/role?q=ab&start=abc", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]).
null
https://raw.githubusercontent.com/chef/chef-server/6d31841ecd73d984d819244add7ad6ebac284323/src/oc_erchef/knife/chefreq.erl
erlang
-module(chefreq). -compile([export_all, nowarn_export_all]). -include_lib("eunit/include/eunit.hrl"). main([Path]) -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, Path, <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). bad_time([Path]) -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, Path, <<"GET">>), Headers1 = lists:keyreplace("X-Ops-Timestamp", 1, Headers0, {"X-Ops-Timestamp", "2011-06-21T19:06:35Z"}), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers1], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). missing([Path]) -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, Path, <<"GET">>), Headers1 = lists:keydelete("X-Ops-Timestamp", 1, Headers0), Headers2 = lists:keydelete("X-Ops-Content-Hash", 1, Headers1), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers2], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). bad_query() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/userprimary/search/role?q=a[b", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). bad_start() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/userprimary/search/role?q=ab&start=abc", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). user_not_in_org() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/knifetest-org/search/role?q=ab&start=abc", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]). no_user() -> application:start(crypto), ssl:start(), ibrowse:start(), PFile = "/Users/seth/oc/environments/orgs/userprimary/.chef/seth.pem", {ok, PBin} = file:read_file(PFile), Private = chef_authn:extract_private_key(PBin), Client = chef_rest_client:make_chef_rest_client("", "seth-xxx-yyy", Private), {Url, Headers0} = chef_rest_client:generate_signed_headers(Client, "/organizations/userprimary/search/role?q=ab&start=abc", <<"GET">>), Headers = [{"Accept", "application/json"}, {"X-CHEF-VERSION", "0.10.0"} | Headers0], ibrowse:send_req(Url, Headers, get, [], [{ssl_options, []}]).
77ffeb5d4b06ef0e101e10600e459930caf2397b046351859e135bb93c97f190
amosr/folderol
Helper.hs
module Bench.Array.Helper where # INLINE expensive # expensive :: Int -> Int expensive f = f * 2 # INLINE expensive1 # expensive1 :: Int -> Int expensive1 f = f * 2 # INLINE expensive2 # expensive2 :: Int -> Int expensive2 f = f `div` 2
null
https://raw.githubusercontent.com/amosr/folderol/9b8c0cd30cfb798dadaa404cc66404765b1fc4fe/bench/Bench/Array/Helper.hs
haskell
module Bench.Array.Helper where # INLINE expensive # expensive :: Int -> Int expensive f = f * 2 # INLINE expensive1 # expensive1 :: Int -> Int expensive1 f = f * 2 # INLINE expensive2 # expensive2 :: Int -> Int expensive2 f = f `div` 2
31e76ad44f08acdcb49f90d0f4f2b5311673c9642e708169cd190f0e41e53527
stan-dev/stanc3
Stmt.mli
(** MIR types and modules corresponding to the statements of the language *) open Common module Fixed : sig module Pattern : sig type ('a, 'b) t = | Assignment of 'a lvalue * 'a | TargetPE of 'a | NRFunApp of 'a Fun_kind.t * 'a list | Break | Continue | Return of 'a option | Skip | IfElse of 'a * 'b * 'b option | While of 'a * 'b | For of {loopvar: string; lower: 'a; upper: 'a; body: 'b} | Profile of string * 'b list | Block of 'b list | SList of 'b list | Decl of { decl_adtype: UnsizedType.autodifftype ; decl_id: string ; decl_type: 'a Type.t ; initialize: bool } [@@deriving sexp, hash, compare] and 'a lvalue = string * UnsizedType.t * 'a Index.t list [@@deriving sexp, hash, map, compare, fold] include Pattern.S2 with type ('a, 'b) t := ('a, 'b) t end include Fixed.S2 with module First = Expr.Fixed and module Pattern := Pattern end module Located : sig module Meta : sig type t = (Location_span.t[@sexp.opaque] [@compare.ignore]) [@@deriving compare, sexp, hash] include Specialized.Meta with type t := t end include Specialized.S with module Meta := Meta and type t = ( Expr.Typed.Meta.t , (Meta.t[@sexp.opaque] [@compare.ignore]) ) Fixed.t val loc_of : t -> Location_span.t module Non_recursive : sig type t = { pattern: (Expr.Typed.t, int) Fixed.Pattern.t ; meta: (Meta.t[@sexp.opaque] [@compare.ignore]) } [@@deriving compare, sexp, hash] end end module Numbered : sig module Meta : sig type t = (int[@sexp.opaque] [@compare.ignore]) [@@deriving compare, sexp, hash] include Specialized.Meta with type t := t val from_int : int -> t end include Specialized.S with module Meta := Meta and type t = (Expr.Typed.Meta.t, Meta.t) Fixed.t end module Helpers : sig val temp_vars : Expr.Typed.t list -> Located.t list * Expr.Typed.t list * (unit -> unit) val ensure_var : (Expr.Typed.t -> 'a -> Located.t) -> Expr.Typed.t -> 'a -> Located.t val internal_nrfunapp : 'a Fixed.First.t Internal_fun.t -> 'a Fixed.First.t list -> 'b -> ('a, 'b) Fixed.t val contains_fn_kind : ('a Fixed.First.t Fun_kind.t -> bool) -> ?init:bool -> ('a, 'b) Fixed.t -> bool val mk_for : Expr.Typed.t -> (Expr.Typed.t -> Located.t) -> Location_span.t -> Located.t val mk_nested_for : Expr.Typed.t list -> (Expr.Typed.t list -> Located.t) -> Location_span.t -> Located.t val mk_for_iteratee : Expr.Typed.t -> (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val for_each : (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val for_scalar : Expr.Typed.t SizedType.t -> (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val for_scalar_inv : Expr.Typed.t SizedType.t -> (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val assign_indexed : UnsizedType.t -> string -> 'a -> ('b Expr.Fixed.t -> 'b Expr.Fixed.t) -> 'b Expr.Fixed.t -> ('b, 'a) Fixed.t end
null
https://raw.githubusercontent.com/stan-dev/stanc3/975b2132890f2f6008875cee722ae4f766501952/src/middle/Stmt.mli
ocaml
* MIR types and modules corresponding to the statements of the language
open Common module Fixed : sig module Pattern : sig type ('a, 'b) t = | Assignment of 'a lvalue * 'a | TargetPE of 'a | NRFunApp of 'a Fun_kind.t * 'a list | Break | Continue | Return of 'a option | Skip | IfElse of 'a * 'b * 'b option | While of 'a * 'b | For of {loopvar: string; lower: 'a; upper: 'a; body: 'b} | Profile of string * 'b list | Block of 'b list | SList of 'b list | Decl of { decl_adtype: UnsizedType.autodifftype ; decl_id: string ; decl_type: 'a Type.t ; initialize: bool } [@@deriving sexp, hash, compare] and 'a lvalue = string * UnsizedType.t * 'a Index.t list [@@deriving sexp, hash, map, compare, fold] include Pattern.S2 with type ('a, 'b) t := ('a, 'b) t end include Fixed.S2 with module First = Expr.Fixed and module Pattern := Pattern end module Located : sig module Meta : sig type t = (Location_span.t[@sexp.opaque] [@compare.ignore]) [@@deriving compare, sexp, hash] include Specialized.Meta with type t := t end include Specialized.S with module Meta := Meta and type t = ( Expr.Typed.Meta.t , (Meta.t[@sexp.opaque] [@compare.ignore]) ) Fixed.t val loc_of : t -> Location_span.t module Non_recursive : sig type t = { pattern: (Expr.Typed.t, int) Fixed.Pattern.t ; meta: (Meta.t[@sexp.opaque] [@compare.ignore]) } [@@deriving compare, sexp, hash] end end module Numbered : sig module Meta : sig type t = (int[@sexp.opaque] [@compare.ignore]) [@@deriving compare, sexp, hash] include Specialized.Meta with type t := t val from_int : int -> t end include Specialized.S with module Meta := Meta and type t = (Expr.Typed.Meta.t, Meta.t) Fixed.t end module Helpers : sig val temp_vars : Expr.Typed.t list -> Located.t list * Expr.Typed.t list * (unit -> unit) val ensure_var : (Expr.Typed.t -> 'a -> Located.t) -> Expr.Typed.t -> 'a -> Located.t val internal_nrfunapp : 'a Fixed.First.t Internal_fun.t -> 'a Fixed.First.t list -> 'b -> ('a, 'b) Fixed.t val contains_fn_kind : ('a Fixed.First.t Fun_kind.t -> bool) -> ?init:bool -> ('a, 'b) Fixed.t -> bool val mk_for : Expr.Typed.t -> (Expr.Typed.t -> Located.t) -> Location_span.t -> Located.t val mk_nested_for : Expr.Typed.t list -> (Expr.Typed.t list -> Located.t) -> Location_span.t -> Located.t val mk_for_iteratee : Expr.Typed.t -> (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val for_each : (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val for_scalar : Expr.Typed.t SizedType.t -> (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val for_scalar_inv : Expr.Typed.t SizedType.t -> (Expr.Typed.t -> Located.t) -> Expr.Typed.t -> Location_span.t -> Located.t val assign_indexed : UnsizedType.t -> string -> 'a -> ('b Expr.Fixed.t -> 'b Expr.Fixed.t) -> 'b Expr.Fixed.t -> ('b, 'a) Fixed.t end
61bbb09a09c44a5ee2f1e556011b0f151b191909af9ff49b9a1be7877efa237c
yogthos/krueger
tag_editor.cljs
(ns krueger.components.widgets.tag-editor (:require [cljsjs.semantic-ui-react :as ui] [clojure.set :refer [difference]] [krueger.input-events :as input] [reagent.core :as r] [re-frame.core :refer [subscribe]] [re-frame.core :as rf]))
null
https://raw.githubusercontent.com/yogthos/krueger/782e1f8ab358867102b907c5a80e56ee6bc6ff82/src/cljs/krueger/components/widgets/tag_editor.cljs
clojure
(ns krueger.components.widgets.tag-editor (:require [cljsjs.semantic-ui-react :as ui] [clojure.set :refer [difference]] [krueger.input-events :as input] [reagent.core :as r] [re-frame.core :refer [subscribe]] [re-frame.core :as rf]))
7d8fffe2b4865dbcf99c35759c50e5e2112a69abcd0b52bc66970992f4103741
ucsd-progsys/liquidhaskell
Utf16.hs
# LANGUAGE MagicHash , BangPatterns # -- | -- Module : Data.Text.Encoding.Utf16 Copyright : ( c ) 2008 , 2009 , ( c ) 2009 , ( c ) 2009 -- -- License : BSD-style -- Maintainer : , , -- -- Stability : experimental Portability : GHC -- -- Basic UTF-16 validation and character manipulation. module Data.Text.Encoding.Utf16 ( chr2 , validate1 , validate2 ) where import GHC.Exts import GHC.Word (Word16(..)) chr2 :: Word16 -> Word16 -> Char chr2 (W16# a#) (W16# b#) = C# (chr# (upper# +# lower# +# 0x10000#)) where !x# = word2Int# a# !y# = word2Int# b# !upper# = uncheckedIShiftL# (x# -# 0xD800#) 10# !lower# = y# -# 0xDC00# # INLINE chr2 # validate1 :: Word16 -> Bool validate1 x1 = x1 < 0xD800 || x1 > 0xDFFF # INLINE validate1 # validate2 :: Word16 -> Word16 -> Bool validate2 x1 x2 = x1 >= 0xD800 && x1 <= 0xDBFF && x2 >= 0xDC00 && x2 <= 0xDFFF # INLINE validate2 #
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/20cd67af038930cb592d68d272c8eb1cbe3cb6bf/tests/benchmarks/text-0.11.2.3/Data/Text/Encoding/Utf16.hs
haskell
| Module : Data.Text.Encoding.Utf16 License : BSD-style Maintainer : , , Stability : experimental Basic UTF-16 validation and character manipulation.
# LANGUAGE MagicHash , BangPatterns # Copyright : ( c ) 2008 , 2009 , ( c ) 2009 , ( c ) 2009 Portability : GHC module Data.Text.Encoding.Utf16 ( chr2 , validate1 , validate2 ) where import GHC.Exts import GHC.Word (Word16(..)) chr2 :: Word16 -> Word16 -> Char chr2 (W16# a#) (W16# b#) = C# (chr# (upper# +# lower# +# 0x10000#)) where !x# = word2Int# a# !y# = word2Int# b# !upper# = uncheckedIShiftL# (x# -# 0xD800#) 10# !lower# = y# -# 0xDC00# # INLINE chr2 # validate1 :: Word16 -> Bool validate1 x1 = x1 < 0xD800 || x1 > 0xDFFF # INLINE validate1 # validate2 :: Word16 -> Word16 -> Bool validate2 x1 x2 = x1 >= 0xD800 && x1 <= 0xDBFF && x2 >= 0xDC00 && x2 <= 0xDFFF # INLINE validate2 #
bbeab1526b36b0c589e4f0ebb2fca7c129ee68dcf9d32b88e469d4661c029648
nkpart/kit
Repository.hs
module Kit.Repository ( -- KitRepository, makeRepository, -- readKitSpec, unpackKit, packagesDirectory, publishLocally ) where import Kit.Spec import Kit.Util import Data.Yaml (decodeFile) import Control.Error data KitRepository = KitRepository { dotKitDir :: FilePath } deriving (Eq, Show) localCacheDir :: KitRepository -> FilePath localCacheDir kr = dotKitDir kr </> "cache" </> "local" makeRepository :: FilePath -> IO KitRepository makeRepository fp = let repo = KitRepository fp in do mkdirP $ localCacheDir repo return repo readKitSpec :: MonadIO m => KitRepository -> Kit -> EitherT String m KitSpec readKitSpec repo kit = do mbLoaded <- liftIO $ decodeFile (localCacheDir repo </> kitSpecPath kit) tryJust ("Invalid KitSpec file for " ++ packageFileName kit) mbLoaded baseKitPath :: Packageable a => a -> String baseKitPath k = packageName k </> packageVersion k kitPackagePath :: Packageable a => a -> String kitPackagePath k = baseKitPath k </> packageFileName k ++ ".tar.gz" kitSpecPath :: Packageable a => a -> String kitSpecPath k = baseKitPath k </> "KitSpec" packagesDirectory :: KitRepository -> FilePath packagesDirectory kr = dotKitDir kr </> "packages" unpackKit :: (Packageable a) => KitRepository -> a -> IO () unpackKit kr kit = do let source = localCacheDir kr </> kitPackagePath kit let dest = packagesDirectory kr d <- doesDirectoryExist $ dest </> packageFileName kit if not d then do putStrLn $ "Unpacking: " ++ packageFileName kit mkdirP dest inDirectory dest $ shell ("tar zxf " ++ source) return () else putStrLn $ "Using: " ++ packageFileName kit return () publishLocally :: KitRepository -> KitSpec -> FilePath -> FilePath -> IO () publishLocally kr ks specFile packageFile = do let cacheDir = localCacheDir kr let thisKitDir = cacheDir </> baseKitPath ks mkdirP thisKitDir let fname = takeFileName packageFile copyFile packageFile (thisKitDir </> fname) copyFile specFile (thisKitDir </> "KitSpec") let pkg = packagesDirectory kr </> packageFileName ks d <- doesDirectoryExist pkg when d $ removeDirectoryRecursive pkg
null
https://raw.githubusercontent.com/nkpart/kit/ed217ddbc90688350e52156503cca092c9bf8300/Kit/Repository.hs
haskell
module Kit.Repository ( KitRepository, makeRepository, readKitSpec, unpackKit, packagesDirectory, publishLocally ) where import Kit.Spec import Kit.Util import Data.Yaml (decodeFile) import Control.Error data KitRepository = KitRepository { dotKitDir :: FilePath } deriving (Eq, Show) localCacheDir :: KitRepository -> FilePath localCacheDir kr = dotKitDir kr </> "cache" </> "local" makeRepository :: FilePath -> IO KitRepository makeRepository fp = let repo = KitRepository fp in do mkdirP $ localCacheDir repo return repo readKitSpec :: MonadIO m => KitRepository -> Kit -> EitherT String m KitSpec readKitSpec repo kit = do mbLoaded <- liftIO $ decodeFile (localCacheDir repo </> kitSpecPath kit) tryJust ("Invalid KitSpec file for " ++ packageFileName kit) mbLoaded baseKitPath :: Packageable a => a -> String baseKitPath k = packageName k </> packageVersion k kitPackagePath :: Packageable a => a -> String kitPackagePath k = baseKitPath k </> packageFileName k ++ ".tar.gz" kitSpecPath :: Packageable a => a -> String kitSpecPath k = baseKitPath k </> "KitSpec" packagesDirectory :: KitRepository -> FilePath packagesDirectory kr = dotKitDir kr </> "packages" unpackKit :: (Packageable a) => KitRepository -> a -> IO () unpackKit kr kit = do let source = localCacheDir kr </> kitPackagePath kit let dest = packagesDirectory kr d <- doesDirectoryExist $ dest </> packageFileName kit if not d then do putStrLn $ "Unpacking: " ++ packageFileName kit mkdirP dest inDirectory dest $ shell ("tar zxf " ++ source) return () else putStrLn $ "Using: " ++ packageFileName kit return () publishLocally :: KitRepository -> KitSpec -> FilePath -> FilePath -> IO () publishLocally kr ks specFile packageFile = do let cacheDir = localCacheDir kr let thisKitDir = cacheDir </> baseKitPath ks mkdirP thisKitDir let fname = takeFileName packageFile copyFile packageFile (thisKitDir </> fname) copyFile specFile (thisKitDir </> "KitSpec") let pkg = packagesDirectory kr </> packageFileName ks d <- doesDirectoryExist pkg when d $ removeDirectoryRecursive pkg
8d7c53546ce0207cd37353f50235dcbafea4815dc28faaa3fd276e650b76f803
dustin/environ
env_alert_mailer.erl
%% Copyright ( c ) 2006 < > %% -module(env_alert_mailer). -behaviour(gen_server). -export([start_link/0, code_change/3, handle_info/2, terminate/2]). -export([send_message/4, stop/0]). -export([init/1, handle_call/3, handle_cast/2]). start_link() -> gen_server:start_link({local, env_alert_mailer}, ?MODULE, [], []). init(_Args) -> {ok, 0}. send_message(To, Server, Subject, Message) -> gen_server:cast(?MODULE, {send, [To, Server, Subject, Message]}). stop() -> gen_server:cast(?MODULE, stop). handle_call(X, From, _St) -> error_logger:error_msg( "Received a call request from ~p for ~p~n", [From, X]). do_send(To, MailServerHost, Subject, Body) -> From = environ_utilities:get_env(mail_sender, ""), Msg = email_msg:simp_msg(From, To, Subject, Body), {ok, MailServer} = smtp_fsm:start(MailServerHost), {ok, _Status} = smtp_fsm:ehlo(MailServer), ok = smtp_fsm:sendemail(MailServer, From, To, Msg), smtp_fsm:close(MailServer), ok. handle_cast(stop, State) -> {stop, normal, State}; handle_cast({send, [To, Server, Subject, Message]}, St) -> case catch do_send(To, Server, Subject, Message) of ok -> error_logger:info_msg("Sent alert to ~p~n", [To]); E -> error_logger:error_msg("Failed to send alert to ~p via ~p:~n~p~n", [To, Server, E]) end, {noreply, St + 1}. handle_info(X, St) -> error_logger:error_msg( "Received an unhandled message: ~p~n", [X]), {noreply,St}. code_change(_OldVsn, St, _Extra) -> error_logger:error_msg("Code change~n", []), {ok, St}. terminate(normal, _State) -> ok.
null
https://raw.githubusercontent.com/dustin/environ/a45e714752a38e0b67ebd7e8d0bf8fb0c74d7945/src/env_alert_mailer.erl
erlang
Copyright ( c ) 2006 < > -module(env_alert_mailer). -behaviour(gen_server). -export([start_link/0, code_change/3, handle_info/2, terminate/2]). -export([send_message/4, stop/0]). -export([init/1, handle_call/3, handle_cast/2]). start_link() -> gen_server:start_link({local, env_alert_mailer}, ?MODULE, [], []). init(_Args) -> {ok, 0}. send_message(To, Server, Subject, Message) -> gen_server:cast(?MODULE, {send, [To, Server, Subject, Message]}). stop() -> gen_server:cast(?MODULE, stop). handle_call(X, From, _St) -> error_logger:error_msg( "Received a call request from ~p for ~p~n", [From, X]). do_send(To, MailServerHost, Subject, Body) -> From = environ_utilities:get_env(mail_sender, ""), Msg = email_msg:simp_msg(From, To, Subject, Body), {ok, MailServer} = smtp_fsm:start(MailServerHost), {ok, _Status} = smtp_fsm:ehlo(MailServer), ok = smtp_fsm:sendemail(MailServer, From, To, Msg), smtp_fsm:close(MailServer), ok. handle_cast(stop, State) -> {stop, normal, State}; handle_cast({send, [To, Server, Subject, Message]}, St) -> case catch do_send(To, Server, Subject, Message) of ok -> error_logger:info_msg("Sent alert to ~p~n", [To]); E -> error_logger:error_msg("Failed to send alert to ~p via ~p:~n~p~n", [To, Server, E]) end, {noreply, St + 1}. handle_info(X, St) -> error_logger:error_msg( "Received an unhandled message: ~p~n", [X]), {noreply,St}. code_change(_OldVsn, St, _Extra) -> error_logger:error_msg("Code change~n", []), {ok, St}. terminate(normal, _State) -> ok.
f44fc78c8089709fd4622723d843c2cdf2a121d5791344f942895bf61eb2888f
debug-ito/wild-bind
Description.hs
-- | -- Module: WildBind.Description -- Description: Types about ActionDescription Maintainer : < > -- module WildBind.Description ( ActionDescription , Describable (..) ) where import Data.Text (Text) -- | Human-readable description of an action. 'ActionDescription' is -- used to describe the current binding to the user. type ActionDescription = Text -- | Class for something describable. class Describable d where describe :: d -> ActionDescription -- | @since 0.1.1.0 instance (Describable a, Describable b) => Describable (Either a b) where describe = either describe describe
null
https://raw.githubusercontent.com/debug-ito/wild-bind/ef65370ded4f9687fed554107df4cc58247943de/wild-bind/src/WildBind/Description.hs
haskell
| Module: WildBind.Description Description: Types about ActionDescription | Human-readable description of an action. 'ActionDescription' is used to describe the current binding to the user. | Class for something describable. | @since 0.1.1.0
Maintainer : < > module WildBind.Description ( ActionDescription , Describable (..) ) where import Data.Text (Text) type ActionDescription = Text class Describable d where describe :: d -> ActionDescription instance (Describable a, Describable b) => Describable (Either a b) where describe = either describe describe
8765bbe62e7a70d6a4f72dfa65555869f7c4f710950b796003b3ec9ea02e0074
simhu/cubical
Concrete.hs
{-# LANGUAGE TupleSections, ParallelListComp #-} | Convert the concrete syntax into the syntax of cubical TT . module Concrete where import Exp.Abs import qualified CTT as C import Pretty import Control.Applicative import Control.Arrow (second) import Control.Monad.Trans import Control.Monad.Trans.Reader import Control.Monad.Trans.Error hiding (throwError) import Control.Monad.Error (throwError) import Control.Monad (when) import Data.Functor.Identity import Data.List (nub) type Tele = [(AIdent,Exp)] type Ter = C.Ter -- | Useful auxiliary functions -- Applicative cons (<:>) :: Applicative f => f a -> f [a] -> f [a] a <:> b = (:) <$> a <*> b un - something functions unAIdent :: AIdent -> C.Ident unAIdent (AIdent (_,x)) = x unVar :: Exp -> Maybe AIdent unVar (Var x) = Just x unVar _ = Nothing unWhere :: ExpWhere -> Exp unWhere (Where e ds) = Let ds e unWhere (NoWhere e) = e -- tail recursive form to transform a sequence of applications -- App (App (App u v) ...) w into (u, [v, …, w]) ( cleaner than the previous version of unApps ) unApps :: Exp -> [Exp] -> (Exp, [Exp]) unApps (App u v) ws = unApps u (v : ws) unApps u ws = (u, ws) vTele :: [VTDecl] -> Tele vTele decls = [ (i, typ) | VTDecl id ids typ <- decls, i <- id:ids ] turns an expression of the form App ( ... ( App id1 id2 ) ... ) -- into a list of idents pseudoIdents :: Exp -> Maybe [AIdent] pseudoIdents = mapM unVar . uncurry (:) . flip unApps [] pseudoTele :: [PseudoTDecl] -> Maybe Tele pseudoTele [] = return [] pseudoTele (PseudoTDecl exp typ : pd) = do ids <- pseudoIdents exp pt <- pseudoTele pd return $ map (,typ) ids ++ pt ------------------------------------------------------------------------------- -- | Resolver and environment type Arity = Int data SymKind = Variable | Constructor Arity deriving (Eq,Show) -- local environment for constructors data Env = Env { envModule :: String, variables :: [(C.Binder,SymKind)] } deriving (Eq, Show) type Resolver a = ReaderT Env (ErrorT String Identity) a emptyEnv :: Env emptyEnv = Env "" [] runResolver :: Resolver a -> Either String a runResolver x = runIdentity $ runErrorT $ runReaderT x emptyEnv updateModule :: String -> Env -> Env updateModule mod e = e {envModule = mod} insertBinder :: (C.Binder,SymKind) -> Env -> Env insertBinder (x@(n,_),var) e | n == "_" || n == "undefined" = e | otherwise = e {variables = (x, var) : variables e} insertBinders :: [(C.Binder,SymKind)] -> Env -> Env insertBinders = flip $ foldr insertBinder insertVar :: C.Binder -> Env -> Env insertVar x = insertBinder (x,Variable) insertVars :: [C.Binder] -> Env -> Env insertVars = flip $ foldr insertVar insertCon :: (C.Binder,Arity) -> Env -> Env insertCon (x,a) = insertBinder (x,Constructor a) insertCons :: [(C.Binder,Arity)] -> Env -> Env insertCons = flip $ foldr insertCon getModule :: Resolver String getModule = envModule <$> ask getVariables :: Resolver [(C.Binder,SymKind)] getVariables = variables <$> ask getLoc :: (Int,Int) -> Resolver C.Loc getLoc l = C.Loc <$> getModule <*> pure l resolveBinder :: AIdent -> Resolver C.Binder resolveBinder (AIdent (l,x)) = (x,) <$> getLoc l Eta expand constructors expandConstr :: Arity -> String -> [Exp] -> Resolver Ter expandConstr a x es = do let r = a - length es binders = map (('_' :) . show) [1..r] args = map C.Var binders ts <- mapM resolveExp es return $ C.mkLams binders $ C.mkApps (C.Con x []) (ts ++ args) resolveVar :: AIdent -> Resolver Ter resolveVar (AIdent (l,x)) | (x == "_") || (x == "undefined") = C.PN <$> C.Undef <$> getLoc l | otherwise = do modName <- getModule vars <- getVariables case C.getIdent x vars of Just Variable -> return $ C.Var x Just (Constructor a) -> expandConstr a x [] _ -> throwError $ "Cannot resolve variable" <+> x <+> "at position" <+> show l <+> "in module" <+> modName lam :: AIdent -> Resolver Ter -> Resolver Ter lam a e = do x <- resolveBinder a; C.Lam x <$> local (insertVar x) e lams :: [AIdent] -> Resolver Ter -> Resolver Ter lams = flip $ foldr lam bind :: (Ter -> Ter -> Ter) -> (AIdent, Exp) -> Resolver Ter -> Resolver Ter bind f (x,t) e = f <$> resolveExp t <*> lam x e binds :: (Ter -> Ter -> Ter) -> Tele -> Resolver Ter -> Resolver Ter binds f = flip $ foldr $ bind f resolveExp :: Exp -> Resolver Ter resolveExp U = return C.U resolveExp (Var x) = resolveVar x resolveExp (App t s) = case unApps t [s] of (x@(Var (AIdent (_,n))),xs) -> do -- Special treatment in the case of a constructor in order not to -- eta expand too much vars <- getVariables case C.getIdent n vars of Just (Constructor a) -> expandConstr a n xs _ -> C.mkApps <$> resolveExp x <*> mapM resolveExp xs (x,xs) -> C.mkApps <$> resolveExp x <*> mapM resolveExp xs resolveExp (Sigma t b) = case pseudoTele t of Just tele -> binds C.Sigma tele (resolveExp b) Nothing -> throwError "Telescope malformed in Sigma" resolveExp (Pi t b) = case pseudoTele t of Just tele -> binds C.Pi tele (resolveExp b) Nothing -> throwError "Telescope malformed in Pigma" resolveExp (Fun a b) = bind C.Pi (AIdent ((0,0),"_"), a) (resolveExp b) resolveExp (Lam x xs t) = lams (x:xs) (resolveExp t) resolveExp (Fst t) = C.Fst <$> resolveExp t resolveExp (Snd t) = C.Snd <$> resolveExp t resolveExp (Pair t0 t1) = C.SPair <$> resolveExp t0 <*> resolveExp t1 resolveExp (Split brs) = do brs' <- mapM resolveBranch brs loc <- getLoc (case brs of Branch (AIdent (l,_)) _ _:_ -> l ; _ -> (0,0)) return $ C.Split loc brs' resolveExp (Let decls e) = do (rdecls,names) <- resolveDecls decls C.mkWheres rdecls <$> local (insertBinders names) (resolveExp e) resolveWhere :: ExpWhere -> Resolver Ter resolveWhere = resolveExp . unWhere resolveBranch :: Branch -> Resolver (C.Label,([C.Binder],C.Ter)) resolveBranch (Branch lbl args e) = do binders <- mapM resolveBinder args re <- local (insertVars binders) $ resolveWhere e return (unAIdent lbl, (binders, re)) resolveTele :: [(AIdent,Exp)] -> Resolver C.Tele resolveTele [] = return [] resolveTele ((i,d):t) = do x <- resolveBinder i ((x,) <$> resolveExp d) <:> local (insertVar x) (resolveTele t) resolveLabel :: Label -> Resolver (C.Binder, C.Tele) resolveLabel (Label n vdecl) = (,) <$> resolveBinder n <*> resolveTele (vTele vdecl) declsLabels :: [Decl] -> Resolver [(C.Binder,Arity)] declsLabels decls = do let sums = concat [sum | DeclData _ _ sum <- decls] sequence [ (,length args) <$> resolveBinder lbl | Label lbl args <- sums ] Resolve Data or Def declaration resolveDDecl :: Decl -> Resolver (C.Ident, C.Ter) resolveDDecl (DeclDef (AIdent (_,n)) args body) = (n,) <$> lams args (resolveWhere body) resolveDDecl (DeclData x@(AIdent (l,n)) args sum) = (n,) <$> lams args (C.Sum <$> resolveBinder x <*> mapM resolveLabel sum) resolveDDecl d = throwError $ "Definition expected" <+> show d -- Resolve mutual declarations (possibly one) resolveMutuals :: [Decl] -> Resolver (C.Decls,[(C.Binder,SymKind)]) resolveMutuals decls = do binders <- mapM resolveBinder idents cs <- declsLabels decls let cns = map (fst . fst) cs ++ names when (nub cns /= cns) $ throwError $ "Duplicated constructor or ident:" <+> show cns rddecls <- mapM (local (insertVars binders . insertCons cs) . resolveDDecl) ddecls when (names /= map fst rddecls) $ throwError $ "Mismatching names in" <+> show decls rtdecls <- resolveTele tdecls return ([ (x,t,d) | (x,t) <- rtdecls | (_,d) <- rddecls ], map (second Constructor) cs ++ map (,Variable) binders) where idents = [ x | DeclType x _ <- decls ] names = [ unAIdent x | x <- idents ] tdecls = [ (x,t) | DeclType x t <- decls ] ddecls = filter (not . isTDecl) decls isTDecl d = case d of DeclType{} -> True; _ -> False -- Resolve opaque/transparent decls resolveOTDecl :: (C.Binder -> C.ODecls) -> AIdent -> [Decl] -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveOTDecl c n ds = do vars <- getVariables (rest,names) <- resolveDecls ds case C.getBinder (unAIdent n) vars of Just x -> return (c x : rest, names) Nothing -> throwError $ "Not in scope:" <+> show n -- Resolve declarations resolveDecls :: [Decl] -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveDecls [] = return ([],[]) resolveDecls (DeclOpaque n:ds) = resolveOTDecl C.Opaque n ds resolveDecls (DeclTransp n:ds) = resolveOTDecl C.Transp n ds resolveDecls (td@DeclType{}:d:ds) = do (rtd,names) <- resolveMutuals [td,d] (rds,names') <- local (insertBinders names) $ resolveDecls ds return (C.ODecls rtd : rds, names' ++ names) resolveDecls (DeclPrim x t:ds) = case C.mkPN (unAIdent x) of Just pn -> do b <- resolveBinder x rt <- resolveExp t (rds,names) <- local (insertVar b) $ resolveDecls ds return (C.ODecls [(b, rt, C.PN pn)] : rds, names ++ [(b,Variable)]) Nothing -> throwError $ "Primitive notion not defined:" <+> unAIdent x resolveDecls (DeclMutual defs : ds) = do (rdefs,names) <- resolveMutuals defs (rds, names') <- local (insertBinders names) $ resolveDecls ds return (C.ODecls rdefs : rds, names' ++ names) resolveDecls (decl:_) = throwError $ "Invalid declaration:" <+> show decl resolveModule :: Module -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveModule (Module n imports decls) = local (updateModule $ unAIdent n) $ resolveDecls decls resolveModules :: [Module] -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveModules [] = return ([],[]) resolveModules (mod:mods) = do (rmod, names) <- resolveModule mod (rmods,names') <- local (insertBinders names) $ resolveModules mods return (rmod ++ rmods, names' ++ names)
null
https://raw.githubusercontent.com/simhu/cubical/53bab8a89246ec658d4a6436534242d0ce15eb35/Concrete.hs
haskell
# LANGUAGE TupleSections, ParallelListComp # | Useful auxiliary functions Applicative cons tail recursive form to transform a sequence of applications App (App (App u v) ...) w into (u, [v, …, w]) into a list of idents ----------------------------------------------------------------------------- | Resolver and environment local environment for constructors Special treatment in the case of a constructor in order not to eta expand too much Resolve mutual declarations (possibly one) Resolve opaque/transparent decls Resolve declarations
| Convert the concrete syntax into the syntax of cubical TT . module Concrete where import Exp.Abs import qualified CTT as C import Pretty import Control.Applicative import Control.Arrow (second) import Control.Monad.Trans import Control.Monad.Trans.Reader import Control.Monad.Trans.Error hiding (throwError) import Control.Monad.Error (throwError) import Control.Monad (when) import Data.Functor.Identity import Data.List (nub) type Tele = [(AIdent,Exp)] type Ter = C.Ter (<:>) :: Applicative f => f a -> f [a] -> f [a] a <:> b = (:) <$> a <*> b un - something functions unAIdent :: AIdent -> C.Ident unAIdent (AIdent (_,x)) = x unVar :: Exp -> Maybe AIdent unVar (Var x) = Just x unVar _ = Nothing unWhere :: ExpWhere -> Exp unWhere (Where e ds) = Let ds e unWhere (NoWhere e) = e ( cleaner than the previous version of unApps ) unApps :: Exp -> [Exp] -> (Exp, [Exp]) unApps (App u v) ws = unApps u (v : ws) unApps u ws = (u, ws) vTele :: [VTDecl] -> Tele vTele decls = [ (i, typ) | VTDecl id ids typ <- decls, i <- id:ids ] turns an expression of the form App ( ... ( App id1 id2 ) ... ) pseudoIdents :: Exp -> Maybe [AIdent] pseudoIdents = mapM unVar . uncurry (:) . flip unApps [] pseudoTele :: [PseudoTDecl] -> Maybe Tele pseudoTele [] = return [] pseudoTele (PseudoTDecl exp typ : pd) = do ids <- pseudoIdents exp pt <- pseudoTele pd return $ map (,typ) ids ++ pt type Arity = Int data SymKind = Variable | Constructor Arity deriving (Eq,Show) data Env = Env { envModule :: String, variables :: [(C.Binder,SymKind)] } deriving (Eq, Show) type Resolver a = ReaderT Env (ErrorT String Identity) a emptyEnv :: Env emptyEnv = Env "" [] runResolver :: Resolver a -> Either String a runResolver x = runIdentity $ runErrorT $ runReaderT x emptyEnv updateModule :: String -> Env -> Env updateModule mod e = e {envModule = mod} insertBinder :: (C.Binder,SymKind) -> Env -> Env insertBinder (x@(n,_),var) e | n == "_" || n == "undefined" = e | otherwise = e {variables = (x, var) : variables e} insertBinders :: [(C.Binder,SymKind)] -> Env -> Env insertBinders = flip $ foldr insertBinder insertVar :: C.Binder -> Env -> Env insertVar x = insertBinder (x,Variable) insertVars :: [C.Binder] -> Env -> Env insertVars = flip $ foldr insertVar insertCon :: (C.Binder,Arity) -> Env -> Env insertCon (x,a) = insertBinder (x,Constructor a) insertCons :: [(C.Binder,Arity)] -> Env -> Env insertCons = flip $ foldr insertCon getModule :: Resolver String getModule = envModule <$> ask getVariables :: Resolver [(C.Binder,SymKind)] getVariables = variables <$> ask getLoc :: (Int,Int) -> Resolver C.Loc getLoc l = C.Loc <$> getModule <*> pure l resolveBinder :: AIdent -> Resolver C.Binder resolveBinder (AIdent (l,x)) = (x,) <$> getLoc l Eta expand constructors expandConstr :: Arity -> String -> [Exp] -> Resolver Ter expandConstr a x es = do let r = a - length es binders = map (('_' :) . show) [1..r] args = map C.Var binders ts <- mapM resolveExp es return $ C.mkLams binders $ C.mkApps (C.Con x []) (ts ++ args) resolveVar :: AIdent -> Resolver Ter resolveVar (AIdent (l,x)) | (x == "_") || (x == "undefined") = C.PN <$> C.Undef <$> getLoc l | otherwise = do modName <- getModule vars <- getVariables case C.getIdent x vars of Just Variable -> return $ C.Var x Just (Constructor a) -> expandConstr a x [] _ -> throwError $ "Cannot resolve variable" <+> x <+> "at position" <+> show l <+> "in module" <+> modName lam :: AIdent -> Resolver Ter -> Resolver Ter lam a e = do x <- resolveBinder a; C.Lam x <$> local (insertVar x) e lams :: [AIdent] -> Resolver Ter -> Resolver Ter lams = flip $ foldr lam bind :: (Ter -> Ter -> Ter) -> (AIdent, Exp) -> Resolver Ter -> Resolver Ter bind f (x,t) e = f <$> resolveExp t <*> lam x e binds :: (Ter -> Ter -> Ter) -> Tele -> Resolver Ter -> Resolver Ter binds f = flip $ foldr $ bind f resolveExp :: Exp -> Resolver Ter resolveExp U = return C.U resolveExp (Var x) = resolveVar x resolveExp (App t s) = case unApps t [s] of (x@(Var (AIdent (_,n))),xs) -> do vars <- getVariables case C.getIdent n vars of Just (Constructor a) -> expandConstr a n xs _ -> C.mkApps <$> resolveExp x <*> mapM resolveExp xs (x,xs) -> C.mkApps <$> resolveExp x <*> mapM resolveExp xs resolveExp (Sigma t b) = case pseudoTele t of Just tele -> binds C.Sigma tele (resolveExp b) Nothing -> throwError "Telescope malformed in Sigma" resolveExp (Pi t b) = case pseudoTele t of Just tele -> binds C.Pi tele (resolveExp b) Nothing -> throwError "Telescope malformed in Pigma" resolveExp (Fun a b) = bind C.Pi (AIdent ((0,0),"_"), a) (resolveExp b) resolveExp (Lam x xs t) = lams (x:xs) (resolveExp t) resolveExp (Fst t) = C.Fst <$> resolveExp t resolveExp (Snd t) = C.Snd <$> resolveExp t resolveExp (Pair t0 t1) = C.SPair <$> resolveExp t0 <*> resolveExp t1 resolveExp (Split brs) = do brs' <- mapM resolveBranch brs loc <- getLoc (case brs of Branch (AIdent (l,_)) _ _:_ -> l ; _ -> (0,0)) return $ C.Split loc brs' resolveExp (Let decls e) = do (rdecls,names) <- resolveDecls decls C.mkWheres rdecls <$> local (insertBinders names) (resolveExp e) resolveWhere :: ExpWhere -> Resolver Ter resolveWhere = resolveExp . unWhere resolveBranch :: Branch -> Resolver (C.Label,([C.Binder],C.Ter)) resolveBranch (Branch lbl args e) = do binders <- mapM resolveBinder args re <- local (insertVars binders) $ resolveWhere e return (unAIdent lbl, (binders, re)) resolveTele :: [(AIdent,Exp)] -> Resolver C.Tele resolveTele [] = return [] resolveTele ((i,d):t) = do x <- resolveBinder i ((x,) <$> resolveExp d) <:> local (insertVar x) (resolveTele t) resolveLabel :: Label -> Resolver (C.Binder, C.Tele) resolveLabel (Label n vdecl) = (,) <$> resolveBinder n <*> resolveTele (vTele vdecl) declsLabels :: [Decl] -> Resolver [(C.Binder,Arity)] declsLabels decls = do let sums = concat [sum | DeclData _ _ sum <- decls] sequence [ (,length args) <$> resolveBinder lbl | Label lbl args <- sums ] Resolve Data or Def declaration resolveDDecl :: Decl -> Resolver (C.Ident, C.Ter) resolveDDecl (DeclDef (AIdent (_,n)) args body) = (n,) <$> lams args (resolveWhere body) resolveDDecl (DeclData x@(AIdent (l,n)) args sum) = (n,) <$> lams args (C.Sum <$> resolveBinder x <*> mapM resolveLabel sum) resolveDDecl d = throwError $ "Definition expected" <+> show d resolveMutuals :: [Decl] -> Resolver (C.Decls,[(C.Binder,SymKind)]) resolveMutuals decls = do binders <- mapM resolveBinder idents cs <- declsLabels decls let cns = map (fst . fst) cs ++ names when (nub cns /= cns) $ throwError $ "Duplicated constructor or ident:" <+> show cns rddecls <- mapM (local (insertVars binders . insertCons cs) . resolveDDecl) ddecls when (names /= map fst rddecls) $ throwError $ "Mismatching names in" <+> show decls rtdecls <- resolveTele tdecls return ([ (x,t,d) | (x,t) <- rtdecls | (_,d) <- rddecls ], map (second Constructor) cs ++ map (,Variable) binders) where idents = [ x | DeclType x _ <- decls ] names = [ unAIdent x | x <- idents ] tdecls = [ (x,t) | DeclType x t <- decls ] ddecls = filter (not . isTDecl) decls isTDecl d = case d of DeclType{} -> True; _ -> False resolveOTDecl :: (C.Binder -> C.ODecls) -> AIdent -> [Decl] -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveOTDecl c n ds = do vars <- getVariables (rest,names) <- resolveDecls ds case C.getBinder (unAIdent n) vars of Just x -> return (c x : rest, names) Nothing -> throwError $ "Not in scope:" <+> show n resolveDecls :: [Decl] -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveDecls [] = return ([],[]) resolveDecls (DeclOpaque n:ds) = resolveOTDecl C.Opaque n ds resolveDecls (DeclTransp n:ds) = resolveOTDecl C.Transp n ds resolveDecls (td@DeclType{}:d:ds) = do (rtd,names) <- resolveMutuals [td,d] (rds,names') <- local (insertBinders names) $ resolveDecls ds return (C.ODecls rtd : rds, names' ++ names) resolveDecls (DeclPrim x t:ds) = case C.mkPN (unAIdent x) of Just pn -> do b <- resolveBinder x rt <- resolveExp t (rds,names) <- local (insertVar b) $ resolveDecls ds return (C.ODecls [(b, rt, C.PN pn)] : rds, names ++ [(b,Variable)]) Nothing -> throwError $ "Primitive notion not defined:" <+> unAIdent x resolveDecls (DeclMutual defs : ds) = do (rdefs,names) <- resolveMutuals defs (rds, names') <- local (insertBinders names) $ resolveDecls ds return (C.ODecls rdefs : rds, names' ++ names) resolveDecls (decl:_) = throwError $ "Invalid declaration:" <+> show decl resolveModule :: Module -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveModule (Module n imports decls) = local (updateModule $ unAIdent n) $ resolveDecls decls resolveModules :: [Module] -> Resolver ([C.ODecls],[(C.Binder,SymKind)]) resolveModules [] = return ([],[]) resolveModules (mod:mods) = do (rmod, names) <- resolveModule mod (rmods,names') <- local (insertBinders names) $ resolveModules mods return (rmod ++ rmods, names' ++ names)
01e271f3f9c21823aba5160f8099172c93eda9ac651065cfbe5aad5121831601
xvw/preface
arrow_zero.ml
module Suite (R : Model.PROFUNCTORIAL) (P : Preface_specs.ARROW_ZERO with type ('a, 'b) t = ('a, 'b) R.t) = Arrow.Suite (R) (P)
null
https://raw.githubusercontent.com/xvw/preface/84a297e1ee2967ad4341dca875da8d2dc6d7638c/lib/preface_qcheck/arrow_zero.ml
ocaml
module Suite (R : Model.PROFUNCTORIAL) (P : Preface_specs.ARROW_ZERO with type ('a, 'b) t = ('a, 'b) R.t) = Arrow.Suite (R) (P)
392e807ffef89803ea42af5e173548ef581bff8d350c5b1459b132f411808b64
2600hz-archive/whistle
amqp_network_connection.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License at %% / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the %% License for the specific language governing rights and limitations %% under the License. %% The Original Code is RabbitMQ . %% The Initial Developer of the Original Code is VMware , Inc. Copyright ( c ) 2007 - 2011 VMware , Inc. All rights reserved . %% @private -module(amqp_network_connection). -include("amqp_client.hrl"). -behaviour(amqp_gen_connection). -export([init/1, terminate/2, connect/4, do/2, open_channel_args/1, i/2, info_keys/0, handle_message/2, closing/3, channels_terminated/1]). -define(RABBIT_TCP_OPTS, [binary, {packet, 0}, {active,false}, {nodelay, true}]). -define(SOCKET_CLOSING_TIMEOUT, 1000). -define(HANDSHAKE_RECEIVE_TIMEOUT, 60000). -record(state, {sock, heartbeat, writer0, frame_max, closing_reason, %% undefined | Reason waiting_socket_close = false}). -define(INFO_KEYS, [type, heartbeat, frame_max, sock]). %%--------------------------------------------------------------------------- init([]) -> {ok, #state{}}. open_channel_args(#state{sock = Sock}) -> [Sock]. do(#'connection.close_ok'{} = CloseOk, State) -> erlang:send_after(?SOCKET_CLOSING_TIMEOUT, self(), socket_closing_timeout), do2(CloseOk, State); do(Method, State) -> do2(Method, State). do2(Method, #state{writer0 = Writer}) -> %% Catching because it expects the {channel_exit, _} message on error catch rabbit_writer:send_command_sync(Writer, Method). handle_message(timeout_waiting_for_close_ok, State = #state{closing_reason = Reason}) -> {stop, {timeout_waiting_for_close_ok, Reason}, State}; handle_message(socket_closing_timeout, State = #state{closing_reason = Reason}) -> {stop, {socket_closing_timeout, Reason}, State}; handle_message(socket_closed, State = #state{waiting_socket_close = true, closing_reason = Reason}) -> {stop, {shutdown, Reason}, State}; handle_message(socket_closed, State = #state{waiting_socket_close = false}) -> {stop, socket_closed_unexpectedly, State}; handle_message({socket_error, _} = SocketError, State) -> {stop, SocketError, State}; handle_message({channel_exit, Reason}, State) -> {stop, {channel0_died, Reason}, State}; handle_message(heartbeat_timeout, State) -> {stop, heartbeat_timeout, State}. closing(_ChannelCloseType, Reason, State) -> {ok, State#state{closing_reason = Reason}}. channels_terminated(State = #state{closing_reason = {server_initiated_close, _, _}}) -> {ok, State#state{waiting_socket_close = true}}; channels_terminated(State) -> {ok, State}. terminate(_Reason, _State) -> ok. i(type, _State) -> network; i(heartbeat, State) -> State#state.heartbeat; i(frame_max, State) -> State#state.frame_max; i(sock, State) -> State#state.sock; i(Item, _State) -> throw({bad_argument, Item}). info_keys() -> ?INFO_KEYS. %%--------------------------------------------------------------------------- %% Handshake %%--------------------------------------------------------------------------- connect(AmqpParams = #amqp_params{ssl_options = none, host = Host, port = Port}, SIF, ChMgr, State) -> case gen_tcp:connect(Host, Port, ?RABBIT_TCP_OPTS) of {ok, Sock} -> try_handshake(AmqpParams, SIF, ChMgr, State#state{sock = Sock}); {error, _} = E -> E end; connect(AmqpParams = #amqp_params{ssl_options = SslOpts, host = Host, port = Port}, SIF, ChMgr, State) -> rabbit_misc:start_applications([crypto, public_key, ssl]), case gen_tcp:connect(Host, Port, ?RABBIT_TCP_OPTS) of {ok, Sock} -> case ssl:connect(Sock, SslOpts) of {ok, SslSock} -> RabbitSslSock = #ssl_socket{ssl = SslSock, tcp = Sock}, try_handshake(AmqpParams, SIF, ChMgr, State#state{sock = RabbitSslSock}); {error, _} = E -> E end; {error, _} = E -> E end. try_handshake(AmqpParams, SIF, ChMgr, State) -> try handshake(AmqpParams, SIF, ChMgr, State) of Return -> Return catch exit:Reason -> {error, Reason} end. handshake(AmqpParams, SIF, ChMgr, State0 = #state{sock = Sock}) -> ok = rabbit_net:send(Sock, ?PROTOCOL_HEADER), {SHF, State1} = start_infrastructure(SIF, ChMgr, State0), network_handshake(AmqpParams, SHF, State1). start_infrastructure(SIF, ChMgr, State = #state{sock = Sock}) -> {ok, {_MainReader, _AState, Writer, SHF}} = SIF(Sock, ChMgr), {SHF, State#state{writer0 = Writer}}. network_handshake(AmqpParams, SHF, State0) -> Start = #'connection.start'{server_properties = ServerProperties, mechanisms = Mechanisms} = handshake_recv('connection.start'), ok = check_version(Start), Tune = login(AmqpParams, Mechanisms, State0), {TuneOk, ChannelMax, State1} = tune(Tune, AmqpParams, SHF, State0), do2(TuneOk, State1), do2(#'connection.open'{virtual_host = AmqpParams#amqp_params.virtual_host}, State1), Params = {ServerProperties, ChannelMax, State1}, case handshake_recv('connection.open_ok') of #'connection.open_ok'{} -> {ok, Params}; {closing, #amqp_error{} = AmqpError, Error} -> {closing, Params, AmqpError, Error} end. check_version(#'connection.start'{version_major = ?PROTOCOL_VERSION_MAJOR, version_minor = ?PROTOCOL_VERSION_MINOR}) -> ok; check_version(#'connection.start'{version_major = 8, version_minor = 0}) -> exit({protocol_version_mismatch, 0, 8}); check_version(#'connection.start'{version_major = Major, version_minor = Minor}) -> exit({protocol_version_mismatch, Major, Minor}). tune(#'connection.tune'{channel_max = ServerChannelMax, frame_max = ServerFrameMax, heartbeat = ServerHeartbeat}, #amqp_params{channel_max = ClientChannelMax, frame_max = ClientFrameMax, heartbeat = ClientHeartbeat}, SHF, State) -> [ChannelMax, Heartbeat, FrameMax] = lists:zipwith(fun (Client, Server) when Client =:= 0; Server =:= 0 -> lists:max([Client, Server]); (Client, Server) -> lists:min([Client, Server]) end, [ClientChannelMax, ClientHeartbeat, ClientFrameMax], [ServerChannelMax, ServerHeartbeat, ServerFrameMax]), NewState = State#state{heartbeat = Heartbeat, frame_max = FrameMax}, start_heartbeat(SHF, NewState), {#'connection.tune_ok'{channel_max = ChannelMax, frame_max = FrameMax, heartbeat = Heartbeat}, ChannelMax, NewState}. start_heartbeat(SHF, #state{sock = Sock, heartbeat = Heartbeat}) -> Frame = rabbit_binary_generator:build_heartbeat_frame(), SendFun = fun () -> catch rabbit_net:send(Sock, Frame) end, Connection = self(), ReceiveFun = fun () -> Connection ! heartbeat_timeout end, SHF(Sock, Heartbeat, SendFun, Heartbeat, ReceiveFun). login(Params = #amqp_params{auth_mechanisms = ClientMechanisms, client_properties = UserProps}, ServerMechanismsStr, State) -> ServerMechanisms = string:tokens(binary_to_list(ServerMechanismsStr), " "), case [{N, S, F} || F <- ClientMechanisms, {N, S} <- [F(none, Params, init)], lists:member(binary_to_list(N), ServerMechanisms)] of [{Name, MState0, Mech}|_] -> {Resp, MState1} = Mech(none, Params, MState0), StartOk = #'connection.start_ok'{ client_properties = client_properties(UserProps), mechanism = Name, response = Resp}, do2(StartOk, State), login_loop(Mech, MState1, Params, State); [] -> exit({no_suitable_auth_mechanism, ServerMechanisms}) end. login_loop(Mech, MState0, Params, State) -> case handshake_recv('connection.tune') of Tune = #'connection.tune'{} -> Tune; #'connection.secure'{challenge = Challenge} -> {Resp, MState1} = Mech(Challenge, Params, MState0), do2(#'connection.secure_ok'{response = Resp}, State), login_loop(Mech, MState1, Params, State) end. client_properties(UserProperties) -> {ok, Vsn} = application:get_key(amqp_client, vsn), Default = [{<<"product">>, longstr, <<"RabbitMQ">>}, {<<"version">>, longstr, list_to_binary(Vsn)}, {<<"platform">>, longstr, <<"Erlang">>}, {<<"copyright">>, longstr, <<"Copyright (c) 2007-2011 VMware, Inc.">>}, {<<"information">>, longstr, <<"Licensed under the MPL. " "See /">>}, {<<"capabilities">>, table, ?CLIENT_CAPABILITIES}], lists:foldl(fun({K, _, _} = Tuple, Acc) -> lists:keystore(K, 1, Acc, Tuple) end, Default, UserProperties). handshake_recv(Expecting) -> receive {'$gen_cast', {method, Method, none}} -> case {Expecting, element(1, Method)} of {E, M} when E =:= M -> Method; {'connection.open_ok', _} -> {closing, #amqp_error{name = command_invalid, explanation = "was expecting " "connection.open_ok"}, {error, {unexpected_method, Method, {expecting, Expecting}}}}; _ -> throw({unexpected_method, Method, {expecting, Expecting}}) end; socket_closed -> case Expecting of 'connection.tune' -> exit(auth_failure); 'connection.open_ok' -> exit(access_refused); _ -> exit({socket_closed_unexpectedly, Expecting}) end; {socket_error, _} = SocketError -> exit({SocketError, {expecting, Expecting}}); heartbeat_timeout -> exit(heartbeat_timeout); Other -> throw({handshake_recv_unexpected_message, Other}) after ?HANDSHAKE_RECEIVE_TIMEOUT -> case Expecting of 'connection.open_ok' -> {closing, #amqp_error{name = internal_error, explanation = "handshake timed out waiting " "connection.open_ok"}, {error, handshake_receive_timed_out}}; _ -> exit(handshake_receive_timed_out) end end.
null
https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/lib/rabbitmq_erlang_client-2.4.1/src/amqp_network_connection.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. undefined | Reason --------------------------------------------------------------------------- Catching because it expects the {channel_exit, _} message on error --------------------------------------------------------------------------- Handshake ---------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ . The Initial Developer of the Original Code is VMware , Inc. Copyright ( c ) 2007 - 2011 VMware , Inc. All rights reserved . @private -module(amqp_network_connection). -include("amqp_client.hrl"). -behaviour(amqp_gen_connection). -export([init/1, terminate/2, connect/4, do/2, open_channel_args/1, i/2, info_keys/0, handle_message/2, closing/3, channels_terminated/1]). -define(RABBIT_TCP_OPTS, [binary, {packet, 0}, {active,false}, {nodelay, true}]). -define(SOCKET_CLOSING_TIMEOUT, 1000). -define(HANDSHAKE_RECEIVE_TIMEOUT, 60000). -record(state, {sock, heartbeat, writer0, frame_max, waiting_socket_close = false}). -define(INFO_KEYS, [type, heartbeat, frame_max, sock]). init([]) -> {ok, #state{}}. open_channel_args(#state{sock = Sock}) -> [Sock]. do(#'connection.close_ok'{} = CloseOk, State) -> erlang:send_after(?SOCKET_CLOSING_TIMEOUT, self(), socket_closing_timeout), do2(CloseOk, State); do(Method, State) -> do2(Method, State). do2(Method, #state{writer0 = Writer}) -> catch rabbit_writer:send_command_sync(Writer, Method). handle_message(timeout_waiting_for_close_ok, State = #state{closing_reason = Reason}) -> {stop, {timeout_waiting_for_close_ok, Reason}, State}; handle_message(socket_closing_timeout, State = #state{closing_reason = Reason}) -> {stop, {socket_closing_timeout, Reason}, State}; handle_message(socket_closed, State = #state{waiting_socket_close = true, closing_reason = Reason}) -> {stop, {shutdown, Reason}, State}; handle_message(socket_closed, State = #state{waiting_socket_close = false}) -> {stop, socket_closed_unexpectedly, State}; handle_message({socket_error, _} = SocketError, State) -> {stop, SocketError, State}; handle_message({channel_exit, Reason}, State) -> {stop, {channel0_died, Reason}, State}; handle_message(heartbeat_timeout, State) -> {stop, heartbeat_timeout, State}. closing(_ChannelCloseType, Reason, State) -> {ok, State#state{closing_reason = Reason}}. channels_terminated(State = #state{closing_reason = {server_initiated_close, _, _}}) -> {ok, State#state{waiting_socket_close = true}}; channels_terminated(State) -> {ok, State}. terminate(_Reason, _State) -> ok. i(type, _State) -> network; i(heartbeat, State) -> State#state.heartbeat; i(frame_max, State) -> State#state.frame_max; i(sock, State) -> State#state.sock; i(Item, _State) -> throw({bad_argument, Item}). info_keys() -> ?INFO_KEYS. connect(AmqpParams = #amqp_params{ssl_options = none, host = Host, port = Port}, SIF, ChMgr, State) -> case gen_tcp:connect(Host, Port, ?RABBIT_TCP_OPTS) of {ok, Sock} -> try_handshake(AmqpParams, SIF, ChMgr, State#state{sock = Sock}); {error, _} = E -> E end; connect(AmqpParams = #amqp_params{ssl_options = SslOpts, host = Host, port = Port}, SIF, ChMgr, State) -> rabbit_misc:start_applications([crypto, public_key, ssl]), case gen_tcp:connect(Host, Port, ?RABBIT_TCP_OPTS) of {ok, Sock} -> case ssl:connect(Sock, SslOpts) of {ok, SslSock} -> RabbitSslSock = #ssl_socket{ssl = SslSock, tcp = Sock}, try_handshake(AmqpParams, SIF, ChMgr, State#state{sock = RabbitSslSock}); {error, _} = E -> E end; {error, _} = E -> E end. try_handshake(AmqpParams, SIF, ChMgr, State) -> try handshake(AmqpParams, SIF, ChMgr, State) of Return -> Return catch exit:Reason -> {error, Reason} end. handshake(AmqpParams, SIF, ChMgr, State0 = #state{sock = Sock}) -> ok = rabbit_net:send(Sock, ?PROTOCOL_HEADER), {SHF, State1} = start_infrastructure(SIF, ChMgr, State0), network_handshake(AmqpParams, SHF, State1). start_infrastructure(SIF, ChMgr, State = #state{sock = Sock}) -> {ok, {_MainReader, _AState, Writer, SHF}} = SIF(Sock, ChMgr), {SHF, State#state{writer0 = Writer}}. network_handshake(AmqpParams, SHF, State0) -> Start = #'connection.start'{server_properties = ServerProperties, mechanisms = Mechanisms} = handshake_recv('connection.start'), ok = check_version(Start), Tune = login(AmqpParams, Mechanisms, State0), {TuneOk, ChannelMax, State1} = tune(Tune, AmqpParams, SHF, State0), do2(TuneOk, State1), do2(#'connection.open'{virtual_host = AmqpParams#amqp_params.virtual_host}, State1), Params = {ServerProperties, ChannelMax, State1}, case handshake_recv('connection.open_ok') of #'connection.open_ok'{} -> {ok, Params}; {closing, #amqp_error{} = AmqpError, Error} -> {closing, Params, AmqpError, Error} end. check_version(#'connection.start'{version_major = ?PROTOCOL_VERSION_MAJOR, version_minor = ?PROTOCOL_VERSION_MINOR}) -> ok; check_version(#'connection.start'{version_major = 8, version_minor = 0}) -> exit({protocol_version_mismatch, 0, 8}); check_version(#'connection.start'{version_major = Major, version_minor = Minor}) -> exit({protocol_version_mismatch, Major, Minor}). tune(#'connection.tune'{channel_max = ServerChannelMax, frame_max = ServerFrameMax, heartbeat = ServerHeartbeat}, #amqp_params{channel_max = ClientChannelMax, frame_max = ClientFrameMax, heartbeat = ClientHeartbeat}, SHF, State) -> [ChannelMax, Heartbeat, FrameMax] = lists:zipwith(fun (Client, Server) when Client =:= 0; Server =:= 0 -> lists:max([Client, Server]); (Client, Server) -> lists:min([Client, Server]) end, [ClientChannelMax, ClientHeartbeat, ClientFrameMax], [ServerChannelMax, ServerHeartbeat, ServerFrameMax]), NewState = State#state{heartbeat = Heartbeat, frame_max = FrameMax}, start_heartbeat(SHF, NewState), {#'connection.tune_ok'{channel_max = ChannelMax, frame_max = FrameMax, heartbeat = Heartbeat}, ChannelMax, NewState}. start_heartbeat(SHF, #state{sock = Sock, heartbeat = Heartbeat}) -> Frame = rabbit_binary_generator:build_heartbeat_frame(), SendFun = fun () -> catch rabbit_net:send(Sock, Frame) end, Connection = self(), ReceiveFun = fun () -> Connection ! heartbeat_timeout end, SHF(Sock, Heartbeat, SendFun, Heartbeat, ReceiveFun). login(Params = #amqp_params{auth_mechanisms = ClientMechanisms, client_properties = UserProps}, ServerMechanismsStr, State) -> ServerMechanisms = string:tokens(binary_to_list(ServerMechanismsStr), " "), case [{N, S, F} || F <- ClientMechanisms, {N, S} <- [F(none, Params, init)], lists:member(binary_to_list(N), ServerMechanisms)] of [{Name, MState0, Mech}|_] -> {Resp, MState1} = Mech(none, Params, MState0), StartOk = #'connection.start_ok'{ client_properties = client_properties(UserProps), mechanism = Name, response = Resp}, do2(StartOk, State), login_loop(Mech, MState1, Params, State); [] -> exit({no_suitable_auth_mechanism, ServerMechanisms}) end. login_loop(Mech, MState0, Params, State) -> case handshake_recv('connection.tune') of Tune = #'connection.tune'{} -> Tune; #'connection.secure'{challenge = Challenge} -> {Resp, MState1} = Mech(Challenge, Params, MState0), do2(#'connection.secure_ok'{response = Resp}, State), login_loop(Mech, MState1, Params, State) end. client_properties(UserProperties) -> {ok, Vsn} = application:get_key(amqp_client, vsn), Default = [{<<"product">>, longstr, <<"RabbitMQ">>}, {<<"version">>, longstr, list_to_binary(Vsn)}, {<<"platform">>, longstr, <<"Erlang">>}, {<<"copyright">>, longstr, <<"Copyright (c) 2007-2011 VMware, Inc.">>}, {<<"information">>, longstr, <<"Licensed under the MPL. " "See /">>}, {<<"capabilities">>, table, ?CLIENT_CAPABILITIES}], lists:foldl(fun({K, _, _} = Tuple, Acc) -> lists:keystore(K, 1, Acc, Tuple) end, Default, UserProperties). handshake_recv(Expecting) -> receive {'$gen_cast', {method, Method, none}} -> case {Expecting, element(1, Method)} of {E, M} when E =:= M -> Method; {'connection.open_ok', _} -> {closing, #amqp_error{name = command_invalid, explanation = "was expecting " "connection.open_ok"}, {error, {unexpected_method, Method, {expecting, Expecting}}}}; _ -> throw({unexpected_method, Method, {expecting, Expecting}}) end; socket_closed -> case Expecting of 'connection.tune' -> exit(auth_failure); 'connection.open_ok' -> exit(access_refused); _ -> exit({socket_closed_unexpectedly, Expecting}) end; {socket_error, _} = SocketError -> exit({SocketError, {expecting, Expecting}}); heartbeat_timeout -> exit(heartbeat_timeout); Other -> throw({handshake_recv_unexpected_message, Other}) after ?HANDSHAKE_RECEIVE_TIMEOUT -> case Expecting of 'connection.open_ok' -> {closing, #amqp_error{name = internal_error, explanation = "handshake timed out waiting " "connection.open_ok"}, {error, handshake_receive_timed_out}}; _ -> exit(handshake_receive_timed_out) end end.
3e3d423658d68d1aa38355f48cc1ec283ce8bdf4c25faa4031aa1b46e49a5a76
synduce/Synduce
leftmostodd.ml
* @synduce -s 2 -NB (* The type of labelled binary trees *) type 'a btree = | Empty | Node of 'a * 'a btree * 'a btree (* Zipper for labelled binary trees *) type sel = | Left | Right type 'c zipper = | Top | Zip of sel * 'c * 'c btree * 'c zipper let rec spec = function | Empty -> false, 1 | Node (a, l, r) -> let b1, x1 = spec l in if b1 then b1, x1 else if a mod 2 = 1 then true, a else spec r ;; let rec target = function | Top -> [%synt s0] | Zip (c, a, child, z) -> aux a child z c and aux a child z = function | Left -> [%synt joinl] | Right -> [%synt joinr] and og = function | Empty -> false, 1 | Node (a, l, r) -> let b1, x1 = og l in if b1 then b1, x1 else if a mod 2 = 1 then true, a else og r ;; let rec repr = function | Top -> Empty | Zip (w, lbl, child, z) -> h lbl child z w and h lbl child z = function | Left -> Node (lbl, child, repr z) | Right -> Node (lbl, repr z, child) ;;
null
https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/treepaths/leftmostodd.ml
ocaml
The type of labelled binary trees Zipper for labelled binary trees
* @synduce -s 2 -NB type 'a btree = | Empty | Node of 'a * 'a btree * 'a btree type sel = | Left | Right type 'c zipper = | Top | Zip of sel * 'c * 'c btree * 'c zipper let rec spec = function | Empty -> false, 1 | Node (a, l, r) -> let b1, x1 = spec l in if b1 then b1, x1 else if a mod 2 = 1 then true, a else spec r ;; let rec target = function | Top -> [%synt s0] | Zip (c, a, child, z) -> aux a child z c and aux a child z = function | Left -> [%synt joinl] | Right -> [%synt joinr] and og = function | Empty -> false, 1 | Node (a, l, r) -> let b1, x1 = og l in if b1 then b1, x1 else if a mod 2 = 1 then true, a else og r ;; let rec repr = function | Top -> Empty | Zip (w, lbl, child, z) -> h lbl child z w and h lbl child z = function | Left -> Node (lbl, child, repr z) | Right -> Node (lbl, repr z, child) ;;
5340e46f74df6ae15fb7f4b6cfdf40f8fd6b1e494d919c2fd4571d7dc30894df
mbillingr/lisp-in-small-pieces
system.scm
(define-class Program Object ()) (define-class Reference Program (variable)) (define-class Local-Reference Reference ()) (define-class Global-Reference Reference ()) (define-class Predefined-Reference Reference ()) (define-class Global-Assignment Program (variable form)) (define-class Local-Assignment Program (reference form)) (define-class Function Program (variables body)) (define-class Alternative Program (condition consequent alternant)) (define-class Sequence Program (first last)) (define-class Constant Program (value)) (define-class Application Program ()) (define-class Regular-Application Application (function arguments)) (define-class Predefined-Application Application (variable arguments)) (define-class Fix-Let Program (variables arguments body)) (define-class Arguments Program (first others)) (define-class No-Argument Program ()) (define-class Variable Object (name)) (define-class Global-Variable Variable ()) (define-class Predefined-Variable Variable (description)) (define-class Local-Variable Variable (mutable? dotted?)) (define-class Magic-Keyword Object (name handler)) (define-class Environment Object (next)) (define-class Full-Environment Environment (variable)) (define-class Functional-Description Object (comparator arity text)) (include "visualize.scm") (include "scan-out-defines.scm") (define (objectify e r) ;(println "objectify" e) (if (atom? e) (cond ((Magic-Keyword? e) e) ((Program? e) e) ((symbol? e) (objectify-symbol e r)) (else (objectify-quotation e r))) (let ((m (objectify (car e) r))) (if (Magic-Keyword? m) ((Magic-Keyword-handler m) e r) (objectify-application m (cdr e) r))))) (define (objectify-quotation value r) (make-Constant value)) (define (objectify-alternative ec et ef r) (make-Alternative (objectify ec r) (objectify et r) (objectify ef r))) (define (objectify-sequence e* r) (if (pair? e*) (if (pair? (cdr e*)) (let ((a (objectify (car e*) r))) (make-Sequence a (objectify-sequence (cdr e*) r))) (objectify (car e*) r)) (make-Constant 42))) (define (objectify-application ff e* r) (let ((ee* (convert2arguments (map (lambda (e) (objectify e r)) e*)))) (cond ((Function? ff) (process-closed-application ff ee*)) ((Predefined-Reference? ff) (let* ((fvf (Predefined-Reference-variable ff)) (desc (Predefined-Variable-description fvf))) (if (Functional-Description? desc) (if ((Functional-Description-comparator desc) (length e*) (Functional-Description-arity desc)) (make-Predefined-Application fvf ee*) (objectify-error "Incorrect predefined arity" ff e*)) (make-Regular-Application ff ee*)))) (else (make-Regular-Application ff ee*))))) (define (process-closed-application f e*) (let ((v* (Function-variables f)) (b (Function-body f))) (if (and (pair? v*) (Local-Variable-dotted? (car (last-pair v*)))) (process-nary-closed-application f e*) (if (= (number-of e*) (length v*)) (make-Fix-Let v* e* b) (objectify-error "Incorrect regular arity" f e*))))) (define (convert2arguments e*) (if (pair? e*) (make-Arguments (car e*) (convert2arguments (cdr e*))) (make-No-Argument))) (define-generic (number-of (o)) (error "no implementation of number-of" o)) (define-method (number-of (o Arguments)) (+ 1 (number-of (Arguments-others o)))) (define-method (number-of (o No-Argument)) 0) (define (process-nary-closed-application f e*) (let* ((v* (Function-variables f)) (b (Function-body f)) (o (make-Fix-Let v* (let gather ((e* e*) (v* v*)) (if (Local-Variable-dotted? (car v*)) (make-Arguments (let pack ((e* e*)) (if (Arguments? e*) (make-Predefined-Application (find-variable? 'cons g.predef) (make-Arguments (Arguments-first e*) (make-Arguments (pack (Arguments-others e*)) (make-No-Argument)))) (make-Constant '()))) (make-No-Argument)) (if (Arguments? e*) (make-Arguments (Arguments-first e*) (gather (Arguments-others e*) (cdr v*))) (objectify-error "Incorrect dotted arity" f e*)))) b))) (set-Local-Variable-dotted?! (car (last-pair v*)) #f) o)) (define (objectify-function names body r) (let* ((vars (objectify-variables-list names)) (b (objectify-sequence body (r-extend* r vars)))) (make-Function vars b))) (define (objectify-variables-list names) (if (pair? names) (cons (make-Local-Variable (car names) #f #f) (objectify-variables-list (cdr names))) (if (symbol? names) (list (make-Local-Variable names #f #t)) '()))) (define (objectify-symbol variable r) (let ((v (find-variable? variable r))) (cond ((Magic-Keyword? v) v) ((Local-Variable? v) (make-Local-Reference v)) ((Global-Variable? v) (make-Global-Reference v)) ((Predefined-Variable? v) (make-Predefined-Reference v)) (else (objectify-free-global-reference variable r))))) (define (objectify-free-global-reference name r) (let ((v (make-Global-Variable name))) (insert-global! v r) (make-Global-Reference v))) (define (r-extend* r vars) (if (pair? vars) (r-extend (r-extend* r (cdr vars)) (car vars)) r)) (define (r-extend r var) (make-Full-Environment r var)) (define (find-variable? name r) (if (Full-Environment? r) (let ((var (Full-Environment-variable r))) (if (eq? name (cond ((Variable? var) (Variable-name var)) ((Magic-Keyword? var) (Magic-Keyword-name var)))) var (find-variable? name (Full-Environment-next r)))) (if (Environment? r) (find-variable? name (Environment-next r)) #f))) (define (insert-global! variable r) (let ((r (find-global-environment r))) (set-Environment-next! r (make-Full-Environment (Environment-next r) variable)))) (define (mark-global-preparation-environment g) (make-Environment g)) (define (find-global-environment r) (if (Full-Environment? r) (find-global-environment (Full-Environment-next r)) r)) (define (objectify-assignment variable e r) (let ((ov (objectify variable r)) (of (objectify e r))) (cond ((Local-Reference? ov) (set-Local-Variable-mutable?! (Local-Reference-variable ov) #t) (make-Local-Assignment ov of)) ((Global-Reference? ov) (make-Global-Assignment (Global-Reference-variable ov) of)) (else (objectify-error "Illegal mutated reference" variable))))) (define (objectify-definition var body r) (if (pair? var) (objectify-assignment (car var) (cons 'lambda (cons (cdr var) body)) r) ;(make-Definition (objectify (car var) r) ; (objectify (cons 'lambda (cons (cdr var) body)) r)) (objectify-assignment var (car body) r))) ;(make-Definition (objectify var r) ; (objectify (car body) r)))) (define special-if (make-Magic-Keyword 'if (lambda (e r) (objectify-alternative (cadr e) (caddr e) (cadddr e) r)))) (define special-begin (make-Magic-Keyword 'begin (lambda (e r) (objectify-sequence (cdr e) r)))) (define special-quote (make-Magic-Keyword 'quote (lambda (e r) (objectify-quotation (cadr e) r)))) (define special-set! (make-Magic-Keyword 'set! (lambda (e r) (objectify-assignment (cadr e) (caddr e) r)))) (define special-lambda (make-Magic-Keyword 'lambda (lambda (e r) (objectify-function (cadr e) (scan-out-defines (cddr e)) r)))) (define special-define (make-Magic-Keyword 'define (lambda (e r) (objectify-definition (cadr e) (cddr e) r)))) Backquote forms are supposed to be correct . This is very ugly and only approximate . should be better interleaved with ;;; objectification. What if unquote shadows lexically a comma ? ;;; QUICK and DIRTY! (define special-quasiquote (make-Magic-Keyword 'quasiquote (lambda (e r) (define (walk e) (if (pair? e) (if (eq? (car e) 'unquote) (cadr e) (if (eq? (car e) 'quasiquote) (objectify-error "No embedded quasiquotation" e) (walk-pair e))) (list special-quote e))) (define (walk-pair e) (if (pair? (car e)) (if (eq? (car (car e)) 'unquote-splicing) (list (make-Predefined-Reference (find-variable? 'append g.predef)) (cadr (car e)) (walk (cdr e))) (list (make-Predefined-Reference (find-variable? 'cons g.predef)) (walk (car e)) (walk (cdr e)))) (list (make-Predefined-Reference (find-variable? 'cons g.predef)) (list special-quote (car e)) (walk (cdr e))))) (objectify (walk (cadr e)) r)))) (define *special-form-keywords* (list special-quote special-if special-begin special-set! special-lambda ; ... special-define special-quasiquote)) (define-class Evaluator Object (mother Preparation-Environment RunTime-Environment eval expand)) (define (create-evaluator old-level) (let ((level 'wait) (g g.predef) (sg sg.predef)) (define (expand e) (let ((prg (objectify e (Evaluator-Preparation-Environment level)))) (enrich-with-new-global-variables! level) prg)) (define (eval e) (let ((prg (expand e))) (evaluate prg (Evaluator-RunTime-Environment level)))) ;; Create resulting evaluator instance (set! level (make-Evaluator old-level 'wait 'wait eval expand)) ;; Enrich environment with eval (set! g (r-extend* g *special-form-keywords*)) (set! g (r-extend* g (make-macro-environment level))) (let ((eval-var (make-Predefined-Variable 'eval (make-Functional-Description = 1 ""))) (eval-fn (make-RunTime-Primitive eval = 1))) (set! g (r-extend g eval-var)) (set! sg (sr-extend sg eval-var eval-fn))) ;; Mark the beginning of the global environment (set-Evaluator-Preparation-Environment! level (mark-global-preparation-environment g)) (set-Evaluator-RunTime-Environment! level (mark-global-runtime-environment sg)) level)) (define (make-macro-environment current-level) (let ((metalevel (delay (create-evaluator current-level)))) (list (make-Magic-Keyword 'eval-in-abbreviation-world (special-eval-in-abbreviation-world metalevel)) (make-Magic-Keyword 'define-abbreviation (special-define-abbreviation metalevel)) (make-Magic-Keyword 'let-abbreviation (special-let-abbreviation metalevel)) (make-Magic-Keyword 'with-aliases (special-with-aliases metalevel))))) (define (special-eval-in-abbreviation-world level) (lambda (e r) (let ((body (cdr e))) (objectify ((Evaluator-eval (force level)) `(,special-begin . ,body)) r)))) (define (special-define-abbreviation level) (lambda (e r) (let* ((call (cadr e)) (body (cddr e)) (name (car call)) (variables (cdr call))) (let ((expander ((Evaluator-eval (force level)) `(,special-lambda ,variables . ,body)))) (define (handler e r) (println "| expanding macro" e) (println "| =>" (invoke expander (cdr e))) (objectify (invoke expander (cdr e)) r)) (insert-global! (make-Magic-Keyword name handler) r) (objectify #t r))))) (define (special-let-abbreviation level) (lambda (e r) (let ((level (force level)) (macros (cadr e)) (body (cddr e))) (define (make-macro def) (let* ((call (cadr def)) (body (cddr def)) (name (car call)) (variables (cdr call))) (let ((expander ((Evaluator-eval level) `(,special-lambda ,variables . ,body)))) (define (handler e r) (objectify (invoke expander (cdr e)) r)) (make-Magic-Keyword name handler)))) (objectify `(,special-begin . ,body) (r-extend* r (map mace-macro macros)))))) (define (special-with-aliases level) (lambda (e current-r) (let* ((level (force level)) (oldr (Evaluator-Preparation-Environment level)) (oldsr (Evaluator-Runtime-Environment level)) (aliases (cadr e)) (body (cddr e))) (let bind ((aliases aliases) (r oldr) (sr oldsr)) (if (pair? aliases) (let* ((variable (car (car aliases))) (word (cadr (car aliases))) (var (make-Local-Variable variable #f #f))) (bind (cdr aliases) (r-extend r var) (sr-extend sr var (objectify word current-r)))) (let ((result 'wait)) (set-Evaluator-Preparation-Environment! level r) (set-Evaluator-RunTime-Environment! level sr) (set! result (objectify `(,special-begin . ,body) current-r)) (set-Evaluator-Preparation-Environment! level oldr) (set-Evaluator-RunTime-Environment! level oldsr) result))))))
null
https://raw.githubusercontent.com/mbillingr/lisp-in-small-pieces/b2b158dfa91dc95d75af4bd7d93f8df22219047e/09-macros/system.scm
scheme
(println "objectify" e) (make-Definition (objectify (car var) r) (objectify (cons 'lambda (cons (cdr var) body)) r)) (make-Definition (objectify var r) (objectify (car body) r)))) objectification. What if unquote shadows lexically a comma ? QUICK and DIRTY! ... Create resulting evaluator instance Enrich environment with eval Mark the beginning of the global environment
(define-class Program Object ()) (define-class Reference Program (variable)) (define-class Local-Reference Reference ()) (define-class Global-Reference Reference ()) (define-class Predefined-Reference Reference ()) (define-class Global-Assignment Program (variable form)) (define-class Local-Assignment Program (reference form)) (define-class Function Program (variables body)) (define-class Alternative Program (condition consequent alternant)) (define-class Sequence Program (first last)) (define-class Constant Program (value)) (define-class Application Program ()) (define-class Regular-Application Application (function arguments)) (define-class Predefined-Application Application (variable arguments)) (define-class Fix-Let Program (variables arguments body)) (define-class Arguments Program (first others)) (define-class No-Argument Program ()) (define-class Variable Object (name)) (define-class Global-Variable Variable ()) (define-class Predefined-Variable Variable (description)) (define-class Local-Variable Variable (mutable? dotted?)) (define-class Magic-Keyword Object (name handler)) (define-class Environment Object (next)) (define-class Full-Environment Environment (variable)) (define-class Functional-Description Object (comparator arity text)) (include "visualize.scm") (include "scan-out-defines.scm") (define (objectify e r) (if (atom? e) (cond ((Magic-Keyword? e) e) ((Program? e) e) ((symbol? e) (objectify-symbol e r)) (else (objectify-quotation e r))) (let ((m (objectify (car e) r))) (if (Magic-Keyword? m) ((Magic-Keyword-handler m) e r) (objectify-application m (cdr e) r))))) (define (objectify-quotation value r) (make-Constant value)) (define (objectify-alternative ec et ef r) (make-Alternative (objectify ec r) (objectify et r) (objectify ef r))) (define (objectify-sequence e* r) (if (pair? e*) (if (pair? (cdr e*)) (let ((a (objectify (car e*) r))) (make-Sequence a (objectify-sequence (cdr e*) r))) (objectify (car e*) r)) (make-Constant 42))) (define (objectify-application ff e* r) (let ((ee* (convert2arguments (map (lambda (e) (objectify e r)) e*)))) (cond ((Function? ff) (process-closed-application ff ee*)) ((Predefined-Reference? ff) (let* ((fvf (Predefined-Reference-variable ff)) (desc (Predefined-Variable-description fvf))) (if (Functional-Description? desc) (if ((Functional-Description-comparator desc) (length e*) (Functional-Description-arity desc)) (make-Predefined-Application fvf ee*) (objectify-error "Incorrect predefined arity" ff e*)) (make-Regular-Application ff ee*)))) (else (make-Regular-Application ff ee*))))) (define (process-closed-application f e*) (let ((v* (Function-variables f)) (b (Function-body f))) (if (and (pair? v*) (Local-Variable-dotted? (car (last-pair v*)))) (process-nary-closed-application f e*) (if (= (number-of e*) (length v*)) (make-Fix-Let v* e* b) (objectify-error "Incorrect regular arity" f e*))))) (define (convert2arguments e*) (if (pair? e*) (make-Arguments (car e*) (convert2arguments (cdr e*))) (make-No-Argument))) (define-generic (number-of (o)) (error "no implementation of number-of" o)) (define-method (number-of (o Arguments)) (+ 1 (number-of (Arguments-others o)))) (define-method (number-of (o No-Argument)) 0) (define (process-nary-closed-application f e*) (let* ((v* (Function-variables f)) (b (Function-body f)) (o (make-Fix-Let v* (let gather ((e* e*) (v* v*)) (if (Local-Variable-dotted? (car v*)) (make-Arguments (let pack ((e* e*)) (if (Arguments? e*) (make-Predefined-Application (find-variable? 'cons g.predef) (make-Arguments (Arguments-first e*) (make-Arguments (pack (Arguments-others e*)) (make-No-Argument)))) (make-Constant '()))) (make-No-Argument)) (if (Arguments? e*) (make-Arguments (Arguments-first e*) (gather (Arguments-others e*) (cdr v*))) (objectify-error "Incorrect dotted arity" f e*)))) b))) (set-Local-Variable-dotted?! (car (last-pair v*)) #f) o)) (define (objectify-function names body r) (let* ((vars (objectify-variables-list names)) (b (objectify-sequence body (r-extend* r vars)))) (make-Function vars b))) (define (objectify-variables-list names) (if (pair? names) (cons (make-Local-Variable (car names) #f #f) (objectify-variables-list (cdr names))) (if (symbol? names) (list (make-Local-Variable names #f #t)) '()))) (define (objectify-symbol variable r) (let ((v (find-variable? variable r))) (cond ((Magic-Keyword? v) v) ((Local-Variable? v) (make-Local-Reference v)) ((Global-Variable? v) (make-Global-Reference v)) ((Predefined-Variable? v) (make-Predefined-Reference v)) (else (objectify-free-global-reference variable r))))) (define (objectify-free-global-reference name r) (let ((v (make-Global-Variable name))) (insert-global! v r) (make-Global-Reference v))) (define (r-extend* r vars) (if (pair? vars) (r-extend (r-extend* r (cdr vars)) (car vars)) r)) (define (r-extend r var) (make-Full-Environment r var)) (define (find-variable? name r) (if (Full-Environment? r) (let ((var (Full-Environment-variable r))) (if (eq? name (cond ((Variable? var) (Variable-name var)) ((Magic-Keyword? var) (Magic-Keyword-name var)))) var (find-variable? name (Full-Environment-next r)))) (if (Environment? r) (find-variable? name (Environment-next r)) #f))) (define (insert-global! variable r) (let ((r (find-global-environment r))) (set-Environment-next! r (make-Full-Environment (Environment-next r) variable)))) (define (mark-global-preparation-environment g) (make-Environment g)) (define (find-global-environment r) (if (Full-Environment? r) (find-global-environment (Full-Environment-next r)) r)) (define (objectify-assignment variable e r) (let ((ov (objectify variable r)) (of (objectify e r))) (cond ((Local-Reference? ov) (set-Local-Variable-mutable?! (Local-Reference-variable ov) #t) (make-Local-Assignment ov of)) ((Global-Reference? ov) (make-Global-Assignment (Global-Reference-variable ov) of)) (else (objectify-error "Illegal mutated reference" variable))))) (define (objectify-definition var body r) (if (pair? var) (objectify-assignment (car var) (cons 'lambda (cons (cdr var) body)) r) (objectify-assignment var (car body) r))) (define special-if (make-Magic-Keyword 'if (lambda (e r) (objectify-alternative (cadr e) (caddr e) (cadddr e) r)))) (define special-begin (make-Magic-Keyword 'begin (lambda (e r) (objectify-sequence (cdr e) r)))) (define special-quote (make-Magic-Keyword 'quote (lambda (e r) (objectify-quotation (cadr e) r)))) (define special-set! (make-Magic-Keyword 'set! (lambda (e r) (objectify-assignment (cadr e) (caddr e) r)))) (define special-lambda (make-Magic-Keyword 'lambda (lambda (e r) (objectify-function (cadr e) (scan-out-defines (cddr e)) r)))) (define special-define (make-Magic-Keyword 'define (lambda (e r) (objectify-definition (cadr e) (cddr e) r)))) Backquote forms are supposed to be correct . This is very ugly and only approximate . should be better interleaved with (define special-quasiquote (make-Magic-Keyword 'quasiquote (lambda (e r) (define (walk e) (if (pair? e) (if (eq? (car e) 'unquote) (cadr e) (if (eq? (car e) 'quasiquote) (objectify-error "No embedded quasiquotation" e) (walk-pair e))) (list special-quote e))) (define (walk-pair e) (if (pair? (car e)) (if (eq? (car (car e)) 'unquote-splicing) (list (make-Predefined-Reference (find-variable? 'append g.predef)) (cadr (car e)) (walk (cdr e))) (list (make-Predefined-Reference (find-variable? 'cons g.predef)) (walk (car e)) (walk (cdr e)))) (list (make-Predefined-Reference (find-variable? 'cons g.predef)) (list special-quote (car e)) (walk (cdr e))))) (objectify (walk (cadr e)) r)))) (define *special-form-keywords* (list special-quote special-if special-begin special-set! special-lambda special-define special-quasiquote)) (define-class Evaluator Object (mother Preparation-Environment RunTime-Environment eval expand)) (define (create-evaluator old-level) (let ((level 'wait) (g g.predef) (sg sg.predef)) (define (expand e) (let ((prg (objectify e (Evaluator-Preparation-Environment level)))) (enrich-with-new-global-variables! level) prg)) (define (eval e) (let ((prg (expand e))) (evaluate prg (Evaluator-RunTime-Environment level)))) (set! level (make-Evaluator old-level 'wait 'wait eval expand)) (set! g (r-extend* g *special-form-keywords*)) (set! g (r-extend* g (make-macro-environment level))) (let ((eval-var (make-Predefined-Variable 'eval (make-Functional-Description = 1 ""))) (eval-fn (make-RunTime-Primitive eval = 1))) (set! g (r-extend g eval-var)) (set! sg (sr-extend sg eval-var eval-fn))) (set-Evaluator-Preparation-Environment! level (mark-global-preparation-environment g)) (set-Evaluator-RunTime-Environment! level (mark-global-runtime-environment sg)) level)) (define (make-macro-environment current-level) (let ((metalevel (delay (create-evaluator current-level)))) (list (make-Magic-Keyword 'eval-in-abbreviation-world (special-eval-in-abbreviation-world metalevel)) (make-Magic-Keyword 'define-abbreviation (special-define-abbreviation metalevel)) (make-Magic-Keyword 'let-abbreviation (special-let-abbreviation metalevel)) (make-Magic-Keyword 'with-aliases (special-with-aliases metalevel))))) (define (special-eval-in-abbreviation-world level) (lambda (e r) (let ((body (cdr e))) (objectify ((Evaluator-eval (force level)) `(,special-begin . ,body)) r)))) (define (special-define-abbreviation level) (lambda (e r) (let* ((call (cadr e)) (body (cddr e)) (name (car call)) (variables (cdr call))) (let ((expander ((Evaluator-eval (force level)) `(,special-lambda ,variables . ,body)))) (define (handler e r) (println "| expanding macro" e) (println "| =>" (invoke expander (cdr e))) (objectify (invoke expander (cdr e)) r)) (insert-global! (make-Magic-Keyword name handler) r) (objectify #t r))))) (define (special-let-abbreviation level) (lambda (e r) (let ((level (force level)) (macros (cadr e)) (body (cddr e))) (define (make-macro def) (let* ((call (cadr def)) (body (cddr def)) (name (car call)) (variables (cdr call))) (let ((expander ((Evaluator-eval level) `(,special-lambda ,variables . ,body)))) (define (handler e r) (objectify (invoke expander (cdr e)) r)) (make-Magic-Keyword name handler)))) (objectify `(,special-begin . ,body) (r-extend* r (map mace-macro macros)))))) (define (special-with-aliases level) (lambda (e current-r) (let* ((level (force level)) (oldr (Evaluator-Preparation-Environment level)) (oldsr (Evaluator-Runtime-Environment level)) (aliases (cadr e)) (body (cddr e))) (let bind ((aliases aliases) (r oldr) (sr oldsr)) (if (pair? aliases) (let* ((variable (car (car aliases))) (word (cadr (car aliases))) (var (make-Local-Variable variable #f #f))) (bind (cdr aliases) (r-extend r var) (sr-extend sr var (objectify word current-r)))) (let ((result 'wait)) (set-Evaluator-Preparation-Environment! level r) (set-Evaluator-RunTime-Environment! level sr) (set! result (objectify `(,special-begin . ,body) current-r)) (set-Evaluator-Preparation-Environment! level oldr) (set-Evaluator-RunTime-Environment! level oldsr) result))))))
20b930151fbe9d102303e3968c1f42482a1842d230147022dad823e4689b8818
fakedata-haskell/fakedata
House.hs
# LANGUAGE TemplateHaskell # {-# LANGUAGE OverloadedStrings #-} module Faker.House where import Data.Text import Faker import Faker.Internal import Faker.Provider.House import Faker.TH $(generateFakeField "house" "furniture") $(generateFakeField "house" "rooms")
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/src/Faker/House.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell # module Faker.House where import Data.Text import Faker import Faker.Internal import Faker.Provider.House import Faker.TH $(generateFakeField "house" "furniture") $(generateFakeField "house" "rooms")
b6bec2607a40cdb76d5fac47093392bd21864d6dedcc0a1164173e64f8805206
rcherrueau/APE
adder+let-test.rkt
#lang s-exp "../adder+let/lang.rkt" (let ([x 5] [y (add1 x)]) (sub1 y))
null
https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/pan/examples/adder%2Blet-test.rkt
racket
#lang s-exp "../adder+let/lang.rkt" (let ([x 5] [y (add1 x)]) (sub1 y))
e327d70c40111bcf179e59519d728667579a16fd1769bc0f15139aad1fe3b021
dmitryvk/sbcl-win32-threads
early-defstructs.lisp
This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!KERNEL") (/show0 "entering early-defstructs.lisp") (!set-up-structure-object-class) #.`(progn ,@(mapcar (lambda (args) `(defstruct ,@args)) (sb-cold:read-from-file "src/code/early-defstruct-args.lisp-expr"))) (/show0 "done with early-defstructs.lisp")
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/code/early-defstructs.lisp
lisp
more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!KERNEL") (/show0 "entering early-defstructs.lisp") (!set-up-structure-object-class) #.`(progn ,@(mapcar (lambda (args) `(defstruct ,@args)) (sb-cold:read-from-file "src/code/early-defstruct-args.lisp-expr"))) (/show0 "done with early-defstructs.lisp")
567d0cbf3731835caf1d578677d8ba313e74fcc81cdac2686bdefc9f6f1ea44c
sdiehl/write-you-a-haskell
Main.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE GeneralizedNewtypeDeriving # import Syntax import Infer import Parser import Pretty import Eval import Data.Monoid import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.IO as L import Data.List (isPrefixOf, foldl') import Control.Monad.State.Strict import System.Exit import System.Environment import System.Console.Repline ------------------------------------------------------------------------------- -- Types ------------------------------------------------------------------------------- data IState = IState { tyctx :: TypeEnv -- Type environment , tmctx :: TermEnv -- Value environment } initState :: IState initState = IState emptyTyenv emptyTmenv type Repl a = HaskelineT (StateT IState IO) a hoistErr :: Show e => Either e a -> Repl a hoistErr (Right val) = return val hoistErr (Left err) = do liftIO $ print err abort ------------------------------------------------------------------------------- -- Execution ------------------------------------------------------------------------------- evalDef :: TermEnv -> (String, Expr) -> TermEnv evalDef env (nm, ex) = tmctx' where (val, tmctx') = runEval env nm ex exec :: Bool -> L.Text -> Repl () exec update source = do -- Get the current interpreter state st <- get Parser ( returns AST ) mod <- hoistErr $ parseModule "<stdin>" source -- Type Inference ( returns Typing Environment ) tyctx' <- hoistErr $ inferTop (tyctx st) mod -- Create the new environment let st' = st { tmctx = foldl' evalDef (tmctx st) mod , tyctx = tyctx' <> (tyctx st) } -- Update the interpreter state when update (put st') -- If a value is entered, print it. case lookup "it" mod of Nothing -> return () Just ex -> do let (val, _) = runEval (tmctx st') "it" ex showOutput (show val) st' showOutput :: String -> IState -> Repl () showOutput arg st = do case Infer.typeof (tyctx st) "it" of Just val -> liftIO $ putStrLn $ ppsignature (arg, val) Nothing -> return () cmd :: String -> Repl () cmd source = exec True (L.pack source) ------------------------------------------------------------------------------- -- Commands ------------------------------------------------------------------------------- -- :browse command browse :: [String] -> Repl () browse _ = do st <- get liftIO $ mapM_ putStrLn $ filter (not . ('#' `elem`)) $ ppenv (tyctx st) -- :load command load :: [String] -> Repl () load args = do contents <- liftIO $ L.readFile (unwords args) exec True contents -- :type command typeof :: [String] -> Repl () typeof args = do st <- get let arg = unwords args case Infer.typeof (tyctx st) arg of Just val -> liftIO $ putStrLn $ ppsignature (arg, val) Nothing -> exec False (L.pack arg) -- :quit command quit :: a -> Repl () quit _ = liftIO $ exitSuccess ------------------------------------------------------------------------------- -- Tab completion ------------------------------------------------------------------------------- -- Prefix tab completer defaultMatcher :: MonadIO m => [(String, CompletionFunc m)] defaultMatcher = [ (":load" , fileCompleter) ] -- Default tab completer comp :: (Monad m, MonadState IState m) => WordCompleter m comp n = do let cmds = [":load", ":browse", ":quit", ":type"] TypeEnv ctx <- gets tyctx let defs = Map.keys ctx return $ filter (isPrefixOf n) (cmds ++ defs) options :: [(String, [String] -> Repl ())] options = [ ("load" , load) , ("browse" , browse) , ("quit" , quit) , ("type" , Main.typeof) ] completer :: CompleterStyle (StateT IState IO) completer = Prefix (wordCompleter comp) defaultMatcher ------------------------------------------------------------------------------- Shell ------------------------------------------------------------------------------- shell :: Repl a -> IO () shell pre = flip evalStateT initState $ evalRepl "Poly> " cmd options completer pre ------------------------------------------------------------------------------- Toplevel ------------------------------------------------------------------------------- main :: IO () main = do args <- getArgs case args of [] -> shell (return ()) [fname] -> shell (load [fname]) ["test", fname] -> shell (load [fname] >> browse [] >> quit ()) _ -> putStrLn "invalid arguments"
null
https://raw.githubusercontent.com/sdiehl/write-you-a-haskell/ae73485e045ef38f50846b62bd91777a9943d1f7/chapter7/poly/src/Main.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeSynonymInstances # ----------------------------------------------------------------------------- Types ----------------------------------------------------------------------------- Type environment Value environment ----------------------------------------------------------------------------- Execution ----------------------------------------------------------------------------- Get the current interpreter state Type Inference ( returns Typing Environment ) Create the new environment Update the interpreter state If a value is entered, print it. ----------------------------------------------------------------------------- Commands ----------------------------------------------------------------------------- :browse command :load command :type command :quit command ----------------------------------------------------------------------------- Tab completion ----------------------------------------------------------------------------- Prefix tab completer Default tab completer ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -----------------------------------------------------------------------------
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE GeneralizedNewtypeDeriving # import Syntax import Infer import Parser import Pretty import Eval import Data.Monoid import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.IO as L import Data.List (isPrefixOf, foldl') import Control.Monad.State.Strict import System.Exit import System.Environment import System.Console.Repline data IState = IState } initState :: IState initState = IState emptyTyenv emptyTmenv type Repl a = HaskelineT (StateT IState IO) a hoistErr :: Show e => Either e a -> Repl a hoistErr (Right val) = return val hoistErr (Left err) = do liftIO $ print err abort evalDef :: TermEnv -> (String, Expr) -> TermEnv evalDef env (nm, ex) = tmctx' where (val, tmctx') = runEval env nm ex exec :: Bool -> L.Text -> Repl () exec update source = do st <- get Parser ( returns AST ) mod <- hoistErr $ parseModule "<stdin>" source tyctx' <- hoistErr $ inferTop (tyctx st) mod let st' = st { tmctx = foldl' evalDef (tmctx st) mod , tyctx = tyctx' <> (tyctx st) } when update (put st') case lookup "it" mod of Nothing -> return () Just ex -> do let (val, _) = runEval (tmctx st') "it" ex showOutput (show val) st' showOutput :: String -> IState -> Repl () showOutput arg st = do case Infer.typeof (tyctx st) "it" of Just val -> liftIO $ putStrLn $ ppsignature (arg, val) Nothing -> return () cmd :: String -> Repl () cmd source = exec True (L.pack source) browse :: [String] -> Repl () browse _ = do st <- get liftIO $ mapM_ putStrLn $ filter (not . ('#' `elem`)) $ ppenv (tyctx st) load :: [String] -> Repl () load args = do contents <- liftIO $ L.readFile (unwords args) exec True contents typeof :: [String] -> Repl () typeof args = do st <- get let arg = unwords args case Infer.typeof (tyctx st) arg of Just val -> liftIO $ putStrLn $ ppsignature (arg, val) Nothing -> exec False (L.pack arg) quit :: a -> Repl () quit _ = liftIO $ exitSuccess defaultMatcher :: MonadIO m => [(String, CompletionFunc m)] defaultMatcher = [ (":load" , fileCompleter) ] comp :: (Monad m, MonadState IState m) => WordCompleter m comp n = do let cmds = [":load", ":browse", ":quit", ":type"] TypeEnv ctx <- gets tyctx let defs = Map.keys ctx return $ filter (isPrefixOf n) (cmds ++ defs) options :: [(String, [String] -> Repl ())] options = [ ("load" , load) , ("browse" , browse) , ("quit" , quit) , ("type" , Main.typeof) ] completer :: CompleterStyle (StateT IState IO) completer = Prefix (wordCompleter comp) defaultMatcher Shell shell :: Repl a -> IO () shell pre = flip evalStateT initState $ evalRepl "Poly> " cmd options completer pre Toplevel main :: IO () main = do args <- getArgs case args of [] -> shell (return ()) [fname] -> shell (load [fname]) ["test", fname] -> shell (load [fname] >> browse [] >> quit ()) _ -> putStrLn "invalid arguments"
c4698d3b2b4783dbd30ea557bee883a6d682240957b65877d457293e840154de
LPCIC/matita
disambiguateTypes.ml
Copyright ( C ) 2004 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) $ I d : disambiguateTypes.ml 12479 2013 - 02 - 01 13:47:25Z fguidi $ type 'a expected_type = [ `XTNone (* unknown *) | `XTSome of 'a (* the given term *) | `XTSort (* any sort *) | `XTInd (* any (co)inductive type *) ] type domain_item = | Id of string (* literal *) | Symbol of string * int (* literal, instance num *) | Num of int (* instance num *) exception Invalid_choice of (Stdpp.location * string) Lazy.t module OrderedDomain = struct type t = domain_item let compare = Pervasives.compare end (* module Domain = Set.Make (OrderedDomain) *) module Environment = struct module Environment' = Map.Make (OrderedDomain) include Environment' let find k env = match k with Symbol (sym,n) -> (try find k env with Not_found -> find (Symbol (sym,0)) env) | Num n -> (try find k env with Not_found -> find (Num 0) env) | _ -> find k env let cons desc_of_alias k v env = try let current = find k env in let dsc = desc_of_alias v in add k (v :: (List.filter (fun x -> desc_of_alias x <> dsc) current)) env with Not_found -> add k [v] env end type 'term codomain_item = string * (* description *) [`Num_interp of string -> 'term |`Sym_interp of 'term list -> 'term] type interactive_user_uri_choice_type = selection_mode:[`SINGLE | `MULTIPLE] -> ?ok:string -> ?enable_button_for_non_vars:bool -> title:string -> msg:string -> id:string -> NReference.reference list -> NReference.reference list type interactive_interpretation_choice_type = string -> int -> (Stdpp.location list * string * string) list list -> int list type input_or_locate_uri_type = title:string -> ?id:string -> unit -> NReference.reference option let string_of_domain_item = function | Id s -> Printf.sprintf "ID(%s)" s | Symbol (s, i) -> Printf.sprintf "SYMBOL(%s,%d)" s i | Num i -> Printf.sprintf "NUM(instance %d)" i
null
https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/disambiguation/disambiguateTypes.ml
ocaml
unknown the given term any sort any (co)inductive type literal literal, instance num instance num module Domain = Set.Make (OrderedDomain) description
Copyright ( C ) 2004 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) $ I d : disambiguateTypes.ml 12479 2013 - 02 - 01 13:47:25Z fguidi $ ] type domain_item = exception Invalid_choice of (Stdpp.location * string) Lazy.t module OrderedDomain = struct type t = domain_item let compare = Pervasives.compare end module Environment = struct module Environment' = Map.Make (OrderedDomain) include Environment' let find k env = match k with Symbol (sym,n) -> (try find k env with Not_found -> find (Symbol (sym,0)) env) | Num n -> (try find k env with Not_found -> find (Num 0) env) | _ -> find k env let cons desc_of_alias k v env = try let current = find k env in let dsc = desc_of_alias v in add k (v :: (List.filter (fun x -> desc_of_alias x <> dsc) current)) env with Not_found -> add k [v] env end type 'term codomain_item = [`Num_interp of string -> 'term |`Sym_interp of 'term list -> 'term] type interactive_user_uri_choice_type = selection_mode:[`SINGLE | `MULTIPLE] -> ?ok:string -> ?enable_button_for_non_vars:bool -> title:string -> msg:string -> id:string -> NReference.reference list -> NReference.reference list type interactive_interpretation_choice_type = string -> int -> (Stdpp.location list * string * string) list list -> int list type input_or_locate_uri_type = title:string -> ?id:string -> unit -> NReference.reference option let string_of_domain_item = function | Id s -> Printf.sprintf "ID(%s)" s | Symbol (s, i) -> Printf.sprintf "SYMBOL(%s,%d)" s i | Num i -> Printf.sprintf "NUM(instance %d)" i
b212b62334b5d38039bcd9358cb4c0c50fadfd296e61fd505e375135449ff1a7
ghcjs/jsaddle-dom
CSSPageRule.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.CSSPageRule (setSelectorText, getSelectorText, getSelectorTextUnsafe, getSelectorTextUnchecked, getStyle, CSSPageRule(..), gTypeCSSPageRule) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > setSelectorText :: (MonadDOM m, ToJSString val) => CSSPageRule -> Maybe val -> m () setSelectorText self val = liftDOM (self ^. jss "selectorText" (toJSVal val)) | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > getSelectorText :: (MonadDOM m, FromJSString result) => CSSPageRule -> m (Maybe result) getSelectorText self = liftDOM ((self ^. js "selectorText") >>= fromMaybeJSString) | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > getSelectorTextUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => CSSPageRule -> m result getSelectorTextUnsafe self = liftDOM (((self ^. js "selectorText") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > getSelectorTextUnchecked :: (MonadDOM m, FromJSString result) => CSSPageRule -> m result getSelectorTextUnchecked self = liftDOM ((self ^. js "selectorText") >>= fromJSValUnchecked) | < -US/docs/Web/API/CSSPageRule.style Mozilla CSSPageRule.style documentation > getStyle :: (MonadDOM m) => CSSPageRule -> m CSSStyleDeclaration getStyle self = liftDOM ((self ^. js "style") >>= fromJSValUnchecked)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/CSSPageRule.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.CSSPageRule (setSelectorText, getSelectorText, getSelectorTextUnsafe, getSelectorTextUnchecked, getStyle, CSSPageRule(..), gTypeCSSPageRule) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > setSelectorText :: (MonadDOM m, ToJSString val) => CSSPageRule -> Maybe val -> m () setSelectorText self val = liftDOM (self ^. jss "selectorText" (toJSVal val)) | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > getSelectorText :: (MonadDOM m, FromJSString result) => CSSPageRule -> m (Maybe result) getSelectorText self = liftDOM ((self ^. js "selectorText") >>= fromMaybeJSString) | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > getSelectorTextUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => CSSPageRule -> m result getSelectorTextUnsafe self = liftDOM (((self ^. js "selectorText") >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) | < -US/docs/Web/API/CSSPageRule.selectorText Mozilla CSSPageRule.selectorText documentation > getSelectorTextUnchecked :: (MonadDOM m, FromJSString result) => CSSPageRule -> m result getSelectorTextUnchecked self = liftDOM ((self ^. js "selectorText") >>= fromJSValUnchecked) | < -US/docs/Web/API/CSSPageRule.style Mozilla CSSPageRule.style documentation > getStyle :: (MonadDOM m) => CSSPageRule -> m CSSStyleDeclaration getStyle self = liftDOM ((self ^. js "style") >>= fromJSValUnchecked)
f109bda6b3e102966240f4945b079336ae664ebbc1ba331c44aced9ec0a3ca11
jpmonettas/clindex
api.clj
(ns clindex.api "The namespace intended to be required by clindex users. Use `index-project!` for indexing any project and `db` for retrieveing datascript dbs by platform." (:require [clindex.scanner :as scanner] [clindex.indexer :as indexer] [datascript.core :as d] [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.namespace.find :as ns-find] [clojure.tools.namespace.parse :as ns-parse] [clojure.tools.namespace.track :as ns-track] [clindex.schema :refer [schema]] [clindex.utils :as utils] [hawk.core :as hawk] [clojure.tools.namespace.file :as ns-file] [clojure.pprint :as pprint] [clojure.spec.alpha :as s])) (def effective-schema (atom nil)) (def db-conns (atom {})) (def all-projects-by-platform (atom nil)) (def all-ns-by-platform (atom nil)) (def trackers-by-platform (atom nil)) (comment (index-project! "./test-resources/test-project" {:platforms #{:clj}}) (index-project! "/home/jmonetta/my-projects/district0x/memefactory" {:platforms #{:cljs}}) (require '[clojure.pprint :as pprint]) (file-change-handler (fn [diff] (pprint/pprint diff)) #{:clj} {} {:kind :delete :file (io/file "./test-resources/test-project/src/test_code.cljc")}) (file-change-handler (fn [diff] (pprint/pprint diff)) #{:clj} {} {:kind :modify :file (io/file "./test-resources/test-project/src/test_code.cljc")}) ) (defn- get-ns-for-path [all-ns file-path] (->> (vals all-ns) (some #(when (= (:namespace/file-content-path %) file-path) (:namespace/name %))))) (defn- build-dep-map [all-ns] (reduce (fn [r [ns-name {:keys [:namespace/dependencies]}]] (assoc r ns-name dependencies)) {} all-ns)) (defn- build-opts [platform-key] {:platform (case platform-key :clj ns-find/clj :cljs ns-find/cljs)}) (defn- process-unloads [{:keys [tracker] :as m}] (reduce (fn [r ns-symb] (let [ns-id (utils/namespace-id ns-symb) reload? (some #(= % ns-symb) (::ns-track/load tracker))] (cond-> r true (update-in [:tracker ::ns-track/unload] rest) ;; don't remove it if we are going to re load it, since we need the info there (not reload?) (update :namespaces dissoc ns-symb) true (update :tx-data conj [:db.fn/retractEntity ns-id])))) m (::ns-track/unload tracker))) (defn- process-loads [{:keys [tracker namespaces all-projects] :as m} opts] (reduce (fn [r ns-symb] (let [ns-file-path (:namespace/file-content-path (or (get namespaces ns-symb) (meta ns-symb))) ns (scanner/scan-namespace ns-file-path all-projects opts) updated-namespaces (assoc namespaces ns-symb ns) ns-facts (indexer/namespace-full-facts updated-namespaces ns-symb)] (-> r (update-in [:tracker ::ns-track/load] rest) (assoc :namespaces updated-namespaces) (update :tx-data into ns-facts)))) m (::ns-track/load tracker))) (defn- reindex-namespaces [all-projs all-ns tracker opts] (-> {:tracker tracker :tx-data [] :namespaces all-ns :all-projects all-projs} process-unloads (process-loads opts))) (defn- index-file? [file-name platform] ;; to avoid indexing emacs backup files (and (not (.startsWith file-name ".#")) (or (.endsWith file-name "clj") (.endsWith file-name "cljc") (.endsWith file-name "cljs")))) (defn- file-change-handler [on-new-facts platforms ctx {:keys [kind file]}] ;; kind can be :create, :modify or :delete ;; file is java.io.File (doseq [p platforms] (when (index-file? (.getName file) p) (let [plat-opts (build-opts p) all-platform-projs (get @all-projects-by-platform p) all-platform-ns (get @all-ns-by-platform p) platform-tracker (get @trackers-by-platform p) file-path (utils/normalize-path file) platform-tracker' (cond (#{:delete} kind) (let [ns-symb (get-ns-for-path all-platform-ns file-path)] (ns-track/remove platform-tracker [ns-symb])) (#{:modify :add} kind) (let [ns-decl (try (ns-file/read-file-ns-decl file ns-find/clj) (catch Exception e (println "[Warning] exception while trying to read ns-decl for " (merge {:file-path file-path} (ex-data e))))) ns-symb (with-meta (ns-parse/name-from-ns-decl ns-decl) {:namespace/file-content-path file-path}) deps (ns-parse/deps-from-ns-decl ns-decl)] (ns-track/add platform-tracker {ns-symb deps}))) _ (println (format "File %s changed, retracting namespaces (%s), indexing namspeces (%s)" file-path (pr-str (::ns-track/unload platform-tracker')) (pr-str (::ns-track/load platform-tracker')))) {:keys [tx-data namespaces tracker]} (reindex-namespaces all-platform-projs all-platform-ns platform-tracker' plat-opts) tx-data-diff (:tx-data (d/transact! (get @db-conns p) tx-data))] (swap! all-ns-by-platform assoc p namespaces) (swap! trackers-by-platform assoc p tracker) (on-new-facts tx-data-diff))))) (s/def ::on-new-facts (s/fspec :args (s/cat :new-facts (s/coll-of :datomic/fact)))) (s/fdef index-project! :args (s/cat :base-dir :file/path :opts (s/keys :req-un [:clindex/platforms] :opt-un [:datascript/extra-schema ::on-new-facts]))) (defn index-project! "Goes over all Clojure[Script] files (depending on platforms) inside `base-dir` and index facts about the project and all its dependencies. Possible `opts` are : - :platforms (required), a set with the platforms to index, like #{:clj :cljs} - :extra-schema, a datascript schema that is going to be merged with clindex.schema/schema - :on-new-facts, a fn of one arg that will be called with new facts everytime a file inside `base-dir` project sources changes" [base-dir {:keys [platforms extra-schema on-new-facts] :as opts}] (if-not (utils/sane-classpath?) (throw (ex-info "org.clojure/tools.namespace detected on classpath. Clindex uses a modified version of tools.namespace so exclude it from the classpath before continuing" {})) ;; index everything by platform (let [source-paths (->> (:paths (scanner/find-project-in-dir base-dir)) (map (fn [p] (str (utils/normalize-path (io/file base-dir)) p))))] (doseq [p platforms] (let [plat-opts (build-opts p) all-projs (scanner/scan-all-projects base-dir plat-opts) all-ns (scanner/scan-namespaces all-projs plat-opts) tracker (-> (ns-track/tracker) (ns-track/add (build-dep-map (utils/reloadable-namespaces all-ns))) we can discard this first time since we are indexing everything tx-data (-> (indexer/all-facts {:projects all-projs :namespaces all-ns}) utils/check-facts)] (reset! effective-schema (merge schema extra-schema)) (swap! db-conns assoc p (d/create-conn @effective-schema)) (swap! all-projects-by-platform assoc p all-projs) (swap! all-ns-by-platform assoc p all-ns) (swap! trackers-by-platform assoc p tracker) (println (format "About to transact %d facts" (count tx-data) "for platform" p)) (d/transact! (get @db-conns p) tx-data))) ;; install watcher for reindexing when on-new-facts callback provided (when on-new-facts (println "Watching " source-paths) (hawk/watch! [{:paths source-paths :handler (partial file-change-handler on-new-facts platforms)}])))) nil) (s/fdef db :args (s/cat :platform :clindex/platform)) (defn db "Returns the datascript db index for the `platform`" [platform] @(get @db-conns platform)) (defn db-schema "Returns the current dbs schema" [] @effective-schema)
null
https://raw.githubusercontent.com/jpmonettas/clindex/77097d80a23aa85d2ff50e55645a1452f2dcb3c0/src/clindex/api.clj
clojure
don't remove it if we are going to re load it, since we need the info there to avoid indexing emacs backup files kind can be :create, :modify or :delete ;; file is java.io.File index everything by platform install watcher for reindexing when on-new-facts callback provided
(ns clindex.api "The namespace intended to be required by clindex users. Use `index-project!` for indexing any project and `db` for retrieveing datascript dbs by platform." (:require [clindex.scanner :as scanner] [clindex.indexer :as indexer] [datascript.core :as d] [clojure.java.io :as io] [clojure.string :as str] [clojure.tools.namespace.find :as ns-find] [clojure.tools.namespace.parse :as ns-parse] [clojure.tools.namespace.track :as ns-track] [clindex.schema :refer [schema]] [clindex.utils :as utils] [hawk.core :as hawk] [clojure.tools.namespace.file :as ns-file] [clojure.pprint :as pprint] [clojure.spec.alpha :as s])) (def effective-schema (atom nil)) (def db-conns (atom {})) (def all-projects-by-platform (atom nil)) (def all-ns-by-platform (atom nil)) (def trackers-by-platform (atom nil)) (comment (index-project! "./test-resources/test-project" {:platforms #{:clj}}) (index-project! "/home/jmonetta/my-projects/district0x/memefactory" {:platforms #{:cljs}}) (require '[clojure.pprint :as pprint]) (file-change-handler (fn [diff] (pprint/pprint diff)) #{:clj} {} {:kind :delete :file (io/file "./test-resources/test-project/src/test_code.cljc")}) (file-change-handler (fn [diff] (pprint/pprint diff)) #{:clj} {} {:kind :modify :file (io/file "./test-resources/test-project/src/test_code.cljc")}) ) (defn- get-ns-for-path [all-ns file-path] (->> (vals all-ns) (some #(when (= (:namespace/file-content-path %) file-path) (:namespace/name %))))) (defn- build-dep-map [all-ns] (reduce (fn [r [ns-name {:keys [:namespace/dependencies]}]] (assoc r ns-name dependencies)) {} all-ns)) (defn- build-opts [platform-key] {:platform (case platform-key :clj ns-find/clj :cljs ns-find/cljs)}) (defn- process-unloads [{:keys [tracker] :as m}] (reduce (fn [r ns-symb] (let [ns-id (utils/namespace-id ns-symb) reload? (some #(= % ns-symb) (::ns-track/load tracker))] (cond-> r true (update-in [:tracker ::ns-track/unload] rest) (not reload?) (update :namespaces dissoc ns-symb) true (update :tx-data conj [:db.fn/retractEntity ns-id])))) m (::ns-track/unload tracker))) (defn- process-loads [{:keys [tracker namespaces all-projects] :as m} opts] (reduce (fn [r ns-symb] (let [ns-file-path (:namespace/file-content-path (or (get namespaces ns-symb) (meta ns-symb))) ns (scanner/scan-namespace ns-file-path all-projects opts) updated-namespaces (assoc namespaces ns-symb ns) ns-facts (indexer/namespace-full-facts updated-namespaces ns-symb)] (-> r (update-in [:tracker ::ns-track/load] rest) (assoc :namespaces updated-namespaces) (update :tx-data into ns-facts)))) m (::ns-track/load tracker))) (defn- reindex-namespaces [all-projs all-ns tracker opts] (-> {:tracker tracker :tx-data [] :namespaces all-ns :all-projects all-projs} process-unloads (process-loads opts))) (defn- index-file? [file-name platform] (and (not (.startsWith file-name ".#")) (or (.endsWith file-name "clj") (.endsWith file-name "cljc") (.endsWith file-name "cljs")))) (doseq [p platforms] (when (index-file? (.getName file) p) (let [plat-opts (build-opts p) all-platform-projs (get @all-projects-by-platform p) all-platform-ns (get @all-ns-by-platform p) platform-tracker (get @trackers-by-platform p) file-path (utils/normalize-path file) platform-tracker' (cond (#{:delete} kind) (let [ns-symb (get-ns-for-path all-platform-ns file-path)] (ns-track/remove platform-tracker [ns-symb])) (#{:modify :add} kind) (let [ns-decl (try (ns-file/read-file-ns-decl file ns-find/clj) (catch Exception e (println "[Warning] exception while trying to read ns-decl for " (merge {:file-path file-path} (ex-data e))))) ns-symb (with-meta (ns-parse/name-from-ns-decl ns-decl) {:namespace/file-content-path file-path}) deps (ns-parse/deps-from-ns-decl ns-decl)] (ns-track/add platform-tracker {ns-symb deps}))) _ (println (format "File %s changed, retracting namespaces (%s), indexing namspeces (%s)" file-path (pr-str (::ns-track/unload platform-tracker')) (pr-str (::ns-track/load platform-tracker')))) {:keys [tx-data namespaces tracker]} (reindex-namespaces all-platform-projs all-platform-ns platform-tracker' plat-opts) tx-data-diff (:tx-data (d/transact! (get @db-conns p) tx-data))] (swap! all-ns-by-platform assoc p namespaces) (swap! trackers-by-platform assoc p tracker) (on-new-facts tx-data-diff))))) (s/def ::on-new-facts (s/fspec :args (s/cat :new-facts (s/coll-of :datomic/fact)))) (s/fdef index-project! :args (s/cat :base-dir :file/path :opts (s/keys :req-un [:clindex/platforms] :opt-un [:datascript/extra-schema ::on-new-facts]))) (defn index-project! "Goes over all Clojure[Script] files (depending on platforms) inside `base-dir` and index facts about the project and all its dependencies. Possible `opts` are : - :platforms (required), a set with the platforms to index, like #{:clj :cljs} - :extra-schema, a datascript schema that is going to be merged with clindex.schema/schema - :on-new-facts, a fn of one arg that will be called with new facts everytime a file inside `base-dir` project sources changes" [base-dir {:keys [platforms extra-schema on-new-facts] :as opts}] (if-not (utils/sane-classpath?) (throw (ex-info "org.clojure/tools.namespace detected on classpath. Clindex uses a modified version of tools.namespace so exclude it from the classpath before continuing" {})) (let [source-paths (->> (:paths (scanner/find-project-in-dir base-dir)) (map (fn [p] (str (utils/normalize-path (io/file base-dir)) p))))] (doseq [p platforms] (let [plat-opts (build-opts p) all-projs (scanner/scan-all-projects base-dir plat-opts) all-ns (scanner/scan-namespaces all-projs plat-opts) tracker (-> (ns-track/tracker) (ns-track/add (build-dep-map (utils/reloadable-namespaces all-ns))) we can discard this first time since we are indexing everything tx-data (-> (indexer/all-facts {:projects all-projs :namespaces all-ns}) utils/check-facts)] (reset! effective-schema (merge schema extra-schema)) (swap! db-conns assoc p (d/create-conn @effective-schema)) (swap! all-projects-by-platform assoc p all-projs) (swap! all-ns-by-platform assoc p all-ns) (swap! trackers-by-platform assoc p tracker) (println (format "About to transact %d facts" (count tx-data) "for platform" p)) (d/transact! (get @db-conns p) tx-data))) (when on-new-facts (println "Watching " source-paths) (hawk/watch! [{:paths source-paths :handler (partial file-change-handler on-new-facts platforms)}])))) nil) (s/fdef db :args (s/cat :platform :clindex/platform)) (defn db "Returns the datascript db index for the `platform`" [platform] @(get @db-conns platform)) (defn db-schema "Returns the current dbs schema" [] @effective-schema)
5b104cdc5f89c925ffd8c61e741ed9890e83e4eb6189236276ed773d709928a5
haskell-foundation/foundation
Partial.hs
-- | -- Module : Foundation.Partial -- License : BSD-style Maintainer : < > -- Stability : experimental -- Portability : portable -- -- Partial give a way to annotate your partial function with -- a simple wrapper, which can only evaluated using 'fromPartial' -- > fromPartial ( head [ ] ) -- # LANGUAGE GeneralizedNewtypeDeriving # module Foundation.Partial ( Partial , PartialError , partialError , partial , fromPartial , head , fromJust , fromLeft , fromRight ) where import Basement.Compat.Base import Basement.Compat.Identity -- | Partialiality wrapper. newtype Partial a = Partial (Identity a) deriving (Functor, Applicative, Monad) -- | An error related to the evaluation of a Partial value that failed. -- -- it contains the name of the function and the reason for failure data PartialError = PartialError [Char] [Char] deriving (Show,Eq,Typeable) instance Exception PartialError | Throw an asynchronous PartialError partialError :: [Char] -> [Char] -> a partialError lbl exp = throw (PartialError lbl exp) -- | Create a value that is partial. this can only be -- unwrap using the 'fromPartial' function partial :: a -> Partial a partial = pure -- | Dewrap a possible partial value fromPartial :: Partial a -> a fromPartial (Partial ida) = runIdentity ida -- | Partial function to get the head of a list head :: [a] -> Partial a head l = partial $ case l of [] -> partialError "head" "empty list" x:_ -> x -- | Partial function to grab the value inside a Maybe fromJust :: Maybe a -> Partial a fromJust x = partial $ case x of Nothing -> partialError "fromJust" "Nothing" Just y -> y -- Grab the Right value of an Either fromRight :: Either a b -> Partial b fromRight x = partial $ case x of Left _ -> partialError "fromRight" "Left" Right a -> a -- Grab the Left value of an Either fromLeft :: Either a b -> Partial a fromLeft x = partial $ case x of Right _ -> partialError "fromLeft" "Right" Left a -> a
null
https://raw.githubusercontent.com/haskell-foundation/foundation/58568e9f5368170d272000ecf16ef64fb91d0732/foundation/Foundation/Partial.hs
haskell
| Module : Foundation.Partial License : BSD-style Stability : experimental Portability : portable Partial give a way to annotate your partial function with a simple wrapper, which can only evaluated using 'fromPartial' | Partialiality wrapper. | An error related to the evaluation of a Partial value that failed. it contains the name of the function and the reason for failure | Create a value that is partial. this can only be unwrap using the 'fromPartial' function | Dewrap a possible partial value | Partial function to get the head of a list | Partial function to grab the value inside a Maybe Grab the Right value of an Either Grab the Left value of an Either
Maintainer : < > > fromPartial ( head [ ] ) # LANGUAGE GeneralizedNewtypeDeriving # module Foundation.Partial ( Partial , PartialError , partialError , partial , fromPartial , head , fromJust , fromLeft , fromRight ) where import Basement.Compat.Base import Basement.Compat.Identity newtype Partial a = Partial (Identity a) deriving (Functor, Applicative, Monad) data PartialError = PartialError [Char] [Char] deriving (Show,Eq,Typeable) instance Exception PartialError | Throw an asynchronous PartialError partialError :: [Char] -> [Char] -> a partialError lbl exp = throw (PartialError lbl exp) partial :: a -> Partial a partial = pure fromPartial :: Partial a -> a fromPartial (Partial ida) = runIdentity ida head :: [a] -> Partial a head l = partial $ case l of [] -> partialError "head" "empty list" x:_ -> x fromJust :: Maybe a -> Partial a fromJust x = partial $ case x of Nothing -> partialError "fromJust" "Nothing" Just y -> y fromRight :: Either a b -> Partial b fromRight x = partial $ case x of Left _ -> partialError "fromRight" "Left" Right a -> a fromLeft :: Either a b -> Partial a fromLeft x = partial $ case x of Right _ -> partialError "fromLeft" "Right" Left a -> a
fc2189ec4e81027bcf29f02f4723e397e293ea75e79bab0703691305ee818346
ivanperez-keera/Yampa
TailgatingDetector.hs
{-# LANGUAGE Arrows #-} -- | Module : TailgatingDetector -- Description : AFRP Expressitivity Test Copyright : Yale University , 2003 Authors : -- Context: an autonomous flying vehicle carrying out traffic surveillance -- through an on-board video camera. -- -- Objective: finding a tailgater among a group of vehicles traveling along -- a highway lane. The group is defined by the section of the highway in view and thus changes dynamically as ground vehicles with non - zero -- relative speed to the flying vehicles enters or leaves the field of -- vision. -- -- Simplifying assumptions: -- * The positive x-axis of the video images is supposed to correspond to the -- direction of travel. -- * The flying vehicle is assumed to travel directly over and along the -- highway lane when looking for tailgaters. The y-coordinate of the -- highway is thus roughly 0. -- * It is enough to consider the x-coordinate of ground vehicle positions. -- Thus the position and velocity types are both just (signed) Double -- for our purposes. -- I find this example interesting because it makes use of TWO COLLECTION of -- signal functions, these collections HAVE TO BE DYNAMIC by the very nature of the problem , and it makes use of the the fact that CONTINUATIONS ARE FIRST CLASS ENTITIES in a way which arguably also is justified -- by the nature of the problem. module TailgatingDetector where import Data.List (sortBy, (\\)) import FRP.Yampa import FRP.Yampa.Conditional import FRP.Yampa.EventS -- * Testing framework type Position = Double -- [m] type Distance = Double -- [m] type Velocity = Double -- [m/s] -- We'll call any ground vehicle "car". For our purposes, a car is -- represented by its ground position and ground velocity. type Car = (Position, Velocity) -- A highway is just a list of cars. In this simple setting, we assume all -- cars are there all the time (no enter or exit ramps etc.) type Highway = [Car] -- Type of the Video signal. Here just an association list of cars *in view* -- with *relative* positions. type Video = [(Int, Car)] -- System info, such as height and ground speed. Here, just the position. type UAVStatus = Position -- Various ways of making cars. switchAfter :: Time -> SF a b -> (b -> SF a b) -> SF a b switchAfter t sf k = switch (sf &&& after t () >>^ \(b,e) -> (b, e `tag` b)) k mkCar1 :: Position -> Velocity -> SF a Car mkCar1 p0 v = constant v >>> (integral >>^ (+p0)) &&& identity mkCar2 :: Position -> Velocity -> Time -> Velocity -> SF a Car mkCar2 p0 v0 t0 v = switchAfter t0 (mkCar1 p0 v0) (flip mkCar1 v . fst) mkCar3 :: Position->Velocity->Time->Velocity->Time->Velocity->SF a Car mkCar3 p0 v0 t0 v1 t1 v = switchAfter t0 (mkCar1 p0 v0) $ \(p1, _) -> switchAfter t1 (mkCar1 p1 v1) $ \(p2, _) -> mkCar1 p2 v highway :: SF a Highway highway = parB [ mkCar1 (-600) 30.9 , mkCar1 0 30 , mkCar3 (-1000) 40 95 30 200 30.9 , mkCar1 (-3000) 45 , mkCar1 700 28 , mkCar1 800 29.1 ] -- The status of the UAV. For now, it's just flying at constant speed. uavStatus :: SF a UAVStatus uavStatus = constant 30 >>> integral -- Tracks a car in the video stream. An event is generated when tracking is -- lost, which we assume only happens if the car leaves the field of vision. -- We don't concern ourselves with realistic creation of trackers. The UAVStatus signal provides the current flying height and ground speed -- which allows the perceived position to be scaled to a position in meters -- relative to the origin directly under the flying vehicle, and the perceived -- velocity to be transformed to ground velocity. type CarTracker = SF (Video, UAVStatus) (Car, Event ()) range = 500 -- Creation of video stream subject to field of view and car trackers -- as cars enters the field of view. mkVideoAndTrackers :: SF (Highway, UAVStatus) (Video, Event CarTracker) mkVideoAndTrackers = arr mkVideo >>> identity &&& carEntry where mkVideo :: (Highway, Position) -> Video mkVideo (cars, p_uav) = [ (i, (p_rel, v)) | (i, (p, v)) <- zip [0..] cars , let p_rel = p - p_uav, abs p_rel <= range ] carEntry :: SF Video (Event CarTracker) carEntry = edgeBy newCar [] where newCar v_prev v = case (map fst v) \\ (map fst v_prev) of [] -> Nothing (i : _) -> Just (mkCarTracker i) mkCarTracker :: Int -> CarTracker mkCarTracker i = arr (lookup i . fst) >>> trackAndHold undefined &&& edgeBy justToNothing (Just undefined) where justToNothing Nothing Nothing = Nothing justToNothing Nothing (Just _) = Nothing justToNothing (Just _) (Just _) = Nothing justToNothing (Just _) Nothing = Just () videoAndTrackers :: SF a (Video, Event CarTracker) videoAndTrackers = highway &&& uavStatus >>> mkVideoAndTrackers smplFreq = 2.0 smplPer = 1/smplFreq -- * Tailgating detector Looks at the positions of two cars and determines if the first is tailgating the second . Tailgating is assumed to have occurred if : * the first car is behind the second ; * the absolute speed of the first car is greater than 5 m / s ; * the relative speed of the cars is within 20 % of the absolute speed ; * the first car is no more than 5 s behind the second ; and -- * after 30 s, the average distance between the cars normalized by the absolute speed is less than a second . tailgating :: SF (Car, Car) (Event ()) tailgating = provided follow tooClose never where follow ((p1, v1), (p2, v2)) = p1 < p2 && v1 > 5.0 && abs ((v2 - v1)/v1) < 0.2 && (p2 - p1) / v1 < 5.0 -- Under the assumption that car c1 is following car c2, generate an event if has been too close to car2 on average during the last 30 s. tooClose :: SF (Car, Car) (Event ()) tooClose = proc (c1, c2) -> do ead <- recur (snapAfter 30 <<< avgDist) -< (c1, c2) returnA -< (filterE (<1.0) ead) `tag` () avgDist = proc ((p1, v1), (p2, v2)) -> do let nd = (p2 - p1) / v1 ind <- integral -< nd t <- localTime -< () returnA -< if t > 0 then ind / t else nd -- * Multi-Car tracker -- Auxiliary definitions type Id = Int data MCTCol a = MCTCol Id [(Id, a)] instance Functor MCTCol where fmap f (MCTCol n ias) = MCTCol n [ (i, f a) | (i, a) <- ias ] -- Tracking of individual cars in a group. The arrival of a new car is -- signalled by an external event, which causes a new tracker to be added -- to internal collection of car trackers. A tracker is removed as soon -- as it looses tracking. -- -- The output consists of the output from the individual trackers, tagged -- with an assigned identity unique to each tracker. -- -- I'M GIVING UP ON THIS BIT FOR NOW -- The external identity event signals that the car being tracked by the -- tracker tagged by the identity carried by the event is guilty of -- tailgating. This causes an event carrying the *continuation* of the -- corresponding tracker to be generated, e.g. allowing the overall controll system to focus on follwing that particular car without first -- having to start a new tracker (risking misidentification). mct :: SF (Video, UAVStatus, Event CarTracker) [(Id, Car)] mct = pSwitch route cts_init addOrDelCTs (\cts' f -> mctAux (f cts')) >>^ getCars where mctAux cts = pSwitch route cts (noEvent --> addOrDelCTs) (\cts' f -> mctAux (f cts')) route (v, s, _) = fmap (\ct -> ((v, s), ct)) addOrDelCTs : : SF _ ( Event ( MCTCol CarTracker - > MCTCol carTracker ) ) addOrDelCTs = proc ((_, _, ect), ces) -> do let eAdd = fmap addCT ect let eDel = fmap delCTs (catEvents (getEvents ces)) returnA -< mergeBy (.) eAdd eDel cts_init :: MCTCol CarTracker cts_init = MCTCol 0 [] addCT :: CarTracker -> MCTCol CarTracker -> MCTCol CarTracker addCT ct (MCTCol n icts) = MCTCol (n+1) ((n, ct) : icts) delCTs :: [Id] -> MCTCol CarTracker -> MCTCol CarTracker delCTs is (MCTCol n icts) = MCTCol n (filter (flip notElem is . fst) icts) getCars :: MCTCol (Car, Event ()) -> [(Id, Car)] getCars (MCTCol _ ices) = [(i, c) | (i, (c, _)) <- ices ] getEvents :: MCTCol (Car, Event ()) -> [Event Id] getEvents (MCTCol _ ices) = [e `tag` i | (i,(_,e)) <- ices] -- * Multi tailgating detector -- Auxiliary definitions newtype MTGDCol a = MTGDCol [((Id,Id), a)] instance Functor MTGDCol where fmap f (MTGDCol iias) = MTGDCol [ (ii, f a) | (ii, a) <- iias ] -- Run tailgating above for each pair of tracked cars. A structural change -- to the list of tracked cars is signalled by an event, at which point -- the signal function will figure which old tailgating detectors that have -- to be removed and which new that have to be started based on an initial -- sample of the new configuration. An event carrying the identity of a tailgater and the one being tailgated is generated when one of the -- tailgating signal functions generates an event. mtgd :: SF [(Id, Car)] (Event [(Id, Id)]) mtgd = proc ics -> do let ics' = sortBy relPos ics eno <- newOrder -< ics' etgs <- rpSwitch route (MTGDCol []) -< (ics', fmap updateTGDs eno) returnA -< tailgaters etgs where route ics (MTGDCol iitgs) = MTGDCol $ let cs = map snd ics in [ (ii, (cc, tg)) | (cc, (ii, tg)) <- zip (zip cs (tail cs)) iitgs ] relPos (_, (p1, _)) (_, (p2, _)) = compare p1 p2 newOrder :: SF [(Id, Car)] (Event [Id]) newOrder = edgeBy (\ics ics' -> if sameOrder ics ics' then Nothing else Just (map fst ics')) [] where sameOrder [] [] = True sameOrder [] _ = False sameOrder _ [] = False sameOrder ((i,_):ics) ((i',_):ics') | i == i' = sameOrder ics ics' | otherwise = False updateTGDs is (MTGDCol iitgs) = MTGDCol $ [ (ii, maybe tailgating id (lookup ii iitgs)) | ii <- zip is (tail is) ] tailgaters :: MTGDCol (Event ()) -> Event [(Id, Id)] tailgaters (MTGDCol iies) = catEvents [ e `tag` ii | (ii, e) <- iies ] -- Finally, we can tie the individaul pieces together into a signal -- function which finds tailgaters: findTailgaters :: SF (Video, UAVStatus, Event CarTracker) ([(Id, Car)], Event [(Id, Id)]) findTailgaters = proc (v, s, ect) -> do ics <- mct -< (v, s, ect) etgs <- mtgd -< ics returnA -< (ics, etgs)
null
https://raw.githubusercontent.com/ivanperez-keera/Yampa/4465eb47c59f39b40214741dcb61995b7dfb4c5b/yampa/examples/TailgatingDetector/TailgatingDetector.hs
haskell
# LANGUAGE Arrows # | Description : AFRP Expressitivity Test Context: an autonomous flying vehicle carrying out traffic surveillance through an on-board video camera. Objective: finding a tailgater among a group of vehicles traveling along a highway lane. The group is defined by the section of the highway in relative speed to the flying vehicles enters or leaves the field of vision. Simplifying assumptions: * The positive x-axis of the video images is supposed to correspond to the direction of travel. * The flying vehicle is assumed to travel directly over and along the highway lane when looking for tailgaters. The y-coordinate of the highway is thus roughly 0. * It is enough to consider the x-coordinate of ground vehicle positions. Thus the position and velocity types are both just (signed) Double for our purposes. signal functions, these collections HAVE TO BE DYNAMIC by the very by the nature of the problem. * Testing framework [m] [m] [m/s] We'll call any ground vehicle "car". For our purposes, a car is represented by its ground position and ground velocity. A highway is just a list of cars. In this simple setting, we assume all cars are there all the time (no enter or exit ramps etc.) Type of the Video signal. Here just an association list of cars *in view* with *relative* positions. System info, such as height and ground speed. Here, just the position. Various ways of making cars. The status of the UAV. For now, it's just flying at constant speed. Tracks a car in the video stream. An event is generated when tracking is lost, which we assume only happens if the car leaves the field of vision. We don't concern ourselves with realistic creation of trackers. which allows the perceived position to be scaled to a position in meters relative to the origin directly under the flying vehicle, and the perceived velocity to be transformed to ground velocity. Creation of video stream subject to field of view and car trackers as cars enters the field of view. * Tailgating detector * after 30 s, the average distance between the cars normalized by Under the assumption that car c1 is following car c2, generate an event * Multi-Car tracker Auxiliary definitions Tracking of individual cars in a group. The arrival of a new car is signalled by an external event, which causes a new tracker to be added to internal collection of car trackers. A tracker is removed as soon as it looses tracking. The output consists of the output from the individual trackers, tagged with an assigned identity unique to each tracker. I'M GIVING UP ON THIS BIT FOR NOW The external identity event signals that the car being tracked by the tracker tagged by the identity carried by the event is guilty of tailgating. This causes an event carrying the *continuation* of the corresponding tracker to be generated, e.g. allowing the overall having to start a new tracker (risking misidentification). > addOrDelCTs) * Multi tailgating detector Auxiliary definitions Run tailgating above for each pair of tracked cars. A structural change to the list of tracked cars is signalled by an event, at which point the signal function will figure which old tailgating detectors that have to be removed and which new that have to be started based on an initial sample of the new configuration. An event carrying the identity of tailgating signal functions generates an event. Finally, we can tie the individaul pieces together into a signal function which finds tailgaters:
Module : TailgatingDetector Copyright : Yale University , 2003 Authors : view and thus changes dynamically as ground vehicles with non - zero I find this example interesting because it makes use of TWO COLLECTION of nature of the problem , and it makes use of the the fact that CONTINUATIONS ARE FIRST CLASS ENTITIES in a way which arguably also is justified module TailgatingDetector where import Data.List (sortBy, (\\)) import FRP.Yampa import FRP.Yampa.Conditional import FRP.Yampa.EventS type Car = (Position, Velocity) type Highway = [Car] type Video = [(Int, Car)] type UAVStatus = Position switchAfter :: Time -> SF a b -> (b -> SF a b) -> SF a b switchAfter t sf k = switch (sf &&& after t () >>^ \(b,e) -> (b, e `tag` b)) k mkCar1 :: Position -> Velocity -> SF a Car mkCar1 p0 v = constant v >>> (integral >>^ (+p0)) &&& identity mkCar2 :: Position -> Velocity -> Time -> Velocity -> SF a Car mkCar2 p0 v0 t0 v = switchAfter t0 (mkCar1 p0 v0) (flip mkCar1 v . fst) mkCar3 :: Position->Velocity->Time->Velocity->Time->Velocity->SF a Car mkCar3 p0 v0 t0 v1 t1 v = switchAfter t0 (mkCar1 p0 v0) $ \(p1, _) -> switchAfter t1 (mkCar1 p1 v1) $ \(p2, _) -> mkCar1 p2 v highway :: SF a Highway highway = parB [ mkCar1 (-600) 30.9 , mkCar1 0 30 , mkCar3 (-1000) 40 95 30 200 30.9 , mkCar1 (-3000) 45 , mkCar1 700 28 , mkCar1 800 29.1 ] uavStatus :: SF a UAVStatus uavStatus = constant 30 >>> integral The UAVStatus signal provides the current flying height and ground speed type CarTracker = SF (Video, UAVStatus) (Car, Event ()) range = 500 mkVideoAndTrackers :: SF (Highway, UAVStatus) (Video, Event CarTracker) mkVideoAndTrackers = arr mkVideo >>> identity &&& carEntry where mkVideo :: (Highway, Position) -> Video mkVideo (cars, p_uav) = [ (i, (p_rel, v)) | (i, (p, v)) <- zip [0..] cars , let p_rel = p - p_uav, abs p_rel <= range ] carEntry :: SF Video (Event CarTracker) carEntry = edgeBy newCar [] where newCar v_prev v = case (map fst v) \\ (map fst v_prev) of [] -> Nothing (i : _) -> Just (mkCarTracker i) mkCarTracker :: Int -> CarTracker mkCarTracker i = arr (lookup i . fst) >>> trackAndHold undefined &&& edgeBy justToNothing (Just undefined) where justToNothing Nothing Nothing = Nothing justToNothing Nothing (Just _) = Nothing justToNothing (Just _) (Just _) = Nothing justToNothing (Just _) Nothing = Just () videoAndTrackers :: SF a (Video, Event CarTracker) videoAndTrackers = highway &&& uavStatus >>> mkVideoAndTrackers smplFreq = 2.0 smplPer = 1/smplFreq Looks at the positions of two cars and determines if the first is tailgating the second . Tailgating is assumed to have occurred if : * the first car is behind the second ; * the absolute speed of the first car is greater than 5 m / s ; * the relative speed of the cars is within 20 % of the absolute speed ; * the first car is no more than 5 s behind the second ; and the absolute speed is less than a second . tailgating :: SF (Car, Car) (Event ()) tailgating = provided follow tooClose never where follow ((p1, v1), (p2, v2)) = p1 < p2 && v1 > 5.0 && abs ((v2 - v1)/v1) < 0.2 && (p2 - p1) / v1 < 5.0 if has been too close to car2 on average during the last 30 s. tooClose :: SF (Car, Car) (Event ()) tooClose = proc (c1, c2) -> do ead <- recur (snapAfter 30 <<< avgDist) -< (c1, c2) returnA -< (filterE (<1.0) ead) `tag` () avgDist = proc ((p1, v1), (p2, v2)) -> do let nd = (p2 - p1) / v1 ind <- integral -< nd t <- localTime -< () returnA -< if t > 0 then ind / t else nd type Id = Int data MCTCol a = MCTCol Id [(Id, a)] instance Functor MCTCol where fmap f (MCTCol n ias) = MCTCol n [ (i, f a) | (i, a) <- ias ] controll system to focus on follwing that particular car without first mct :: SF (Video, UAVStatus, Event CarTracker) [(Id, Car)] mct = pSwitch route cts_init addOrDelCTs (\cts' f -> mctAux (f cts')) >>^ getCars where mctAux cts = pSwitch route cts (\cts' f -> mctAux (f cts')) route (v, s, _) = fmap (\ct -> ((v, s), ct)) addOrDelCTs : : SF _ ( Event ( MCTCol CarTracker - > MCTCol carTracker ) ) addOrDelCTs = proc ((_, _, ect), ces) -> do let eAdd = fmap addCT ect let eDel = fmap delCTs (catEvents (getEvents ces)) returnA -< mergeBy (.) eAdd eDel cts_init :: MCTCol CarTracker cts_init = MCTCol 0 [] addCT :: CarTracker -> MCTCol CarTracker -> MCTCol CarTracker addCT ct (MCTCol n icts) = MCTCol (n+1) ((n, ct) : icts) delCTs :: [Id] -> MCTCol CarTracker -> MCTCol CarTracker delCTs is (MCTCol n icts) = MCTCol n (filter (flip notElem is . fst) icts) getCars :: MCTCol (Car, Event ()) -> [(Id, Car)] getCars (MCTCol _ ices) = [(i, c) | (i, (c, _)) <- ices ] getEvents :: MCTCol (Car, Event ()) -> [Event Id] getEvents (MCTCol _ ices) = [e `tag` i | (i,(_,e)) <- ices] newtype MTGDCol a = MTGDCol [((Id,Id), a)] instance Functor MTGDCol where fmap f (MTGDCol iias) = MTGDCol [ (ii, f a) | (ii, a) <- iias ] a tailgater and the one being tailgated is generated when one of the mtgd :: SF [(Id, Car)] (Event [(Id, Id)]) mtgd = proc ics -> do let ics' = sortBy relPos ics eno <- newOrder -< ics' etgs <- rpSwitch route (MTGDCol []) -< (ics', fmap updateTGDs eno) returnA -< tailgaters etgs where route ics (MTGDCol iitgs) = MTGDCol $ let cs = map snd ics in [ (ii, (cc, tg)) | (cc, (ii, tg)) <- zip (zip cs (tail cs)) iitgs ] relPos (_, (p1, _)) (_, (p2, _)) = compare p1 p2 newOrder :: SF [(Id, Car)] (Event [Id]) newOrder = edgeBy (\ics ics' -> if sameOrder ics ics' then Nothing else Just (map fst ics')) [] where sameOrder [] [] = True sameOrder [] _ = False sameOrder _ [] = False sameOrder ((i,_):ics) ((i',_):ics') | i == i' = sameOrder ics ics' | otherwise = False updateTGDs is (MTGDCol iitgs) = MTGDCol $ [ (ii, maybe tailgating id (lookup ii iitgs)) | ii <- zip is (tail is) ] tailgaters :: MTGDCol (Event ()) -> Event [(Id, Id)] tailgaters (MTGDCol iies) = catEvents [ e `tag` ii | (ii, e) <- iies ] findTailgaters :: SF (Video, UAVStatus, Event CarTracker) ([(Id, Car)], Event [(Id, Id)]) findTailgaters = proc (v, s, ect) -> do ics <- mct -< (v, s, ect) etgs <- mtgd -< ics returnA -< (ics, etgs)
f045448446603b1e0fb7027fa127822f22d820eed070b366646016c42e2dfab2
xh4/web-toolkit
dimension.lisp
(in-package :css) (defclass dimension () ((number :initarg :number :initform nil :accessor dimension-number) (unit :initarg :unit :initform nil :accessor dimension-unit))) (defmethod print-object ((dimension dimension) stream) (print-unreadable-object (dimension stream :type t) (format stream "~A" (dimension-number dimension)))) (defmethod initialize-instance :after ((dimension dimension) &key) (unless (dimension-number dimension) (error "Missing number when initialize dimension ~A" (type-of dimension))) (check-type (dimension-number dimension) number)) (defmacro define-dimension (name (&optional superclass)) (unless superclass (setf superclass 'dimension)) `(defclass ,name (,superclass) ())) (defvar *dimension-units* '()) (defmacro define-dimension-unit (name (&optional superclass)) (unless superclass (setf superclass 'dimension)) `(progn (defclass ,name (,superclass) ((unit :initform ,(make-keyword (symbol-name name))))) (defun ,name (number) (make-instance ',name :number number)) (pushnew ',name *dimension-units*))) (define-parser .dimension () (lambda (input) (multiple-value-bind (rest value match-p) ;; FIXME: more strict rule (parse (.seq (.some/s (.or (.digit) (.s ".") (.s "-"))) (.maybe (.some/s (.alpha)))) input) (if match-p (let ((n (ignore-errors (parse-number (first value)))) (u (second value))) (if n (if u (loop for unit in *dimension-units* when (string-equal u (symbol-name unit)) do (return (values rest (funcall unit n) t)) finally (return (values input nil nil))) (values rest (make-instance 'length :number n) t)) (values input nil nil))) (values input nil nil))))) (define-serialize-method ((dimension dimension) stream) (let ((number (dimension-number dimension)) (unit (dimension-unit dimension))) (format stream "~A~(~A~)" number (symbol-name unit))))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/css/dimension.lisp
lisp
FIXME: more strict rule
(in-package :css) (defclass dimension () ((number :initarg :number :initform nil :accessor dimension-number) (unit :initarg :unit :initform nil :accessor dimension-unit))) (defmethod print-object ((dimension dimension) stream) (print-unreadable-object (dimension stream :type t) (format stream "~A" (dimension-number dimension)))) (defmethod initialize-instance :after ((dimension dimension) &key) (unless (dimension-number dimension) (error "Missing number when initialize dimension ~A" (type-of dimension))) (check-type (dimension-number dimension) number)) (defmacro define-dimension (name (&optional superclass)) (unless superclass (setf superclass 'dimension)) `(defclass ,name (,superclass) ())) (defvar *dimension-units* '()) (defmacro define-dimension-unit (name (&optional superclass)) (unless superclass (setf superclass 'dimension)) `(progn (defclass ,name (,superclass) ((unit :initform ,(make-keyword (symbol-name name))))) (defun ,name (number) (make-instance ',name :number number)) (pushnew ',name *dimension-units*))) (define-parser .dimension () (lambda (input) (multiple-value-bind (rest value match-p) (parse (.seq (.some/s (.or (.digit) (.s ".") (.s "-"))) (.maybe (.some/s (.alpha)))) input) (if match-p (let ((n (ignore-errors (parse-number (first value)))) (u (second value))) (if n (if u (loop for unit in *dimension-units* when (string-equal u (symbol-name unit)) do (return (values rest (funcall unit n) t)) finally (return (values input nil nil))) (values rest (make-instance 'length :number n) t)) (values input nil nil))) (values input nil nil))))) (define-serialize-method ((dimension dimension) stream) (let ((number (dimension-number dimension)) (unit (dimension-unit dimension))) (format stream "~A~(~A~)" number (symbol-name unit))))
a429e8519e4042f981acbbf13fc35ca96c1262e7e98f812fe1474a2bb69e86e7
screenshotbot/screenshotbot-oss
health-check.lisp
;;;; Copyright 2018-Present Modern Interpreters Inc. ;;;; 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 /. (defpackage :util/health-check (:use #:cl) (:local-nicknames (#:a #:alexandria)) (:export #:def-health-check #:run-health-checks)) (in-package :util/health-check) (defvar *checks* nil) (defclass health-check () ((name :initarg :name :reader health-check-name) (slow :initarg :slow) (function :initarg :function :reader health-check-function))) (defmacro def-health-check (name (&key slow) &body body) `(setf (a:assoc-value *checks* ',name) (make-instance 'health-check :name ',name :slow ',slow :function (lambda () ,@body)))) (defun call-health-check (health-check &key out) (handler-case (progn (format out "Checking ~a... " (health-check-name health-check)) (finish-output out) (funcall (health-check-function health-check)) (format out "SUCCESS~%") (finish-output out) t) (error (e) (format out "FAILURE [~a]~%" e) (finish-output out) nil))) (defun run-health-checks (&key (out *terminal-io*)) (loop for health-check in (mapcar 'cdr (reverse *checks*)) if (not (call-health-check health-check :out out)) collect (health-check-name health-check) into failed finally (progn (cond (failed (format out "=======================~%") (format out "HEALTH CHECKS FAILED!!!~%") (format out "=======================~%")) (t (format out "All health checks done~%"))) (return (values (not failed) failed))))) (def-health-check sanity-test () (values)) ;; ;; (run-health-checks)
null
https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/dc85ea5d70d195b17a83506cbe39cdc8ad85bc14/src/util/health-check.lisp
lisp
Copyright 2018-Present Modern Interpreters Inc. ;; (run-health-checks)
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 /. (defpackage :util/health-check (:use #:cl) (:local-nicknames (#:a #:alexandria)) (:export #:def-health-check #:run-health-checks)) (in-package :util/health-check) (defvar *checks* nil) (defclass health-check () ((name :initarg :name :reader health-check-name) (slow :initarg :slow) (function :initarg :function :reader health-check-function))) (defmacro def-health-check (name (&key slow) &body body) `(setf (a:assoc-value *checks* ',name) (make-instance 'health-check :name ',name :slow ',slow :function (lambda () ,@body)))) (defun call-health-check (health-check &key out) (handler-case (progn (format out "Checking ~a... " (health-check-name health-check)) (finish-output out) (funcall (health-check-function health-check)) (format out "SUCCESS~%") (finish-output out) t) (error (e) (format out "FAILURE [~a]~%" e) (finish-output out) nil))) (defun run-health-checks (&key (out *terminal-io*)) (loop for health-check in (mapcar 'cdr (reverse *checks*)) if (not (call-health-check health-check :out out)) collect (health-check-name health-check) into failed finally (progn (cond (failed (format out "=======================~%") (format out "HEALTH CHECKS FAILED!!!~%") (format out "=======================~%")) (t (format out "All health checks done~%"))) (return (values (not failed) failed))))) (def-health-check sanity-test () (values))
11937d7bc0fb955276f375eb37ae6a8cd67f5762d0b7387c52cd9d8fef428744
dmitryvk/sbcl-win32-threads
hppa-vm.lisp
(in-package "SB!VM") (define-alien-type os-context-t (struct os-context-t-struct)) ;;;; MACHINE-TYPE (defun machine-type () "Returns a string describing the type of the local machine." "HPPA") FIXUP - CODE - OBJECT FIX - lav : unify code with genesis.lisp fixup (defun fixup-code-object (code offset value kind) (unless (zerop (rem offset n-word-bytes)) (error "Unaligned instruction? offset=#x~X." offset)) (sb!sys:without-gcing (let* ((sap (%primitive sb!kernel::code-instructions code)) (inst (sap-ref-32 sap offset))) (setf (sap-ref-32 sap offset) (ecase kind (:load (logior (mask-field (byte 18 14) value) (if (< value 0) (1+ (ash (ldb (byte 13 0) value) 1)) (ash (ldb (byte 13 0) value) 1)))) (:load11u (logior (if (< value 0) (1+ (ash (ldb (byte 10 0) value) 1)) (ash (ldb (byte 11 0) value) 1)) (mask-field (byte 18 14) inst))) (:load-short (let ((low-bits (ldb (byte 11 0) value))) (aver (<= 0 low-bits (1- (ash 1 4)))) (logior (ash (dpb (ldb (byte 4 0) value) (byte 4 1) (ldb (byte 1 4) value)) 17) (logand inst #xffe0ffff)))) (:hi (logior (ash (ldb (byte 5 13) value) 16) (ash (ldb (byte 2 18) value) 14) (ash (ldb (byte 2 11) value) 12) (ash (ldb (byte 11 20) value) 1) (ldb (byte 1 31) value) (logand inst #xffe00000))) (:branch (let ((bits (ldb (byte 9 2) value))) (aver (zerop (ldb (byte 2 0) value))) (logior (ash bits 3) (mask-field (byte 1 1) inst) (mask-field (byte 3 13) inst) (mask-field (byte 11 21) inst))))))))) (define-alien-routine ("os_context_pc_addr" context-pc-addr) (* unsigned-int) (context (* os-context-t))) (defun context-pc (context) (declare (type (alien (* os-context-t)) context)) (int-sap (logandc2 (deref (context-pc-addr context)) 3))) (define-alien-routine ("os_context_register_addr" context-register-addr) (* unsigned-int) (context (* os-context-t)) (index int)) ;;; FIXME: Should this and CONTEXT-PC be INLINE to reduce consing? ;;; (Are they used in anything time-critical, or just the debugger?) (defun context-register (context index) (declare (type (alien (* os-context-t)) context)) (deref (context-register-addr context index))) (defun %set-context-register (context index new) (declare (type (alien (* os-context-t)) context)) (setf (deref (context-register-addr context index)) new)) #!+linux ;;; For now. (defun context-floating-point-modes (context) (warn "stub CONTEXT-FLOATING-POINT-MODES") 0) ;;;; Internal-error-arguments. ;;; INTERNAL-ERROR-ARGUMENTS -- interface. ;;; Given the sigcontext , extract the internal error arguments from the ;;; instruction stream. ;;; (defun internal-error-args (context) (declare (type (alien (* os-context-t)) context)) (let ((pc (context-pc context))) (declare (type system-area-pointer pc)) (let* ((length (sap-ref-8 pc 4)) (vector (make-array length :element-type '(unsigned-byte 8)))) (declare (type (unsigned-byte 8) length) (type (simple-array (unsigned-byte 8) (*)) vector)) (copy-ub8-from-system-area pc 5 vector 0 length) (let* ((index 0) (error-number (sb!c:read-var-integer vector index))) (collect ((sc-offsets)) (loop (when (>= index length) (return)) (sc-offsets (sb!c:read-var-integer vector index))) (values error-number (sc-offsets)))))))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/code/hppa-vm.lisp
lisp
MACHINE-TYPE FIXME: Should this and CONTEXT-PC be INLINE to reduce consing? (Are they used in anything time-critical, or just the debugger?) For now. Internal-error-arguments. INTERNAL-ERROR-ARGUMENTS -- interface. instruction stream.
(in-package "SB!VM") (define-alien-type os-context-t (struct os-context-t-struct)) (defun machine-type () "Returns a string describing the type of the local machine." "HPPA") FIXUP - CODE - OBJECT FIX - lav : unify code with genesis.lisp fixup (defun fixup-code-object (code offset value kind) (unless (zerop (rem offset n-word-bytes)) (error "Unaligned instruction? offset=#x~X." offset)) (sb!sys:without-gcing (let* ((sap (%primitive sb!kernel::code-instructions code)) (inst (sap-ref-32 sap offset))) (setf (sap-ref-32 sap offset) (ecase kind (:load (logior (mask-field (byte 18 14) value) (if (< value 0) (1+ (ash (ldb (byte 13 0) value) 1)) (ash (ldb (byte 13 0) value) 1)))) (:load11u (logior (if (< value 0) (1+ (ash (ldb (byte 10 0) value) 1)) (ash (ldb (byte 11 0) value) 1)) (mask-field (byte 18 14) inst))) (:load-short (let ((low-bits (ldb (byte 11 0) value))) (aver (<= 0 low-bits (1- (ash 1 4)))) (logior (ash (dpb (ldb (byte 4 0) value) (byte 4 1) (ldb (byte 1 4) value)) 17) (logand inst #xffe0ffff)))) (:hi (logior (ash (ldb (byte 5 13) value) 16) (ash (ldb (byte 2 18) value) 14) (ash (ldb (byte 2 11) value) 12) (ash (ldb (byte 11 20) value) 1) (ldb (byte 1 31) value) (logand inst #xffe00000))) (:branch (let ((bits (ldb (byte 9 2) value))) (aver (zerop (ldb (byte 2 0) value))) (logior (ash bits 3) (mask-field (byte 1 1) inst) (mask-field (byte 3 13) inst) (mask-field (byte 11 21) inst))))))))) (define-alien-routine ("os_context_pc_addr" context-pc-addr) (* unsigned-int) (context (* os-context-t))) (defun context-pc (context) (declare (type (alien (* os-context-t)) context)) (int-sap (logandc2 (deref (context-pc-addr context)) 3))) (define-alien-routine ("os_context_register_addr" context-register-addr) (* unsigned-int) (context (* os-context-t)) (index int)) (defun context-register (context index) (declare (type (alien (* os-context-t)) context)) (deref (context-register-addr context index))) (defun %set-context-register (context index new) (declare (type (alien (* os-context-t)) context)) (setf (deref (context-register-addr context index)) new)) #!+linux (defun context-floating-point-modes (context) (warn "stub CONTEXT-FLOATING-POINT-MODES") 0) Given the sigcontext , extract the internal error arguments from the (defun internal-error-args (context) (declare (type (alien (* os-context-t)) context)) (let ((pc (context-pc context))) (declare (type system-area-pointer pc)) (let* ((length (sap-ref-8 pc 4)) (vector (make-array length :element-type '(unsigned-byte 8)))) (declare (type (unsigned-byte 8) length) (type (simple-array (unsigned-byte 8) (*)) vector)) (copy-ub8-from-system-area pc 5 vector 0 length) (let* ((index 0) (error-number (sb!c:read-var-integer vector index))) (collect ((sc-offsets)) (loop (when (>= index length) (return)) (sc-offsets (sb!c:read-var-integer vector index))) (values error-number (sc-offsets)))))))
3ea40d29fe4b2f1719e35a5cf8be78c9cd309912c0df2450e8eb2df9c00ac37f
clash-lang/clash-compiler
Main.hs
# LANGUAGE CPP # # LANGUAGE LambdaCase # # LANGUAGE NondecreasingIndentation # # LANGUAGE TupleSections # {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-} ----------------------------------------------------------------------------- -- GHC Driver program -- ( c ) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module Clash.Main (defaultMain, defaultMainWithAction) where The official GHC API import qualified GHC DynFlags ( .. ) , HscTarget ( .. ) , GhcMode ( .. ) , ( .. ) , Ghc, GhcMonad(..), LoadHowMuch(..) ) import GHC.Driver.CmdLine -- Implementations of the various modes (--show-iface, mkdependHS. etc.) import GHC.Iface.Load ( showIface ) import GHC.Driver.Main ( newHscEnv ) import GHC.Driver.Pipeline ( oneShot, compileFile ) import GHC.Driver.MakeFile ( doMkDependHS ) import GHC.Driver.Backpack ( doBackpack ) import GHC.Driver.Ways #if defined(HAVE_INTERNAL_INTERPRETER) import Clash.GHCi.UI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings ) #endif Frontend plugins import GHC.Runtime.Loader ( loadFrontendPlugin ) import GHC.Driver.Plugins #if defined(HAVE_INTERNAL_INTERPRETER) import GHC.Runtime.Loader ( initializePlugins ) #endif import GHC.Unit.Module ( ModuleName, mkModuleName ) -- Various other random stuff that we need import GHC.HandleEncoding import GHC.Platform import GHC.Platform.Host import GHC.Settings.Config import GHC.Settings.Constants import GHC.Driver.Types import GHC.Unit.State ( pprUnits, pprUnitsSimple ) import GHC.Driver.Phases import GHC.Types.Basic ( failed ) import GHC.Driver.Session as DynFlags hiding (WarnReason(..)) import GHC.Utils.Error import GHC.Data.EnumSet as EnumSet import GHC.Data.FastString import GHC.Utils.Outputable as Outputable import GHC.SysTools.BaseDir import GHC.Settings.IO import GHC.Types.SrcLoc import GHC.Utils.Misc import GHC.Utils.Panic import GHC.Types.Unique.Supply import GHC.Utils.Monad ( liftIO ) -- Imports for --abi-hash import GHC.Iface.Load ( loadUserInterface ) import GHC.Driver.Finder ( findImportedModule, cannotFindModule ) import GHC.Tc.Utils.Monad ( initIfaceCheck ) import GHC.Utils.Binary ( openBinMem, put_ ) import GHC.Iface.Recomp.Binary ( fingerprintBinMem ) Standard Haskell libraries import System.IO import System.Environment import System.Exit import System.FilePath import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.Except (throwE, runExceptT) import Data.Char import Data.List ( isPrefixOf, partition, intercalate, nub ) import Data.Proxy import qualified Data.Set as Set import Data.Maybe import Prelude -- clash additions import Paths_clash_ghc import Clash.GHCi.UI (makeHDL) import Control.Monad.Catch (catch) import Data.IORef (IORef, newIORef, readIORef, modifyIORef') import qualified Data.Version (showVersion) import Clash.Backend (Backend) import Clash.Backend.SystemVerilog (SystemVerilogState) import Clash.Backend.VHDL (VHDLState) import Clash.Backend.Verilog (VerilogState) import Clash.Driver.Types (ClashOpts (..), defClashOpts) import Clash.GHC.ClashFlags import Clash.Util (clashLibVersion) import Clash.GHC.LoadModules (ghcLibDir, setWantedLanguageExtensions) import Clash.GHC.Util (handleClashException) ----------------------------------------------------------------------------- ToDo : -- time commands when run with -v -- user ways -- Win32 support: proper signal handling -- reading the package configuration file is too slow -- -K<size> ----------------------------------------------------------------------------- GHC 's command - line interface defaultMain :: [String] -> IO () defaultMain = defaultMainWithAction (return ()) defaultMainWithAction :: Ghc () -> [String] -> IO () defaultMainWithAction startAction = flip withArgs $ do initGCStatistics -- See Note [-Bsymbolic and hooks] hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering configureHandleEncoding GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do 1 . extract the -B flag from the args argv0 <- getArgs let ( minusB_args , ) = partition ( " -B " ` isPrefixOf ` ) -- mbMinusB | null minusB_args = Nothing | otherwise = Just ( drop 2 ( last minusB_args ) ) let argv1 = map (mkGeneralLocated "on the commandline") argv0 libDir <- ghcLibDir r <- newIORef defClashOpts (argv2, clashFlagWarnings) <- parseClashFlags r argv1 2 . the " mode " flags ( --make , --interactive etc . ) (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2 let flagWarnings = modeFlagWarnings ++ clashFlagWarnings -- If all we want to do is something like showing the version number then do it now , before we start a GHC session etc . This makes -- getting basic information much more resilient. -- In particular, if we wait until later before giving the version -- number then bootstrapping gets confused, as it tries to find out what version of GHC it 's using before package.conf exists , so -- starting the session fails. case mode of Left preStartupMode -> do case preStartupMode of ShowSupportedExtensions -> showSupportedExtensions (Just libDir) ShowVersion -> showVersion ShowNumVersion -> putStrLn cProjectVersion ShowOptions isInteractive -> showOptions isInteractive r Right postStartupMode -> start our GHC session GHC.runGhc (Just libDir) $ do dflags <- GHC.getSessionDynFlags let dflagsExtra = setWantedLanguageExtensions dflags ghcTyLitNormPlugin = GHC.mkModuleName "GHC.TypeLits.Normalise" ghcTyLitExtrPlugin = GHC.mkModuleName "GHC.TypeLits.Extra.Solver" ghcTyLitKNPlugin = GHC.mkModuleName "GHC.TypeLits.KnownNat.Solver" dflagsExtra1 = dflagsExtra { DynFlags.pluginModNames = nub $ ghcTyLitNormPlugin : ghcTyLitExtrPlugin : ghcTyLitKNPlugin : DynFlags.pluginModNames dflagsExtra } case postStartupMode of Left preLoadMode -> liftIO $ do case preLoadMode of ShowInfo -> showInfo dflagsExtra1 ShowGhcUsage -> showGhcUsage dflagsExtra1 ShowGhciUsage -> showGhciUsage dflagsExtra1 PrintWithDynFlags f -> putStrLn (f dflagsExtra1) Right postLoadMode -> main' postLoadMode dflagsExtra1 argv3 flagWarnings startAction r main' :: PostLoadMode -> DynFlags -> [Located String] -> [Warn] -> Ghc () -> IORef ClashOpts -> Ghc () main' postLoadMode dflags0 args flagWarnings startAction clashOpts = do set the default GhcMode , HscTarget and GhcLink . The HscTarget -- can be further adjusted on a module by module basis, using only the -fvia - C and -fasm flags . If the default HscTarget is not -- HscC or HscAsm, -fvia-C and -fasm have no effect. let dflt_target = hscTarget dflags0 (mode, lang, link) = case postLoadMode of DoInteractive -> (CompManager, HscInterpreted, LinkInMemory) DoEval _ -> (CompManager, HscInterpreted, LinkInMemory) DoMake -> (CompManager, dflt_target, LinkBinary) DoBackpack -> (CompManager, dflt_target, LinkBinary) DoMkDependHS -> (MkDepend, dflt_target, LinkBinary) DoAbiHash -> (OneShot, dflt_target, LinkBinary) DoVHDL -> (CompManager, HscNothing, NoLink) DoVerilog -> (CompManager, HscNothing, NoLink) DoSystemVerilog -> (CompManager, HscNothing, NoLink) _ -> (OneShot, dflt_target, LinkBinary) let dflags1 = dflags0{ ghcMode = mode, hscTarget = lang, ghcLink = link, verbosity = case postLoadMode of DoEval _ -> 0 _other -> 1 } -- turn on -fimplicit-import-qualified for GHCi now, so that it -- can be overridden from the command-line XXX : this should really be in the interactive DynFlags , but we do n't set that until later in interactiveUI We also set -fignore - - changes and -fignore - hpc - changes , -- which are program-level options. Again, this doesn't really -- feel like the right place to handle this, but we don't have -- a great story for the moment. dflags2 | DoInteractive <- postLoadMode = def_ghci_flags | DoEval _ <- postLoadMode = def_ghci_flags | otherwise = dflags1 where def_ghci_flags = dflags1 `gopt_set` Opt_ImplicitImportQualified `gopt_set` Opt_IgnoreOptimChanges `gopt_set` Opt_IgnoreHpcChanges -- The rest of the arguments are "dynamic" -- Leftover ones are presumably files (dflags3, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags2 args -- Propagate -Werror to Clash liftIO . modifyIORef' clashOpts $ \opts -> opts { opt_werror = EnumSet.member Opt_WarnIsError (generalFlags dflags3) } let dflags4 = case lang of HscInterpreted | not (gopt Opt_ExternalInterpreter dflags3) -> let platform = targetPlatform dflags3 dflags3a = dflags3 { ways = hostFullWays } dflags3b = foldl gopt_set dflags3a $ concatMap (wayGeneralFlags platform) hostFullWays dflags3c = foldl gopt_unset dflags3b $ concatMap (wayUnsetGeneralFlags platform) hostFullWays in dflags3c _ -> dflags3 GHC.prettyPrintGhcErrors dflags4 $ do let flagWarnings' = flagWarnings ++ dynamicFlagWarnings handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ handleFlagWarnings dflags4 flagWarnings' liftIO $ showBanner postLoadMode dflags4 let -- To simplify the handling of filepaths, we normalise all filepaths right -- away. Note the asymmetry of FilePath.normalise: Linux : p / q - > p / q ; p\q - > p\q Windows : p / q - > p\q ; p\q - > p\q # 12674 : Filenames starting with a hypen get normalised from ./-foo.hs -- to -foo.hs. We have to re-prepend the current directory. normalise_hyp fp | strt_dot_sl && "-" `isPrefixOf` nfp = cur_dir ++ nfp | otherwise = nfp where #if defined(mingw32_HOST_OS) strt_dot_sl = "./" `isPrefixOf` fp || ".\\" `isPrefixOf` fp #else strt_dot_sl = "./" `isPrefixOf` fp #endif cur_dir = '.' : [pathSeparator] nfp = normalise fp normal_fileish_paths = map (normalise_hyp . unLoc) fileish_args (srcs, objs) = partition_args normal_fileish_paths [] [] dflags5 = dflags4 { ldInputs = map (FileOption "") objs ++ ldInputs dflags4 } we 've finished manipulating the DynFlags , update the session _ <- GHC.setSessionDynFlags dflags5 dflags6 <- GHC.getSessionDynFlags hsc_env <- GHC.getSession ---------------- Display configuration ----------- case verbosity dflags6 of v | v == 4 -> liftIO $ dumpUnitsSimple dflags6 | v >= 5 -> liftIO $ dumpUnits dflags6 | otherwise -> return () liftIO $ initUniqSupply (initialUnique dflags6) (uniqueIncrement dflags6) ---------------- Final sanity checking ----------- liftIO $ checkOptions postLoadMode dflags6 srcs objs ---------------- Do the business ----------- handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do clashOpts' <- liftIO (readIORef clashOpts) let clash fun = catch (fun startAction clashOpts srcs) (handleClashException dflags6 clashOpts') case postLoadMode of ShowInterface f -> liftIO $ doShowIface dflags6 f DoMake -> doMake srcs DoMkDependHS -> doMkDependHS (map fst srcs) StopBefore p -> liftIO (oneShot hsc_env p srcs) DoInteractive -> ghciUI clashOpts hsc_env dflags6 srcs Nothing DoEval exprs -> ghciUI clashOpts hsc_env dflags6 srcs $ Just $ reverse exprs DoAbiHash -> abiHash (map fst srcs) ShowPackages -> liftIO $ showUnits dflags6 DoFrontend f -> doFrontend f srcs DoBackpack -> doBackpack (map fst srcs) DoVHDL -> clash makeVHDL DoVerilog -> clash makeVerilog DoSystemVerilog -> clash makeSystemVerilog liftIO $ dumpFinalStats dflags6 ghciUI :: IORef ClashOpts -> HscEnv -> DynFlags -> [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc () #if !defined(HAVE_INTERNAL_INTERPRETER) ghciUI _ _ _ _ _ = throwGhcException (CmdLineError "not built for interactive use") #else ghciUI clashOpts hsc_env dflags0 srcs maybe_expr = do dflags1 <- liftIO (initializePlugins hsc_env dflags0) _ <- GHC.setSessionDynFlags dflags1 interactiveUI (defaultGhciSettings clashOpts) srcs maybe_expr #endif -- ----------------------------------------------------------------------------- -- Splitting arguments into source files and object files. This is where we -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source -- file indicating the phase specified by the -x option in force, if any. partition_args :: [String] -> [(String, Maybe Phase)] -> [String] -> ([(String, Maybe Phase)], [String]) partition_args [] srcs objs = (reverse srcs, reverse objs) partition_args ("-x":suff:args) srcs objs | "none" <- suff = partition_args args srcs objs | StopLn <- phase = partition_args args srcs (slurp ++ objs) | otherwise = partition_args rest (these_srcs ++ srcs) objs where phase = startPhase suff (slurp,rest) = break (== "-x") args these_srcs = zip slurp (repeat (Just phase)) partition_args (arg:args) srcs objs | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs | otherwise = partition_args args srcs (arg:objs) We split out the object files ( .o , .dll ) and add them to ldInputs for use by the linker . The following things should be considered compilation manager inputs : - haskell source files ( strings ending in .hs , .lhs or other haskellish extension ) , - module names ( not forgetting hierarchical module names ) , - things beginning with ' - ' are flags that were not recognised by the flag parser , and we want them to generate errors later in checkOptions , so we class them as source files ( # 5921 ) - and finally we consider everything without an extension to be a comp manager input , as shorthand for a .hs or .lhs filename . Everything else is considered to be a linker object , and passed straight through to the linker . We split out the object files (.o, .dll) and add them to ldInputs for use by the linker. The following things should be considered compilation manager inputs: - haskell source files (strings ending in .hs, .lhs or other haskellish extension), - module names (not forgetting hierarchical module names), - things beginning with '-' are flags that were not recognised by the flag parser, and we want them to generate errors later in checkOptions, so we class them as source files (#5921) - and finally we consider everything without an extension to be a comp manager input, as shorthand for a .hs or .lhs filename. Everything else is considered to be a linker object, and passed straight through to the linker. -} looks_like_an_input :: String -> Bool looks_like_an_input m = isSourceFilename m || looksLikeModuleName m || "-" `isPrefixOf` m || not (hasExtension m) -- ----------------------------------------------------------------------------- -- Option sanity checks -- | Ensure sanity of options. -- Throws ' UsageError ' or ' CmdLineError ' if not . checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO () -- Final sanity checking before kicking off a compilation (pipeline). checkOptions mode dflags srcs objs = do -- Complain about any unknown flags let unknown_opts = [ f | (f@('-':_), _) <- srcs ] when (notNull unknown_opts) (unknownFlagsErr unknown_opts) when (not (Set.null (Set.filter wayRTSOnly (ways dflags))) && isInterpretiveMode mode) $ hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi") -- -prof and --interactive are not a good combination when ((Set.filter (not . wayRTSOnly) (ways dflags) /= hostFullWays) && isInterpretiveMode mode && not (gopt Opt_ExternalInterpreter dflags)) $ do throwGhcException (UsageError "-fexternal-interpreter is required when using --interactive with a non-standard way (-prof, -static, or -dynamic).") -- -ohi sanity check if (isJust (outputHi dflags) && (isCompManagerMode mode || srcs `lengthExceeds` 1)) then throwGhcException (UsageError "-ohi can only be used when compiling a single source file") else do -- -o sanity checking if (srcs `lengthExceeds` 1 && isJust (outputFile dflags) && not (isLinkMode mode)) then throwGhcException (UsageError "can't apply -o to multiple source files") else do let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags) when (not_linking && not (null objs)) $ hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs) -- Check that there are some input files -- (except in the interactive case) if null srcs && (null objs || not_linking) && needsInputsMode mode then throwGhcException (UsageError "no input files") else do case mode of StopBefore HCc | hscTarget dflags /= HscC -> throwGhcException $ UsageError $ "the option -C is only available with an unregisterised GHC" StopBefore (As False) | ghcLink dflags == NoLink -> throwGhcException $ UsageError $ "the options -S and -fno-code are incompatible. Please omit -S" _ -> return () -- Verify that output files point somewhere sensible. verifyOutputFiles dflags -- Compiler output options -- Called to verify that the output files point somewhere valid. -- -- The assumption is that the directory portion of these output -- options will have to exist by the time 'verifyOutputFiles' -- is invoked. -- -- We create the directories for -odir, -hidir, -outputdir etc. ourselves if they do n't exist , so do n't check for those here ( # 2278 ) . verifyOutputFiles :: DynFlags -> IO () verifyOutputFiles dflags = do let ofile = outputFile dflags when (isJust ofile) $ do let fn = fromJust ofile flg <- doesDirNameExist fn when (not flg) (nonExistentDir "-o" fn) let ohi = outputHi dflags when (isJust ohi) $ do let hi = fromJust ohi flg <- doesDirNameExist hi when (not flg) (nonExistentDir "-ohi" hi) where nonExistentDir flg dir = throwGhcException (CmdLineError ("error: directory portion of " ++ show dir ++ " does not exist (used with " ++ show flg ++ " option.)")) ----------------------------------------------------------------------------- GHC modes of operation type Mode = Either PreStartupMode PostStartupMode type PostStartupMode = Either PreLoadMode PostLoadMode data PreStartupMode = ShowVersion -- ghc -V/--version | ShowNumVersion -- ghc --numeric-version | ShowSupportedExtensions -- ghc --supported-extensions | ShowOptions Bool {- isInteractive -} -- ghc --show-options showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode showVersionMode = mkPreStartupMode ShowVersion showNumVersionMode = mkPreStartupMode ShowNumVersion showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions showOptionsMode = mkPreStartupMode (ShowOptions False) mkPreStartupMode :: PreStartupMode -> Mode mkPreStartupMode = Left isShowVersionMode :: Mode -> Bool isShowVersionMode (Left ShowVersion) = True isShowVersionMode _ = False isShowNumVersionMode :: Mode -> Bool isShowNumVersionMode (Left ShowNumVersion) = True isShowNumVersionMode _ = False data PreLoadMode ghc - ? | ShowGhciUsage -- ghci -? ghc --info ghc --print - foo showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode showGhcUsageMode = mkPreLoadMode ShowGhcUsage showGhciUsageMode = mkPreLoadMode ShowGhciUsage showInfoMode = mkPreLoadMode ShowInfo printSetting :: String -> Mode printSetting k = mkPreLoadMode (PrintWithDynFlags f) where f dflags = fromMaybe (panic ("Setting not found: " ++ show k)) $ lookup k (compilerInfo dflags) mkPreLoadMode :: PreLoadMode -> Mode mkPreLoadMode = Right . Left isShowGhcUsageMode :: Mode -> Bool isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True isShowGhcUsageMode _ = False isShowGhciUsageMode :: Mode -> Bool isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True isShowGhciUsageMode _ = False data PostLoadMode = ShowInterface FilePath -- ghc --show-iface ghc -M | StopBefore Phase -- ghc -E | -C | -S StopBefore StopLn is the default | DoMake -- ghc --make ghc --backpack foo.bkp ghc --interactive | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"] ghc --abi - hash | ShowPackages -- ghc --show-packages | DoFrontend ModuleName -- ghc --frontend Plugin.Module | DoVHDL -- ghc --vhdl | DoVerilog -- ghc --verilog | DoSystemVerilog -- ghc --systemverilog doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode, showUnitsMode, doVHDLMode, doVerilogMode, doSystemVerilogMode :: Mode doMkDependHSMode = mkPostLoadMode DoMkDependHS doMakeMode = mkPostLoadMode DoMake doInteractiveMode = mkPostLoadMode DoInteractive doAbiHashMode = mkPostLoadMode DoAbiHash showUnitsMode = mkPostLoadMode ShowPackages doVHDLMode = mkPostLoadMode DoVHDL doVerilogMode = mkPostLoadMode DoVerilog doSystemVerilogMode = mkPostLoadMode DoSystemVerilog showInterfaceMode :: FilePath -> Mode showInterfaceMode fp = mkPostLoadMode (ShowInterface fp) stopBeforeMode :: Phase -> Mode stopBeforeMode phase = mkPostLoadMode (StopBefore phase) doEvalMode :: String -> Mode doEvalMode str = mkPostLoadMode (DoEval [str]) doFrontendMode :: String -> Mode doFrontendMode str = mkPostLoadMode (DoFrontend (mkModuleName str)) doBackpackMode :: Mode doBackpackMode = mkPostLoadMode DoBackpack mkPostLoadMode :: PostLoadMode -> Mode mkPostLoadMode = Right . Right isDoInteractiveMode :: Mode -> Bool isDoInteractiveMode (Right (Right DoInteractive)) = True isDoInteractiveMode _ = False isStopLnMode :: Mode -> Bool isStopLnMode (Right (Right (StopBefore StopLn))) = True isStopLnMode _ = False isDoMakeMode :: Mode -> Bool isDoMakeMode (Right (Right DoMake)) = True isDoMakeMode _ = False isDoEvalMode :: Mode -> Bool isDoEvalMode (Right (Right (DoEval _))) = True isDoEvalMode _ = False #if defined(HAVE_INTERNAL_INTERPRETER) isInteractiveMode :: PostLoadMode -> Bool isInteractiveMode DoInteractive = True isInteractiveMode _ = False #endif -- isInterpretiveMode: byte-code compiler involved isInterpretiveMode :: PostLoadMode -> Bool isInterpretiveMode DoInteractive = True isInterpretiveMode (DoEval _) = True isInterpretiveMode _ = False needsInputsMode :: PostLoadMode -> Bool needsInputsMode DoMkDependHS = True needsInputsMode (StopBefore _) = True needsInputsMode DoMake = True needsInputsMode DoVHDL = True needsInputsMode DoVerilog = True needsInputsMode DoSystemVerilog = True needsInputsMode _ = False -- True if we are going to attempt to link in this mode. ( we might not actually link , depending on the GhcLink flag ) isLinkMode :: PostLoadMode -> Bool isLinkMode (StopBefore StopLn) = True isLinkMode DoMake = True isLinkMode DoInteractive = True isLinkMode (DoEval _) = True isLinkMode _ = False isCompManagerMode :: PostLoadMode -> Bool isCompManagerMode DoMake = True isCompManagerMode DoInteractive = True isCompManagerMode (DoEval _) = True isCompManagerMode DoVHDL = True isCompManagerMode DoVerilog = True isCompManagerMode DoSystemVerilog = True isCompManagerMode _ = False -- ----------------------------------------------------------------------------- -- Parsing the mode flag parseModeFlags :: [Located String] -> IO (Mode, [Located String], [Warn]) parseModeFlags args = do let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) = runCmdLine (processArgs mode_flags args) (Nothing, [], []) mode = case mModeFlag of Nothing -> doMakeMode Just (m, _) -> m -- See Note [Handling errors when parsing commandline flags] unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $ map (("on the commandline", )) $ map (unLoc . errMsg) errs1 ++ errs2 return (mode, flags' ++ leftover, warns) type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String]) mode flags sometimes give rise to new DynFlags ( eg . -C , see below ) -- so we collect the new ones and return them. mode_flags :: [Flag ModeM] mode_flags = [ ------- help / version ---------------------------------------------- defFlag "?" (PassFlag (setMode showGhcUsageMode)) , defFlag "-help" (PassFlag (setMode showGhcUsageMode)) , defFlag "V" (PassFlag (setMode showVersionMode)) , defFlag "-version" (PassFlag (setMode showVersionMode)) , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode)) , defFlag "-info" (PassFlag (setMode showInfoMode)) , defFlag "-show-options" (PassFlag (setMode showOptionsMode)) , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-show-packages" (PassFlag (setMode showUnitsMode)) ] ++ [ defFlag k' (PassFlag (setMode (printSetting k))) | k <- ["Project version", "Project Git commit id", "Booter version", "Stage", "Build platform", "Host platform", "Target platform", "Have interpreter", "Object splitting supported", "Have native code generator", "Support SMP", "Unregisterised", "Tables next to code", "RTS ways", "Leading underscore", "Debug on", "LibDir", "Global Package DB", "C compiler flags", "C compiler link flags", "ld flags"], let k' = "-print-" ++ map (replaceSpace . toLower) k replaceSpace ' ' = '-' replaceSpace c = c ] ++ ------- interfaces ---------------------------------------------------- [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f) "--show-iface")) ------- primary modes ------------------------------------------------ , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f addFlag "-no-link" f)) , defFlag "M" (PassFlag (setMode doMkDependHSMode)) , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc))) , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc))) , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False)))) , defFlag "-make" (PassFlag (setMode doMakeMode)) , defFlag "-backpack" (PassFlag (setMode doBackpackMode)) , defFlag "-interactive" (PassFlag (setMode doInteractiveMode)) , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode)) , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e")) , defFlag "-frontend" (SepArg (\s -> setMode (doFrontendMode s) "-frontend")) , defFlag "-vhdl" (PassFlag (setMode doVHDLMode)) , defFlag "-verilog" (PassFlag (setMode doVerilogMode)) , defFlag "-systemverilog" (PassFlag (setMode doSystemVerilogMode)) ] setMode :: Mode -> String -> EwM ModeM () setMode newMode newFlag = liftEwM $ do (mModeFlag, errs, flags') <- getCmdLineState let (modeFlag', errs') = case mModeFlag of Nothing -> ((newMode, newFlag), errs) Just (oldMode, oldFlag) -> case (oldMode, newMode) of -- -c/--make are allowed together, and mean --make -no-link _ | isStopLnMode oldMode && isDoMakeMode newMode || isStopLnMode newMode && isDoMakeMode oldMode -> ((doMakeMode, "--make"), []) -- If we have both --help and --interactive then we -- want showGhciUsage _ | isShowGhcUsageMode oldMode && isDoInteractiveMode newMode -> ((showGhciUsageMode, oldFlag), []) | isShowGhcUsageMode newMode && isDoInteractiveMode oldMode -> ((showGhciUsageMode, newFlag), []) -- If we have both -e and --interactive then -e always wins _ | isDoEvalMode oldMode && isDoInteractiveMode newMode -> ((oldMode, oldFlag), []) | isDoEvalMode newMode && isDoInteractiveMode oldMode -> ((newMode, newFlag), []) -- Otherwise, --help/--version/--numeric-version always win | isDominantFlag oldMode -> ((oldMode, oldFlag), []) | isDominantFlag newMode -> ((newMode, newFlag), []) -- We need to accumulate eval flags like "-e foo -e bar" (Right (Right (DoEval esOld)), Right (Right (DoEval [eNew]))) -> ((Right (Right (DoEval (eNew : esOld))), oldFlag), errs) -- Saying e.g. --interactive --interactive is OK _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs) -- --interactive and --show-options are used together (Right (Right DoInteractive), Left (ShowOptions _)) -> ((Left (ShowOptions True), "--interactive --show-options"), errs) (Left (ShowOptions _), (Right (Right DoInteractive))) -> ((Left (ShowOptions True), "--show-options --interactive"), errs) -- Otherwise, complain _ -> let err = flagMismatchErr oldFlag newFlag in ((oldMode, oldFlag), err : errs) putCmdLineState (Just modeFlag', errs', flags') where isDominantFlag f = isShowGhcUsageMode f || isShowGhciUsageMode f || isShowVersionMode f || isShowNumVersionMode f flagMismatchErr :: String -> String -> String flagMismatchErr oldFlag newFlag = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'" addFlag :: String -> String -> EwM ModeM () addFlag s flag = liftEwM $ do (m, e, flags') <- getCmdLineState putCmdLineState (m, e, mkGeneralLocated loc s : flags') where loc = "addFlag by " ++ flag ++ " on the commandline" -- ---------------------------------------------------------------------------- -- Run --make mode doMake :: [(String,Maybe Phase)] -> Ghc () doMake srcs = do let (hs_srcs, non_hs_srcs) = partition isHaskellishTarget srcs hsc_env <- GHC.getSession -- if we have no haskell sources from which to do a dependency analysis , then just do one - shot compilation and/or linking . -- This means that "ghc Foo.o Bar.o -o baz" links the program as -- we expect. if (null hs_srcs) then liftIO (oneShot hsc_env StopLn srcs) else do o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x) non_hs_srcs dflags <- GHC.getSessionDynFlags let dflags' = dflags { ldInputs = map (FileOption "") o_files ++ ldInputs dflags } _ <- GHC.setSessionDynFlags dflags' targets <- mapM (uncurry GHC.guessTarget) hs_srcs GHC.setTargets targets ok_flag <- GHC.load LoadAllTargets when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1)) return () -- --------------------------------------------------------------------------- -- --show-iface mode doShowIface :: DynFlags -> FilePath -> IO () doShowIface dflags file = do hsc_env <- newHscEnv dflags showIface hsc_env file -- --------------------------------------------------------------------------- -- Various banners and verbosity output. showBanner :: PostLoadMode -> DynFlags -> IO () showBanner _postLoadMode dflags = do let verb = verbosity dflags #if defined(HAVE_INTERNAL_INTERPRETER) -- Show the GHCi banner when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg #endif -- Display details of the configuration in verbose mode when (verb >= 2) $ do hPutStr stderr "Glasgow Haskell Compiler, Version " hPutStr stderr cProjectVersion hPutStr stderr ", stage " hPutStr stderr cStage hPutStr stderr " booted by GHC version " hPutStrLn stderr cBooterVersion -- We print out a Read-friendly string, but a prettier one than the -- Show instance gives us showInfo :: DynFlags -> IO () showInfo dflags = do let sq x = " [" ++ x ++ "\n ]" putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags TODO use GHC.Utils . Error once that is disentangled from all the other GhcMonad stuff ? showSupportedExtensions :: Maybe String -> IO () showSupportedExtensions m_top_dir = do res <- runExceptT $ do top_dir <- lift (tryFindTopDir m_top_dir) >>= \case Nothing -> throwE $ SettingsError_MissingData "Could not find the top directory, missing -B flag" Just dir -> pure dir initSettings top_dir targetPlatformMini <- case res of Right s -> pure $ platformMini $ sTargetPlatform s Left (SettingsError_MissingData msg) -> do hPutStrLn stderr $ "WARNING: " ++ show msg hPutStrLn stderr $ "cannot know target platform so guessing target == host (native compiler)." pure cHostPlatformMini Left (SettingsError_BadData msg) -> do hPutStrLn stderr msg exitWith $ ExitFailure 1 mapM_ putStrLn $ supportedLanguagesAndExtensions targetPlatformMini showVersion :: IO () showVersion = putStrLn $ concat [ "Clash, version " , Data.Version.showVersion Paths_clash_ghc.version , " (using clash-lib, version: " , Data.Version.showVersion clashLibVersion , ")" ] showOptions :: Bool -> IORef ClashOpts -> IO () showOptions isInteractive = putStr . unlines . availableOptions where availableOptions opts = concat [ flagsForCompletion isInteractive, map ('-':) (getFlagNames mode_flags), map ('-':) (getFlagNames (flagsClash opts)) ] getFlagNames opts = map flagName opts showGhcUsage :: DynFlags -> IO () showGhcUsage = showUsage False showGhciUsage :: DynFlags -> IO () showGhciUsage = showUsage True showUsage :: Bool -> DynFlags -> IO () showUsage ghci dflags = do let usage_path = if ghci then ghciUsagePath dflags else ghcUsagePath dflags usage <- readFile usage_path dump usage where dump "" = return () dump ('$':'$':s) = putStr progName >> dump s dump (c:s) = putChar c >> dump s dumpFinalStats :: DynFlags -> IO () dumpFinalStats dflags = when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags dumpFastStringStats :: DynFlags -> IO () dumpFastStringStats dflags = do segments <- getFastStringTable hasZ <- getFastStringZEncCounter let buckets = concat segments bucketsPerSegment = map length segments entriesPerBucket = map length buckets entries = sum entriesPerBucket msg = text "FastString stats:" $$ nest 4 (vcat [ text "segments: " <+> int (length segments) , text "buckets: " <+> int (sum bucketsPerSegment) , text "entries: " <+> int entries , text "largest segment: " <+> int (maximum bucketsPerSegment) , text "smallest segment: " <+> int (minimum bucketsPerSegment) , text "longest bucket: " <+> int (maximum entriesPerBucket) , text "has z-encoding: " <+> (hasZ `pcntOf` entries) ]) -- we usually get more "has z-encoding" than "z-encoded", because -- when we z-encode a string it might hash to the exact same string, -- which is not counted as "z-encoded". Only strings whose -- Z-encoding is different from the original string are counted in -- the "z-encoded" total. putMsg dflags msg where x `pcntOf` y = int ((x * 100) `quot` y) Outputable.<> char '%' showUnits, dumpUnits, dumpUnitsSimple :: DynFlags -> IO () showUnits dflags = putStrLn (showSDoc dflags (pprUnits (unitState dflags))) dumpUnits dflags = putMsg dflags (pprUnits (unitState dflags)) dumpUnitsSimple dflags = putMsg dflags (pprUnitsSimple (unitState dflags)) -- ----------------------------------------------------------------------------- Frontend plugin support doFrontend :: ModuleName -> [(String, Maybe Phase)] -> Ghc () doFrontend modname srcs = do hsc_env <- getSession frontend_plugin <- liftIO $ loadFrontendPlugin hsc_env modname frontend frontend_plugin (reverse $ frontendPluginOpts (hsc_dflags hsc_env)) srcs -- ----------------------------------------------------------------------------- ABI hash support ghc --abi - hash Data . Foo System . Bar Generates a combined hash of the ABI for modules Data . and System . Bar . The modules must already be compiled , and appropriate -i options may be necessary in order to find the .hi files . This is used by Cabal for generating the ComponentId for a package . The ComponentId must change when the visible ABI of the package changes , so during registration Cabal calls ghc --abi - hash to get a hash of the package 's ABI . ghc --abi-hash Data.Foo System.Bar Generates a combined hash of the ABI for modules Data.Foo and System.Bar. The modules must already be compiled, and appropriate -i options may be necessary in order to find the .hi files. This is used by Cabal for generating the ComponentId for a package. The ComponentId must change when the visible ABI of the package changes, so during registration Cabal calls ghc --abi-hash to get a hash of the package's ABI. -} -- | Print ABI hash of input modules. -- The resulting hash is the MD5 of the GHC version used ( # 5328 , see ' hiVersion ' ) and of the existing ABI hash from each module ( see -- 'mi_mod_hash'). abiHash :: [String] -- ^ List of module names -> Ghc () abiHash strs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env liftIO $ do let find_it str = do let modname = mkModuleName str r <- findImportedModule hsc_env modname Nothing case r of Found _ m -> return m _error -> throwGhcException $ CmdLineError $ showSDoc dflags $ cannotFindModule dflags modname r mods <- mapM find_it strs let get_iface modl = loadUserInterface NotBoot (text "abiHash") modl ifaces <- initIfaceCheck (text "abiHash") hsc_env $ mapM get_iface mods bh <- openBinMem (3*1024) -- just less than a block put_ bh hiVersion -- package hashes change when the compiler version changes (for now) see # 5328 mapM_ (put_ bh . mi_mod_hash . mi_final_exts) ifaces f <- fingerprintBinMem bh putStrLn (showPpr dflags f) ----------------------------------------------------------------------------- -- HDL Generation makeHDL' :: forall backend . Backend backend => Proxy backend -> Ghc () -> IORef ClashOpts -> [(String,Maybe Phase)] -> Ghc () makeHDL' _ _ _ [] = throwGhcException (CmdLineError "No input files") makeHDL' proxy startAction r srcs = makeHDL proxy startAction r $ fmap fst srcs makeVHDL :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc () makeVHDL = makeHDL' (Proxy @VHDLState) makeVerilog :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc () makeVerilog = makeHDL' (Proxy @VerilogState) makeSystemVerilog :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc () makeSystemVerilog = makeHDL' (Proxy @SystemVerilogState) -- ----------------------------------------------------------------------------- -- Util unknownFlagsErr :: [String] -> a unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs where oneError f = "unrecognised flag: " ++ f ++ "\n" ++ (case match f (nubSort allNonDeprecatedFlags) of [] -> "" suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs)) fixes # 11789 -- If the flag contains '=', -- this uses both the whole and the left side of '=' for comparing. match f allFlags | elem '=' f = let (flagsWithEq, flagsWithoutEq) = partition (elem '=') allFlags fName = takeWhile (/= '=') f in (fuzzyMatch f flagsWithEq) ++ (fuzzyMatch fName flagsWithoutEq) | otherwise = fuzzyMatch f allFlags Note [ -Bsymbolic and hooks ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled ( see ` man ld ` ) . When dynamically linking , we do n't use -Bsymbolic on the RTS package : that is because we want hooks to be overridden by the user , we do n't want to constrain them to the RTS package . Unfortunately this seems to have broken somehow on OS X : as a result , defaultHooks ( in hschooks.c ) is not called , which does not initialize the GC stats . As a result , this breaks things like ` : set + s ` in GHCi ( # 8754 ) . As a hacky workaround , we instead call ' defaultHooks ' directly to initialize the flags in the RTS . A byproduct of this , I believe , is that hooks are likely broken on OS X when dynamically linking . But this probably does n't affect most people since we 're linking GHC dynamically , but most things themselves link statically . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled (see `man ld`). When dynamically linking, we don't use -Bsymbolic on the RTS package: that is because we want hooks to be overridden by the user, we don't want to constrain them to the RTS package. Unfortunately this seems to have broken somehow on OS X: as a result, defaultHooks (in hschooks.c) is not called, which does not initialize the GC stats. As a result, this breaks things like `:set +s` in GHCi (#8754). As a hacky workaround, we instead call 'defaultHooks' directly to initialize the flags in the RTS. A byproduct of this, I believe, is that hooks are likely broken on OS X when dynamically linking. But this probably doesn't affect most people since we're linking GHC dynamically, but most things themselves link statically. -} If GHC_LOADED_INTO_GHCI is not set when GHC is loaded into GHCi , then -- running it causes an error like this: -- -- Loading temp shared object failed: /tmp / ghc13836_0 / libghc_1872.so : undefined symbol : initGCStatistics -- -- Skipping the foreign call fixes this problem, and the outer GHCi -- should have already made this call anyway. #if defined(GHC_LOADED_INTO_GHCI) initGCStatistics :: IO () initGCStatistics = return () #else foreign import ccall safe "initGCStatistics" initGCStatistics :: IO () #endif
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/8c98dfd55094b0dd0faaeb1667a681965d077946/clash-ghc/src-bin-9.0/Clash/Main.hs
haskell
# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE # --------------------------------------------------------------------------- --------------------------------------------------------------------------- Implementations of the various modes (--show-iface, mkdependHS. etc.) Various other random stuff that we need Imports for --abi-hash clash additions --------------------------------------------------------------------------- time commands when run with -v user ways Win32 support: proper signal handling reading the package configuration file is too slow -K<size> --------------------------------------------------------------------------- See Note [-Bsymbolic and hooks] mbMinusB | null minusB_args = Nothing make , --interactive etc . ) If all we want to do is something like showing the version number getting basic information much more resilient. In particular, if we wait until later before giving the version number then bootstrapping gets confused, as it tries to find out starting the session fails. can be further adjusted on a module by module basis, using only HscC or HscAsm, -fvia-C and -fasm have no effect. turn on -fimplicit-import-qualified for GHCi now, so that it can be overridden from the command-line which are program-level options. Again, this doesn't really feel like the right place to handle this, but we don't have a great story for the moment. The rest of the arguments are "dynamic" Leftover ones are presumably files Propagate -Werror to Clash To simplify the handling of filepaths, we normalise all filepaths right away. Note the asymmetry of FilePath.normalise: to -foo.hs. We have to re-prepend the current directory. -------------- Display configuration ----------- -------------- Final sanity checking ----------- -------------- Do the business ----------- ----------------------------------------------------------------------------- Splitting arguments into source files and object files. This is where we interpret the -x <suffix> option, and attach a (Maybe Phase) to each source file indicating the phase specified by the -x option in force, if any. ----------------------------------------------------------------------------- Option sanity checks | Ensure sanity of options. Final sanity checking before kicking off a compilation (pipeline). Complain about any unknown flags -prof and --interactive are not a good combination -ohi sanity check -o sanity checking Check that there are some input files (except in the interactive case) Verify that output files point somewhere sensible. Compiler output options Called to verify that the output files point somewhere valid. The assumption is that the directory portion of these output options will have to exist by the time 'verifyOutputFiles' is invoked. We create the directories for -odir, -hidir, -outputdir etc. ourselves if --------------------------------------------------------------------------- ghc -V/--version ghc --numeric-version ghc --supported-extensions isInteractive ghc --show-options ghci -? info print - foo ghc --show-iface ghc -E | -C | -S ghc --make backpack foo.bkp interactive ghc -e foo -e bar => DoEval ["bar", "foo"] abi - hash ghc --show-packages ghc --frontend Plugin.Module ghc --vhdl ghc --verilog ghc --systemverilog isInterpretiveMode: byte-code compiler involved True if we are going to attempt to link in this mode. ----------------------------------------------------------------------------- Parsing the mode flag See Note [Handling errors when parsing commandline flags] so we collect the new ones and return them. ----- help / version ---------------------------------------------- ----- interfaces ---------------------------------------------------- ----- primary modes ------------------------------------------------ -c/--make are allowed together, and mean --make -no-link If we have both --help and --interactive then we want showGhciUsage If we have both -e and --interactive then -e always wins Otherwise, --help/--version/--numeric-version always win We need to accumulate eval flags like "-e foo -e bar" Saying e.g. --interactive --interactive is OK --interactive and --show-options are used together Otherwise, complain ---------------------------------------------------------------------------- Run --make mode if we have no haskell sources from which to do a dependency This means that "ghc Foo.o Bar.o -o baz" links the program as we expect. --------------------------------------------------------------------------- --show-iface mode --------------------------------------------------------------------------- Various banners and verbosity output. Show the GHCi banner Display details of the configuration in verbose mode We print out a Read-friendly string, but a prettier one than the Show instance gives us we usually get more "has z-encoding" than "z-encoded", because when we z-encode a string it might hash to the exact same string, which is not counted as "z-encoded". Only strings whose Z-encoding is different from the original string are counted in the "z-encoded" total. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- abi - hash Data . Foo System . Bar abi - hash abi-hash Data.Foo System.Bar abi-hash | Print ABI hash of input modules. 'mi_mod_hash'). ^ List of module names just less than a block package hashes change when the compiler version changes (for now) --------------------------------------------------------------------------- HDL Generation ----------------------------------------------------------------------------- Util If the flag contains '=', this uses both the whole and the left side of '=' for comparing. running it causes an error like this: Loading temp shared object failed: Skipping the foreign call fixes this problem, and the outer GHCi should have already made this call anyway.
# LANGUAGE CPP # # LANGUAGE LambdaCase # # LANGUAGE NondecreasingIndentation # # LANGUAGE TupleSections # GHC Driver program ( c ) The University of Glasgow 2005 module Clash.Main (defaultMain, defaultMainWithAction) where The official GHC API import qualified GHC DynFlags ( .. ) , HscTarget ( .. ) , GhcMode ( .. ) , ( .. ) , Ghc, GhcMonad(..), LoadHowMuch(..) ) import GHC.Driver.CmdLine import GHC.Iface.Load ( showIface ) import GHC.Driver.Main ( newHscEnv ) import GHC.Driver.Pipeline ( oneShot, compileFile ) import GHC.Driver.MakeFile ( doMkDependHS ) import GHC.Driver.Backpack ( doBackpack ) import GHC.Driver.Ways #if defined(HAVE_INTERNAL_INTERPRETER) import Clash.GHCi.UI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings ) #endif Frontend plugins import GHC.Runtime.Loader ( loadFrontendPlugin ) import GHC.Driver.Plugins #if defined(HAVE_INTERNAL_INTERPRETER) import GHC.Runtime.Loader ( initializePlugins ) #endif import GHC.Unit.Module ( ModuleName, mkModuleName ) import GHC.HandleEncoding import GHC.Platform import GHC.Platform.Host import GHC.Settings.Config import GHC.Settings.Constants import GHC.Driver.Types import GHC.Unit.State ( pprUnits, pprUnitsSimple ) import GHC.Driver.Phases import GHC.Types.Basic ( failed ) import GHC.Driver.Session as DynFlags hiding (WarnReason(..)) import GHC.Utils.Error import GHC.Data.EnumSet as EnumSet import GHC.Data.FastString import GHC.Utils.Outputable as Outputable import GHC.SysTools.BaseDir import GHC.Settings.IO import GHC.Types.SrcLoc import GHC.Utils.Misc import GHC.Utils.Panic import GHC.Types.Unique.Supply import GHC.Utils.Monad ( liftIO ) import GHC.Iface.Load ( loadUserInterface ) import GHC.Driver.Finder ( findImportedModule, cannotFindModule ) import GHC.Tc.Utils.Monad ( initIfaceCheck ) import GHC.Utils.Binary ( openBinMem, put_ ) import GHC.Iface.Recomp.Binary ( fingerprintBinMem ) Standard Haskell libraries import System.IO import System.Environment import System.Exit import System.FilePath import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.Except (throwE, runExceptT) import Data.Char import Data.List ( isPrefixOf, partition, intercalate, nub ) import Data.Proxy import qualified Data.Set as Set import Data.Maybe import Prelude import Paths_clash_ghc import Clash.GHCi.UI (makeHDL) import Control.Monad.Catch (catch) import Data.IORef (IORef, newIORef, readIORef, modifyIORef') import qualified Data.Version (showVersion) import Clash.Backend (Backend) import Clash.Backend.SystemVerilog (SystemVerilogState) import Clash.Backend.VHDL (VHDLState) import Clash.Backend.Verilog (VerilogState) import Clash.Driver.Types (ClashOpts (..), defClashOpts) import Clash.GHC.ClashFlags import Clash.Util (clashLibVersion) import Clash.GHC.LoadModules (ghcLibDir, setWantedLanguageExtensions) import Clash.GHC.Util (handleClashException) ToDo : GHC 's command - line interface defaultMain :: [String] -> IO () defaultMain = defaultMainWithAction (return ()) defaultMainWithAction :: Ghc () -> [String] -> IO () defaultMainWithAction startAction = flip withArgs $ do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering configureHandleEncoding GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do 1 . extract the -B flag from the args argv0 <- getArgs let ( minusB_args , ) = partition ( " -B " ` isPrefixOf ` ) | otherwise = Just ( drop 2 ( last minusB_args ) ) let argv1 = map (mkGeneralLocated "on the commandline") argv0 libDir <- ghcLibDir r <- newIORef defClashOpts (argv2, clashFlagWarnings) <- parseClashFlags r argv1 (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2 let flagWarnings = modeFlagWarnings ++ clashFlagWarnings then do it now , before we start a GHC session etc . This makes what version of GHC it 's using before package.conf exists , so case mode of Left preStartupMode -> do case preStartupMode of ShowSupportedExtensions -> showSupportedExtensions (Just libDir) ShowVersion -> showVersion ShowNumVersion -> putStrLn cProjectVersion ShowOptions isInteractive -> showOptions isInteractive r Right postStartupMode -> start our GHC session GHC.runGhc (Just libDir) $ do dflags <- GHC.getSessionDynFlags let dflagsExtra = setWantedLanguageExtensions dflags ghcTyLitNormPlugin = GHC.mkModuleName "GHC.TypeLits.Normalise" ghcTyLitExtrPlugin = GHC.mkModuleName "GHC.TypeLits.Extra.Solver" ghcTyLitKNPlugin = GHC.mkModuleName "GHC.TypeLits.KnownNat.Solver" dflagsExtra1 = dflagsExtra { DynFlags.pluginModNames = nub $ ghcTyLitNormPlugin : ghcTyLitExtrPlugin : ghcTyLitKNPlugin : DynFlags.pluginModNames dflagsExtra } case postStartupMode of Left preLoadMode -> liftIO $ do case preLoadMode of ShowInfo -> showInfo dflagsExtra1 ShowGhcUsage -> showGhcUsage dflagsExtra1 ShowGhciUsage -> showGhciUsage dflagsExtra1 PrintWithDynFlags f -> putStrLn (f dflagsExtra1) Right postLoadMode -> main' postLoadMode dflagsExtra1 argv3 flagWarnings startAction r main' :: PostLoadMode -> DynFlags -> [Located String] -> [Warn] -> Ghc () -> IORef ClashOpts -> Ghc () main' postLoadMode dflags0 args flagWarnings startAction clashOpts = do set the default GhcMode , HscTarget and GhcLink . The HscTarget the -fvia - C and -fasm flags . If the default HscTarget is not let dflt_target = hscTarget dflags0 (mode, lang, link) = case postLoadMode of DoInteractive -> (CompManager, HscInterpreted, LinkInMemory) DoEval _ -> (CompManager, HscInterpreted, LinkInMemory) DoMake -> (CompManager, dflt_target, LinkBinary) DoBackpack -> (CompManager, dflt_target, LinkBinary) DoMkDependHS -> (MkDepend, dflt_target, LinkBinary) DoAbiHash -> (OneShot, dflt_target, LinkBinary) DoVHDL -> (CompManager, HscNothing, NoLink) DoVerilog -> (CompManager, HscNothing, NoLink) DoSystemVerilog -> (CompManager, HscNothing, NoLink) _ -> (OneShot, dflt_target, LinkBinary) let dflags1 = dflags0{ ghcMode = mode, hscTarget = lang, ghcLink = link, verbosity = case postLoadMode of DoEval _ -> 0 _other -> 1 } XXX : this should really be in the interactive DynFlags , but we do n't set that until later in interactiveUI We also set -fignore - - changes and -fignore - hpc - changes , dflags2 | DoInteractive <- postLoadMode = def_ghci_flags | DoEval _ <- postLoadMode = def_ghci_flags | otherwise = dflags1 where def_ghci_flags = dflags1 `gopt_set` Opt_ImplicitImportQualified `gopt_set` Opt_IgnoreOptimChanges `gopt_set` Opt_IgnoreHpcChanges (dflags3, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags2 args liftIO . modifyIORef' clashOpts $ \opts -> opts { opt_werror = EnumSet.member Opt_WarnIsError (generalFlags dflags3) } let dflags4 = case lang of HscInterpreted | not (gopt Opt_ExternalInterpreter dflags3) -> let platform = targetPlatform dflags3 dflags3a = dflags3 { ways = hostFullWays } dflags3b = foldl gopt_set dflags3a $ concatMap (wayGeneralFlags platform) hostFullWays dflags3c = foldl gopt_unset dflags3b $ concatMap (wayUnsetGeneralFlags platform) hostFullWays in dflags3c _ -> dflags3 GHC.prettyPrintGhcErrors dflags4 $ do let flagWarnings' = flagWarnings ++ dynamicFlagWarnings handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ handleFlagWarnings dflags4 flagWarnings' liftIO $ showBanner postLoadMode dflags4 let Linux : p / q - > p / q ; p\q - > p\q Windows : p / q - > p\q ; p\q - > p\q # 12674 : Filenames starting with a hypen get normalised from ./-foo.hs normalise_hyp fp | strt_dot_sl && "-" `isPrefixOf` nfp = cur_dir ++ nfp | otherwise = nfp where #if defined(mingw32_HOST_OS) strt_dot_sl = "./" `isPrefixOf` fp || ".\\" `isPrefixOf` fp #else strt_dot_sl = "./" `isPrefixOf` fp #endif cur_dir = '.' : [pathSeparator] nfp = normalise fp normal_fileish_paths = map (normalise_hyp . unLoc) fileish_args (srcs, objs) = partition_args normal_fileish_paths [] [] dflags5 = dflags4 { ldInputs = map (FileOption "") objs ++ ldInputs dflags4 } we 've finished manipulating the DynFlags , update the session _ <- GHC.setSessionDynFlags dflags5 dflags6 <- GHC.getSessionDynFlags hsc_env <- GHC.getSession case verbosity dflags6 of v | v == 4 -> liftIO $ dumpUnitsSimple dflags6 | v >= 5 -> liftIO $ dumpUnits dflags6 | otherwise -> return () liftIO $ initUniqSupply (initialUnique dflags6) (uniqueIncrement dflags6) liftIO $ checkOptions postLoadMode dflags6 srcs objs handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do clashOpts' <- liftIO (readIORef clashOpts) let clash fun = catch (fun startAction clashOpts srcs) (handleClashException dflags6 clashOpts') case postLoadMode of ShowInterface f -> liftIO $ doShowIface dflags6 f DoMake -> doMake srcs DoMkDependHS -> doMkDependHS (map fst srcs) StopBefore p -> liftIO (oneShot hsc_env p srcs) DoInteractive -> ghciUI clashOpts hsc_env dflags6 srcs Nothing DoEval exprs -> ghciUI clashOpts hsc_env dflags6 srcs $ Just $ reverse exprs DoAbiHash -> abiHash (map fst srcs) ShowPackages -> liftIO $ showUnits dflags6 DoFrontend f -> doFrontend f srcs DoBackpack -> doBackpack (map fst srcs) DoVHDL -> clash makeVHDL DoVerilog -> clash makeVerilog DoSystemVerilog -> clash makeSystemVerilog liftIO $ dumpFinalStats dflags6 ghciUI :: IORef ClashOpts -> HscEnv -> DynFlags -> [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc () #if !defined(HAVE_INTERNAL_INTERPRETER) ghciUI _ _ _ _ _ = throwGhcException (CmdLineError "not built for interactive use") #else ghciUI clashOpts hsc_env dflags0 srcs maybe_expr = do dflags1 <- liftIO (initializePlugins hsc_env dflags0) _ <- GHC.setSessionDynFlags dflags1 interactiveUI (defaultGhciSettings clashOpts) srcs maybe_expr #endif partition_args :: [String] -> [(String, Maybe Phase)] -> [String] -> ([(String, Maybe Phase)], [String]) partition_args [] srcs objs = (reverse srcs, reverse objs) partition_args ("-x":suff:args) srcs objs | "none" <- suff = partition_args args srcs objs | StopLn <- phase = partition_args args srcs (slurp ++ objs) | otherwise = partition_args rest (these_srcs ++ srcs) objs where phase = startPhase suff (slurp,rest) = break (== "-x") args these_srcs = zip slurp (repeat (Just phase)) partition_args (arg:args) srcs objs | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs | otherwise = partition_args args srcs (arg:objs) We split out the object files ( .o , .dll ) and add them to ldInputs for use by the linker . The following things should be considered compilation manager inputs : - haskell source files ( strings ending in .hs , .lhs or other haskellish extension ) , - module names ( not forgetting hierarchical module names ) , - things beginning with ' - ' are flags that were not recognised by the flag parser , and we want them to generate errors later in checkOptions , so we class them as source files ( # 5921 ) - and finally we consider everything without an extension to be a comp manager input , as shorthand for a .hs or .lhs filename . Everything else is considered to be a linker object , and passed straight through to the linker . We split out the object files (.o, .dll) and add them to ldInputs for use by the linker. The following things should be considered compilation manager inputs: - haskell source files (strings ending in .hs, .lhs or other haskellish extension), - module names (not forgetting hierarchical module names), - things beginning with '-' are flags that were not recognised by the flag parser, and we want them to generate errors later in checkOptions, so we class them as source files (#5921) - and finally we consider everything without an extension to be a comp manager input, as shorthand for a .hs or .lhs filename. Everything else is considered to be a linker object, and passed straight through to the linker. -} looks_like_an_input :: String -> Bool looks_like_an_input m = isSourceFilename m || looksLikeModuleName m || "-" `isPrefixOf` m || not (hasExtension m) Throws ' UsageError ' or ' CmdLineError ' if not . checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO () checkOptions mode dflags srcs objs = do let unknown_opts = [ f | (f@('-':_), _) <- srcs ] when (notNull unknown_opts) (unknownFlagsErr unknown_opts) when (not (Set.null (Set.filter wayRTSOnly (ways dflags))) && isInterpretiveMode mode) $ hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi") when ((Set.filter (not . wayRTSOnly) (ways dflags) /= hostFullWays) && isInterpretiveMode mode && not (gopt Opt_ExternalInterpreter dflags)) $ do throwGhcException (UsageError "-fexternal-interpreter is required when using --interactive with a non-standard way (-prof, -static, or -dynamic).") if (isJust (outputHi dflags) && (isCompManagerMode mode || srcs `lengthExceeds` 1)) then throwGhcException (UsageError "-ohi can only be used when compiling a single source file") else do if (srcs `lengthExceeds` 1 && isJust (outputFile dflags) && not (isLinkMode mode)) then throwGhcException (UsageError "can't apply -o to multiple source files") else do let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags) when (not_linking && not (null objs)) $ hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs) if null srcs && (null objs || not_linking) && needsInputsMode mode then throwGhcException (UsageError "no input files") else do case mode of StopBefore HCc | hscTarget dflags /= HscC -> throwGhcException $ UsageError $ "the option -C is only available with an unregisterised GHC" StopBefore (As False) | ghcLink dflags == NoLink -> throwGhcException $ UsageError $ "the options -S and -fno-code are incompatible. Please omit -S" _ -> return () verifyOutputFiles dflags they do n't exist , so do n't check for those here ( # 2278 ) . verifyOutputFiles :: DynFlags -> IO () verifyOutputFiles dflags = do let ofile = outputFile dflags when (isJust ofile) $ do let fn = fromJust ofile flg <- doesDirNameExist fn when (not flg) (nonExistentDir "-o" fn) let ohi = outputHi dflags when (isJust ohi) $ do let hi = fromJust ohi flg <- doesDirNameExist hi when (not flg) (nonExistentDir "-ohi" hi) where nonExistentDir flg dir = throwGhcException (CmdLineError ("error: directory portion of " ++ show dir ++ " does not exist (used with " ++ show flg ++ " option.)")) GHC modes of operation type Mode = Either PreStartupMode PostStartupMode type PostStartupMode = Either PreLoadMode PostLoadMode data PreStartupMode showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode showVersionMode = mkPreStartupMode ShowVersion showNumVersionMode = mkPreStartupMode ShowNumVersion showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions showOptionsMode = mkPreStartupMode (ShowOptions False) mkPreStartupMode :: PreStartupMode -> Mode mkPreStartupMode = Left isShowVersionMode :: Mode -> Bool isShowVersionMode (Left ShowVersion) = True isShowVersionMode _ = False isShowNumVersionMode :: Mode -> Bool isShowNumVersionMode (Left ShowNumVersion) = True isShowNumVersionMode _ = False data PreLoadMode ghc - ? showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode showGhcUsageMode = mkPreLoadMode ShowGhcUsage showGhciUsageMode = mkPreLoadMode ShowGhciUsage showInfoMode = mkPreLoadMode ShowInfo printSetting :: String -> Mode printSetting k = mkPreLoadMode (PrintWithDynFlags f) where f dflags = fromMaybe (panic ("Setting not found: " ++ show k)) $ lookup k (compilerInfo dflags) mkPreLoadMode :: PreLoadMode -> Mode mkPreLoadMode = Right . Left isShowGhcUsageMode :: Mode -> Bool isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True isShowGhcUsageMode _ = False isShowGhciUsageMode :: Mode -> Bool isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True isShowGhciUsageMode _ = False data PostLoadMode ghc -M StopBefore StopLn is the default doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode, showUnitsMode, doVHDLMode, doVerilogMode, doSystemVerilogMode :: Mode doMkDependHSMode = mkPostLoadMode DoMkDependHS doMakeMode = mkPostLoadMode DoMake doInteractiveMode = mkPostLoadMode DoInteractive doAbiHashMode = mkPostLoadMode DoAbiHash showUnitsMode = mkPostLoadMode ShowPackages doVHDLMode = mkPostLoadMode DoVHDL doVerilogMode = mkPostLoadMode DoVerilog doSystemVerilogMode = mkPostLoadMode DoSystemVerilog showInterfaceMode :: FilePath -> Mode showInterfaceMode fp = mkPostLoadMode (ShowInterface fp) stopBeforeMode :: Phase -> Mode stopBeforeMode phase = mkPostLoadMode (StopBefore phase) doEvalMode :: String -> Mode doEvalMode str = mkPostLoadMode (DoEval [str]) doFrontendMode :: String -> Mode doFrontendMode str = mkPostLoadMode (DoFrontend (mkModuleName str)) doBackpackMode :: Mode doBackpackMode = mkPostLoadMode DoBackpack mkPostLoadMode :: PostLoadMode -> Mode mkPostLoadMode = Right . Right isDoInteractiveMode :: Mode -> Bool isDoInteractiveMode (Right (Right DoInteractive)) = True isDoInteractiveMode _ = False isStopLnMode :: Mode -> Bool isStopLnMode (Right (Right (StopBefore StopLn))) = True isStopLnMode _ = False isDoMakeMode :: Mode -> Bool isDoMakeMode (Right (Right DoMake)) = True isDoMakeMode _ = False isDoEvalMode :: Mode -> Bool isDoEvalMode (Right (Right (DoEval _))) = True isDoEvalMode _ = False #if defined(HAVE_INTERNAL_INTERPRETER) isInteractiveMode :: PostLoadMode -> Bool isInteractiveMode DoInteractive = True isInteractiveMode _ = False #endif isInterpretiveMode :: PostLoadMode -> Bool isInterpretiveMode DoInteractive = True isInterpretiveMode (DoEval _) = True isInterpretiveMode _ = False needsInputsMode :: PostLoadMode -> Bool needsInputsMode DoMkDependHS = True needsInputsMode (StopBefore _) = True needsInputsMode DoMake = True needsInputsMode DoVHDL = True needsInputsMode DoVerilog = True needsInputsMode DoSystemVerilog = True needsInputsMode _ = False ( we might not actually link , depending on the GhcLink flag ) isLinkMode :: PostLoadMode -> Bool isLinkMode (StopBefore StopLn) = True isLinkMode DoMake = True isLinkMode DoInteractive = True isLinkMode (DoEval _) = True isLinkMode _ = False isCompManagerMode :: PostLoadMode -> Bool isCompManagerMode DoMake = True isCompManagerMode DoInteractive = True isCompManagerMode (DoEval _) = True isCompManagerMode DoVHDL = True isCompManagerMode DoVerilog = True isCompManagerMode DoSystemVerilog = True isCompManagerMode _ = False parseModeFlags :: [Located String] -> IO (Mode, [Located String], [Warn]) parseModeFlags args = do let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) = runCmdLine (processArgs mode_flags args) (Nothing, [], []) mode = case mModeFlag of Nothing -> doMakeMode Just (m, _) -> m unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $ map (("on the commandline", )) $ map (unLoc . errMsg) errs1 ++ errs2 return (mode, flags' ++ leftover, warns) type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String]) mode flags sometimes give rise to new DynFlags ( eg . -C , see below ) mode_flags :: [Flag ModeM] mode_flags = defFlag "?" (PassFlag (setMode showGhcUsageMode)) , defFlag "-help" (PassFlag (setMode showGhcUsageMode)) , defFlag "V" (PassFlag (setMode showVersionMode)) , defFlag "-version" (PassFlag (setMode showVersionMode)) , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode)) , defFlag "-info" (PassFlag (setMode showInfoMode)) , defFlag "-show-options" (PassFlag (setMode showOptionsMode)) , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-show-packages" (PassFlag (setMode showUnitsMode)) ] ++ [ defFlag k' (PassFlag (setMode (printSetting k))) | k <- ["Project version", "Project Git commit id", "Booter version", "Stage", "Build platform", "Host platform", "Target platform", "Have interpreter", "Object splitting supported", "Have native code generator", "Support SMP", "Unregisterised", "Tables next to code", "RTS ways", "Leading underscore", "Debug on", "LibDir", "Global Package DB", "C compiler flags", "C compiler link flags", "ld flags"], let k' = "-print-" ++ map (replaceSpace . toLower) k replaceSpace ' ' = '-' replaceSpace c = c ] ++ [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f) "--show-iface")) , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f addFlag "-no-link" f)) , defFlag "M" (PassFlag (setMode doMkDependHSMode)) , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc))) , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc))) , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False)))) , defFlag "-make" (PassFlag (setMode doMakeMode)) , defFlag "-backpack" (PassFlag (setMode doBackpackMode)) , defFlag "-interactive" (PassFlag (setMode doInteractiveMode)) , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode)) , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e")) , defFlag "-frontend" (SepArg (\s -> setMode (doFrontendMode s) "-frontend")) , defFlag "-vhdl" (PassFlag (setMode doVHDLMode)) , defFlag "-verilog" (PassFlag (setMode doVerilogMode)) , defFlag "-systemverilog" (PassFlag (setMode doSystemVerilogMode)) ] setMode :: Mode -> String -> EwM ModeM () setMode newMode newFlag = liftEwM $ do (mModeFlag, errs, flags') <- getCmdLineState let (modeFlag', errs') = case mModeFlag of Nothing -> ((newMode, newFlag), errs) Just (oldMode, oldFlag) -> case (oldMode, newMode) of _ | isStopLnMode oldMode && isDoMakeMode newMode || isStopLnMode newMode && isDoMakeMode oldMode -> ((doMakeMode, "--make"), []) _ | isShowGhcUsageMode oldMode && isDoInteractiveMode newMode -> ((showGhciUsageMode, oldFlag), []) | isShowGhcUsageMode newMode && isDoInteractiveMode oldMode -> ((showGhciUsageMode, newFlag), []) _ | isDoEvalMode oldMode && isDoInteractiveMode newMode -> ((oldMode, oldFlag), []) | isDoEvalMode newMode && isDoInteractiveMode oldMode -> ((newMode, newFlag), []) | isDominantFlag oldMode -> ((oldMode, oldFlag), []) | isDominantFlag newMode -> ((newMode, newFlag), []) (Right (Right (DoEval esOld)), Right (Right (DoEval [eNew]))) -> ((Right (Right (DoEval (eNew : esOld))), oldFlag), errs) _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs) (Right (Right DoInteractive), Left (ShowOptions _)) -> ((Left (ShowOptions True), "--interactive --show-options"), errs) (Left (ShowOptions _), (Right (Right DoInteractive))) -> ((Left (ShowOptions True), "--show-options --interactive"), errs) _ -> let err = flagMismatchErr oldFlag newFlag in ((oldMode, oldFlag), err : errs) putCmdLineState (Just modeFlag', errs', flags') where isDominantFlag f = isShowGhcUsageMode f || isShowGhciUsageMode f || isShowVersionMode f || isShowNumVersionMode f flagMismatchErr :: String -> String -> String flagMismatchErr oldFlag newFlag = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'" addFlag :: String -> String -> EwM ModeM () addFlag s flag = liftEwM $ do (m, e, flags') <- getCmdLineState putCmdLineState (m, e, mkGeneralLocated loc s : flags') where loc = "addFlag by " ++ flag ++ " on the commandline" doMake :: [(String,Maybe Phase)] -> Ghc () doMake srcs = do let (hs_srcs, non_hs_srcs) = partition isHaskellishTarget srcs hsc_env <- GHC.getSession analysis , then just do one - shot compilation and/or linking . if (null hs_srcs) then liftIO (oneShot hsc_env StopLn srcs) else do o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x) non_hs_srcs dflags <- GHC.getSessionDynFlags let dflags' = dflags { ldInputs = map (FileOption "") o_files ++ ldInputs dflags } _ <- GHC.setSessionDynFlags dflags' targets <- mapM (uncurry GHC.guessTarget) hs_srcs GHC.setTargets targets ok_flag <- GHC.load LoadAllTargets when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1)) return () doShowIface :: DynFlags -> FilePath -> IO () doShowIface dflags file = do hsc_env <- newHscEnv dflags showIface hsc_env file showBanner :: PostLoadMode -> DynFlags -> IO () showBanner _postLoadMode dflags = do let verb = verbosity dflags #if defined(HAVE_INTERNAL_INTERPRETER) when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg #endif when (verb >= 2) $ do hPutStr stderr "Glasgow Haskell Compiler, Version " hPutStr stderr cProjectVersion hPutStr stderr ", stage " hPutStr stderr cStage hPutStr stderr " booted by GHC version " hPutStrLn stderr cBooterVersion showInfo :: DynFlags -> IO () showInfo dflags = do let sq x = " [" ++ x ++ "\n ]" putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags TODO use GHC.Utils . Error once that is disentangled from all the other GhcMonad stuff ? showSupportedExtensions :: Maybe String -> IO () showSupportedExtensions m_top_dir = do res <- runExceptT $ do top_dir <- lift (tryFindTopDir m_top_dir) >>= \case Nothing -> throwE $ SettingsError_MissingData "Could not find the top directory, missing -B flag" Just dir -> pure dir initSettings top_dir targetPlatformMini <- case res of Right s -> pure $ platformMini $ sTargetPlatform s Left (SettingsError_MissingData msg) -> do hPutStrLn stderr $ "WARNING: " ++ show msg hPutStrLn stderr $ "cannot know target platform so guessing target == host (native compiler)." pure cHostPlatformMini Left (SettingsError_BadData msg) -> do hPutStrLn stderr msg exitWith $ ExitFailure 1 mapM_ putStrLn $ supportedLanguagesAndExtensions targetPlatformMini showVersion :: IO () showVersion = putStrLn $ concat [ "Clash, version " , Data.Version.showVersion Paths_clash_ghc.version , " (using clash-lib, version: " , Data.Version.showVersion clashLibVersion , ")" ] showOptions :: Bool -> IORef ClashOpts -> IO () showOptions isInteractive = putStr . unlines . availableOptions where availableOptions opts = concat [ flagsForCompletion isInteractive, map ('-':) (getFlagNames mode_flags), map ('-':) (getFlagNames (flagsClash opts)) ] getFlagNames opts = map flagName opts showGhcUsage :: DynFlags -> IO () showGhcUsage = showUsage False showGhciUsage :: DynFlags -> IO () showGhciUsage = showUsage True showUsage :: Bool -> DynFlags -> IO () showUsage ghci dflags = do let usage_path = if ghci then ghciUsagePath dflags else ghcUsagePath dflags usage <- readFile usage_path dump usage where dump "" = return () dump ('$':'$':s) = putStr progName >> dump s dump (c:s) = putChar c >> dump s dumpFinalStats :: DynFlags -> IO () dumpFinalStats dflags = when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags dumpFastStringStats :: DynFlags -> IO () dumpFastStringStats dflags = do segments <- getFastStringTable hasZ <- getFastStringZEncCounter let buckets = concat segments bucketsPerSegment = map length segments entriesPerBucket = map length buckets entries = sum entriesPerBucket msg = text "FastString stats:" $$ nest 4 (vcat [ text "segments: " <+> int (length segments) , text "buckets: " <+> int (sum bucketsPerSegment) , text "entries: " <+> int entries , text "largest segment: " <+> int (maximum bucketsPerSegment) , text "smallest segment: " <+> int (minimum bucketsPerSegment) , text "longest bucket: " <+> int (maximum entriesPerBucket) , text "has z-encoding: " <+> (hasZ `pcntOf` entries) ]) putMsg dflags msg where x `pcntOf` y = int ((x * 100) `quot` y) Outputable.<> char '%' showUnits, dumpUnits, dumpUnitsSimple :: DynFlags -> IO () showUnits dflags = putStrLn (showSDoc dflags (pprUnits (unitState dflags))) dumpUnits dflags = putMsg dflags (pprUnits (unitState dflags)) dumpUnitsSimple dflags = putMsg dflags (pprUnitsSimple (unitState dflags)) Frontend plugin support doFrontend :: ModuleName -> [(String, Maybe Phase)] -> Ghc () doFrontend modname srcs = do hsc_env <- getSession frontend_plugin <- liftIO $ loadFrontendPlugin hsc_env modname frontend frontend_plugin (reverse $ frontendPluginOpts (hsc_dflags hsc_env)) srcs ABI hash support Generates a combined hash of the ABI for modules Data . and System . Bar . The modules must already be compiled , and appropriate -i options may be necessary in order to find the .hi files . This is used by Cabal for generating the ComponentId for a package . The ComponentId must change when the visible ABI of to get a hash of the package 's ABI . Generates a combined hash of the ABI for modules Data.Foo and System.Bar. The modules must already be compiled, and appropriate -i options may be necessary in order to find the .hi files. This is used by Cabal for generating the ComponentId for a package. The ComponentId must change when the visible ABI of to get a hash of the package's ABI. -} The resulting hash is the MD5 of the GHC version used ( # 5328 , see ' hiVersion ' ) and of the existing ABI hash from each module ( see -> Ghc () abiHash strs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env liftIO $ do let find_it str = do let modname = mkModuleName str r <- findImportedModule hsc_env modname Nothing case r of Found _ m -> return m _error -> throwGhcException $ CmdLineError $ showSDoc dflags $ cannotFindModule dflags modname r mods <- mapM find_it strs let get_iface modl = loadUserInterface NotBoot (text "abiHash") modl ifaces <- initIfaceCheck (text "abiHash") hsc_env $ mapM get_iface mods put_ bh hiVersion see # 5328 mapM_ (put_ bh . mi_mod_hash . mi_final_exts) ifaces f <- fingerprintBinMem bh putStrLn (showPpr dflags f) makeHDL' :: forall backend . Backend backend => Proxy backend -> Ghc () -> IORef ClashOpts -> [(String,Maybe Phase)] -> Ghc () makeHDL' _ _ _ [] = throwGhcException (CmdLineError "No input files") makeHDL' proxy startAction r srcs = makeHDL proxy startAction r $ fmap fst srcs makeVHDL :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc () makeVHDL = makeHDL' (Proxy @VHDLState) makeVerilog :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc () makeVerilog = makeHDL' (Proxy @VerilogState) makeSystemVerilog :: Ghc () -> IORef ClashOpts -> [(String, Maybe Phase)] -> Ghc () makeSystemVerilog = makeHDL' (Proxy @SystemVerilogState) unknownFlagsErr :: [String] -> a unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs where oneError f = "unrecognised flag: " ++ f ++ "\n" ++ (case match f (nubSort allNonDeprecatedFlags) of [] -> "" suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs)) fixes # 11789 match f allFlags | elem '=' f = let (flagsWithEq, flagsWithoutEq) = partition (elem '=') allFlags fName = takeWhile (/= '=') f in (fuzzyMatch f flagsWithEq) ++ (fuzzyMatch fName flagsWithoutEq) | otherwise = fuzzyMatch f allFlags Note [ -Bsymbolic and hooks ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled ( see ` man ld ` ) . When dynamically linking , we do n't use -Bsymbolic on the RTS package : that is because we want hooks to be overridden by the user , we do n't want to constrain them to the RTS package . Unfortunately this seems to have broken somehow on OS X : as a result , defaultHooks ( in hschooks.c ) is not called , which does not initialize the GC stats . As a result , this breaks things like ` : set + s ` in GHCi ( # 8754 ) . As a hacky workaround , we instead call ' defaultHooks ' directly to initialize the flags in the RTS . A byproduct of this , I believe , is that hooks are likely broken on OS X when dynamically linking . But this probably does n't affect most people since we 're linking GHC dynamically , but most things themselves link statically . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled (see `man ld`). When dynamically linking, we don't use -Bsymbolic on the RTS package: that is because we want hooks to be overridden by the user, we don't want to constrain them to the RTS package. Unfortunately this seems to have broken somehow on OS X: as a result, defaultHooks (in hschooks.c) is not called, which does not initialize the GC stats. As a result, this breaks things like `:set +s` in GHCi (#8754). As a hacky workaround, we instead call 'defaultHooks' directly to initialize the flags in the RTS. A byproduct of this, I believe, is that hooks are likely broken on OS X when dynamically linking. But this probably doesn't affect most people since we're linking GHC dynamically, but most things themselves link statically. -} If GHC_LOADED_INTO_GHCI is not set when GHC is loaded into GHCi , then /tmp / ghc13836_0 / libghc_1872.so : undefined symbol : initGCStatistics #if defined(GHC_LOADED_INTO_GHCI) initGCStatistics :: IO () initGCStatistics = return () #else foreign import ccall safe "initGCStatistics" initGCStatistics :: IO () #endif
add016e885b98196bd80e58c9feb703c4875500719c11298bef1b8b68bbde883
Frama-C/Frama-C-snapshot
split_return.ml
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* 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 . (* *) (* It 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. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Cil_types open Abstract_interp (* Auxiliary module for inference of split criterion. We collect all the usages of a function call, and all places where they are compared against an integral constant *) module ReturnUsage = struct let debug = false module MapLval = Cil_datatype.Lval.Map (* Uses of a given lvalue *) type return_usage_by_lv = { ret_callees: Kernel_function.Hptset.t (* all the functions that put their results in this lvalue *); ret_compared: Datatype.Integer.Set.t (* all the constant values this lvalue is compared against *); } Per - function usage : all interesting are mapped to the way they are used they are used *) and return_usage_per_fun = return_usage_by_lv MapLval.t module RUDatatype = Kernel_function.Map.Make(Datatype.Integer.Set) let find_or_default uf lv = try MapLval.find lv uf with Not_found -> { ret_callees = Kernel_function.Hptset.empty; ret_compared = Datatype.Integer.Set.empty; } (* Treat a [Call] instruction. Immediate calls (no functions pointers) are added to the current usage store *) let add_call (uf: return_usage_per_fun) lv_opt e_fun = match e_fun.enode, lv_opt with | Lval (Var vi, NoOffset), Some lv when Cil.isIntegralOrPointerType (Cil.typeOfLval lv) -> let kf = Globals.Functions.get vi in let u = find_or_default uf lv in let funs = Kernel_function.Hptset.add kf u.ret_callees in let u = { u with ret_callees = funs } in if debug then Format.printf "[Usage] %a returns %a@." Kernel_function.pretty kf Printer.pp_lval lv; MapLval.add lv u uf | _ -> uf (* Treat a [Set] instruction [lv = (cast) lv']. Useful for return codes that are stored inside values of a slightly different type *) let add_alias (uf: return_usage_per_fun) lv_dest e = match e.enode with | CastE (typ, { enode = Lval lve }) when Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lve) -> let u = find_or_default uf lve in MapLval.add lv_dest u uf | _ -> uf (* add a comparison with the integer [i] to the lvalue [lv] *) let add_compare_ct uf i lv = if Cil.isIntegralOrPointerType (Cil.typeOfLval lv) then let u = find_or_default uf lv in let v = Datatype.Integer.Set.add i u.ret_compared in let u = { u with ret_compared = v } in if debug then Format.printf "[Usage] Comparing %a to %a@." Printer.pp_lval lv Int.pretty i; MapLval.add lv u uf else uf (* Treat an expression [lv == ct], [lv != ct] or [!lv], possibly with some cast. [ct] is added to the store of usages. *) let add_compare (uf: return_usage_per_fun) cond = (* if [ct] is an integer constant, memoize it is compared to [lv] *) let add ct lv = (match Cil.constFoldToInt ct with | Some i -> add_compare_ct uf i lv | _ -> uf) in (match cond.enode with | BinOp ((Eq | Ne), {enode = Lval lv}, ct, _) | BinOp ((Eq | Ne), ct, {enode = Lval lv}, _) -> add ct lv | BinOp ((Eq | Ne), {enode = CastE (typ, {enode = Lval lv})}, ct, _) | BinOp ((Eq | Ne), ct, {enode = CastE (typ, {enode = Lval lv})}, _) -> if Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lv) then add ct lv else uf | UnOp (LNot, {enode = Lval lv}, _) -> add_compare_ct uf Int.zero lv | UnOp (LNot, {enode = CastE (typ, {enode = Lval lv})}, _) when Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lv) -> add_compare_ct uf Int.zero lv | _ -> uf) Treat an expression [ v ] or [ e1 & & e2 ] or [ e1 || e2 ] . This expression is supposed to be just inside an [ if ( ... ) ] , so that we may recognize patterns such as [ if ( f ( ) & & g ( ) ) ] . Patterns such as [ if ( f ( ) = = 1 & & ! ( ) ) ] are handled in another way : the visitor recognizes comparison operators and [ ! ] , and calls { ! } . supposed to be just inside an [if(...)], so that we may recognize patterns such as [if (f() && g())]. Patterns such as [if (f() == 1 && !g())] are handled in another way: the visitor recognizes comparison operators and [!], and calls {!add_compare}. *) let rec add_direct_comparison uf e = match e.enode with | Lval lv -> add_compare_ct uf Int.zero lv | CastE (typ, {enode = Lval lv}) when Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lv) -> add_compare_ct uf Int.zero lv | BinOp ((LAnd | LOr), e1, e2, _) -> add_direct_comparison (add_direct_comparison uf e1) e2 | _ -> uf (* Per-program split strategy. Functions are mapped to the values their return code should be split against. *) type return_split = Datatype.Integer.Set.t Kernel_function.Map.t (* add to [kf] hints to split on all integers in [s]. *) let add_split kf s (ru:return_split) : return_split = let cur = try Kernel_function.Map.find kf ru with Not_found -> Datatype.Integer.Set.empty in let s = Datatype.Integer.Set.union cur s in Kernel_function.Map.add kf s ru (* Extract global usage: map functions to integers their return values are tested against *) let summarize_by_lv (uf: return_usage_per_fun): return_split = let aux _lv u acc = if Datatype.Integer.Set.is_empty u.ret_compared then acc else let aux_kf kf ru = add_split kf u.ret_compared ru in Kernel_function.Hptset.fold aux_kf u.ret_callees acc in MapLval.fold aux uf Kernel_function.Map.empty class visitorVarUsage = object inherit Visitor.frama_c_inplace val mutable usage = MapLval.empty method! vinst i = (match i with | Set (lv, e, _) -> usage <- add_alias usage lv e | Call (lv_opt, e, _, _) -> usage <- add_call usage lv_opt e | Local_init(v, AssignInit i, _) -> let rec aux lv i = match i with | SingleInit e -> usage <- add_alias usage lv e | CompoundInit (_, l) -> List.iter (fun (o,i) -> aux (Cil.addOffsetLval o lv) i) l in aux (Cil.var v) i | Local_init(v, ConsInit(f,_,Plain_func), _) -> usage <- add_call usage (Some (Cil.var v)) (Cil.evar f) | Local_init(_, ConsInit _,_) -> () (* not a real assignment. *) | Asm _ | Skip _ | Code_annot _ -> () ); Cil.DoChildren method! vstmt_aux s = (match s.skind with | If (e, _, _, _) | Switch (e, _, _, _) -> usage <- add_direct_comparison usage e | _ -> () ); Cil.DoChildren method! vexpr e = usage <- add_compare usage e; Cil.DoChildren method result () = summarize_by_lv usage end (* For functions returning pointers, add a split on NULL/non-NULL *) let add_null_pointers_split (ru: return_split): return_split = let null_set = Datatype.Integer.Set.singleton Integer.zero in let aux kf acc = if Cil.isPointerType (Kernel_function.get_return_type kf) then add_split kf null_set acc else acc in Globals.Functions.fold aux ru let compute file = let vis = new visitorVarUsage in Visitor.visitFramacFileSameGlobals (vis:> Visitor.frama_c_visitor) file; let split_compared = vis#result () in let split_null_pointers = add_null_pointers_split split_compared in split_null_pointers end module AutoStrategy = State_builder.Option_ref (ReturnUsage.RUDatatype) (struct let name = "Value.Split_return.Autostrategy" let dependencies = [Ast.self] end) let () = Ast.add_monotonic_state AutoStrategy.self let compute_auto () = if AutoStrategy.is_computed () then AutoStrategy.get () else begin let s = ReturnUsage.compute (Ast.get ()) in AutoStrategy.set s; AutoStrategy.mark_as_computed (); s end (* Auto-strategy for one given function *) let find_auto_strategy kf = try let s = Kernel_function.Map.find kf (compute_auto ()) in Split_strategy.SplitEqList (Datatype.Integer.Set.elements s) with Not_found -> Split_strategy.NoSplit module KfStrategy = Kernel_function.Make_Table(Split_strategy) (struct let size = 17 let dependencies = [Value_parameters.SplitReturnFunction.self; Value_parameters.SplitGlobalStrategy.self; AutoStrategy.self] let name = "Value.Split_return.Kfstrategy" end) (* Invariant: this function never returns Split_strategy.SplitAuto *) let kf_strategy = KfStrategy.memo (fun kf -> try (* User strategies take precedence *) match Value_parameters.SplitReturnFunction.find kf with | Split_strategy.SplitAuto -> find_auto_strategy kf | s -> s with Not_found -> match Value_parameters.SplitGlobalStrategy.get () with | Split_strategy.SplitAuto -> find_auto_strategy kf | s -> s ) let pretty_strategies fmt = Format.fprintf fmt "@[<v>"; let open Split_strategy in let pp_list = Pretty_utils.pp_list ~sep:",@ " Int.pretty in let pp_one user_auto pp = function | NoSplit -> () | FullSplit -> Format.fprintf fmt "@[\\full_split(%t)@]@ " pp | SplitEqList l -> Format.fprintf fmt "@[\\return(%t) == %a (%s)@]@ " pp pp_list l user_auto should have been replaced by SplitEqList in let pp_kf kf fmt = Kernel_function.pretty fmt kf in let pp_user (kf, strategy) = match strategy with | None -> () | Some SplitAuto -> pp_one "auto" (pp_kf kf) (kf_strategy kf) | Some s -> pp_one "user" (pp_kf kf) s in Value_parameters.SplitReturnFunction.iter pp_user; if not (Value_parameters.SplitReturnFunction.is_empty ()) && match Value_parameters.SplitGlobalStrategy.get () with | Split_strategy.NoSplit | Split_strategy.SplitAuto -> false | _ -> true then Format.fprintf fmt "@[other functions:@]@ "; begin match Value_parameters.SplitGlobalStrategy.get () with | SplitAuto -> let pp_auto kf s = if not (Value_parameters.SplitReturnFunction.mem kf) then let s = SplitEqList (Datatype.Integer.Set.elements s) in pp_one "auto" (pp_kf kf) s in let auto = compute_auto () in Kernel_function.Map.iter pp_auto auto; | s -> pp_one "auto" (fun fmt -> Format.pp_print_string fmt "@all") s end; Format.fprintf fmt "@]" let pretty_strategies () = if not (Value_parameters.SplitReturnFunction.is_empty ()) || (Value_parameters.SplitGlobalStrategy.get () != Split_strategy.NoSplit) then Value_parameters.result "Splitting return states on:@.%t" pretty_strategies (* Local Variables: compile-command: "make -C ../../../.." End: *)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/partitioning/split_return.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It 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. ************************************************************************ Auxiliary module for inference of split criterion. We collect all the usages of a function call, and all places where they are compared against an integral constant Uses of a given lvalue all the functions that put their results in this lvalue all the constant values this lvalue is compared against Treat a [Call] instruction. Immediate calls (no functions pointers) are added to the current usage store Treat a [Set] instruction [lv = (cast) lv']. Useful for return codes that are stored inside values of a slightly different type add a comparison with the integer [i] to the lvalue [lv] Treat an expression [lv == ct], [lv != ct] or [!lv], possibly with some cast. [ct] is added to the store of usages. if [ct] is an integer constant, memoize it is compared to [lv] Per-program split strategy. Functions are mapped to the values their return code should be split against. add to [kf] hints to split on all integers in [s]. Extract global usage: map functions to integers their return values are tested against not a real assignment. For functions returning pointers, add a split on NULL/non-NULL Auto-strategy for one given function Invariant: this function never returns Split_strategy.SplitAuto User strategies take precedence Local Variables: compile-command: "make -C ../../../.." End:
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types open Abstract_interp module ReturnUsage = struct let debug = false module MapLval = Cil_datatype.Lval.Map type return_usage_by_lv = { } Per - function usage : all interesting are mapped to the way they are used they are used *) and return_usage_per_fun = return_usage_by_lv MapLval.t module RUDatatype = Kernel_function.Map.Make(Datatype.Integer.Set) let find_or_default uf lv = try MapLval.find lv uf with Not_found -> { ret_callees = Kernel_function.Hptset.empty; ret_compared = Datatype.Integer.Set.empty; } let add_call (uf: return_usage_per_fun) lv_opt e_fun = match e_fun.enode, lv_opt with | Lval (Var vi, NoOffset), Some lv when Cil.isIntegralOrPointerType (Cil.typeOfLval lv) -> let kf = Globals.Functions.get vi in let u = find_or_default uf lv in let funs = Kernel_function.Hptset.add kf u.ret_callees in let u = { u with ret_callees = funs } in if debug then Format.printf "[Usage] %a returns %a@." Kernel_function.pretty kf Printer.pp_lval lv; MapLval.add lv u uf | _ -> uf let add_alias (uf: return_usage_per_fun) lv_dest e = match e.enode with | CastE (typ, { enode = Lval lve }) when Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lve) -> let u = find_or_default uf lve in MapLval.add lv_dest u uf | _ -> uf let add_compare_ct uf i lv = if Cil.isIntegralOrPointerType (Cil.typeOfLval lv) then let u = find_or_default uf lv in let v = Datatype.Integer.Set.add i u.ret_compared in let u = { u with ret_compared = v } in if debug then Format.printf "[Usage] Comparing %a to %a@." Printer.pp_lval lv Int.pretty i; MapLval.add lv u uf else uf let add_compare (uf: return_usage_per_fun) cond = let add ct lv = (match Cil.constFoldToInt ct with | Some i -> add_compare_ct uf i lv | _ -> uf) in (match cond.enode with | BinOp ((Eq | Ne), {enode = Lval lv}, ct, _) | BinOp ((Eq | Ne), ct, {enode = Lval lv}, _) -> add ct lv | BinOp ((Eq | Ne), {enode = CastE (typ, {enode = Lval lv})}, ct, _) | BinOp ((Eq | Ne), ct, {enode = CastE (typ, {enode = Lval lv})}, _) -> if Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lv) then add ct lv else uf | UnOp (LNot, {enode = Lval lv}, _) -> add_compare_ct uf Int.zero lv | UnOp (LNot, {enode = CastE (typ, {enode = Lval lv})}, _) when Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lv) -> add_compare_ct uf Int.zero lv | _ -> uf) Treat an expression [ v ] or [ e1 & & e2 ] or [ e1 || e2 ] . This expression is supposed to be just inside an [ if ( ... ) ] , so that we may recognize patterns such as [ if ( f ( ) & & g ( ) ) ] . Patterns such as [ if ( f ( ) = = 1 & & ! ( ) ) ] are handled in another way : the visitor recognizes comparison operators and [ ! ] , and calls { ! } . supposed to be just inside an [if(...)], so that we may recognize patterns such as [if (f() && g())]. Patterns such as [if (f() == 1 && !g())] are handled in another way: the visitor recognizes comparison operators and [!], and calls {!add_compare}. *) let rec add_direct_comparison uf e = match e.enode with | Lval lv -> add_compare_ct uf Int.zero lv | CastE (typ, {enode = Lval lv}) when Cil.isIntegralOrPointerType typ && Cil.isIntegralOrPointerType (Cil.typeOfLval lv) -> add_compare_ct uf Int.zero lv | BinOp ((LAnd | LOr), e1, e2, _) -> add_direct_comparison (add_direct_comparison uf e1) e2 | _ -> uf type return_split = Datatype.Integer.Set.t Kernel_function.Map.t let add_split kf s (ru:return_split) : return_split = let cur = try Kernel_function.Map.find kf ru with Not_found -> Datatype.Integer.Set.empty in let s = Datatype.Integer.Set.union cur s in Kernel_function.Map.add kf s ru let summarize_by_lv (uf: return_usage_per_fun): return_split = let aux _lv u acc = if Datatype.Integer.Set.is_empty u.ret_compared then acc else let aux_kf kf ru = add_split kf u.ret_compared ru in Kernel_function.Hptset.fold aux_kf u.ret_callees acc in MapLval.fold aux uf Kernel_function.Map.empty class visitorVarUsage = object inherit Visitor.frama_c_inplace val mutable usage = MapLval.empty method! vinst i = (match i with | Set (lv, e, _) -> usage <- add_alias usage lv e | Call (lv_opt, e, _, _) -> usage <- add_call usage lv_opt e | Local_init(v, AssignInit i, _) -> let rec aux lv i = match i with | SingleInit e -> usage <- add_alias usage lv e | CompoundInit (_, l) -> List.iter (fun (o,i) -> aux (Cil.addOffsetLval o lv) i) l in aux (Cil.var v) i | Local_init(v, ConsInit(f,_,Plain_func), _) -> usage <- add_call usage (Some (Cil.var v)) (Cil.evar f) | Asm _ | Skip _ | Code_annot _ -> () ); Cil.DoChildren method! vstmt_aux s = (match s.skind with | If (e, _, _, _) | Switch (e, _, _, _) -> usage <- add_direct_comparison usage e | _ -> () ); Cil.DoChildren method! vexpr e = usage <- add_compare usage e; Cil.DoChildren method result () = summarize_by_lv usage end let add_null_pointers_split (ru: return_split): return_split = let null_set = Datatype.Integer.Set.singleton Integer.zero in let aux kf acc = if Cil.isPointerType (Kernel_function.get_return_type kf) then add_split kf null_set acc else acc in Globals.Functions.fold aux ru let compute file = let vis = new visitorVarUsage in Visitor.visitFramacFileSameGlobals (vis:> Visitor.frama_c_visitor) file; let split_compared = vis#result () in let split_null_pointers = add_null_pointers_split split_compared in split_null_pointers end module AutoStrategy = State_builder.Option_ref (ReturnUsage.RUDatatype) (struct let name = "Value.Split_return.Autostrategy" let dependencies = [Ast.self] end) let () = Ast.add_monotonic_state AutoStrategy.self let compute_auto () = if AutoStrategy.is_computed () then AutoStrategy.get () else begin let s = ReturnUsage.compute (Ast.get ()) in AutoStrategy.set s; AutoStrategy.mark_as_computed (); s end let find_auto_strategy kf = try let s = Kernel_function.Map.find kf (compute_auto ()) in Split_strategy.SplitEqList (Datatype.Integer.Set.elements s) with Not_found -> Split_strategy.NoSplit module KfStrategy = Kernel_function.Make_Table(Split_strategy) (struct let size = 17 let dependencies = [Value_parameters.SplitReturnFunction.self; Value_parameters.SplitGlobalStrategy.self; AutoStrategy.self] let name = "Value.Split_return.Kfstrategy" end) let kf_strategy = KfStrategy.memo (fun kf -> match Value_parameters.SplitReturnFunction.find kf with | Split_strategy.SplitAuto -> find_auto_strategy kf | s -> s with Not_found -> match Value_parameters.SplitGlobalStrategy.get () with | Split_strategy.SplitAuto -> find_auto_strategy kf | s -> s ) let pretty_strategies fmt = Format.fprintf fmt "@[<v>"; let open Split_strategy in let pp_list = Pretty_utils.pp_list ~sep:",@ " Int.pretty in let pp_one user_auto pp = function | NoSplit -> () | FullSplit -> Format.fprintf fmt "@[\\full_split(%t)@]@ " pp | SplitEqList l -> Format.fprintf fmt "@[\\return(%t) == %a (%s)@]@ " pp pp_list l user_auto should have been replaced by SplitEqList in let pp_kf kf fmt = Kernel_function.pretty fmt kf in let pp_user (kf, strategy) = match strategy with | None -> () | Some SplitAuto -> pp_one "auto" (pp_kf kf) (kf_strategy kf) | Some s -> pp_one "user" (pp_kf kf) s in Value_parameters.SplitReturnFunction.iter pp_user; if not (Value_parameters.SplitReturnFunction.is_empty ()) && match Value_parameters.SplitGlobalStrategy.get () with | Split_strategy.NoSplit | Split_strategy.SplitAuto -> false | _ -> true then Format.fprintf fmt "@[other functions:@]@ "; begin match Value_parameters.SplitGlobalStrategy.get () with | SplitAuto -> let pp_auto kf s = if not (Value_parameters.SplitReturnFunction.mem kf) then let s = SplitEqList (Datatype.Integer.Set.elements s) in pp_one "auto" (pp_kf kf) s in let auto = compute_auto () in Kernel_function.Map.iter pp_auto auto; | s -> pp_one "auto" (fun fmt -> Format.pp_print_string fmt "@all") s end; Format.fprintf fmt "@]" let pretty_strategies () = if not (Value_parameters.SplitReturnFunction.is_empty ()) || (Value_parameters.SplitGlobalStrategy.get () != Split_strategy.NoSplit) then Value_parameters.result "Splitting return states on:@.%t" pretty_strategies
5c21b1e7b243dab54150e693ec01c37534be816d5bf00c385f2bc75c33d899bc
boris-ci/boris
Configuration.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE PackageImports #-} module Boris.Core.Data.Configuration ( Command (..) , BuildPattern (..) , Specification (..) , BuildNamePattern , renderBuildNamePattern , parseBuildNamePattern , matchesBuild ) where import Boris.Core.Data.Build import Boris.Prelude import qualified Data.Text as Text import qualified "Glob" System.FilePath.Glob as Glob data Command = Command { commandName :: Text , commandArgs :: [Text] } deriving (Eq, Show) data Specification = Specification { specificationBuild :: BuildName , specificationPre :: [Command] , specificationCommand :: [Command] , specificationPost :: [Command] , specificationSuccess :: [Command] , specificationFailure :: [Command] } deriving (Eq, Show) data BuildPattern = BuildPattern { buildNamePattern :: BuildNamePattern , buildPattern :: Pattern } deriving (Eq, Show) newtype BuildNamePattern = BuildNamePattern { _getBuildNamePattern :: Glob.Pattern } deriving (Eq, Show) renderBuildNamePattern :: BuildNamePattern -> Text renderBuildNamePattern (BuildNamePattern g) = Text.pack . Glob.decompile $ g parseBuildNamePattern :: Text -> Either Text BuildNamePattern parseBuildNamePattern = let options = Glob.CompOptions { Glob.characterClasses = False , Glob.characterRanges = False , Glob.numberRanges = False , Glob.wildcards = True , Glob.recursiveWildcards = False , Glob.pathSepInRanges = False , Glob.errorRecovery = False } in bimap Text.pack BuildNamePattern . Glob.tryCompileWith options . Text.unpack matchesBuild :: BuildNamePattern -> BuildName -> Bool matchesBuild (BuildNamePattern glob) build = Glob.match glob (Text.unpack $ renderBuildName build)
null
https://raw.githubusercontent.com/boris-ci/boris/c321187490afc889bf281442ac4ef9398b77b200/boris-core/src/Boris/Core/Data/Configuration.hs
haskell
# LANGUAGE PackageImports #
# LANGUAGE NoImplicitPrelude # module Boris.Core.Data.Configuration ( Command (..) , BuildPattern (..) , Specification (..) , BuildNamePattern , renderBuildNamePattern , parseBuildNamePattern , matchesBuild ) where import Boris.Core.Data.Build import Boris.Prelude import qualified Data.Text as Text import qualified "Glob" System.FilePath.Glob as Glob data Command = Command { commandName :: Text , commandArgs :: [Text] } deriving (Eq, Show) data Specification = Specification { specificationBuild :: BuildName , specificationPre :: [Command] , specificationCommand :: [Command] , specificationPost :: [Command] , specificationSuccess :: [Command] , specificationFailure :: [Command] } deriving (Eq, Show) data BuildPattern = BuildPattern { buildNamePattern :: BuildNamePattern , buildPattern :: Pattern } deriving (Eq, Show) newtype BuildNamePattern = BuildNamePattern { _getBuildNamePattern :: Glob.Pattern } deriving (Eq, Show) renderBuildNamePattern :: BuildNamePattern -> Text renderBuildNamePattern (BuildNamePattern g) = Text.pack . Glob.decompile $ g parseBuildNamePattern :: Text -> Either Text BuildNamePattern parseBuildNamePattern = let options = Glob.CompOptions { Glob.characterClasses = False , Glob.characterRanges = False , Glob.numberRanges = False , Glob.wildcards = True , Glob.recursiveWildcards = False , Glob.pathSepInRanges = False , Glob.errorRecovery = False } in bimap Text.pack BuildNamePattern . Glob.tryCompileWith options . Text.unpack matchesBuild :: BuildNamePattern -> BuildName -> Bool matchesBuild (BuildNamePattern glob) build = Glob.match glob (Text.unpack $ renderBuildName build)
c1aaf1156203fee27031052657bab273c618720924a4b1492389971474f65a9f
marick/fp-oo
monad.clj
(domonad maybe-m [a (+ 1 2) b nil c (+ a b)] c) (def oops! (fn [reason & args] (with-meta (merge {:reason reason} (apply hash-map args)) {:type :error}))) (def oopsie? (fn [value] (= (type value) :error))) (defmonad error-m [m-result identity m-bind (fn [value continue] (if (= (type value) :error) value (continue value))) ]) (def factorial (fn [n] (cond (< n 0) (oops! "Factorial can never be less than zero." :number n) (< n 2) 1 :else (* n (factorial (dec n)))))) (domonad error-m [a -1 b (factorial a) c (factorial (- a))] (* a b c)) (domonad error-m [step1-value (+ 1 2) step2-value (* step1-value 3) step3-value (+ step2-value 4)] step3-value) (defn make [computation with value] (computation value)) (def step3-value (fn [step2-value] (* step2-value 6))) (def step2-value (fn [step1-value] (+ 1 step1-value))) (def step1-value (fn [] (+ 1 2))) (step1-value) (step2-value (step1-value)) (step3-value (step2-value (step1-value))) (+ (* (+ 1 2) 3) 4) (-> (+ 1 2) (fn [step1-value] (+ (* step1-value 3) 4))) (-> (+ 1 2) (fn [step1-value] (-> (* step1-value 3) (fn [step2-value] (+ step2-value 4))))) (let [step1-value (+ 1 2) step2-value (* step1-value 3)] (+ step2-value 4)) step3-value (+ step2-value 4)] step3-value) (-> (+ 1 2) (fn [step1-value] (-> (* step1-value 3) (fn [step2-value] (-> (+ step2-value step1-value) (fn [step3-value] (* step2-value step3-value))))))) (let [step1-value (+ 1 2) step2-value (* step1-value 3)] (def use-value-to-decide-what-to-do (fn [value continuation] (if (= :error (type value)) value (continuation value)))) (def use-value-to-decide-what-to-do (fn [value continuation] (continuation value))) (def use-value-to-decide-what-to-do (fn [value continuation] (if (nil? value) nil (continuation value)))) (-> (function-that-returns-nil) (fn [step1-value] (+ step1-value 3))) (-> (function-that-returns-nil) (use-value-to-decide-what-to-do (fn [step1-value] (+ step1-value 3)))) (-> (+ 1 2) (use-value-to-decide-what-to-do (fn [step1-value] (-> (* step1-value 3) (use-value-to-decide-what-to-do (fn [step2-value] (+ step2-value step1-value))))))) (defmonad error-m [m-result identity m-bind (fn [value continuation] (if (= (type value) :error) value (continuation value))) ]) (defmonad error-m [m-result identity m-bind (fn [value continue] (if (= (type value) :error) value (continue value))) ]) ;;;; (domonad sequence-m [a [1 2 3] b [-1 1]] (* a b)) (def use-value-to-decide-what-to-do (fn [value continuation] (map continuation value))) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (* a b))))))) (def patch-final-result (fn [result] (apply concat result))) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (-> [8 9] (use-value-to-decide-what-to-do (fn [c] (* a b c)))))))))) (def patch-innermost-result list) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (-> [8 9] (use-value-to-decide-what-to-do (fn [c] (patch-innermost-result (* a b c))))))))))) (domonad multiple-nesting-m [a [1 2 3] b [-1 1] c [8 9]] (* a b c)) (for [a [1 2 3] b [-1 1] c [8 9]] (* a b c)) (defmonad nested-loop-m [m-result list m-bind (fn [value continuation] (apply concat (map continuation value)))]) (domonad nested-loop-m [a [1 2 3] b [-1 1]] (* a b)) ;;;;;; (defmonad work-with-wrapped-ints-m [m-result list m-bind (fn [value continue] (continue (first value)))]) (def inc-and-wrap (comp list inc)) (def double-and-wrap (comp list (partial * 2))) (domonad work-with-wrapped-ints-m [a (list 1) b (double-and-wrap a) c (inc-and-wrap b)] c) (def tolerant-inc (fn [n] (if (nil? n) 1 (inc n)))) (def nil-patch (fn [function replacement] (fn [original] (if (nil? original) (function replacement) (function original))))) (def nil-patch (fn [function replacement] (fn [original] (function (or original replacement))))) (when-let (domonad maybe-m [step1-value (function-that-might-produce-nil 1) step2-value (* (inc step1-value) 3)] (dec step2-value)) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (-> [8 9] (use-value-to-decide-what-to-do (fn [c] (* a b c)))))))))) (domonad sequence-m [a [1 2 3] b [-1 1] c [8 8]] (* a b c)) ;;;; The monad laws, by example (defn monad-law-1 [raw-value] (println (use-value-to-decide-what-to-do (patch-innermost-result raw-value) identity)) (println (identity raw-value))) (use-value-to-decide-what-to-do (patch-innermost-result 1) patch-innermost-result) (patch-innermost-result 1) (use-value-to-decide-what-to-do (use-value-to-decide-what-to-do (patch-innermost-result 1) inc) (partial + 2)) (use-value-to-decide-what-to-do (patch-innermost-result 1) (fn [x] (use-value-to-decide-what-to-do (inc x) (partial + 2)))) ;;; definitions for the sequence monad (def patch-innermost-result list) (def use-value-to-decide-what-to-do (fn [value continuation] (apply concat (map continuation value)))) (def patch-innermost-result (fn [result] (fn [] result))) (def use-value-to-decide-what-to-do (fn [value continuation] (continuation (value))) ) (defmonad functional-m [m-result (fn [value] value) m-bind (fn [value continuation] (fn [value] (value)))]) (domonad nested-loop-m [a [1 2 3] b [-1 1]] (* a b))
null
https://raw.githubusercontent.com/marick/fp-oo/434937826d794d6fe02b3e9a62cf5b4fbc314412/old-code/monad.clj
clojure
The monad laws, by example definitions for the sequence monad
(domonad maybe-m [a (+ 1 2) b nil c (+ a b)] c) (def oops! (fn [reason & args] (with-meta (merge {:reason reason} (apply hash-map args)) {:type :error}))) (def oopsie? (fn [value] (= (type value) :error))) (defmonad error-m [m-result identity m-bind (fn [value continue] (if (= (type value) :error) value (continue value))) ]) (def factorial (fn [n] (cond (< n 0) (oops! "Factorial can never be less than zero." :number n) (< n 2) 1 :else (* n (factorial (dec n)))))) (domonad error-m [a -1 b (factorial a) c (factorial (- a))] (* a b c)) (domonad error-m [step1-value (+ 1 2) step2-value (* step1-value 3) step3-value (+ step2-value 4)] step3-value) (defn make [computation with value] (computation value)) (def step3-value (fn [step2-value] (* step2-value 6))) (def step2-value (fn [step1-value] (+ 1 step1-value))) (def step1-value (fn [] (+ 1 2))) (step1-value) (step2-value (step1-value)) (step3-value (step2-value (step1-value))) (+ (* (+ 1 2) 3) 4) (-> (+ 1 2) (fn [step1-value] (+ (* step1-value 3) 4))) (-> (+ 1 2) (fn [step1-value] (-> (* step1-value 3) (fn [step2-value] (+ step2-value 4))))) (let [step1-value (+ 1 2) step2-value (* step1-value 3)] (+ step2-value 4)) step3-value (+ step2-value 4)] step3-value) (-> (+ 1 2) (fn [step1-value] (-> (* step1-value 3) (fn [step2-value] (-> (+ step2-value step1-value) (fn [step3-value] (* step2-value step3-value))))))) (let [step1-value (+ 1 2) step2-value (* step1-value 3)] (def use-value-to-decide-what-to-do (fn [value continuation] (if (= :error (type value)) value (continuation value)))) (def use-value-to-decide-what-to-do (fn [value continuation] (continuation value))) (def use-value-to-decide-what-to-do (fn [value continuation] (if (nil? value) nil (continuation value)))) (-> (function-that-returns-nil) (fn [step1-value] (+ step1-value 3))) (-> (function-that-returns-nil) (use-value-to-decide-what-to-do (fn [step1-value] (+ step1-value 3)))) (-> (+ 1 2) (use-value-to-decide-what-to-do (fn [step1-value] (-> (* step1-value 3) (use-value-to-decide-what-to-do (fn [step2-value] (+ step2-value step1-value))))))) (defmonad error-m [m-result identity m-bind (fn [value continuation] (if (= (type value) :error) value (continuation value))) ]) (defmonad error-m [m-result identity m-bind (fn [value continue] (if (= (type value) :error) value (continue value))) ]) (domonad sequence-m [a [1 2 3] b [-1 1]] (* a b)) (def use-value-to-decide-what-to-do (fn [value continuation] (map continuation value))) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (* a b))))))) (def patch-final-result (fn [result] (apply concat result))) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (-> [8 9] (use-value-to-decide-what-to-do (fn [c] (* a b c)))))))))) (def patch-innermost-result list) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (-> [8 9] (use-value-to-decide-what-to-do (fn [c] (patch-innermost-result (* a b c))))))))))) (domonad multiple-nesting-m [a [1 2 3] b [-1 1] c [8 9]] (* a b c)) (for [a [1 2 3] b [-1 1] c [8 9]] (* a b c)) (defmonad nested-loop-m [m-result list m-bind (fn [value continuation] (apply concat (map continuation value)))]) (domonad nested-loop-m [a [1 2 3] b [-1 1]] (* a b)) (defmonad work-with-wrapped-ints-m [m-result list m-bind (fn [value continue] (continue (first value)))]) (def inc-and-wrap (comp list inc)) (def double-and-wrap (comp list (partial * 2))) (domonad work-with-wrapped-ints-m [a (list 1) b (double-and-wrap a) c (inc-and-wrap b)] c) (def tolerant-inc (fn [n] (if (nil? n) 1 (inc n)))) (def nil-patch (fn [function replacement] (fn [original] (if (nil? original) (function replacement) (function original))))) (def nil-patch (fn [function replacement] (fn [original] (function (or original replacement))))) (when-let (domonad maybe-m [step1-value (function-that-might-produce-nil 1) step2-value (* (inc step1-value) 3)] (dec step2-value)) (-> [1 2 3] (use-value-to-decide-what-to-do (fn [a] (-> [-1 1] (use-value-to-decide-what-to-do (fn [b] (-> [8 9] (use-value-to-decide-what-to-do (fn [c] (* a b c)))))))))) (domonad sequence-m [a [1 2 3] b [-1 1] c [8 8]] (* a b c)) (defn monad-law-1 [raw-value] (println (use-value-to-decide-what-to-do (patch-innermost-result raw-value) identity)) (println (identity raw-value))) (use-value-to-decide-what-to-do (patch-innermost-result 1) patch-innermost-result) (patch-innermost-result 1) (use-value-to-decide-what-to-do (use-value-to-decide-what-to-do (patch-innermost-result 1) inc) (partial + 2)) (use-value-to-decide-what-to-do (patch-innermost-result 1) (fn [x] (use-value-to-decide-what-to-do (inc x) (partial + 2)))) (def patch-innermost-result list) (def use-value-to-decide-what-to-do (fn [value continuation] (apply concat (map continuation value)))) (def patch-innermost-result (fn [result] (fn [] result))) (def use-value-to-decide-what-to-do (fn [value continuation] (continuation (value))) ) (defmonad functional-m [m-result (fn [value] value) m-bind (fn [value continuation] (fn [value] (value)))]) (domonad nested-loop-m [a [1 2 3] b [-1 1]] (* a b))
e8f392ecfc4ab05130e27c03371337113dafef23ad5b5268706563a9366198e0
geneweb/geneweb
cousins.mli
open Gwdb open Config val default_max_cnt : int (** Default number of relatives that could be listed at the same page *) val max_cousin_level : config -> base -> person -> int val children_of_fam : base -> ifam -> iper list * Retruns list of children of the giving family val siblings : config -> base -> iper -> (iper * (iper * Def.sex)) list * Returns list of person 's siblings that includes also half - blood siblings . Every sibling is annotated with parent 's i d and parent 's sex . For common father 's and mother 's children father 's annotation is preserved . is annotated with parent's id and parent's sex. For common father's and mother's children father's annotation is preserved. *) val has_desc_lev : config -> base -> int -> person -> bool * [ has_desc_lev conf base lev p ] tells if person [ p ] has descendants at the level [ lev ] . [ lev ] 2 represents his children , 3 represents grandchildren , etc . [lev] 2 represents his children, 3 represents grandchildren, etc. *) val br_inter_is_empty : ('a * 'b) list -> ('a * 'c) list -> bool * Tells if two family branches do n't itersect val sibling_has_desc_lev : config -> base -> int -> iper * 'a -> bool (** Same as [has_desc_lev] but used for a person's sibling as returned by [siblings]. *)
null
https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/cousins.mli
ocaml
* Default number of relatives that could be listed at the same page * Same as [has_desc_lev] but used for a person's sibling as returned by [siblings].
open Gwdb open Config val default_max_cnt : int val max_cousin_level : config -> base -> person -> int val children_of_fam : base -> ifam -> iper list * Retruns list of children of the giving family val siblings : config -> base -> iper -> (iper * (iper * Def.sex)) list * Returns list of person 's siblings that includes also half - blood siblings . Every sibling is annotated with parent 's i d and parent 's sex . For common father 's and mother 's children father 's annotation is preserved . is annotated with parent's id and parent's sex. For common father's and mother's children father's annotation is preserved. *) val has_desc_lev : config -> base -> int -> person -> bool * [ has_desc_lev conf base lev p ] tells if person [ p ] has descendants at the level [ lev ] . [ lev ] 2 represents his children , 3 represents grandchildren , etc . [lev] 2 represents his children, 3 represents grandchildren, etc. *) val br_inter_is_empty : ('a * 'b) list -> ('a * 'c) list -> bool * Tells if two family branches do n't itersect val sibling_has_desc_lev : config -> base -> int -> iper * 'a -> bool
49f7d9ed72f46949dda26a9296633363c130fedbf55f86e41e870b46e6da054a
Octachron/codept
deps.ml
module Edge = struct type t = Normal | Epsilon let max x y = if x = Epsilon then x else y let min x y = if x = Normal then x else y let sch = let open Schematic in custom (Sum["Normal", Void; "Epsilon", Void ]) (function Normal -> C E | Epsilon -> C (S E)) (function C E -> Normal | C S E -> Epsilon | _ -> . ) let pp ppf = function | Normal -> Pp.fp ppf "N" | Epsilon -> Pp.fp ppf "ε" end module S = Namespaced.Set type dep = { path: Namespaced.t; edge:Edge.t; pkg:Pkg.t; aliases:S.t} type subdep = { edge:Edge.t; pkg:Pkg.t; aliases:S.t } module Map = Namespaced.Map type t = subdep Map.t let sch: t Schematic.t = let module T = Schematic.Tuple in let from_list = let open T in List.fold_left (fun m [k; edge; pkg; aliases] -> Map.add k {edge;pkg;aliases} m) Map.empty in let to_list m = Map.fold (fun k {edge;pkg;aliases} l -> T.[k;edge;pkg;aliases] :: l) m [] in let open Schematic in custom (Array [Namespaced.sch; Edge.sch; Pkg.sch; S.sch]) to_list from_list module Pth = Paths.S module P = Pkg let empty = Map.empty let update ~path ?(aliases=S.empty) ~edge pkg deps: t = let ep = let update x = let aliases = S.union aliases x.aliases in { x with edge = Edge.max edge x.edge; aliases } in Option.either update {edge;pkg; aliases } (Map.find_opt path deps) in Map.add path ep deps let make ~path ?aliases ~edge pkg = update ~path ?aliases ~edge pkg empty let merge = Map.union (fun _k x y -> let aliases = S.union x.aliases y.aliases in Some { y with edge = Edge.max x.edge y.edge; aliases }) let (+) = merge let find path deps = Option.fmap (fun {edge;pkg;aliases} -> {path;edge;pkg;aliases}) @@ Map.find_opt path deps let fold f deps acc = Map.fold (fun path {edge;pkg;aliases} -> f {path;edge;pkg;aliases}) deps acc let pp_elt ppf (path, {edge;pkg;aliases}) = Pp.fp ppf "%s%a(%a)%a" (if edge = Edge.Normal then "" else "ε∙") Namespaced.pp path P.pp pkg S.pp aliases let pp ppf s = Pp.fp ppf "@[<hov>{%a}@]" (Pp.list pp_elt) (Map.bindings s) let of_list l = List.fold_left (fun m {path;edge;pkg;aliases} -> Map.add path {edge; pkg; aliases} m) empty l let pkgs deps = fold (fun {pkg; _ } x -> pkg :: x) deps [] let paths deps = fold (fun {path; _ } x -> path :: x) deps [] let all deps = fold List.cons deps [] let pkg_set x = Map.fold (fun _ x s -> P.Set.add x.pkg s) x P.Set.empty
null
https://raw.githubusercontent.com/Octachron/codept/771421500c1769a13b9dc51204c8841e7f1368c6/lib/deps.ml
ocaml
module Edge = struct type t = Normal | Epsilon let max x y = if x = Epsilon then x else y let min x y = if x = Normal then x else y let sch = let open Schematic in custom (Sum["Normal", Void; "Epsilon", Void ]) (function Normal -> C E | Epsilon -> C (S E)) (function C E -> Normal | C S E -> Epsilon | _ -> . ) let pp ppf = function | Normal -> Pp.fp ppf "N" | Epsilon -> Pp.fp ppf "ε" end module S = Namespaced.Set type dep = { path: Namespaced.t; edge:Edge.t; pkg:Pkg.t; aliases:S.t} type subdep = { edge:Edge.t; pkg:Pkg.t; aliases:S.t } module Map = Namespaced.Map type t = subdep Map.t let sch: t Schematic.t = let module T = Schematic.Tuple in let from_list = let open T in List.fold_left (fun m [k; edge; pkg; aliases] -> Map.add k {edge;pkg;aliases} m) Map.empty in let to_list m = Map.fold (fun k {edge;pkg;aliases} l -> T.[k;edge;pkg;aliases] :: l) m [] in let open Schematic in custom (Array [Namespaced.sch; Edge.sch; Pkg.sch; S.sch]) to_list from_list module Pth = Paths.S module P = Pkg let empty = Map.empty let update ~path ?(aliases=S.empty) ~edge pkg deps: t = let ep = let update x = let aliases = S.union aliases x.aliases in { x with edge = Edge.max edge x.edge; aliases } in Option.either update {edge;pkg; aliases } (Map.find_opt path deps) in Map.add path ep deps let make ~path ?aliases ~edge pkg = update ~path ?aliases ~edge pkg empty let merge = Map.union (fun _k x y -> let aliases = S.union x.aliases y.aliases in Some { y with edge = Edge.max x.edge y.edge; aliases }) let (+) = merge let find path deps = Option.fmap (fun {edge;pkg;aliases} -> {path;edge;pkg;aliases}) @@ Map.find_opt path deps let fold f deps acc = Map.fold (fun path {edge;pkg;aliases} -> f {path;edge;pkg;aliases}) deps acc let pp_elt ppf (path, {edge;pkg;aliases}) = Pp.fp ppf "%s%a(%a)%a" (if edge = Edge.Normal then "" else "ε∙") Namespaced.pp path P.pp pkg S.pp aliases let pp ppf s = Pp.fp ppf "@[<hov>{%a}@]" (Pp.list pp_elt) (Map.bindings s) let of_list l = List.fold_left (fun m {path;edge;pkg;aliases} -> Map.add path {edge; pkg; aliases} m) empty l let pkgs deps = fold (fun {pkg; _ } x -> pkg :: x) deps [] let paths deps = fold (fun {path; _ } x -> path :: x) deps [] let all deps = fold List.cons deps [] let pkg_set x = Map.fold (fun _ x s -> P.Set.add x.pkg s) x P.Set.empty
52eca46f208880a72bd8d6719c26777745f8d2274c443204e7ca3d6d5487bbc7
hyperfiddle/electric
hfql11.clj
(ns dustin.hfql11 (:require [clojure.walk :refer [walk prewalk postwalk]] [contrib.do :refer [via* Do-via *this !]] [datomic.api :as d] [dustin.fiddle :refer :all] [dustin.hf-nav :refer :all] [hyperfiddle.api :as hf] [meander.epsilon :as m :refer [match rewrite]] [minitest :refer [tests]])) (defn hf-edge->sym [edge] (if (keyword? edge) (symbol edge) edge)) (defn hf-eval [edge scope] (let [v (cond (keyword? edge) (hf-nav edge (get scope '%)) (seq? edge) (let [[f & args] edge] (clojure.core/apply (clojure.core/resolve f) (replace scope args))) () (println "hf-eval unmatched edge: " edge))] (merge scope {(hf-edge->sym edge) v '% v}))) (tests (hf-eval :dustingetz/gender {'% 17592186045441}) := '{% :dustingetz/male, dustingetz/gender :dustingetz/male} (hf-eval '(identity %) {'% 17592186045441}) := '{% 17592186045441, (identity %) 17592186045441} ) (defn hf-pull [pat] (match pat one entry (fn [scope] {?edge ((hf-pull ?pat) (hf-eval ?edge scope))}) : / gender ' ( f dustingetz / gender ) (fn [scope] {?leaf (-> (hf-eval ?leaf scope) (get '%))}) )) (tests (hf-pull :db/ident) := #:db{:ident '(fn [scope] ...)} ; a thunked tree, feed it scopes while traversing ((:db/ident *1) {'% :dustingetz/male}) := :dustingetz/male ) (tests ((hf-pull :db/ident) {'% :dustingetz/male}) := #:db{:ident :dustingetz/male} ( hf - pull ' (: db / ident % ) { ' % : / male } ) ; interpret kw as entity nav ? There 's no need to , do n't do this : = { (: db / ident % ) (: db / ident : / male ) } ; ClassCastException ((hf-pull '(hf-nav :db/ident %)) {'% :dustingetz/male}) := {'(hf-nav :db/ident %) :dustingetz/male} ((hf-pull '(identity %)) {'% :dustingetz/male}) := {'(identity %) :dustingetz/male} ((hf-pull :dustingetz/gender) {'% 17592186045441}) := #:dustingetz{:gender :dustingetz/male} ( hf - pull ' (: / gender % ) { ' % 17592186045441 } ) : = { (: / gender % ) (: / gender 17592186045441 ) } ((hf-pull {:dustingetz/gender :db/ident}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:ident :dustingetz/male}} ((hf-pull '(gender)) {}) := '{(gender) 17592186045430} ((hf-pull '(submission needle)) {'needle "alic"}) := '{(submission needle) 17592186045440} ((hf-pull {'(submission needle) :dustingetz/gender}) {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender :dustingetz/female}} ((hf-pull {'(submission needle) {:dustingetz/gender :db/ident}}) {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender #:db{:ident :dustingetz/female}}} ((hf-pull '{(submission needle) {:dustingetz/gender (shirt-size dustingetz/gender)}}) {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender {(shirt-size dustingetz/gender) 17592186045436}}} ((hf-pull '{(submission needle) ; query {:dustingetz/gender {(shirt-size dustingetz/gender) :db/ident}}}) {'needle "alic"}) ; scope := '{(submission needle) ; result {:dustingetz/gender {(shirt-size dustingetz/gender) {:db/ident :dustingetz/womens-small}}}} ((hf-pull {:db/ident :db/id}) {'% 17592186045430}) := #:db{:ident #:db{:id 17592186045430}} ((hf-pull {:dustingetz/gender {:db/ident :db/id}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:ident #:db{:id 17592186045430}}} ((hf-pull {:dustingetz/gender {:db/ident {:db/ident :db/ident}}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:ident #:db{:ident #:db{:ident :dustingetz/male}}}} ((hf-pull {:dustingetz/gender :db/id}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:id 17592186045430}} ((hf-pull {:dustingetz/gender {:db/id :db/id}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:id #:db{:id 17592186045430}}} ; :db/id is a self reference so this actually is coherent ((hf-pull {:dustingetz/gender {:db/id {:db/id {:db/id :db/id}}}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:id #:db{:id #:db{:id #:db{:id 17592186045430}}}}} )
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2020/hfql/hfql11.clj
clojure
a thunked tree, feed it scopes while traversing interpret kw as entity nav ? There 's no need to , do n't do this ClassCastException query scope result :db/id is a self reference so this actually is coherent
(ns dustin.hfql11 (:require [clojure.walk :refer [walk prewalk postwalk]] [contrib.do :refer [via* Do-via *this !]] [datomic.api :as d] [dustin.fiddle :refer :all] [dustin.hf-nav :refer :all] [hyperfiddle.api :as hf] [meander.epsilon :as m :refer [match rewrite]] [minitest :refer [tests]])) (defn hf-edge->sym [edge] (if (keyword? edge) (symbol edge) edge)) (defn hf-eval [edge scope] (let [v (cond (keyword? edge) (hf-nav edge (get scope '%)) (seq? edge) (let [[f & args] edge] (clojure.core/apply (clojure.core/resolve f) (replace scope args))) () (println "hf-eval unmatched edge: " edge))] (merge scope {(hf-edge->sym edge) v '% v}))) (tests (hf-eval :dustingetz/gender {'% 17592186045441}) := '{% :dustingetz/male, dustingetz/gender :dustingetz/male} (hf-eval '(identity %) {'% 17592186045441}) := '{% 17592186045441, (identity %) 17592186045441} ) (defn hf-pull [pat] (match pat one entry (fn [scope] {?edge ((hf-pull ?pat) (hf-eval ?edge scope))}) : / gender ' ( f dustingetz / gender ) (fn [scope] {?leaf (-> (hf-eval ?leaf scope) (get '%))}) )) (tests ((:db/ident *1) {'% :dustingetz/male}) := :dustingetz/male ) (tests ((hf-pull :db/ident) {'% :dustingetz/male}) := #:db{:ident :dustingetz/male} ((hf-pull '(hf-nav :db/ident %)) {'% :dustingetz/male}) := {'(hf-nav :db/ident %) :dustingetz/male} ((hf-pull '(identity %)) {'% :dustingetz/male}) := {'(identity %) :dustingetz/male} ((hf-pull :dustingetz/gender) {'% 17592186045441}) := #:dustingetz{:gender :dustingetz/male} ( hf - pull ' (: / gender % ) { ' % 17592186045441 } ) : = { (: / gender % ) (: / gender 17592186045441 ) } ((hf-pull {:dustingetz/gender :db/ident}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:ident :dustingetz/male}} ((hf-pull '(gender)) {}) := '{(gender) 17592186045430} ((hf-pull '(submission needle)) {'needle "alic"}) := '{(submission needle) 17592186045440} ((hf-pull {'(submission needle) :dustingetz/gender}) {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender :dustingetz/female}} ((hf-pull {'(submission needle) {:dustingetz/gender :db/ident}}) {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender #:db{:ident :dustingetz/female}}} ((hf-pull '{(submission needle) {:dustingetz/gender (shirt-size dustingetz/gender)}}) {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender {(shirt-size dustingetz/gender) 17592186045436}}} ((hf-pull {:dustingetz/gender {(shirt-size dustingetz/gender) :db/ident}}}) {:dustingetz/gender {(shirt-size dustingetz/gender) {:db/ident :dustingetz/womens-small}}}} ((hf-pull {:db/ident :db/id}) {'% 17592186045430}) := #:db{:ident #:db{:id 17592186045430}} ((hf-pull {:dustingetz/gender {:db/ident :db/id}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:ident #:db{:id 17592186045430}}} ((hf-pull {:dustingetz/gender {:db/ident {:db/ident :db/ident}}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:ident #:db{:ident #:db{:ident :dustingetz/male}}}} ((hf-pull {:dustingetz/gender :db/id}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:id 17592186045430}} ((hf-pull {:dustingetz/gender {:db/id :db/id}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:id #:db{:id 17592186045430}}} ((hf-pull {:dustingetz/gender {:db/id {:db/id {:db/id :db/id}}}}) {'% 17592186045441}) := #:dustingetz{:gender #:db{:id #:db{:id #:db{:id #:db{:id 17592186045430}}}}} )
78f336ea12c811a2fce02d49356b9f054c0cf20b3140113f7d86b1a5dd085173
PacktWorkshops/The-Clojure-Workshop
project.clj
(defproject packt-clj.chapter-4-tests "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :dependencies [[org.clojure/clojure "1.10.0"] [semantic-csv "0.2.1-alpha1"] [org.clojure/data.csv "0.1.4"]] :repl-options {:init-ns packt-clj.chapter-4-tests} :profiles {:dev {:resource-paths ["test/resources"]}})
null
https://raw.githubusercontent.com/PacktWorkshops/The-Clojure-Workshop/3d309bb0e46a41ce2c93737870433b47ce0ba6a2/Chapter04/tests/packt-clj.chapter-4-tests/project.clj
clojure
(defproject packt-clj.chapter-4-tests "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :dependencies [[org.clojure/clojure "1.10.0"] [semantic-csv "0.2.1-alpha1"] [org.clojure/data.csv "0.1.4"]] :repl-options {:init-ns packt-clj.chapter-4-tests} :profiles {:dev {:resource-paths ["test/resources"]}})
6c733635574becb7219d6f683eb5f51a06bb8edc44a4e24bcaaa95c27bc0842c
tezos-checker/checker
testArbitrary.ml
open Ctok open Kit open Lqt open Tok * Generate a random non - negative tez amount in the full spectrum . Note that * most of these amounts are not expected in practice , since there is not that * much currency in existence ( and will never be ) . This means that for example * adding two amounts generated by [ arb_tez ] can easily lead to an Int64 * overflow , so use with care . * most of these amounts are not expected in practice, since there is not that * much currency in existence (and will never be). This means that for example * adding two amounts generated by [arb_tez] can easily lead to an Int64 * overflow, so use with care. *) let arb_tez = QCheck.map (fun x -> Ligo.tez_from_literal ((string_of_int x) ^ "mutez")) QCheck.(0 -- max_int) * Generate a random non - negative tok amount in the full spectrum . Note that * most of these amounts are not expected in practice , since there is not that * much currency in existence ( and will never be ) . This means that for example * adding two amounts generated by [ arb_tok ] can easily lead to an Int64 * overflow , so use with care . * most of these amounts are not expected in practice, since there is not that * much currency in existence (and will never be). This means that for example * adding two amounts generated by [arb_tok] can easily lead to an Int64 * overflow, so use with care. *) let arb_tok = QCheck.map (fun x -> tok_of_denomination (Ligo.nat_from_literal ((string_of_int x) ^ "n"))) QCheck.(0 -- max_int) * Generate a random positive tez amount in the full spectrum . Note that most * of these amounts are not expected in practice , since there is not that much * currency in existence ( and will never be ) . This means that for example * adding two amounts generated by [ arb_positive_tez ] can easily lead to an * Int64 overflow , so use with care . * of these amounts are not expected in practice, since there is not that much * currency in existence (and will never be). This means that for example * adding two amounts generated by [arb_positive_tez] can easily lead to an * Int64 overflow, so use with care. *) let arb_positive_tez = QCheck.map (fun x -> Ligo.tez_from_literal ((string_of_int x) ^ "mutez")) QCheck.(1 -- max_int) * Generate a random positive tez amount that does not exceed 10Ktez . This * size should be sufficient to capture realistic tez amounts , and is far * enough from [ Int64.max_int ] to be safe from overflows . * size should be sufficient to capture realistic tez amounts, and is far * enough from [Int64.max_int] to be safe from overflows. *) let arb_small_positive_tez = QCheck.map (fun x -> Ligo.tez_from_literal ((string_of_int x) ^ "mutez")) QCheck.(1 -- 10_000_000_000) let arb_positive_ctok = QCheck.map (fun x -> ctok_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(1 -- max_int) let arb_address = QCheck.map Ligo.address_of_string QCheck.(string_of_size (Gen.return 36)) let arb_kit = QCheck.map (fun x -> kit_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(0 -- max_int) let arb_positive_kit = QCheck.map (fun x -> kit_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(1 -- max_int) let arb_lqt = QCheck.map (fun x -> lqt_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(0 -- max_int) let arb_positive_lqt = QCheck.map (fun x -> lqt_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(1 -- max_int) let arb_nat = QCheck.map (fun x -> Ligo.nat_from_literal ((string_of_int x) ^ "n")) QCheck.(0 -- max_int) let arb_small_positive_nat = QCheck.map (fun x -> Ligo.nat_from_literal ((string_of_int x) ^ "n")) QCheck.(1 -- 10_000_000_000) let arb_liquidation_slice_contents = QCheck.map (fun tk -> LiquidationAuctionPrimitiveTypes. ({ tok = tok_of_denomination (Ligo.nat_from_literal ((string_of_int tk) ^ "n")) ; burrow = (Ligo.address_of_string "", Ligo.nat_from_literal "0n") ; min_kit_for_unwarranted = Some kit_zero }) ) QCheck.(0 -- 1000) let arb_liquidation_slice = QCheck.map (fun sl -> LiquidationAuctionPrimitiveTypes. ({ contents = sl ; older = None ; younger = None }) ) arb_liquidation_slice_contents
null
https://raw.githubusercontent.com/tezos-checker/checker/04de01fd512c89d0d357aa7312610d04f20c6992/tests/testArbitrary.ml
ocaml
open Ctok open Kit open Lqt open Tok * Generate a random non - negative tez amount in the full spectrum . Note that * most of these amounts are not expected in practice , since there is not that * much currency in existence ( and will never be ) . This means that for example * adding two amounts generated by [ arb_tez ] can easily lead to an Int64 * overflow , so use with care . * most of these amounts are not expected in practice, since there is not that * much currency in existence (and will never be). This means that for example * adding two amounts generated by [arb_tez] can easily lead to an Int64 * overflow, so use with care. *) let arb_tez = QCheck.map (fun x -> Ligo.tez_from_literal ((string_of_int x) ^ "mutez")) QCheck.(0 -- max_int) * Generate a random non - negative tok amount in the full spectrum . Note that * most of these amounts are not expected in practice , since there is not that * much currency in existence ( and will never be ) . This means that for example * adding two amounts generated by [ arb_tok ] can easily lead to an Int64 * overflow , so use with care . * most of these amounts are not expected in practice, since there is not that * much currency in existence (and will never be). This means that for example * adding two amounts generated by [arb_tok] can easily lead to an Int64 * overflow, so use with care. *) let arb_tok = QCheck.map (fun x -> tok_of_denomination (Ligo.nat_from_literal ((string_of_int x) ^ "n"))) QCheck.(0 -- max_int) * Generate a random positive tez amount in the full spectrum . Note that most * of these amounts are not expected in practice , since there is not that much * currency in existence ( and will never be ) . This means that for example * adding two amounts generated by [ arb_positive_tez ] can easily lead to an * Int64 overflow , so use with care . * of these amounts are not expected in practice, since there is not that much * currency in existence (and will never be). This means that for example * adding two amounts generated by [arb_positive_tez] can easily lead to an * Int64 overflow, so use with care. *) let arb_positive_tez = QCheck.map (fun x -> Ligo.tez_from_literal ((string_of_int x) ^ "mutez")) QCheck.(1 -- max_int) * Generate a random positive tez amount that does not exceed 10Ktez . This * size should be sufficient to capture realistic tez amounts , and is far * enough from [ Int64.max_int ] to be safe from overflows . * size should be sufficient to capture realistic tez amounts, and is far * enough from [Int64.max_int] to be safe from overflows. *) let arb_small_positive_tez = QCheck.map (fun x -> Ligo.tez_from_literal ((string_of_int x) ^ "mutez")) QCheck.(1 -- 10_000_000_000) let arb_positive_ctok = QCheck.map (fun x -> ctok_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(1 -- max_int) let arb_address = QCheck.map Ligo.address_of_string QCheck.(string_of_size (Gen.return 36)) let arb_kit = QCheck.map (fun x -> kit_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(0 -- max_int) let arb_positive_kit = QCheck.map (fun x -> kit_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(1 -- max_int) let arb_lqt = QCheck.map (fun x -> lqt_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(0 -- max_int) let arb_positive_lqt = QCheck.map (fun x -> lqt_of_denomination (Ligo.nat_from_literal (string_of_int x ^ "n"))) QCheck.(1 -- max_int) let arb_nat = QCheck.map (fun x -> Ligo.nat_from_literal ((string_of_int x) ^ "n")) QCheck.(0 -- max_int) let arb_small_positive_nat = QCheck.map (fun x -> Ligo.nat_from_literal ((string_of_int x) ^ "n")) QCheck.(1 -- 10_000_000_000) let arb_liquidation_slice_contents = QCheck.map (fun tk -> LiquidationAuctionPrimitiveTypes. ({ tok = tok_of_denomination (Ligo.nat_from_literal ((string_of_int tk) ^ "n")) ; burrow = (Ligo.address_of_string "", Ligo.nat_from_literal "0n") ; min_kit_for_unwarranted = Some kit_zero }) ) QCheck.(0 -- 1000) let arb_liquidation_slice = QCheck.map (fun sl -> LiquidationAuctionPrimitiveTypes. ({ contents = sl ; older = None ; younger = None }) ) arb_liquidation_slice_contents
b44d3f44f15320515d907ea287513bca530adc04d7cf5118e85dab1e1932404c
ucsd-progsys/liquidhaskell
Poly2_degenerate.hs
module Poly2_degenerate (prop_id6) where import Language.Haskell.Liquid.Prelude myabs x = if x `gt` 0 then x else 0 `minus` x ---------------------------------------------------------- myid3 x y = y prop_id6 x = liquidAssertB (x' `geq` 0) where x' = myid3 [] $ myabs x
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/20cd67af038930cb592d68d272c8eb1cbe3cb6bf/tests/pos/Poly2_degenerate.hs
haskell
--------------------------------------------------------
module Poly2_degenerate (prop_id6) where import Language.Haskell.Liquid.Prelude myabs x = if x `gt` 0 then x else 0 `minus` x myid3 x y = y prop_id6 x = liquidAssertB (x' `geq` 0) where x' = myid3 [] $ myabs x
b8710d00d6eac23b6438210545e66c7f8f7f82e1dabad11f874ce39634199fbf
janestreet/ppx_css
css_inliner.mli
(* this file intentionally left blank *)
null
https://raw.githubusercontent.com/janestreet/ppx_css/3baeb2a2d9787bec88942a2cefbead6a257ef5a1/standalone/css_inliner.mli
ocaml
this file intentionally left blank
af543b2b048dfb3979791a573eeccfbfd1478b088056b9d5ca8b608ef759d659
flipstone/redcard
Types.hs
module Data.Validation.Types ( module Data.Validation.Types.Pure , module Data.Validation.Types.Trans ) where import Data.Validation.Types.Pure import Data.Validation.Types.Trans
null
https://raw.githubusercontent.com/flipstone/redcard/9a15a6a00a1ddac7095fe590c76c258da4053a84/src/Data/Validation/Types.hs
haskell
module Data.Validation.Types ( module Data.Validation.Types.Pure , module Data.Validation.Types.Trans ) where import Data.Validation.Types.Pure import Data.Validation.Types.Trans
08e42b97b27d959249541b00cadc5f6a3f9d94d572f37486aa1bbaf4ce5ae4be
yellowbean/clojucture
cn.clj
(ns clojucture.reader.cn (:require [clojucture.asset :as asset] [clojucture.assumption :as assump] [clojucture.account :as account] [clojucture.expense :as exp ] [clojucture.util :as u] [clojucture.tranche :as b] [clojucture.account :as a] [clojucture.pool :as p] [clojucture.spv :as spv ] [clojure.java.io :as io] [clojure.core.match :as m] [java-time :as jt] ) (:use [ dk.ative.docjure.spreadsheet ]) (:import [tech.tablesaw.api Table Row DoubleColumn DateColumn StringColumn BooleanColumn] [java.util Locale] [java.time ZoneId] [tech.tablesaw.io.csv CsvReader CsvReadOptions$Builder] ) ) (defn to-ld [ x ] (-> x (.toInstant) (.atZone (ZoneId/systemDefault)) (.toLocalDate) ) ) China spreadsheet loader (defn cn-setup-bond [ bm settle-date] (let [ fbm bm ] (m/match fbm { :name bid :balance bal :rate r :type "过手"} (b/->sequence-bond {:name bid :settle-date settle-date} bal r [] settle-date 0 0 ) :else nil ) ) ) (defn cn-setup-fee [ fm end-date] (m/match fm {:name n :amount a :start-date s :interval i} (exp/->recur-expense {:name n :amount a :period i :start-date (to-ld s) :end-date end-date } [] 0) {:name n :amount a} (exp/->amount-expense {:name n} [] nil a ) {:name n :rate r :base b} (exp/->pct-expense-by-amount {:name n :base b :pct r} [] nil 0 ) :else nil ) ) (defn cn-setup-wf [ dist-action ] (m/match dist-action {:cond cons :source source :target target :opt opt} "D" {:source source :target target :opt opt} {:source (keyword source) :target (keyword target) :opt (keyword opt)} {:source source :target target } {:source (keyword source) :target (keyword target)} :else nil ) ) (defn cn-setup-pool [ a ] (m/match a {:originate-date od :maturity-date md :term term :closing-date cd :current-balance obalance :rate r :int-feq freq :int-interval int-interval :first-pay first-pay :remain-term rm} (asset/->loan {:start-date (to-ld od) :term term :rate r :balance obalance :periodicity (jt/months 3) :first-pay (to-ld first-pay) :maturity-date (to-ld md)} obalance rm r nil ) :nil ) ) (defn cn-setup-acc [ a ] (m/match a {:name n :type t :balance b} (account/->account (keyword n) (keyword t) b []) :else nil ) ) (comment (defn cn-load-model! [ wb-path ] (let [ wb (load-workbook wb-path) info-s (select-sheet "info" wb) [ closing-date settle-date first-payment-date stated-maturity ] (map #(to-ld (:date %) ) (select-columns {:A :name :B :date} info-s)) [ h & assets ] (row-seq (select-sheet "pool" wb)) pool-s (select-sheet "pool" wb) asset-list (map cn-setup-pool (subvec (select-columns {:B :originate-date :C :maturity-date :D :closing-date :F :current-balance :G :rate :H :int-feq :I :int-interval :J :term :K :remain-term :L :first-pay} pool-s) 1)) bond-s (select-sheet "bond" wb) bonds (map #(cn-setup-bond % settle-date ) (rest (select-columns {:A :name :B :balance :C :rate :D :feq :E :type } bond-s))) fee-s (select-sheet "fee" wb) fees-oneoff (map #(cn-setup-fee % closing-date) (subvec (select-columns {:A :name :B :amount} fee-s) 2 )) fees-base (map #(cn-setup-fee % closing-date) (subvec (select-columns {:D :name :E :rate :F :base} fee-s) 2 )) fees-recur (map #(cn-setup-fee % closing-date) (subvec (select-columns {:H :name :I :amount :J :start-date :K :interval } fee-s) 2 )) waterfall-s (select-sheet "waterfall" wb) wf-norm (map cn-setup-wf (subvec (select-columns {:A :cond :B :source :C :target :D :opt } waterfall-s) 2 )) wf-default (map cn-setup-wf (subvec (select-columns {:F :cond :G :source :H :target :I :opt } waterfall-s) 2 )) account-s (select-sheet "account" wb) accounts (->> (map cn-setup-acc (subvec (select-columns {:A :name :B :type :C :balance} account-s) 1 )) (u/build-map-from-field :name)) assump-s (select-sheet "assumption" wb) assump-prepay nil assump-default nil ] (spv/build-deal {:info { :dates { :closing-date closing-date :first-collect-date (jt/local-date 2017 6 30) :collect-interval :Q :stated-maturity stated-maturity :first-payment-date (jt/local-date 2017 6 30) :payment-interval :Q :delay-days 20 } :waterfall { :normal wf-norm :default wf-default } :accounts accounts :country :China :deposit-mapping {:principal :账户P :interest :账户I} } :status { :update-date (jt/local-date 2017 4 30) :pool (p/->pool asset-list (jt/local-date 2018 1 1 )) :bond bonds :expense [fees-oneoff fees-base fees-recur] :account accounts }} ) ) ))
null
https://raw.githubusercontent.com/yellowbean/clojucture/3ad99e06ecd9e5c478f653df4afbd69991cd4964/src/clj/clojucture/reader/cn.clj
clojure
(ns clojucture.reader.cn (:require [clojucture.asset :as asset] [clojucture.assumption :as assump] [clojucture.account :as account] [clojucture.expense :as exp ] [clojucture.util :as u] [clojucture.tranche :as b] [clojucture.account :as a] [clojucture.pool :as p] [clojucture.spv :as spv ] [clojure.java.io :as io] [clojure.core.match :as m] [java-time :as jt] ) (:use [ dk.ative.docjure.spreadsheet ]) (:import [tech.tablesaw.api Table Row DoubleColumn DateColumn StringColumn BooleanColumn] [java.util Locale] [java.time ZoneId] [tech.tablesaw.io.csv CsvReader CsvReadOptions$Builder] ) ) (defn to-ld [ x ] (-> x (.toInstant) (.atZone (ZoneId/systemDefault)) (.toLocalDate) ) ) China spreadsheet loader (defn cn-setup-bond [ bm settle-date] (let [ fbm bm ] (m/match fbm { :name bid :balance bal :rate r :type "过手"} (b/->sequence-bond {:name bid :settle-date settle-date} bal r [] settle-date 0 0 ) :else nil ) ) ) (defn cn-setup-fee [ fm end-date] (m/match fm {:name n :amount a :start-date s :interval i} (exp/->recur-expense {:name n :amount a :period i :start-date (to-ld s) :end-date end-date } [] 0) {:name n :amount a} (exp/->amount-expense {:name n} [] nil a ) {:name n :rate r :base b} (exp/->pct-expense-by-amount {:name n :base b :pct r} [] nil 0 ) :else nil ) ) (defn cn-setup-wf [ dist-action ] (m/match dist-action {:cond cons :source source :target target :opt opt} "D" {:source source :target target :opt opt} {:source (keyword source) :target (keyword target) :opt (keyword opt)} {:source source :target target } {:source (keyword source) :target (keyword target)} :else nil ) ) (defn cn-setup-pool [ a ] (m/match a {:originate-date od :maturity-date md :term term :closing-date cd :current-balance obalance :rate r :int-feq freq :int-interval int-interval :first-pay first-pay :remain-term rm} (asset/->loan {:start-date (to-ld od) :term term :rate r :balance obalance :periodicity (jt/months 3) :first-pay (to-ld first-pay) :maturity-date (to-ld md)} obalance rm r nil ) :nil ) ) (defn cn-setup-acc [ a ] (m/match a {:name n :type t :balance b} (account/->account (keyword n) (keyword t) b []) :else nil ) ) (comment (defn cn-load-model! [ wb-path ] (let [ wb (load-workbook wb-path) info-s (select-sheet "info" wb) [ closing-date settle-date first-payment-date stated-maturity ] (map #(to-ld (:date %) ) (select-columns {:A :name :B :date} info-s)) [ h & assets ] (row-seq (select-sheet "pool" wb)) pool-s (select-sheet "pool" wb) asset-list (map cn-setup-pool (subvec (select-columns {:B :originate-date :C :maturity-date :D :closing-date :F :current-balance :G :rate :H :int-feq :I :int-interval :J :term :K :remain-term :L :first-pay} pool-s) 1)) bond-s (select-sheet "bond" wb) bonds (map #(cn-setup-bond % settle-date ) (rest (select-columns {:A :name :B :balance :C :rate :D :feq :E :type } bond-s))) fee-s (select-sheet "fee" wb) fees-oneoff (map #(cn-setup-fee % closing-date) (subvec (select-columns {:A :name :B :amount} fee-s) 2 )) fees-base (map #(cn-setup-fee % closing-date) (subvec (select-columns {:D :name :E :rate :F :base} fee-s) 2 )) fees-recur (map #(cn-setup-fee % closing-date) (subvec (select-columns {:H :name :I :amount :J :start-date :K :interval } fee-s) 2 )) waterfall-s (select-sheet "waterfall" wb) wf-norm (map cn-setup-wf (subvec (select-columns {:A :cond :B :source :C :target :D :opt } waterfall-s) 2 )) wf-default (map cn-setup-wf (subvec (select-columns {:F :cond :G :source :H :target :I :opt } waterfall-s) 2 )) account-s (select-sheet "account" wb) accounts (->> (map cn-setup-acc (subvec (select-columns {:A :name :B :type :C :balance} account-s) 1 )) (u/build-map-from-field :name)) assump-s (select-sheet "assumption" wb) assump-prepay nil assump-default nil ] (spv/build-deal {:info { :dates { :closing-date closing-date :first-collect-date (jt/local-date 2017 6 30) :collect-interval :Q :stated-maturity stated-maturity :first-payment-date (jt/local-date 2017 6 30) :payment-interval :Q :delay-days 20 } :waterfall { :normal wf-norm :default wf-default } :accounts accounts :country :China :deposit-mapping {:principal :账户P :interest :账户I} } :status { :update-date (jt/local-date 2017 4 30) :pool (p/->pool asset-list (jt/local-date 2018 1 1 )) :bond bonds :expense [fees-oneoff fees-base fees-recur] :account accounts }} ) ) ))
da876920eceb3747baed904c2b54649a449da32a99bf3f25beff24ca7738af81
alanz/ghc-exactprint
SlidingListComp.hs
foo = [concatMap (\(n, f) -> [findPath copts v >>= f (listArg "ghc" as) | v <- listArg n as]) [ ("project", Update.scanProject), ("file", Update.scanFile), ("path", Update.scanDirectory)], map (Update.scanCabal (listArg "ghc" as)) cabals]
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc710/SlidingListComp.hs
haskell
foo = [concatMap (\(n, f) -> [findPath copts v >>= f (listArg "ghc" as) | v <- listArg n as]) [ ("project", Update.scanProject), ("file", Update.scanFile), ("path", Update.scanDirectory)], map (Update.scanCabal (listArg "ghc" as)) cabals]
a3b3d4e95f515a0462260d6de830a860fcd0a6ec8c99762aa84291eccb374f82
aantron/luv
sigint.ml
let () = let handle = Luv.Signal.init () |> Result.get_ok in ignore @@ Luv.Signal.start handle Luv.Signal.sigint begin fun () -> Luv.Handle.close handle ignore; print_endline "Exiting" end; print_endline "Type Ctrl+C to continue..."; ignore (Luv.Loop.run () : bool)
null
https://raw.githubusercontent.com/aantron/luv/4b49d3edad2179c76d685500edf1b44f61ec4be8/example/sigint.ml
ocaml
let () = let handle = Luv.Signal.init () |> Result.get_ok in ignore @@ Luv.Signal.start handle Luv.Signal.sigint begin fun () -> Luv.Handle.close handle ignore; print_endline "Exiting" end; print_endline "Type Ctrl+C to continue..."; ignore (Luv.Loop.run () : bool)
42e454b403c143f066b8d77466330e478fac0c18b5c7a9df8f99229743be8e96
johnwhitington/ocamli
mod_binding.ml
module LargeFile = struct external seek_out : out_channel -> int64 -> unit = "caml_ml_seek_out_64" end
null
https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/examples/mod_binding.ml
ocaml
module LargeFile = struct external seek_out : out_channel -> int64 -> unit = "caml_ml_seek_out_64" end
eb4373e39e53fe418c87e7261cce54953b2552db938a3eef2d75d05fe65d718b
rbrito/pkg-mp3packer
unicode.ml
type 'a t = Normal of 'a | Error of int;; external is_win : unit -> bool = "uni_is_win" "noalloc";; let win = is_win ();; (***********) UNICODE (***********) external set_utf8_output : unit -> unit = "uni_set_utf8_output";; external silly_print_c : string -> unit = "uni_silly_print";; let silly_print x = flush stdout; silly_print_c x; ;; This is only good on Windows ! Unixy systems return Error for everything ! external utf16_of_utf8_c : string -> bool -> string t = "uni_utf16_of_utf8";; let utf16_of_utf8 ?(include_null=false) a = utf16_of_utf8_c a include_null;; external utf8_of_utf16_unsafe : int -> string -> string t = "uni_utf8_of_utf16";; let utf8_of_utf16 x = utf8_of_utf16_unsafe (String.length x) x;; external active_of_utf16_unsafe : int -> string -> string t = "uni_active_of_utf16";; let active_of_utf16 x = active_of_utf16_unsafe (String.length x) x;; let active_of_utf8 x8 = match utf16_of_utf8_c x8 false with | Normal x16 -> active_of_utf16_unsafe (String.length x16) x16 | Error e -> Error e ;; Like , but returns the UTF8 string if an error occured let sprint_utf8 x8 = match active_of_utf8 x8 with | Normal n -> n | Error _ -> x8 ;; (* the length value is in WCHARS, not bytes! *) (* Unsafe since the length is not checked *) external utf8_of_utf16_and_length_unsafe : string -> int -> string t = "uni_utf8_of_utf16_and_length";; let utf8_of_utf16 s = utf8_of_utf16_and_length_unsafe s (String.length s / 2);; external get_utf16_command_line : unit -> string t = "uni_get_utf16_command_line";; external get_utf8_argv_c : unit -> string array t = "uni_get_utf8_argv";; let argv_opt = if win then ( get_utf8_argv_c () ) else ( Normal Sys.argv );; (* UTF8 *) external openfile_utf16_c : string -> Unix.open_flag list -> Unix.file_perm -> Unix.file_descr = "uni_openfile_utf16";; let openfile_utf8 = if win then ( fun s -> ( match utf16_of_utf8 ~include_null:true s with | Normal s16 -> openfile_utf16_c s16 | Error e -> failwith (Printf.sprintf "Unicode.openfile_utf8 failed with Windows error %d" e) ) ) else ( Unix.openfile );; Input AND output values are zero - terminated UTF16 (*external readdir_utf16_c : string -> string array = "uni_readdir_utf16";;*) type dir_handle_t;; external readdir_find_first_file_utf16_unsafe : string -> (dir_handle_t * string) t = "uni_readdir_find_first_file_utf16";; external readdir_find_next_file_utf16 : dir_handle_t -> string t = "uni_readdir_find_next_file_utf16";; external readdir_find_close : dir_handle_t -> unit t = "uni_readdir_find_close";; let readdir_utf8 = if win then ( fun dir_in -> ( let read_this = dir_in ^ "\\*" in match utf16_of_utf8 ~include_null:true read_this with | Normal read_this_16 -> ( match readdir_find_first_file_utf16_unsafe read_this_16 with | Normal (h, first_16) -> ( Printf.printf " Got first 16 : % s\n " first_16 ; (* This should really be "length - sizeof(WCHAR)", but this will round down correctly *) match utf8_of_utf16_unsafe (String.length first_16 - 1) first_16 with | Normal first_8 -> ( let rec keep_reading num so_far = match readdir_find_next_file_utf16 h with | Normal next_16 -> ( Printf.printf " Got next 16 : % s\n " next_16 ; match utf8_of_utf16_unsafe (String.length next_16 - 1) next_16 with | Normal "." | Normal ".." -> keep_reading num so_far | Normal next_8 -> ( keep_reading (succ num) (next_8 :: so_far) ) | Error e -> Error e ) | Error 18(*ERROR_NO_MORE_FILES*) -> Normal (num, so_far) | Error e -> Error e in let got_list = if first_8 = "." || first_8 = ".." then ( keep_reading 0 [] ) else ( keep_reading 1 [first_8] ) in match got_list with | Normal (num, got) -> ( let out_array = Array.make num "" in let rec keep_putting n = function | [] -> () | hd :: tl -> ( out_array.(n) <- hd; keep_putting (pred n) tl ) in keep_putting (pred num) got; out_array ) | Error e -> ( ignore (readdir_find_close h); failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) ) | Error e -> ( ignore (readdir_find_close h); failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) ) | Error 2(*ERROR_FILE_NOT_FOUND*) -> [||] | Error e -> failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) | Error e -> failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) ) else ( Sys.readdir );; (* File info *) external stat_utf16_unsafe : string -> Unix.stats t = "uni_stat_utf16";; let stat_utf8 = if win then ( fun name -> ( match utf16_of_utf8 ~include_null:true name with | Normal name16 -> ( match stat_utf16_unsafe name16 with | Normal s -> s | Error _ -> raise Not_found ) | Error _ -> invalid_arg "Unicode.stat_utf8" ) ) else ( Unix.stat );; external file_exists_utf16_unsafe : string -> bool = "uni_file_exists_utf16";; let file_exists_utf8 = if win then ( fun n -> ( match utf16_of_utf8 ~include_null:true n with | Normal wn -> file_exists_utf16_unsafe wn | Error e -> failwith (Printf.sprintf "Unicode.file_exists_utf8 got Windows error %d" e) ) ) else ( Sys.file_exists );; (* Rename *) external rename_utf16_unsafe : string -> string -> unit t = "uni_rename_utf16";; let rename_utf8 = if win then ( fun n1 n2 -> ( match (utf16_of_utf8 ~include_null:true n1, utf16_of_utf8 ~include_null:true n2) with | (Normal wn1, Normal wn2) -> (match rename_utf16_unsafe wn1 wn2 with | Normal () -> () | Error e -> failwith (Printf.sprintf "Unicode.rename_utf8 got Windows error %d" e) ) | (Error e, _) -> failwith (Printf.sprintf "Unicode.rename_utf8 got Windows error %d" e) | (_, Error e) -> failwith (Printf.sprintf "Unicode.rename_utf8 got Windows error %d" e) ) ) else ( Sys.rename );; external remove_utf16_unsafe : string -> unit t = "uni_remove_utf16";; let remove_utf8 = if win then ( fun f -> (match utf16_of_utf8 ~include_null:true f with | Normal f16 -> ( match remove_utf16_unsafe f16 with | Normal () -> () | Error e -> failwith (Printf.sprintf "Unicode.remove_utf8 got Windows error %d" e) ) | Error e -> failwith (Printf.sprintf "Unicode.remove_utf8 got Windows error %d" e) ) ) else ( Sys.remove );;
null
https://raw.githubusercontent.com/rbrito/pkg-mp3packer/ac75f1d9cfd492f96248c6446147d0e510c1e299/unicode.ml
ocaml
********* ********* the length value is in WCHARS, not bytes! Unsafe since the length is not checked UTF8 external readdir_utf16_c : string -> string array = "uni_readdir_utf16";; This should really be "length - sizeof(WCHAR)", but this will round down correctly ERROR_NO_MORE_FILES ERROR_FILE_NOT_FOUND File info Rename
type 'a t = Normal of 'a | Error of int;; external is_win : unit -> bool = "uni_is_win" "noalloc";; let win = is_win ();; UNICODE external set_utf8_output : unit -> unit = "uni_set_utf8_output";; external silly_print_c : string -> unit = "uni_silly_print";; let silly_print x = flush stdout; silly_print_c x; ;; This is only good on Windows ! Unixy systems return Error for everything ! external utf16_of_utf8_c : string -> bool -> string t = "uni_utf16_of_utf8";; let utf16_of_utf8 ?(include_null=false) a = utf16_of_utf8_c a include_null;; external utf8_of_utf16_unsafe : int -> string -> string t = "uni_utf8_of_utf16";; let utf8_of_utf16 x = utf8_of_utf16_unsafe (String.length x) x;; external active_of_utf16_unsafe : int -> string -> string t = "uni_active_of_utf16";; let active_of_utf16 x = active_of_utf16_unsafe (String.length x) x;; let active_of_utf8 x8 = match utf16_of_utf8_c x8 false with | Normal x16 -> active_of_utf16_unsafe (String.length x16) x16 | Error e -> Error e ;; Like , but returns the UTF8 string if an error occured let sprint_utf8 x8 = match active_of_utf8 x8 with | Normal n -> n | Error _ -> x8 ;; external utf8_of_utf16_and_length_unsafe : string -> int -> string t = "uni_utf8_of_utf16_and_length";; let utf8_of_utf16 s = utf8_of_utf16_and_length_unsafe s (String.length s / 2);; external get_utf16_command_line : unit -> string t = "uni_get_utf16_command_line";; external get_utf8_argv_c : unit -> string array t = "uni_get_utf8_argv";; let argv_opt = if win then ( get_utf8_argv_c () ) else ( Normal Sys.argv );; external openfile_utf16_c : string -> Unix.open_flag list -> Unix.file_perm -> Unix.file_descr = "uni_openfile_utf16";; let openfile_utf8 = if win then ( fun s -> ( match utf16_of_utf8 ~include_null:true s with | Normal s16 -> openfile_utf16_c s16 | Error e -> failwith (Printf.sprintf "Unicode.openfile_utf8 failed with Windows error %d" e) ) ) else ( Unix.openfile );; Input AND output values are zero - terminated UTF16 type dir_handle_t;; external readdir_find_first_file_utf16_unsafe : string -> (dir_handle_t * string) t = "uni_readdir_find_first_file_utf16";; external readdir_find_next_file_utf16 : dir_handle_t -> string t = "uni_readdir_find_next_file_utf16";; external readdir_find_close : dir_handle_t -> unit t = "uni_readdir_find_close";; let readdir_utf8 = if win then ( fun dir_in -> ( let read_this = dir_in ^ "\\*" in match utf16_of_utf8 ~include_null:true read_this with | Normal read_this_16 -> ( match readdir_find_first_file_utf16_unsafe read_this_16 with | Normal (h, first_16) -> ( Printf.printf " Got first 16 : % s\n " first_16 ; match utf8_of_utf16_unsafe (String.length first_16 - 1) first_16 with | Normal first_8 -> ( let rec keep_reading num so_far = match readdir_find_next_file_utf16 h with | Normal next_16 -> ( Printf.printf " Got next 16 : % s\n " next_16 ; match utf8_of_utf16_unsafe (String.length next_16 - 1) next_16 with | Normal "." | Normal ".." -> keep_reading num so_far | Normal next_8 -> ( keep_reading (succ num) (next_8 :: so_far) ) | Error e -> Error e ) | Error e -> Error e in let got_list = if first_8 = "." || first_8 = ".." then ( keep_reading 0 [] ) else ( keep_reading 1 [first_8] ) in match got_list with | Normal (num, got) -> ( let out_array = Array.make num "" in let rec keep_putting n = function | [] -> () | hd :: tl -> ( out_array.(n) <- hd; keep_putting (pred n) tl ) in keep_putting (pred num) got; out_array ) | Error e -> ( ignore (readdir_find_close h); failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) ) | Error e -> ( ignore (readdir_find_close h); failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) ) | Error e -> failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) | Error e -> failwith (Printf.sprintf "Unicode.readdir_utf8 got Windows error %d" e) ) ) else ( Sys.readdir );; external stat_utf16_unsafe : string -> Unix.stats t = "uni_stat_utf16";; let stat_utf8 = if win then ( fun name -> ( match utf16_of_utf8 ~include_null:true name with | Normal name16 -> ( match stat_utf16_unsafe name16 with | Normal s -> s | Error _ -> raise Not_found ) | Error _ -> invalid_arg "Unicode.stat_utf8" ) ) else ( Unix.stat );; external file_exists_utf16_unsafe : string -> bool = "uni_file_exists_utf16";; let file_exists_utf8 = if win then ( fun n -> ( match utf16_of_utf8 ~include_null:true n with | Normal wn -> file_exists_utf16_unsafe wn | Error e -> failwith (Printf.sprintf "Unicode.file_exists_utf8 got Windows error %d" e) ) ) else ( Sys.file_exists );; external rename_utf16_unsafe : string -> string -> unit t = "uni_rename_utf16";; let rename_utf8 = if win then ( fun n1 n2 -> ( match (utf16_of_utf8 ~include_null:true n1, utf16_of_utf8 ~include_null:true n2) with | (Normal wn1, Normal wn2) -> (match rename_utf16_unsafe wn1 wn2 with | Normal () -> () | Error e -> failwith (Printf.sprintf "Unicode.rename_utf8 got Windows error %d" e) ) | (Error e, _) -> failwith (Printf.sprintf "Unicode.rename_utf8 got Windows error %d" e) | (_, Error e) -> failwith (Printf.sprintf "Unicode.rename_utf8 got Windows error %d" e) ) ) else ( Sys.rename );; external remove_utf16_unsafe : string -> unit t = "uni_remove_utf16";; let remove_utf8 = if win then ( fun f -> (match utf16_of_utf8 ~include_null:true f with | Normal f16 -> ( match remove_utf16_unsafe f16 with | Normal () -> () | Error e -> failwith (Printf.sprintf "Unicode.remove_utf8 got Windows error %d" e) ) | Error e -> failwith (Printf.sprintf "Unicode.remove_utf8 got Windows error %d" e) ) ) else ( Sys.remove );;
5eca82e4f3982e2d9a7c9654211cb16840c337917d3f90eb1b27ebcd493b10c6
fossas/fossa-cli
Extra.hs
module Algebra.Graph.AdjacencyMap.Extra ( gtraverse, shrink, shrinkSingle, splitGraph, ) where import Algebra.Graph.AdjacencyMap qualified as AM import Algebra.Graph.AdjacencyMap.Algorithm qualified as AMA import Data.Set (Set) import Data.Set qualified as Set -- | It's 'traverse', but for graphs -- -- It's also unlawful. 'f' might be called several times for each node in the graph gtraverse :: (Applicative f, Ord b) => (a -> f b) -> AM.AdjacencyMap a -> f (AM.AdjacencyMap b) gtraverse f = fmap mkAdjacencyMap . traverse (\(a, xs) -> (,) <$> f a <*> traverse f xs) . AM.adjacencyList where mkAdjacencyMap :: Ord c => [(c, [c])] -> AM.AdjacencyMap c mkAdjacencyMap = AM.fromAdjacencySets . fmap (fmap Set.fromList) | Filter vertices in an AdjacencyMap , preserving the overall structure by rewiring edges through deleted vertices . -- For example , given the graph @1 - > 2 - > 3 - > 4@ and applying @shrink ( /= 3)@ , we return the graph @1 - > 2 - > 4@ shrink :: Ord a => (a -> Bool) -> AM.AdjacencyMap a -> AM.AdjacencyMap a shrink f gr = foldr shrinkSingle gr filteredOutVertices where filteredOutVertices = filter (not . f) (AM.vertexList gr) | Delete a vertex in an AdjacencyMap , preserving the overall structure by rewiring edges through the delted vertex . -- For example , given the graph @1 - > 2 - > 3 - > 4@ and applying @shrinkSingle 3@ , we return the graph @1 - > 2 - > 4@ shrinkSingle :: forall a. Ord a => a -> AM.AdjacencyMap a -> AM.AdjacencyMap a shrinkSingle vert gr = AM.overlay (AM.removeVertex vert gr) inducedEdges where -- If @vert@ has an edge to itself, it would be added back in by @overlay@ -- as an induced edge so delete vert from it's pre/post set inducedEdges :: AM.AdjacencyMap a inducedEdges = AM.edges [ (pre, post) | pre <- Set.toList . Set.delete vert $ AM.preSet vert gr , post <- Set.toList . Set.delete vert $ AM.postSet vert gr ] -- | Split graph into distinct sibling graphs (unconnected subgraphs) via nodes -- that have no incoming edges. Returns 'Nothing' if graph is cyclic. -- -- @ splitGraph ' edges ' [ ( 1 , 2 ) , ( 2 , 3 ) , ( 4 , 5 ) ] = [ ' edges ' [ ( 1 , 2 ) , ( 2 , 3 ) ] , ' edge ' 4 5 ] -- @ splitGraph :: Ord a => AM.AdjacencyMap a -> Maybe [AM.AdjacencyMap a] splitGraph gr = if AMA.isAcyclic gr then Just $ splitAcyclicGraph gr else Nothing -- | The internals of splitGraph, but only for acyclic graphs. Results for -- cyclic graphs are unspecified. splitAcyclicGraph :: Ord a => AM.AdjacencyMap a -> [AM.AdjacencyMap a] splitAcyclicGraph gr = case AM.vertexList $ AM.induce (\x -> Set.null $ AM.preSet x gr) gr of [] -> [gr] tops -> map (`takeReachable` gr) tops takeReachable :: forall a. Ord a => a -> AM.AdjacencyMap a -> AM.AdjacencyMap a takeReachable x gr = AM.induce (`Set.member` vertices) gr where vertices :: Set a vertices = Set.fromList $ AMA.reachable gr x
null
https://raw.githubusercontent.com/fossas/fossa-cli/cddea296c88ddc021913c7d0222a53948b6f1893/src/Algebra/Graph/AdjacencyMap/Extra.hs
haskell
| It's 'traverse', but for graphs It's also unlawful. 'f' might be called several times for each node in the graph If @vert@ has an edge to itself, it would be added back in by @overlay@ as an induced edge so delete vert from it's pre/post set | Split graph into distinct sibling graphs (unconnected subgraphs) via nodes that have no incoming edges. Returns 'Nothing' if graph is cyclic. @ @ | The internals of splitGraph, but only for acyclic graphs. Results for cyclic graphs are unspecified.
module Algebra.Graph.AdjacencyMap.Extra ( gtraverse, shrink, shrinkSingle, splitGraph, ) where import Algebra.Graph.AdjacencyMap qualified as AM import Algebra.Graph.AdjacencyMap.Algorithm qualified as AMA import Data.Set (Set) import Data.Set qualified as Set gtraverse :: (Applicative f, Ord b) => (a -> f b) -> AM.AdjacencyMap a -> f (AM.AdjacencyMap b) gtraverse f = fmap mkAdjacencyMap . traverse (\(a, xs) -> (,) <$> f a <*> traverse f xs) . AM.adjacencyList where mkAdjacencyMap :: Ord c => [(c, [c])] -> AM.AdjacencyMap c mkAdjacencyMap = AM.fromAdjacencySets . fmap (fmap Set.fromList) | Filter vertices in an AdjacencyMap , preserving the overall structure by rewiring edges through deleted vertices . For example , given the graph @1 - > 2 - > 3 - > 4@ and applying @shrink ( /= 3)@ , we return the graph @1 - > 2 - > 4@ shrink :: Ord a => (a -> Bool) -> AM.AdjacencyMap a -> AM.AdjacencyMap a shrink f gr = foldr shrinkSingle gr filteredOutVertices where filteredOutVertices = filter (not . f) (AM.vertexList gr) | Delete a vertex in an AdjacencyMap , preserving the overall structure by rewiring edges through the delted vertex . For example , given the graph @1 - > 2 - > 3 - > 4@ and applying @shrinkSingle 3@ , we return the graph @1 - > 2 - > 4@ shrinkSingle :: forall a. Ord a => a -> AM.AdjacencyMap a -> AM.AdjacencyMap a shrinkSingle vert gr = AM.overlay (AM.removeVertex vert gr) inducedEdges where inducedEdges :: AM.AdjacencyMap a inducedEdges = AM.edges [ (pre, post) | pre <- Set.toList . Set.delete vert $ AM.preSet vert gr , post <- Set.toList . Set.delete vert $ AM.postSet vert gr ] splitGraph ' edges ' [ ( 1 , 2 ) , ( 2 , 3 ) , ( 4 , 5 ) ] = [ ' edges ' [ ( 1 , 2 ) , ( 2 , 3 ) ] , ' edge ' 4 5 ] splitGraph :: Ord a => AM.AdjacencyMap a -> Maybe [AM.AdjacencyMap a] splitGraph gr = if AMA.isAcyclic gr then Just $ splitAcyclicGraph gr else Nothing splitAcyclicGraph :: Ord a => AM.AdjacencyMap a -> [AM.AdjacencyMap a] splitAcyclicGraph gr = case AM.vertexList $ AM.induce (\x -> Set.null $ AM.preSet x gr) gr of [] -> [gr] tops -> map (`takeReachable` gr) tops takeReachable :: forall a. Ord a => a -> AM.AdjacencyMap a -> AM.AdjacencyMap a takeReachable x gr = AM.induce (`Set.member` vertices) gr where vertices :: Set a vertices = Set.fromList $ AMA.reachable gr x
0176c601a4ca1d935530c1946fe07e76d9f33386f5874d09e394eaf9656ee28a
dannypsnl/sauron
editor.rkt
#lang racket/gui (provide tool@) (require drracket/tool framework) (define-unit tool@ (import drracket:tool^) (export drracket:tool-exports^) (define (phase1) (void)) (define (phase2) (void)) (define drracket-editor-mixin (mixin (drracket:unit:definitions-text<%> racket:text<%>) () (super-new) (define/augment (on-save-file filename format) (remove-trailing-whitespace-all) (send this tabify-all)) (define/private (remove-trailing-whitespace-all) (remove-trailing-whitespace-select 0 (send this last-position))) (define/private (remove-trailing-whitespace-select [start (send this get-start-position)] [end (send this get-end-position)]) (define first-para (send this position-paragraph start)) (define end-para (send this position-paragraph end)) (define modifying-multiple-paras? (not (= first-para end-para))) (with-handlers ([exn:break? (λ (x) #t)]) (dynamic-wind (λ () (when (< first-para end-para) (begin-busy-cursor)) (send this begin-edit-sequence)) (λ () (define skip-this-line? #f) (let loop ([para first-para]) (when (<= para end-para) (define start (send this paragraph-start-position para)) (define end (send this paragraph-end-position para)) (for ([i (range start (add1 end))]) (when (and (char=? #\" (send this get-character i)) (not (char=? #\\ (send this get-character (sub1 i))))) (set! skip-this-line? (not skip-this-line?)))) (set! skip-this-line? (and modifying-multiple-paras? skip-this-line?)) (unless skip-this-line? (remove-trailing-whitespace start)) (parameterize-break #t (void)) (loop (add1 para)))) (when (and (>= (send this position-paragraph start) end-para) (<= (send this skip-whitespace (send this get-start-position) 'backward #f) (send this paragraph-start-position first-para))) (send this set-position (let loop ([new-pos (send this get-start-position)]) (if (let ([next (send this get-character new-pos)]) (and (char-whitespace? next) (not (char=? next #\newline)))) (loop (add1 new-pos)) new-pos))))) (λ () (send this end-edit-sequence) (when (< first-para end-para) (end-busy-cursor)))))) (define (remove-trailing-whitespace [pos (send this get-start-position)]) (define line (send this position-line pos)) (define line-start (send this line-start-position line)) (define line-end (send this line-end-position line)) (define (do-remove line) (define para (send this position-paragraph pos)) (define end (send this paragraph-start-position para)) (send this delete line-start line-end) (send this insert (string-trim line #px"\\s+" #:left? #f) end)) (do-remove (send this get-text line-start line-end))))) (drracket:get/extend:extend-definitions-text drracket-editor-mixin))
null
https://raw.githubusercontent.com/dannypsnl/sauron/1d1d0e263e104251b44b2baa7741869374e922e1/tool/editor.rkt
racket
#lang racket/gui (provide tool@) (require drracket/tool framework) (define-unit tool@ (import drracket:tool^) (export drracket:tool-exports^) (define (phase1) (void)) (define (phase2) (void)) (define drracket-editor-mixin (mixin (drracket:unit:definitions-text<%> racket:text<%>) () (super-new) (define/augment (on-save-file filename format) (remove-trailing-whitespace-all) (send this tabify-all)) (define/private (remove-trailing-whitespace-all) (remove-trailing-whitespace-select 0 (send this last-position))) (define/private (remove-trailing-whitespace-select [start (send this get-start-position)] [end (send this get-end-position)]) (define first-para (send this position-paragraph start)) (define end-para (send this position-paragraph end)) (define modifying-multiple-paras? (not (= first-para end-para))) (with-handlers ([exn:break? (λ (x) #t)]) (dynamic-wind (λ () (when (< first-para end-para) (begin-busy-cursor)) (send this begin-edit-sequence)) (λ () (define skip-this-line? #f) (let loop ([para first-para]) (when (<= para end-para) (define start (send this paragraph-start-position para)) (define end (send this paragraph-end-position para)) (for ([i (range start (add1 end))]) (when (and (char=? #\" (send this get-character i)) (not (char=? #\\ (send this get-character (sub1 i))))) (set! skip-this-line? (not skip-this-line?)))) (set! skip-this-line? (and modifying-multiple-paras? skip-this-line?)) (unless skip-this-line? (remove-trailing-whitespace start)) (parameterize-break #t (void)) (loop (add1 para)))) (when (and (>= (send this position-paragraph start) end-para) (<= (send this skip-whitespace (send this get-start-position) 'backward #f) (send this paragraph-start-position first-para))) (send this set-position (let loop ([new-pos (send this get-start-position)]) (if (let ([next (send this get-character new-pos)]) (and (char-whitespace? next) (not (char=? next #\newline)))) (loop (add1 new-pos)) new-pos))))) (λ () (send this end-edit-sequence) (when (< first-para end-para) (end-busy-cursor)))))) (define (remove-trailing-whitespace [pos (send this get-start-position)]) (define line (send this position-line pos)) (define line-start (send this line-start-position line)) (define line-end (send this line-end-position line)) (define (do-remove line) (define para (send this position-paragraph pos)) (define end (send this paragraph-start-position para)) (send this delete line-start line-end) (send this insert (string-trim line #px"\\s+" #:left? #f) end)) (do-remove (send this get-text line-start line-end))))) (drracket:get/extend:extend-definitions-text drracket-editor-mixin))
8cb81276c2333857f4468e02c5986a5abeb851b6675e5a9a5304933f7d28ad19
alvatar/spheres
c-define-array#.scm
! Build FFI procedures for C type arrays . Only for use with basic types , not structs . ;; (c-define-array float f32) -> ;; alloc-float* ;; float*-ref ;; float*-set! ;; *->float* ;; f32vector->float* (define-macro (c-define-array scheme-type . rest) (let ((c-type (%%get-key-arg rest c-type: scheme-type)) (scheme-vector (%%get-key-arg rest scheme-vector: #f))) (if (not scheme-vector) (error "c-define-array macro :: scheme-vector: argument is mandatory")) (let ((release-type-str (string-append "___release_" (%%scheme-name->c-name scheme-type))) (type scheme-type) (type* (%%generic-symbol-append scheme-type "*")) (type*/nonnull (%%generic-symbol-append scheme-type "*/nonnull")) (type*/release-rc (%%generic-symbol-append scheme-type "*/release-rc"))) (let ((expansion (%%begin-top-level-forms `(c-declare ,(string-append "static ___SCMOBJ " release-type-str "( void* ptr )\n" "{\n" " printf(\"GC called free()!\\n\");\n " " _ _ _ EXT(___release_rc ) ( ptr ) ; \n " " free( ptr );\n" " return ___FIX(___NO_ERR);\n" "}\n")) Alloc managed by Gambit 's GC `(define ,(%%generic-symbol-append 'alloc- scheme-type '*/unmanaged) (c-lambda (size-t) ,type*/nonnull ,(%%generic-string-append "___result_voidstar = malloc(___arg1*sizeof(" c-type "));"))) Alloc unmanaged by Gambit 's GC `(define ,(%%generic-symbol-append 'alloc- scheme-type '*) (c-lambda (size-t) ,type*/release-rc ;; ,(%%generic-string-append "___result_voidstar = ___EXT(___alloc_rc)(___arg1*sizeof(" c-type "));") ,(%%generic-string-append "___result_voidstar = malloc(___arg1*sizeof(" c-type "));"))) `(define ,(%%generic-symbol-append scheme-type '*-ref) (c-lambda (,type*/nonnull size-t) ,scheme-type "___result = ___arg1[___arg2];")) `(define ,(%%generic-symbol-append scheme-type '*-set!) (c-lambda (,type*/nonnull size-t ,scheme-type) void "___arg1[___arg2] = ___arg3;")) `(define ,(%%generic-symbol-append '*-> scheme-type) (c-lambda (,type*/nonnull) ,scheme-type "___result = *___arg1;")) (if scheme-vector `(define (,(%%generic-symbol-append scheme-vector 'vector-> scheme-type '*) vec) (let* ((length (,(%%generic-symbol-append scheme-vector 'vector-length) vec)) (buf (,(%%generic-symbol-append 'alloc- scheme-type '*) length))) (let loop ((i 0)) (if (fx< i length) (begin (,(%%generic-symbol-append scheme-type '*-set!) buf i (,(%%generic-symbol-append scheme-vector 'vector-ref) vec i)) (loop (fx+ i 1))) buf)))) '())))) (if #f ;; #t for debugging (pp `(definition: (c-define-array scheme-type: ,scheme-type c-type: ,c-type scheme-vector: ,scheme-vector) expansion: ,expansion))) expansion))))
null
https://raw.githubusercontent.com/alvatar/spheres/568836f234a469ef70c69f4a2d9b56d41c3fc5bd/spheres/gambit/ffi/c-define-array%23.scm
scheme
(c-define-array float f32) -> alloc-float* float*-ref float*-set! *->float* f32vector->float* ,(%%generic-string-append "___result_voidstar = ___EXT(___alloc_rc)(___arg1*sizeof(" c-type "));") #t for debugging
! Build FFI procedures for C type arrays . Only for use with basic types , not structs . (define-macro (c-define-array scheme-type . rest) (let ((c-type (%%get-key-arg rest c-type: scheme-type)) (scheme-vector (%%get-key-arg rest scheme-vector: #f))) (if (not scheme-vector) (error "c-define-array macro :: scheme-vector: argument is mandatory")) (let ((release-type-str (string-append "___release_" (%%scheme-name->c-name scheme-type))) (type scheme-type) (type* (%%generic-symbol-append scheme-type "*")) (type*/nonnull (%%generic-symbol-append scheme-type "*/nonnull")) (type*/release-rc (%%generic-symbol-append scheme-type "*/release-rc"))) (let ((expansion (%%begin-top-level-forms `(c-declare ,(string-append "static ___SCMOBJ " release-type-str "( void* ptr )\n" "{\n" " printf(\"GC called free()!\\n\");\n " " _ _ _ EXT(___release_rc ) ( ptr ) ; \n " " free( ptr );\n" " return ___FIX(___NO_ERR);\n" "}\n")) Alloc managed by Gambit 's GC `(define ,(%%generic-symbol-append 'alloc- scheme-type '*/unmanaged) (c-lambda (size-t) ,type*/nonnull ,(%%generic-string-append "___result_voidstar = malloc(___arg1*sizeof(" c-type "));"))) Alloc unmanaged by Gambit 's GC `(define ,(%%generic-symbol-append 'alloc- scheme-type '*) (c-lambda (size-t) ,type*/release-rc ,(%%generic-string-append "___result_voidstar = malloc(___arg1*sizeof(" c-type "));"))) `(define ,(%%generic-symbol-append scheme-type '*-ref) (c-lambda (,type*/nonnull size-t) ,scheme-type "___result = ___arg1[___arg2];")) `(define ,(%%generic-symbol-append scheme-type '*-set!) (c-lambda (,type*/nonnull size-t ,scheme-type) void "___arg1[___arg2] = ___arg3;")) `(define ,(%%generic-symbol-append '*-> scheme-type) (c-lambda (,type*/nonnull) ,scheme-type "___result = *___arg1;")) (if scheme-vector `(define (,(%%generic-symbol-append scheme-vector 'vector-> scheme-type '*) vec) (let* ((length (,(%%generic-symbol-append scheme-vector 'vector-length) vec)) (buf (,(%%generic-symbol-append 'alloc- scheme-type '*) length))) (let loop ((i 0)) (if (fx< i length) (begin (,(%%generic-symbol-append scheme-type '*-set!) buf i (,(%%generic-symbol-append scheme-vector 'vector-ref) vec i)) (loop (fx+ i 1))) buf)))) '())))) (pp `(definition: (c-define-array scheme-type: ,scheme-type c-type: ,c-type scheme-vector: ,scheme-vector) expansion: ,expansion))) expansion))))
b62b57907c140763ae51614fed35a00098778e7480b2f1cb08dbe81dd35f7d01
ygrek/opam-bundle
main.ml
open Printf open OpamTypes let match_package_atom nv (name,cstr) = OpamPackage.Name.compare (OpamPackage.name nv) name = 0 && match cstr with | None -> true | Some (relop,version) -> OpamFormula.eval_relop relop (OpamPackage.version nv) version let resolve_deps t atoms = let atoms = OpamSolution.sanitize_atom_list t ~permissive:true atoms in let action = Install (OpamPackage.Name.Set.of_list (List.map fst atoms)) in let universe = { (OpamState.universe t action) with u_installed = OpamPackage.Set.empty; } in let request = { wish_install = atoms; wish_remove = []; wish_upgrade = []; criteria = `Default; extra_attributes = []; } in match OpamSolver.resolve ~verbose:true universe ~orphans:OpamPackage.Set.empty request with | Success solution -> (* OpamSolver.new_packages, but return in order *) let l = OpamSolver.ActionGraph.Topological.fold (fun act acc -> match act with | `Install p | `Change (_,_,p) -> p :: acc | `Reinstall _ | `Remove _ | `Build _ -> acc) (OpamSolver.get_atomic_action_graph solution) [] in List.rev l | Conflicts cs -> OpamConsole.error_and_exit "Conflicts: %s" (OpamCudf.string_of_conflict (OpamState.unavailable_reason t) cs) * see OpamState.install_compiler let bundle_compiler ~dryrun ( t : OpamState.state ) archive = let open OpamFilename in let repo_name = Option.map_default ( fun ( r , _ ) - > OpamRepositoryName.to_string ) " unknown repo " ( OpamState.repository_and_prefix_of_compiler t t.compiler ) in OpamConsole.msg " Bundling compiler % s [ % s]\n " ( OpamCompiler.to_string t.compiler ) repo_name ; let comp_f = OpamPath.compiler_comp t.root t.compiler in match exists comp_f with | false - > OpamConsole.error_and_exit " Can not bundle compiler % s : no such file : % s " ( OpamCompiler.to_string t.compiler ) ( to_string comp_f ) ; | true - > let comp = OpamFile.Comp.read comp_f in match OpamFile.Comp.preinstalled comp with | true - > OpamConsole.error_and_exit " Can not bundle preinstalled compiler % s " ( OpamCompiler.to_string t.compiler ) | false - > match OpamFile.Comp.configure comp @ OpamFile.Comp.make comp < > [ ] with | true - > assert false ( * old style comp file - not supported let bundle_compiler ~reuse ~dryrun (t:OpamState.state) archive = let open OpamFilename in let repo_name = Option.map_default (fun (r,_) -> OpamRepositoryName.to_string r.repo_name) "unknown repo" (OpamState.repository_and_prefix_of_compiler t t.compiler) in OpamConsole.msg "Bundling compiler %s [%s]\n" (OpamCompiler.to_string t.compiler) repo_name; let comp_f = OpamPath.compiler_comp t.root t.compiler in match exists comp_f with | false -> OpamConsole.error_and_exit "Cannot bundle compiler %s: no such file : %s" (OpamCompiler.to_string t.compiler) (to_string comp_f); | true -> let comp = OpamFile.Comp.read comp_f in match OpamFile.Comp.preinstalled comp with | true -> OpamConsole.error_and_exit "Cannot bundle preinstalled compiler %s" (OpamCompiler.to_string t.compiler) | false -> match OpamFile.Comp.configure comp @ OpamFile.Comp.make comp <> [] with | true -> assert false (* old style comp file - not supported *) | false -> (* Install the compiler *) match OpamFile.Comp.src comp with | None -> OpamConsole.error_and_exit "No source for compiler %s" (OpamCompiler.to_string t.compiler) | Some comp_src -> match dryrun with | true -> None | false -> let build_dir = OpamPath.Switch.build_ocaml t.root t.switch in let return = Some (basename_dir build_dir, comp) in match reuse && exists archive with | true -> OpamConsole.msg "Reusing %s\n" (to_string archive); return | false -> let open OpamProcess.Job.Op in let kind = OpamFile.Comp.kind comp in if kind = `local && Sys.file_exists (fst comp_src) && Sys.is_directory (fst comp_src) then OpamFilename.link_dir ~src:(OpamFilename.Dir.of_string (fst comp_src)) ~dst:build_dir else OpamProcess.Job.run @@ OpamFilename.with_tmp_dir_job begin fun download_dir -> OpamRepository.pull_url kind (OpamPackage.of_string "compiler.get") download_dir None [comp_src] @@| function | Not_available u -> OpamConsole.error_and_exit "%s is not available." u | Up_to_date r | Result r -> OpamFilename.extract_generic_file r build_dir end; let patches = OpamFile.Comp.patches comp in let patches = List.map (fun f -> OpamFilename.download ~overwrite:true f build_dir ) patches in List.iter (fun f -> OpamFilename.patch f build_dir) patches; (exec (dirname_dir build_dir) [ [ "tar"; "czf"; (to_string archive); Base.to_string (basename_dir build_dir) ] ]); return *) let bundle ~reuse ~dryrun ~deps_only ~with_compiler bundle atoms = let open OpamFilename in (* OpamSystem.real_path is pure evil *) let bundle = let open OpamFilename in if Filename.is_relative @@ Dir.to_string bundle then Op.(cwd () / Dir.to_string bundle) else bundle in let archives = OpamFilename.Op.(bundle / "archives") in if not dryrun && not reuse && exists_dir bundle then OpamConsole.error_and_exit "Directory %s already exists" (Dir.to_string bundle); let root = OpamStateConfig.opamroot () in OpamFormatConfig.init (); match OpamStateConfig.load_defaults root with | false -> OpamConsole.error_and_exit "Failed init" | true -> OpamStateConfig.init ~root_dir:root (); OpamRepositoryConfig.init (); OpamSolverConfig.init (); OpamStd.Config.init (); let t = OpamState.load_state "bundle" OpamStateConfig.(!r.current_switch) in let atoms = ( OpamPackage . Name.of_string " opam " , None ) : : atoms in let atoms = OpamSolution.sanitize_atom_list ~permissive:true t atoms in let packages = resolve_deps t atoms in let packages = match deps_only with | false -> packages | true -> List.filter (fun nv -> not (List.exists (match_package_atom nv) atoms)) packages in sync : variables and OpamPath . Switch directories let root_dirs = [ "lib"; "bin"; "sbin"; "man"; "doc"; "share"; "etc" ] in let variables = let vars1 = List.map (fun k -> OpamVariable.(of_string k, S (Filename.concat "$BUNDLE_PREFIX" k))) root_dirs in let vars2 = OpamVariable.([ of_string "prefix", S "$BUNDLE_PREFIX"; of_string "stublibs", S "$BUNDLE_PREFIX/lib/stublibs"; of_string "preinstalled", B (not with_compiler); of_string "make", S "$MAKE"; ]) in OpamVariable.Map.of_list @@ List.map (fun (k,v) -> k, Some v) (vars1 @ vars2) in let b = Buffer.create 10 in (* expecting quoted commands *) let shellout_build ?dir ~archive ~env commands = let archive_name = Filename.chop_suffix archive ".tar.gz" in let dir = Option.default archive_name dir in let pr fmt = ksprintf (fun s -> Buffer.add_string b (s ^ "\n")) fmt in pr "("; pr "echo BUILD %s" archive_name; pr "cd build"; pr "rm -rf %s" dir; pr "tar -xzf ../archives/%s" archive; pr "cd %s" dir; List.iter (fun (k,v) -> pr "export %s=%s" k v) env; List.iter (fun args -> pr "%s" (String.concat " " args)) commands; pr ")" in List.iter (fun s -> Buffer.add_string b (s^"\n")) [ "#! /bin/sh"; "set -eu"; ": ${BUNDLE_PREFIX=$(pwd)/local}"; ": ${MAKE=make}"; "mkdir -p build $BUNDLE_PREFIX " ^ (String.concat " " (List.map (Filename.concat "$BUNDLE_PREFIX") root_dirs)) ^ " $BUNDLE_PREFIX/lib/stublibs"; "export PATH=$BUNDLE_PREFIX/bin:$PATH"; "export CAML_LD_LIBRARY_PATH=$BUNDLE_PREFIX/lib/stublibs:${CAML_LD_LIBRARY_PATH:-}"; ]; if not dryrun then List.iter mkdir [bundle; archives]; if with_compiler then begin OpamConsole.msg "compiler bundling - not implemented"; let archive = " ocaml . " ^ ( OpamCompiler.to_string t.compiler ) ^ " .tar.gz " in let archive_path = OP.(archives // archive ) in match bundle_compiler ~reuse ~dryrun t archive_path with | None - > ( ) | Some ( dir , comp ) - > let env = OpamState.add_to_env t [ ] ( OpamFile.Comp.env comp ) variables in let commands = OpamState.filter_commands t variables ( OpamFile.Comp.build comp ) in let commands = ( fun l - > l @ [ " > > build.log 2>>build.log || ( echo FAILED ; tail build.log ; exit 1 ) " ] ) commands in ) ~archive ~env commands let archive = "ocaml." ^ (OpamCompiler.to_string t.compiler) ^ ".tar.gz" in let archive_path = OP.(archives // archive) in match bundle_compiler ~reuse ~dryrun t archive_path with | None -> () | Some (dir,comp) -> let env = OpamState.add_to_env t [] (OpamFile.Comp.env comp) variables in let commands = OpamState.filter_commands t variables (OpamFile.Comp.build comp) in let commands = List.map (fun l -> l @ [">>build.log 2>>build.log || (echo FAILED; tail build.log; exit 1)"]) commands in shellout_build ~dir:(Base.to_string dir) ~archive ~env commands *) end; List.iter begin fun nv -> try let repo_name = Option.map_default (fun r -> OpamRepositoryName.to_string r.OpamTypes.repo_name) "unknown repo" (OpamState.repository_of_package t nv) in OpamConsole.msg "Bundling %s [%s]\n" (OpamPackage.to_string nv) repo_name; match dryrun with | true -> () | false -> let archive = OpamFilename.Op.(archives // (OpamPackage.to_string nv ^ ".tar.gz")) in if reuse && exists archive then begin OpamConsole.msg "Reusing %s\n" (to_string archive) end else begin (* gets the source (from url, local path, git, etc) and applies patches and substitutions *) match OpamProcess.Job.run (OpamAction.download_package t nv) with | `Error s -> OpamConsole.error_and_exit "Download failed : %s" s | `Successful s -> OpamAction.extract_package t s nv; let p_build = OpamPath.Switch.build t.root t.switch nv in OpamConsole.msg " p_build : % s\n " ( OpamFilename . ) ; OpamConsole.msg " archives : % s\n " ( OpamFilename . Dir.to_string archives ) ; OpamConsole.msg " archive : % s\n " ( OpamFilename.to_string archive ) ; OpamConsole.msg "p_build: %s\n" (OpamFilename.Dir.to_string p_build); OpamConsole.msg "archives: %s\n" (OpamFilename.Dir.to_string archives); OpamConsole.msg "archive: %s\n" (OpamFilename.to_string archive); *) exec (dirname_dir p_build) [ [ "tar"; "czf"; to_string archive; Base.to_string (basename_dir p_build) ] ]; end; let archive = Base.to_string (basename archive) in let opam = OpamState.opam t nv in (* dev? *) let env = OpamState.add_to_env t ~opam [] (OpamFile.OPAM.build_env opam) ~variables in let commands = OpamFile.OPAM.build opam @ OpamFile.OPAM.install opam in let commands = OpamFilter.commands (OpamState.filter_env t ~opam ~local_variables:variables) commands in let commands = List.map (fun l -> l @ [">>build.log 2>>build.log || (echo FAILED; tail build.log; exit 1)"]) commands in let install_commands = let name = OpamPackage.(Name.to_string @@ name nv) in [ [ sprintf "if [ -f \"%s.install\" ] ; then opam-installer --prefix \"$BUNDLE_PREFIX\" \"%s.install\" ; fi" name name ] ] in shellout_build ~archive ~env (commands @ install_commands); with e -> OpamStd.Exn.fatal e; OpamConsole.error_and_exit "%s" (Printexc.to_string e); end packages; match dryrun with | true -> () | false -> let install_sh = OpamFilename.Op.(bundle // "install.sh") in write install_sh (Buffer.contents b); chmod install_sh 0o755; () let cmd = let open Cmdliner in / various bits from OpamArg let dirname = let parse str = `Ok (OpamFilename.Dir.of_string str) in let print ppf dir = Format.pp_print_string ppf (OpamFilename.prettify_dir dir) in parse, print in let nonempty_arg_list name doc conv = let doc = Arg.info ~docv:name ~doc [] in Arg.(non_empty & pos_all conv [] & doc) in (* name * version constraint *) let atom = let parse str = let re = Re_str.regexp "\\([^>=<.!]+\\)\\(>=?\\|<=?\\|=\\|\\.\\|!=\\)\\(.*\\)" in try if not (Re_str.string_match re str 0) then failwith "no_version"; let sname = Re_str.matched_group 1 str in let sop = Re_str.matched_group 2 str in let sversion = Re_str.matched_group 3 str in let name = OpamPackage.Name.of_string sname in let sop = if sop = "." then "=" else sop in let op = OpamFormula.relop_of_string sop in (* may raise Invalid_argument *) let version = OpamPackage.Version.of_string sversion in `Ok (name, Some (op, version)) with Failure _ | Invalid_argument _ -> try `Ok (OpamPackage.Name.of_string str, None) with Failure msg -> `Error msg in let print ppf atom = Format.pp_print_string ppf (OpamFormula.short_string_of_atom atom) in parse, print in let nonempty_atom_list = nonempty_arg_list "PACKAGES" "List of package names, with an optional version or constraint, \ e.g `pkg', `pkg.1.0' or `pkg>=0.5'." atom in (* / *) let doc = "Generate a self-contained bundle of given packages with all dependencies." in let man = [ `S "DESCRIPTION"; `P "This command calculates the transitive dependencies of the given packages \ and collects all the corresponding archives into a specified directory, \ along with the shell script to unpack, build and install those packages \ on any remote machine (even without OPAM installed)."; ] in let outdir = let doc = Arg.info ["o";"outdir"] ~docv:"DIR" ~doc:"Write bundle to the directory $(docv)." in Arg.(value & opt dirname (OpamFilename.Dir.of_string "bundle") & doc) in let deps_only = Arg.(value & flag & info ["deps-only"] ~doc:"Bundle only the dependencies, excluding the specified packages.") in let dryrun = Arg.(value & flag & info ["dry-run"] ~doc:"Do not actually create bundle, only show actions to be done.") in let with_compiler = Arg.(value & flag & info ["with-compiler"] ~doc:"Bundle the compiler too") in let reuse = let doc = "Allow reusing archives already bundled in the output directory (no checking performed, can be useful to \ skip redownloading compiler sources)" in Arg.(value & flag & info ["reuse"] ~doc) in let bundle deps_only dryrun with_compiler reuse outdir names = bundle ~dryrun ~deps_only ~with_compiler ~reuse outdir names in Term.(pure bundle $deps_only $dryrun $with_compiler $reuse $outdir $nonempty_atom_list), Term.info "opam-bundle" ~doc ~man let () = match Cmdliner.Term.eval cmd with `Error _ -> exit 1 | _ -> exit 0
null
https://raw.githubusercontent.com/ygrek/opam-bundle/2d35ee077186a58bb5fd39a7890dbf6b3a4731f6/src/main.ml
ocaml
OpamSolver.new_packages, but return in order old style comp file - not supported Install the compiler OpamSystem.real_path is pure evil expecting quoted commands gets the source (from url, local path, git, etc) and applies patches and substitutions dev? name * version constraint may raise Invalid_argument /
open Printf open OpamTypes let match_package_atom nv (name,cstr) = OpamPackage.Name.compare (OpamPackage.name nv) name = 0 && match cstr with | None -> true | Some (relop,version) -> OpamFormula.eval_relop relop (OpamPackage.version nv) version let resolve_deps t atoms = let atoms = OpamSolution.sanitize_atom_list t ~permissive:true atoms in let action = Install (OpamPackage.Name.Set.of_list (List.map fst atoms)) in let universe = { (OpamState.universe t action) with u_installed = OpamPackage.Set.empty; } in let request = { wish_install = atoms; wish_remove = []; wish_upgrade = []; criteria = `Default; extra_attributes = []; } in match OpamSolver.resolve ~verbose:true universe ~orphans:OpamPackage.Set.empty request with | Success solution -> let l = OpamSolver.ActionGraph.Topological.fold (fun act acc -> match act with | `Install p | `Change (_,_,p) -> p :: acc | `Reinstall _ | `Remove _ | `Build _ -> acc) (OpamSolver.get_atomic_action_graph solution) [] in List.rev l | Conflicts cs -> OpamConsole.error_and_exit "Conflicts: %s" (OpamCudf.string_of_conflict (OpamState.unavailable_reason t) cs) * see OpamState.install_compiler let bundle_compiler ~dryrun ( t : OpamState.state ) archive = let open OpamFilename in let repo_name = Option.map_default ( fun ( r , _ ) - > OpamRepositoryName.to_string ) " unknown repo " ( OpamState.repository_and_prefix_of_compiler t t.compiler ) in OpamConsole.msg " Bundling compiler % s [ % s]\n " ( OpamCompiler.to_string t.compiler ) repo_name ; let comp_f = OpamPath.compiler_comp t.root t.compiler in match exists comp_f with | false - > OpamConsole.error_and_exit " Can not bundle compiler % s : no such file : % s " ( OpamCompiler.to_string t.compiler ) ( to_string comp_f ) ; | true - > let comp = OpamFile.Comp.read comp_f in match OpamFile.Comp.preinstalled comp with | true - > OpamConsole.error_and_exit " Can not bundle preinstalled compiler % s " ( OpamCompiler.to_string t.compiler ) | false - > match OpamFile.Comp.configure comp @ OpamFile.Comp.make comp < > [ ] with | true - > assert false ( * old style comp file - not supported let bundle_compiler ~reuse ~dryrun (t:OpamState.state) archive = let open OpamFilename in let repo_name = Option.map_default (fun (r,_) -> OpamRepositoryName.to_string r.repo_name) "unknown repo" (OpamState.repository_and_prefix_of_compiler t t.compiler) in OpamConsole.msg "Bundling compiler %s [%s]\n" (OpamCompiler.to_string t.compiler) repo_name; let comp_f = OpamPath.compiler_comp t.root t.compiler in match exists comp_f with | false -> OpamConsole.error_and_exit "Cannot bundle compiler %s: no such file : %s" (OpamCompiler.to_string t.compiler) (to_string comp_f); | true -> let comp = OpamFile.Comp.read comp_f in match OpamFile.Comp.preinstalled comp with | true -> OpamConsole.error_and_exit "Cannot bundle preinstalled compiler %s" (OpamCompiler.to_string t.compiler) | false -> match OpamFile.Comp.configure comp @ OpamFile.Comp.make comp <> [] with | false -> match OpamFile.Comp.src comp with | None -> OpamConsole.error_and_exit "No source for compiler %s" (OpamCompiler.to_string t.compiler) | Some comp_src -> match dryrun with | true -> None | false -> let build_dir = OpamPath.Switch.build_ocaml t.root t.switch in let return = Some (basename_dir build_dir, comp) in match reuse && exists archive with | true -> OpamConsole.msg "Reusing %s\n" (to_string archive); return | false -> let open OpamProcess.Job.Op in let kind = OpamFile.Comp.kind comp in if kind = `local && Sys.file_exists (fst comp_src) && Sys.is_directory (fst comp_src) then OpamFilename.link_dir ~src:(OpamFilename.Dir.of_string (fst comp_src)) ~dst:build_dir else OpamProcess.Job.run @@ OpamFilename.with_tmp_dir_job begin fun download_dir -> OpamRepository.pull_url kind (OpamPackage.of_string "compiler.get") download_dir None [comp_src] @@| function | Not_available u -> OpamConsole.error_and_exit "%s is not available." u | Up_to_date r | Result r -> OpamFilename.extract_generic_file r build_dir end; let patches = OpamFile.Comp.patches comp in let patches = List.map (fun f -> OpamFilename.download ~overwrite:true f build_dir ) patches in List.iter (fun f -> OpamFilename.patch f build_dir) patches; (exec (dirname_dir build_dir) [ [ "tar"; "czf"; (to_string archive); Base.to_string (basename_dir build_dir) ] ]); return *) let bundle ~reuse ~dryrun ~deps_only ~with_compiler bundle atoms = let open OpamFilename in let bundle = let open OpamFilename in if Filename.is_relative @@ Dir.to_string bundle then Op.(cwd () / Dir.to_string bundle) else bundle in let archives = OpamFilename.Op.(bundle / "archives") in if not dryrun && not reuse && exists_dir bundle then OpamConsole.error_and_exit "Directory %s already exists" (Dir.to_string bundle); let root = OpamStateConfig.opamroot () in OpamFormatConfig.init (); match OpamStateConfig.load_defaults root with | false -> OpamConsole.error_and_exit "Failed init" | true -> OpamStateConfig.init ~root_dir:root (); OpamRepositoryConfig.init (); OpamSolverConfig.init (); OpamStd.Config.init (); let t = OpamState.load_state "bundle" OpamStateConfig.(!r.current_switch) in let atoms = ( OpamPackage . Name.of_string " opam " , None ) : : atoms in let atoms = OpamSolution.sanitize_atom_list ~permissive:true t atoms in let packages = resolve_deps t atoms in let packages = match deps_only with | false -> packages | true -> List.filter (fun nv -> not (List.exists (match_package_atom nv) atoms)) packages in sync : variables and OpamPath . Switch directories let root_dirs = [ "lib"; "bin"; "sbin"; "man"; "doc"; "share"; "etc" ] in let variables = let vars1 = List.map (fun k -> OpamVariable.(of_string k, S (Filename.concat "$BUNDLE_PREFIX" k))) root_dirs in let vars2 = OpamVariable.([ of_string "prefix", S "$BUNDLE_PREFIX"; of_string "stublibs", S "$BUNDLE_PREFIX/lib/stublibs"; of_string "preinstalled", B (not with_compiler); of_string "make", S "$MAKE"; ]) in OpamVariable.Map.of_list @@ List.map (fun (k,v) -> k, Some v) (vars1 @ vars2) in let b = Buffer.create 10 in let shellout_build ?dir ~archive ~env commands = let archive_name = Filename.chop_suffix archive ".tar.gz" in let dir = Option.default archive_name dir in let pr fmt = ksprintf (fun s -> Buffer.add_string b (s ^ "\n")) fmt in pr "("; pr "echo BUILD %s" archive_name; pr "cd build"; pr "rm -rf %s" dir; pr "tar -xzf ../archives/%s" archive; pr "cd %s" dir; List.iter (fun (k,v) -> pr "export %s=%s" k v) env; List.iter (fun args -> pr "%s" (String.concat " " args)) commands; pr ")" in List.iter (fun s -> Buffer.add_string b (s^"\n")) [ "#! /bin/sh"; "set -eu"; ": ${BUNDLE_PREFIX=$(pwd)/local}"; ": ${MAKE=make}"; "mkdir -p build $BUNDLE_PREFIX " ^ (String.concat " " (List.map (Filename.concat "$BUNDLE_PREFIX") root_dirs)) ^ " $BUNDLE_PREFIX/lib/stublibs"; "export PATH=$BUNDLE_PREFIX/bin:$PATH"; "export CAML_LD_LIBRARY_PATH=$BUNDLE_PREFIX/lib/stublibs:${CAML_LD_LIBRARY_PATH:-}"; ]; if not dryrun then List.iter mkdir [bundle; archives]; if with_compiler then begin OpamConsole.msg "compiler bundling - not implemented"; let archive = " ocaml . " ^ ( OpamCompiler.to_string t.compiler ) ^ " .tar.gz " in let archive_path = OP.(archives // archive ) in match bundle_compiler ~reuse ~dryrun t archive_path with | None - > ( ) | Some ( dir , comp ) - > let env = OpamState.add_to_env t [ ] ( OpamFile.Comp.env comp ) variables in let commands = OpamState.filter_commands t variables ( OpamFile.Comp.build comp ) in let commands = ( fun l - > l @ [ " > > build.log 2>>build.log || ( echo FAILED ; tail build.log ; exit 1 ) " ] ) commands in ) ~archive ~env commands let archive = "ocaml." ^ (OpamCompiler.to_string t.compiler) ^ ".tar.gz" in let archive_path = OP.(archives // archive) in match bundle_compiler ~reuse ~dryrun t archive_path with | None -> () | Some (dir,comp) -> let env = OpamState.add_to_env t [] (OpamFile.Comp.env comp) variables in let commands = OpamState.filter_commands t variables (OpamFile.Comp.build comp) in let commands = List.map (fun l -> l @ [">>build.log 2>>build.log || (echo FAILED; tail build.log; exit 1)"]) commands in shellout_build ~dir:(Base.to_string dir) ~archive ~env commands *) end; List.iter begin fun nv -> try let repo_name = Option.map_default (fun r -> OpamRepositoryName.to_string r.OpamTypes.repo_name) "unknown repo" (OpamState.repository_of_package t nv) in OpamConsole.msg "Bundling %s [%s]\n" (OpamPackage.to_string nv) repo_name; match dryrun with | true -> () | false -> let archive = OpamFilename.Op.(archives // (OpamPackage.to_string nv ^ ".tar.gz")) in if reuse && exists archive then begin OpamConsole.msg "Reusing %s\n" (to_string archive) end else begin match OpamProcess.Job.run (OpamAction.download_package t nv) with | `Error s -> OpamConsole.error_and_exit "Download failed : %s" s | `Successful s -> OpamAction.extract_package t s nv; let p_build = OpamPath.Switch.build t.root t.switch nv in OpamConsole.msg " p_build : % s\n " ( OpamFilename . ) ; OpamConsole.msg " archives : % s\n " ( OpamFilename . Dir.to_string archives ) ; OpamConsole.msg " archive : % s\n " ( OpamFilename.to_string archive ) ; OpamConsole.msg "p_build: %s\n" (OpamFilename.Dir.to_string p_build); OpamConsole.msg "archives: %s\n" (OpamFilename.Dir.to_string archives); OpamConsole.msg "archive: %s\n" (OpamFilename.to_string archive); *) exec (dirname_dir p_build) [ [ "tar"; "czf"; to_string archive; Base.to_string (basename_dir p_build) ] ]; end; let archive = Base.to_string (basename archive) in let env = OpamState.add_to_env t ~opam [] (OpamFile.OPAM.build_env opam) ~variables in let commands = OpamFile.OPAM.build opam @ OpamFile.OPAM.install opam in let commands = OpamFilter.commands (OpamState.filter_env t ~opam ~local_variables:variables) commands in let commands = List.map (fun l -> l @ [">>build.log 2>>build.log || (echo FAILED; tail build.log; exit 1)"]) commands in let install_commands = let name = OpamPackage.(Name.to_string @@ name nv) in [ [ sprintf "if [ -f \"%s.install\" ] ; then opam-installer --prefix \"$BUNDLE_PREFIX\" \"%s.install\" ; fi" name name ] ] in shellout_build ~archive ~env (commands @ install_commands); with e -> OpamStd.Exn.fatal e; OpamConsole.error_and_exit "%s" (Printexc.to_string e); end packages; match dryrun with | true -> () | false -> let install_sh = OpamFilename.Op.(bundle // "install.sh") in write install_sh (Buffer.contents b); chmod install_sh 0o755; () let cmd = let open Cmdliner in / various bits from OpamArg let dirname = let parse str = `Ok (OpamFilename.Dir.of_string str) in let print ppf dir = Format.pp_print_string ppf (OpamFilename.prettify_dir dir) in parse, print in let nonempty_arg_list name doc conv = let doc = Arg.info ~docv:name ~doc [] in Arg.(non_empty & pos_all conv [] & doc) in let atom = let parse str = let re = Re_str.regexp "\\([^>=<.!]+\\)\\(>=?\\|<=?\\|=\\|\\.\\|!=\\)\\(.*\\)" in try if not (Re_str.string_match re str 0) then failwith "no_version"; let sname = Re_str.matched_group 1 str in let sop = Re_str.matched_group 2 str in let sversion = Re_str.matched_group 3 str in let name = OpamPackage.Name.of_string sname in let sop = if sop = "." then "=" else sop in let version = OpamPackage.Version.of_string sversion in `Ok (name, Some (op, version)) with Failure _ | Invalid_argument _ -> try `Ok (OpamPackage.Name.of_string str, None) with Failure msg -> `Error msg in let print ppf atom = Format.pp_print_string ppf (OpamFormula.short_string_of_atom atom) in parse, print in let nonempty_atom_list = nonempty_arg_list "PACKAGES" "List of package names, with an optional version or constraint, \ e.g `pkg', `pkg.1.0' or `pkg>=0.5'." atom in let doc = "Generate a self-contained bundle of given packages with all dependencies." in let man = [ `S "DESCRIPTION"; `P "This command calculates the transitive dependencies of the given packages \ and collects all the corresponding archives into a specified directory, \ along with the shell script to unpack, build and install those packages \ on any remote machine (even without OPAM installed)."; ] in let outdir = let doc = Arg.info ["o";"outdir"] ~docv:"DIR" ~doc:"Write bundle to the directory $(docv)." in Arg.(value & opt dirname (OpamFilename.Dir.of_string "bundle") & doc) in let deps_only = Arg.(value & flag & info ["deps-only"] ~doc:"Bundle only the dependencies, excluding the specified packages.") in let dryrun = Arg.(value & flag & info ["dry-run"] ~doc:"Do not actually create bundle, only show actions to be done.") in let with_compiler = Arg.(value & flag & info ["with-compiler"] ~doc:"Bundle the compiler too") in let reuse = let doc = "Allow reusing archives already bundled in the output directory (no checking performed, can be useful to \ skip redownloading compiler sources)" in Arg.(value & flag & info ["reuse"] ~doc) in let bundle deps_only dryrun with_compiler reuse outdir names = bundle ~dryrun ~deps_only ~with_compiler ~reuse outdir names in Term.(pure bundle $deps_only $dryrun $with_compiler $reuse $outdir $nonempty_atom_list), Term.info "opam-bundle" ~doc ~man let () = match Cmdliner.Term.eval cmd with `Error _ -> exit 1 | _ -> exit 0
f9868f1f0274562b89829b15b506da5c674bf9ac760edf6d8b5ef93a65c2555b
zwizwa/staapl
pic18-dtc.rkt
#lang racket/base ;; Threaded Forth for PIC18. (require "../tools.rkt" "../ns.rkt" "../macro.rkt" (only-in "pic18.rkt" target-byte-address)) (require/provide "../asm.rkt" "asm.rkt" "dtc.rkt" "double-math.rkt" "../coma/macro-forth.rkt" "../coma/macro-forth-sig.rkt" "dtc-forth-unit.rkt") (provide (all-defined-out) target-byte-address) (define-dasm-collection dasm-collection) (define/invoke (macro-forth^) (dtc-forth@)) (define (wrap-macro m) m) (define (wrap-word m) (macro: ',m _compile)) ;; Map primitives. (define-syntax-rule (define-wrapped wrapper (out in) ...) (begin (ns (macro) (define out (wrapper (macro: in)))) ...)) (define-wrapped wrap-macro (begin _begin) (again _again) (until _until) (do _do) (while _while) (repeat _repeat) (if _if) (else _else) (then _then) ) (define-wrapped wrap-word (|;| _exit) (exit _exit) (>r _>r) (r> _r>) (r _r) (rdrop _rdrop) (@ _@) (! _!) (ram@ _ram@) (ram! _ram!) (rom@ _rom@) (dup _dup) (drop _drop) (2drop _2drop) (+ _+) (- _-) (* _*) (*>>16 _*>>16) (*>>8 _*>>8) (um* _um*) (invert _invert) (negate _negate) (not _not) (1+ _1+) (1- _1-) (and _and) (or _or) (xor _xor) (lohi _lohi) )
null
https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/pic18/pic18-dtc.rkt
racket
Threaded Forth for PIC18. Map primitives. | _exit)
#lang racket/base (require "../tools.rkt" "../ns.rkt" "../macro.rkt" (only-in "pic18.rkt" target-byte-address)) (require/provide "../asm.rkt" "asm.rkt" "dtc.rkt" "double-math.rkt" "../coma/macro-forth.rkt" "../coma/macro-forth-sig.rkt" "dtc-forth-unit.rkt") (provide (all-defined-out) target-byte-address) (define-dasm-collection dasm-collection) (define/invoke (macro-forth^) (dtc-forth@)) (define (wrap-macro m) m) (define (wrap-word m) (macro: ',m _compile)) (define-syntax-rule (define-wrapped wrapper (out in) ...) (begin (ns (macro) (define out (wrapper (macro: in)))) ...)) (define-wrapped wrap-macro (begin _begin) (again _again) (until _until) (do _do) (while _while) (repeat _repeat) (if _if) (else _else) (then _then) ) (define-wrapped wrap-word (exit _exit) (>r _>r) (r> _r>) (r _r) (rdrop _rdrop) (@ _@) (! _!) (ram@ _ram@) (ram! _ram!) (rom@ _rom@) (dup _dup) (drop _drop) (2drop _2drop) (+ _+) (- _-) (* _*) (*>>16 _*>>16) (*>>8 _*>>8) (um* _um*) (invert _invert) (negate _negate) (not _not) (1+ _1+) (1- _1-) (and _and) (or _or) (xor _xor) (lohi _lohi) )
521bcbcb874b9e24e0b077b5ab90df880a9d787d7aa18617285c149e8a55615a
ppaml-op3/insomnia
FromF.hs
# LANGUAGE TypeFamilies , FlexibleInstances # module Gambling.FromF where import Control.Applicative import Control.Monad.Reader hiding (forM) import Data.Function (on) import Data.List (sortBy) import Data.Traversable import Unbound.Generics.LocallyNameless import Insomnia.Common.Literal import Insomnia.Common.SampleParameters import qualified Gambling.Racket as R import FOmega.Syntax fomegaToGamble :: String -> Command -> R.Module fomegaToGamble modName c = runLFreshM $ runReaderT comp () where comp = do mdefns <- gamble (Outer c) let reqs = [ R.RequireMB $ R.RequiresAll (embed $ R.RequireModulePath "racket/match") , R.RequireMB $ R.RequiresAll (embed $ R.RequireFilePath "boot.rkt") ] defns = reqs ++ mdefns return $ R.Module (s2n modName) "gamble" $ R.ModuleDefnCtx $ bind (rec defns) R.ProvidesAll newtype wrapper to distinguish Commands at the toplevel vs nest in the LHS of a bind . newtype Outer a = Outer {getOutter :: a} type M = ReaderT Context LFreshM type Context = () class Gamble i where type Gambled i :: * gamble :: i -> M (Gambled i) -- dangerous! unsafeCoerceName :: Name a -> Name b unsafeCoerceName nm = makeName (name2String nm) (name2Integer nm) lookupVar :: Var -> M R.Var lookupVar = return . unsafeCoerceName associate :: Var -> M R.Var associate = return . unsafeCoerceName simpleBody :: R.Expr -> R.Body simpleBody = R.Body . bind (rec []) instance Gamble Literal where type Gambled Literal = Literal gamble = return instance Gamble Term where type Gambled Term = R.Expr gamble (V x) = R.Var <$> lookupVar x gamble (L lit) = R.Literal <$> gamble lit gamble (Lam bnd) = lunbind bnd $ \((x, _ty), body) -> do x' <- associate x R.Lam . bind [x'] . simpleBody <$> gamble body gamble (PLam bnd) = lunbind bnd $ \((_tv, _k), body) -> do R.Lam . bind [] . simpleBody <$> gamble body gamble (PApp m _ty) = papp <$> gamble m where papp e = R.App [e] gamble (App m1 m2) = app <$> gamble m1 <*> gamble m2 where app e1 e2 = R.App [e1, e2] gamble (Let bnd) = lunbind bnd $ \((x, m1), body) -> do m1' <- gamble (unembed m1) x' <- associate x R.Let . bind [R.Binding x' $ embed m1'] . simpleBody <$> gamble body gamble (Pack _hidTy m _asTy) = gamble m gamble (Unpack bnd) = lunbind bnd $ \((_tv, x, m1), body) -> do m1' <- gamble (unembed m1) x' <- associate x R.Let . bind [R.Binding x' $ embed m1'] . simpleBody <$> gamble body gamble (Return m) = do gambleReturn <$> gamble m gamble (LetSample bnd) = lunbind bnd $ \((x, m1), m2) -> gambleBind <$> associate x <*> gamble (unembed m1) <*> gamble m2 gamble (LetRec bnd) = lunbind bnd $ \(recBnds, body) -> do recBnds' <- forM (unrec recBnds) $ \(x, _tp, m) -> do x' <- associate x e <- gamble (unembed m) return $ R.Binding x' (embed e) body' <- gamble body return $ R.LetRec $ bind (rec recBnds') $ simpleBody body' gamble (Record fs) = case sniffFields fs of Tuplish vs -> gambleImmutableVector <$> traverse gamble vs Recordish sfs -> fmap gambleImmutableHash $ forM sfs $ \(s, m) -> do e <- gamble m return (R.StringLit s, e) Boring -> return $ gambleNull Valueish m -> gamble m DataInOutish mIn mOut -> gambleInOutPair <$> gamble mIn <*> gamble mOut Consish cs -> fmap gambleImmutableHash $ forM cs $ \(c, m) -> do e <- gamble m return (R.QuoteSymbol c, e) gamble (Proj m f) = case f of FUser s -> gambleHashRef (R.StringLit s) <$> gamble m FVal -> gamble m FCon c -> gambleHashRef (R.QuoteSymbol c) <$> gamble m FTuple i -> gambleVectorRef (R.Literal $ IntL $ toInteger i) <$> gamble m FDataIn -> gambleProjectDataIn <$> gamble m FDataOut -> gambleProjectDataOut <$> gamble m _ -> error ("projecting a " ++ show f ++ " field") gamble (Unroll _muTy m _ctxTy) = gamble m gamble (Roll _muty m _ctxTy) = gamble m gamble (Inj c m _sumTy) = do e <- gamble m s <- case c of FCon c' -> return $ R.QuoteSymbol c' return $ gambleCons s e gamble (Case subj clauses defaultClause) = do subj' <- gamble subj clauses' <- traverse gamble clauses defaultClause' <- gamble defaultClause return $ R.Match subj' (clauses' ++ defaultClause') gamble m = error $ "Gamble.gamble " ++ show m ++ " unimplemented" instance Gamble DefaultClause where type Gambled DefaultClause = [R.Clause] gamble (DefaultClause dc) = do e <- case dc of Left caseMatchFailure -> gamble caseMatchFailure Right m -> gamble m return [R.Clause $ bind R.WildP $ simpleBody e] instance Gamble CaseMatchFailure where type Gambled CaseMatchFailure = R.Expr gamble (CaseMatchFailure _resultTy) = return gambleAbort instance Gamble Clause where type Gambled Clause = R.Clause gamble (Clause fld bnd) = lunbind bnd $ \(x, m) -> do f' <- case fld of FCon f -> return f x' <- associate x e <- gamble m return $ R.Clause $ bind (R.ConsP (R.QuoteSymbolP $ embed f') (R.VarP x')) $ simpleBody e -- implement "return m" as "(lambda () e)" gambleReturn :: R.Expr -> R.Expr gambleReturn = R.Lam . bind [] . simpleBody -- implement "let x ~ m1 in m2" as "(lambda () (let ([x' (e1)]) (e2)))" gambleBind :: R.Var -> R.Expr -> R.Expr -> R.Expr gambleBind x e1 e2 = R.Lam . bind [] . simpleBody $ R.Let $ bind [R.Binding x (embed $ R.App [e1])] (simpleBody $ R.App [e2]) -- force a distribution monad thunk "m" as "(e)" gambleForce :: R.Expr -> R.Expr gambleForce e = R.App [e] gambleNull :: R.Expr gambleNull = R.Var (s2n "null") -- compile constructor C applied to value m as "(cons 'C m)" gambleCons :: R.Expr -> R.Expr -> R.Expr gambleCons c s = R.App [R.Var (s2n "cons") , c , s ] -- gamble's sampler -- (mh-sample e) gambleSampler :: SampleParameters -> R.Expr -> R.Expr gambleSampler _params e = R.App [R.Var (s2n "mh-sampler"), e] -- | implement tuples as immutable vectors gambleImmutableVector :: [R.Expr] -> R.Expr gambleImmutableVector es = R.App (R.Var (s2n "vector-immutable") : es) gambleImmutableHash :: [(R.Expr, R.Expr)] -> R.Expr gambleImmutableHash ses = R.App (R.Var (s2n "hash") : concat (map kv ses)) where kv (k, v) = [k, v] gambleHashRef :: R.Expr -> R.Expr -> R.Expr gambleHashRef k e = R.App [R.Var (s2n "hash-ref") , e , k] gambleVectorRef :: R.Expr -> R.Expr -> R.Expr gambleVectorRef j e = R.App [R.Var (s2n "vector-ref") , e , j] gambleInOutPair :: R.Expr -> R.Expr -> R.Expr gambleInOutPair eIn eOut = R.App [R.Var (s2n "vector-immutable") , eIn , eOut ] gambleProjectDataIn :: R.Expr -> R.Expr gambleProjectDataIn e = R.App [R.Var (s2n "vector-ref") , e , R.Literal (IntL 0) ] gambleProjectDataOut :: R.Expr -> R.Expr gambleProjectDataOut e = R.App [R.Var (s2n "vector-ref") , e , R.Literal (IntL 1) ] gambleAbort :: R.Expr gambleAbort = R.App [R.Var (s2n "error") , R.QuoteSymbol "insomnia-abort" ] singleton :: a -> [a] singleton x = [x] instance Gamble (Outer Command) where type Gambled (Outer Command) = [R.ModuleBinding] gamble (Outer (EffectC _pc m)) = TODO XXX use the command gamble (Outer (ReturnC _m)) = return [] -- ignore the return at the end of the whole program gamble (Outer (LetC bnd)) = lunbind bnd $ \((x, m), c) -> do x' <- associate x e <- gamble (unembed m) let mb = R.DefnMB $ R.Define $ rebind x' (embed e) mbs <- gamble (Outer c) return (mb:mbs) gamble (Outer (BindC bnd)) = lunbind bnd $ \((x, c1), c2) -> do x' <- associate x e <- gamble (unembed c1) let mb = R.DefnMB $ R.Define $ rebind x' (embed e) mbs <- gamble (Outer c2) return (mb:mbs) gamble (Outer (UnpackC bnd)) = lunbind bnd $ \((_tv, x, m), c) -> do x' <- associate x e <- gamble (unembed m) let mb = R.DefnMB $ R.Define $ rebind x' (embed e) mbs <- gamble (Outer c) return (mb:mbs) instance Gamble Command where type Gambled Command = R.Expr gamble (EffectC (SamplePC params) m) = do e <- gambleForce <$> gamble m return (gambleSampler params e) gamble (EffectC PrintPC m) = gambleForce <$> gamble m gamble (ReturnC m) = gamble m gamble (LetC bnd) = lunbind bnd $ \((x, m), c) -> do x' <- associate x e1 <- gamble (unembed m) R.Let . bind [R.Binding x' $ embed e1] . simpleBody <$> gamble c gamble (BindC bnd) = lunbind bnd $ \((x, c1), c2) -> do x' <- associate x e1 <- gamble (unembed c1) R.Let . bind [R.Binding x' $ embed e1] . simpleBody <$> gamble c2 gamble (UnpackC bnd) = lunbind bnd $ \((_tv, x, m), c) -> do x' <- associate x e <- gamble (unembed m) R.Let . bind [R.Binding x' $ embed e] . simpleBody <$> gamble c sniffFields :: [(Field, Term)] -> Recordsy Term sniffFields [] = Boring sniffFields ((FUser u, m):rest) = Recordish $ (u,m):expectRecordish rest sniffFields ((FTuple i, m):rest) = Tuplish . map snd . sortBy (compare `on` fst) $ (i,m):expectTuplish rest sniffFields ((FCon c, m):rest) = Consish $ (c,m):expectConsish rest sniffFields [(FDataIn, mIn), (FDataOut, mOut)] = DataInOutish mIn mOut sniffFields [(FDataOut, mOut), (FDataIn, mIn)] = DataInOutish mIn mOut sniffFields [(FType, _)] = Boring sniffFields [(FSig, _)] = Boring sniffFields [(FVal, m)] = Valueish m -- take apart a record where we expect to see only user-supplied fields expectRecordish :: [(Field, Term)] -> [(String, Term)] expectRecordish [] = [] expectRecordish ((FUser u, m):rest) = (u,m):expectRecordish rest expectTuplish :: [(Field, Term)] -> [(Int, Term)] expectTuplish [] = [] expectTuplish ((FTuple i, m):rest) = (i,m):expectTuplish rest expectConsish :: [(Field, Term)] -> [(String, Term)] expectConsish [] = [] expectConsish ((FCon c, m):rest) = (c,m):expectConsish rest -- ugh data Recordsy a = Tuplish [a] | Recordish [(String, a)] | Boring | DataInOutish a a -- in, out | Consish [(String, a)] | Valueish a
null
https://raw.githubusercontent.com/ppaml-op3/insomnia/5fc6eb1d554e8853d2fc929a957c7edce9e8867d/src/Gambling/FromF.hs
haskell
dangerous! implement "return m" as "(lambda () e)" implement "let x ~ m1 in m2" as "(lambda () (let ([x' (e1)]) (e2)))" force a distribution monad thunk "m" as "(e)" compile constructor C applied to value m as "(cons 'C m)" gamble's sampler (mh-sample e) | implement tuples as immutable vectors ignore the return at the end of the whole program take apart a record where we expect to see only user-supplied fields ugh in, out
# LANGUAGE TypeFamilies , FlexibleInstances # module Gambling.FromF where import Control.Applicative import Control.Monad.Reader hiding (forM) import Data.Function (on) import Data.List (sortBy) import Data.Traversable import Unbound.Generics.LocallyNameless import Insomnia.Common.Literal import Insomnia.Common.SampleParameters import qualified Gambling.Racket as R import FOmega.Syntax fomegaToGamble :: String -> Command -> R.Module fomegaToGamble modName c = runLFreshM $ runReaderT comp () where comp = do mdefns <- gamble (Outer c) let reqs = [ R.RequireMB $ R.RequiresAll (embed $ R.RequireModulePath "racket/match") , R.RequireMB $ R.RequiresAll (embed $ R.RequireFilePath "boot.rkt") ] defns = reqs ++ mdefns return $ R.Module (s2n modName) "gamble" $ R.ModuleDefnCtx $ bind (rec defns) R.ProvidesAll newtype wrapper to distinguish Commands at the toplevel vs nest in the LHS of a bind . newtype Outer a = Outer {getOutter :: a} type M = ReaderT Context LFreshM type Context = () class Gamble i where type Gambled i :: * gamble :: i -> M (Gambled i) unsafeCoerceName :: Name a -> Name b unsafeCoerceName nm = makeName (name2String nm) (name2Integer nm) lookupVar :: Var -> M R.Var lookupVar = return . unsafeCoerceName associate :: Var -> M R.Var associate = return . unsafeCoerceName simpleBody :: R.Expr -> R.Body simpleBody = R.Body . bind (rec []) instance Gamble Literal where type Gambled Literal = Literal gamble = return instance Gamble Term where type Gambled Term = R.Expr gamble (V x) = R.Var <$> lookupVar x gamble (L lit) = R.Literal <$> gamble lit gamble (Lam bnd) = lunbind bnd $ \((x, _ty), body) -> do x' <- associate x R.Lam . bind [x'] . simpleBody <$> gamble body gamble (PLam bnd) = lunbind bnd $ \((_tv, _k), body) -> do R.Lam . bind [] . simpleBody <$> gamble body gamble (PApp m _ty) = papp <$> gamble m where papp e = R.App [e] gamble (App m1 m2) = app <$> gamble m1 <*> gamble m2 where app e1 e2 = R.App [e1, e2] gamble (Let bnd) = lunbind bnd $ \((x, m1), body) -> do m1' <- gamble (unembed m1) x' <- associate x R.Let . bind [R.Binding x' $ embed m1'] . simpleBody <$> gamble body gamble (Pack _hidTy m _asTy) = gamble m gamble (Unpack bnd) = lunbind bnd $ \((_tv, x, m1), body) -> do m1' <- gamble (unembed m1) x' <- associate x R.Let . bind [R.Binding x' $ embed m1'] . simpleBody <$> gamble body gamble (Return m) = do gambleReturn <$> gamble m gamble (LetSample bnd) = lunbind bnd $ \((x, m1), m2) -> gambleBind <$> associate x <*> gamble (unembed m1) <*> gamble m2 gamble (LetRec bnd) = lunbind bnd $ \(recBnds, body) -> do recBnds' <- forM (unrec recBnds) $ \(x, _tp, m) -> do x' <- associate x e <- gamble (unembed m) return $ R.Binding x' (embed e) body' <- gamble body return $ R.LetRec $ bind (rec recBnds') $ simpleBody body' gamble (Record fs) = case sniffFields fs of Tuplish vs -> gambleImmutableVector <$> traverse gamble vs Recordish sfs -> fmap gambleImmutableHash $ forM sfs $ \(s, m) -> do e <- gamble m return (R.StringLit s, e) Boring -> return $ gambleNull Valueish m -> gamble m DataInOutish mIn mOut -> gambleInOutPair <$> gamble mIn <*> gamble mOut Consish cs -> fmap gambleImmutableHash $ forM cs $ \(c, m) -> do e <- gamble m return (R.QuoteSymbol c, e) gamble (Proj m f) = case f of FUser s -> gambleHashRef (R.StringLit s) <$> gamble m FVal -> gamble m FCon c -> gambleHashRef (R.QuoteSymbol c) <$> gamble m FTuple i -> gambleVectorRef (R.Literal $ IntL $ toInteger i) <$> gamble m FDataIn -> gambleProjectDataIn <$> gamble m FDataOut -> gambleProjectDataOut <$> gamble m _ -> error ("projecting a " ++ show f ++ " field") gamble (Unroll _muTy m _ctxTy) = gamble m gamble (Roll _muty m _ctxTy) = gamble m gamble (Inj c m _sumTy) = do e <- gamble m s <- case c of FCon c' -> return $ R.QuoteSymbol c' return $ gambleCons s e gamble (Case subj clauses defaultClause) = do subj' <- gamble subj clauses' <- traverse gamble clauses defaultClause' <- gamble defaultClause return $ R.Match subj' (clauses' ++ defaultClause') gamble m = error $ "Gamble.gamble " ++ show m ++ " unimplemented" instance Gamble DefaultClause where type Gambled DefaultClause = [R.Clause] gamble (DefaultClause dc) = do e <- case dc of Left caseMatchFailure -> gamble caseMatchFailure Right m -> gamble m return [R.Clause $ bind R.WildP $ simpleBody e] instance Gamble CaseMatchFailure where type Gambled CaseMatchFailure = R.Expr gamble (CaseMatchFailure _resultTy) = return gambleAbort instance Gamble Clause where type Gambled Clause = R.Clause gamble (Clause fld bnd) = lunbind bnd $ \(x, m) -> do f' <- case fld of FCon f -> return f x' <- associate x e <- gamble m return $ R.Clause $ bind (R.ConsP (R.QuoteSymbolP $ embed f') (R.VarP x')) $ simpleBody e gambleReturn :: R.Expr -> R.Expr gambleReturn = R.Lam . bind [] . simpleBody gambleBind :: R.Var -> R.Expr -> R.Expr -> R.Expr gambleBind x e1 e2 = R.Lam . bind [] . simpleBody $ R.Let $ bind [R.Binding x (embed $ R.App [e1])] (simpleBody $ R.App [e2]) gambleForce :: R.Expr -> R.Expr gambleForce e = R.App [e] gambleNull :: R.Expr gambleNull = R.Var (s2n "null") gambleCons :: R.Expr -> R.Expr -> R.Expr gambleCons c s = R.App [R.Var (s2n "cons") , c , s ] gambleSampler :: SampleParameters -> R.Expr -> R.Expr gambleSampler _params e = R.App [R.Var (s2n "mh-sampler"), e] gambleImmutableVector :: [R.Expr] -> R.Expr gambleImmutableVector es = R.App (R.Var (s2n "vector-immutable") : es) gambleImmutableHash :: [(R.Expr, R.Expr)] -> R.Expr gambleImmutableHash ses = R.App (R.Var (s2n "hash") : concat (map kv ses)) where kv (k, v) = [k, v] gambleHashRef :: R.Expr -> R.Expr -> R.Expr gambleHashRef k e = R.App [R.Var (s2n "hash-ref") , e , k] gambleVectorRef :: R.Expr -> R.Expr -> R.Expr gambleVectorRef j e = R.App [R.Var (s2n "vector-ref") , e , j] gambleInOutPair :: R.Expr -> R.Expr -> R.Expr gambleInOutPair eIn eOut = R.App [R.Var (s2n "vector-immutable") , eIn , eOut ] gambleProjectDataIn :: R.Expr -> R.Expr gambleProjectDataIn e = R.App [R.Var (s2n "vector-ref") , e , R.Literal (IntL 0) ] gambleProjectDataOut :: R.Expr -> R.Expr gambleProjectDataOut e = R.App [R.Var (s2n "vector-ref") , e , R.Literal (IntL 1) ] gambleAbort :: R.Expr gambleAbort = R.App [R.Var (s2n "error") , R.QuoteSymbol "insomnia-abort" ] singleton :: a -> [a] singleton x = [x] instance Gamble (Outer Command) where type Gambled (Outer Command) = [R.ModuleBinding] gamble (Outer (EffectC _pc m)) = TODO XXX use the command gamble (Outer (LetC bnd)) = lunbind bnd $ \((x, m), c) -> do x' <- associate x e <- gamble (unembed m) let mb = R.DefnMB $ R.Define $ rebind x' (embed e) mbs <- gamble (Outer c) return (mb:mbs) gamble (Outer (BindC bnd)) = lunbind bnd $ \((x, c1), c2) -> do x' <- associate x e <- gamble (unembed c1) let mb = R.DefnMB $ R.Define $ rebind x' (embed e) mbs <- gamble (Outer c2) return (mb:mbs) gamble (Outer (UnpackC bnd)) = lunbind bnd $ \((_tv, x, m), c) -> do x' <- associate x e <- gamble (unembed m) let mb = R.DefnMB $ R.Define $ rebind x' (embed e) mbs <- gamble (Outer c) return (mb:mbs) instance Gamble Command where type Gambled Command = R.Expr gamble (EffectC (SamplePC params) m) = do e <- gambleForce <$> gamble m return (gambleSampler params e) gamble (EffectC PrintPC m) = gambleForce <$> gamble m gamble (ReturnC m) = gamble m gamble (LetC bnd) = lunbind bnd $ \((x, m), c) -> do x' <- associate x e1 <- gamble (unembed m) R.Let . bind [R.Binding x' $ embed e1] . simpleBody <$> gamble c gamble (BindC bnd) = lunbind bnd $ \((x, c1), c2) -> do x' <- associate x e1 <- gamble (unembed c1) R.Let . bind [R.Binding x' $ embed e1] . simpleBody <$> gamble c2 gamble (UnpackC bnd) = lunbind bnd $ \((_tv, x, m), c) -> do x' <- associate x e <- gamble (unembed m) R.Let . bind [R.Binding x' $ embed e] . simpleBody <$> gamble c sniffFields :: [(Field, Term)] -> Recordsy Term sniffFields [] = Boring sniffFields ((FUser u, m):rest) = Recordish $ (u,m):expectRecordish rest sniffFields ((FTuple i, m):rest) = Tuplish . map snd . sortBy (compare `on` fst) $ (i,m):expectTuplish rest sniffFields ((FCon c, m):rest) = Consish $ (c,m):expectConsish rest sniffFields [(FDataIn, mIn), (FDataOut, mOut)] = DataInOutish mIn mOut sniffFields [(FDataOut, mOut), (FDataIn, mIn)] = DataInOutish mIn mOut sniffFields [(FType, _)] = Boring sniffFields [(FSig, _)] = Boring sniffFields [(FVal, m)] = Valueish m expectRecordish :: [(Field, Term)] -> [(String, Term)] expectRecordish [] = [] expectRecordish ((FUser u, m):rest) = (u,m):expectRecordish rest expectTuplish :: [(Field, Term)] -> [(Int, Term)] expectTuplish [] = [] expectTuplish ((FTuple i, m):rest) = (i,m):expectTuplish rest expectConsish :: [(Field, Term)] -> [(String, Term)] expectConsish [] = [] expectConsish ((FCon c, m):rest) = (c,m):expectConsish rest data Recordsy a = Tuplish [a] | Recordish [(String, a)] | Boring | Consish [(String, a)] | Valueish a
22fa6228d8217cd2425b1ea083b78a9c1ff79f012e59673ed5724181c87023a3
ndmitchell/neil
FileData.hs
module Paper.Util.FileData( FileData(..), getFileData ) where import Control.Monad import Data.List.Extra import System.Directory import System.FilePath data FileData = FileData ^ All files must reside in one directory ,mainFile :: FilePath -- ^ The main file ,argFiles :: [FilePath] -- ^ Files given on the command line ,allFiles :: [FilePath] -- ^ All files in the directory ,flags :: [String] -- ^ Any flags given ,darcs :: FilePath -- ^ The location of the _darcs directory } deriving Show getFileData :: [String] -> IO FileData getFileData args = do let (opt,files) = partition ("-" `isPrefixOf`) args files <- if null files then liftM (:[]) getCurrentDirectory else return files (dirs,explicit,implicit) <- liftM unzip3 $ mapM f files (explicit,implicit) <- return (concat explicit, concat implicit) when (length (nub dirs) > 1) $ error "All files must be from the same directory" let nullErr x | null explicit = error $ "Error: No Latex files found in " ++ show (head dirs) | otherwise = x let dir = head dirs darcs <- getDarcs dir return $ FileData dir (nullErr $ head $ explicit) (nullErr $ nubSort $ explicit) (nullErr $ nubSort $ explicit ++ implicit) (map tail opt) darcs where -- return (directory, explicit, implicit) f file = do file <- canonicalizePath file bDir <- doesDirectoryExist file bFile <- doesFileExist file if bDir then getDir file else if bFile then getFile file else error $ "Error: Could not find file " ++ show file getDir dir = do files <- getDirectoryContents dir files <- return $ filter ((==) ".tex" . takeExtension) files -- now pick the main file let mainFile = snd $ maximum [(rank x, x) | x <- files] dirs = reverse $ splitDirectories dir rank x = liftM negate $ elemIndex (dropExtension x) dirs return (dir, [mainFile | not $ null files] ++ files, []) getFile file = do (a,b,[]) <- getDir $ takeDirectory file return (a, [file], b) getDarcs = f . reverse . map joinPath . tail . inits . splitDirectories where f [] = return $ error "Darcs repo not found" f (x:xs) = do b <- doesDirectoryExist (x </> "_darcs") if b then return $ dropTrailingPathSeparator x else f xs
null
https://raw.githubusercontent.com/ndmitchell/neil/7162f33af3baa76f1c1ffed9c05b1c965cac8a55/src/Paper/Util/FileData.hs
haskell
^ The main file ^ Files given on the command line ^ All files in the directory ^ Any flags given ^ The location of the _darcs directory return (directory, explicit, implicit) now pick the main file
module Paper.Util.FileData( FileData(..), getFileData ) where import Control.Monad import Data.List.Extra import System.Directory import System.FilePath data FileData = FileData ^ All files must reside in one directory } deriving Show getFileData :: [String] -> IO FileData getFileData args = do let (opt,files) = partition ("-" `isPrefixOf`) args files <- if null files then liftM (:[]) getCurrentDirectory else return files (dirs,explicit,implicit) <- liftM unzip3 $ mapM f files (explicit,implicit) <- return (concat explicit, concat implicit) when (length (nub dirs) > 1) $ error "All files must be from the same directory" let nullErr x | null explicit = error $ "Error: No Latex files found in " ++ show (head dirs) | otherwise = x let dir = head dirs darcs <- getDarcs dir return $ FileData dir (nullErr $ head $ explicit) (nullErr $ nubSort $ explicit) (nullErr $ nubSort $ explicit ++ implicit) (map tail opt) darcs where f file = do file <- canonicalizePath file bDir <- doesDirectoryExist file bFile <- doesFileExist file if bDir then getDir file else if bFile then getFile file else error $ "Error: Could not find file " ++ show file getDir dir = do files <- getDirectoryContents dir files <- return $ filter ((==) ".tex" . takeExtension) files let mainFile = snd $ maximum [(rank x, x) | x <- files] dirs = reverse $ splitDirectories dir rank x = liftM negate $ elemIndex (dropExtension x) dirs return (dir, [mainFile | not $ null files] ++ files, []) getFile file = do (a,b,[]) <- getDir $ takeDirectory file return (a, [file], b) getDarcs = f . reverse . map joinPath . tail . inits . splitDirectories where f [] = return $ error "Darcs repo not found" f (x:xs) = do b <- doesDirectoryExist (x </> "_darcs") if b then return $ dropTrailingPathSeparator x else f xs
6b2d3baeb7da54cea1ebd7afce81ab278caa21fc1ed5bc29a5d36060764cf34d
project-oak/hafnium-verification
boundMap.ml
* Copyright ( c ) Facebook , Inc. and its 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) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module L = Logging module BasicCost = CostDomain.BasicCost CFG modules used in several other modules module InstrCFG = ProcCfg.NormalOneInstrPerNode module NodeCFG = ProcCfg.Normal module Node = ProcCfg.DefaultNode let print_upper_bound_map bound_map = L.(debug Analysis Medium) "@\n\n******* Bound Map : [node -> bound] ITV **** @\n %a @\n" (Node.IdMap.pp ~pp_value:BasicCost.pp) bound_map ; L.(debug Analysis Medium) "@\n******* END Bound Map ITV **** @\n\n" let filter_loc vars_to_keep = function | AbsLoc.Loc.Var (Var.LogicalVar _) -> None | AbsLoc.Loc.Var var -> Control.ControlMap.find_opt var vars_to_keep | _ -> None let compute_upperbound_map node_cfg inferbo_invariant_map control_invariant_map loop_inv_map = let compute_node_upper_bound bound_map node = let node_id = NodeCFG.Node.id node in match Procdesc.Node.get_kind node with | Procdesc.Node.Exit_node -> Node.IdMap.add node_id BasicCost.one bound_map | _ -> ( let exit_state_opt = let instr_node_id = InstrCFG.last_of_underlying_node node |> InstrCFG.Node.id in BufferOverrunAnalysis.extract_post instr_node_id inferbo_invariant_map in match exit_state_opt with | Some entry_mem -> (* compute control vars, i.e. set of variables that affect the execution count *) let control_map = Control.compute_control_vars control_invariant_map loop_inv_map node in L.(debug Analysis Medium) "@\n>>> All dependencies for node = %a : %a @\n\n" Procdesc.Node.pp node (Control.ControlMap.pp ~pp_value:Location.pp) control_map ; (* bound = env(v1) *... * env(vn) *) let bound = match entry_mem with | Bottom -> L.debug Analysis Medium "@\n\ [COST ANALYSIS INTERNAL WARNING:] No 'env' found. This location is \ unreachable returning cost 0 \n" ; BasicCost.zero | ExcRaised -> BasicCost.one | NonBottom mem -> let cost = BufferOverrunDomain.MemReach.range ~filter_loc:(filter_loc control_map) ~node_id mem in The zero cost of node does not make sense especially when the abstract memory is non - bottom . is non-bottom. *) if BasicCost.is_zero cost then BasicCost.one else cost in L.(debug Analysis Medium) "@\n>>>Setting bound for node = %a to %a@\n\n" Node.pp_id node_id BasicCost.pp bound ; Node.IdMap.add node_id bound bound_map | _ -> Node.IdMap.add node_id BasicCost.zero bound_map ) in let bound_map = NodeCFG.fold_nodes node_cfg ~f:compute_node_upper_bound ~init:Node.IdMap.empty in print_upper_bound_map bound_map ; bound_map let lookup_upperbound bound_map nid = match Node.IdMap.find_opt nid bound_map with | Some bound -> bound | None -> L.(debug Analysis Medium) "@\n\n[WARNING] Bound not found for node %a, returning Top @\n" Node.pp_id nid ; BasicCost.top
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/cost/boundMap.ml
ocaml
compute control vars, i.e. set of variables that affect the execution count bound = env(v1) *... * env(vn)
* Copyright ( c ) Facebook , Inc. and its 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) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module L = Logging module BasicCost = CostDomain.BasicCost CFG modules used in several other modules module InstrCFG = ProcCfg.NormalOneInstrPerNode module NodeCFG = ProcCfg.Normal module Node = ProcCfg.DefaultNode let print_upper_bound_map bound_map = L.(debug Analysis Medium) "@\n\n******* Bound Map : [node -> bound] ITV **** @\n %a @\n" (Node.IdMap.pp ~pp_value:BasicCost.pp) bound_map ; L.(debug Analysis Medium) "@\n******* END Bound Map ITV **** @\n\n" let filter_loc vars_to_keep = function | AbsLoc.Loc.Var (Var.LogicalVar _) -> None | AbsLoc.Loc.Var var -> Control.ControlMap.find_opt var vars_to_keep | _ -> None let compute_upperbound_map node_cfg inferbo_invariant_map control_invariant_map loop_inv_map = let compute_node_upper_bound bound_map node = let node_id = NodeCFG.Node.id node in match Procdesc.Node.get_kind node with | Procdesc.Node.Exit_node -> Node.IdMap.add node_id BasicCost.one bound_map | _ -> ( let exit_state_opt = let instr_node_id = InstrCFG.last_of_underlying_node node |> InstrCFG.Node.id in BufferOverrunAnalysis.extract_post instr_node_id inferbo_invariant_map in match exit_state_opt with | Some entry_mem -> let control_map = Control.compute_control_vars control_invariant_map loop_inv_map node in L.(debug Analysis Medium) "@\n>>> All dependencies for node = %a : %a @\n\n" Procdesc.Node.pp node (Control.ControlMap.pp ~pp_value:Location.pp) control_map ; let bound = match entry_mem with | Bottom -> L.debug Analysis Medium "@\n\ [COST ANALYSIS INTERNAL WARNING:] No 'env' found. This location is \ unreachable returning cost 0 \n" ; BasicCost.zero | ExcRaised -> BasicCost.one | NonBottom mem -> let cost = BufferOverrunDomain.MemReach.range ~filter_loc:(filter_loc control_map) ~node_id mem in The zero cost of node does not make sense especially when the abstract memory is non - bottom . is non-bottom. *) if BasicCost.is_zero cost then BasicCost.one else cost in L.(debug Analysis Medium) "@\n>>>Setting bound for node = %a to %a@\n\n" Node.pp_id node_id BasicCost.pp bound ; Node.IdMap.add node_id bound bound_map | _ -> Node.IdMap.add node_id BasicCost.zero bound_map ) in let bound_map = NodeCFG.fold_nodes node_cfg ~f:compute_node_upper_bound ~init:Node.IdMap.empty in print_upper_bound_map bound_map ; bound_map let lookup_upperbound bound_map nid = match Node.IdMap.find_opt nid bound_map with | Some bound -> bound | None -> L.(debug Analysis Medium) "@\n\n[WARNING] Bound not found for node %a, returning Top @\n" Node.pp_id nid ; BasicCost.top
192fdfbeae2954dad8641f5c57064962bdfba7e1a3c04d5e5155336755f8d33b
DomainDrivenArchitecture/dda-k8s-crate
k8s.clj
Licensed to the Apache Software Foundation ( ASF ) under one ; or more contributor license agreements. See the NOTICE file ; distributed with this work for additional information ; regarding copyright ownership. The ASF licenses this file 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. (ns dda.pallet.dda-k8s-crate.infra.k8s (:require [schema.core :as s] [pallet.actions :as actions] [dda.provision :as p] [dda.provision.pallet :as pp])) (s/def K8s {:external-ip s/Str :external-ipv6 s/Str :advertise-address s/Str}) (def k8s-base "k8s-base") (def k8s-flannel "k8s-flannel") (def k8s-admin "k8s-admin") (def k8s-metallb "k8s-metallb") (def k8s-ingress "k8s-ingress") (def k8s-dashboard "k8s-dashboard") (s/defn init [facility :- s/Keyword config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "init") (p/copy-resources-to-tmp ::pp/pallet facility-name k8s-base [{:filename "init.sh"}]) (p/exec-file-on-target-as-root ::pp/pallet facility-name k8s-base "init.sh"))) (s/defn system-install [facility :- s/Keyword config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "system-install") (let [{:keys [advertise-address]} config] (p/copy-resources-to-tmp ::pp/pallet facility-name k8s-base [{:filename "install-system.sh" :config {:advertise-address advertise-address}}]) (p/exec-file-on-target-as-root ::pp/pallet facility-name k8s-base "install-system.sh")))) (s/defn user-install [facility :- s/Keyword user :- s/Str config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "user-install") (p/copy-resources-to-tmp ::pp/pallet facility-name k8s-base [{:filename "install-user-as-root.sh" :config {:user user}}]) (p/exec-file-on-target-as-root ::pp/pallet facility-name k8s-base "install-user-as-root.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-flannel [{:filename "flannel-rbac.yml"} {:filename "flannel.yml"} {:filename "install.sh"} {:filename "verify.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-flannel "install.sh"))) (s/defn system-configure [facility :- s/Keyword config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "system-configure"))) (s/defn user-configure [facility :- s/Keyword user :- s/Str config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "user-configure") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-admin [{:filename "admin-user.yml"} {:filename "remove.sh"} {:filename "install.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-admin "install.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-metallb [{:filename "metallb.yml"} {:filename "metallb-config.yml" :config config} {:filename "proxy.yml"} {:filename "remove.sh"} {:filename "verify.sh"} {:filename "install.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-metallb "install.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-ingress [{:filename "mandatory.yml"} {:filename "ingress-using-metallb.yml"} {:filename "remove.sh"} {:filename "verify.sh"} {:filename "install.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-ingress "install.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-dashboard [{:filename "kubernetes-dashboard.2.0.0.rc6.yml"} {:filename "admin_dash.2.0.0.rc6.yml"} {:filename "install.sh"} {:filename "remove.sh"} {:filename "verify.sh"} {:filename "proxy.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-dashboard "install.sh")))
null
https://raw.githubusercontent.com/DomainDrivenArchitecture/dda-k8s-crate/eaeb4d965a63692973d3c1d98759fbdf756596b2/main/src/dda/pallet/dda_k8s_crate/infra/k8s.clj
clojure
or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file "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 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.
Licensed to the Apache Software Foundation ( ASF ) under one to you under the Apache License , Version 2.0 ( the distributed under the License is distributed on an " AS IS " BASIS , (ns dda.pallet.dda-k8s-crate.infra.k8s (:require [schema.core :as s] [pallet.actions :as actions] [dda.provision :as p] [dda.provision.pallet :as pp])) (s/def K8s {:external-ip s/Str :external-ipv6 s/Str :advertise-address s/Str}) (def k8s-base "k8s-base") (def k8s-flannel "k8s-flannel") (def k8s-admin "k8s-admin") (def k8s-metallb "k8s-metallb") (def k8s-ingress "k8s-ingress") (def k8s-dashboard "k8s-dashboard") (s/defn init [facility :- s/Keyword config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "init") (p/copy-resources-to-tmp ::pp/pallet facility-name k8s-base [{:filename "init.sh"}]) (p/exec-file-on-target-as-root ::pp/pallet facility-name k8s-base "init.sh"))) (s/defn system-install [facility :- s/Keyword config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "system-install") (let [{:keys [advertise-address]} config] (p/copy-resources-to-tmp ::pp/pallet facility-name k8s-base [{:filename "install-system.sh" :config {:advertise-address advertise-address}}]) (p/exec-file-on-target-as-root ::pp/pallet facility-name k8s-base "install-system.sh")))) (s/defn user-install [facility :- s/Keyword user :- s/Str config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "user-install") (p/copy-resources-to-tmp ::pp/pallet facility-name k8s-base [{:filename "install-user-as-root.sh" :config {:user user}}]) (p/exec-file-on-target-as-root ::pp/pallet facility-name k8s-base "install-user-as-root.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-flannel [{:filename "flannel-rbac.yml"} {:filename "flannel.yml"} {:filename "install.sh"} {:filename "verify.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-flannel "install.sh"))) (s/defn system-configure [facility :- s/Keyword config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "system-configure"))) (s/defn user-configure [facility :- s/Keyword user :- s/Str config :- K8s] (let [facility-name (name facility)] (p/provision-log ::pp/pallet facility-name k8s-base ::p/info "user-configure") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-admin [{:filename "admin-user.yml"} {:filename "remove.sh"} {:filename "install.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-admin "install.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-metallb [{:filename "metallb.yml"} {:filename "metallb-config.yml" :config config} {:filename "proxy.yml"} {:filename "remove.sh"} {:filename "verify.sh"} {:filename "install.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-metallb "install.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-ingress [{:filename "mandatory.yml"} {:filename "ingress-using-metallb.yml"} {:filename "remove.sh"} {:filename "verify.sh"} {:filename "install.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-ingress "install.sh") (p/copy-resources-to-user ::pp/pallet user facility-name k8s-dashboard [{:filename "kubernetes-dashboard.2.0.0.rc6.yml"} {:filename "admin_dash.2.0.0.rc6.yml"} {:filename "install.sh"} {:filename "remove.sh"} {:filename "verify.sh"} {:filename "proxy.sh"}]) (p/exec-file-on-target-as-user ::pp/pallet user facility-name k8s-dashboard "install.sh")))
8e958a8476c29145032c74205188287bac1dfee97e77b5c7241309201271f920
aleator/CV
FunnyStatistics.hs
module CV.FunnyStatistics where import CV.Image import CV.Filters import qualified CV.ImageMath as IM import CV.ImageMathOp nthCM s n i = blur s $ ( i # - blur s i ) |^ n r_variance s i = msq #- (m #* m) where msq = gaussian s (i #* i) m = gaussian s i variance s i = msq #- (m #* m) where msq = blur s (i #* i) m = blur s i stdDev s i = IM.sqrt $ variance s i r_stdDev s i = IM.sqrt $ r_variance s i skewness s i = IM.div ( nthCM s 3 i ) ( stdDev s i |^3 ) kurtosis s i = IM.div ( nthCM s 4 i ) ( stdDev s i ) xx s i = IM.div ( nthCM s 6 i ) ( stdDev s i |^6 ) skewness s i = IM.div (nthCM s 3 i) (stdDev s i |^3) kurtosis s i = IM.div (nthCM s 4 i) (stdDev s i |^4) xx s i = IM.div (nthCM s 6 i) (stdDev s i |^6) -} pearsonSkewness1 s image = IM.div (blur s image #- unsafeImageTo32F (median s (unsafeImageTo8Bit image))) (stdDev s image)
null
https://raw.githubusercontent.com/aleator/CV/1e2c9116bcaacdf305044c861a1b36d0d8fb71b7/CV/FunnyStatistics.hs
haskell
module CV.FunnyStatistics where import CV.Image import CV.Filters import qualified CV.ImageMath as IM import CV.ImageMathOp nthCM s n i = blur s $ ( i # - blur s i ) |^ n r_variance s i = msq #- (m #* m) where msq = gaussian s (i #* i) m = gaussian s i variance s i = msq #- (m #* m) where msq = blur s (i #* i) m = blur s i stdDev s i = IM.sqrt $ variance s i r_stdDev s i = IM.sqrt $ r_variance s i skewness s i = IM.div ( nthCM s 3 i ) ( stdDev s i |^3 ) kurtosis s i = IM.div ( nthCM s 4 i ) ( stdDev s i ) xx s i = IM.div ( nthCM s 6 i ) ( stdDev s i |^6 ) skewness s i = IM.div (nthCM s 3 i) (stdDev s i |^3) kurtosis s i = IM.div (nthCM s 4 i) (stdDev s i |^4) xx s i = IM.div (nthCM s 6 i) (stdDev s i |^6) -} pearsonSkewness1 s image = IM.div (blur s image #- unsafeImageTo32F (median s (unsafeImageTo8Bit image))) (stdDev s image)
4bc1f5efce97f478724ff28cc20063c7eed8631ec2ad4616060dd07a5dfa556b
informatimago/lisp
priority-queue.lisp
-*- mode : lisp;coding : utf-8 -*- ;;;;************************************************************************** FILE : priority-queue.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp USER - INTERFACE : ;;;;DESCRIPTION ;;;; ;;;; Priority queues are lists ordered on a key of each element. ;;;; < PJB > < > MODIFICATIONS 2011 - 05 - 29 < PJB > Created . ;;;;LEGAL AGPL3 ;;;; Copyright 2011 - 2016 ;;;; ;;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ;;;; (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details . ;;;; You should have received a copy of the GNU Affero General Public License ;;;; along with this program. If not, see </> ;;;;************************************************************************** (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PRIORITY-QUEUE" (:use "COMMON-LISP") (:export "PQ" "MAKE-PQ" "PQ-P" "COPY-PQ" "PQ-LESSP" "PQ-EMPTYP" "PQ-LENGTH" "PQ-ELEMENTS" "PQ-ELEMENTS" "PQ-FIRST" "PQ-POP" "PQ-POP*" "PQ-INSERT" "PQ-INSERT*" "PQ-REMOVE" "PQ-KEY")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PRIORITY-QUEUE") (defstruct pq "Defines a priority queue data structure. We keep the %queue sorted in a stubbed list. The pq structure may be initialized with a LESSP function (default is <) and with a KEY function (default is IDENTITY)." (%queue (list 'head)) (lessp (function <)) (key (function identity))) (defun pq-emptyp (pq) "Whether the priority queue is empty. [O(1)]" (null (rest (pq-%queue pq)))) (defun pq-length (pq) "The number of elements in the priority queue. [O(length(pq))]" (length (rest (pq-%queue pq)))) (defun pq-elements (pq) "Returns a list containing the sorted elements in the priority queue. [O(length(pq))]" (mapcar (function car) (rest (pq-%queue pq)))) (defun (setf pq-elements) (new-elements pq) "Replaces all the elements of PQ by the NEW-ELEMENTS (need not be sorted). Returns NEW-ELEMENTS." (let ((key (pq-key pq))) (setf (pq-%queue pq) (cons 'head (sort (map 'list (lambda (x) (cons x (funcall key x))) new-elements) (pq-lessp pq) :key (function cdr))))) new-elements) (defun pq-first (pq) "Returns the first element of the priority queue." (let ((%queue (pq-%queue pq))) (if (rest %queue) (car (second %queue)) (error "PQ-FIRST: The priority queue is empty.")))) (defun pq-pop (pq) "Removes and returns the first element of the priority queue." (let ((%queue (pq-%queue pq))) (if (rest %queue) (car (pop (rest %queue))) (error "PQ-POP: The priority queue is empty.")))) (defun pq-pop* (pq) "Removes and returns the first element of the priority queue." (let ((%queue (pq-%queue pq))) (if (rest %queue) (prog1 (rest %queue) (setf (rest %queue) (rest (rest %queue)))) (error "PQ-POP: The priority queue is empty.")))) (defun pq-insert (pq element) "Inserts the element in order in the priority queue [O(length(pq))]. Returns the PQ." (let ((lessp (pq-lessp pq)) (key (pq-key pq))) (loop :with ekey = (funcall key element) :for current = (pq-%queue pq) :then (rest current) :while (and (rest current) (funcall lessp (cdr (second current)) ekey)) :finally (setf (rest current) (acons element ekey (rest current)))) pq)) (defun pq-insert* (pq element) "Inserts the ((element . key)) in order in the priority queue [O(length(pq))]. Returns the PQ." (let ((lessp (pq-lessp pq)) (key (pq-key pq))) (loop :with ekey = (funcall key (caar element)) :for current = (pq-%queue pq) :then (rest current) :while (and (rest current) (funcall lessp (cdr (second current)) ekey)) :finally (setf (cdar element) ekey (cdr element) (rest current) (rest current) element)) pq)) (defun pq-remove (pq element) "Removes the first occurence of the element from the priority queue [O(length(pq))] O(pq-remove pq (pq-first pq)) = O(1) Returns the ELEMENT." (loop :for current = (pq-%queue pq) :then (rest current) :while (and (rest current) (not (eql element (car (second current))))) :finally (when (rest current) (setf (rest current) (rest (rest current))))) element) ;;;; THE END ;;;;
null
https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/common-lisp/cesarum/priority-queue.lisp
lisp
coding : utf-8 -*- ************************************************************************** LANGUAGE: Common-Lisp SYSTEM: Common-Lisp DESCRIPTION Priority queues are lists ordered on a key of each element. LEGAL 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 along with this program. If not, see </> ************************************************************************** THE END ;;;;
FILE : priority-queue.lisp USER - INTERFACE : < PJB > < > MODIFICATIONS 2011 - 05 - 29 < PJB > Created . AGPL3 Copyright 2011 - 2016 it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License (eval-when (:compile-toplevel :load-toplevel :execute) (setf *readtable* (copy-readtable nil))) (defpackage "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PRIORITY-QUEUE" (:use "COMMON-LISP") (:export "PQ" "MAKE-PQ" "PQ-P" "COPY-PQ" "PQ-LESSP" "PQ-EMPTYP" "PQ-LENGTH" "PQ-ELEMENTS" "PQ-ELEMENTS" "PQ-FIRST" "PQ-POP" "PQ-POP*" "PQ-INSERT" "PQ-INSERT*" "PQ-REMOVE" "PQ-KEY")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PRIORITY-QUEUE") (defstruct pq "Defines a priority queue data structure. We keep the %queue sorted in a stubbed list. The pq structure may be initialized with a LESSP function (default is <) and with a KEY function (default is IDENTITY)." (%queue (list 'head)) (lessp (function <)) (key (function identity))) (defun pq-emptyp (pq) "Whether the priority queue is empty. [O(1)]" (null (rest (pq-%queue pq)))) (defun pq-length (pq) "The number of elements in the priority queue. [O(length(pq))]" (length (rest (pq-%queue pq)))) (defun pq-elements (pq) "Returns a list containing the sorted elements in the priority queue. [O(length(pq))]" (mapcar (function car) (rest (pq-%queue pq)))) (defun (setf pq-elements) (new-elements pq) "Replaces all the elements of PQ by the NEW-ELEMENTS (need not be sorted). Returns NEW-ELEMENTS." (let ((key (pq-key pq))) (setf (pq-%queue pq) (cons 'head (sort (map 'list (lambda (x) (cons x (funcall key x))) new-elements) (pq-lessp pq) :key (function cdr))))) new-elements) (defun pq-first (pq) "Returns the first element of the priority queue." (let ((%queue (pq-%queue pq))) (if (rest %queue) (car (second %queue)) (error "PQ-FIRST: The priority queue is empty.")))) (defun pq-pop (pq) "Removes and returns the first element of the priority queue." (let ((%queue (pq-%queue pq))) (if (rest %queue) (car (pop (rest %queue))) (error "PQ-POP: The priority queue is empty.")))) (defun pq-pop* (pq) "Removes and returns the first element of the priority queue." (let ((%queue (pq-%queue pq))) (if (rest %queue) (prog1 (rest %queue) (setf (rest %queue) (rest (rest %queue)))) (error "PQ-POP: The priority queue is empty.")))) (defun pq-insert (pq element) "Inserts the element in order in the priority queue [O(length(pq))]. Returns the PQ." (let ((lessp (pq-lessp pq)) (key (pq-key pq))) (loop :with ekey = (funcall key element) :for current = (pq-%queue pq) :then (rest current) :while (and (rest current) (funcall lessp (cdr (second current)) ekey)) :finally (setf (rest current) (acons element ekey (rest current)))) pq)) (defun pq-insert* (pq element) "Inserts the ((element . key)) in order in the priority queue [O(length(pq))]. Returns the PQ." (let ((lessp (pq-lessp pq)) (key (pq-key pq))) (loop :with ekey = (funcall key (caar element)) :for current = (pq-%queue pq) :then (rest current) :while (and (rest current) (funcall lessp (cdr (second current)) ekey)) :finally (setf (cdar element) ekey (cdr element) (rest current) (rest current) element)) pq)) (defun pq-remove (pq element) "Removes the first occurence of the element from the priority queue [O(length(pq))] O(pq-remove pq (pq-first pq)) = O(1) Returns the ELEMENT." (loop :for current = (pq-%queue pq) :then (rest current) :while (and (rest current) (not (eql element (car (second current))))) :finally (when (rest current) (setf (rest current) (rest (rest current))))) element)
bce4864bb409639f0f0938f3acdac6762c761c9b766ec3a23c4c21e7254daefd
mcorbin/tour-of-clojure
macros.clj
(defmacro infix [coll] (list (second coll) (first coll (last coll)))) (println (infix (2 + 3)) "\n") (println (macroexpand '(infix (2 + 3))))
null
https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/resources/public/pages/code/macros.clj
clojure
(defmacro infix [coll] (list (second coll) (first coll (last coll)))) (println (infix (2 + 3)) "\n") (println (macroexpand '(infix (2 + 3))))
a4013467533a612a3b989fea4726945c039e193fa94e157d92a3e717b7833e0a
heraldry/heraldicon
suggestions.cljs
(ns heraldicon.frontend.blazonry-editor.suggestions (:require [clojure.string :as str] [heraldicon.frontend.auto-complete :as auto-complete] [re-frame.core :as rf])) (def ^:private hint-order (into {} (map-indexed (fn [index hint] [hint index])) ["layout" "cottising" "line" "fimbriation" "extra tincture" "tincture" "ordinary" "ordinary option" "charge" "charge option" "partition" "attitude" "facing" "number"])) (defn- filter-choices [choices s] (->> choices (filter (fn [[choice _]] (str/starts-with? choice s))) (sort-by (fn [[choice hint]] [(get hint-order hint 1000) choice])))) (rf/reg-event-fx ::set (fn [_ [_ caret-position suggestions substring-since-error on-click]] (let [auto-complete (when suggestions {:choices (filter-choices suggestions substring-since-error) :on-click on-click :position caret-position})] {:dispatch (if auto-complete [::auto-complete/set auto-complete] [::auto-complete/clear])})))
null
https://raw.githubusercontent.com/heraldry/heraldicon/54e003614cf2c14cda496ef36358059ba78275b0/src/heraldicon/frontend/blazonry_editor/suggestions.cljs
clojure
(ns heraldicon.frontend.blazonry-editor.suggestions (:require [clojure.string :as str] [heraldicon.frontend.auto-complete :as auto-complete] [re-frame.core :as rf])) (def ^:private hint-order (into {} (map-indexed (fn [index hint] [hint index])) ["layout" "cottising" "line" "fimbriation" "extra tincture" "tincture" "ordinary" "ordinary option" "charge" "charge option" "partition" "attitude" "facing" "number"])) (defn- filter-choices [choices s] (->> choices (filter (fn [[choice _]] (str/starts-with? choice s))) (sort-by (fn [[choice hint]] [(get hint-order hint 1000) choice])))) (rf/reg-event-fx ::set (fn [_ [_ caret-position suggestions substring-since-error on-click]] (let [auto-complete (when suggestions {:choices (filter-choices suggestions substring-since-error) :on-click on-click :position caret-position})] {:dispatch (if auto-complete [::auto-complete/set auto-complete] [::auto-complete/clear])})))
39cd8c00c4df34ab2e9665dee7bcea5aa7ea1f2cbcd6544345fb565a2a0bbbc9
racket/drracket
info.rkt
#lang info (define collection 'multi) (define version "1.1") (define deps '("base" "compatibility-lib")) (define pkg-desc "DrRacket's plugin API") (define pkg-authors '(robby)) (define license '(Apache-2.0 OR MIT))
null
https://raw.githubusercontent.com/racket/drracket/a852792aa3a858a15debc5d1e5f553bce4d99d9c/drracket-plugin-lib/info.rkt
racket
#lang info (define collection 'multi) (define version "1.1") (define deps '("base" "compatibility-lib")) (define pkg-desc "DrRacket's plugin API") (define pkg-authors '(robby)) (define license '(Apache-2.0 OR MIT))
8484e5490e9fd1ff7a485faa97fda7f15a5b17cec5852764931a1aae3c8f78d2
softwarelanguageslab/maf
R5RS_scp1_haha-4.scm
; Changes: * removed : 0 * added : 0 * swaps : 1 ; * negated predicates: 0 ; * swapped branches: 0 * calls to i d fun : 1 (letrec ((result ()) (output (lambda (i) (set! result (cons i result)))) (hulp 2) (haha (lambda (x) (<change> (let ((hulp (* x hulp))) (output hulp)) (output hulp)) (<change> (output hulp) (let ((hulp (* x hulp))) (output hulp))) (set! hulp 4)))) (<change> (haha 2) ((lambda (x) x) (haha 2))) (haha 3) (equal? result (__toplevel_cons 4 (__toplevel_cons 12 (__toplevel_cons 2 (__toplevel_cons 4 ()))))))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_scp1_haha-4.scm
scheme
Changes: * negated predicates: 0 * swapped branches: 0
* removed : 0 * added : 0 * swaps : 1 * calls to i d fun : 1 (letrec ((result ()) (output (lambda (i) (set! result (cons i result)))) (hulp 2) (haha (lambda (x) (<change> (let ((hulp (* x hulp))) (output hulp)) (output hulp)) (<change> (output hulp) (let ((hulp (* x hulp))) (output hulp))) (set! hulp 4)))) (<change> (haha 2) ((lambda (x) x) (haha 2))) (haha 3) (equal? result (__toplevel_cons 4 (__toplevel_cons 12 (__toplevel_cons 2 (__toplevel_cons 4 ()))))))
22602a4ccb295a9ca6dbc571f686da02a93f4473a16da2476184da395151b74f
jarofghosts/clojure-koans
03_vectors.clj
(meditations "You can use vectors in clojure as array-like structures" (= 1 (count [42])) "You can create a vector from a list" (= [1] (vec '(1))) "Or from some elements" (= [nil nil] (vector nil nil)) "But you can populate it with any number of elements at once" (= [1 2] (vec '(1 2))) "Conjoining to a vector is different than to a list" (= [111 222 333] (conj [111 222] 333)) "You can get the first element of a vector like so" (= :peanut (first [:peanut :butter :and :jelly])) "And the last in a similar fashion" (= :jelly (last [:peanut :butter :and :jelly])) "Or any index if you wish" (= :jelly (nth [:peanut :butter :and :jelly] 3)) "You can also slice a vector" (= '[:butter :and] (subvec [:peanut :butter :and :jelly] 1 3)) "Equality with collections is in terms of values" (= (list 1 2 3) (vector 1 2 3)))
null
https://raw.githubusercontent.com/jarofghosts/clojure-koans/9bc2a46414f479021ff27ac8744d36dce507ad7f/03_vectors.clj
clojure
(meditations "You can use vectors in clojure as array-like structures" (= 1 (count [42])) "You can create a vector from a list" (= [1] (vec '(1))) "Or from some elements" (= [nil nil] (vector nil nil)) "But you can populate it with any number of elements at once" (= [1 2] (vec '(1 2))) "Conjoining to a vector is different than to a list" (= [111 222 333] (conj [111 222] 333)) "You can get the first element of a vector like so" (= :peanut (first [:peanut :butter :and :jelly])) "And the last in a similar fashion" (= :jelly (last [:peanut :butter :and :jelly])) "Or any index if you wish" (= :jelly (nth [:peanut :butter :and :jelly] 3)) "You can also slice a vector" (= '[:butter :and] (subvec [:peanut :butter :and :jelly] 1 3)) "Equality with collections is in terms of values" (= (list 1 2 3) (vector 1 2 3)))
e4906e440ae3b38953c7a6ae1c12ef565dd78298fe2459486f75bdb6a6124b03
remixlabs/wasicaml
wc_prims.ml
Copyright ( C ) 2021 by Figly , Inc. This code is free software , see the file LICENSE for details . This code is free software, see the file LICENSE for details. *) let mk_table l = let tab = Hashtbl.create 7 in List.iter (fun k -> Hashtbl.add tab k ()) l; tab (* primitives that cannot return functions: *) let prims_non_func_result = [ "caml_abs_float"; "caml_acos_float"; "caml_add_debug_info"; "caml_add_float"; "caml_alloc_dummy_float"; "caml_array_append"; "caml_array_blit"; "caml_array_concat"; "caml_array_fill"; "caml_array_get_float"; "caml_array_set"; "caml_array_set_addr"; "caml_array_set_float"; "caml_array_sub"; "caml_array_unsafe_get_float"; "caml_array_unsafe_set"; "caml_array_unsafe_set_addr"; "caml_array_unsafe_set_float"; "caml_asin_float"; "caml_atan2_float"; "caml_atan_float"; "caml_ba_blit"; "caml_ba_change_layout"; "caml_ba_create"; "caml_ba_dim"; "caml_ba_dim_1"; "caml_ba_dim_2"; "caml_ba_dim_3"; "caml_ba_fill"; "caml_ba_get_1"; "caml_ba_get_2"; "caml_ba_get_3"; "caml_ba_get_generic"; "caml_ba_kind"; "caml_ba_layout"; "caml_ba_num_dims"; "caml_ba_reshape"; "caml_ba_set_1"; "caml_ba_set_2"; "caml_ba_set_3"; "caml_ba_set_generic"; "caml_ba_slice"; "caml_ba_sub"; "caml_ba_uint8_get16"; "caml_ba_uint8_get32"; "caml_ba_uint8_get64"; "caml_ba_uint8_set16"; "caml_ba_uint8_set32"; "caml_ba_uint8_set64"; "caml_backtrace_status"; "caml_blit_bytes"; "caml_blit_string"; "caml_bswap16"; "caml_bytes_compare"; "caml_bytes_equal"; "caml_bytes_get"; "caml_bytes_get16"; "caml_bytes_get32"; "caml_bytes_get64"; "caml_bytes_greaterequal"; "caml_bytes_greaterthan"; "caml_bytes_lessequal"; "caml_bytes_lessthan"; "caml_bytes_notequal"; "caml_bytes_of_string"; "caml_bytes_set"; "caml_bytes_set16"; "caml_bytes_set32"; "caml_bytes_set64"; "caml_ceil_float"; "caml_channel_descriptor"; "caml_classify_float"; "caml_compare"; "caml_convert_raw_backtrace"; "caml_convert_raw_backtrace_slot"; "caml_copysign_float"; "caml_cos_float"; "caml_cosh_float"; "caml_create_bytes"; "caml_create_string"; "caml_div_float"; "caml_dynlink_add_primitive"; "caml_dynlink_close_lib"; "caml_dynlink_get_current_libs"; "caml_dynlink_lookup_symbol"; "caml_dynlink_open_lib"; "caml_ensure_stack_capacity"; "caml_ephe_blit_data"; "caml_ephe_blit_key"; "caml_ephe_check_data"; "caml_ephe_check_key"; "caml_ephe_create"; "caml_ephe_get_data"; "caml_ephe_get_data_copy"; "caml_ephe_get_key"; "caml_ephe_get_key_copy"; "caml_ephe_set_data"; "caml_ephe_set_key"; "caml_ephe_unset_data"; "caml_ephe_unset_key"; "caml_eq_float"; "caml_equal"; "caml_eventlog_pause"; "caml_eventlog_resume"; "caml_exp_float"; "caml_expm1_float"; "caml_fill_bytes"; "caml_fill_string"; "caml_final_register"; "caml_final_register_called_without_value"; "caml_final_release"; "caml_float_compare"; "caml_float_of_int"; "caml_float_of_string"; "caml_floatarray_blit"; "caml_floatarray_create"; "caml_floatarray_get"; "caml_floatarray_set"; "caml_floatarray_unsafe_get"; "caml_floatarray_unsafe_set"; "caml_floor_float"; "caml_fma_float"; "caml_fmod_float"; "caml_format_float"; "caml_format_int"; "caml_fresh_oo_id"; "caml_frexp_float"; "caml_gc_compaction"; "caml_gc_counters"; "caml_gc_full_major"; "caml_gc_get"; "caml_gc_huge_fallback_count"; "caml_gc_major"; "caml_gc_major_slice"; "caml_gc_minor"; "caml_gc_minor_words"; "caml_gc_quick_stat"; "caml_gc_set"; "caml_gc_stat"; "caml_ge_float"; "caml_get_current_callstack"; "caml_get_current_environment"; "caml_get_exception_backtrace"; "caml_get_exception_raw_backtrace"; "caml_get_global_data"; "caml_get_major_bucket"; "caml_get_major_credit"; "caml_get_minor_free"; "caml_get_public_method"; "caml_get_section_table"; "caml_greaterequal"; "caml_greaterthan"; "caml_gt_float"; "caml_hash"; "caml_hexstring_of_float"; "caml_hypot_float"; "caml_install_signal_handler"; "caml_int32_add"; "caml_int32_and"; "caml_int32_bits_of_float"; "caml_int32_bswap"; "caml_int32_compare"; "caml_int32_div"; "caml_int32_float_of_bits"; "caml_int32_format"; "caml_int32_mod"; "caml_int32_mul"; "caml_int32_neg"; "caml_int32_of_float"; "caml_int32_of_int"; "caml_int32_of_string"; "caml_int32_or"; "caml_int32_shift_left"; "caml_int32_shift_right"; "caml_int32_shift_right_unsigned"; "caml_int32_sub"; "caml_int32_to_float"; "caml_int32_to_int"; "caml_int32_xor"; "caml_int64_add"; "caml_int64_add_native"; "caml_int64_and"; "caml_int64_and_native"; "caml_int64_bits_of_float"; "caml_int64_bswap"; "caml_int64_compare"; "caml_int64_div"; "caml_int64_div_native"; "caml_int64_float_of_bits"; "caml_int64_format"; "caml_int64_mod"; "caml_int64_mod_native"; "caml_int64_mul"; "caml_int64_mul_native"; "caml_int64_neg"; "caml_int64_neg_native"; "caml_int64_of_float"; "caml_int64_of_int"; "caml_int64_of_int32"; "caml_int64_of_nativeint"; "caml_int64_of_string"; "caml_int64_or"; "caml_int64_or_native"; "caml_int64_shift_left"; "caml_int64_shift_right"; "caml_int64_shift_right_unsigned"; "caml_int64_sub"; "caml_int64_sub_native"; "caml_int64_to_float"; "caml_int64_to_int"; "caml_int64_to_int32"; "caml_int64_to_nativeint"; "caml_int64_xor"; "caml_int64_xor_native"; "caml_int_as_pointer"; "caml_int_compare"; "caml_int_of_float"; "caml_int_of_string"; "caml_lazy_make_forward"; "caml_ldexp_float"; "caml_le_float"; "caml_lessequal"; "caml_lessthan"; "caml_lex_engine"; "caml_log10_float"; "caml_log1p_float"; "caml_log_float"; "caml_lt_float"; "caml_make_array"; "caml_make_float_vect"; "caml_make_vect"; "caml_marshal_data_size"; "caml_md5_chan"; "caml_md5_string"; "caml_memprof_start"; "caml_memprof_stop"; "caml_ml_bytes_length"; "caml_ml_channel_size"; "caml_ml_channel_size_64"; "caml_ml_close_channel"; "caml_ml_debug_info_status"; "caml_ml_enable_runtime_warnings"; "caml_ml_flush"; "caml_ml_input"; "caml_ml_input_char"; "caml_ml_input_int"; "caml_ml_input_scan_line"; "caml_ml_open_descriptor_in"; "caml_ml_open_descriptor_out"; "caml_ml_out_channels_list"; "caml_ml_output"; "caml_ml_output_bytes"; "caml_ml_output_char"; "caml_ml_output_int"; "caml_ml_pos_in"; "caml_ml_pos_in_64"; "caml_ml_pos_out"; "caml_ml_pos_out_64"; "caml_ml_runtime_warnings_enabled"; "caml_ml_seek_in"; "caml_ml_seek_in_64"; "caml_ml_seek_out"; "caml_ml_seek_out_64"; "caml_ml_set_binary_mode"; "caml_ml_set_channel_name"; "caml_ml_string_length"; "caml_modf_float"; "caml_mul_float"; "caml_nativeint_add"; "caml_nativeint_and"; "caml_nativeint_bswap"; "caml_nativeint_compare"; "caml_nativeint_div"; "caml_nativeint_format"; "caml_nativeint_mod"; "caml_nativeint_mul"; "caml_nativeint_neg"; "caml_nativeint_of_float"; "caml_nativeint_of_int"; "caml_nativeint_of_int32"; "caml_nativeint_of_string"; "caml_nativeint_or"; "caml_nativeint_shift_left"; "caml_nativeint_shift_right"; "caml_nativeint_shift_right_unsigned"; "caml_nativeint_sub"; "caml_nativeint_to_float"; "caml_nativeint_to_int"; "caml_nativeint_to_int32"; "caml_nativeint_xor"; "caml_neg_float"; "caml_neq_float"; "caml_new_lex_engine"; "caml_nextafter_float"; "caml_notequal"; "caml_obj_block"; "caml_obj_make_forward"; "caml_obj_reachable_words"; "caml_obj_set_raw_field"; "caml_obj_set_tag"; "caml_obj_tag"; "caml_output_value"; "caml_output_value_to_buffer"; "caml_output_value_to_bytes"; "caml_output_value_to_string"; "caml_parse_engine"; "caml_power_float"; "caml_raw_backtrace_length"; "caml_raw_backtrace_next_slot"; "caml_raw_backtrace_slot"; "caml_realloc_global"; "caml_record_backtrace"; "caml_register_named_value"; "caml_reify_bytecode"; "caml_remove_debug_info"; "caml_reset_afl_instrumentation"; "caml_restore_raw_backtrace"; "caml_round_float"; "caml_runtime_parameters"; "caml_runtime_variant"; "caml_set_oo_id"; "caml_set_parser_trace"; "caml_setup_afl"; "caml_signbit"; "caml_signbit_float"; "caml_sin_float"; "caml_sinh_float"; "caml_sqrt_float"; "caml_static_release_bytecode"; "caml_string_compare"; "caml_string_equal"; "caml_string_get"; "caml_string_get16"; "caml_string_get32"; "caml_string_get64"; "caml_string_greaterequal"; "caml_string_greaterthan"; "caml_string_lessequal"; "caml_string_lessthan"; "caml_string_notequal"; "caml_string_of_bytes"; "caml_string_set"; "caml_sub_float"; "caml_sys_argv"; "caml_sys_chdir"; "caml_sys_close"; "caml_sys_const_backend_type"; "caml_sys_const_big_endian"; "caml_sys_const_int_size"; "caml_sys_const_max_wosize"; "caml_sys_const_naked_pointers_checked"; "caml_sys_const_ostype_cygwin"; "caml_sys_const_ostype_unix"; "caml_sys_const_ostype_win32"; "caml_sys_const_word_size"; "caml_sys_executable_name"; "caml_sys_exit"; "caml_sys_file_exists"; "caml_sys_get_argv"; "caml_sys_get_config"; "caml_sys_getcwd"; "caml_sys_getenv"; "caml_sys_is_directory"; "caml_sys_isatty"; "caml_sys_mkdir"; "caml_sys_modify_argv"; "caml_sys_open"; "caml_sys_random_seed"; "caml_sys_read_directory"; "caml_sys_remove"; "caml_sys_rename"; "caml_sys_rmdir"; "caml_sys_system_command"; "caml_sys_time"; "caml_sys_time_include_children"; "caml_sys_unsafe_getenv"; "caml_tan_float"; "caml_tanh_float"; "caml_terminfo_rows"; "caml_trunc_float"; "caml_update_dummy"; "caml_weak_blit"; "caml_weak_check"; "caml_weak_create"; "caml_weak_get"; "caml_weak_get_copy"; "caml_weak_set"; ] |> mk_table
null
https://raw.githubusercontent.com/remixlabs/wasicaml/74ff72535aa8e49ab94a05d9c32c059ce264c1bb/src/wasicaml/wc_prims.ml
ocaml
primitives that cannot return functions:
Copyright ( C ) 2021 by Figly , Inc. This code is free software , see the file LICENSE for details . This code is free software, see the file LICENSE for details. *) let mk_table l = let tab = Hashtbl.create 7 in List.iter (fun k -> Hashtbl.add tab k ()) l; tab let prims_non_func_result = [ "caml_abs_float"; "caml_acos_float"; "caml_add_debug_info"; "caml_add_float"; "caml_alloc_dummy_float"; "caml_array_append"; "caml_array_blit"; "caml_array_concat"; "caml_array_fill"; "caml_array_get_float"; "caml_array_set"; "caml_array_set_addr"; "caml_array_set_float"; "caml_array_sub"; "caml_array_unsafe_get_float"; "caml_array_unsafe_set"; "caml_array_unsafe_set_addr"; "caml_array_unsafe_set_float"; "caml_asin_float"; "caml_atan2_float"; "caml_atan_float"; "caml_ba_blit"; "caml_ba_change_layout"; "caml_ba_create"; "caml_ba_dim"; "caml_ba_dim_1"; "caml_ba_dim_2"; "caml_ba_dim_3"; "caml_ba_fill"; "caml_ba_get_1"; "caml_ba_get_2"; "caml_ba_get_3"; "caml_ba_get_generic"; "caml_ba_kind"; "caml_ba_layout"; "caml_ba_num_dims"; "caml_ba_reshape"; "caml_ba_set_1"; "caml_ba_set_2"; "caml_ba_set_3"; "caml_ba_set_generic"; "caml_ba_slice"; "caml_ba_sub"; "caml_ba_uint8_get16"; "caml_ba_uint8_get32"; "caml_ba_uint8_get64"; "caml_ba_uint8_set16"; "caml_ba_uint8_set32"; "caml_ba_uint8_set64"; "caml_backtrace_status"; "caml_blit_bytes"; "caml_blit_string"; "caml_bswap16"; "caml_bytes_compare"; "caml_bytes_equal"; "caml_bytes_get"; "caml_bytes_get16"; "caml_bytes_get32"; "caml_bytes_get64"; "caml_bytes_greaterequal"; "caml_bytes_greaterthan"; "caml_bytes_lessequal"; "caml_bytes_lessthan"; "caml_bytes_notequal"; "caml_bytes_of_string"; "caml_bytes_set"; "caml_bytes_set16"; "caml_bytes_set32"; "caml_bytes_set64"; "caml_ceil_float"; "caml_channel_descriptor"; "caml_classify_float"; "caml_compare"; "caml_convert_raw_backtrace"; "caml_convert_raw_backtrace_slot"; "caml_copysign_float"; "caml_cos_float"; "caml_cosh_float"; "caml_create_bytes"; "caml_create_string"; "caml_div_float"; "caml_dynlink_add_primitive"; "caml_dynlink_close_lib"; "caml_dynlink_get_current_libs"; "caml_dynlink_lookup_symbol"; "caml_dynlink_open_lib"; "caml_ensure_stack_capacity"; "caml_ephe_blit_data"; "caml_ephe_blit_key"; "caml_ephe_check_data"; "caml_ephe_check_key"; "caml_ephe_create"; "caml_ephe_get_data"; "caml_ephe_get_data_copy"; "caml_ephe_get_key"; "caml_ephe_get_key_copy"; "caml_ephe_set_data"; "caml_ephe_set_key"; "caml_ephe_unset_data"; "caml_ephe_unset_key"; "caml_eq_float"; "caml_equal"; "caml_eventlog_pause"; "caml_eventlog_resume"; "caml_exp_float"; "caml_expm1_float"; "caml_fill_bytes"; "caml_fill_string"; "caml_final_register"; "caml_final_register_called_without_value"; "caml_final_release"; "caml_float_compare"; "caml_float_of_int"; "caml_float_of_string"; "caml_floatarray_blit"; "caml_floatarray_create"; "caml_floatarray_get"; "caml_floatarray_set"; "caml_floatarray_unsafe_get"; "caml_floatarray_unsafe_set"; "caml_floor_float"; "caml_fma_float"; "caml_fmod_float"; "caml_format_float"; "caml_format_int"; "caml_fresh_oo_id"; "caml_frexp_float"; "caml_gc_compaction"; "caml_gc_counters"; "caml_gc_full_major"; "caml_gc_get"; "caml_gc_huge_fallback_count"; "caml_gc_major"; "caml_gc_major_slice"; "caml_gc_minor"; "caml_gc_minor_words"; "caml_gc_quick_stat"; "caml_gc_set"; "caml_gc_stat"; "caml_ge_float"; "caml_get_current_callstack"; "caml_get_current_environment"; "caml_get_exception_backtrace"; "caml_get_exception_raw_backtrace"; "caml_get_global_data"; "caml_get_major_bucket"; "caml_get_major_credit"; "caml_get_minor_free"; "caml_get_public_method"; "caml_get_section_table"; "caml_greaterequal"; "caml_greaterthan"; "caml_gt_float"; "caml_hash"; "caml_hexstring_of_float"; "caml_hypot_float"; "caml_install_signal_handler"; "caml_int32_add"; "caml_int32_and"; "caml_int32_bits_of_float"; "caml_int32_bswap"; "caml_int32_compare"; "caml_int32_div"; "caml_int32_float_of_bits"; "caml_int32_format"; "caml_int32_mod"; "caml_int32_mul"; "caml_int32_neg"; "caml_int32_of_float"; "caml_int32_of_int"; "caml_int32_of_string"; "caml_int32_or"; "caml_int32_shift_left"; "caml_int32_shift_right"; "caml_int32_shift_right_unsigned"; "caml_int32_sub"; "caml_int32_to_float"; "caml_int32_to_int"; "caml_int32_xor"; "caml_int64_add"; "caml_int64_add_native"; "caml_int64_and"; "caml_int64_and_native"; "caml_int64_bits_of_float"; "caml_int64_bswap"; "caml_int64_compare"; "caml_int64_div"; "caml_int64_div_native"; "caml_int64_float_of_bits"; "caml_int64_format"; "caml_int64_mod"; "caml_int64_mod_native"; "caml_int64_mul"; "caml_int64_mul_native"; "caml_int64_neg"; "caml_int64_neg_native"; "caml_int64_of_float"; "caml_int64_of_int"; "caml_int64_of_int32"; "caml_int64_of_nativeint"; "caml_int64_of_string"; "caml_int64_or"; "caml_int64_or_native"; "caml_int64_shift_left"; "caml_int64_shift_right"; "caml_int64_shift_right_unsigned"; "caml_int64_sub"; "caml_int64_sub_native"; "caml_int64_to_float"; "caml_int64_to_int"; "caml_int64_to_int32"; "caml_int64_to_nativeint"; "caml_int64_xor"; "caml_int64_xor_native"; "caml_int_as_pointer"; "caml_int_compare"; "caml_int_of_float"; "caml_int_of_string"; "caml_lazy_make_forward"; "caml_ldexp_float"; "caml_le_float"; "caml_lessequal"; "caml_lessthan"; "caml_lex_engine"; "caml_log10_float"; "caml_log1p_float"; "caml_log_float"; "caml_lt_float"; "caml_make_array"; "caml_make_float_vect"; "caml_make_vect"; "caml_marshal_data_size"; "caml_md5_chan"; "caml_md5_string"; "caml_memprof_start"; "caml_memprof_stop"; "caml_ml_bytes_length"; "caml_ml_channel_size"; "caml_ml_channel_size_64"; "caml_ml_close_channel"; "caml_ml_debug_info_status"; "caml_ml_enable_runtime_warnings"; "caml_ml_flush"; "caml_ml_input"; "caml_ml_input_char"; "caml_ml_input_int"; "caml_ml_input_scan_line"; "caml_ml_open_descriptor_in"; "caml_ml_open_descriptor_out"; "caml_ml_out_channels_list"; "caml_ml_output"; "caml_ml_output_bytes"; "caml_ml_output_char"; "caml_ml_output_int"; "caml_ml_pos_in"; "caml_ml_pos_in_64"; "caml_ml_pos_out"; "caml_ml_pos_out_64"; "caml_ml_runtime_warnings_enabled"; "caml_ml_seek_in"; "caml_ml_seek_in_64"; "caml_ml_seek_out"; "caml_ml_seek_out_64"; "caml_ml_set_binary_mode"; "caml_ml_set_channel_name"; "caml_ml_string_length"; "caml_modf_float"; "caml_mul_float"; "caml_nativeint_add"; "caml_nativeint_and"; "caml_nativeint_bswap"; "caml_nativeint_compare"; "caml_nativeint_div"; "caml_nativeint_format"; "caml_nativeint_mod"; "caml_nativeint_mul"; "caml_nativeint_neg"; "caml_nativeint_of_float"; "caml_nativeint_of_int"; "caml_nativeint_of_int32"; "caml_nativeint_of_string"; "caml_nativeint_or"; "caml_nativeint_shift_left"; "caml_nativeint_shift_right"; "caml_nativeint_shift_right_unsigned"; "caml_nativeint_sub"; "caml_nativeint_to_float"; "caml_nativeint_to_int"; "caml_nativeint_to_int32"; "caml_nativeint_xor"; "caml_neg_float"; "caml_neq_float"; "caml_new_lex_engine"; "caml_nextafter_float"; "caml_notequal"; "caml_obj_block"; "caml_obj_make_forward"; "caml_obj_reachable_words"; "caml_obj_set_raw_field"; "caml_obj_set_tag"; "caml_obj_tag"; "caml_output_value"; "caml_output_value_to_buffer"; "caml_output_value_to_bytes"; "caml_output_value_to_string"; "caml_parse_engine"; "caml_power_float"; "caml_raw_backtrace_length"; "caml_raw_backtrace_next_slot"; "caml_raw_backtrace_slot"; "caml_realloc_global"; "caml_record_backtrace"; "caml_register_named_value"; "caml_reify_bytecode"; "caml_remove_debug_info"; "caml_reset_afl_instrumentation"; "caml_restore_raw_backtrace"; "caml_round_float"; "caml_runtime_parameters"; "caml_runtime_variant"; "caml_set_oo_id"; "caml_set_parser_trace"; "caml_setup_afl"; "caml_signbit"; "caml_signbit_float"; "caml_sin_float"; "caml_sinh_float"; "caml_sqrt_float"; "caml_static_release_bytecode"; "caml_string_compare"; "caml_string_equal"; "caml_string_get"; "caml_string_get16"; "caml_string_get32"; "caml_string_get64"; "caml_string_greaterequal"; "caml_string_greaterthan"; "caml_string_lessequal"; "caml_string_lessthan"; "caml_string_notequal"; "caml_string_of_bytes"; "caml_string_set"; "caml_sub_float"; "caml_sys_argv"; "caml_sys_chdir"; "caml_sys_close"; "caml_sys_const_backend_type"; "caml_sys_const_big_endian"; "caml_sys_const_int_size"; "caml_sys_const_max_wosize"; "caml_sys_const_naked_pointers_checked"; "caml_sys_const_ostype_cygwin"; "caml_sys_const_ostype_unix"; "caml_sys_const_ostype_win32"; "caml_sys_const_word_size"; "caml_sys_executable_name"; "caml_sys_exit"; "caml_sys_file_exists"; "caml_sys_get_argv"; "caml_sys_get_config"; "caml_sys_getcwd"; "caml_sys_getenv"; "caml_sys_is_directory"; "caml_sys_isatty"; "caml_sys_mkdir"; "caml_sys_modify_argv"; "caml_sys_open"; "caml_sys_random_seed"; "caml_sys_read_directory"; "caml_sys_remove"; "caml_sys_rename"; "caml_sys_rmdir"; "caml_sys_system_command"; "caml_sys_time"; "caml_sys_time_include_children"; "caml_sys_unsafe_getenv"; "caml_tan_float"; "caml_tanh_float"; "caml_terminfo_rows"; "caml_trunc_float"; "caml_update_dummy"; "caml_weak_blit"; "caml_weak_check"; "caml_weak_create"; "caml_weak_get"; "caml_weak_get_copy"; "caml_weak_set"; ] |> mk_table
e88329662fb31c6972bdf119c42e804c624c29f463810e12f9772c41b14851a1
osteele/cl-spec
failing-spec.lisp
Copyright 2008 by . Released under the MIT License . (in-package #:cl-user) (cl-spec:specify "a spec with some failing examples" () ("should pass" (=> (+ 1 2) should = 3)) ("should fail" (=> (+ 1 2) should = 4)) ("should also fail" (=> (+ 1 2) should = 4))) (cl-spec:specify "a spec with all passing examples" () ("first example should pass" (=> (+ 1 2) should = 3)) ("second example should also pass" (=> (+ 1 2) should = 3)))
null
https://raw.githubusercontent.com/osteele/cl-spec/d83b8a89d55771691e439e2fb910ce202dbd6abe/examples/failing-spec.lisp
lisp
Copyright 2008 by . Released under the MIT License . (in-package #:cl-user) (cl-spec:specify "a spec with some failing examples" () ("should pass" (=> (+ 1 2) should = 3)) ("should fail" (=> (+ 1 2) should = 4)) ("should also fail" (=> (+ 1 2) should = 4))) (cl-spec:specify "a spec with all passing examples" () ("first example should pass" (=> (+ 1 2) should = 3)) ("second example should also pass" (=> (+ 1 2) should = 3)))
bfb7f90d50faa558b9014db76a3cdf4c05912a0a0e52b96ced787745b25be202
input-output-hk/project-icarus-importer
DB.hs
-- | Re-exports of Pos.DB functionality. module Pos.DB ( module Pos.DB.Sum , module Pos.DB.Rocks , module Pos.DB.Pure , module Pos.DB.Functions , module Pos.DB.Error , module Pos.DB.Class , module Pos.DB.BlockIndex , module Pos.DB.BatchOp , module Pos.DB.Misc.Common , module Pos.DB.GState.Common , module Pos.DB.GState.Stakes ) where import Pos.DB.Sum import Pos.DB.Rocks import Pos.DB.Pure import Pos.DB.Functions import Pos.DB.Error import Pos.DB.Class import Pos.DB.BlockIndex import Pos.DB.BatchOp import Pos.DB.Misc.Common import Pos.DB.GState.Common import Pos.DB.GState.Stakes
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/db/Pos/DB.hs
haskell
| Re-exports of Pos.DB functionality.
module Pos.DB ( module Pos.DB.Sum , module Pos.DB.Rocks , module Pos.DB.Pure , module Pos.DB.Functions , module Pos.DB.Error , module Pos.DB.Class , module Pos.DB.BlockIndex , module Pos.DB.BatchOp , module Pos.DB.Misc.Common , module Pos.DB.GState.Common , module Pos.DB.GState.Stakes ) where import Pos.DB.Sum import Pos.DB.Rocks import Pos.DB.Pure import Pos.DB.Functions import Pos.DB.Error import Pos.DB.Class import Pos.DB.BlockIndex import Pos.DB.BatchOp import Pos.DB.Misc.Common import Pos.DB.GState.Common import Pos.DB.GState.Stakes
16fac32724aff5a2f9f7650013482d9e42e139e74d401b5a94590b8fc03163b5
RefactoringTools/HaRe
GuardsCase2.hs
module GuardsCase2 where f x = case x of 1 | x `mod` 4 == 0 -> g x where g x = x + 1 _ -> 42
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/testing/whereToLet/GuardsCase2.hs
haskell
module GuardsCase2 where f x = case x of 1 | x `mod` 4 == 0 -> g x where g x = x + 1 _ -> 42
9542c0aa80decf362a6c6783756a7e2bdf902cad3d32f1672cdb0819e24b4095
alanzplus/EOPL
2.18-test.rkt
#lang eopl (require rackunit "2.18.rkt") (require rackunit/text-ui) (define test-lst '(6 (5 4 3 2 1) (7 8 9))) (define node-in-sequence-test (test-suite "Tests for node in sequence" (check-equal? (number->sequence 7) '(7 () ())) (check-equal? (current-element test-lst) 6) (check-equal? (move-to-left test-lst) '(5 (4 3 2 1) (6 7 8 9))) (check-equal? (move-to-right test-lst) '(7 (6 5 4 3 2 1) (8 9))) (check-equal? (insert-to-left 13 test-lst) '(6 (13 5 4 3 2 1) (7 8 9))) (check-equal? (insert-to-right 13 test-lst) '(6 (5 4 3 2 1) (13 7 8 9))) )) (run-tests node-in-sequence-test)
null
https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/EOPL/ch2/2.18-test.rkt
racket
#lang eopl (require rackunit "2.18.rkt") (require rackunit/text-ui) (define test-lst '(6 (5 4 3 2 1) (7 8 9))) (define node-in-sequence-test (test-suite "Tests for node in sequence" (check-equal? (number->sequence 7) '(7 () ())) (check-equal? (current-element test-lst) 6) (check-equal? (move-to-left test-lst) '(5 (4 3 2 1) (6 7 8 9))) (check-equal? (move-to-right test-lst) '(7 (6 5 4 3 2 1) (8 9))) (check-equal? (insert-to-left 13 test-lst) '(6 (13 5 4 3 2 1) (7 8 9))) (check-equal? (insert-to-right 13 test-lst) '(6 (5 4 3 2 1) (13 7 8 9))) )) (run-tests node-in-sequence-test)
fe17ae92640e9fc831783cc5f3a323944ac350df5b58546ad9d6de4a9fb358a9
conscell/hugs-android
GetOpt.hs
# OPTIONS_GHC -cpp # ----------------------------------------------------------------------------- -- | Module : Distribution . Copyright : ( c ) 2002 - 2005 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- -- This library provides facilities for parsing the command-line options in a standalone program . It is essentially a Haskell port of the GNU -- @getopt@ library. -- ----------------------------------------------------------------------------- < > Oct. 1996 ( small changes Dec. 1997 ) Two rather obscure features are missing : The Bash 2.0 non - option hack ( if you do n't already know it , you probably do n't want to hear about it ... ) and the recognition of long options with a single dash ( e.g. ' -help ' is recognised as ' --help ' , as long as there is no short option ' h ' ) . Other differences between GNU 's and this implementation : * To enforce a coherent description of options and arguments , there are explanation fields in the option / argument descriptor . * Error messages are now more informative , but no longer POSIX compliant ... :-( And a final advertisement : The GNU C implementation uses well over 1100 lines , we need only 195 here , including a 46 line example ! :-) Sven Panne <> Oct. 1996 (small changes Dec. 1997) Two rather obscure features are missing: The Bash 2.0 non-option hack (if you don't already know it, you probably don't want to hear about it...) and the recognition of long options with a single dash (e.g. '-help' is recognised as '--help', as long as there is no short option 'h'). Other differences between GNU's getopt and this implementation: * To enforce a coherent description of options and arguments, there are explanation fields in the option/argument descriptor. * Error messages are now more informative, but no longer POSIX compliant... :-( And a final Haskell advertisement: The GNU C implementation uses well over 1100 lines, we need only 195 here, including a 46 line example! :-) -} -- #hide module Distribution.GetOpt ( * getOpt, getOpt', usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..), -- * Example -- $example ) where import System.Console.GetOpt $ example To hopefully illuminate the role of the different data structures , here\ 's the command - line options for a ( very simple ) compiler : > module where > > import Distribution . > import Data . Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | > deriving Show > > options : : [ OptDescr Flag ] > options = > [ Option [ ' v ' ] [ " verbose " ] ( ) " chatty output on stderr " > , Option [ ' V ' , ' ? ' ] [ " version " ] ( NoArg Version ) " show version number " > , Option [ ' o ' ] [ " output " ] ( OptArg outp " FILE " ) " output FILE " > , Option [ ' c ' ] [ ] ( OptArg inp " FILE " ) " input FILE " > , Option [ ' L ' ] [ " " ] ( ReqArg LibDir " DIR " ) " library directory " > ] > > , outp : : Maybe String - > Flag > outp = Output . fromMaybe " stdout " > inp = Input . fromMaybe " stdin " > > compilerOpts : : [ String ] - > IO ( [ Flag ] , [ String ] ) > compilerOpts argv = > case getOpt Permute options argv of > ( o , n , [ ] ) - > return ( o , n ) > ( _ , _ , errs ) - > ioError ( userError ( concat errs + + usageInfo header options ) ) > where header = " Usage : ic [ OPTION ... ] files ... " To hopefully illuminate the role of the different data structures, here\'s the command-line options for a (very simple) compiler: > module Opts where > > import Distribution.GetOpt > import Data.Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | LibDir String > deriving Show > > options :: [OptDescr Flag] > options = > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr" > , Option ['V','?'] ["version"] (NoArg Version) "show version number" > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE" > , Option ['c'] [] (OptArg inp "FILE") "input FILE" > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory" > ] > > inp,outp :: Maybe String -> Flag > outp = Output . fromMaybe "stdout" > inp = Input . fromMaybe "stdin" > > compilerOpts :: [String] -> IO ([Flag], [String]) > compilerOpts argv = > case getOpt Permute options argv of > (o,n,[] ) -> return (o,n) > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) > where header = "Usage: ic [OPTION...] files..." -}
null
https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/packages/Cabal/Distribution/GetOpt.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : portable This library provides facilities for parsing the command-line options @getopt@ library. --------------------------------------------------------------------------- help ' , as long as there is no short help', as long as there is no short #hide * Example $example
# OPTIONS_GHC -cpp # Module : Distribution . Copyright : ( c ) 2002 - 2005 in a standalone program . It is essentially a Haskell port of the GNU < > Oct. 1996 ( small changes Dec. 1997 ) Two rather obscure features are missing : The Bash 2.0 non - option hack ( if you do n't already know it , you probably do n't want to hear about it ... ) and the recognition of long options with a single dash option ' h ' ) . Other differences between GNU 's and this implementation : * To enforce a coherent description of options and arguments , there are explanation fields in the option / argument descriptor . * Error messages are now more informative , but no longer POSIX compliant ... :-( And a final advertisement : The GNU C implementation uses well over 1100 lines , we need only 195 here , including a 46 line example ! :-) Sven Panne <> Oct. 1996 (small changes Dec. 1997) Two rather obscure features are missing: The Bash 2.0 non-option hack (if you don't already know it, you probably don't want to hear about it...) and the recognition of long options with a single dash option 'h'). Other differences between GNU's getopt and this implementation: * To enforce a coherent description of options and arguments, there are explanation fields in the option/argument descriptor. * Error messages are now more informative, but no longer POSIX compliant... :-( And a final Haskell advertisement: The GNU C implementation uses well over 1100 lines, we need only 195 here, including a 46 line example! :-) -} module Distribution.GetOpt ( * getOpt, getOpt', usageInfo, ArgOrder(..), OptDescr(..), ArgDescr(..), ) where import System.Console.GetOpt $ example To hopefully illuminate the role of the different data structures , here\ 's the command - line options for a ( very simple ) compiler : > module where > > import Distribution . > import Data . Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | > deriving Show > > options : : [ OptDescr Flag ] > options = > [ Option [ ' v ' ] [ " verbose " ] ( ) " chatty output on stderr " > , Option [ ' V ' , ' ? ' ] [ " version " ] ( NoArg Version ) " show version number " > , Option [ ' o ' ] [ " output " ] ( OptArg outp " FILE " ) " output FILE " > , Option [ ' c ' ] [ ] ( OptArg inp " FILE " ) " input FILE " > , Option [ ' L ' ] [ " " ] ( ReqArg LibDir " DIR " ) " library directory " > ] > > , outp : : Maybe String - > Flag > outp = Output . fromMaybe " stdout " > inp = Input . fromMaybe " stdin " > > compilerOpts : : [ String ] - > IO ( [ Flag ] , [ String ] ) > compilerOpts argv = > case getOpt Permute options argv of > ( o , n , [ ] ) - > return ( o , n ) > ( _ , _ , errs ) - > ioError ( userError ( concat errs + + usageInfo header options ) ) > where header = " Usage : ic [ OPTION ... ] files ... " To hopefully illuminate the role of the different data structures, here\'s the command-line options for a (very simple) compiler: > module Opts where > > import Distribution.GetOpt > import Data.Maybe ( fromMaybe ) > > data Flag > = Verbose | Version > | Input String | Output String | LibDir String > deriving Show > > options :: [OptDescr Flag] > options = > [ Option ['v'] ["verbose"] (NoArg Verbose) "chatty output on stderr" > , Option ['V','?'] ["version"] (NoArg Version) "show version number" > , Option ['o'] ["output"] (OptArg outp "FILE") "output FILE" > , Option ['c'] [] (OptArg inp "FILE") "input FILE" > , Option ['L'] ["libdir"] (ReqArg LibDir "DIR") "library directory" > ] > > inp,outp :: Maybe String -> Flag > outp = Output . fromMaybe "stdout" > inp = Input . fromMaybe "stdin" > > compilerOpts :: [String] -> IO ([Flag], [String]) > compilerOpts argv = > case getOpt Permute options argv of > (o,n,[] ) -> return (o,n) > (_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options)) > where header = "Usage: ic [OPTION...] files..." -}
143ddf3af771d401ff96814cfbfcbaba6528e82a12d2a539d4e63d01063aebd8
tarcieri/reia
reia_bytecode.erl
% reia_bytecode : Generate bytecode from compiled Reia AST Copyright ( C)2009 - 10 % Redistribution is permitted under the MIT license . See LICENSE for details . % -module(reia_bytecode). -export([compile/2, compile/3, load_file/1, load/1, load/2]). -include("reia_nodes.hrl"). -include("reia_compile_options.hrl"). % Ideally this record is opaque to everything except this module % No other modules should operate directly on raw Reia bytecode -record(reia_module, {version=0, filename, base_module}). % Load the given file, executing its toplevel function load_file(Filename) -> {ok, Bin} = file:read_file(Filename), load(Bin). Load the given compiled Reia module , executing its toplevel function load(Bin) -> load(Bin, []). Load the given compiled Reia module , executing its toplevel function with % the given arguments (in order to pass along a default binding) load(Bin, Args) -> #reia_module{filename = Filename, base_module = Module} = binary_to_term(Bin), Name = list_to_atom(filename:rootname(Filename)), code:load_binary(Name, Filename, Module), Result = apply(Name, toplevel, Args), {ok, Name, Result}. % Compiled evaluation of a parsed Reia file compile(Filename, Exprs) -> compile(Filename, Exprs, #compile_options{}). compile(Filename, Exprs, Options) -> case compile_expressions(Filename, Exprs, Options) of {ok, _Module, Bin} -> Module = #reia_module{filename=Filename, base_module=Bin}, {ok, term_to_binary(Module)}; error -> throw({error, "internal Erlang compiler error"}) end. Output raw Erlang bytecode for inclusion into compiled Reia bytecode compile_expressions(Filename, Exprs, Options) -> {Module, Submodules} = case Options#compile_options.toplevel_wrapper of true -> wrapped_module(Filename, Exprs); false -> unwrapped_module(Exprs) end, Header = module_header(Module#module.name, Filename, Module#module.attrs, Options), Submodules2 = compile_submodules(Submodules, Filename, Options), SubmoduleAttr = {attribute, 1, submodules, Submodules2}, ErlModule = lists:flatten([Header, SubmoduleAttr, Module#module.exprs]), compile:forms(ErlModule, compile_options(Options)). compile_submodules(Submodules, Filename, Options) -> [compile_submodule(Submodule, Filename, Options) || Submodule <- Submodules]. compile_submodule(Module, Filename, Options) -> Header = module_header(Module#module.name, Filename, Module#module.attrs, Options), ErlModule = Header ++ Module#module.exprs, {ok, Name, Bin} = compile:forms(ErlModule, compile_options(Options)), {static, Name, Bin}. module_header(Name, Filename, CustomAttrs, Options) -> ParentAttr = {attribute, 1, parent, list_to_atom(filename:rootname(Filename))}, ErlAttrs = lists:map( fun({AttrName, Value}) -> {attribute, 1, AttrName, Value} end, CustomAttrs ), [ {attribute, 1, module, Name}, {attribute, 1, file, {Filename, 1}}, {attribute, 1, code, Options#compile_options.code}, ParentAttr|ErlAttrs ]. wrapped_module(Filename, Exprs) -> Name = list_to_atom(filename:rootname(Filename)), {ok, Exprs2, Submodules} = reia_modules:replace(Exprs, fun module_loader/1), Function = {function, 1, toplevel, 0, [ {clause, 1, [], [], Exprs2} ]}, Module = #module{line=1, name=Name, exprs=[Function]}, {Module, Submodules}. unwrapped_module(Exprs) -> case Exprs of [#module{} = Module] -> {ok, Functions2, Submodules} = reia_modules:replace(Module#module.exprs, fun module_loader/1), {Module#module{exprs=Functions2}, Submodules}; _ -> throw({error, "code without a toplevel wrapper should define exactly one module"}) end. compile_options(Options) -> ErlOptions = Options#compile_options.erlc_options, HiPEAvailable = hipe_available(), if Options#compile_options.autohipe and HiPEAvailable -> [native|ErlOptions]; true -> ErlOptions end. hipe_available() -> case erlang:system_info(hipe_architecture) of undefined -> false; _ -> true end. module_loader(Module) -> Name = Module#module.name, {call,1, {remote,1,{atom,1,reia_internal},{atom,1,load_submodule}}, [{atom,1,Name},{call,1,{atom,1,module_info},[{atom,1,attributes}]}] }.
null
https://raw.githubusercontent.com/tarcieri/reia/77b8b5603ae5d89a0d8fc0b3e179ef052260b5bf/src/compiler/reia_bytecode.erl
erlang
Ideally this record is opaque to everything except this module No other modules should operate directly on raw Reia bytecode Load the given file, executing its toplevel function the given arguments (in order to pass along a default binding) Compiled evaluation of a parsed Reia file
reia_bytecode : Generate bytecode from compiled Reia AST Copyright ( C)2009 - 10 Redistribution is permitted under the MIT license . See LICENSE for details . -module(reia_bytecode). -export([compile/2, compile/3, load_file/1, load/1, load/2]). -include("reia_nodes.hrl"). -include("reia_compile_options.hrl"). -record(reia_module, {version=0, filename, base_module}). load_file(Filename) -> {ok, Bin} = file:read_file(Filename), load(Bin). Load the given compiled Reia module , executing its toplevel function load(Bin) -> load(Bin, []). Load the given compiled Reia module , executing its toplevel function with load(Bin, Args) -> #reia_module{filename = Filename, base_module = Module} = binary_to_term(Bin), Name = list_to_atom(filename:rootname(Filename)), code:load_binary(Name, Filename, Module), Result = apply(Name, toplevel, Args), {ok, Name, Result}. compile(Filename, Exprs) -> compile(Filename, Exprs, #compile_options{}). compile(Filename, Exprs, Options) -> case compile_expressions(Filename, Exprs, Options) of {ok, _Module, Bin} -> Module = #reia_module{filename=Filename, base_module=Bin}, {ok, term_to_binary(Module)}; error -> throw({error, "internal Erlang compiler error"}) end. Output raw Erlang bytecode for inclusion into compiled Reia bytecode compile_expressions(Filename, Exprs, Options) -> {Module, Submodules} = case Options#compile_options.toplevel_wrapper of true -> wrapped_module(Filename, Exprs); false -> unwrapped_module(Exprs) end, Header = module_header(Module#module.name, Filename, Module#module.attrs, Options), Submodules2 = compile_submodules(Submodules, Filename, Options), SubmoduleAttr = {attribute, 1, submodules, Submodules2}, ErlModule = lists:flatten([Header, SubmoduleAttr, Module#module.exprs]), compile:forms(ErlModule, compile_options(Options)). compile_submodules(Submodules, Filename, Options) -> [compile_submodule(Submodule, Filename, Options) || Submodule <- Submodules]. compile_submodule(Module, Filename, Options) -> Header = module_header(Module#module.name, Filename, Module#module.attrs, Options), ErlModule = Header ++ Module#module.exprs, {ok, Name, Bin} = compile:forms(ErlModule, compile_options(Options)), {static, Name, Bin}. module_header(Name, Filename, CustomAttrs, Options) -> ParentAttr = {attribute, 1, parent, list_to_atom(filename:rootname(Filename))}, ErlAttrs = lists:map( fun({AttrName, Value}) -> {attribute, 1, AttrName, Value} end, CustomAttrs ), [ {attribute, 1, module, Name}, {attribute, 1, file, {Filename, 1}}, {attribute, 1, code, Options#compile_options.code}, ParentAttr|ErlAttrs ]. wrapped_module(Filename, Exprs) -> Name = list_to_atom(filename:rootname(Filename)), {ok, Exprs2, Submodules} = reia_modules:replace(Exprs, fun module_loader/1), Function = {function, 1, toplevel, 0, [ {clause, 1, [], [], Exprs2} ]}, Module = #module{line=1, name=Name, exprs=[Function]}, {Module, Submodules}. unwrapped_module(Exprs) -> case Exprs of [#module{} = Module] -> {ok, Functions2, Submodules} = reia_modules:replace(Module#module.exprs, fun module_loader/1), {Module#module{exprs=Functions2}, Submodules}; _ -> throw({error, "code without a toplevel wrapper should define exactly one module"}) end. compile_options(Options) -> ErlOptions = Options#compile_options.erlc_options, HiPEAvailable = hipe_available(), if Options#compile_options.autohipe and HiPEAvailable -> [native|ErlOptions]; true -> ErlOptions end. hipe_available() -> case erlang:system_info(hipe_architecture) of undefined -> false; _ -> true end. module_loader(Module) -> Name = Module#module.name, {call,1, {remote,1,{atom,1,reia_internal},{atom,1,load_submodule}}, [{atom,1,Name},{call,1,{atom,1,module_info},[{atom,1,attributes}]}] }.
59123cd940a2b9d6c7d088cc76d87c46080473c51e39ad799edd704582f721d4
purcell/adventofcode2016
Day2.hs
module Main where import AdventOfCode import qualified Data.Map as M import Data.Maybe (fromMaybe) data Direction = U | D | L | R data Button = Button { bNum :: String , bPos :: (Int, Int) } deriving (Show) type Grid = (Int, Int) -> Maybe String makeGrid :: [String] -> Grid makeGrid gridRows = flip M.lookup gridMap where gridMap = M.fromList [ ((x, y), [c]) | (y, l) <- lines , (x, c) <- line l , c /= ' ' ] lines = zip [0 ..] gridRows line = zip [0 ..] squareGrid = makeGrid ["123", "456", "798"] diamondGrid = makeGrid [" 1 ", " 234 ", "56789", " ABC ", " D "] maybeButton :: Grid -> (Int, Int) -> Maybe Button maybeButton grid pos = flip Button pos <$> grid pos neighbour :: Grid -> Button -> Direction -> Maybe Button neighbour grid (Button _ (x, y)) U = maybeButton grid (x, y - 1) neighbour grid (Button _ (x, y)) D = maybeButton grid (x, y + 1) neighbour grid (Button _ (x, y)) L = maybeButton grid (x - 1, y) neighbour grid (Button _ (x, y)) R = maybeButton grid (x + 1, y) move :: Grid -> Button -> Direction -> Button move grid b d = fromMaybe b $ neighbour grid b d code :: Grid -> Button -> [[Direction]] -> String code grid init lines = concatMap bNum $ tail (scanl followLine init lines) where followLine = foldl (move grid) parseDirection :: Parser Direction parseDirection = string "U" *> return U <|> string "D" *> return D <|> string "L" *> return L <|> string "R" *> return R main = runDay $ Day 2 (many1 (many1 parseDirection <* newline)) (return . code squareGrid (Button "5" (1, 1))) (return . code diamondGrid (Button "5" (0, 2)))
null
https://raw.githubusercontent.com/purcell/adventofcode2016/081f30de4ea6b939e6c3736d83836f4dd72ab9a2/src/Day2.hs
haskell
module Main where import AdventOfCode import qualified Data.Map as M import Data.Maybe (fromMaybe) data Direction = U | D | L | R data Button = Button { bNum :: String , bPos :: (Int, Int) } deriving (Show) type Grid = (Int, Int) -> Maybe String makeGrid :: [String] -> Grid makeGrid gridRows = flip M.lookup gridMap where gridMap = M.fromList [ ((x, y), [c]) | (y, l) <- lines , (x, c) <- line l , c /= ' ' ] lines = zip [0 ..] gridRows line = zip [0 ..] squareGrid = makeGrid ["123", "456", "798"] diamondGrid = makeGrid [" 1 ", " 234 ", "56789", " ABC ", " D "] maybeButton :: Grid -> (Int, Int) -> Maybe Button maybeButton grid pos = flip Button pos <$> grid pos neighbour :: Grid -> Button -> Direction -> Maybe Button neighbour grid (Button _ (x, y)) U = maybeButton grid (x, y - 1) neighbour grid (Button _ (x, y)) D = maybeButton grid (x, y + 1) neighbour grid (Button _ (x, y)) L = maybeButton grid (x - 1, y) neighbour grid (Button _ (x, y)) R = maybeButton grid (x + 1, y) move :: Grid -> Button -> Direction -> Button move grid b d = fromMaybe b $ neighbour grid b d code :: Grid -> Button -> [[Direction]] -> String code grid init lines = concatMap bNum $ tail (scanl followLine init lines) where followLine = foldl (move grid) parseDirection :: Parser Direction parseDirection = string "U" *> return U <|> string "D" *> return D <|> string "L" *> return L <|> string "R" *> return R main = runDay $ Day 2 (many1 (many1 parseDirection <* newline)) (return . code squareGrid (Button "5" (1, 1))) (return . code diamondGrid (Button "5" (0, 2)))
917295f126b154b478965109ddfd6020b97816e889e003610754afed1feeb75b
camlp5/camlp5
odyl_main.ml
(* camlp5r pa_macro.cmo *) (* odyl_main.ml,v *) Copyright ( c ) INRIA 2007 - 2017 let go = ref (fun () -> ());; let name = ref "odyl";; let first_arg_no_load () = let rec loop i = if i < Array.length Sys.argv then match Sys.argv.(i) with "-I" -> loop (i + 2) | "-nolib" -> loop (i + 1) | "-where" -> loop (i + 1) | "--" -> i + 1 | s -> if Filename.check_suffix s ".cmo" || Filename.check_suffix s ".cma" then loop (i + 1) else i else i in loop 1 ;; Arg.current := first_arg_no_load () - 1;; (* Load files in core *) let find_in_path path name = if Filename.basename name <> name then if Sys.file_exists name then name else raise Not_found else let rec try_dir = function [] -> raise Not_found | dir :: rem -> let fullname = Filename.concat dir name in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path ;; exception Error of string * string;; let nolib = ref false;; let initialized = ref false;; let path = ref ([] : string list);; let loadfile file = if not !initialized then begin Dynlink.allow_unsafe_modules true; initialized := true end; let path = if !nolib then !path else Odyl_config.standard_library :: !path in let fname = try find_in_path (List.rev path) file with Not_found -> raise (Error (file, "file not found in path")) in try Dynlink.loadfile fname with Dynlink.Error e -> raise (Error (fname, Dynlink.error_message e)) ;; let directory d = path := d :: !path;;
null
https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/ocaml_src/odyl/odyl_main.ml
ocaml
camlp5r pa_macro.cmo odyl_main.ml,v Load files in core
Copyright ( c ) INRIA 2007 - 2017 let go = ref (fun () -> ());; let name = ref "odyl";; let first_arg_no_load () = let rec loop i = if i < Array.length Sys.argv then match Sys.argv.(i) with "-I" -> loop (i + 2) | "-nolib" -> loop (i + 1) | "-where" -> loop (i + 1) | "--" -> i + 1 | s -> if Filename.check_suffix s ".cmo" || Filename.check_suffix s ".cma" then loop (i + 1) else i else i in loop 1 ;; Arg.current := first_arg_no_load () - 1;; let find_in_path path name = if Filename.basename name <> name then if Sys.file_exists name then name else raise Not_found else let rec try_dir = function [] -> raise Not_found | dir :: rem -> let fullname = Filename.concat dir name in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path ;; exception Error of string * string;; let nolib = ref false;; let initialized = ref false;; let path = ref ([] : string list);; let loadfile file = if not !initialized then begin Dynlink.allow_unsafe_modules true; initialized := true end; let path = if !nolib then !path else Odyl_config.standard_library :: !path in let fname = try find_in_path (List.rev path) file with Not_found -> raise (Error (file, "file not found in path")) in try Dynlink.loadfile fname with Dynlink.Error e -> raise (Error (fname, Dynlink.error_message e)) ;; let directory d = path := d :: !path;;
18ec3a26c0736a7cbe65a99762739c18918f9f64e40635f3cc4c47d63ee38e1e
ocsigen/js_of_ocaml
test.ml
(* TEST *) let is_even x = (x mod 2 = 0) let string_of_even_opt x = if is_even x then Some (string_of_int x) else None let string_of_even_or_int x = if is_even x then Either.Left (string_of_int x) else Either.Right x (* Standard test case *) let () = let l = List.init 10 (fun x -> x) in let sl = List.init 10 string_of_int in assert (List.exists (fun a -> a < 10) l); assert (List.exists (fun a -> a > 0) l); assert (List.exists (fun a -> a = 0) l); assert (List.exists (fun a -> a = 1) l); assert (List.exists (fun a -> a = 2) l); assert (List.exists (fun a -> a = 3) l); assert (List.exists (fun a -> a = 4) l); assert (List.exists (fun a -> a = 5) l); assert (List.exists (fun a -> a = 6) l); assert (List.exists (fun a -> a = 7) l); assert (List.exists (fun a -> a = 8) l); assert (List.exists (fun a -> a = 9) l); assert (not (List.exists (fun a -> a < 0) l)); assert (not (List.exists (fun a -> a > 9) l)); assert (List.exists (fun _ -> true) l); assert (List.equal (=) [1; 2; 3] [1; 2; 3]); assert (not (List.equal (=) [1; 2; 3] [1; 2])); assert (not (List.equal (=) [1; 2; 3] [1; 3; 2])); (* The current implementation of List.equal calls the comparison function even for different-size lists. This is not part of the specification, so it would be valid to change this behavior, but we don't want to change it without noticing so here is a test for it. *) assert (let c = ref 0 in not (List.equal (fun _ _ -> incr c; true) [1; 2] [1; 2; 3]) && !c = 2); assert (List.compare compare [1; 2; 3] [1; 2; 3] = 0); assert (List.compare compare [1; 2; 3] [1; 2] > 0); assert (List.compare compare [1; 2; 3] [1; 3; 2] < 0); assert (List.compare compare [3] [2; 1] > 0); begin let f ~limit a = if a >= limit then Some (a, limit) else None in assert (List.find_map (f ~limit:3) [] = None); assert (List.find_map (f ~limit:3) l = Some (3, 3)); assert (List.find_map (f ~limit:30) l = None); end; assert (List.filteri (fun i _ -> i < 2) (List.rev l) = [9; 8]); assert (List.partition is_even [1; 2; 3; 4; 5] = ([2; 4], [1; 3; 5])); assert (List.partition_map string_of_even_or_int [1; 2; 3; 4; 5] = (["2"; "4"], [1; 3; 5])); assert (List.compare_lengths [] [] = 0); assert (List.compare_lengths [1;2] ['a';'b'] = 0); assert (List.compare_lengths [] [1;2] < 0); assert (List.compare_lengths ['a'] [1;2] < 0); assert (List.compare_lengths [1;2] [] > 0); assert (List.compare_lengths [1;2] ['a'] > 0); assert (List.compare_length_with [] 0 = 0); assert (List.compare_length_with [] 1 < 0); assert (List.compare_length_with [] (-1) > 0); assert (List.compare_length_with [] max_int < 0); assert (List.compare_length_with [] min_int > 0); assert (List.compare_length_with [1] 0 > 0); assert (List.compare_length_with ['1'] 1 = 0); assert (List.compare_length_with ['1'] 2 < 0); assert (List.filter_map string_of_even_opt l = ["0";"2";"4";"6";"8"]); assert (List.concat_map (fun i -> [i; i+1]) [1; 5] = [1; 2; 5; 6]); assert ( let count = ref 0 in List.concat_map (fun i -> incr count; [i; !count]) [1; 5] = [1; 1; 5; 2]); assert (List.fold_left_map (fun a b -> a + b, b) 0 l = (45, l)); assert (List.fold_left_map (fun a b -> assert false) 0 [] = (0, [])); assert ( let f a b = a + b, string_of_int b in List.fold_left_map f 0 l = (45, sl)); () ;; (* Empty test case *) let () = assert ((List.init 0 (fun x -> x)) = []); ;; (* Erroneous test case *) let () = let result = try let _ = List.init (-1) (fun x -> x) in false with Invalid_argument e -> true (* Exception caught *) in assert result; ;; (* Evaluation order *) let () = let test n = let result = ref false in let _ = List.init n (fun x -> result := (x = n - 1)) in assert !result in (* Threshold must equal the value in stdlib/list.ml *) let threshold = 10_000 in test threshold; (* Non tail-recursive case *) test (threshold + 1) (* Tail-recursive case *) ;; let () = print_endline "OK";;
null
https://raw.githubusercontent.com/ocsigen/js_of_ocaml/31c8a3d9d4e34f3fd573dd5056e733233ca4f4f6/compiler/tests-ocaml/lib-list/test.ml
ocaml
TEST Standard test case The current implementation of List.equal calls the comparison function even for different-size lists. This is not part of the specification, so it would be valid to change this behavior, but we don't want to change it without noticing so here is a test for it. Empty test case Erroneous test case Exception caught Evaluation order Threshold must equal the value in stdlib/list.ml Non tail-recursive case Tail-recursive case
let is_even x = (x mod 2 = 0) let string_of_even_opt x = if is_even x then Some (string_of_int x) else None let string_of_even_or_int x = if is_even x then Either.Left (string_of_int x) else Either.Right x let () = let l = List.init 10 (fun x -> x) in let sl = List.init 10 string_of_int in assert (List.exists (fun a -> a < 10) l); assert (List.exists (fun a -> a > 0) l); assert (List.exists (fun a -> a = 0) l); assert (List.exists (fun a -> a = 1) l); assert (List.exists (fun a -> a = 2) l); assert (List.exists (fun a -> a = 3) l); assert (List.exists (fun a -> a = 4) l); assert (List.exists (fun a -> a = 5) l); assert (List.exists (fun a -> a = 6) l); assert (List.exists (fun a -> a = 7) l); assert (List.exists (fun a -> a = 8) l); assert (List.exists (fun a -> a = 9) l); assert (not (List.exists (fun a -> a < 0) l)); assert (not (List.exists (fun a -> a > 9) l)); assert (List.exists (fun _ -> true) l); assert (List.equal (=) [1; 2; 3] [1; 2; 3]); assert (not (List.equal (=) [1; 2; 3] [1; 2])); assert (not (List.equal (=) [1; 2; 3] [1; 3; 2])); assert (let c = ref 0 in not (List.equal (fun _ _ -> incr c; true) [1; 2] [1; 2; 3]) && !c = 2); assert (List.compare compare [1; 2; 3] [1; 2; 3] = 0); assert (List.compare compare [1; 2; 3] [1; 2] > 0); assert (List.compare compare [1; 2; 3] [1; 3; 2] < 0); assert (List.compare compare [3] [2; 1] > 0); begin let f ~limit a = if a >= limit then Some (a, limit) else None in assert (List.find_map (f ~limit:3) [] = None); assert (List.find_map (f ~limit:3) l = Some (3, 3)); assert (List.find_map (f ~limit:30) l = None); end; assert (List.filteri (fun i _ -> i < 2) (List.rev l) = [9; 8]); assert (List.partition is_even [1; 2; 3; 4; 5] = ([2; 4], [1; 3; 5])); assert (List.partition_map string_of_even_or_int [1; 2; 3; 4; 5] = (["2"; "4"], [1; 3; 5])); assert (List.compare_lengths [] [] = 0); assert (List.compare_lengths [1;2] ['a';'b'] = 0); assert (List.compare_lengths [] [1;2] < 0); assert (List.compare_lengths ['a'] [1;2] < 0); assert (List.compare_lengths [1;2] [] > 0); assert (List.compare_lengths [1;2] ['a'] > 0); assert (List.compare_length_with [] 0 = 0); assert (List.compare_length_with [] 1 < 0); assert (List.compare_length_with [] (-1) > 0); assert (List.compare_length_with [] max_int < 0); assert (List.compare_length_with [] min_int > 0); assert (List.compare_length_with [1] 0 > 0); assert (List.compare_length_with ['1'] 1 = 0); assert (List.compare_length_with ['1'] 2 < 0); assert (List.filter_map string_of_even_opt l = ["0";"2";"4";"6";"8"]); assert (List.concat_map (fun i -> [i; i+1]) [1; 5] = [1; 2; 5; 6]); assert ( let count = ref 0 in List.concat_map (fun i -> incr count; [i; !count]) [1; 5] = [1; 1; 5; 2]); assert (List.fold_left_map (fun a b -> a + b, b) 0 l = (45, l)); assert (List.fold_left_map (fun a b -> assert false) 0 [] = (0, [])); assert ( let f a b = a + b, string_of_int b in List.fold_left_map f 0 l = (45, sl)); () ;; let () = assert ((List.init 0 (fun x -> x)) = []); ;; let () = let result = try let _ = List.init (-1) (fun x -> x) in false in assert result; ;; let () = let test n = let result = ref false in let _ = List.init n (fun x -> result := (x = n - 1)) in assert !result in let threshold = 10_000 in ;; let () = print_endline "OK";;
5164fdb6467d7fe761e98bc39c3cf871b2d2ea5c4b61ec839ed50befe10aedca
synduce/Synduce
min.ml
* @synduce -s 2 --no - lifting -NB --se2gis type itree = | Leaf of int | Node of int * itree * itree let rec is_symmetric = function | Leaf x -> true | Node (a, l, r) -> symm1 l r && is_symmetric l && is_symmetric r and symm1 l = function | Leaf x -> is_leaf x l | Node (ar, rl, rr) -> symm2 ar rl rr l and symm2 ar rl rr = function | Leaf x -> false | Node (al, ll, lr) -> al = ar && symm1 lr rl && symm1 ll rr and is_leaf x = function | Leaf y -> x = y | Node (a, l, r) -> false ;; let rec amin = function | Leaf x -> x | Node (a, l, r) -> min a (min (amin l) (amin r)) ;; In a symmetric tree we should only need to compute the min for half the tree . let rec amin2 = function | Leaf x -> [%synt s0] x | Node (a, l, r) -> [%synt f0] a (amin2 l) [@@requires is_symmetric] ;; assert (amin2 = amin)
null
https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/constraints/symmetric_tree/min.ml
ocaml
* @synduce -s 2 --no - lifting -NB --se2gis type itree = | Leaf of int | Node of int * itree * itree let rec is_symmetric = function | Leaf x -> true | Node (a, l, r) -> symm1 l r && is_symmetric l && is_symmetric r and symm1 l = function | Leaf x -> is_leaf x l | Node (ar, rl, rr) -> symm2 ar rl rr l and symm2 ar rl rr = function | Leaf x -> false | Node (al, ll, lr) -> al = ar && symm1 lr rl && symm1 ll rr and is_leaf x = function | Leaf y -> x = y | Node (a, l, r) -> false ;; let rec amin = function | Leaf x -> x | Node (a, l, r) -> min a (min (amin l) (amin r)) ;; In a symmetric tree we should only need to compute the min for half the tree . let rec amin2 = function | Leaf x -> [%synt s0] x | Node (a, l, r) -> [%synt f0] a (amin2 l) [@@requires is_symmetric] ;; assert (amin2 = amin)
b8b0c50cdfc45ec89483c5924c84ea610f435ad3ae51a68a73f382cda33a9354
lambdaclass/erlang-katana
ktn_random_SUITE.erl
-module(ktn_random_SUITE). -export([ all/0, init_per_suite/1, end_per_suite/1 ]). -export([ string/1, uniform/1, pick/1 ]). -define(EXCLUDED_FUNS, [ module_info, all, test, init_per_suite, end_per_suite ]). -type config() :: [{atom(), term()}]. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Common test %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec all() -> [atom()]. all() -> Exports = ?MODULE:module_info(exports), [F || {F, _} <- Exports, not lists:member(F, ?EXCLUDED_FUNS)]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> Config. -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> Config. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Test Cases %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec string(config()) -> ok. string(_Config) -> true = is_list(ktn_random:string()), 16 = length(ktn_random:string()), 25 = length(ktn_random:string(25)), ok. -spec uniform(config()) -> ok. uniform(_Config) -> Times = 10000, do_times(fun (_) -> in_range(ktn_random:uniform(10), 1, 10) end, Times), {error, _} = ktn_random:uniform(0), do_times(fun (_) -> in_range(ktn_random:uniform(5, 90), 5, 90) end, Times), {error, _} = ktn_random:uniform(165, 165), {error, _} = ktn_random:uniform(15, 5), ok. -spec pick(config()) -> ok. pick(_Config) -> [1, 2, 3, 4] = [ktn_random:pick([I]) || I <- lists:seq(1, 4)], lists:foreach( fun(I) -> List = lists:seq($a, $a + I), K = ktn_random:pick(List), true = lists:member(K, List) end, lists:seq(1, 1000)). do_times(Fun, N) -> lists:foreach(Fun, lists:seq(1, N)). in_range(X, Min, Max) when Min =< X, X =< Max -> ok.
null
https://raw.githubusercontent.com/lambdaclass/erlang-katana/ebb6b1358c974b5e3b16f5e95422061385ae34ac/test/ktn_random_SUITE.erl
erlang
Common test Test Cases
-module(ktn_random_SUITE). -export([ all/0, init_per_suite/1, end_per_suite/1 ]). -export([ string/1, uniform/1, pick/1 ]). -define(EXCLUDED_FUNS, [ module_info, all, test, init_per_suite, end_per_suite ]). -type config() :: [{atom(), term()}]. -spec all() -> [atom()]. all() -> Exports = ?MODULE:module_info(exports), [F || {F, _} <- Exports, not lists:member(F, ?EXCLUDED_FUNS)]. -spec init_per_suite(config()) -> config(). init_per_suite(Config) -> Config. -spec end_per_suite(config()) -> config(). end_per_suite(Config) -> Config. -spec string(config()) -> ok. string(_Config) -> true = is_list(ktn_random:string()), 16 = length(ktn_random:string()), 25 = length(ktn_random:string(25)), ok. -spec uniform(config()) -> ok. uniform(_Config) -> Times = 10000, do_times(fun (_) -> in_range(ktn_random:uniform(10), 1, 10) end, Times), {error, _} = ktn_random:uniform(0), do_times(fun (_) -> in_range(ktn_random:uniform(5, 90), 5, 90) end, Times), {error, _} = ktn_random:uniform(165, 165), {error, _} = ktn_random:uniform(15, 5), ok. -spec pick(config()) -> ok. pick(_Config) -> [1, 2, 3, 4] = [ktn_random:pick([I]) || I <- lists:seq(1, 4)], lists:foreach( fun(I) -> List = lists:seq($a, $a + I), K = ktn_random:pick(List), true = lists:member(K, List) end, lists:seq(1, 1000)). do_times(Fun, N) -> lists:foreach(Fun, lists:seq(1, N)). in_range(X, Min, Max) when Min =< X, X =< Max -> ok.
ea070da27673873fe10d224ad569f9f70ac3582dfc6b5548314b4d498f183c01
argp/bap
asmir_vars.ml
(** Asmir variables *) open Type let x86_regs = Disasm_i386.regs_x86 let x64_regs = Disasm_i386.regs_x86_64 let full_regs = Disasm_i386.regs_full let x86_mem = Disasm_i386.R32.mem let x64_mem = Disasm_i386.R64.mem module X86 = struct module R32 = Disasm_i386.R32 module R64 = Disasm_i386.R64 end let mem_of_type = function | Type.Reg 32 -> x86_mem | Type.Reg 64 -> x64_mem | t -> failwith (Printf.sprintf "Unable to find memory for address type %s" (Pp.typ_to_string t)) let arm_regs = List.map (fun n -> Var.newvar n (Reg 32)) [ "R0"; "R1"; "R2"; "R3"; "R4"; "R5"; "R6"; "R7"; "R8"; "R9"; "R10"; "R11"; "R12"; "R13"; "R14"; "R15T"; "CC"; "CC_OP"; "CC_DEP1"; "CC_DEP2"; "CC_NDEP"; ] let subregs = [ (* x86 subregisters *) ("R_AL_32", ("R_EAX_32", 0, Reg 32)); ("R_BL_32", ("R_EBX_32", 0, Reg 32)); ("R_CL_32", ("R_ECX_32", 0, Reg 32)); ("R_DL_32", ("R_EDX_32", 0, Reg 32)); ("R_AH_32", ("R_EAX_32", 8, Reg 32)); ("R_BH_32", ("R_EBX_32", 8, Reg 32)); ("R_CH_32", ("R_ECX_32", 8, Reg 32)); ("R_DH_32", ("R_EDX_32", 8, Reg 32)); ("R_DI_32", ("R_EDI_32", 0, Reg 32)); ("R_SI_32", ("R_ESI_32", 0, Reg 32)); ("R_BP_32", ("R_EBP_32", 0, Reg 32)); ("R_SP_32", ("R_ESP_32", 0, Reg 32)); ("R_AX_32", ("R_EAX_32", 0, Reg 32)); ("R_BX_32", ("R_EBX_32", 0, Reg 32)); ("R_CX_32", ("R_ECX_32", 0, Reg 32)); ("R_DX_32", ("R_EDX_32", 0, Reg 32)); ("R_BP_32", ("R_EBP_32", 0, Reg 32)); ("R_SI_32", ("R_ESI_32", 0, Reg 32)); ("R_DI_32", ("R_EDI_32", 0, Reg 32)); ("R_SP_32", ("R_ESP_32", 0, Reg 32)); (* x64 subregisters *) ("R_AL_64", ("R_RAX", 0, Reg 64)); ("R_BL_64", ("R_RBX", 0, Reg 64)); ("R_CL_64", ("R_RCX", 0, Reg 64)); ("R_DL_64", ("R_RDX", 0, Reg 64)); ("R_AH_64", ("R_RAX", 8, Reg 64)); ("R_BH_64", ("R_RBX", 8, Reg 64)); ("R_CH_64", ("R_RCX", 8, Reg 64)); ("R_DH_64", ("R_RDX", 8, Reg 64)); ("R_DIL", ("R_RDI", 0, Reg 64)); ("R_SIL", ("R_RSI", 0, Reg 64)); ("R_BPL", ("R_RBP", 0, Reg 64)); ("R_SPL", ("R_RSP", 0, Reg 64)); ("R_DI_64", ("R_RDI", 0, Reg 64)); ("R_SI_64", ("R_RSI", 0, Reg 64)); ("R_BP_64", ("R_RBP", 0, Reg 64)); ("R_SP_64", ("R_RSP", 0, Reg 64)); ("R_AX_64", ("R_RAX", 0, Reg 64)); ("R_BX_64", ("R_RBX", 0, Reg 64)); ("R_CX_64", ("R_RCX", 0, Reg 64)); ("R_DX_64", ("R_RDX", 0, Reg 64)); ("R_BP_64", ("R_RBP", 0, Reg 64)); ("R_SI_64", ("R_RSI", 0, Reg 64)); ("R_DI_64", ("R_RDI", 0, Reg 64)); ("R_SP_64", ("R_RSP", 0, Reg 64)); ("R_EAX_64", ("R_RAX", 0, Reg 64)); ("R_EBX_64", ("R_RBX", 0, Reg 64)); ("R_ECX_64", ("R_RCX", 0, Reg 64)); ("R_EDX_64", ("R_RDX", 0, Reg 64)); ("R_EBP_64", ("R_RBP", 0, Reg 64)); ("R_ESI_64", ("R_RSI", 0, Reg 64)); ("R_EDI_64", ("R_RDI", 0, Reg 64)); ("R_ESP_64", ("R_RSP", 0, Reg 64)); ] @ Array.to_list (Array.init 16 (fun i -> (Printf.sprintf "R_XMM%d" i, (Printf.sprintf "R_YMM%d" i, 0, Reg 256)))) @ Array.to_list (Array.init 16 (fun i -> (Printf.sprintf "R_MM%d" i, (Printf.sprintf "R_YMM%d" i, 0, Reg 256)))) @ Array.to_list (Array.init 8 (fun i -> (Printf.sprintf "R_R%dL" (i+8), (Printf.sprintf "R_R%d" (i+8), 0, Reg 64)))) @ Array.to_list (Array.init 8 (fun i -> (Printf.sprintf "R_R%dW" (i+8), (Printf.sprintf "R_R%d" (i+8), 0, Reg 64)))) @ Array.to_list (Array.init 8 (fun i -> (Printf.sprintf "R_R%dD" (i+8), (Printf.sprintf "R_R%d" (i+8), 0, Reg 64)))) let x86_all_regs = x86_mem :: x86_regs @ arm_regs let x64_all_regs = x64_mem :: x64_regs let multiarch_all_regs = x64_mem :: x86_mem :: full_regs
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocaml/asmir_vars.ml
ocaml
* Asmir variables x86 subregisters x64 subregisters
open Type let x86_regs = Disasm_i386.regs_x86 let x64_regs = Disasm_i386.regs_x86_64 let full_regs = Disasm_i386.regs_full let x86_mem = Disasm_i386.R32.mem let x64_mem = Disasm_i386.R64.mem module X86 = struct module R32 = Disasm_i386.R32 module R64 = Disasm_i386.R64 end let mem_of_type = function | Type.Reg 32 -> x86_mem | Type.Reg 64 -> x64_mem | t -> failwith (Printf.sprintf "Unable to find memory for address type %s" (Pp.typ_to_string t)) let arm_regs = List.map (fun n -> Var.newvar n (Reg 32)) [ "R0"; "R1"; "R2"; "R3"; "R4"; "R5"; "R6"; "R7"; "R8"; "R9"; "R10"; "R11"; "R12"; "R13"; "R14"; "R15T"; "CC"; "CC_OP"; "CC_DEP1"; "CC_DEP2"; "CC_NDEP"; ] let subregs = [ ("R_AL_32", ("R_EAX_32", 0, Reg 32)); ("R_BL_32", ("R_EBX_32", 0, Reg 32)); ("R_CL_32", ("R_ECX_32", 0, Reg 32)); ("R_DL_32", ("R_EDX_32", 0, Reg 32)); ("R_AH_32", ("R_EAX_32", 8, Reg 32)); ("R_BH_32", ("R_EBX_32", 8, Reg 32)); ("R_CH_32", ("R_ECX_32", 8, Reg 32)); ("R_DH_32", ("R_EDX_32", 8, Reg 32)); ("R_DI_32", ("R_EDI_32", 0, Reg 32)); ("R_SI_32", ("R_ESI_32", 0, Reg 32)); ("R_BP_32", ("R_EBP_32", 0, Reg 32)); ("R_SP_32", ("R_ESP_32", 0, Reg 32)); ("R_AX_32", ("R_EAX_32", 0, Reg 32)); ("R_BX_32", ("R_EBX_32", 0, Reg 32)); ("R_CX_32", ("R_ECX_32", 0, Reg 32)); ("R_DX_32", ("R_EDX_32", 0, Reg 32)); ("R_BP_32", ("R_EBP_32", 0, Reg 32)); ("R_SI_32", ("R_ESI_32", 0, Reg 32)); ("R_DI_32", ("R_EDI_32", 0, Reg 32)); ("R_SP_32", ("R_ESP_32", 0, Reg 32)); ("R_AL_64", ("R_RAX", 0, Reg 64)); ("R_BL_64", ("R_RBX", 0, Reg 64)); ("R_CL_64", ("R_RCX", 0, Reg 64)); ("R_DL_64", ("R_RDX", 0, Reg 64)); ("R_AH_64", ("R_RAX", 8, Reg 64)); ("R_BH_64", ("R_RBX", 8, Reg 64)); ("R_CH_64", ("R_RCX", 8, Reg 64)); ("R_DH_64", ("R_RDX", 8, Reg 64)); ("R_DIL", ("R_RDI", 0, Reg 64)); ("R_SIL", ("R_RSI", 0, Reg 64)); ("R_BPL", ("R_RBP", 0, Reg 64)); ("R_SPL", ("R_RSP", 0, Reg 64)); ("R_DI_64", ("R_RDI", 0, Reg 64)); ("R_SI_64", ("R_RSI", 0, Reg 64)); ("R_BP_64", ("R_RBP", 0, Reg 64)); ("R_SP_64", ("R_RSP", 0, Reg 64)); ("R_AX_64", ("R_RAX", 0, Reg 64)); ("R_BX_64", ("R_RBX", 0, Reg 64)); ("R_CX_64", ("R_RCX", 0, Reg 64)); ("R_DX_64", ("R_RDX", 0, Reg 64)); ("R_BP_64", ("R_RBP", 0, Reg 64)); ("R_SI_64", ("R_RSI", 0, Reg 64)); ("R_DI_64", ("R_RDI", 0, Reg 64)); ("R_SP_64", ("R_RSP", 0, Reg 64)); ("R_EAX_64", ("R_RAX", 0, Reg 64)); ("R_EBX_64", ("R_RBX", 0, Reg 64)); ("R_ECX_64", ("R_RCX", 0, Reg 64)); ("R_EDX_64", ("R_RDX", 0, Reg 64)); ("R_EBP_64", ("R_RBP", 0, Reg 64)); ("R_ESI_64", ("R_RSI", 0, Reg 64)); ("R_EDI_64", ("R_RDI", 0, Reg 64)); ("R_ESP_64", ("R_RSP", 0, Reg 64)); ] @ Array.to_list (Array.init 16 (fun i -> (Printf.sprintf "R_XMM%d" i, (Printf.sprintf "R_YMM%d" i, 0, Reg 256)))) @ Array.to_list (Array.init 16 (fun i -> (Printf.sprintf "R_MM%d" i, (Printf.sprintf "R_YMM%d" i, 0, Reg 256)))) @ Array.to_list (Array.init 8 (fun i -> (Printf.sprintf "R_R%dL" (i+8), (Printf.sprintf "R_R%d" (i+8), 0, Reg 64)))) @ Array.to_list (Array.init 8 (fun i -> (Printf.sprintf "R_R%dW" (i+8), (Printf.sprintf "R_R%d" (i+8), 0, Reg 64)))) @ Array.to_list (Array.init 8 (fun i -> (Printf.sprintf "R_R%dD" (i+8), (Printf.sprintf "R_R%d" (i+8), 0, Reg 64)))) let x86_all_regs = x86_mem :: x86_regs @ arm_regs let x64_all_regs = x64_mem :: x64_regs let multiarch_all_regs = x64_mem :: x86_mem :: full_regs
aea202168136a31594e2e6e2ae88c1438d743288ca3575431fa6afdd99fd39ec
logseq/mldoc
mldoc_parser.ml
open Angstrom open! Prelude let list_content_parsers config = let p = choice [ Table.parse config ; Type_parser.Block.parse config ; Latex_env.parse config ; Hr.parse config ; Type_parser.Block.results ; Comment.parse config ; Paragraph.parse ; Paragraph.sep ] in let p = Helper.with_pos_meta p in many1 p (* Orders care *) let parsers config = [ Paragraph.sep ; Directive.parse ; Drawer.parse config ; Type_parser.Heading.parse config ; Table.parse config ; Latex_env.parse config ; Type_parser.Block.parse config ; Footnote.parse config ; Type_parser.Lists.parse config (list_content_parsers config) ; Hr.parse config ; Type_parser.Block.results ; Comment.parse config ; Paragraph.parse ] TODO : ignore tags , page / block refs from , Example , etc . let outline_parsers config = [ Paragraph.sep ; Type_parser.Heading.parse config ; Drawer.parse config ; Directive.parse ; Paragraph.parse ] let md_front_matter_parse parse = Markdown_front_matter.parse >>= fun fm_result -> parse >>= fun result -> return (List.append fm_result result) let build_parsers parsers config = let parsers = parsers config in let choice = choice parsers in let p = Helper.with_pos_meta choice in let parse = many p in md_front_matter_parse parse <|> parse let parse config input = let outline_only = Conf.(config.parse_outline_only) in let parsers = build_parsers parsers config in match parse_string ~consume:All parsers input with | Ok result -> let ast = Paragraph.concat_paragraph_lines config result in let ast = if outline_only then Prelude.remove (fun (t, _) -> match t with | Type.Results | Type.Example _ | Type.Src _ | Type.Latex_Environment _ | Type.Latex_Fragment _ | Type.Displayed_Math _ | Type.Horizontal_Rule | Type.Raw_Html _ | Type.Hiccup _ -> true | _ -> false) ast else ast in if Conf.is_markdown config then List.map (fun (t, pos) -> (Type_op.md_unescaped t, pos)) ast else ast | Error err -> failwith err let load_file f = let ic = open_in f in let n = in_channel_length ic in let s = Bytes.create n in really_input ic s 0 n; close_in ic; Bytes.to_string s
null
https://raw.githubusercontent.com/logseq/mldoc/e353ea9cffa73b6244cb6d62e48cd26c3169faf6/lib/mldoc_parser.ml
ocaml
Orders care
open Angstrom open! Prelude let list_content_parsers config = let p = choice [ Table.parse config ; Type_parser.Block.parse config ; Latex_env.parse config ; Hr.parse config ; Type_parser.Block.results ; Comment.parse config ; Paragraph.parse ; Paragraph.sep ] in let p = Helper.with_pos_meta p in many1 p let parsers config = [ Paragraph.sep ; Directive.parse ; Drawer.parse config ; Type_parser.Heading.parse config ; Table.parse config ; Latex_env.parse config ; Type_parser.Block.parse config ; Footnote.parse config ; Type_parser.Lists.parse config (list_content_parsers config) ; Hr.parse config ; Type_parser.Block.results ; Comment.parse config ; Paragraph.parse ] TODO : ignore tags , page / block refs from , Example , etc . let outline_parsers config = [ Paragraph.sep ; Type_parser.Heading.parse config ; Drawer.parse config ; Directive.parse ; Paragraph.parse ] let md_front_matter_parse parse = Markdown_front_matter.parse >>= fun fm_result -> parse >>= fun result -> return (List.append fm_result result) let build_parsers parsers config = let parsers = parsers config in let choice = choice parsers in let p = Helper.with_pos_meta choice in let parse = many p in md_front_matter_parse parse <|> parse let parse config input = let outline_only = Conf.(config.parse_outline_only) in let parsers = build_parsers parsers config in match parse_string ~consume:All parsers input with | Ok result -> let ast = Paragraph.concat_paragraph_lines config result in let ast = if outline_only then Prelude.remove (fun (t, _) -> match t with | Type.Results | Type.Example _ | Type.Src _ | Type.Latex_Environment _ | Type.Latex_Fragment _ | Type.Displayed_Math _ | Type.Horizontal_Rule | Type.Raw_Html _ | Type.Hiccup _ -> true | _ -> false) ast else ast in if Conf.is_markdown config then List.map (fun (t, pos) -> (Type_op.md_unescaped t, pos)) ast else ast | Error err -> failwith err let load_file f = let ic = open_in f in let n = in_channel_length ic in let s = Bytes.create n in really_input ic s 0 n; close_in ic; Bytes.to_string s
037aed8fd3f859f4ddc458b2f337e333b4bb8f97bc1fd6eaa9288e128cd8fbfd
tmattio/js-bindings
vscode_languageserver_protocol_protocol_call_hierarchy.ml
[@@@js.dummy "!! This code has been generated by gen_js_api !!"] [@@@ocaml.warning "-7-32-39"] [@@@ocaml.warning "-7-11-32-33-39"] open Es5 open Vscode_jsonrpc open Vscode_languageserver_types open Vscode_languageserver_protocol_messages open Vscode_languageserver_protocol_protocol module CallHierarchyClientCapabilities = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2 and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1 let (get_dynamic_registration : t -> bool) = fun (x3 : t) -> Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x3) "dynamicRegistration") let (set_dynamic_registration : t -> bool -> unit) = fun (x4 : t) -> fun (x5 : bool) -> Ojs.set_prop_ascii (t_to_js x4) "dynamicRegistration" (Ojs.bool_to_js x5) end module CallHierarchyOptions = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x7 : Ojs.t) -> x7 and t_to_js : t -> Ojs.t = fun (x6 : Ojs.t) -> x6 let (cast : t -> WorkDoneProgressOptions.t) = fun (x8 : t) -> WorkDoneProgressOptions.t_of_js (t_to_js x8) end module CallHierarchyRegistrationOptions = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x10 : Ojs.t) -> x10 and t_to_js : t -> Ojs.t = fun (x9 : Ojs.t) -> x9 let (cast : t -> TextDocumentRegistrationOptions.t) = fun (x11 : t) -> TextDocumentRegistrationOptions.t_of_js (t_to_js x11) let (cast' : t -> CallHierarchyOptions.t) = fun (x12 : t) -> CallHierarchyOptions.t_of_js (t_to_js x12) let (cast'' : t -> StaticRegistrationOptions.t) = fun (x13 : t) -> StaticRegistrationOptions.t_of_js (t_to_js x13) end module CallHierarchyPrepareParams = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x15 : Ojs.t) -> x15 and t_to_js : t -> Ojs.t = fun (x14 : Ojs.t) -> x14 let (cast : t -> TextDocumentPositionParams.t) = fun (x16 : t) -> TextDocumentPositionParams.t_of_js (t_to_js x16) let (cast' : t -> WorkDoneProgressParams.t) = fun (x17 : t) -> WorkDoneProgressParams.t_of_js (t_to_js x17) end module CallHierarchyPrepareRequest = struct let (method_ : [ `L_s2_textDocument_prepareCallHierarchy ]) = let x18 = Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyPrepareRequest") "method" in match Ojs.string_of_js x18 with | "textDocument/prepareCallHierarchy" -> `L_s2_textDocument_prepareCallHierarchy | _ -> assert false let (type_ : (CallHierarchyPrepareParams.t, CallHierarchyItem.t list or_null, never, unit, CallHierarchyRegistrationOptions.t) ProtocolRequestType.t) = ProtocolRequestType.t_of_js CallHierarchyPrepareParams.t_of_js (fun (x20 : Ojs.t) -> or_null_of_js (fun (x21 : Ojs.t) -> Ojs.list_of_js CallHierarchyItem.t_of_js x21) x20) never_of_js Ojs.unit_of_js CallHierarchyRegistrationOptions.t_of_js (Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyPrepareRequest") "type") module HandlerSignature = struct type t = (CallHierarchyPrepareParams.t, CallHierarchyItem.t list or_null, unit) RequestHandler.t let rec t_of_js : Ojs.t -> t = fun (x32 : Ojs.t) -> RequestHandler.t_of_js CallHierarchyPrepareParams.t_of_js (fun (x34 : Ojs.t) -> or_null_of_js (fun (x35 : Ojs.t) -> Ojs.list_of_js CallHierarchyItem.t_of_js x35) x34) Ojs.unit_of_js x32 and t_to_js : t -> Ojs.t = fun (x26 : (CallHierarchyPrepareParams.t, CallHierarchyItem.t list or_null, unit) RequestHandler.t) -> RequestHandler.t_to_js CallHierarchyPrepareParams.t_to_js (fun (x28 : CallHierarchyItem.t list or_null) -> or_null_to_js (fun (x29 : CallHierarchyItem.t list) -> Ojs.list_to_js CallHierarchyItem.t_to_js x29) x28) Ojs.unit_to_js x26 end end module CallHierarchyIncomingCallsParams = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x39 : Ojs.t) -> x39 and t_to_js : t -> Ojs.t = fun (x38 : Ojs.t) -> x38 let (get_item : t -> CallHierarchyItem.t) = fun (x40 : t) -> CallHierarchyItem.t_of_js (Ojs.get_prop_ascii (t_to_js x40) "item") let (set_item : t -> CallHierarchyItem.t -> unit) = fun (x41 : t) -> fun (x42 : CallHierarchyItem.t) -> Ojs.set_prop_ascii (t_to_js x41) "item" (CallHierarchyItem.t_to_js x42) let (cast : t -> WorkDoneProgressParams.t) = fun (x43 : t) -> WorkDoneProgressParams.t_of_js (t_to_js x43) let (cast' : t -> PartialResultParams.t) = fun (x44 : t) -> PartialResultParams.t_of_js (t_to_js x44) end module CallHierarchyIncomingCallsRequest = struct let (method_ : [ `L_s0_callHierarchy_incomingCalls ]) = let x45 = Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyIncomingCallsRequest") "method" in match Ojs.string_of_js x45 with | "callHierarchy/incomingCalls" -> `L_s0_callHierarchy_incomingCalls | _ -> assert false let (type_ : (CallHierarchyIncomingCallsParams.t, CallHierarchyIncomingCall.t list or_null, CallHierarchyIncomingCall.t list, unit, unit) ProtocolRequestType.t) = ProtocolRequestType.t_of_js CallHierarchyIncomingCallsParams.t_of_js (fun (x47 : Ojs.t) -> or_null_of_js (fun (x48 : Ojs.t) -> Ojs.list_of_js CallHierarchyIncomingCall.t_of_js x48) x47) (fun (x50 : Ojs.t) -> Ojs.list_of_js CallHierarchyIncomingCall.t_of_js x50) Ojs.unit_of_js Ojs.unit_of_js (Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyIncomingCallsRequest") "type") module HandlerSignature = struct type t = (CallHierarchyIncomingCallsParams.t, CallHierarchyIncomingCall.t list or_null, unit) RequestHandler.t let rec t_of_js : Ojs.t -> t = fun (x60 : Ojs.t) -> RequestHandler.t_of_js CallHierarchyIncomingCallsParams.t_of_js (fun (x62 : Ojs.t) -> or_null_of_js (fun (x63 : Ojs.t) -> Ojs.list_of_js CallHierarchyIncomingCall.t_of_js x63) x62) Ojs.unit_of_js x60 and t_to_js : t -> Ojs.t = fun (x54 : (CallHierarchyIncomingCallsParams.t, CallHierarchyIncomingCall.t list or_null, unit) RequestHandler.t) -> RequestHandler.t_to_js CallHierarchyIncomingCallsParams.t_to_js (fun (x56 : CallHierarchyIncomingCall.t list or_null) -> or_null_to_js (fun (x57 : CallHierarchyIncomingCall.t list) -> Ojs.list_to_js CallHierarchyIncomingCall.t_to_js x57) x56) Ojs.unit_to_js x54 end end module CallHierarchyOutgoingCallsParams = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x67 : Ojs.t) -> x67 and t_to_js : t -> Ojs.t = fun (x66 : Ojs.t) -> x66 let (get_item : t -> CallHierarchyItem.t) = fun (x68 : t) -> CallHierarchyItem.t_of_js (Ojs.get_prop_ascii (t_to_js x68) "item") let (set_item : t -> CallHierarchyItem.t -> unit) = fun (x69 : t) -> fun (x70 : CallHierarchyItem.t) -> Ojs.set_prop_ascii (t_to_js x69) "item" (CallHierarchyItem.t_to_js x70) let (cast : t -> WorkDoneProgressParams.t) = fun (x71 : t) -> WorkDoneProgressParams.t_of_js (t_to_js x71) let (cast' : t -> PartialResultParams.t) = fun (x72 : t) -> PartialResultParams.t_of_js (t_to_js x72) end module CallHierarchyOutgoingCallsRequest = struct let (method_ : [ `L_s1_callHierarchy_outgoingCalls ]) = let x73 = Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyOutgoingCallsRequest") "method" in match Ojs.string_of_js x73 with | "callHierarchy/outgoingCalls" -> `L_s1_callHierarchy_outgoingCalls | _ -> assert false let (type_ : (CallHierarchyOutgoingCallsParams.t, CallHierarchyOutgoingCall.t list or_null, CallHierarchyOutgoingCall.t list, unit, unit) ProtocolRequestType.t) = ProtocolRequestType.t_of_js CallHierarchyOutgoingCallsParams.t_of_js (fun (x75 : Ojs.t) -> or_null_of_js (fun (x76 : Ojs.t) -> Ojs.list_of_js CallHierarchyOutgoingCall.t_of_js x76) x75) (fun (x78 : Ojs.t) -> Ojs.list_of_js CallHierarchyOutgoingCall.t_of_js x78) Ojs.unit_of_js Ojs.unit_of_js (Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyOutgoingCallsRequest") "type") module HandlerSignature = struct type t = (CallHierarchyOutgoingCallsParams.t, CallHierarchyOutgoingCall.t list or_null, unit) RequestHandler.t let rec t_of_js : Ojs.t -> t = fun (x88 : Ojs.t) -> RequestHandler.t_of_js CallHierarchyOutgoingCallsParams.t_of_js (fun (x90 : Ojs.t) -> or_null_of_js (fun (x91 : Ojs.t) -> Ojs.list_of_js CallHierarchyOutgoingCall.t_of_js x91) x90) Ojs.unit_of_js x88 and t_to_js : t -> Ojs.t = fun (x82 : (CallHierarchyOutgoingCallsParams.t, CallHierarchyOutgoingCall.t list or_null, unit) RequestHandler.t) -> RequestHandler.t_to_js CallHierarchyOutgoingCallsParams.t_to_js (fun (x84 : CallHierarchyOutgoingCall.t list or_null) -> or_null_to_js (fun (x85 : CallHierarchyOutgoingCall.t list) -> Ojs.list_to_js CallHierarchyOutgoingCall.t_to_js x85) x84) Ojs.unit_to_js x82 end end
null
https://raw.githubusercontent.com/tmattio/js-bindings/ca3bd6a12db519c8de7f41b303f14cf70cfd4c5f/lib/vscode-languageserver-protocol/vscode_languageserver_protocol_protocol_call_hierarchy.ml
ocaml
[@@@js.dummy "!! This code has been generated by gen_js_api !!"] [@@@ocaml.warning "-7-32-39"] [@@@ocaml.warning "-7-11-32-33-39"] open Es5 open Vscode_jsonrpc open Vscode_languageserver_types open Vscode_languageserver_protocol_messages open Vscode_languageserver_protocol_protocol module CallHierarchyClientCapabilities = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x2 : Ojs.t) -> x2 and t_to_js : t -> Ojs.t = fun (x1 : Ojs.t) -> x1 let (get_dynamic_registration : t -> bool) = fun (x3 : t) -> Ojs.bool_of_js (Ojs.get_prop_ascii (t_to_js x3) "dynamicRegistration") let (set_dynamic_registration : t -> bool -> unit) = fun (x4 : t) -> fun (x5 : bool) -> Ojs.set_prop_ascii (t_to_js x4) "dynamicRegistration" (Ojs.bool_to_js x5) end module CallHierarchyOptions = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x7 : Ojs.t) -> x7 and t_to_js : t -> Ojs.t = fun (x6 : Ojs.t) -> x6 let (cast : t -> WorkDoneProgressOptions.t) = fun (x8 : t) -> WorkDoneProgressOptions.t_of_js (t_to_js x8) end module CallHierarchyRegistrationOptions = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x10 : Ojs.t) -> x10 and t_to_js : t -> Ojs.t = fun (x9 : Ojs.t) -> x9 let (cast : t -> TextDocumentRegistrationOptions.t) = fun (x11 : t) -> TextDocumentRegistrationOptions.t_of_js (t_to_js x11) let (cast' : t -> CallHierarchyOptions.t) = fun (x12 : t) -> CallHierarchyOptions.t_of_js (t_to_js x12) let (cast'' : t -> StaticRegistrationOptions.t) = fun (x13 : t) -> StaticRegistrationOptions.t_of_js (t_to_js x13) end module CallHierarchyPrepareParams = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x15 : Ojs.t) -> x15 and t_to_js : t -> Ojs.t = fun (x14 : Ojs.t) -> x14 let (cast : t -> TextDocumentPositionParams.t) = fun (x16 : t) -> TextDocumentPositionParams.t_of_js (t_to_js x16) let (cast' : t -> WorkDoneProgressParams.t) = fun (x17 : t) -> WorkDoneProgressParams.t_of_js (t_to_js x17) end module CallHierarchyPrepareRequest = struct let (method_ : [ `L_s2_textDocument_prepareCallHierarchy ]) = let x18 = Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyPrepareRequest") "method" in match Ojs.string_of_js x18 with | "textDocument/prepareCallHierarchy" -> `L_s2_textDocument_prepareCallHierarchy | _ -> assert false let (type_ : (CallHierarchyPrepareParams.t, CallHierarchyItem.t list or_null, never, unit, CallHierarchyRegistrationOptions.t) ProtocolRequestType.t) = ProtocolRequestType.t_of_js CallHierarchyPrepareParams.t_of_js (fun (x20 : Ojs.t) -> or_null_of_js (fun (x21 : Ojs.t) -> Ojs.list_of_js CallHierarchyItem.t_of_js x21) x20) never_of_js Ojs.unit_of_js CallHierarchyRegistrationOptions.t_of_js (Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyPrepareRequest") "type") module HandlerSignature = struct type t = (CallHierarchyPrepareParams.t, CallHierarchyItem.t list or_null, unit) RequestHandler.t let rec t_of_js : Ojs.t -> t = fun (x32 : Ojs.t) -> RequestHandler.t_of_js CallHierarchyPrepareParams.t_of_js (fun (x34 : Ojs.t) -> or_null_of_js (fun (x35 : Ojs.t) -> Ojs.list_of_js CallHierarchyItem.t_of_js x35) x34) Ojs.unit_of_js x32 and t_to_js : t -> Ojs.t = fun (x26 : (CallHierarchyPrepareParams.t, CallHierarchyItem.t list or_null, unit) RequestHandler.t) -> RequestHandler.t_to_js CallHierarchyPrepareParams.t_to_js (fun (x28 : CallHierarchyItem.t list or_null) -> or_null_to_js (fun (x29 : CallHierarchyItem.t list) -> Ojs.list_to_js CallHierarchyItem.t_to_js x29) x28) Ojs.unit_to_js x26 end end module CallHierarchyIncomingCallsParams = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x39 : Ojs.t) -> x39 and t_to_js : t -> Ojs.t = fun (x38 : Ojs.t) -> x38 let (get_item : t -> CallHierarchyItem.t) = fun (x40 : t) -> CallHierarchyItem.t_of_js (Ojs.get_prop_ascii (t_to_js x40) "item") let (set_item : t -> CallHierarchyItem.t -> unit) = fun (x41 : t) -> fun (x42 : CallHierarchyItem.t) -> Ojs.set_prop_ascii (t_to_js x41) "item" (CallHierarchyItem.t_to_js x42) let (cast : t -> WorkDoneProgressParams.t) = fun (x43 : t) -> WorkDoneProgressParams.t_of_js (t_to_js x43) let (cast' : t -> PartialResultParams.t) = fun (x44 : t) -> PartialResultParams.t_of_js (t_to_js x44) end module CallHierarchyIncomingCallsRequest = struct let (method_ : [ `L_s0_callHierarchy_incomingCalls ]) = let x45 = Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyIncomingCallsRequest") "method" in match Ojs.string_of_js x45 with | "callHierarchy/incomingCalls" -> `L_s0_callHierarchy_incomingCalls | _ -> assert false let (type_ : (CallHierarchyIncomingCallsParams.t, CallHierarchyIncomingCall.t list or_null, CallHierarchyIncomingCall.t list, unit, unit) ProtocolRequestType.t) = ProtocolRequestType.t_of_js CallHierarchyIncomingCallsParams.t_of_js (fun (x47 : Ojs.t) -> or_null_of_js (fun (x48 : Ojs.t) -> Ojs.list_of_js CallHierarchyIncomingCall.t_of_js x48) x47) (fun (x50 : Ojs.t) -> Ojs.list_of_js CallHierarchyIncomingCall.t_of_js x50) Ojs.unit_of_js Ojs.unit_of_js (Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyIncomingCallsRequest") "type") module HandlerSignature = struct type t = (CallHierarchyIncomingCallsParams.t, CallHierarchyIncomingCall.t list or_null, unit) RequestHandler.t let rec t_of_js : Ojs.t -> t = fun (x60 : Ojs.t) -> RequestHandler.t_of_js CallHierarchyIncomingCallsParams.t_of_js (fun (x62 : Ojs.t) -> or_null_of_js (fun (x63 : Ojs.t) -> Ojs.list_of_js CallHierarchyIncomingCall.t_of_js x63) x62) Ojs.unit_of_js x60 and t_to_js : t -> Ojs.t = fun (x54 : (CallHierarchyIncomingCallsParams.t, CallHierarchyIncomingCall.t list or_null, unit) RequestHandler.t) -> RequestHandler.t_to_js CallHierarchyIncomingCallsParams.t_to_js (fun (x56 : CallHierarchyIncomingCall.t list or_null) -> or_null_to_js (fun (x57 : CallHierarchyIncomingCall.t list) -> Ojs.list_to_js CallHierarchyIncomingCall.t_to_js x57) x56) Ojs.unit_to_js x54 end end module CallHierarchyOutgoingCallsParams = struct type t = Ojs.t let rec t_of_js : Ojs.t -> t = fun (x67 : Ojs.t) -> x67 and t_to_js : t -> Ojs.t = fun (x66 : Ojs.t) -> x66 let (get_item : t -> CallHierarchyItem.t) = fun (x68 : t) -> CallHierarchyItem.t_of_js (Ojs.get_prop_ascii (t_to_js x68) "item") let (set_item : t -> CallHierarchyItem.t -> unit) = fun (x69 : t) -> fun (x70 : CallHierarchyItem.t) -> Ojs.set_prop_ascii (t_to_js x69) "item" (CallHierarchyItem.t_to_js x70) let (cast : t -> WorkDoneProgressParams.t) = fun (x71 : t) -> WorkDoneProgressParams.t_of_js (t_to_js x71) let (cast' : t -> PartialResultParams.t) = fun (x72 : t) -> PartialResultParams.t_of_js (t_to_js x72) end module CallHierarchyOutgoingCallsRequest = struct let (method_ : [ `L_s1_callHierarchy_outgoingCalls ]) = let x73 = Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyOutgoingCallsRequest") "method" in match Ojs.string_of_js x73 with | "callHierarchy/outgoingCalls" -> `L_s1_callHierarchy_outgoingCalls | _ -> assert false let (type_ : (CallHierarchyOutgoingCallsParams.t, CallHierarchyOutgoingCall.t list or_null, CallHierarchyOutgoingCall.t list, unit, unit) ProtocolRequestType.t) = ProtocolRequestType.t_of_js CallHierarchyOutgoingCallsParams.t_of_js (fun (x75 : Ojs.t) -> or_null_of_js (fun (x76 : Ojs.t) -> Ojs.list_of_js CallHierarchyOutgoingCall.t_of_js x76) x75) (fun (x78 : Ojs.t) -> Ojs.list_of_js CallHierarchyOutgoingCall.t_of_js x78) Ojs.unit_of_js Ojs.unit_of_js (Ojs.get_prop_ascii (Ojs.get_prop_ascii Ojs.global "CallHierarchyOutgoingCallsRequest") "type") module HandlerSignature = struct type t = (CallHierarchyOutgoingCallsParams.t, CallHierarchyOutgoingCall.t list or_null, unit) RequestHandler.t let rec t_of_js : Ojs.t -> t = fun (x88 : Ojs.t) -> RequestHandler.t_of_js CallHierarchyOutgoingCallsParams.t_of_js (fun (x90 : Ojs.t) -> or_null_of_js (fun (x91 : Ojs.t) -> Ojs.list_of_js CallHierarchyOutgoingCall.t_of_js x91) x90) Ojs.unit_of_js x88 and t_to_js : t -> Ojs.t = fun (x82 : (CallHierarchyOutgoingCallsParams.t, CallHierarchyOutgoingCall.t list or_null, unit) RequestHandler.t) -> RequestHandler.t_to_js CallHierarchyOutgoingCallsParams.t_to_js (fun (x84 : CallHierarchyOutgoingCall.t list or_null) -> or_null_to_js (fun (x85 : CallHierarchyOutgoingCall.t list) -> Ojs.list_to_js CallHierarchyOutgoingCall.t_to_js x85) x84) Ojs.unit_to_js x82 end end
e364830277d00fc93a6b703f7e0f71ad0f8687f8c51373d86e1197c8a7f1e587
valderman/haste-compiler
Parsing.hs
# LANGUAGE FlexibleInstances # -- | Home-grown parser, just because. module Haste.Parsing ( Parse, runParser, char, charP, string, oneOf, possibly, atLeast, whitespace, word, Haste.Parsing.words, int, double, positiveDouble, suchThat, quotedString, skip, rest, lookahead, anyChar ) where import Control.Applicative import Control.Monad import Data.Char newtype Parse a = Parse {unP :: (String -> Maybe (String, a))} runParser :: Parse a -> String -> Maybe a runParser (Parse p) s = case p s of Just ("", x) -> Just x _ -> Nothing instance Monad Parse where return x = Parse $ \s -> Just (s, x) Parse m >>= f = Parse $ \s -> do (s', x) <- m s unP (f x) s' instance Alternative Parse where empty = mzero (<|>) = mplus instance MonadPlus Parse where mplus (Parse p1) (Parse p2) = Parse $ \s -> case p1 s of x@(Just _) -> x _ -> p2 s mzero = Parse $ const Nothing instance Functor Parse where fmap f (Parse g) = Parse $ fmap (fmap f) . g instance Applicative Parse where pure = return (<*>) = ap | Read one character . Fails if end of stream . anyChar :: Parse Char anyChar = Parse $ \s -> case s of (c:cs) -> Just (cs, c) _ -> Nothing -- | Require a specific character. char :: Char -> Parse Char char c = charP (== c) -- | Parse a character that matches a given predicate. charP :: (Char -> Bool) -> Parse Char charP p = Parse $ \s -> case s of (c:next) | p c -> Just (next, c) _ -> Nothing -- | Require a specific string. string :: String -> Parse String string str = Parse $ \s -> let len = length str (s', next) = splitAt len s in if s' == str then Just (next, str) else Nothing | Apply the first matching parser . oneOf :: [Parse a] -> Parse a oneOf = msum -- | Invoke a parser with the possibility of failure. possibly :: Parse a -> Parse (Maybe a) possibly p = oneOf [Just <$> p, return Nothing] -- | Invoke a parser at least n times. atLeast :: Int -> Parse a -> Parse [a] atLeast 0 p = do x <- possibly p case x of Just x' -> do xs <- atLeast 0 p return (x':xs) _ -> return [] atLeast n p = do x <- p xs <- atLeast (n-1) p return (x:xs) | Parse zero or more characters of whitespace . whitespace :: Parse String whitespace = atLeast 0 $ charP isSpace | Parse a non - empty word . A word is a string of at least one non - whitespace -- character. word :: Parse String word = atLeast 1 $ charP (not . isSpace) -- | Parse several words, separated by whitespace. words :: Parse [String] words = atLeast 0 $ word <* whitespace -- | Parse an Int. int :: Parse Int int = oneOf [read <$> atLeast 1 (charP isDigit), char '-' >> (0-) . read <$> atLeast 1 (charP isDigit)] -- | Parse a floating point number. double :: Parse Double double = oneOf [positiveDouble, char '-' >> (0-) <$> positiveDouble] -- | Parse a non-negative floating point number. positiveDouble :: Parse Double positiveDouble = do first <- atLeast 1 $ charP isDigit msecond <- possibly $ char '.' *> atLeast 1 (charP isDigit) case msecond of Just second -> return $ read $ first ++ "." ++ second _ -> return $ read first -- | Fail on unwanted input. suchThat :: Parse a -> (a -> Bool) -> Parse a suchThat p f = do {x <- p ; if f x then return x else mzero} -- | A string quoted with the given quotation mark. Strings can contain escaped -- quotation marks; escape characters are stripped from the returned string. quotedString :: Char -> Parse String quotedString q = char q *> strContents q <* char q strContents :: Char -> Parse String strContents c = do s <- atLeast 0 $ charP (\x -> x /= c && x /= '\\') c' <- lookahead anyChar if c == c' then do return s else do skip 1 c'' <- anyChar s' <- strContents c return $ s ++ [c''] ++ s' -- | Read the rest of the input. rest :: Parse String rest = Parse $ \s -> Just ("", s) -- | Run a parser with the current parsing state, but don't consume any input. lookahead :: Parse a -> Parse a lookahead p = do s' <- Parse $ \s -> Just (s, s) x <- p Parse $ \_ -> Just (s', x) -- | Skip n characters from the input. skip :: Int -> Parse () skip n = Parse $ \s -> Just (drop n s, ())
null
https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/libraries/haste-lib/src/Haste/Parsing.hs
haskell
| Home-grown parser, just because. | Require a specific character. | Parse a character that matches a given predicate. | Require a specific string. | Invoke a parser with the possibility of failure. | Invoke a parser at least n times. character. | Parse several words, separated by whitespace. | Parse an Int. | Parse a floating point number. | Parse a non-negative floating point number. | Fail on unwanted input. | A string quoted with the given quotation mark. Strings can contain escaped quotation marks; escape characters are stripped from the returned string. | Read the rest of the input. | Run a parser with the current parsing state, but don't consume any input. | Skip n characters from the input.
# LANGUAGE FlexibleInstances # module Haste.Parsing ( Parse, runParser, char, charP, string, oneOf, possibly, atLeast, whitespace, word, Haste.Parsing.words, int, double, positiveDouble, suchThat, quotedString, skip, rest, lookahead, anyChar ) where import Control.Applicative import Control.Monad import Data.Char newtype Parse a = Parse {unP :: (String -> Maybe (String, a))} runParser :: Parse a -> String -> Maybe a runParser (Parse p) s = case p s of Just ("", x) -> Just x _ -> Nothing instance Monad Parse where return x = Parse $ \s -> Just (s, x) Parse m >>= f = Parse $ \s -> do (s', x) <- m s unP (f x) s' instance Alternative Parse where empty = mzero (<|>) = mplus instance MonadPlus Parse where mplus (Parse p1) (Parse p2) = Parse $ \s -> case p1 s of x@(Just _) -> x _ -> p2 s mzero = Parse $ const Nothing instance Functor Parse where fmap f (Parse g) = Parse $ fmap (fmap f) . g instance Applicative Parse where pure = return (<*>) = ap | Read one character . Fails if end of stream . anyChar :: Parse Char anyChar = Parse $ \s -> case s of (c:cs) -> Just (cs, c) _ -> Nothing char :: Char -> Parse Char char c = charP (== c) charP :: (Char -> Bool) -> Parse Char charP p = Parse $ \s -> case s of (c:next) | p c -> Just (next, c) _ -> Nothing string :: String -> Parse String string str = Parse $ \s -> let len = length str (s', next) = splitAt len s in if s' == str then Just (next, str) else Nothing | Apply the first matching parser . oneOf :: [Parse a] -> Parse a oneOf = msum possibly :: Parse a -> Parse (Maybe a) possibly p = oneOf [Just <$> p, return Nothing] atLeast :: Int -> Parse a -> Parse [a] atLeast 0 p = do x <- possibly p case x of Just x' -> do xs <- atLeast 0 p return (x':xs) _ -> return [] atLeast n p = do x <- p xs <- atLeast (n-1) p return (x:xs) | Parse zero or more characters of whitespace . whitespace :: Parse String whitespace = atLeast 0 $ charP isSpace | Parse a non - empty word . A word is a string of at least one non - whitespace word :: Parse String word = atLeast 1 $ charP (not . isSpace) words :: Parse [String] words = atLeast 0 $ word <* whitespace int :: Parse Int int = oneOf [read <$> atLeast 1 (charP isDigit), char '-' >> (0-) . read <$> atLeast 1 (charP isDigit)] double :: Parse Double double = oneOf [positiveDouble, char '-' >> (0-) <$> positiveDouble] positiveDouble :: Parse Double positiveDouble = do first <- atLeast 1 $ charP isDigit msecond <- possibly $ char '.' *> atLeast 1 (charP isDigit) case msecond of Just second -> return $ read $ first ++ "." ++ second _ -> return $ read first suchThat :: Parse a -> (a -> Bool) -> Parse a suchThat p f = do {x <- p ; if f x then return x else mzero} quotedString :: Char -> Parse String quotedString q = char q *> strContents q <* char q strContents :: Char -> Parse String strContents c = do s <- atLeast 0 $ charP (\x -> x /= c && x /= '\\') c' <- lookahead anyChar if c == c' then do return s else do skip 1 c'' <- anyChar s' <- strContents c return $ s ++ [c''] ++ s' rest :: Parse String rest = Parse $ \s -> Just ("", s) lookahead :: Parse a -> Parse a lookahead p = do s' <- Parse $ \s -> Just (s, s) x <- p Parse $ \_ -> Just (s', x) skip :: Int -> Parse () skip n = Parse $ \s -> Just (drop n s, ())
8924a0adbe8a44880a5426031e77d0d0587fae1b0a075d16e5c03cec417f7606
marcinjangrzybowski/cubeViz2
ExprTransform.hs
# LANGUAGE TupleSections # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # # OPTIONS_GHC -fwarn - incomplete - patterns # module ExprTransform where import Syntax -- import Drawing.Base import Data.Maybe import Data.Either import Data.Bifunctor import Data.Traversable import Data.Functor import Data.Foldable import Control.Applicative import Data.Functor.Identity import Combi import qualified Data.Map as Map import qualified Data.Set as Set import DataExtra import Abstract import Debug.Trace import Control.Monad.State.Strict import Control.Monad.Writer import ConsolePrint ntrace _ x = x -- use only for subfaces without parents in particular cylinder -- TODO : good place to intoduce NotFullSubFace type clCubRemoveSideMaximal :: SubFace -> ClCub () -> ClCub () clCubRemoveSideMaximal sf clcub@(ClCub (FromLI n g)) | isFullSF sf = error "subface of codim > 0 is required here" | otherwise = case (clInterior clcub) of Cub {} -> error "fatal, clCubRemoveSideMaximal accept only adequate ClCubs, suplied arg is not Hcomp" Hcomp _ mbn si@(CylCub (FromLI n f)) a -> if (isNothing (appLI sf (cylCub si))) then error "fatal, clCubRemoveSideMaximal accept only adequate ClCubs, suplied arg do not have particular subface" else let f' sfCyl | getDim sfCyl /= getDim sf = error "fatal" | sfCyl == sf = Nothing | otherwise = f sfCyl g' sfBd | getDim sfBd /= getDim sf = error "fatal" | isFullSF sfBd = Hcomp () mbn (CylCub (FromLI n f')) a | sf == sfBd = let a' = clCubSubFace sf a f'' sfCyl' | isFullSF sfCyl' = Nothing | otherwise = f $ injSubFace sfCyl' sf Cub ( subFaceDimEmb sf ) ( ) Nothing if subFaceDimEmb sf = = 0 -- then clInterior a' -- else Hcomp () mbn (CylCub (FromLI (subFaceDimEmb sf) f'')) a' | sf `isSubFaceOf` sfBd = let sf' = jniSubFace sf sfBd preSideTake = (clCubSubFace sfBd clcub) postSideTake = trace ("\n----\n" ++ printClOutOfCtx preSideTake) clCubRemoveSideMaximal sf' preSideTake postSideTakeInterior = trace ("\n" ++ printOOutOfCtx (clInterior postSideTake)) clInterior $ postSideTake in postSideTakeInterior | otherwise = g sfBd res = ClCub (FromLI n g') in res data ClearCellRegime = OnlyInterior | WithFreeSubFaces deriving (Eq) -- data ConstraintsOverrideStrategy = -- COSClearWithConstrained -- | COSClearNecessary -- | COSInflate -- deriving (Eq) data ConstraintsOverrideRegime = NoConstraintsOverride | ConstraintsOverride ConstraintsOverrideStrategy data RemoveSideRegime = RSRRemoveLeavesAlso | RSRKeepLeaves data SplitCellMode = AlsoSplitParents | SubstWithSplited data CubTransformation = ClearCell CAddress ClearCellRegime | SplitCell SplitCellMode CAddress | SubstAt CAddress (ClCub ()) | RemoveSide CAddress (SubFace , RemoveSideRegime) | AddSide CAddress SubFace -- | ReplaceAt Address (ClCub ()) -- | RemoveCell Address -- | RemoveCellLeaveFaces Address -- | AddSubFace (Address , SubFace) -- | MapAt Address (ClCub () -> Either String (ClCub ())) -- deriving (Show) -- TODO :: transofrmations for filling - automaticly recognises holes in faces of compositions which can be removed ct2CAddress :: CubTransformation -> CAddress ct2CAddress = \case ClearCell x _ -> x SplitCell _ x -> x SubstAt x _ -> x RemoveSide x _ -> x AddSide x _ -> x type SubstAtConflict a1 a2 = ((CAddress , (ClCub a1 ,ClCub a2)), ClCub (PreUnificationResult (a1 , Address) (a2 , Address))) data SubstAtConflictResolutionStrategy = ClearOutwards | ClearInwards | InflateInwards | InflateOutwards deriving (Enum, Show, Bounded, Eq) data CubTransformationError = CubTransformationError String | CubTransformationConflict (SubstAtConflict () ()) instance Show CubTransformationError where show (CubTransformationError x) = x show (CubTransformationConflict x) = show x -- substAtTry :: CAddress -> ClCub (SubstAtUnificationResult a1 a2) - > Either ( SubstAtConflict ( ) ( ) ) ( ClCub Bool ) substAtTry a x | any isConflictSAUR x = Left ( a , fmap ( bimap ( \ _ - > ( ) ) ( \ _ - > ( ) ) ) x ) -- | otherwise = Right (fmap isEditedSAUR x) make it more speclialised , distinction betwen conflict and comaptibility will be good , compatibility can be by Ordering -- data SubstAtUnificationResultCase a1 a2 = -- AgreementAtBoundary (ClCub (SubstAtUnificationResult (,) a1 a2)) ( ClCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) -- | MixedAtBoundary ( ClCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) -- deriving (Show) preSubstAt :: forall a1 a2. ClCub a1 -> CAddress -> ClCub a2 -> ClCub (PreUnificationResult (a1 , Address) (a2 , Address)) preSubstAt x caddr cub = preUnifyClCub x' cub' where x' :: ClCub (a1 , Address) x' = fromJust $ clCubPick (toAddress caddr) $ cubMapWAddr (flip (,)) x cub' :: ClCub (a2 , Address) cub' = cubMapWAddr (flip (,)) cub -- preSubstAtCases :: forall a1 a2. ClCub ( PreUnificationResult ( a1 , Address ) ( a2 , Address ) ) -- -> SubstAtUnificationResultCase a1 a2 -- preSubstAtCases x = -- if all isAgreementSAUR x -- then AgreementAtBoundary (fromAgreementSAUR <$> x) -- else ConflictAtBoundary x applyTransform :: CubTransformation -> ClCub () -> Either CubTransformationError (ClCub Bool) applyTransform (ClearCell caddr OnlyInterior) clcub = Right $ fmap fst $ clearCell caddr clcub applyTransform (ClearCell caddr WithFreeSubFaces) clcub = Right $ fmap fst $ clearCellWithFreeSF caddr clcub applyTransform (SubstAt caddr cub) x = let p = preSubstAt x caddr cub isHoleAtSubstSite = isHole $ clInterior (fromJust $ clCubPick (toAddress caddr) x) in if ((all isAgreementQ $ clBoundary p) && (eqDim cub x || isHoleAtSubstSite)) then Right $ fmap (isJust . snd) $ substInside (clInterior cub) caddr x else Left $ CubTransformationConflict $ ((caddr , (x , cub )) , p ) applyTransform (SplitCell SubstWithSplited caddr) clcub = error "todo" applyTransform (SplitCell AlsoSplitParents caddr) clcub = let tracked = traceConstraintsSingle clcub caddr f n addr x = case (oCubPickTopLevelData x) of (Nothing , _) -> Right Nothing (Just sf , _) -> Right $ Just $ (Just undefined , undefined) <$ --undefined is intended here, it should not be evaluated (splitOCub sf (fromMaybe (error "bad address") (clCubPick addr clcub))) in fmap (fmap (isJust . fst)) $ cubMapMayReplace f tracked applyTransform (RemoveSide caddr (sf , RSRRemoveLeavesAlso)) clcub = error "todo" applyTransform (RemoveSide caddr (sf , RSRKeepLeaves)) clcub = do let cub = fromJust $ clCubPick (toAddress caddr) clcub cubWithHole <- fmap void $ applyTransform (ClearCell caddr OnlyInterior) clcub let newCell = clCubRemoveSideMaximal sf cub applyTransform (SubstAt caddr newCell) cubWithHole -- should be safe but uses unsafe operation applyTransform (AddSide caddr sf) clcub = do let parCub@(ClCub (FromLI n f)) = fromJust $ clCubPick (toAddress caddr) clcub let parOCub = clInterior parCub case parOCub of Cub _ _ _ -> Left (CubTransformationError "not address of side cell!") Hcomp _ mbN (CylCub (FromLI n' g)) a -> do cubWithHole <- fmap void $ applyTransform (ClearCell caddr OnlyInterior) clcub let f' sff | isFullSF sff = let g' sf' = case (g sf') of Just x -> Just x Nothing -> if isSubFaceOf sf' sf then Just (Cub (subFaceDimEmb sf' + 1) () Nothing) else Nothing in Hcomp () mbN (CylCub (FromLI n' g')) a | otherwise = f sff newCell = ClCub (FromLI n f') applyTransform (SubstAt caddr newCell) cubWithHole splitOCub :: SubFace -> ClCub () -> OCub () splitOCub sf x@(ClCub xx) = -- clInterior x Hcomp () Nothing (CylCub $ FromLI (getDim x) cylF) x where cylF sf' | sf `isSubFaceOf` sf' = Nothing Just ( Cub ( subFaceDimEmb sf ' + 1 ) ( ) Nothing ) Just $ oDegenerate ( ( getDim x ) - 1 ) $ appLI sf ' xx Just $ oDegenerate (subFaceDimEmb sf') $ appLI sf' xx fhcConflictingAddresses : : SubstAtConflict a1 a2 - > ( Set . Set Address , Set . Set Address ) -- fhcConflictingAddresses (_ , cub) = execWriter $ ( cubMapTrav f g cub : : Writer ( Set . Set Address , Set . Set Address ) ( ClCub ( ) ) ) -- where -- f _ a b z zz zzz = -- do h a b -- return $ () -- g k a b z = -- do h a b -- return $ () h : : Address - > ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Writer ( Set . Set Address , Set . Set Address ) ( ) -- h addr = \case -- SAUROutside _ -> return () -- SAURInside a2 -> return () -- case ur of -- Agreement a1 a2 -> return () Val1 a1 mba2 - > tell ( Set.singleton addr , undefined ) Val2 mba1 a2 - > tell ( Set.empty , undefined ) -- Mixed a1 a2 -> return () Conflict _ _ - > tell ( Set.singleton addr , undefined ) : : SubstAtConflict a1 a2 - > ClCub ( ) -- fhcOuter (_ , cub) = void $ -- runIdentity $ cubMapMayReplace f cub -- where f : : Int - > Address - > OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Identity ( Maybe ( OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) ) -- f k _ z = -- case (oCubPickTopLevelData z) of -- SAUROutside _ -> -- Identity $ Nothing -- SAURInside a2 -> Identity $ Just $ Cub k undefined Nothing -- case ur of -- Agreement a1 a2 -> Identity $ Nothing Val1 a1 mba2 - > Identity $ Nothing -- Val2 mba1 a2 -> -- Identity $ Just $ Cub k (oCubPickTopLevelData z) Nothing -- Mixed a1 a2 -> Identity $ Nothing -- Conflict cub' _ -> -- Identity $ Just $ fmap undefined cub' fhcOuterForFollowCandidate : : SubstAtConflict a1 a2 -- -> (ClCub a1 , [(CAddress , ClCub a2)]) -- fhcOuterForFollowCandidate (_ , cub) = -- undefined -- -- void $ -- -- runIdentity $ cubMapMayReplace f cub -- where f : : Int - > Address - > OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Identity ( Maybe ( OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) ) -- f k _ z = -- case (oCubPickTopLevelData z) of -- SAUROutside _ -> -- Identity $ Nothing -- SAURInside a2 -> Identity $ Just $ Cub k undefined Nothing -- case ur of -- Agreement a1 a2 -> Identity $ Nothing Val1 a1 mba2 - > Identity $ Nothing -- Val2 mba1 a2 -> -- Identity $ Just $ Cub k (oCubPickTopLevelData z) Nothing -- Mixed a1 a2 -> Identity $ Nothing -- Conflict cub' _ -> -- Identity $ Just $ fmap undefined cub' -- cub' :: ClCub a1 -- cub' = runIdentity $ cubMapMayReplace f cub fhcCandidate : : SubstAtConflict a1 a2 - > ClCub ( ) fhcCandidate ( cAddr , cub ' ) = void $ -- runIdentity $ cubMapMayReplace f cub -- where cub = fromJust $ clCubPick ( toAddress cAddr ) cub ' f : : Int - > Address - > OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Identity ( Maybe ( OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) ) -- f k _ z = -- case (oCubPickTopLevelData z) of -- SAUROutside _ -> undefined -- SAURInside a2 -> Identity $ Nothing -- case ur of -- Agreement a1 a2 -> Identity $ Nothing Val1 a1 mba2 - > Identity $ Just $ Cub k ( oCubPickTopLevelData z ) Nothing -- Val2 mba1 a2 -> Identity $ Nothing -- Mixed a1 a2 -> Identity $ Nothing -- Conflict _ cub' -> -- Identity $ Just $ fmap undefined cub' resolveConflict :: forall a1 a2 . SubstAtConflict a1 a2 -> SubstAtConflictResolutionStrategy -> Maybe (ClCub ()) resolveConflict fhc@((caddr , (outer , inner)) , p) ClearOutwards = do toV <- Map.toList <$> toVisit let outer'' = foldr (\ca -> (fmap snd) . (clearCell ca)) outer' (fst <$> toV) Just $ void $ foldr (\(ca , y) -> (fmap h) . substInside y ca) outer'' toV where h :: (Maybe (Maybe a1, Maybe a2), Maybe a2) -> (Maybe a1, Maybe a2) h = first (join . fmap fst) outer' = fmap ((, Nothing) . Just) outer fromInnerSubst :: (PreUnificationResult (a1 , Address) (a2 , Address)) -> Maybe (CAddress , OCub a2) fromInnerSubst = (fmap $ (\x -> (addressClass outer (snd (fst x)) , clInterior $ fromJust $ clCubPick (snd (snd x)) inner ) )) . \case Val1 a1 (Just a2) -> Just (a1 , a2) Val2 (Just a1) a2 -> Just (a1 , a2) Conflict (cub1) (cub2) -> Just (oCubPickTopLevelData cub1 , oCubPickTopLevelData cub2) Mixed a1 a2 -> Nothing Agreement _ _ -> Nothing Val1 _ Nothing -> Nothing Val2 Nothing _ -> Nothing toVisit :: Maybe (Map.Map CAddress (OCub a2)) toVisit = foldrM (\(ca , y) z -> case Map.lookup ca z of Nothing -> Just (Map.insert ca y z) Just y' -> if (void y') == (void y) then Just z else Nothing ) Map.empty (catMaybes $ toList (fromInnerSubst <$> p)) let caddrList = Set.toList $ Set.map ( ( addressClass $ fhcOuter fhc ) ) $ fst $ fhcConflictingAddresses fhc -- cleared = foldM -- (\cu caddr' -> either (const Nothing) (Just . void) ( ClearCell caddr ' OnlyInterior ) cu ) -- (fhcOuter fhc) caddrList -- -- filled = foldM -- -- (\cu caddr' -> either (const Nothing) (Just . void) -- ( ClearCell caddr ' OnlyInterior ) cu ) -- -- cleared caddrList in ( \y - > void $ substInsideHoleUnsafe y caddr $ clInterior ( fhcCandidate fhc ) ) < $ > cleared -- -- either (error "fatal - unification failed after resolving") void -- $ substAtTry caddr -- -- $ substAt cleared caddr (fhcCandidate fhc) resolveConflict fhc@((caddr , (outer , inner)) , p) ClearInwards = if (not $ eqDim outer inner) TODO prevent this to happen by hiding this option in such case else do toV <- Map.toList <$> toVisit let inner'' = foldr (\ca -> (fmap snd) . (clearCell ca)) inner' (fst <$> toV) newInner = clInterior $ void $ foldr (\(ca , y) -> (fmap h) . substInside y ca) inner'' toV Just $ void $ substInside newInner caddr outer where h :: (Maybe (Maybe a0, Maybe a2), Maybe a0) -> (Maybe a0, Maybe a2) h (x , y) = (y , join $ fmap snd x) inner' = fmap ((Nothing ,) . Just) inner todo move outside together with similar one from ClearOutwards fromInnerSubst :: (PreUnificationResult (a1 , Address) (a2 , Address)) -> Maybe (CAddress , OCub a1) fromInnerSubst = (fmap $ (\x -> (addressClass inner (snd (snd x)) , clInterior $ fromJust $ clCubPick (snd (fst x)) outer ) )) . \case Val1 a1 (Just a2) -> Just (a1 , a2) Val2 (Just a1) a2 -> Just (a1 , a2) Conflict (cub1) (cub2) -> Just (oCubPickTopLevelData cub1 , oCubPickTopLevelData cub2) Mixed a1 a2 -> Nothing Agreement _ _ -> Nothing Val1 _ Nothing -> Nothing Val2 Nothing _ -> Nothing p' :: BdCub (Maybe (CAddress , OCub a1)) p' = clBoundary $ fmap fromInnerSubst p toVisit :: Maybe (Map.Map CAddress (OCub a1)) toVisit = foldrM (\(ca , y) z -> case Map.lookup ca z of Nothing -> Just (Map.insert ca y z) Just y' -> if (void y') == (void y) then Just z else Nothing ) Map.empty (catMaybes $ toList (p')) resolveConflict fhc@((caddr , (outer , inner)) , p) InflateInwards = error "todo" resolveConflict fhc@((caddr , (outer , inner)) , p) InflateOutwards = error "todo" let caddrList = Set.toList $ Set.map ( ( addressClass $ fhcCandidate fhc ) . snd ) $ fhcConflictingAddresses fhc -- cleared = foldl -- (\cu caddr' -> either (error "fatal") void ( ClearCell caddr ' OnlyInterior ) cu ) -- (fhcCandidate fhc) caddrList -- in either (error "fatal - unification failed after resolving") void $ substAtTry caddr $ substAt ( fhcOuter fhc ) caddr cleared applyTransform ( ClearCell addrToReplace OnlyInterior ) z = -- cubMapMayReplace ( - > if addr = = addrToReplace -- then --Right $ Just (clInterior valToPut) let bndr = clBoundary $ fromRight ( error " imposible " ) $ clCubPick addr z -- in undefined -- else Right $ Nothing -- ) z applyTransform ( SplitCell addrToSplit ) = -- flip cubMapMayReplace [] $ ( - > -- if addr == addrToSplit then let sides = Map.fromList ( map ( \fc - > ( toSubFace fc , cubHole n ) ) $ ) -- -- needs injectDim to work! -- ( map ( \fc@(Face n ( i , b ) ) - > ( toSubFace fc , injDim i $ cubFace fc x ) ) $ ) in Just $ Right $ ( Hcomp ( ) " splitVar " sides x ) -- else Nothing -- ) applyTransform ( RemoveCell [ ] ) = Right applyTransform ( RemoveCell ( addrToRemoveHead : addrToRemoveTail ) ) = -- flip cubMapMayReplace [] $ ( - > -- if addr == addrToRemoveTail -- then case x of ( ) nm sides x - > -- Just $ Right $ Hcomp () nm (Map.delete addrToRemoveHead sides) x -- _ -> Nothing -- else Nothing -- ) -- applyTransform (RemoveCellLeaveFaces [] ) = Right -- applyTransform (RemoveCellLeaveFaces (addrToRemoveHead : addrToRemoveTail) ) = -- flip cubMapMayReplace [] $ -- (\n addr parX -> -- if addr == addrToRemoveTail -- then case parX of ( ) nm sides x - > -- Just $ Right $ Hcomp () nm -- (deleteButLeaveFaces -- ( const ( Cub undefined ( Left 0 ) ) ) -- (\fc -> cubFace (injFaceSide fc) ) -- addrToRemoveHead sides) x -- _ -> Nothing -- else Nothing -- ) applyTransform ( AddSubFace ( addrToAdd , sf ) ) = -- flip cubMapMayReplace [] $ ( - > if addr = = addrToAdd -- then case x of ( ) nm sides x - > -- Just $ Right $ Hcomp () nm ( addSubFace -- (cubHole n) -- sf sides) x -- _ -> Nothing -- else Nothing -- ) applyTransform ( MapAt addrToMap f ) = -- flip cubMapMayReplace [] $ ( - > if addr = = addrToMap -- then Just $ f x -- else Nothing -- )
null
https://raw.githubusercontent.com/marcinjangrzybowski/cubeViz2/f73135e03db0b6c923cc103afe328b37da2d319d/src/ExprTransform.hs
haskell
import Drawing.Base use only for subfaces without parents in particular cylinder TODO : good place to intoduce NotFullSubFace type then clInterior a' else data ConstraintsOverrideStrategy = COSClearWithConstrained | COSClearNecessary | COSInflate deriving (Eq) | ReplaceAt Address (ClCub ()) | RemoveCell Address | RemoveCellLeaveFaces Address | AddSubFace (Address , SubFace) | MapAt Address (ClCub () -> Either String (ClCub ())) deriving (Show) TODO :: transofrmations for filling - automaticly recognises holes in faces of compositions which can be removed substAtTry :: CAddress -> ClCub (SubstAtUnificationResult a1 a2) | otherwise = Right (fmap isEditedSAUR x) data SubstAtUnificationResultCase a1 a2 = AgreementAtBoundary (ClCub (SubstAtUnificationResult (,) a1 a2)) | MixedAtBoundary ( ClCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) deriving (Show) preSubstAtCases :: forall a1 a2. -> SubstAtUnificationResultCase a1 a2 preSubstAtCases x = if all isAgreementSAUR x then AgreementAtBoundary (fromAgreementSAUR <$> x) else ConflictAtBoundary x undefined is intended here, it should not be evaluated should be safe but uses unsafe operation clInterior x fhcConflictingAddresses (_ , cub) = execWriter $ where f _ a b z zz zzz = do h a b return $ () g k a b z = do h a b return $ () h addr = \case SAUROutside _ -> return () SAURInside a2 -> return () case ur of Agreement a1 a2 -> return () Mixed a1 a2 -> return () fhcOuter (_ , cub) = void $ runIdentity $ cubMapMayReplace f cub where f k _ z = case (oCubPickTopLevelData z) of SAUROutside _ -> Identity $ Nothing SAURInside a2 -> Identity $ Just $ Cub k undefined Nothing case ur of Agreement a1 a2 -> Identity $ Nothing Val2 mba1 a2 -> Identity $ Just $ Cub k (oCubPickTopLevelData z) Nothing Mixed a1 a2 -> Identity $ Nothing Conflict cub' _ -> Identity $ Just $ fmap undefined cub' -> (ClCub a1 , [(CAddress , ClCub a2)]) fhcOuterForFollowCandidate (_ , cub) = undefined -- void $ -- runIdentity $ cubMapMayReplace f cub where f k _ z = case (oCubPickTopLevelData z) of SAUROutside _ -> Identity $ Nothing SAURInside a2 -> Identity $ Just $ Cub k undefined Nothing case ur of Agreement a1 a2 -> Identity $ Nothing Val2 mba1 a2 -> Identity $ Just $ Cub k (oCubPickTopLevelData z) Nothing Mixed a1 a2 -> Identity $ Nothing Conflict cub' _ -> Identity $ Just $ fmap undefined cub' cub' :: ClCub a1 cub' = runIdentity $ cubMapMayReplace f cub runIdentity $ cubMapMayReplace f cub where f k _ z = case (oCubPickTopLevelData z) of SAUROutside _ -> undefined SAURInside a2 -> Identity $ Nothing case ur of Agreement a1 a2 -> Identity $ Nothing Val2 mba1 a2 -> Identity $ Nothing Mixed a1 a2 -> Identity $ Nothing Conflict _ cub' -> Identity $ Just $ fmap undefined cub' cleared = foldM (\cu caddr' -> either (const Nothing) (Just . void) (fhcOuter fhc) caddrList -- filled = foldM -- (\cu caddr' -> either (const Nothing) (Just . void) ( ClearCell caddr ' OnlyInterior ) cu ) -- cleared caddrList -- either (error "fatal - unification failed after resolving") void $ substAtTry caddr -- $ substAt cleared caddr (fhcCandidate fhc) cleared = foldl (\cu caddr' -> either (error "fatal") void (fhcCandidate fhc) caddrList in either (error "fatal - unification failed after resolving") void cubMapMayReplace then --Right $ Just (clInterior valToPut) in undefined else Right $ Nothing ) z flip cubMapMayReplace [] $ if addr == addrToSplit -- needs injectDim to work! ( map ( \fc@(Face n ( i , b ) ) - > ( toSubFace fc , injDim i $ cubFace fc x ) ) $ ) else Nothing ) flip cubMapMayReplace [] $ if addr == addrToRemoveTail then case x of Just $ Right $ Hcomp () nm (Map.delete addrToRemoveHead sides) x _ -> Nothing else Nothing ) applyTransform (RemoveCellLeaveFaces [] ) = Right applyTransform (RemoveCellLeaveFaces (addrToRemoveHead : addrToRemoveTail) ) = flip cubMapMayReplace [] $ (\n addr parX -> if addr == addrToRemoveTail then case parX of Just $ Right $ Hcomp () nm (deleteButLeaveFaces ( const ( Cub undefined ( Left 0 ) ) ) (\fc -> cubFace (injFaceSide fc) ) addrToRemoveHead sides) x _ -> Nothing else Nothing ) flip cubMapMayReplace [] $ then case x of Just $ Right $ Hcomp () nm (cubHole n) sf sides) x _ -> Nothing else Nothing ) flip cubMapMayReplace [] $ then Just $ f x else Nothing )
# LANGUAGE TupleSections # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # # OPTIONS_GHC -fwarn - incomplete - patterns # module ExprTransform where import Syntax import Data.Maybe import Data.Either import Data.Bifunctor import Data.Traversable import Data.Functor import Data.Foldable import Control.Applicative import Data.Functor.Identity import Combi import qualified Data.Map as Map import qualified Data.Set as Set import DataExtra import Abstract import Debug.Trace import Control.Monad.State.Strict import Control.Monad.Writer import ConsolePrint ntrace _ x = x clCubRemoveSideMaximal :: SubFace -> ClCub () -> ClCub () clCubRemoveSideMaximal sf clcub@(ClCub (FromLI n g)) | isFullSF sf = error "subface of codim > 0 is required here" | otherwise = case (clInterior clcub) of Cub {} -> error "fatal, clCubRemoveSideMaximal accept only adequate ClCubs, suplied arg is not Hcomp" Hcomp _ mbn si@(CylCub (FromLI n f)) a -> if (isNothing (appLI sf (cylCub si))) then error "fatal, clCubRemoveSideMaximal accept only adequate ClCubs, suplied arg do not have particular subface" else let f' sfCyl | getDim sfCyl /= getDim sf = error "fatal" | sfCyl == sf = Nothing | otherwise = f sfCyl g' sfBd | getDim sfBd /= getDim sf = error "fatal" | isFullSF sfBd = Hcomp () mbn (CylCub (FromLI n f')) a | sf == sfBd = let a' = clCubSubFace sf a f'' sfCyl' | isFullSF sfCyl' = Nothing | otherwise = f $ injSubFace sfCyl' sf Cub ( subFaceDimEmb sf ) ( ) Nothing if subFaceDimEmb sf = = 0 Hcomp () mbn (CylCub (FromLI (subFaceDimEmb sf) f'')) a' | sf `isSubFaceOf` sfBd = let sf' = jniSubFace sf sfBd preSideTake = (clCubSubFace sfBd clcub) postSideTake = trace ("\n----\n" ++ printClOutOfCtx preSideTake) clCubRemoveSideMaximal sf' preSideTake postSideTakeInterior = trace ("\n" ++ printOOutOfCtx (clInterior postSideTake)) clInterior $ postSideTake in postSideTakeInterior | otherwise = g sfBd res = ClCub (FromLI n g') in res data ClearCellRegime = OnlyInterior | WithFreeSubFaces deriving (Eq) data ConstraintsOverrideRegime = NoConstraintsOverride | ConstraintsOverride ConstraintsOverrideStrategy data RemoveSideRegime = RSRRemoveLeavesAlso | RSRKeepLeaves data SplitCellMode = AlsoSplitParents | SubstWithSplited data CubTransformation = ClearCell CAddress ClearCellRegime | SplitCell SplitCellMode CAddress | SubstAt CAddress (ClCub ()) | RemoveSide CAddress (SubFace , RemoveSideRegime) | AddSide CAddress SubFace ct2CAddress :: CubTransformation -> CAddress ct2CAddress = \case ClearCell x _ -> x SplitCell _ x -> x SubstAt x _ -> x RemoveSide x _ -> x AddSide x _ -> x type SubstAtConflict a1 a2 = ((CAddress , (ClCub a1 ,ClCub a2)), ClCub (PreUnificationResult (a1 , Address) (a2 , Address))) data SubstAtConflictResolutionStrategy = ClearOutwards | ClearInwards | InflateInwards | InflateOutwards deriving (Enum, Show, Bounded, Eq) data CubTransformationError = CubTransformationError String | CubTransformationConflict (SubstAtConflict () ()) instance Show CubTransformationError where show (CubTransformationError x) = x show (CubTransformationConflict x) = show x - > Either ( SubstAtConflict ( ) ( ) ) ( ClCub Bool ) substAtTry a x | any isConflictSAUR x = Left ( a , fmap ( bimap ( \ _ - > ( ) ) ( \ _ - > ( ) ) ) x ) make it more speclialised , distinction betwen conflict and comaptibility will be good , compatibility can be by Ordering ( ClCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) preSubstAt :: forall a1 a2. ClCub a1 -> CAddress -> ClCub a2 -> ClCub (PreUnificationResult (a1 , Address) (a2 , Address)) preSubstAt x caddr cub = preUnifyClCub x' cub' where x' :: ClCub (a1 , Address) x' = fromJust $ clCubPick (toAddress caddr) $ cubMapWAddr (flip (,)) x cub' :: ClCub (a2 , Address) cub' = cubMapWAddr (flip (,)) cub ClCub ( PreUnificationResult ( a1 , Address ) ( a2 , Address ) ) applyTransform :: CubTransformation -> ClCub () -> Either CubTransformationError (ClCub Bool) applyTransform (ClearCell caddr OnlyInterior) clcub = Right $ fmap fst $ clearCell caddr clcub applyTransform (ClearCell caddr WithFreeSubFaces) clcub = Right $ fmap fst $ clearCellWithFreeSF caddr clcub applyTransform (SubstAt caddr cub) x = let p = preSubstAt x caddr cub isHoleAtSubstSite = isHole $ clInterior (fromJust $ clCubPick (toAddress caddr) x) in if ((all isAgreementQ $ clBoundary p) && (eqDim cub x || isHoleAtSubstSite)) then Right $ fmap (isJust . snd) $ substInside (clInterior cub) caddr x else Left $ CubTransformationConflict $ ((caddr , (x , cub )) , p ) applyTransform (SplitCell SubstWithSplited caddr) clcub = error "todo" applyTransform (SplitCell AlsoSplitParents caddr) clcub = let tracked = traceConstraintsSingle clcub caddr f n addr x = case (oCubPickTopLevelData x) of (Nothing , _) -> Right Nothing (splitOCub sf (fromMaybe (error "bad address") (clCubPick addr clcub))) in fmap (fmap (isJust . fst)) $ cubMapMayReplace f tracked applyTransform (RemoveSide caddr (sf , RSRRemoveLeavesAlso)) clcub = error "todo" applyTransform (RemoveSide caddr (sf , RSRKeepLeaves)) clcub = do let cub = fromJust $ clCubPick (toAddress caddr) clcub cubWithHole <- fmap void $ applyTransform (ClearCell caddr OnlyInterior) clcub let newCell = clCubRemoveSideMaximal sf cub applyTransform (SubstAt caddr newCell) cubWithHole applyTransform (AddSide caddr sf) clcub = do let parCub@(ClCub (FromLI n f)) = fromJust $ clCubPick (toAddress caddr) clcub let parOCub = clInterior parCub case parOCub of Cub _ _ _ -> Left (CubTransformationError "not address of side cell!") Hcomp _ mbN (CylCub (FromLI n' g)) a -> do cubWithHole <- fmap void $ applyTransform (ClearCell caddr OnlyInterior) clcub let f' sff | isFullSF sff = let g' sf' = case (g sf') of Just x -> Just x Nothing -> if isSubFaceOf sf' sf then Just (Cub (subFaceDimEmb sf' + 1) () Nothing) else Nothing in Hcomp () mbN (CylCub (FromLI n' g')) a | otherwise = f sff newCell = ClCub (FromLI n f') applyTransform (SubstAt caddr newCell) cubWithHole splitOCub :: SubFace -> ClCub () -> OCub () Hcomp () Nothing (CylCub $ FromLI (getDim x) cylF) x where cylF sf' | sf `isSubFaceOf` sf' = Nothing Just ( Cub ( subFaceDimEmb sf ' + 1 ) ( ) Nothing ) Just $ oDegenerate ( ( getDim x ) - 1 ) $ appLI sf ' xx Just $ oDegenerate (subFaceDimEmb sf') $ appLI sf' xx fhcConflictingAddresses : : SubstAtConflict a1 a2 - > ( Set . Set Address , Set . Set Address ) ( cubMapTrav f g cub : : Writer ( Set . Set Address , Set . Set Address ) ( ClCub ( ) ) ) h : : Address - > ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Writer ( Set . Set Address , Set . Set Address ) ( ) Val1 a1 mba2 - > tell ( Set.singleton addr , undefined ) Val2 mba1 a2 - > tell ( Set.empty , undefined ) Conflict _ _ - > tell ( Set.singleton addr , undefined ) : : SubstAtConflict a1 a2 - > ClCub ( ) f : : Int - > Address - > OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Identity ( Maybe ( OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) ) Val1 a1 mba2 - > Identity $ Nothing fhcOuterForFollowCandidate : : SubstAtConflict a1 a2 f : : Int - > Address - > OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Identity ( Maybe ( OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) ) Val1 a1 mba2 - > Identity $ Nothing fhcCandidate : : SubstAtConflict a1 a2 - > ClCub ( ) fhcCandidate ( cAddr , cub ' ) = void $ cub = fromJust $ clCubPick ( toAddress cAddr ) cub ' f : : Int - > Address - > OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) - > Identity ( Maybe ( OCub ( SubstAtUnificationResult PreUnificationResult a1 a2 ) ) ) Val1 a1 mba2 - > Identity $ Just $ Cub k ( oCubPickTopLevelData z ) Nothing resolveConflict :: forall a1 a2 . SubstAtConflict a1 a2 -> SubstAtConflictResolutionStrategy -> Maybe (ClCub ()) resolveConflict fhc@((caddr , (outer , inner)) , p) ClearOutwards = do toV <- Map.toList <$> toVisit let outer'' = foldr (\ca -> (fmap snd) . (clearCell ca)) outer' (fst <$> toV) Just $ void $ foldr (\(ca , y) -> (fmap h) . substInside y ca) outer'' toV where h :: (Maybe (Maybe a1, Maybe a2), Maybe a2) -> (Maybe a1, Maybe a2) h = first (join . fmap fst) outer' = fmap ((, Nothing) . Just) outer fromInnerSubst :: (PreUnificationResult (a1 , Address) (a2 , Address)) -> Maybe (CAddress , OCub a2) fromInnerSubst = (fmap $ (\x -> (addressClass outer (snd (fst x)) , clInterior $ fromJust $ clCubPick (snd (snd x)) inner ) )) . \case Val1 a1 (Just a2) -> Just (a1 , a2) Val2 (Just a1) a2 -> Just (a1 , a2) Conflict (cub1) (cub2) -> Just (oCubPickTopLevelData cub1 , oCubPickTopLevelData cub2) Mixed a1 a2 -> Nothing Agreement _ _ -> Nothing Val1 _ Nothing -> Nothing Val2 Nothing _ -> Nothing toVisit :: Maybe (Map.Map CAddress (OCub a2)) toVisit = foldrM (\(ca , y) z -> case Map.lookup ca z of Nothing -> Just (Map.insert ca y z) Just y' -> if (void y') == (void y) then Just z else Nothing ) Map.empty (catMaybes $ toList (fromInnerSubst <$> p)) let caddrList = Set.toList $ Set.map ( ( addressClass $ fhcOuter fhc ) ) $ fst $ fhcConflictingAddresses fhc ( ClearCell caddr ' OnlyInterior ) cu ) in ( \y - > void $ substInsideHoleUnsafe y caddr $ clInterior ( fhcCandidate fhc ) ) < $ > cleared resolveConflict fhc@((caddr , (outer , inner)) , p) ClearInwards = if (not $ eqDim outer inner) TODO prevent this to happen by hiding this option in such case else do toV <- Map.toList <$> toVisit let inner'' = foldr (\ca -> (fmap snd) . (clearCell ca)) inner' (fst <$> toV) newInner = clInterior $ void $ foldr (\(ca , y) -> (fmap h) . substInside y ca) inner'' toV Just $ void $ substInside newInner caddr outer where h :: (Maybe (Maybe a0, Maybe a2), Maybe a0) -> (Maybe a0, Maybe a2) h (x , y) = (y , join $ fmap snd x) inner' = fmap ((Nothing ,) . Just) inner todo move outside together with similar one from ClearOutwards fromInnerSubst :: (PreUnificationResult (a1 , Address) (a2 , Address)) -> Maybe (CAddress , OCub a1) fromInnerSubst = (fmap $ (\x -> (addressClass inner (snd (snd x)) , clInterior $ fromJust $ clCubPick (snd (fst x)) outer ) )) . \case Val1 a1 (Just a2) -> Just (a1 , a2) Val2 (Just a1) a2 -> Just (a1 , a2) Conflict (cub1) (cub2) -> Just (oCubPickTopLevelData cub1 , oCubPickTopLevelData cub2) Mixed a1 a2 -> Nothing Agreement _ _ -> Nothing Val1 _ Nothing -> Nothing Val2 Nothing _ -> Nothing p' :: BdCub (Maybe (CAddress , OCub a1)) p' = clBoundary $ fmap fromInnerSubst p toVisit :: Maybe (Map.Map CAddress (OCub a1)) toVisit = foldrM (\(ca , y) z -> case Map.lookup ca z of Nothing -> Just (Map.insert ca y z) Just y' -> if (void y') == (void y) then Just z else Nothing ) Map.empty (catMaybes $ toList (p')) resolveConflict fhc@((caddr , (outer , inner)) , p) InflateInwards = error "todo" resolveConflict fhc@((caddr , (outer , inner)) , p) InflateOutwards = error "todo" let caddrList = Set.toList $ Set.map ( ( addressClass $ fhcCandidate fhc ) . snd ) $ fhcConflictingAddresses fhc ( ClearCell caddr ' OnlyInterior ) cu ) $ substAtTry caddr $ substAt ( fhcOuter fhc ) caddr cleared applyTransform ( ClearCell addrToReplace OnlyInterior ) z = ( - > if addr = = addrToReplace let bndr = clBoundary $ fromRight ( error " imposible " ) $ clCubPick addr z applyTransform ( SplitCell addrToSplit ) = ( - > then let sides = Map.fromList ( map ( \fc - > ( toSubFace fc , cubHole n ) ) $ ) in Just $ Right $ ( Hcomp ( ) " splitVar " sides x ) applyTransform ( RemoveCell [ ] ) = Right applyTransform ( RemoveCell ( addrToRemoveHead : addrToRemoveTail ) ) = ( - > ( ) nm sides x - > ( ) nm sides x - > applyTransform ( AddSubFace ( addrToAdd , sf ) ) = ( - > if addr = = addrToAdd ( ) nm sides x - > ( addSubFace applyTransform ( MapAt addrToMap f ) = ( - > if addr = = addrToMap
dbe41e32600ad68a3aa6820a34303459235de3c66e19cc676f22ace3e57bb165
madstap/cadastro-de-pessoa
cnpj.cljc
(ns cadastro-de-pessoa.cnpj (:refer-clojure :exclude [format]) (:require [cadastro-de-pessoa.shared :as shared])) (def length 14) (def ^:private mask1 [5 4 3 2 9 8 7 6 5 4 3 2]) (def ^:private mask2 [6 5 4 3 2 9 8 7 6 5 4 3 2]) (def control-digits (partial shared/control-digits mask1 mask2)) (def repeated "A set of cnpjs with repeated digits that are considered valid by the algorithm, but normally shouldn't count as valid." (set (for [i (range 10) :let [xs (repeat (- length 2) i)]] (concat xs (control-digits xs))))) (defn valid? "Takes a string, seq of digits or a cnpj. Returns true if valid, else false. Does not validate formatting." ([cnpj] (let [cnpj (shared/parse cnpj) [digits control] (shared/split-control cnpj)] (and (= length (count cnpj)) (not (repeated cnpj)) (= control (control-digits digits)))))) (def regex #"^[0-9]{2}\.[0-9]{3}\.[0-9]{3}/[0-9]{4}-[0-9]{2}$") (defn formatted? "Is the cnpj formatted correctly?" [cnpj] (boolean (and (string? cnpj) (re-find regex cnpj)))) (defn format "Returns a string of the correctly formatted cnpj" [cnpj] (shared/format length {2 ".", 5 ".", 8 "/", 12 "-"} cnpj)) (defn gen "Generates a random valid cnpj. An integer argument can be given to choose headquarters or a branch. (Matriz ou filial) In a cnpj xx.xxx.xxx/0001-xx, 0001 is the branch number, in this case headquarters." ([] (let [digs (shared/rand-digits (- length 2))] (format (concat digs (control-digits digs))))) ([branch] {:pre [(< 0 branch 10e3) (integer? branch)]} (let [digs (shared/rand-digits (- length 2 4)) branch-digs (shared/left-pad 4 0 (shared/digits branch)) digs' (concat digs branch-digs)] (format (concat digs' (control-digits digs'))))))
null
https://raw.githubusercontent.com/madstap/cadastro-de-pessoa/dd2ecc4a51c4f6bb39e1666055f16821dfec2d84/src/cadastro_de_pessoa/cnpj.cljc
clojure
(ns cadastro-de-pessoa.cnpj (:refer-clojure :exclude [format]) (:require [cadastro-de-pessoa.shared :as shared])) (def length 14) (def ^:private mask1 [5 4 3 2 9 8 7 6 5 4 3 2]) (def ^:private mask2 [6 5 4 3 2 9 8 7 6 5 4 3 2]) (def control-digits (partial shared/control-digits mask1 mask2)) (def repeated "A set of cnpjs with repeated digits that are considered valid by the algorithm, but normally shouldn't count as valid." (set (for [i (range 10) :let [xs (repeat (- length 2) i)]] (concat xs (control-digits xs))))) (defn valid? "Takes a string, seq of digits or a cnpj. Returns true if valid, else false. Does not validate formatting." ([cnpj] (let [cnpj (shared/parse cnpj) [digits control] (shared/split-control cnpj)] (and (= length (count cnpj)) (not (repeated cnpj)) (= control (control-digits digits)))))) (def regex #"^[0-9]{2}\.[0-9]{3}\.[0-9]{3}/[0-9]{4}-[0-9]{2}$") (defn formatted? "Is the cnpj formatted correctly?" [cnpj] (boolean (and (string? cnpj) (re-find regex cnpj)))) (defn format "Returns a string of the correctly formatted cnpj" [cnpj] (shared/format length {2 ".", 5 ".", 8 "/", 12 "-"} cnpj)) (defn gen "Generates a random valid cnpj. An integer argument can be given to choose headquarters or a branch. (Matriz ou filial) In a cnpj xx.xxx.xxx/0001-xx, 0001 is the branch number, in this case headquarters." ([] (let [digs (shared/rand-digits (- length 2))] (format (concat digs (control-digits digs))))) ([branch] {:pre [(< 0 branch 10e3) (integer? branch)]} (let [digs (shared/rand-digits (- length 2 4)) branch-digs (shared/left-pad 4 0 (shared/digits branch)) digs' (concat digs branch-digs)] (format (concat digs' (control-digits digs'))))))
8f64a14c43cc68922bdaf10c3b46ec6a4caea094375acf5ffc08a34e76d1aca2
riak-haskell-client/riak-haskell-client
Basic.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # -- | -- Module: Network.Riak.Basic Copyright : ( c ) 2011 MailRank , Inc. License : Apache Maintainer : < > , < > -- Stability: experimental -- Portability: portable -- Basic support for the Riak decentralized data store . -- -- When storing and retrieving data, the functions in this module do -- not perform any encoding or decoding of data, nor do they resolve -- conflicts. module Network.Riak.Basic ( -- * Client configuration and identification ClientID , Client(..) , defaultClient -- * Connection management , Connection(..) , connect , disconnect , ping , getClientID , setClientID , getServerInfo -- * Data management , Quorum(..) , get , put , put_ , delete -- * Metadata , listBuckets , foldKeys , getBucket , setBucket , getBucketType -- * Map/reduce , mapReduce ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif import Control.Monad.IO.Class import Network.Riak.Connection.Internal import Network.Riak.Escape (unescape) import Network.Riak.Lens import Network.Riak.Types.Internal hiding (MessageTag(..)) import qualified Data.Foldable as F import qualified Data.Riak.Proto as Proto import qualified Network.Riak.Request as Req import qualified Network.Riak.Response as Resp import qualified Network.Riak.Types.Internal as T -- | Check to see if the connection to the server is alive. ping :: Connection -> IO () ping conn = exchange_ conn Req.ping -- | Find out from the server what client ID this connection is using. getClientID :: Connection -> IO ClientID getClientID conn = Resp.getClientID <$> exchange conn Req.getClientID -- | Retrieve information about the server. getServerInfo :: Connection -> IO Proto.RpbGetServerInfoResp getServerInfo conn = exchange conn Req.getServerInfo -- | Retrieve a value. This may return multiple conflicting siblings. -- Choosing among them is your responsibility. get :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> R -> IO (Maybe ([Proto.RpbContent], VClock)) get conn btype bucket key r = Resp.get <$> exchangeMaybe conn (Req.get btype bucket key r) -- | Store a single value. This may return multiple conflicting -- siblings. Choosing among them, and storing a new value, is your -- responsibility. -- -- You should /only/ supply 'Nothing' as a 'T.VClock' if you are sure -- that the given type+bucket+key combination does not already exist. -- If you omit a 'T.VClock' but the type+bucket+key /does/ exist, your -- value will not be stored. put :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> Maybe T.VClock -> Proto.RpbContent -> W -> DW -> IO ([Proto.RpbContent], VClock) put conn btype bucket key mvclock cont w dw = Resp.put <$> exchange conn (Req.put btype bucket key mvclock cont w dw True) -- | Store a single value, without the possibility of conflict -- resolution. -- -- You should /only/ supply 'Nothing' as a 'T.VClock' if you are sure -- that the given type+bucket+key combination does not already exist. -- If you omit a 'T.VClock' but the type+bucket+key /does/ exist, your -- value will not be stored, and you will not be notified. put_ :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> Maybe T.VClock -> Proto.RpbContent -> W -> DW -> IO () put_ conn btype bucket key mvclock cont w dw = exchange_ conn (Req.put btype bucket key mvclock cont w dw False) -- | Delete a value. delete :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> RW -> IO () delete conn btype bucket key rw = exchange_ conn $ Req.delete btype bucket key rw -- | List the buckets in the cluster. -- -- /Note/: this operation is expensive. Do not use it in production. listBuckets :: Connection -> Maybe BucketType -> IO [T.Bucket] listBuckets conn btype = Resp.listBuckets <$> exchange conn (Req.listBuckets btype) -- | Fold over the keys in a bucket. -- -- /Note/: this operation is expensive. Do not use it in production. foldKeys :: (MonadIO m) => Connection -> Maybe BucketType -> Bucket -> (a -> Key -> m a) -> a -> m a foldKeys conn btype bucket f z0 = do liftIO $ sendRequest conn $ Req.listKeys btype bucket let g z = f z . unescape loop z = do response <- liftIO $ (recvResponse conn :: IO Proto.RpbListKeysResp) z1 <- F.foldlM g z (response ^. Proto.keys) if response ^. Proto.done then return z1 else loop z1 loop z0 -- | Retrieve the properties of a bucket. getBucket :: Connection -> Maybe BucketType -> Bucket -> IO Proto.RpbBucketProps getBucket conn btype bucket = Resp.getBucket <$> exchange conn (Req.getBucket btype bucket) -- | Store new properties for a bucket. setBucket :: Connection -> Maybe BucketType -> Bucket -> Proto.RpbBucketProps -> IO () setBucket conn btype bucket props = exchange_ conn $ Req.setBucket btype bucket props -- | Gets the bucket properties associated with a bucket type. getBucketType :: Connection -> T.BucketType -> IO Proto.RpbBucketProps getBucketType conn btype = Resp.getBucket <$> exchange conn (Req.getBucketType btype) -- | Run a 'MapReduce' job. Its result is consumed via a strict left -- fold. mapReduce :: Connection -> Job -> (a -> Proto.RpbMapRedResp -> a) -> a -> IO a mapReduce conn job f z0 = loop z0 =<< (exchange conn . Req.mapReduce $ job) where loop z mr = do let !z' = f z mr if mr ^. Proto.done then return z' else loop z' =<< recvResponse conn
null
https://raw.githubusercontent.com/riak-haskell-client/riak-haskell-client/a1eafc4c16b85a98b2d29e306165f4d93819609f/riak/src/Network/Riak/Basic.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE OverloadedStrings # | Module: Network.Riak.Basic Stability: experimental Portability: portable When storing and retrieving data, the functions in this module do not perform any encoding or decoding of data, nor do they resolve conflicts. * Client configuration and identification * Connection management * Data management * Metadata * Map/reduce | Check to see if the connection to the server is alive. | Find out from the server what client ID this connection is using. | Retrieve information about the server. | Retrieve a value. This may return multiple conflicting siblings. Choosing among them is your responsibility. | Store a single value. This may return multiple conflicting siblings. Choosing among them, and storing a new value, is your responsibility. You should /only/ supply 'Nothing' as a 'T.VClock' if you are sure that the given type+bucket+key combination does not already exist. If you omit a 'T.VClock' but the type+bucket+key /does/ exist, your value will not be stored. | Store a single value, without the possibility of conflict resolution. You should /only/ supply 'Nothing' as a 'T.VClock' if you are sure that the given type+bucket+key combination does not already exist. If you omit a 'T.VClock' but the type+bucket+key /does/ exist, your value will not be stored, and you will not be notified. | Delete a value. | List the buckets in the cluster. /Note/: this operation is expensive. Do not use it in production. | Fold over the keys in a bucket. /Note/: this operation is expensive. Do not use it in production. | Retrieve the properties of a bucket. | Store new properties for a bucket. | Gets the bucket properties associated with a bucket type. | Run a 'MapReduce' job. Its result is consumed via a strict left fold.
# LANGUAGE CPP # # LANGUAGE RecordWildCards # Copyright : ( c ) 2011 MailRank , Inc. License : Apache Maintainer : < > , < > Basic support for the Riak decentralized data store . module Network.Riak.Basic ( ClientID , Client(..) , defaultClient , Connection(..) , connect , disconnect , ping , getClientID , setClientID , getServerInfo , Quorum(..) , get , put , put_ , delete , listBuckets , foldKeys , getBucket , setBucket , getBucketType , mapReduce ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif import Control.Monad.IO.Class import Network.Riak.Connection.Internal import Network.Riak.Escape (unescape) import Network.Riak.Lens import Network.Riak.Types.Internal hiding (MessageTag(..)) import qualified Data.Foldable as F import qualified Data.Riak.Proto as Proto import qualified Network.Riak.Request as Req import qualified Network.Riak.Response as Resp import qualified Network.Riak.Types.Internal as T ping :: Connection -> IO () ping conn = exchange_ conn Req.ping getClientID :: Connection -> IO ClientID getClientID conn = Resp.getClientID <$> exchange conn Req.getClientID getServerInfo :: Connection -> IO Proto.RpbGetServerInfoResp getServerInfo conn = exchange conn Req.getServerInfo get :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> R -> IO (Maybe ([Proto.RpbContent], VClock)) get conn btype bucket key r = Resp.get <$> exchangeMaybe conn (Req.get btype bucket key r) put :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> Maybe T.VClock -> Proto.RpbContent -> W -> DW -> IO ([Proto.RpbContent], VClock) put conn btype bucket key mvclock cont w dw = Resp.put <$> exchange conn (Req.put btype bucket key mvclock cont w dw True) put_ :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> Maybe T.VClock -> Proto.RpbContent -> W -> DW -> IO () put_ conn btype bucket key mvclock cont w dw = exchange_ conn (Req.put btype bucket key mvclock cont w dw False) delete :: Connection -> Maybe T.BucketType -> T.Bucket -> T.Key -> RW -> IO () delete conn btype bucket key rw = exchange_ conn $ Req.delete btype bucket key rw listBuckets :: Connection -> Maybe BucketType -> IO [T.Bucket] listBuckets conn btype = Resp.listBuckets <$> exchange conn (Req.listBuckets btype) foldKeys :: (MonadIO m) => Connection -> Maybe BucketType -> Bucket -> (a -> Key -> m a) -> a -> m a foldKeys conn btype bucket f z0 = do liftIO $ sendRequest conn $ Req.listKeys btype bucket let g z = f z . unescape loop z = do response <- liftIO $ (recvResponse conn :: IO Proto.RpbListKeysResp) z1 <- F.foldlM g z (response ^. Proto.keys) if response ^. Proto.done then return z1 else loop z1 loop z0 getBucket :: Connection -> Maybe BucketType -> Bucket -> IO Proto.RpbBucketProps getBucket conn btype bucket = Resp.getBucket <$> exchange conn (Req.getBucket btype bucket) setBucket :: Connection -> Maybe BucketType -> Bucket -> Proto.RpbBucketProps -> IO () setBucket conn btype bucket props = exchange_ conn $ Req.setBucket btype bucket props getBucketType :: Connection -> T.BucketType -> IO Proto.RpbBucketProps getBucketType conn btype = Resp.getBucket <$> exchange conn (Req.getBucketType btype) mapReduce :: Connection -> Job -> (a -> Proto.RpbMapRedResp -> a) -> a -> IO a mapReduce conn job f z0 = loop z0 =<< (exchange conn . Req.mapReduce $ job) where loop z mr = do let !z' = f z mr if mr ^. Proto.done then return z' else loop z' =<< recvResponse conn
17045bb0a5105d963343773f36096950dcdc520d853d6b255d91a0a6afbaffdb
ryanpbrewster/haskell
P204.hs
module Problems.P204 ( solve ) where import qualified Data.Set as DS - A Hamming number is a positive number which has no prime factor larger than - 5 . So the first few Hamming numbers are 1 , 2 , 3 , 4 , 5 , 6 , 8 , 9 , 10 , 12 , 15 . - There are 1105 Hamming numbers not exceeding 10 ^ 8 . - - We will call a positive number a generalised Hamming number of type n , if it - has no prime factor larger than n. Hence the Hamming numbers are the - generalised Hamming numbers of type 5 . - - How many generalised Hamming numbers of type 100 are there which do n't - exceed 10 ^ 9 ? - A Hamming number is a positive number which has no prime factor larger than - 5. So the first few Hamming numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15. - There are 1105 Hamming numbers not exceeding 10^8. - - We will call a positive number a generalised Hamming number of type n, if it - has no prime factor larger than n. Hence the Hamming numbers are the - generalised Hamming numbers of type 5. - - How many generalised Hamming numbers of type 100 are there which don't - exceed 10^9? -} import qualified Util.Prime as Prime hammingNumbers n bound = let ps = takeWhile (<= n) Prime.primes in allMultiples ps bound allMultiples [] _ = [1] allMultiples (p:ps) bound = let xs = allMultiples ps bound p_powers = takeWhile (<= bound) $ iterate (p *) p xs_with_p = [p' * x | p' <- p_powers, x <- xs] in xs ++ (filter (<= bound) xs_with_p) solveProblem n bound = length $ hammingNumbers n bound solve = show $ solveProblem 100 (10 ^ 9)
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/src/Problems/P204.hs
haskell
module Problems.P204 ( solve ) where import qualified Data.Set as DS - A Hamming number is a positive number which has no prime factor larger than - 5 . So the first few Hamming numbers are 1 , 2 , 3 , 4 , 5 , 6 , 8 , 9 , 10 , 12 , 15 . - There are 1105 Hamming numbers not exceeding 10 ^ 8 . - - We will call a positive number a generalised Hamming number of type n , if it - has no prime factor larger than n. Hence the Hamming numbers are the - generalised Hamming numbers of type 5 . - - How many generalised Hamming numbers of type 100 are there which do n't - exceed 10 ^ 9 ? - A Hamming number is a positive number which has no prime factor larger than - 5. So the first few Hamming numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15. - There are 1105 Hamming numbers not exceeding 10^8. - - We will call a positive number a generalised Hamming number of type n, if it - has no prime factor larger than n. Hence the Hamming numbers are the - generalised Hamming numbers of type 5. - - How many generalised Hamming numbers of type 100 are there which don't - exceed 10^9? -} import qualified Util.Prime as Prime hammingNumbers n bound = let ps = takeWhile (<= n) Prime.primes in allMultiples ps bound allMultiples [] _ = [1] allMultiples (p:ps) bound = let xs = allMultiples ps bound p_powers = takeWhile (<= bound) $ iterate (p *) p xs_with_p = [p' * x | p' <- p_powers, x <- xs] in xs ++ (filter (<= bound) xs_with_p) solveProblem n bound = length $ hammingNumbers n bound solve = show $ solveProblem 100 (10 ^ 9)
6f770984507f92fa53866e47177f971dc6a1becc7a2a48249c32f6c703b20863
kupl/LearnML
original.ml
type formula = | True | False | Not of formula | AndAlso of (formula * formula) | OrElse of (formula * formula) | Imply of (formula * formula) | Equal of (exp * exp) and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp) let rec calc (f : exp) : int = match f with | Num x -> x | Plus (x, y) -> calc x + calc y | Minus (x, y) -> calc x - calc y let eval (f : formula) : bool = match f with | True -> true | False -> false | Not x -> if x = True then false else true | AndAlso (x, y) -> if x = True && y = True then true else false | OrElse (x, y) -> if x = True || y = False then true else false | Imply (x, y) -> if x = True && y = False then false else true | Equal (x, y) -> if calc x = calc y then true else false let (_ : bool) = eval (Imply (Imply (True, False), True)) let (_ : bool) = eval (Equal (Num 1, Plus (Num 1, Num 2)))
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/formula/sub103/original.ml
ocaml
type formula = | True | False | Not of formula | AndAlso of (formula * formula) | OrElse of (formula * formula) | Imply of (formula * formula) | Equal of (exp * exp) and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp) let rec calc (f : exp) : int = match f with | Num x -> x | Plus (x, y) -> calc x + calc y | Minus (x, y) -> calc x - calc y let eval (f : formula) : bool = match f with | True -> true | False -> false | Not x -> if x = True then false else true | AndAlso (x, y) -> if x = True && y = True then true else false | OrElse (x, y) -> if x = True || y = False then true else false | Imply (x, y) -> if x = True && y = False then false else true | Equal (x, y) -> if calc x = calc y then true else false let (_ : bool) = eval (Imply (Imply (True, False), True)) let (_ : bool) = eval (Equal (Num 1, Plus (Num 1, Num 2)))
81b62121c6990905c34511dc2c8f0f134eeda57d69c28ca378178ddf92098cdd
avras/nsime
nsime_netdevice_SUITE.erl
%% Copyright ( C ) 2012 < > %% %% This file is part of nsime. %% nsime 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. %% %% nsime 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 nsime. If not, see </>. %% %% Purpose : Test module for nsime_netdevice Author : -module(nsime_netdevice_SUITE). -author("Saravanan Vijayakumaran"). -compile(export_all). -include("ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include("nsime_types.hrl"). -include("nsime_event.hrl"). -include("nsime_packet.hrl"). -include("nsime_droptail_queue_state.hrl"). -include("nsime_ptp_netdevice_state.hrl"). all() -> [ test_creation_shutdown, test_set_get_components, test_device_properties, test_set_get_callbacks, test_send ]. init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. test_creation_shutdown(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_set_get_components(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), ?assertEqual(nsime_netdevice:get_channel(DevicePid), undefined), NodePid = list_to_pid("<0.1.1>"), ?assertEqual(nsime_netdevice:set_node(DevicePid, NodePid), ok), ?assertEqual(nsime_netdevice:get_node(DevicePid), NodePid), Address = <<16#FFFFFFFFFFFF:48>>, ?assertEqual(nsime_netdevice:set_address(DevicePid, Address), ok), ?assertEqual(nsime_netdevice:get_address(DevicePid), Address), MTU = 1000, ?assertEqual(nsime_netdevice:set_mtu(DevicePid, MTU), ok), ?assertEqual(nsime_netdevice:get_mtu(DevicePid), MTU), InterfacePid = list_to_pid("<0.0.0>"), ?assertEqual(nsime_netdevice:set_interface(DevicePid, InterfacePid), ok), ?assertEqual(nsime_netdevice:get_interface(DevicePid), InterfacePid), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_device_properties(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), ?assertEqual(nsime_netdevice:get_device_type(DevicePid), nsime_ptp_netdevice), ?assertNot(nsime_netdevice:is_bridge(DevicePid)), ?assert(nsime_netdevice:is_ptp(DevicePid)), ?assert(nsime_netdevice:is_broadcast(DevicePid)), ?assertEqual(nsime_netdevice:get_broadcast_address(DevicePid), <<16#FF, 16#FF, 16#FF, 16#FF, 16#FF, 16#FF>>), ?assert(nsime_netdevice:is_multicast(DevicePid)), ?assertEqual(nsime_netdevice:get_multicast_address(DevicePid, {0,0,0,0}), <<16#01, 16#00, 16#5E, 16#00, 16#00, 16#00>>), ?assertEqual(nsime_netdevice:get_multicast_address(DevicePid, {0,0,0,0,0,0}), <<16#33, 16#33, 16#33, 16#00, 16#00, 16#00>>), ?assertNot(nsime_netdevice:needs_arp(DevicePid)), ?assertNot(nsime_netdevice:supports_send_from(DevicePid)), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_set_get_callbacks(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), Callback1 = {erlang, date, []}, ?assertEqual(nsime_netdevice:set_receive_callback(DevicePid, Callback1), ok), ?assertEqual(nsime_netdevice:get_receive_callback(DevicePid), Callback1), Callback2 = {erlang, date, []}, ?assertEqual(nsime_netdevice:set_promisc_receive_callback(DevicePid, Callback2), ok), ?assertEqual(nsime_netdevice:get_promisc_receive_callback(DevicePid), Callback2), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_send(_) -> nsime_simulator:start(), ChannelPid = nsime_ptp_channel:create(), ?assert(is_pid(ChannelPid)), DevicePid1 = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid1)), DevicePid2 = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid2)), Data = <<0:160>>, Packet = create_packet(make_ref(), 20, Data), ?assertEqual(nsime_netdevice:send(DevicePid1, Packet, address, 16#86DD), false), ?assertNot(nsime_netdevice:is_link_up(DevicePid1)), ?assertNot(nsime_netdevice:is_link_up(DevicePid2)), ?assertEqual(nsime_ptp_netdevice:attach_channel(DevicePid1, ChannelPid), ok), ?assert(nsime_netdevice:is_link_up(DevicePid1)), ?assertEqual(nsime_ptp_netdevice:attach_channel(DevicePid2, ChannelPid), ok), ?assert(nsime_netdevice:is_link_up(DevicePid2)), DataRate = {10, bits_per_sec}, ?assertEqual(nsime_ptp_netdevice:set_data_rate(DevicePid1, DataRate), ok), InterFrameGap = {10, micro_sec}, ?assertEqual(nsime_ptp_netdevice:set_interframe_gap(DevicePid1, InterFrameGap), ok), ?assertEqual(nsime_netdevice:send(DevicePid1, Packet, address, 16#86DD), true), ?assertEqual(nsime_simulator:stop(), simulation_complete), ?assertEqual(nsime_ptp_netdevice:destroy(DevicePid1), stopped), ?assertEqual(nsime_ptp_netdevice:destroy(DevicePid2), stopped). create_packet(Id, Size, Data) -> #nsime_packet{ id = Id, size = Size, data = Data }.
null
https://raw.githubusercontent.com/avras/nsime/fc5c164272aa649541bb3895d9f4bea34f45beec/test/nsime_netdevice_SUITE.erl
erlang
This file is part of nsime. (at your option) any later version. nsime 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 nsime. If not, see </>. Purpose : Test module for nsime_netdevice
Copyright ( C ) 2012 < > nsime 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 You should have received a copy of the GNU General Public License Author : -module(nsime_netdevice_SUITE). -author("Saravanan Vijayakumaran"). -compile(export_all). -include("ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include("nsime_types.hrl"). -include("nsime_event.hrl"). -include("nsime_packet.hrl"). -include("nsime_droptail_queue_state.hrl"). -include("nsime_ptp_netdevice_state.hrl"). all() -> [ test_creation_shutdown, test_set_get_components, test_device_properties, test_set_get_callbacks, test_send ]. init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. test_creation_shutdown(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_set_get_components(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), ?assertEqual(nsime_netdevice:get_channel(DevicePid), undefined), NodePid = list_to_pid("<0.1.1>"), ?assertEqual(nsime_netdevice:set_node(DevicePid, NodePid), ok), ?assertEqual(nsime_netdevice:get_node(DevicePid), NodePid), Address = <<16#FFFFFFFFFFFF:48>>, ?assertEqual(nsime_netdevice:set_address(DevicePid, Address), ok), ?assertEqual(nsime_netdevice:get_address(DevicePid), Address), MTU = 1000, ?assertEqual(nsime_netdevice:set_mtu(DevicePid, MTU), ok), ?assertEqual(nsime_netdevice:get_mtu(DevicePid), MTU), InterfacePid = list_to_pid("<0.0.0>"), ?assertEqual(nsime_netdevice:set_interface(DevicePid, InterfacePid), ok), ?assertEqual(nsime_netdevice:get_interface(DevicePid), InterfacePid), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_device_properties(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), ?assertEqual(nsime_netdevice:get_device_type(DevicePid), nsime_ptp_netdevice), ?assertNot(nsime_netdevice:is_bridge(DevicePid)), ?assert(nsime_netdevice:is_ptp(DevicePid)), ?assert(nsime_netdevice:is_broadcast(DevicePid)), ?assertEqual(nsime_netdevice:get_broadcast_address(DevicePid), <<16#FF, 16#FF, 16#FF, 16#FF, 16#FF, 16#FF>>), ?assert(nsime_netdevice:is_multicast(DevicePid)), ?assertEqual(nsime_netdevice:get_multicast_address(DevicePid, {0,0,0,0}), <<16#01, 16#00, 16#5E, 16#00, 16#00, 16#00>>), ?assertEqual(nsime_netdevice:get_multicast_address(DevicePid, {0,0,0,0,0,0}), <<16#33, 16#33, 16#33, 16#00, 16#00, 16#00>>), ?assertNot(nsime_netdevice:needs_arp(DevicePid)), ?assertNot(nsime_netdevice:supports_send_from(DevicePid)), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_set_get_callbacks(_) -> DevicePid = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid)), Callback1 = {erlang, date, []}, ?assertEqual(nsime_netdevice:set_receive_callback(DevicePid, Callback1), ok), ?assertEqual(nsime_netdevice:get_receive_callback(DevicePid), Callback1), Callback2 = {erlang, date, []}, ?assertEqual(nsime_netdevice:set_promisc_receive_callback(DevicePid, Callback2), ok), ?assertEqual(nsime_netdevice:get_promisc_receive_callback(DevicePid), Callback2), ?assertEqual(nsime_netdevice:destroy(DevicePid), stopped). test_send(_) -> nsime_simulator:start(), ChannelPid = nsime_ptp_channel:create(), ?assert(is_pid(ChannelPid)), DevicePid1 = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid1)), DevicePid2 = nsime_ptp_netdevice:create(), ?assert(is_pid(DevicePid2)), Data = <<0:160>>, Packet = create_packet(make_ref(), 20, Data), ?assertEqual(nsime_netdevice:send(DevicePid1, Packet, address, 16#86DD), false), ?assertNot(nsime_netdevice:is_link_up(DevicePid1)), ?assertNot(nsime_netdevice:is_link_up(DevicePid2)), ?assertEqual(nsime_ptp_netdevice:attach_channel(DevicePid1, ChannelPid), ok), ?assert(nsime_netdevice:is_link_up(DevicePid1)), ?assertEqual(nsime_ptp_netdevice:attach_channel(DevicePid2, ChannelPid), ok), ?assert(nsime_netdevice:is_link_up(DevicePid2)), DataRate = {10, bits_per_sec}, ?assertEqual(nsime_ptp_netdevice:set_data_rate(DevicePid1, DataRate), ok), InterFrameGap = {10, micro_sec}, ?assertEqual(nsime_ptp_netdevice:set_interframe_gap(DevicePid1, InterFrameGap), ok), ?assertEqual(nsime_netdevice:send(DevicePid1, Packet, address, 16#86DD), true), ?assertEqual(nsime_simulator:stop(), simulation_complete), ?assertEqual(nsime_ptp_netdevice:destroy(DevicePid1), stopped), ?assertEqual(nsime_ptp_netdevice:destroy(DevicePid2), stopped). create_packet(Id, Size, Data) -> #nsime_packet{ id = Id, size = Size, data = Data }.
05c2d6704d44fd0514270b552722b0c0e79100e01402bb8bf07822c99d2a1952
avsm/eeww
actions_helpers.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Gallium , INRIA Paris (* *) Copyright 2016 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Helper functions when writing actions *) open Ocamltest_stdlib let skip_with_reason reason = let code _log env = let result = Result.skip_with_reason reason in (result, env) in Actions.make ~name:"skip" ~description:"Skip the test" code let pass_or_skip test pass_reason skip_reason _log env = let open Result in let result = if test then pass_with_reason pass_reason else skip_with_reason skip_reason in (result, env) let mkreason what commandline exitcode = Printf.sprintf "%s: command\n%s\nfailed with exit code %d" what commandline exitcode let testfile env = match Environments.lookup Builtin_variables.test_file env with | None -> assert false | Some t -> t let test_source_directory env = Environments.safe_lookup Builtin_variables.test_source_directory env let test_build_directory env = Environments.safe_lookup Builtin_variables.test_build_directory env let test_build_directory_prefix env = Environments.safe_lookup Builtin_variables.test_build_directory_prefix env let words_of_variable env variable = String.words (Environments.safe_lookup variable env) let exit_status_of_variable env variable = try int_of_string (Environments.safe_lookup variable env) with _ -> 0 let readonly_files env = words_of_variable env Builtin_variables.readonly_files let subdirectories env = words_of_variable env Builtin_variables.subdirectories let setup_symlinks test_source_directory build_directory files = let symlink filename = (* Emulate ln -sfT *) let src = Filename.concat test_source_directory filename in let dst = Filename.concat build_directory filename in let () = if Sys.file_exists dst then if Sys.win32 && Sys.is_directory dst then Native symbolic links to directories do n't disappear with unlink ; doing rmdir here is technically slightly more than ln -sfT would do doing rmdir here is technically slightly more than ln -sfT would do *) Sys.rmdir dst else Sys.remove dst in Unix.symlink src dst in let copy filename = let src = Filename.concat test_source_directory filename in let dst = Filename.concat build_directory filename in Sys.copy_file src dst in let f = if Unix.has_symlink () then symlink else copy in Sys.make_directory build_directory; List.iter f files let setup_subdirectories source_directory build_directory subdirs = let full_src_path name = Filename.concat source_directory name in let full_dst_path name = Filename.concat build_directory name in let cp_dir name = Sys.copy_directory (full_src_path name) (full_dst_path name) in List.iter cp_dir subdirs let setup_build_env add_testfile additional_files (_log : out_channel) env = let source_dir = (test_source_directory env) in let build_dir = (test_build_directory env) in let some_files = additional_files @ (readonly_files env) in let files = if add_testfile then (testfile env) :: some_files else some_files in setup_symlinks source_dir build_dir files; let subdirs = subdirectories env in setup_subdirectories source_dir build_dir subdirs; Sys.chdir build_dir; (Result.pass, env) let setup_simple_build_env add_testfile additional_files log env = let build_env = Environments.add Builtin_variables.test_build_directory (test_build_directory_prefix env) env in setup_build_env add_testfile additional_files log build_env let run_cmd ?(environment=[||]) ?(stdin_variable=Builtin_variables.stdin) ?(stdout_variable=Builtin_variables.stdout) ?(stderr_variable=Builtin_variables.stderr) ?(append=false) ?timeout log env original_cmd = let log_redirection std filename = if filename<>"" then begin Printf.fprintf log " Redirecting %s to %s \n%!" std filename end in let cmd = if (Environments.lookup_as_bool Strace.strace env) = Some true then begin let action_name = Environments.safe_lookup Actions.action_name env in let test_build_directory = test_build_directory env in let strace_logfile_name = Strace.get_logfile_name action_name in let strace_logfile = Filename.make_path [test_build_directory; strace_logfile_name] in let strace_flags = Environments.safe_lookup Strace.strace_flags env in let strace_cmd = ["strace"; "-f"; "-o"; strace_logfile; strace_flags] in strace_cmd @ original_cmd end else original_cmd in let lst = List.concat (List.map String.words cmd) in let quoted_lst = if Sys.win32 then List.map Filename.maybe_quote lst else lst in let cmd' = String.concat " " quoted_lst in Printf.fprintf log "Commandline: %s\n" cmd'; let progname = List.hd quoted_lst in let arguments = Array.of_list quoted_lst in let stdin_filename = Environments.safe_lookup stdin_variable env in let stdout_filename = Environments.safe_lookup stdout_variable env in let stderr_filename = Environments.safe_lookup stderr_variable env in log_redirection "stdin" stdin_filename; log_redirection "stdout" stdout_filename; log_redirection "stderr" stderr_filename; let systemenv = Environments.append_to_system_env environment env in let timeout = match timeout with | Some timeout -> timeout | None -> Option.value ~default:0 (Environments.lookup_as_int Builtin_variables.timeout env) in let n = Run_command.run { Run_command.progname = progname; Run_command.argv = arguments; Run_command.envp = systemenv; Run_command.stdin_filename = stdin_filename; Run_command.stdout_filename = stdout_filename; Run_command.stderr_filename = stderr_filename; Run_command.append = append; Run_command.timeout = timeout; Run_command.log = log } in let dump_file s fn = if not (Sys.file_is_empty fn) then begin Printf.fprintf log "### begin %s ###\n" s; Sys.dump_file log fn; Printf.fprintf log "### end %s ###\n" s end in dump_file "stdout" stdout_filename; if stdout_filename <> stderr_filename then dump_file "stderr" stderr_filename; n let run (log_message : string) (redirect_output : bool) (can_skip : bool) (prog_variable : Variables.t) (args_variable : Variables.t option) (log : out_channel) (env : Environments.t) = match Environments.lookup prog_variable env with | None -> let msg = Printf.sprintf "%s: variable %s is undefined" log_message (Variables.name_of_variable prog_variable) in (Result.fail_with_reason msg, env) | Some program -> let arguments = match args_variable with | None -> "" | Some variable -> Environments.safe_lookup variable env in let commandline = [program; arguments] in let what = log_message ^ " " ^ program ^ " " ^ begin if arguments="" then "without any argument" else "with arguments " ^ arguments end in let env = if redirect_output then begin let output = Environments.safe_lookup Builtin_variables.output env in let env = Environments.add_if_undefined Builtin_variables.stdout output env in Environments.add_if_undefined Builtin_variables.stderr output env end else env in let expected_exit_status = exit_status_of_variable env Builtin_variables.exit_status in let exit_status = run_cmd log env commandline in if exit_status=expected_exit_status then (Result.pass, env) else begin let reason = mkreason what (String.concat " " commandline) exit_status in if exit_status = 125 && can_skip then (Result.skip_with_reason reason, env) else (Result.fail_with_reason reason, env) end let run_program = run "Running program" true false Builtin_variables.program (Some Builtin_variables.arguments) let run_script log env = let response_file = Filename.temp_file "ocamltest-" ".response" in Printf.fprintf log "Script should write its response to %s\n%!" response_file; let scriptenv = Environments.add Builtin_variables.ocamltest_response response_file env in let (result, newenv) = run "Running script" true true Builtin_variables.script None log scriptenv in let final_value = if Result.is_pass result then begin match Modifier_parser.modifiers_of_file response_file with | modifiers -> let modified_env = Environments.apply_modifiers newenv modifiers in (result, modified_env) | exception Failure reason -> (Result.fail_with_reason reason, newenv) | exception Variables.No_such_variable name -> let reason = Printf.sprintf "error in script response: unknown variable %s" name in (Result.fail_with_reason reason, newenv) end else begin let reason = String.trim (Sys.string_of_file response_file) in let newresult = { result with Result.reason = Some reason } in (newresult, newenv) end in Sys.force_remove response_file; final_value let run_hook hook_name log input_env = Printf.fprintf log "Entering run_hook for hook %s\n%!" hook_name; let response_file = Filename.temp_file "ocamltest-" ".response" in Printf.fprintf log "Hook should write its response to %s\n%!" response_file; let hookenv = Environments.add Builtin_variables.ocamltest_response response_file input_env in let systemenv = Environments.to_system_env hookenv in let timeout = Option.value ~default:0 (Environments.lookup_as_int Builtin_variables.timeout input_env) in let open Run_command in let settings = { progname = "sh"; argv = [|"sh"; Filename.maybe_quote hook_name|]; envp = systemenv; stdin_filename = ""; stdout_filename = ""; stderr_filename = ""; append = false; timeout = timeout; log = log; } in let exit_status = run settings in let final_value = match exit_status with | 0 -> begin match Modifier_parser.modifiers_of_file response_file with | modifiers -> let modified_env = Environments.apply_modifiers hookenv modifiers in (Result.pass, modified_env) | exception Failure reason -> (Result.fail_with_reason reason, hookenv) | exception Variables.No_such_variable name -> let reason = Printf.sprintf "error in script response: unknown variable %s" name in (Result.fail_with_reason reason, hookenv) end | _ -> Printf.fprintf log "Hook returned %d" exit_status; let reason = String.trim (Sys.string_of_file response_file) in if exit_status=125 then (Result.skip_with_reason reason, hookenv) else (Result.fail_with_reason reason, hookenv) in Sys.force_remove response_file; final_value let check_output kind_of_output output_variable reference_variable log env = let to_int = function None -> 0 | Some s -> int_of_string s in let skip_lines = to_int (Environments.lookup Builtin_variables.skip_header_lines env) in let skip_bytes = to_int (Environments.lookup Builtin_variables.skip_header_bytes env) in let reference_filename = Environments.safe_lookup reference_variable env in let output_filename = Environments.safe_lookup output_variable env in Printf.fprintf log "Comparing %s output %s to reference %s\n%!" kind_of_output output_filename reference_filename; let files = { Filecompare.filetype = Filecompare.Text; Filecompare.reference_filename = reference_filename; Filecompare.output_filename = output_filename } in let ignore_header_conf = { Filecompare.lines = skip_lines; Filecompare.bytes = skip_bytes; } in let tool = Filecompare.make_cmp_tool ~ignore:ignore_header_conf in match Filecompare.check_file ~tool files with | Filecompare.Same -> (Result.pass, env) | Filecompare.Different -> let diff = Filecompare.diff files in let diffstr = match diff with | Ok difference -> difference | Error diff_file -> ("See " ^ diff_file) in let reason = Printf.sprintf "%s output %s differs from reference %s: \n%s\n" kind_of_output output_filename reference_filename diffstr in if Environments.lookup_as_bool Builtin_variables.promote env = Some true then begin Printf.fprintf log "Promoting %s output %s to reference %s\n%!" kind_of_output output_filename reference_filename; Filecompare.promote files ignore_header_conf; end; (Result.fail_with_reason reason, env) | Filecompare.Unexpected_output -> let banner = String.make 40 '=' in let unexpected_output = Sys.string_of_file output_filename in let unexpected_output_with_banners = Printf.sprintf "%s\n%s%s\n" banner unexpected_output banner in let reason = Printf.sprintf "The file %s was expected to be empty because there is no \ reference file %s but it is not:\n%s\n" output_filename reference_filename unexpected_output_with_banners in (Result.fail_with_reason reason, env) | Filecompare.Error (commandline, exitcode) -> let reason = Printf.sprintf "The command %s failed with status %d" commandline exitcode in (Result.fail_with_reason reason, env)
null
https://raw.githubusercontent.com/avsm/eeww/4d65720b5dd51376842ffe5c8c220d5329c1dc10/boot/ocaml/ocamltest/actions_helpers.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Helper functions when writing actions Emulate ln -sfT
, projet Gallium , INRIA Paris Copyright 2016 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Ocamltest_stdlib let skip_with_reason reason = let code _log env = let result = Result.skip_with_reason reason in (result, env) in Actions.make ~name:"skip" ~description:"Skip the test" code let pass_or_skip test pass_reason skip_reason _log env = let open Result in let result = if test then pass_with_reason pass_reason else skip_with_reason skip_reason in (result, env) let mkreason what commandline exitcode = Printf.sprintf "%s: command\n%s\nfailed with exit code %d" what commandline exitcode let testfile env = match Environments.lookup Builtin_variables.test_file env with | None -> assert false | Some t -> t let test_source_directory env = Environments.safe_lookup Builtin_variables.test_source_directory env let test_build_directory env = Environments.safe_lookup Builtin_variables.test_build_directory env let test_build_directory_prefix env = Environments.safe_lookup Builtin_variables.test_build_directory_prefix env let words_of_variable env variable = String.words (Environments.safe_lookup variable env) let exit_status_of_variable env variable = try int_of_string (Environments.safe_lookup variable env) with _ -> 0 let readonly_files env = words_of_variable env Builtin_variables.readonly_files let subdirectories env = words_of_variable env Builtin_variables.subdirectories let setup_symlinks test_source_directory build_directory files = let symlink filename = let src = Filename.concat test_source_directory filename in let dst = Filename.concat build_directory filename in let () = if Sys.file_exists dst then if Sys.win32 && Sys.is_directory dst then Native symbolic links to directories do n't disappear with unlink ; doing rmdir here is technically slightly more than ln -sfT would do doing rmdir here is technically slightly more than ln -sfT would do *) Sys.rmdir dst else Sys.remove dst in Unix.symlink src dst in let copy filename = let src = Filename.concat test_source_directory filename in let dst = Filename.concat build_directory filename in Sys.copy_file src dst in let f = if Unix.has_symlink () then symlink else copy in Sys.make_directory build_directory; List.iter f files let setup_subdirectories source_directory build_directory subdirs = let full_src_path name = Filename.concat source_directory name in let full_dst_path name = Filename.concat build_directory name in let cp_dir name = Sys.copy_directory (full_src_path name) (full_dst_path name) in List.iter cp_dir subdirs let setup_build_env add_testfile additional_files (_log : out_channel) env = let source_dir = (test_source_directory env) in let build_dir = (test_build_directory env) in let some_files = additional_files @ (readonly_files env) in let files = if add_testfile then (testfile env) :: some_files else some_files in setup_symlinks source_dir build_dir files; let subdirs = subdirectories env in setup_subdirectories source_dir build_dir subdirs; Sys.chdir build_dir; (Result.pass, env) let setup_simple_build_env add_testfile additional_files log env = let build_env = Environments.add Builtin_variables.test_build_directory (test_build_directory_prefix env) env in setup_build_env add_testfile additional_files log build_env let run_cmd ?(environment=[||]) ?(stdin_variable=Builtin_variables.stdin) ?(stdout_variable=Builtin_variables.stdout) ?(stderr_variable=Builtin_variables.stderr) ?(append=false) ?timeout log env original_cmd = let log_redirection std filename = if filename<>"" then begin Printf.fprintf log " Redirecting %s to %s \n%!" std filename end in let cmd = if (Environments.lookup_as_bool Strace.strace env) = Some true then begin let action_name = Environments.safe_lookup Actions.action_name env in let test_build_directory = test_build_directory env in let strace_logfile_name = Strace.get_logfile_name action_name in let strace_logfile = Filename.make_path [test_build_directory; strace_logfile_name] in let strace_flags = Environments.safe_lookup Strace.strace_flags env in let strace_cmd = ["strace"; "-f"; "-o"; strace_logfile; strace_flags] in strace_cmd @ original_cmd end else original_cmd in let lst = List.concat (List.map String.words cmd) in let quoted_lst = if Sys.win32 then List.map Filename.maybe_quote lst else lst in let cmd' = String.concat " " quoted_lst in Printf.fprintf log "Commandline: %s\n" cmd'; let progname = List.hd quoted_lst in let arguments = Array.of_list quoted_lst in let stdin_filename = Environments.safe_lookup stdin_variable env in let stdout_filename = Environments.safe_lookup stdout_variable env in let stderr_filename = Environments.safe_lookup stderr_variable env in log_redirection "stdin" stdin_filename; log_redirection "stdout" stdout_filename; log_redirection "stderr" stderr_filename; let systemenv = Environments.append_to_system_env environment env in let timeout = match timeout with | Some timeout -> timeout | None -> Option.value ~default:0 (Environments.lookup_as_int Builtin_variables.timeout env) in let n = Run_command.run { Run_command.progname = progname; Run_command.argv = arguments; Run_command.envp = systemenv; Run_command.stdin_filename = stdin_filename; Run_command.stdout_filename = stdout_filename; Run_command.stderr_filename = stderr_filename; Run_command.append = append; Run_command.timeout = timeout; Run_command.log = log } in let dump_file s fn = if not (Sys.file_is_empty fn) then begin Printf.fprintf log "### begin %s ###\n" s; Sys.dump_file log fn; Printf.fprintf log "### end %s ###\n" s end in dump_file "stdout" stdout_filename; if stdout_filename <> stderr_filename then dump_file "stderr" stderr_filename; n let run (log_message : string) (redirect_output : bool) (can_skip : bool) (prog_variable : Variables.t) (args_variable : Variables.t option) (log : out_channel) (env : Environments.t) = match Environments.lookup prog_variable env with | None -> let msg = Printf.sprintf "%s: variable %s is undefined" log_message (Variables.name_of_variable prog_variable) in (Result.fail_with_reason msg, env) | Some program -> let arguments = match args_variable with | None -> "" | Some variable -> Environments.safe_lookup variable env in let commandline = [program; arguments] in let what = log_message ^ " " ^ program ^ " " ^ begin if arguments="" then "without any argument" else "with arguments " ^ arguments end in let env = if redirect_output then begin let output = Environments.safe_lookup Builtin_variables.output env in let env = Environments.add_if_undefined Builtin_variables.stdout output env in Environments.add_if_undefined Builtin_variables.stderr output env end else env in let expected_exit_status = exit_status_of_variable env Builtin_variables.exit_status in let exit_status = run_cmd log env commandline in if exit_status=expected_exit_status then (Result.pass, env) else begin let reason = mkreason what (String.concat " " commandline) exit_status in if exit_status = 125 && can_skip then (Result.skip_with_reason reason, env) else (Result.fail_with_reason reason, env) end let run_program = run "Running program" true false Builtin_variables.program (Some Builtin_variables.arguments) let run_script log env = let response_file = Filename.temp_file "ocamltest-" ".response" in Printf.fprintf log "Script should write its response to %s\n%!" response_file; let scriptenv = Environments.add Builtin_variables.ocamltest_response response_file env in let (result, newenv) = run "Running script" true true Builtin_variables.script None log scriptenv in let final_value = if Result.is_pass result then begin match Modifier_parser.modifiers_of_file response_file with | modifiers -> let modified_env = Environments.apply_modifiers newenv modifiers in (result, modified_env) | exception Failure reason -> (Result.fail_with_reason reason, newenv) | exception Variables.No_such_variable name -> let reason = Printf.sprintf "error in script response: unknown variable %s" name in (Result.fail_with_reason reason, newenv) end else begin let reason = String.trim (Sys.string_of_file response_file) in let newresult = { result with Result.reason = Some reason } in (newresult, newenv) end in Sys.force_remove response_file; final_value let run_hook hook_name log input_env = Printf.fprintf log "Entering run_hook for hook %s\n%!" hook_name; let response_file = Filename.temp_file "ocamltest-" ".response" in Printf.fprintf log "Hook should write its response to %s\n%!" response_file; let hookenv = Environments.add Builtin_variables.ocamltest_response response_file input_env in let systemenv = Environments.to_system_env hookenv in let timeout = Option.value ~default:0 (Environments.lookup_as_int Builtin_variables.timeout input_env) in let open Run_command in let settings = { progname = "sh"; argv = [|"sh"; Filename.maybe_quote hook_name|]; envp = systemenv; stdin_filename = ""; stdout_filename = ""; stderr_filename = ""; append = false; timeout = timeout; log = log; } in let exit_status = run settings in let final_value = match exit_status with | 0 -> begin match Modifier_parser.modifiers_of_file response_file with | modifiers -> let modified_env = Environments.apply_modifiers hookenv modifiers in (Result.pass, modified_env) | exception Failure reason -> (Result.fail_with_reason reason, hookenv) | exception Variables.No_such_variable name -> let reason = Printf.sprintf "error in script response: unknown variable %s" name in (Result.fail_with_reason reason, hookenv) end | _ -> Printf.fprintf log "Hook returned %d" exit_status; let reason = String.trim (Sys.string_of_file response_file) in if exit_status=125 then (Result.skip_with_reason reason, hookenv) else (Result.fail_with_reason reason, hookenv) in Sys.force_remove response_file; final_value let check_output kind_of_output output_variable reference_variable log env = let to_int = function None -> 0 | Some s -> int_of_string s in let skip_lines = to_int (Environments.lookup Builtin_variables.skip_header_lines env) in let skip_bytes = to_int (Environments.lookup Builtin_variables.skip_header_bytes env) in let reference_filename = Environments.safe_lookup reference_variable env in let output_filename = Environments.safe_lookup output_variable env in Printf.fprintf log "Comparing %s output %s to reference %s\n%!" kind_of_output output_filename reference_filename; let files = { Filecompare.filetype = Filecompare.Text; Filecompare.reference_filename = reference_filename; Filecompare.output_filename = output_filename } in let ignore_header_conf = { Filecompare.lines = skip_lines; Filecompare.bytes = skip_bytes; } in let tool = Filecompare.make_cmp_tool ~ignore:ignore_header_conf in match Filecompare.check_file ~tool files with | Filecompare.Same -> (Result.pass, env) | Filecompare.Different -> let diff = Filecompare.diff files in let diffstr = match diff with | Ok difference -> difference | Error diff_file -> ("See " ^ diff_file) in let reason = Printf.sprintf "%s output %s differs from reference %s: \n%s\n" kind_of_output output_filename reference_filename diffstr in if Environments.lookup_as_bool Builtin_variables.promote env = Some true then begin Printf.fprintf log "Promoting %s output %s to reference %s\n%!" kind_of_output output_filename reference_filename; Filecompare.promote files ignore_header_conf; end; (Result.fail_with_reason reason, env) | Filecompare.Unexpected_output -> let banner = String.make 40 '=' in let unexpected_output = Sys.string_of_file output_filename in let unexpected_output_with_banners = Printf.sprintf "%s\n%s%s\n" banner unexpected_output banner in let reason = Printf.sprintf "The file %s was expected to be empty because there is no \ reference file %s but it is not:\n%s\n" output_filename reference_filename unexpected_output_with_banners in (Result.fail_with_reason reason, env) | Filecompare.Error (commandline, exitcode) -> let reason = Printf.sprintf "The command %s failed with status %d" commandline exitcode in (Result.fail_with_reason reason, env)
500d3624af29b7511c9401cac67c93fc1347fb582b63924340286228915b080a
dmitryvk/sbcl-win32-threads
objdef.lisp
;;;; machine-independent aspects of the object representation This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!VM") : The primitive objects here may look like self - contained ;;;; definitions, but in general they're not. In particular, if you ;;;; try to add a slot to them, beware of the following: * The GC scavenging code ( and for all I know other GC code too ) ;;;; is not automatically generated from these layouts, but instead ;;;; was hand-written to correspond to them. The offsets are automatically propagated into the GC scavenging code , but the ;;;; existence of slots, and whether they should be scavenged, is ;;;; not automatically propagated. Thus e.g. if you add a ;;;; SIMPLE-FUN-DEBUG-INFO slot holding a tagged object which needs to be GCed , you need to tweak scav_code_header ( ) and verify_space ( ) in gencgc.c , and the corresponding code in gc.c . ;;;; * The src/runtime/print.c code (used by LDB) is implemented ;;;; using hand-written lists of slot names, which aren't automatically ;;;; generated from the code in this file. * Various code ( e.g. STATIC - FSET in genesis.lisp ) is hard - wired ;;;; to know the name of the last slot of the object the code works ;;;; with, and implicitly to know that the last slot is special (being ;;;; the beginning of an arbitrary-length sequence of bytes following ;;;; the fixed-layout slots). -- WHN 2001 - 12 - 29 ;;;; the primitive objects themselves (define-primitive-object (cons :lowtag list-pointer-lowtag :alloc-trans cons) (car :ref-trans car :set-trans sb!c::%rplaca :init :arg :cas-trans %compare-and-swap-car) (cdr :ref-trans cdr :set-trans sb!c::%rplacd :init :arg :cas-trans %compare-and-swap-cdr)) (define-primitive-object (instance :lowtag instance-pointer-lowtag :widetag instance-header-widetag :alloc-trans %make-instance) (slots :rest-p t)) (define-primitive-object (bignum :lowtag other-pointer-lowtag :widetag bignum-widetag :alloc-trans sb!bignum::%allocate-bignum) (digits :rest-p t :c-type #!-alpha "long" #!+alpha "u32")) (define-primitive-object (ratio :type ratio :lowtag other-pointer-lowtag :widetag ratio-widetag :alloc-trans %make-ratio) (numerator :type integer :ref-known (flushable movable) :ref-trans %numerator :init :arg) (denominator :type integer :ref-known (flushable movable) :ref-trans %denominator :init :arg)) #!+#.(cl:if (cl:= sb!vm:n-word-bits 32) '(and) '(or)) (define-primitive-object (single-float :lowtag other-pointer-lowtag :widetag single-float-widetag) (value :c-type "float")) (define-primitive-object (double-float :lowtag other-pointer-lowtag :widetag double-float-widetag) #!-x86-64 (filler) (value :c-type "double" :length #!-x86-64 2 #!+x86-64 1)) #!+long-float (define-primitive-object (long-float :lowtag other-pointer-lowtag :widetag long-float-widetag) #!+sparc (filler) (value :c-type "long double" :length #!+x86 3 #!+sparc 4)) (define-primitive-object (complex :type complex :lowtag other-pointer-lowtag :widetag complex-widetag :alloc-trans %make-complex) (real :type real :ref-known (flushable movable) :ref-trans %realpart :init :arg) (imag :type real :ref-known (flushable movable) :ref-trans %imagpart :init :arg)) (define-primitive-object (array :lowtag other-pointer-lowtag :widetag t) ;; FILL-POINTER of an ARRAY is in the same place as LENGTH of a VECTOR -- see SHRINK - VECTOR . (fill-pointer :type index :ref-trans %array-fill-pointer :ref-known (flushable foldable) :set-trans (setf %array-fill-pointer) :set-known (unsafe)) (fill-pointer-p :type (member t nil) :ref-trans %array-fill-pointer-p :ref-known (flushable foldable) :set-trans (setf %array-fill-pointer-p) :set-known (unsafe)) (elements :type index :ref-trans %array-available-elements :ref-known (flushable foldable) :set-trans (setf %array-available-elements) :set-known (unsafe)) (data :type array :ref-trans %array-data-vector :ref-known (flushable foldable) :set-trans (setf %array-data-vector) :set-known (unsafe)) (displacement :type (or index null) :ref-trans %array-displacement :ref-known (flushable foldable) :set-trans (setf %array-displacement) :set-known (unsafe)) (displaced-p :type t :ref-trans %array-displaced-p :ref-known (flushable foldable) :set-trans (setf %array-displaced-p) :set-known (unsafe)) (displaced-from :type list :ref-trans %array-displaced-from :ref-known (flushable) :set-trans (setf %array-displaced-from) :set-known (unsafe)) (dimensions :rest-p t)) (define-primitive-object (vector :type vector :lowtag other-pointer-lowtag :widetag t) ;; FILL-POINTER of an ARRAY is in the same place as LENGTH of a VECTOR -- see SHRINK - VECTOR . (length :ref-trans sb!c::vector-length :type index) (data :rest-p t :c-type #!-alpha "unsigned long" #!+alpha "u32")) (define-primitive-object (code :type code-component :lowtag other-pointer-lowtag :widetag t) (code-size :type index :ref-known (flushable movable) :ref-trans %code-code-size) (entry-points :type (or function null) :ref-known (flushable) :ref-trans %code-entry-points :set-known (unsafe) :set-trans (setf %code-entry-points)) (debug-info :type t :ref-known (flushable) :ref-trans %code-debug-info :set-known (unsafe) :set-trans (setf %code-debug-info)) (trace-table-offset) (constants :rest-p t)) (define-primitive-object (fdefn :type fdefn :lowtag other-pointer-lowtag :widetag fdefn-widetag) (name :ref-trans fdefn-name) (fun :type (or function null) :ref-trans fdefn-fun) (raw-addr :c-type #!-alpha "char *" #!+alpha "u32")) ;;; a simple function (as opposed to hairier things like closures which are also subtypes of Common Lisp 's FUNCTION type ) (define-primitive-object (simple-fun :type function :lowtag fun-pointer-lowtag :widetag simple-fun-header-widetag) #!-(or x86 x86-64) (self :ref-trans %simple-fun-self :set-trans (setf %simple-fun-self)) #!+(or x86 x86-64) (self : There 's no : SET - KNOWN , : SET - TRANS , : REF - KNOWN , or : REF - TRANS here in this case . Instead , there 's separate DEFKNOWN / DEFINE - VOP / DEFTRANSFORM stuff in ;; compiler/x86/system.lisp to define and declare them by ;; hand. I don't know why this is, but that's (basically) the way it was done in CMU CL , and it works . ( It 's not exactly the same way it was done in CMU CL in that CMU CL 's allows duplicate DEFKNOWNs , blithely overwriting any previous data associated with the previous DEFKNOWN , and ;; that property was used to mask the definitions here. In SBCL as of 0.6.12.64 that 's not allowed -- too confusing ! ;; -- so we have to explicitly suppress the DEFKNOWNish ;; stuff here in order to allow this old hack to work in the new world . -- WHN 2001 - 08 - 82 ) (next :type (or function null) :ref-known (flushable) :ref-trans %simple-fun-next :set-known (unsafe) :set-trans (setf %simple-fun-next)) (name :ref-known (flushable) :ref-trans %simple-fun-name :set-known (unsafe) :set-trans (setf %simple-fun-name)) (arglist :type list :ref-known (flushable) :ref-trans %simple-fun-arglist :set-known (unsafe) :set-trans (setf %simple-fun-arglist)) (type :ref-known (flushable) :ref-trans %simple-fun-type :set-known (unsafe) :set-trans (setf %simple-fun-type)) NIL for empty , STRING for a docstring , SIMPLE - VECTOR for XREFS , and ( CONS ;; STRING SIMPLE-VECTOR) for both. (info :init :null :ref-trans %simple-fun-info :ref-known (flushable) :set-trans (setf %simple-fun-info) :set-known (unsafe)) ;; the SB!C::DEBUG-FUN object corresponding to this object, or NIL for none FIXME : does n't work ( gotcha , lowly ! ) See notes on bug 137 . (debug-fun :ref-known (flushable) :ref-trans %simple-fun-debug-fun :set-known (unsafe) :set-trans (setf %simple-fun-debug-fun)) (code :rest-p t :c-type "unsigned char")) (define-primitive-object (return-pc :lowtag other-pointer-lowtag :widetag t) (return-point :c-type "unsigned char" :rest-p t)) (define-primitive-object (closure :lowtag fun-pointer-lowtag :widetag closure-header-widetag) (fun :init :arg :ref-trans %closure-fun) (info :rest-p t)) (define-primitive-object (funcallable-instance :lowtag fun-pointer-lowtag :widetag funcallable-instance-header-widetag :alloc-trans %make-funcallable-instance) (trampoline :init :funcallable-instance-tramp) (function :ref-known (flushable) :ref-trans %funcallable-instance-function :set-known (unsafe) :set-trans (setf %funcallable-instance-function)) (info :rest-p t)) (define-primitive-object (value-cell :lowtag other-pointer-lowtag :widetag value-cell-header-widetag FIXME : We also have an explicit VOP ;; for this. Is this needed as well? :alloc-trans make-value-cell) (value :set-trans value-cell-set :set-known (unsafe) :ref-trans value-cell-ref :ref-known (flushable) :init :arg)) #!+alpha (define-primitive-object (sap :lowtag other-pointer-lowtag :widetag sap-widetag) (padding) (pointer :c-type "char *" :length 2)) #!-alpha (define-primitive-object (sap :lowtag other-pointer-lowtag :widetag sap-widetag) (pointer :c-type "char *")) (define-primitive-object (weak-pointer :type weak-pointer :lowtag other-pointer-lowtag :widetag weak-pointer-widetag :alloc-trans make-weak-pointer) (value :ref-trans sb!c::%weak-pointer-value :ref-known (flushable) :init :arg) (broken :type (member t nil) :ref-trans sb!c::%weak-pointer-broken :ref-known (flushable) :init :null) (next :c-type #!-alpha "struct weak_pointer *" #!+alpha "u32")) ;;;; other non-heap data blocks (define-primitive-object (binding) value symbol) (define-primitive-object (unwind-block) (current-uwp :c-type #!-alpha "struct unwind_block *" #!+alpha "u32") (current-cont :c-type #!-alpha "lispobj *" #!+alpha "u32") #!-(or x86 x86-64) current-code entry-pc #!+win32 next-seh-frame #!+win32 seh-frame-handler) (define-primitive-object (catch-block) (current-uwp :c-type #!-alpha "struct unwind_block *" #!+alpha "u32") (current-cont :c-type #!-alpha "lispobj *" #!+alpha "u32") #!-(or x86 x86-64) current-code entry-pc #!+win32 next-seh-frame #!+win32 seh-frame-handler tag (previous-catch :c-type #!-alpha "struct catch_block *" #!+alpha "u32")) ;;; (For an explanation of this, see the comments at the definition of ;;; KLUDGE-NONDETERMINISTIC-CATCH-BLOCK-SIZE.) (aver (= kludge-nondeterministic-catch-block-size catch-block-size)) ;;;; symbols (define-primitive-object (symbol :lowtag other-pointer-lowtag :widetag symbol-header-widetag :alloc-trans %make-symbol) Beware when changing this definition . NIL - the - symbol is defined ;; using this layout, and NIL-the-end-of-list-marker is the cons ( NIL . NIL ) , living in the first two slots of NIL - the - symbol ( conses have no header ) . Careful selection of lowtags ensures ;; that the same pointer can be used for both purposes: OTHER - POINTER - LOWTAG is 7 , LIST - POINTER - LOWTAG is 3 , so if you subtract 3 from ( SB - KERNEL : GET - LISP - OBJ - ADDRESS ' NIL ) you get the first data slot , and if you subtract 7 you get a symbol header . ;; also the CAR of NIL-as-end-of-list (value :init :unbound :set-trans %set-symbol-global-value :set-known (unsafe)) ;; also the CDR of NIL-as-end-of-list. Its reffer needs special ;; care for this reason, as hash values must be fixnums. (hash :set-trans %set-symbol-hash) (plist :ref-trans symbol-plist :set-trans %set-symbol-plist :cas-trans %compare-and-swap-symbol-plist :type list :init :null) (name :ref-trans symbol-name :init :arg) (package :ref-trans symbol-package :set-trans %set-symbol-package :init :null) #!+sb-thread (tls-index :ref-known (flushable) :ref-trans symbol-tls-index)) (define-primitive-object (complex-single-float :lowtag other-pointer-lowtag :widetag complex-single-float-widetag) #!+x86-64 (data :c-type "struct { float data[2]; } ") #!-x86-64 (real :c-type "float") #!-x86-64 (imag :c-type "float")) (define-primitive-object (complex-double-float :lowtag other-pointer-lowtag :widetag complex-double-float-widetag) (filler) (real :c-type "double" :length #!-x86-64 2 #!+x86-64 1) (imag :c-type "double" :length #!-x86-64 2 #!+x86-64 1)) #!+(and sb-lutex sb-thread) (define-primitive-object (lutex :lowtag other-pointer-lowtag :widetag lutex-widetag :alloc-trans %make-lutex) (gen :c-type "long" :length 1) (live :c-type "long" :length 1) (next :c-type "struct lutex *" :length 1) (prev :c-type "struct lutex *" :length 1) (mutex :c-type "pthread_mutex_t *" :length 1) (mutexattr :c-type "pthread_mutexattr_t *" :length 1) (condition-variable :c-type "pthread_cond_t *" :length 1)) ;;; this isn't actually a lisp object at all, it's a c structure that lives ;;; in c-land. However, we need sight of so many parts of it from Lisp that it makes sense to define it here anyway , so that the GENESIS machinery ;;; can take care of maintaining Lisp and C versions. ;;; Hence the even-fixnum lowtag just so we don't get odd(sic) numbers ;;; added to the slot offsets (define-primitive-object (thread :lowtag even-fixnum-lowtag) ;; no_tls_value_marker is borrowed very briefly at thread startup to ;; pass the address of initial-function into new_thread_trampoline. ;; tls[0] = NO_TLS_VALUE_MARKER_WIDETAG because a the tls index slot of a symbol is initialized to zero (no-tls-value-marker) (os-thread :c-type "os_thread_t") ;; This is the original address at which the memory was allocated, ;; which may have different alignment then what we prefer to use. ;; Kept here so that when the thread dies we can release the whole ;; memory we reserved. (os-address :c-type "void *" :length #!+alpha 2 #!-alpha 1) #!+sb-thread (os-attr :c-type "pthread_attr_t *" :length #!+alpha 2 #!-alpha 1) #!+sb-thread (state-lock :c-type "pthread_mutex_t *" :length #!+alpha 2 #!-alpha 1) #!+sb-thread (state-cond :c-type "pthread_cond_t *" :length #!+alpha 2 #!-alpha 1) (binding-stack-start :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (binding-stack-pointer :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (control-stack-start :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (control-stack-end :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (control-stack-guard-page-protected) (alien-stack-start :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (alien-stack-pointer :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) #!+gencgc (alloc-region :c-type "struct alloc_region" :length 5) #!+win32 (private-events :c-type "struct private_events" :length 2) (this :c-type "struct thread *" :length #!+alpha 2 #!-alpha 1) (prev :c-type "struct thread *" :length #!+alpha 2 #!-alpha 1) (next :c-type "struct thread *" :length #!+alpha 2 #!-alpha 1) ;; starting, running, suspended, dead (state :c-type "lispobj") on x86 , the LDT index #!+(or x86 x86-64 sb-thread) (pseudo-atomic-bits) (interrupt-data :c-type "struct interrupt_data *" :length #!+alpha 2 #!-alpha 1) (stepping) ;; For various reasons related to pseudo-atomic and interrupt ;; handling, we need to know if the machine context is in Lisp code ;; or not. On non-threaded targets, this is a global variable in ;; the runtime, but it's clearly a per-thread value. #!+sb-thread (foreign-function-call-active :c-type "boolean") ;; Same as above for the location of the current control stack frame. #!+(and sb-thread (not (or x86 x86-64))) (control-frame-pointer :c-type "lispobj *") ;; Same as above for the location of the current control stack ;; pointer. This is also used on threaded x86oids to allow LDB to print an approximation of the CSP as needed . #!+(and sb-thread) (control-stack-pointer :c-type "lispobj *") : On alpha , until STEPPING we have been lucky and the 32 ;; bit slots came in pairs. However the C compiler will align ;; interrupt_contexts on a double word boundary. This logic should ;; be handled by DEFINE-PRIMITIVE-OBJECT. #!+alpha (padding) (interrupt-contexts :c-type "os_context_t *" :rest-p t))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/generic/objdef.lisp
lisp
machine-independent aspects of the object representation more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. definitions, but in general they're not. In particular, if you try to add a slot to them, beware of the following: is not automatically generated from these layouts, but instead was hand-written to correspond to them. The offsets are existence of slots, and whether they should be scavenged, is not automatically propagated. Thus e.g. if you add a SIMPLE-FUN-DEBUG-INFO slot holding a tagged object which needs * The src/runtime/print.c code (used by LDB) is implemented using hand-written lists of slot names, which aren't automatically generated from the code in this file. to know the name of the last slot of the object the code works with, and implicitly to know that the last slot is special (being the beginning of an arbitrary-length sequence of bytes following the fixed-layout slots). the primitive objects themselves FILL-POINTER of an ARRAY is in the same place as LENGTH of a FILL-POINTER of an ARRAY is in the same place as LENGTH of a a simple function (as opposed to hairier things like closures compiler/x86/system.lisp to define and declare them by hand. I don't know why this is, but that's (basically) that property was used to mask the definitions here. In -- so we have to explicitly suppress the DEFKNOWNish stuff here in order to allow this old hack to work in the STRING SIMPLE-VECTOR) for both. the SB!C::DEBUG-FUN object corresponding to this object, or NIL for none for this. Is this needed as well? other non-heap data blocks (For an explanation of this, see the comments at the definition of KLUDGE-NONDETERMINISTIC-CATCH-BLOCK-SIZE.) symbols using this layout, and NIL-the-end-of-list-marker is the cons that the same pointer can be used for both purposes: also the CAR of NIL-as-end-of-list also the CDR of NIL-as-end-of-list. Its reffer needs special care for this reason, as hash values must be fixnums. this isn't actually a lisp object at all, it's a c structure that lives in c-land. However, we need sight of so many parts of it from Lisp that can take care of maintaining Lisp and C versions. Hence the even-fixnum lowtag just so we don't get odd(sic) numbers added to the slot offsets no_tls_value_marker is borrowed very briefly at thread startup to pass the address of initial-function into new_thread_trampoline. tls[0] = NO_TLS_VALUE_MARKER_WIDETAG because a the tls index slot This is the original address at which the memory was allocated, which may have different alignment then what we prefer to use. Kept here so that when the thread dies we can release the whole memory we reserved. starting, running, suspended, dead For various reasons related to pseudo-atomic and interrupt handling, we need to know if the machine context is in Lisp code or not. On non-threaded targets, this is a global variable in the runtime, but it's clearly a per-thread value. Same as above for the location of the current control stack frame. Same as above for the location of the current control stack pointer. This is also used on threaded x86oids to allow LDB to bit slots came in pairs. However the C compiler will align interrupt_contexts on a double word boundary. This logic should be handled by DEFINE-PRIMITIVE-OBJECT.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!VM") : The primitive objects here may look like self - contained * The GC scavenging code ( and for all I know other GC code too ) automatically propagated into the GC scavenging code , but the to be GCed , you need to tweak scav_code_header ( ) and verify_space ( ) in gencgc.c , and the corresponding code in gc.c . * Various code ( e.g. STATIC - FSET in genesis.lisp ) is hard - wired -- WHN 2001 - 12 - 29 (define-primitive-object (cons :lowtag list-pointer-lowtag :alloc-trans cons) (car :ref-trans car :set-trans sb!c::%rplaca :init :arg :cas-trans %compare-and-swap-car) (cdr :ref-trans cdr :set-trans sb!c::%rplacd :init :arg :cas-trans %compare-and-swap-cdr)) (define-primitive-object (instance :lowtag instance-pointer-lowtag :widetag instance-header-widetag :alloc-trans %make-instance) (slots :rest-p t)) (define-primitive-object (bignum :lowtag other-pointer-lowtag :widetag bignum-widetag :alloc-trans sb!bignum::%allocate-bignum) (digits :rest-p t :c-type #!-alpha "long" #!+alpha "u32")) (define-primitive-object (ratio :type ratio :lowtag other-pointer-lowtag :widetag ratio-widetag :alloc-trans %make-ratio) (numerator :type integer :ref-known (flushable movable) :ref-trans %numerator :init :arg) (denominator :type integer :ref-known (flushable movable) :ref-trans %denominator :init :arg)) #!+#.(cl:if (cl:= sb!vm:n-word-bits 32) '(and) '(or)) (define-primitive-object (single-float :lowtag other-pointer-lowtag :widetag single-float-widetag) (value :c-type "float")) (define-primitive-object (double-float :lowtag other-pointer-lowtag :widetag double-float-widetag) #!-x86-64 (filler) (value :c-type "double" :length #!-x86-64 2 #!+x86-64 1)) #!+long-float (define-primitive-object (long-float :lowtag other-pointer-lowtag :widetag long-float-widetag) #!+sparc (filler) (value :c-type "long double" :length #!+x86 3 #!+sparc 4)) (define-primitive-object (complex :type complex :lowtag other-pointer-lowtag :widetag complex-widetag :alloc-trans %make-complex) (real :type real :ref-known (flushable movable) :ref-trans %realpart :init :arg) (imag :type real :ref-known (flushable movable) :ref-trans %imagpart :init :arg)) (define-primitive-object (array :lowtag other-pointer-lowtag :widetag t) VECTOR -- see SHRINK - VECTOR . (fill-pointer :type index :ref-trans %array-fill-pointer :ref-known (flushable foldable) :set-trans (setf %array-fill-pointer) :set-known (unsafe)) (fill-pointer-p :type (member t nil) :ref-trans %array-fill-pointer-p :ref-known (flushable foldable) :set-trans (setf %array-fill-pointer-p) :set-known (unsafe)) (elements :type index :ref-trans %array-available-elements :ref-known (flushable foldable) :set-trans (setf %array-available-elements) :set-known (unsafe)) (data :type array :ref-trans %array-data-vector :ref-known (flushable foldable) :set-trans (setf %array-data-vector) :set-known (unsafe)) (displacement :type (or index null) :ref-trans %array-displacement :ref-known (flushable foldable) :set-trans (setf %array-displacement) :set-known (unsafe)) (displaced-p :type t :ref-trans %array-displaced-p :ref-known (flushable foldable) :set-trans (setf %array-displaced-p) :set-known (unsafe)) (displaced-from :type list :ref-trans %array-displaced-from :ref-known (flushable) :set-trans (setf %array-displaced-from) :set-known (unsafe)) (dimensions :rest-p t)) (define-primitive-object (vector :type vector :lowtag other-pointer-lowtag :widetag t) VECTOR -- see SHRINK - VECTOR . (length :ref-trans sb!c::vector-length :type index) (data :rest-p t :c-type #!-alpha "unsigned long" #!+alpha "u32")) (define-primitive-object (code :type code-component :lowtag other-pointer-lowtag :widetag t) (code-size :type index :ref-known (flushable movable) :ref-trans %code-code-size) (entry-points :type (or function null) :ref-known (flushable) :ref-trans %code-entry-points :set-known (unsafe) :set-trans (setf %code-entry-points)) (debug-info :type t :ref-known (flushable) :ref-trans %code-debug-info :set-known (unsafe) :set-trans (setf %code-debug-info)) (trace-table-offset) (constants :rest-p t)) (define-primitive-object (fdefn :type fdefn :lowtag other-pointer-lowtag :widetag fdefn-widetag) (name :ref-trans fdefn-name) (fun :type (or function null) :ref-trans fdefn-fun) (raw-addr :c-type #!-alpha "char *" #!+alpha "u32")) which are also subtypes of Common Lisp 's FUNCTION type ) (define-primitive-object (simple-fun :type function :lowtag fun-pointer-lowtag :widetag simple-fun-header-widetag) #!-(or x86 x86-64) (self :ref-trans %simple-fun-self :set-trans (setf %simple-fun-self)) #!+(or x86 x86-64) (self : There 's no : SET - KNOWN , : SET - TRANS , : REF - KNOWN , or : REF - TRANS here in this case . Instead , there 's separate DEFKNOWN / DEFINE - VOP / DEFTRANSFORM stuff in the way it was done in CMU CL , and it works . ( It 's not exactly the same way it was done in CMU CL in that CMU CL 's allows duplicate DEFKNOWNs , blithely overwriting any previous data associated with the previous DEFKNOWN , and SBCL as of 0.6.12.64 that 's not allowed -- too confusing ! new world . -- WHN 2001 - 08 - 82 ) (next :type (or function null) :ref-known (flushable) :ref-trans %simple-fun-next :set-known (unsafe) :set-trans (setf %simple-fun-next)) (name :ref-known (flushable) :ref-trans %simple-fun-name :set-known (unsafe) :set-trans (setf %simple-fun-name)) (arglist :type list :ref-known (flushable) :ref-trans %simple-fun-arglist :set-known (unsafe) :set-trans (setf %simple-fun-arglist)) (type :ref-known (flushable) :ref-trans %simple-fun-type :set-known (unsafe) :set-trans (setf %simple-fun-type)) NIL for empty , STRING for a docstring , SIMPLE - VECTOR for XREFS , and ( CONS (info :init :null :ref-trans %simple-fun-info :ref-known (flushable) :set-trans (setf %simple-fun-info) :set-known (unsafe)) FIXME : does n't work ( gotcha , lowly ! ) See notes on bug 137 . (debug-fun :ref-known (flushable) :ref-trans %simple-fun-debug-fun :set-known (unsafe) :set-trans (setf %simple-fun-debug-fun)) (code :rest-p t :c-type "unsigned char")) (define-primitive-object (return-pc :lowtag other-pointer-lowtag :widetag t) (return-point :c-type "unsigned char" :rest-p t)) (define-primitive-object (closure :lowtag fun-pointer-lowtag :widetag closure-header-widetag) (fun :init :arg :ref-trans %closure-fun) (info :rest-p t)) (define-primitive-object (funcallable-instance :lowtag fun-pointer-lowtag :widetag funcallable-instance-header-widetag :alloc-trans %make-funcallable-instance) (trampoline :init :funcallable-instance-tramp) (function :ref-known (flushable) :ref-trans %funcallable-instance-function :set-known (unsafe) :set-trans (setf %funcallable-instance-function)) (info :rest-p t)) (define-primitive-object (value-cell :lowtag other-pointer-lowtag :widetag value-cell-header-widetag FIXME : We also have an explicit VOP :alloc-trans make-value-cell) (value :set-trans value-cell-set :set-known (unsafe) :ref-trans value-cell-ref :ref-known (flushable) :init :arg)) #!+alpha (define-primitive-object (sap :lowtag other-pointer-lowtag :widetag sap-widetag) (padding) (pointer :c-type "char *" :length 2)) #!-alpha (define-primitive-object (sap :lowtag other-pointer-lowtag :widetag sap-widetag) (pointer :c-type "char *")) (define-primitive-object (weak-pointer :type weak-pointer :lowtag other-pointer-lowtag :widetag weak-pointer-widetag :alloc-trans make-weak-pointer) (value :ref-trans sb!c::%weak-pointer-value :ref-known (flushable) :init :arg) (broken :type (member t nil) :ref-trans sb!c::%weak-pointer-broken :ref-known (flushable) :init :null) (next :c-type #!-alpha "struct weak_pointer *" #!+alpha "u32")) (define-primitive-object (binding) value symbol) (define-primitive-object (unwind-block) (current-uwp :c-type #!-alpha "struct unwind_block *" #!+alpha "u32") (current-cont :c-type #!-alpha "lispobj *" #!+alpha "u32") #!-(or x86 x86-64) current-code entry-pc #!+win32 next-seh-frame #!+win32 seh-frame-handler) (define-primitive-object (catch-block) (current-uwp :c-type #!-alpha "struct unwind_block *" #!+alpha "u32") (current-cont :c-type #!-alpha "lispobj *" #!+alpha "u32") #!-(or x86 x86-64) current-code entry-pc #!+win32 next-seh-frame #!+win32 seh-frame-handler tag (previous-catch :c-type #!-alpha "struct catch_block *" #!+alpha "u32")) (aver (= kludge-nondeterministic-catch-block-size catch-block-size)) (define-primitive-object (symbol :lowtag other-pointer-lowtag :widetag symbol-header-widetag :alloc-trans %make-symbol) Beware when changing this definition . NIL - the - symbol is defined ( NIL . NIL ) , living in the first two slots of NIL - the - symbol ( conses have no header ) . Careful selection of lowtags ensures OTHER - POINTER - LOWTAG is 7 , LIST - POINTER - LOWTAG is 3 , so if you subtract 3 from ( SB - KERNEL : GET - LISP - OBJ - ADDRESS ' NIL ) you get the first data slot , and if you subtract 7 you get a symbol header . (value :init :unbound :set-trans %set-symbol-global-value :set-known (unsafe)) (hash :set-trans %set-symbol-hash) (plist :ref-trans symbol-plist :set-trans %set-symbol-plist :cas-trans %compare-and-swap-symbol-plist :type list :init :null) (name :ref-trans symbol-name :init :arg) (package :ref-trans symbol-package :set-trans %set-symbol-package :init :null) #!+sb-thread (tls-index :ref-known (flushable) :ref-trans symbol-tls-index)) (define-primitive-object (complex-single-float :lowtag other-pointer-lowtag :widetag complex-single-float-widetag) #!+x86-64 (data :c-type "struct { float data[2]; } ") #!-x86-64 (real :c-type "float") #!-x86-64 (imag :c-type "float")) (define-primitive-object (complex-double-float :lowtag other-pointer-lowtag :widetag complex-double-float-widetag) (filler) (real :c-type "double" :length #!-x86-64 2 #!+x86-64 1) (imag :c-type "double" :length #!-x86-64 2 #!+x86-64 1)) #!+(and sb-lutex sb-thread) (define-primitive-object (lutex :lowtag other-pointer-lowtag :widetag lutex-widetag :alloc-trans %make-lutex) (gen :c-type "long" :length 1) (live :c-type "long" :length 1) (next :c-type "struct lutex *" :length 1) (prev :c-type "struct lutex *" :length 1) (mutex :c-type "pthread_mutex_t *" :length 1) (mutexattr :c-type "pthread_mutexattr_t *" :length 1) (condition-variable :c-type "pthread_cond_t *" :length 1)) it makes sense to define it here anyway , so that the GENESIS machinery (define-primitive-object (thread :lowtag even-fixnum-lowtag) of a symbol is initialized to zero (no-tls-value-marker) (os-thread :c-type "os_thread_t") (os-address :c-type "void *" :length #!+alpha 2 #!-alpha 1) #!+sb-thread (os-attr :c-type "pthread_attr_t *" :length #!+alpha 2 #!-alpha 1) #!+sb-thread (state-lock :c-type "pthread_mutex_t *" :length #!+alpha 2 #!-alpha 1) #!+sb-thread (state-cond :c-type "pthread_cond_t *" :length #!+alpha 2 #!-alpha 1) (binding-stack-start :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (binding-stack-pointer :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (control-stack-start :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (control-stack-end :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (control-stack-guard-page-protected) (alien-stack-start :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) (alien-stack-pointer :c-type "lispobj *" :length #!+alpha 2 #!-alpha 1) #!+gencgc (alloc-region :c-type "struct alloc_region" :length 5) #!+win32 (private-events :c-type "struct private_events" :length 2) (this :c-type "struct thread *" :length #!+alpha 2 #!-alpha 1) (prev :c-type "struct thread *" :length #!+alpha 2 #!-alpha 1) (next :c-type "struct thread *" :length #!+alpha 2 #!-alpha 1) (state :c-type "lispobj") on x86 , the LDT index #!+(or x86 x86-64 sb-thread) (pseudo-atomic-bits) (interrupt-data :c-type "struct interrupt_data *" :length #!+alpha 2 #!-alpha 1) (stepping) #!+sb-thread (foreign-function-call-active :c-type "boolean") #!+(and sb-thread (not (or x86 x86-64))) (control-frame-pointer :c-type "lispobj *") print an approximation of the CSP as needed . #!+(and sb-thread) (control-stack-pointer :c-type "lispobj *") : On alpha , until STEPPING we have been lucky and the 32 #!+alpha (padding) (interrupt-contexts :c-type "os_context_t *" :rest-p t))
377beb20277ccc0d611f15dc4c712d405600152aadd58a37032afd6a584c1479
bendoerr/real-world-haskell
return1.hs
Avoiding type errors with the IO Monad using return . -- import Data.Char(toUpper) isGreen :: IO Bool isGreen = do putStrLn "Is green your favorite color?" inpStr <- getLine return ((toUpper . head $ inpStr) == 'Y') -------------- -- return2.hs -- pure function broken out -- isYes2 :: String -> Bool isYes2 s = (toUpper . head $ s) == 'Y' isGreen2 :: IO Bool isGreen2 = putStrLn "Is green your favorite color?" >> getLine >>= (\inS -> return (isYes2 inS)) ------------- -- return3.hs -- contrived example showing return doesn't need to be last -- returnTest3 :: IO () returnTest3 = do one <- return 1 let two = 2 putStrLn $ show (one + two)
null
https://raw.githubusercontent.com/bendoerr/real-world-haskell/fa43aa59e42a162f5d2d5655b274b964ebeb8f0a/ch07/return1.hs
haskell
------------ return2.hs pure function broken out ----------- return3.hs contrived example showing return doesn't need to be last
Avoiding type errors with the IO Monad using return . import Data.Char(toUpper) isGreen :: IO Bool isGreen = do putStrLn "Is green your favorite color?" inpStr <- getLine return ((toUpper . head $ inpStr) == 'Y') isYes2 :: String -> Bool isYes2 s = (toUpper . head $ s) == 'Y' isGreen2 :: IO Bool isGreen2 = putStrLn "Is green your favorite color?" >> getLine >>= (\inS -> return (isYes2 inS)) returnTest3 :: IO () returnTest3 = do one <- return 1 let two = 2 putStrLn $ show (one + two)
1952589d83aa5d32dc2b9ac139d43c823f75ab69686e02791d11b504133a679c
tsloughter/kuberl
kuberl_v1_stateful_set_spec.erl
-module(kuberl_v1_stateful_set_spec). -export([encode/1]). -export_type([kuberl_v1_stateful_set_spec/0]). -type kuberl_v1_stateful_set_spec() :: #{ 'podManagementPolicy' => binary(), 'replicas' => integer(), 'revisionHistoryLimit' => integer(), 'selector' := kuberl_v1_label_selector:kuberl_v1_label_selector(), 'serviceName' := binary(), 'template' := kuberl_v1_pod_template_spec:kuberl_v1_pod_template_spec(), 'updateStrategy' => kuberl_v1_stateful_set_update_strategy:kuberl_v1_stateful_set_update_strategy(), 'volumeClaimTemplates' => list() }. encode(#{ 'podManagementPolicy' := PodManagementPolicy, 'replicas' := Replicas, 'revisionHistoryLimit' := RevisionHistoryLimit, 'selector' := Selector, 'serviceName' := ServiceName, 'template' := Template, 'updateStrategy' := UpdateStrategy, 'volumeClaimTemplates' := VolumeClaimTemplates }) -> #{ 'podManagementPolicy' => PodManagementPolicy, 'replicas' => Replicas, 'revisionHistoryLimit' => RevisionHistoryLimit, 'selector' => Selector, 'serviceName' => ServiceName, 'template' => Template, 'updateStrategy' => UpdateStrategy, 'volumeClaimTemplates' => VolumeClaimTemplates }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_stateful_set_spec.erl
erlang
-module(kuberl_v1_stateful_set_spec). -export([encode/1]). -export_type([kuberl_v1_stateful_set_spec/0]). -type kuberl_v1_stateful_set_spec() :: #{ 'podManagementPolicy' => binary(), 'replicas' => integer(), 'revisionHistoryLimit' => integer(), 'selector' := kuberl_v1_label_selector:kuberl_v1_label_selector(), 'serviceName' := binary(), 'template' := kuberl_v1_pod_template_spec:kuberl_v1_pod_template_spec(), 'updateStrategy' => kuberl_v1_stateful_set_update_strategy:kuberl_v1_stateful_set_update_strategy(), 'volumeClaimTemplates' => list() }. encode(#{ 'podManagementPolicy' := PodManagementPolicy, 'replicas' := Replicas, 'revisionHistoryLimit' := RevisionHistoryLimit, 'selector' := Selector, 'serviceName' := ServiceName, 'template' := Template, 'updateStrategy' := UpdateStrategy, 'volumeClaimTemplates' := VolumeClaimTemplates }) -> #{ 'podManagementPolicy' => PodManagementPolicy, 'replicas' => Replicas, 'revisionHistoryLimit' => RevisionHistoryLimit, 'selector' => Selector, 'serviceName' => ServiceName, 'template' => Template, 'updateStrategy' => UpdateStrategy, 'volumeClaimTemplates' => VolumeClaimTemplates }.
49a00231c5db98385f3f5aa73be77427aa4a83bfd710efb514007ea0ac1ed13a
jarmitage/jarmlib
Sensel.hs
-- Sensel OSC input params :{ let sensel1x = cF 0 "sensel1x" sensel1y = cF 0 "sensel1y" sensel1z = cF 0 "sensel1z" :} :{ let sensel n a = cF 0 $ "sensel" ++ (show n) ++ a :} p1 $ s "bd" # gain (sensel 1 "x")
null
https://raw.githubusercontent.com/jarmitage/jarmlib/853f6d18ab32630397be91ea89846d55e59e3d70/tidal/osc/controllers/Sensel.hs
haskell
Sensel OSC input params
:{ let sensel1x = cF 0 "sensel1x" sensel1y = cF 0 "sensel1y" sensel1z = cF 0 "sensel1z" :} :{ let sensel n a = cF 0 $ "sensel" ++ (show n) ++ a :} p1 $ s "bd" # gain (sensel 1 "x")
c3bc1cc606c5a0c64ed40ae9348ba94ddb06649c5826477ddeac34d0d761bf56
mark-watson/haskell_tutorial_cookbook_examples
LetAndWhere.hs
module Main where funnySummation w x y z = let bob = w + x sally = y + z in bob + sally testLetComprehension = [(a,b) | a <- [0..5], let b = 10 * a] testWhereBlocks a = z * q where z = a + 2 q = 2 functionWithWhere n = (n + 1) * tenn where tenn = 10 * n main = do print $ funnySummation 1 2 3 4 let n = "Rigby" print n print testLetComprehension print $ testWhereBlocks 11 print $ functionWithWhere 1
null
https://raw.githubusercontent.com/mark-watson/haskell_tutorial_cookbook_examples/0f46465b67d245fa3853b4e320d79b7d7234e061/Pure/LetAndWhere.hs
haskell
module Main where funnySummation w x y z = let bob = w + x sally = y + z in bob + sally testLetComprehension = [(a,b) | a <- [0..5], let b = 10 * a] testWhereBlocks a = z * q where z = a + 2 q = 2 functionWithWhere n = (n + 1) * tenn where tenn = 10 * n main = do print $ funnySummation 1 2 3 4 let n = "Rigby" print n print testLetComprehension print $ testWhereBlocks 11 print $ functionWithWhere 1
4320d39ceedf6f34722383973b666ddd2e51fa1fb278409a24197dadf5b0975c
McCLIM/McCLIM
binseq2.lisp
;;; --------------------------------------------------------------------------- ;;; License: LGPL-2.1+ (See file 'Copyright' for details). ;;; --------------------------------------------------------------------------- ;;; ( c ) copyright 2005 < > ;;; ;;; --------------------------------------------------------------------------- ;;; Adaptation of binary sequences by ( real-world-phenomena.org ) ;;; Differs from binseq in: nodes contain two counts : number of lines and number of objects ;;; leafs contain obinseqs representing lines (in-package #:binseq) NOTE : should use a 3 - vector instead of the 3 - list ... (or (eq s 'empty) (and (consp s) (or (and (eq (car s) 'leaf) (obinseq-p (cdr s))) (and (eq (car s) 'node) (let ((nc (cadr s))) (and (consp nc) (integerp (car nc)) (integerp (cdr nc)))) (consp (cddr s)) (binseq2-p (caddr s)) (binseq2-p (cdddr s))))))) (defun list-binseq2* (l) ; l is a list of obinseqs (flet ((%split (l n) ; TODO: use side-effects to avoid consing (loop for b on l and i from 0 if (< i n) collect (car b) into a else do (return (values a b)) finally (return (values l nil))))) (cond ((null l) 'empty) ((null (cdr l)) `(leaf . ,(car l))) (t (let ((len (length l))) (multiple-value-bind (a b) (%split l (floor len 2)) (let* ((sa (list-binseq2* a)) (sb (list-binseq2* b)) (size (+ (binseq2-size sa) (binseq2-size sb)))) `(node . ((,len . ,size) . (,sa . ,sb)))))))))) (defun list-binseq2 (l) ; TODO: use side-effects to avoid consing (list-binseq2* (loop with curr = nil and ll = nil for e in l do (push e curr) (when (eql e #\Newline) (push (list-obinseq (nreverse curr)) ll) (setf curr nil)) finally (when curr (push (list-obinseq (nreverse curr)) ll)) (return (nreverse ll))))) (defun binseq2-list (s) (labels ((%to-list (s l) (cond ((eq s 'empty) l) ((eq (car s) 'leaf) (nconc (obinseq-list (cdr s)) l)) (t (%to-list (caddr s) (%to-list (cdddr s) l)))))) (%to-list s nil))) (defun vector-binseq2 (v) (list-binseq2* (loop with len = (length v) for start = 0 then end while (< start len) for end = (1+ (or (position #\Newline v :start start) (1- len))) collect (vector-obinseq v start end)))) (defun binseq2-vector (s) (let ((v (make-array (binseq2-size s)))) (labels ((%set2-v (s o) (cond ((eq s 'empty)) ((eq (car s) 'leaf) (%set-v (cdr s) o)) (t (let ((a (caddr s)) (b (cdddr s))) (%set2-v a o) (%set2-v b (+ o (binseq2-size a))))))) (%set-v (s o) (cond ((null s)) ((atom s) (setf (aref v o) s)) (t (let ((a (cadr s)) (b (cddr s))) (%set-v a o) (%set-v b (+ o (obinseq-length a)))))))) (%set2-v s 0)) v)) (defun binseq2-empty (s) (eq s 'empty)) (defun binseq2-length (s) (cond ((eq s 'empty) 0) ((eq (car s) 'leaf) 1) (t (caadr s)))) (defun binseq2-size (s) (cond ((eq s 'empty) 0) ((eq (car s) 'leaf) (obinseq-length (cdr s))) (t (cdadr s)))) (defun binseq2-cons (e s) (binseq2-append `(leaf . ,e) s)) (defun binseq2-snoc (e s) (binseq2-append s `(leaf . ,e))) (defun binseq2-possibly-append-end-lines (a b) "If the last line of A does not end with a newline, remove the first line of B and append it to the last line of A; otherwise, do nothing." (let ((a-last-line (cdr (binseq2-back a 1)))) (if (eql (obinseq-back a-last-line 1) #\Newline) (values a b) (values (binseq2-set a (1- (binseq2-length a)) (obinseq-append a-last-line (cdr (binseq2-front b 1)))) (binseq2-back b (1- (binseq2-length b))))))) ( defparameter * imbalance - bound * 3 ) ; must be > = 3 (defun binseq2-append (a b) (labels ((%not-much-longer (a b) (<= (binseq2-length a) (* *imbalance-bound* (binseq2-length b)))) (%much-shorter (a b) (not (%not-much-longer b a))) (%similar-in-length (a b) (and (%not-much-longer a b) (%not-much-longer b a))) (%cond-single (la lb lc) (and (<= lb (* *imbalance-bound* lc)) (<= (+ lb lc) (* *imbalance-bound* la)))) (%cond-double (la lb lc) (<= (+ la lb) (* (+ 1 *imbalance-bound*) lc))) (%cons (a b) (let ((len (+ (binseq2-length a) (binseq2-length b))) (size (+ (binseq2-size a) (binseq2-size b)))) (assert (>= len 2)) `(node . ((,len . ,size) . (,a . ,b))))) (%rotate-right (s1 s2) (cond ((and (consp s1) (eq (car s1) 'node)) (let* ((a (caddr s1)) (b (cdddr s1)) (la (binseq2-length a)) (lb (binseq2-length b)) (ls2 (binseq2-length s2))) (cond ((%cond-single la lb ls2) (%cons a (%cons b s2))) ((%cond-double la lb ls2) (let ((s11 (caddr b)) (s12 (cdddr b))) (%cons (%cons a s11) (%cons s12 s2)))) (t (%append a (%append b s2)))))) (t (%append a (%append b s2))))) (%rotate-left (s1 s2) (cond ((and (consp s2) (eq (car s2) 'node)) (let* ((a (cdddr s2)) (b (caddr s2)) (la (binseq2-length a)) (lb (binseq2-length b)) (ls1 (binseq2-length s1))) (cond ((%cond-single la lb ls1) (%cons (%cons s1 b) a)) ((%cond-double la lb ls1) (let ((s21 (cdddr b)) (s22 (caddr b))) (%cons (%cons s1 s22) (%cons s21 a)))) (t (%append (%append s1 b) a))))) (t (%append (%append s1 b) a)))) (%append (a b) (cond ((%similar-in-length a b) (%cons a b)) ((%much-shorter a b) (%rotate-left a b)) (t (%rotate-right a b))))) (cond ((eq a 'empty) b) ((eq b 'empty) a) (t (multiple-value-bind (a2 b2) (binseq2-possibly-append-end-lines a b) (cond ((eq a2 'empty) b2) ((eq b2 'empty) a2) (t (%append a2 b2)))))))) ;;; Functions whose names end with '2' are passed objects and object offsets ;;; and return binseq2s that are possibly accordingly truncated (defun binseq2-front (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-length s) i) s) ((<= i (binseq2-length (caddr s))) (binseq2-front (caddr s) i)) (t (binseq2-append (caddr s) (binseq2-front (cdddr s) (- i (binseq2-length (caddr s)))))))) (defun binseq2-offset (s i) (labels ((%offset (s i o) (cond ((or (eq s 'empty) (<= i 0) (eq (car s) 'leaf)) o) ((< i (binseq2-length (caddr s))) (%offset (caddr s) i o)) (t (%offset (cdddr s) (- i (binseq2-length (caddr s))) (+ o (binseq2-size (caddr s)))))))) (%offset s i 0))) (defun binseq2-front2 (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-size s) i) s) ((eq (car s) 'leaf) `(leaf . ,(obinseq-front (cdr s) i))) ((<= i (binseq2-size (caddr s))) (binseq2-front2 (caddr s) i)) (t (binseq2-append (caddr s) (binseq2-front2 (cdddr s) (- i (binseq2-size (caddr s)))))))) (defun binseq2-line2 (s i) (labels ((%line (s i o) (cond ((or (eq s 'empty) (<= i 0) (eq (car s) 'leaf)) o) ((< i (binseq2-size (caddr s))) (%line (caddr s) i o)) (t (%line (cdddr s) (- i (binseq2-size (caddr s))) (+ o (binseq2-length (caddr s)))))))) (%line s i 0))) (defun binseq2-back (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-length s) i) s) ((<= i (binseq2-length (cdddr s))) (binseq2-back (cdddr s) i)) (t (binseq2-append (binseq2-back (caddr s) (- i (binseq2-length (cdddr s)))) (cdddr s))))) (defun binseq2-back2 (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-size s) i) s) ((eq (car s) 'leaf) `(leaf . ,(obinseq-back (cdr s) i))) ((<= i (binseq2-size (cdddr s))) (binseq2-back2 (cdddr s) i)) (t (binseq2-append (binseq2-back2 (caddr s) (- i (binseq2-size (cdddr s)))) (cdddr s))))) (defun %has2-index (s i) (and (<= 0 i) (< i (binseq2-length s)))) (defun %has2-index2 (s i) (and (<= 0 i) (< i (binseq2-size s)))) (defun %has2-gap (s i) (and (<= 0 i) (<= i (binseq2-length s)))) (defun %has2-gap2 (s i) (and (<= 0 i) (<= i (binseq2-size s)))) (defun binseq2-get (s i) (assert (%has2-index s i) nil "Index out of bounds: ~S, ~S" s i) (cdr (binseq2-back (binseq2-front s (1+ i)) 1))) (defun binseq2-get2 (s i) (assert (%has2-index2 s i) nil "Index out of bounds: ~S, ~S" s i) (cdr (binseq2-back2 (binseq2-front2 s (1+ i)) 1))) (defun binseq2-set (s i e) (assert (%has2-index s i) nil "Index out of bounds: ~S, ~S" s i) (binseq2-append (binseq2-front s i) (binseq2-cons e (binseq2-back s (- (binseq2-length s) i 1))))) (defun binseq2-set2 (s i e) ; an object is also a leaf obinseq! (assert (%has2-index2 s i) nil "Index out of bounds: ~S, ~S" s i) (assert (and e (atom e))) (binseq2-append (binseq2-front2 s i) (binseq2-cons e (binseq2-back2 s (- (binseq2-size s) i 1))))) (defun binseq2-sub (s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-length s))) nil "Invalid subsequence bounds: ~S, ~S, ~S" s i n) (binseq2-back (binseq2-front s (+ i n)) n)) (defun binseq2-sub2 (s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-size s))) nil "Invalid subsequence bounds: ~S, ~S, ~S" s i n) (binseq2-back2 (binseq2-front2 s (+ i n)) n)) (defun binseq2-insert (s i e) (assert (%has2-gap s i) nil "Index out of bounds: ~S, ~S, ~S" s i e) (binseq2-append (binseq2-front s i) (binseq2-cons e (binseq2-back s (- (binseq2-length s) i))))) (defun binseq2-insert2 (s i e) ; an object is also a leaf obinseq! (assert (%has2-gap2 s i) nil "Index out of bounds: ~S, ~S, ~S" s i e) (assert (and e (atom e))) (binseq2-append (binseq2-front2 s i) (binseq2-cons e (binseq2-back2 s (- (binseq2-size s) i))))) (defun binseq2-insert* (s i s2) (assert (%has2-gap s i) nil "Index out of bounds: ~S, ~S, ~S" s i s2) (if (eq s2 'empty) s (binseq2-append (binseq2-front s i) (binseq2-append s2 (binseq2-back s (- (binseq2-length s) i)))))) (defun binseq2-insert*2 (s i s2) (assert (%has2-gap2 s i) nil "Index out of bounds: ~S, ~S, ~S" s i s2) (if (eq s2 'empty) s (binseq2-append (binseq2-front2 s i) (binseq2-append s2 (binseq2-back2 s (- (binseq2-size s) i)))))) (defun binseq2-remove (s i) (assert (%has2-index s i) nil "Index out of bounds: ~S, ~S" s i) (binseq2-append (binseq2-front s i) (binseq2-back s (- (binseq2-length s) i 1)))) (defun binseq2-remove2 (s i) (assert (%has2-index2 s i) nil "Index out of bounds: ~S, ~S" s i) (binseq2-append (binseq2-front2 s i) (binseq2-back2 s (- (binseq2-size s) i 1)))) (defun binseq2-remove* (s i n) (assert (%has2-index s i) nil "Start index out of bounds: ~S, ~S, ~S" s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-length s))) nil "Count out of range: ~S, ~S, ~S" s i n) (if (zerop n) s (binseq2-append (binseq2-front s i) (binseq2-back s (- (binseq2-length s) i n))))) (defun binseq2-remove*2 (s i n) (assert (%has2-index2 s i) nil "Start index out of bounds: ~S, ~S, ~S" s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-size s))) nil "Count out of range: ~S, ~S, ~S" s i n) (if (zerop n) s (binseq2-append (binseq2-front2 s i) (binseq2-back2 s (- (binseq2-size s) i n)))))
null
https://raw.githubusercontent.com/McCLIM/McCLIM/7c890f1ac79f0c6f36866c47af89398e2f05b343/Libraries/Drei/Persistent/binseq2.lisp
lisp
--------------------------------------------------------------------------- License: LGPL-2.1+ (See file 'Copyright' for details). --------------------------------------------------------------------------- --------------------------------------------------------------------------- Differs from binseq in: leafs contain obinseqs representing lines l is a list of obinseqs TODO: use side-effects to avoid consing TODO: use side-effects to avoid consing otherwise, do nothing." must be > = 3 Functions whose names end with '2' are passed objects and object offsets and return binseq2s that are possibly accordingly truncated an object is also a leaf obinseq! an object is also a leaf obinseq!
( c ) copyright 2005 < > Adaptation of binary sequences by ( real-world-phenomena.org ) nodes contain two counts : number of lines and number of objects (in-package #:binseq) NOTE : should use a 3 - vector instead of the 3 - list ... (or (eq s 'empty) (and (consp s) (or (and (eq (car s) 'leaf) (obinseq-p (cdr s))) (and (eq (car s) 'node) (let ((nc (cadr s))) (and (consp nc) (integerp (car nc)) (integerp (cdr nc)))) (consp (cddr s)) (binseq2-p (caddr s)) (binseq2-p (cdddr s))))))) (loop for b on l and i from 0 if (< i n) collect (car b) into a else do (return (values a b)) finally (return (values l nil))))) (cond ((null l) 'empty) ((null (cdr l)) `(leaf . ,(car l))) (t (let ((len (length l))) (multiple-value-bind (a b) (%split l (floor len 2)) (let* ((sa (list-binseq2* a)) (sb (list-binseq2* b)) (size (+ (binseq2-size sa) (binseq2-size sb)))) `(node . ((,len . ,size) . (,sa . ,sb)))))))))) (list-binseq2* (loop with curr = nil and ll = nil for e in l do (push e curr) (when (eql e #\Newline) (push (list-obinseq (nreverse curr)) ll) (setf curr nil)) finally (when curr (push (list-obinseq (nreverse curr)) ll)) (return (nreverse ll))))) (defun binseq2-list (s) (labels ((%to-list (s l) (cond ((eq s 'empty) l) ((eq (car s) 'leaf) (nconc (obinseq-list (cdr s)) l)) (t (%to-list (caddr s) (%to-list (cdddr s) l)))))) (%to-list s nil))) (defun vector-binseq2 (v) (list-binseq2* (loop with len = (length v) for start = 0 then end while (< start len) for end = (1+ (or (position #\Newline v :start start) (1- len))) collect (vector-obinseq v start end)))) (defun binseq2-vector (s) (let ((v (make-array (binseq2-size s)))) (labels ((%set2-v (s o) (cond ((eq s 'empty)) ((eq (car s) 'leaf) (%set-v (cdr s) o)) (t (let ((a (caddr s)) (b (cdddr s))) (%set2-v a o) (%set2-v b (+ o (binseq2-size a))))))) (%set-v (s o) (cond ((null s)) ((atom s) (setf (aref v o) s)) (t (let ((a (cadr s)) (b (cddr s))) (%set-v a o) (%set-v b (+ o (obinseq-length a)))))))) (%set2-v s 0)) v)) (defun binseq2-empty (s) (eq s 'empty)) (defun binseq2-length (s) (cond ((eq s 'empty) 0) ((eq (car s) 'leaf) 1) (t (caadr s)))) (defun binseq2-size (s) (cond ((eq s 'empty) 0) ((eq (car s) 'leaf) (obinseq-length (cdr s))) (t (cdadr s)))) (defun binseq2-cons (e s) (binseq2-append `(leaf . ,e) s)) (defun binseq2-snoc (e s) (binseq2-append s `(leaf . ,e))) (defun binseq2-possibly-append-end-lines (a b) "If the last line of A does not end with a newline, remove the first (let ((a-last-line (cdr (binseq2-back a 1)))) (if (eql (obinseq-back a-last-line 1) #\Newline) (values a b) (values (binseq2-set a (1- (binseq2-length a)) (obinseq-append a-last-line (cdr (binseq2-front b 1)))) (binseq2-back b (1- (binseq2-length b))))))) (defun binseq2-append (a b) (labels ((%not-much-longer (a b) (<= (binseq2-length a) (* *imbalance-bound* (binseq2-length b)))) (%much-shorter (a b) (not (%not-much-longer b a))) (%similar-in-length (a b) (and (%not-much-longer a b) (%not-much-longer b a))) (%cond-single (la lb lc) (and (<= lb (* *imbalance-bound* lc)) (<= (+ lb lc) (* *imbalance-bound* la)))) (%cond-double (la lb lc) (<= (+ la lb) (* (+ 1 *imbalance-bound*) lc))) (%cons (a b) (let ((len (+ (binseq2-length a) (binseq2-length b))) (size (+ (binseq2-size a) (binseq2-size b)))) (assert (>= len 2)) `(node . ((,len . ,size) . (,a . ,b))))) (%rotate-right (s1 s2) (cond ((and (consp s1) (eq (car s1) 'node)) (let* ((a (caddr s1)) (b (cdddr s1)) (la (binseq2-length a)) (lb (binseq2-length b)) (ls2 (binseq2-length s2))) (cond ((%cond-single la lb ls2) (%cons a (%cons b s2))) ((%cond-double la lb ls2) (let ((s11 (caddr b)) (s12 (cdddr b))) (%cons (%cons a s11) (%cons s12 s2)))) (t (%append a (%append b s2)))))) (t (%append a (%append b s2))))) (%rotate-left (s1 s2) (cond ((and (consp s2) (eq (car s2) 'node)) (let* ((a (cdddr s2)) (b (caddr s2)) (la (binseq2-length a)) (lb (binseq2-length b)) (ls1 (binseq2-length s1))) (cond ((%cond-single la lb ls1) (%cons (%cons s1 b) a)) ((%cond-double la lb ls1) (let ((s21 (cdddr b)) (s22 (caddr b))) (%cons (%cons s1 s22) (%cons s21 a)))) (t (%append (%append s1 b) a))))) (t (%append (%append s1 b) a)))) (%append (a b) (cond ((%similar-in-length a b) (%cons a b)) ((%much-shorter a b) (%rotate-left a b)) (t (%rotate-right a b))))) (cond ((eq a 'empty) b) ((eq b 'empty) a) (t (multiple-value-bind (a2 b2) (binseq2-possibly-append-end-lines a b) (cond ((eq a2 'empty) b2) ((eq b2 'empty) a2) (t (%append a2 b2)))))))) (defun binseq2-front (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-length s) i) s) ((<= i (binseq2-length (caddr s))) (binseq2-front (caddr s) i)) (t (binseq2-append (caddr s) (binseq2-front (cdddr s) (- i (binseq2-length (caddr s)))))))) (defun binseq2-offset (s i) (labels ((%offset (s i o) (cond ((or (eq s 'empty) (<= i 0) (eq (car s) 'leaf)) o) ((< i (binseq2-length (caddr s))) (%offset (caddr s) i o)) (t (%offset (cdddr s) (- i (binseq2-length (caddr s))) (+ o (binseq2-size (caddr s)))))))) (%offset s i 0))) (defun binseq2-front2 (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-size s) i) s) ((eq (car s) 'leaf) `(leaf . ,(obinseq-front (cdr s) i))) ((<= i (binseq2-size (caddr s))) (binseq2-front2 (caddr s) i)) (t (binseq2-append (caddr s) (binseq2-front2 (cdddr s) (- i (binseq2-size (caddr s)))))))) (defun binseq2-line2 (s i) (labels ((%line (s i o) (cond ((or (eq s 'empty) (<= i 0) (eq (car s) 'leaf)) o) ((< i (binseq2-size (caddr s))) (%line (caddr s) i o)) (t (%line (cdddr s) (- i (binseq2-size (caddr s))) (+ o (binseq2-length (caddr s)))))))) (%line s i 0))) (defun binseq2-back (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-length s) i) s) ((<= i (binseq2-length (cdddr s))) (binseq2-back (cdddr s) i)) (t (binseq2-append (binseq2-back (caddr s) (- i (binseq2-length (cdddr s)))) (cdddr s))))) (defun binseq2-back2 (s i) (cond ((<= i 0) 'empty) ((<= (binseq2-size s) i) s) ((eq (car s) 'leaf) `(leaf . ,(obinseq-back (cdr s) i))) ((<= i (binseq2-size (cdddr s))) (binseq2-back2 (cdddr s) i)) (t (binseq2-append (binseq2-back2 (caddr s) (- i (binseq2-size (cdddr s)))) (cdddr s))))) (defun %has2-index (s i) (and (<= 0 i) (< i (binseq2-length s)))) (defun %has2-index2 (s i) (and (<= 0 i) (< i (binseq2-size s)))) (defun %has2-gap (s i) (and (<= 0 i) (<= i (binseq2-length s)))) (defun %has2-gap2 (s i) (and (<= 0 i) (<= i (binseq2-size s)))) (defun binseq2-get (s i) (assert (%has2-index s i) nil "Index out of bounds: ~S, ~S" s i) (cdr (binseq2-back (binseq2-front s (1+ i)) 1))) (defun binseq2-get2 (s i) (assert (%has2-index2 s i) nil "Index out of bounds: ~S, ~S" s i) (cdr (binseq2-back2 (binseq2-front2 s (1+ i)) 1))) (defun binseq2-set (s i e) (assert (%has2-index s i) nil "Index out of bounds: ~S, ~S" s i) (binseq2-append (binseq2-front s i) (binseq2-cons e (binseq2-back s (- (binseq2-length s) i 1))))) (assert (%has2-index2 s i) nil "Index out of bounds: ~S, ~S" s i) (assert (and e (atom e))) (binseq2-append (binseq2-front2 s i) (binseq2-cons e (binseq2-back2 s (- (binseq2-size s) i 1))))) (defun binseq2-sub (s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-length s))) nil "Invalid subsequence bounds: ~S, ~S, ~S" s i n) (binseq2-back (binseq2-front s (+ i n)) n)) (defun binseq2-sub2 (s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-size s))) nil "Invalid subsequence bounds: ~S, ~S, ~S" s i n) (binseq2-back2 (binseq2-front2 s (+ i n)) n)) (defun binseq2-insert (s i e) (assert (%has2-gap s i) nil "Index out of bounds: ~S, ~S, ~S" s i e) (binseq2-append (binseq2-front s i) (binseq2-cons e (binseq2-back s (- (binseq2-length s) i))))) (assert (%has2-gap2 s i) nil "Index out of bounds: ~S, ~S, ~S" s i e) (assert (and e (atom e))) (binseq2-append (binseq2-front2 s i) (binseq2-cons e (binseq2-back2 s (- (binseq2-size s) i))))) (defun binseq2-insert* (s i s2) (assert (%has2-gap s i) nil "Index out of bounds: ~S, ~S, ~S" s i s2) (if (eq s2 'empty) s (binseq2-append (binseq2-front s i) (binseq2-append s2 (binseq2-back s (- (binseq2-length s) i)))))) (defun binseq2-insert*2 (s i s2) (assert (%has2-gap2 s i) nil "Index out of bounds: ~S, ~S, ~S" s i s2) (if (eq s2 'empty) s (binseq2-append (binseq2-front2 s i) (binseq2-append s2 (binseq2-back2 s (- (binseq2-size s) i)))))) (defun binseq2-remove (s i) (assert (%has2-index s i) nil "Index out of bounds: ~S, ~S" s i) (binseq2-append (binseq2-front s i) (binseq2-back s (- (binseq2-length s) i 1)))) (defun binseq2-remove2 (s i) (assert (%has2-index2 s i) nil "Index out of bounds: ~S, ~S" s i) (binseq2-append (binseq2-front2 s i) (binseq2-back2 s (- (binseq2-size s) i 1)))) (defun binseq2-remove* (s i n) (assert (%has2-index s i) nil "Start index out of bounds: ~S, ~S, ~S" s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-length s))) nil "Count out of range: ~S, ~S, ~S" s i n) (if (zerop n) s (binseq2-append (binseq2-front s i) (binseq2-back s (- (binseq2-length s) i n))))) (defun binseq2-remove*2 (s i n) (assert (%has2-index2 s i) nil "Start index out of bounds: ~S, ~S, ~S" s i n) (assert (and (>= n 0) (<= (+ i n) (binseq2-size s))) nil "Count out of range: ~S, ~S, ~S" s i n) (if (zerop n) s (binseq2-append (binseq2-front2 s i) (binseq2-back2 s (- (binseq2-size s) i n)))))
c804c5c3cbd3a096943a5d88436dad44e1a812cdf6d4d09a2f03a6ccf6e649a5
pmatiello/mockfn
core.cljc
(ns mockfn.core (:require [mockfn.macros :as macros] [mockfn.matchers :as matchers])) (def #^{:macro true} ^:deprecated providing #'macros/providing) (def #^{:macro true} ^:deprecated verifying #'macros/verifying) (def ^:deprecated exactly matchers/exactly) (def ^:deprecated at-least matchers/at-least) (def ^:deprecated at-most matchers/at-most) (def ^:deprecated any matchers/any) (def ^:deprecated a matchers/a)
null
https://raw.githubusercontent.com/pmatiello/mockfn/f8940ae354033bb600b788f7e0a9cf6abf2146da/src/mockfn/core.cljc
clojure
(ns mockfn.core (:require [mockfn.macros :as macros] [mockfn.matchers :as matchers])) (def #^{:macro true} ^:deprecated providing #'macros/providing) (def #^{:macro true} ^:deprecated verifying #'macros/verifying) (def ^:deprecated exactly matchers/exactly) (def ^:deprecated at-least matchers/at-least) (def ^:deprecated at-most matchers/at-most) (def ^:deprecated any matchers/any) (def ^:deprecated a matchers/a)
248636342965577683b5aa57cd856f9c6430919e586b7ce3da4af350c1f6ac24
DrakeAxelrod/functional-programming
BlackJack.hs
module BlackJack where import Cards import RunGame import System.Random import Test.QuickCheck implementation = Interface { iFullDeck = fullDeck, iValue = value, iDisplay = display, iGameOver = gameOver, iWinner = winner, iDraw = draw, iPlayBank = playBank, iShuffle = shuffleDeck } main :: IO () -- main = do quickCheck prop_size_shuffle quickCheck prop_shuffle_sameCards -- quickCheck prop_onTopOf_assoc quickCheck prop_size_onTopOf main = runGame implementation A0 ------------------------ size hand2 = size ( Add ( Card ( Numeric 2 ) Hearts ) ( Add ( Card Jack Spades ) Empty ) ) = ... = 2 size hand2 = size (Add (Card (Numeric 2) Hearts) (Add (Card Jack Spades) Empty)) = ... = 2 -} hand2 = Add (Card (Numeric 2) Hearts) (Add (Card Jack Spades) Empty) sizeSteps :: [Integer] sizeSteps = [ size hand2, size (Add (Card (Numeric 2) Hearts) (Add (Card Jack Spades) Empty)), size (Add (Card Jack Spades) Empty) + 1, 1 + 1, 2 ] -- A1 ------------------------ -- | Converts a rank to a short diplay representation displayRank :: Rank -> String displayRank (Numeric n) = show n displayRank Ace = "A" displayRank King = "K" displayRank Queen = "Q" displayRank Jack = "J" -- | Converts the suit of a card to a short unicode representation displaySuit :: Suit -> String displaySuit Hearts = "\9829" displaySuit Spades = "\9824" displaySuit Diamonds = "\9830" displaySuit Clubs = "\9827" -- | Display a card in short representation displayCard :: Card -> String displayCard (Card rank suit) = "[" ++ displayRank rank ++ displaySuit suit ++ "]" -- | Display of a hand of cards. display :: Hand -> String display Empty = "" display (Add card hand) = displayCard card ++ " " ++ display hand -- A2 ------------------------ -- | Converts a rank to a value valueRank :: Rank -> Integer valueRank (Numeric n) = n valueRank Ace = 11 valueRank _ = 10 -- | Calculates the Number of Aces in a hand numberOfAces :: Hand -> Integer numberOfAces Empty = 0 numberOfAces (Add (Card Ace _) hand) = 1 + numberOfAces hand numberOfAces (Add _ hand) = numberOfAces hand -- | Calculates the value of a hand not taking into account the number of Aces initialValue :: Hand -> Integer initialValue Empty = 0 initialValue (Add (Card rank _) hand) = valueRank rank + initialValue hand | Lower the value of aces in the hand until the value is less than 21 lowerAces :: Hand -> Integer -> Integer lowerAces hand value | value > 21 && numberOfAces hand > 0 = lowerAces hand (value - 10) | otherwise = value -- | Takes a hand and returns the value of the hand value :: Hand -> Integer value hand = lowerAces hand (initialValue hand) -- A3 ------------------------ -- | Check if the hand is a bust gameOver :: Hand -> Bool gameOver hand = value hand > 21 -- | Check if the hand is a winner -- A4 ------------------------ | Given two hands , returns the winner winner :: Hand -> Hand -> Player winner guest bank | gameOver guest = Bank | gameOver bank = Guest | value guest > value bank = Guest | value guest < value bank = Bank | otherwise = Bank -- B1 ------------------------ | Given two hands , < + puts the first one on top of the second one (<+) :: Hand -> Hand -> Hand (<+) Empty hand = hand (<+) (Add card hand) hand2 = Add card (hand <+ hand2) | < + must satisfy the following laws using QuickCheck prop_onTopOf_assoc :: Hand -> Hand -> Hand -> Bool prop_onTopOf_assoc p1 p2 p3 = p1<+(p2<+p3) == (p1<+p2)<+p3 | < + must satisfy the following laws using QuickCheck prop_size_onTopOf :: Hand -> Hand -> Bool prop_size_onTopOf p1 p2 = size p1 + size p2 == size (p1<+p2) -- B2 ------------------------ -- | Returns a fullSuit of cards fullSuit :: Suit -> Hand fullSuit suit = foldr Add Empty [Card rank suit | rank <- [Numeric n | n <- [2..10]] ++ [Jack, Queen, King, Ace]] -- | Returns FullDeck of cards fullDeck :: Hand fullDeck = foldr (<+) Empty [fullSuit suit | suit <- [Hearts, Spades, Diamonds, Clubs]] -- B3 ------------------------ Given a deck and a hand , draw one card from the deck and put on the hand . Return both the deck and the hand ( in that order ) . Given a deck and a hand, draw one card from the deck and put on the hand. Return both the deck and the hand (in that order). -} removeCard :: Hand -> (Card, Hand) removeCard Empty = error "empty deck" removeCard (Add card hand) = (card, hand) draw :: Hand -> Hand -> (Hand, Hand) draw Empty hand = error "draw: The deck is empty." draw deck hand = (deck', hand') where (card, deck') = removeCard deck hand' = Add card hand -- B4 ------------------------ playBankHelper :: Hand -> Hand -> Hand playBankHelper deck hand | value hand >= 16 = hand | otherwise = playBankHelper deck' hand' where (deck', hand') = draw deck hand -- | Given a deck, play for the bank (starting with an empty hand), and return the bank’s final hand: playBank :: Hand -> Hand playBank deck = playBankHelper deck Empty -- B5 ------------------------ -- c `belongsTo` Empty = False -- c `belongsTo` (Add c' h) = c == c' || c `belongsTo` h belongsTo :: Card -> Hand -> Bool belongsTo _ Empty = False belongsTo card (Add card' hand) | card == card' = True | otherwise = card `belongsTo` hand removeCardAt :: Hand -> Int -> (Card, Hand) removeCardAt Empty _ = error "empty deck" removeCardAt (Add card hand) 0 = (card, hand) removeCardAt (Add card hand) n = (card', Add card hand') where (card', hand') = removeCardAt hand (n-1) | Given a StdGen and a hand of cards , shuffle the cards and return the shuffled hand shuffleDeck :: StdGen -> Hand -> Hand shuffleDeck _ Empty = Empty shuffleDeck gen deck = do -- take a random card from the deck and add it to the shuffled deck -- repeat until the deck is empty let (n, gen') = randomR (0, size deck - 1) gen let (card, deck') = removeCardAt deck n Add card (shuffleDeck gen' deck') prop_shuffle_sameCards :: StdGen -> Card -> Hand -> Bool prop_shuffle_sameCards g c h = c `belongsTo` h == c `belongsTo` shuffleDeck g h prop_size_shuffle :: StdGen -> Hand -> Bool prop_size_shuffle g h = size h == size (shuffleDeck g h)
null
https://raw.githubusercontent.com/DrakeAxelrod/functional-programming/9888822f0824c9568026a61da6beaeeecced518c/lab2/BlackJack.hs
haskell
main = do quickCheck prop_onTopOf_assoc ---------------------- A1 ------------------------ | Converts a rank to a short diplay representation | Converts the suit of a card to a short unicode representation | Display a card in short representation | Display of a hand of cards. A2 ------------------------ | Converts a rank to a value | Calculates the Number of Aces in a hand | Calculates the value of a hand not taking into account the number of Aces | Takes a hand and returns the value of the hand A3 ------------------------ | Check if the hand is a bust | Check if the hand is a winner A4 ------------------------ B1 ------------------------ B2 ------------------------ | Returns a fullSuit of cards | Returns FullDeck of cards B3 ------------------------ B4 ------------------------ | Given a deck, play for the bank (starting with an empty hand), and return the bank’s final hand: B5 ------------------------ c `belongsTo` Empty = False c `belongsTo` (Add c' h) = c == c' || c `belongsTo` h take a random card from the deck and add it to the shuffled deck repeat until the deck is empty
module BlackJack where import Cards import RunGame import System.Random import Test.QuickCheck implementation = Interface { iFullDeck = fullDeck, iValue = value, iDisplay = display, iGameOver = gameOver, iWinner = winner, iDraw = draw, iPlayBank = playBank, iShuffle = shuffleDeck } main :: IO () quickCheck prop_size_shuffle quickCheck prop_shuffle_sameCards quickCheck prop_size_onTopOf main = runGame implementation size hand2 = size ( Add ( Card ( Numeric 2 ) Hearts ) ( Add ( Card Jack Spades ) Empty ) ) = ... = 2 size hand2 = size (Add (Card (Numeric 2) Hearts) (Add (Card Jack Spades) Empty)) = ... = 2 -} hand2 = Add (Card (Numeric 2) Hearts) (Add (Card Jack Spades) Empty) sizeSteps :: [Integer] sizeSteps = [ size hand2, size (Add (Card (Numeric 2) Hearts) (Add (Card Jack Spades) Empty)), size (Add (Card Jack Spades) Empty) + 1, 1 + 1, 2 ] displayRank :: Rank -> String displayRank (Numeric n) = show n displayRank Ace = "A" displayRank King = "K" displayRank Queen = "Q" displayRank Jack = "J" displaySuit :: Suit -> String displaySuit Hearts = "\9829" displaySuit Spades = "\9824" displaySuit Diamonds = "\9830" displaySuit Clubs = "\9827" displayCard :: Card -> String displayCard (Card rank suit) = "[" ++ displayRank rank ++ displaySuit suit ++ "]" display :: Hand -> String display Empty = "" display (Add card hand) = displayCard card ++ " " ++ display hand valueRank :: Rank -> Integer valueRank (Numeric n) = n valueRank Ace = 11 valueRank _ = 10 numberOfAces :: Hand -> Integer numberOfAces Empty = 0 numberOfAces (Add (Card Ace _) hand) = 1 + numberOfAces hand numberOfAces (Add _ hand) = numberOfAces hand initialValue :: Hand -> Integer initialValue Empty = 0 initialValue (Add (Card rank _) hand) = valueRank rank + initialValue hand | Lower the value of aces in the hand until the value is less than 21 lowerAces :: Hand -> Integer -> Integer lowerAces hand value | value > 21 && numberOfAces hand > 0 = lowerAces hand (value - 10) | otherwise = value value :: Hand -> Integer value hand = lowerAces hand (initialValue hand) gameOver :: Hand -> Bool gameOver hand = value hand > 21 | Given two hands , returns the winner winner :: Hand -> Hand -> Player winner guest bank | gameOver guest = Bank | gameOver bank = Guest | value guest > value bank = Guest | value guest < value bank = Bank | otherwise = Bank | Given two hands , < + puts the first one on top of the second one (<+) :: Hand -> Hand -> Hand (<+) Empty hand = hand (<+) (Add card hand) hand2 = Add card (hand <+ hand2) | < + must satisfy the following laws using QuickCheck prop_onTopOf_assoc :: Hand -> Hand -> Hand -> Bool prop_onTopOf_assoc p1 p2 p3 = p1<+(p2<+p3) == (p1<+p2)<+p3 | < + must satisfy the following laws using QuickCheck prop_size_onTopOf :: Hand -> Hand -> Bool prop_size_onTopOf p1 p2 = size p1 + size p2 == size (p1<+p2) fullSuit :: Suit -> Hand fullSuit suit = foldr Add Empty [Card rank suit | rank <- [Numeric n | n <- [2..10]] ++ [Jack, Queen, King, Ace]] fullDeck :: Hand fullDeck = foldr (<+) Empty [fullSuit suit | suit <- [Hearts, Spades, Diamonds, Clubs]] Given a deck and a hand , draw one card from the deck and put on the hand . Return both the deck and the hand ( in that order ) . Given a deck and a hand, draw one card from the deck and put on the hand. Return both the deck and the hand (in that order). -} removeCard :: Hand -> (Card, Hand) removeCard Empty = error "empty deck" removeCard (Add card hand) = (card, hand) draw :: Hand -> Hand -> (Hand, Hand) draw Empty hand = error "draw: The deck is empty." draw deck hand = (deck', hand') where (card, deck') = removeCard deck hand' = Add card hand playBankHelper :: Hand -> Hand -> Hand playBankHelper deck hand | value hand >= 16 = hand | otherwise = playBankHelper deck' hand' where (deck', hand') = draw deck hand playBank :: Hand -> Hand playBank deck = playBankHelper deck Empty belongsTo :: Card -> Hand -> Bool belongsTo _ Empty = False belongsTo card (Add card' hand) | card == card' = True | otherwise = card `belongsTo` hand removeCardAt :: Hand -> Int -> (Card, Hand) removeCardAt Empty _ = error "empty deck" removeCardAt (Add card hand) 0 = (card, hand) removeCardAt (Add card hand) n = (card', Add card hand') where (card', hand') = removeCardAt hand (n-1) | Given a StdGen and a hand of cards , shuffle the cards and return the shuffled hand shuffleDeck :: StdGen -> Hand -> Hand shuffleDeck _ Empty = Empty shuffleDeck gen deck = do let (n, gen') = randomR (0, size deck - 1) gen let (card, deck') = removeCardAt deck n Add card (shuffleDeck gen' deck') prop_shuffle_sameCards :: StdGen -> Card -> Hand -> Bool prop_shuffle_sameCards g c h = c `belongsTo` h == c `belongsTo` shuffleDeck g h prop_size_shuffle :: StdGen -> Hand -> Bool prop_size_shuffle g h = size h == size (shuffleDeck g h)
686a80adf31d74a03bfa3882b446dc4528807a07195b10c9b1c889b38d835e04
LuxLang/lux
record.clj
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 /. (ns lux.analyser.record (:require clojure.core.match clojure.core.match.array (lux [base :as & :refer [|let |do return |case]] [type :as &type]) (lux.analyser [base :as &&] [module :as &&module]))) (defn ^:private record_slot [slot0] (|do [[module name] (&&/resolved-ident slot0) exported?&label (fn [lux] (|case ((&&module/find-slot module name) lux) (&/$Left error) (&/$Right (&/T [lux &/$None])) (&/$Right [lux* output]) (&/$Right (&/T [lux* (&/$Some output)]))))] (return (|case exported?&label (&/$Some [exported? [label* type]]) (&/$Some (&/T [label* type])) (&/$None) &/$None)))) (defn ^:private slot_type "(-> [Label Code] Type)" [it] (|let [[[label* type] value] it] type)) (defn ^:private same_record? "(-> (List [Label Code]) Bit)" [it] (|case it (&/$Item head tail) (|let [expected (slot_type head)] (&/|every? (fn [it] (->> it slot_type (&type/type= expected))) tail)) (&/$End) false)) (defn ^:private complete_record? "(-> (List [Label Code]) Bit)" [it] (loop [expected_lefts 0 remaining it] (|case remaining (&/$Item [[label* type] value] (&/$End)) (|case label* (&/$Some [lefts true family]) (= (dec expected_lefts) lefts) (&/$None) (= 0 expected_lefts)) (&/$Item [[(&/$Some [lefts false family]) type] value] tail) (and (= expected_lefts lefts) (recur (inc expected_lefts) tail)) _ false))) ;; [Exports] (defn order-record "(-> (List Syntax) (Lux (Maybe (List Syntax))))" [pattern_matching? pairs] (let [arity (&/|length pairs)] (cond (= 0 arity) (return &/$None) (even? arity) (let [pairs (&/|as-pairs pairs)] (|do [resolved_slots* (&/map% (fn [pair] (|case pair [[_ (&/$Identifier slot0)] value] (|case slot0 ["" short0] (if pattern_matching? (return &/$None) (|do [local? (&&module/find_local short0)] (|case local? (&/$None) (|do [slot (record_slot slot0)] (return (|case slot (&/$Some slot*) (&/$Some (&/T [slot* value])) (&/$None) &/$None))) (&/$Some [local _inner _outer]) (return &/$None)))) [module0 short0] (|do [slot (record_slot slot0)] (return (|case slot (&/$Some slot*) (&/$Some (&/T [slot* value])) (&/$None) &/$None)))) _ (return &/$None))) pairs)] (|case (&/all_maybe resolved_slots*) (&/$Some resolved_slots) (|do [:let [sorted_slots (->> resolved_slots &/->seq (sort (fn [left right] (|let [[[(&/$Some [leftsL right?L familyL]) typeL] valueL] left [[(&/$Some [leftsR right?R familyR]) typeR] valueR] right] (if (= leftsL leftsR) (not right?L) (< leftsL leftsR))))) &/->list)] _ (&/assert! (same_record? sorted_slots) "[Analyser Error] Slots correspond to different record types.") _ (&/assert! (complete_record? sorted_slots) "[Analyser Error] Missing record slots.")] (return (&/$Some (&/T [(&/|map &/|second sorted_slots) (slot_type (&/|head sorted_slots))])))) (&/$None) (return &/$None)))) true (return &/$None))))
null
https://raw.githubusercontent.com/LuxLang/lux/91bc060bc498a0d2418198cfcb9dc39636d1d867/lux-bootstrapper/src/lux/analyser/record.clj
clojure
[Exports]
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 /. (ns lux.analyser.record (:require clojure.core.match clojure.core.match.array (lux [base :as & :refer [|let |do return |case]] [type :as &type]) (lux.analyser [base :as &&] [module :as &&module]))) (defn ^:private record_slot [slot0] (|do [[module name] (&&/resolved-ident slot0) exported?&label (fn [lux] (|case ((&&module/find-slot module name) lux) (&/$Left error) (&/$Right (&/T [lux &/$None])) (&/$Right [lux* output]) (&/$Right (&/T [lux* (&/$Some output)]))))] (return (|case exported?&label (&/$Some [exported? [label* type]]) (&/$Some (&/T [label* type])) (&/$None) &/$None)))) (defn ^:private slot_type "(-> [Label Code] Type)" [it] (|let [[[label* type] value] it] type)) (defn ^:private same_record? "(-> (List [Label Code]) Bit)" [it] (|case it (&/$Item head tail) (|let [expected (slot_type head)] (&/|every? (fn [it] (->> it slot_type (&type/type= expected))) tail)) (&/$End) false)) (defn ^:private complete_record? "(-> (List [Label Code]) Bit)" [it] (loop [expected_lefts 0 remaining it] (|case remaining (&/$Item [[label* type] value] (&/$End)) (|case label* (&/$Some [lefts true family]) (= (dec expected_lefts) lefts) (&/$None) (= 0 expected_lefts)) (&/$Item [[(&/$Some [lefts false family]) type] value] tail) (and (= expected_lefts lefts) (recur (inc expected_lefts) tail)) _ false))) (defn order-record "(-> (List Syntax) (Lux (Maybe (List Syntax))))" [pattern_matching? pairs] (let [arity (&/|length pairs)] (cond (= 0 arity) (return &/$None) (even? arity) (let [pairs (&/|as-pairs pairs)] (|do [resolved_slots* (&/map% (fn [pair] (|case pair [[_ (&/$Identifier slot0)] value] (|case slot0 ["" short0] (if pattern_matching? (return &/$None) (|do [local? (&&module/find_local short0)] (|case local? (&/$None) (|do [slot (record_slot slot0)] (return (|case slot (&/$Some slot*) (&/$Some (&/T [slot* value])) (&/$None) &/$None))) (&/$Some [local _inner _outer]) (return &/$None)))) [module0 short0] (|do [slot (record_slot slot0)] (return (|case slot (&/$Some slot*) (&/$Some (&/T [slot* value])) (&/$None) &/$None)))) _ (return &/$None))) pairs)] (|case (&/all_maybe resolved_slots*) (&/$Some resolved_slots) (|do [:let [sorted_slots (->> resolved_slots &/->seq (sort (fn [left right] (|let [[[(&/$Some [leftsL right?L familyL]) typeL] valueL] left [[(&/$Some [leftsR right?R familyR]) typeR] valueR] right] (if (= leftsL leftsR) (not right?L) (< leftsL leftsR))))) &/->list)] _ (&/assert! (same_record? sorted_slots) "[Analyser Error] Slots correspond to different record types.") _ (&/assert! (complete_record? sorted_slots) "[Analyser Error] Missing record slots.")] (return (&/$Some (&/T [(&/|map &/|second sorted_slots) (slot_type (&/|head sorted_slots))])))) (&/$None) (return &/$None)))) true (return &/$None))))
9590de1e3c81643be9fbfccd586ef5a723cbed917b3a81dad757da767ae1eabb
tezos-commons/baseDAO
Vote.hs
SPDX - FileCopyrightText : 2021 Tezos Commons SPDX - License - Identifier : LicenseRef - MIT - TC # LANGUAGE ApplicativeDo # | Contains test on @vote@ entrypoint for the LIGO contract . module Test.Ligo.BaseDAO.Proposal.Vote ( proposalCorrectlyTrackVotes , voteNonExistingProposal , voteDeletedProposal , voteMultiProposals , voteOutdatedProposal , voteValidProposal , voteWithPermit , voteWithPermitNonce ) where import Universum import Lorentz hiding (assert, (>>)) import Morley.Util.Named import Test.Cleveland import Ligo.BaseDAO.ErrorCodes import Ligo.BaseDAO.Types import Test.Ligo.BaseDAO.Common import Test.Ligo.BaseDAO.Proposal.Config # ANN module ( " HLint : ignore Reduce duplication " : : Text ) # voteNonExistingProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteNonExistingProposal originateFn = do DaoOriginateData{..} <- originateFn testConfig defaultQuorumThreshold startLevel <- getOriginationLevel dodDao withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 2) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) Advance three voting periods to a proposing stage . advanceToLevel (startLevel + 3*dodPeriod) -- Create sample proposal _ <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = UnsafeHash "\11\12\13" , vFrom = toAddress dodOwner2 } -- Advance one voting period to a voting stage. advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner2 $ (transfer dodDao $ calling (ep @"Vote") [params]) & expectFailedWith proposalNotExist voteMultiProposals :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteMultiProposals originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold startLevel <- getOriginationLevel dodDao withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 20) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 5) -- Advance one voting period to a proposing stage. advanceToLevel (startLevel + 3*dodPeriod) -- Create sample proposal (key1, key2) <- createSampleProposals (1, 2) dodOwner1 dodDao let params = fmap NoPermit [ VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } , VoteParam { vVoteType = False , vVoteAmount = 3 , vProposalKey = key2 , vFrom = toAddress dodOwner2 } ] -- Advance one voting period to a voting stage. advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Vote") params checkBalance dodDao dodOwner2 5 getProposal dodDao key1 >>= \case Just proposal -> assert ((plUpvotes proposal) == 2) "Proposal had unexpected votes" Nothing -> error "Did not find proposal" getProposal dodDao key2 >>= \case Just proposal -> assert ((plDownvotes proposal) == 3) "Proposal had unexpected votes" Nothing -> error "Did not find proposal" proposalCorrectlyTrackVotes :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () proposalCorrectlyTrackVotes originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold originationLevel <- getOriginationLevel dodDao let proposer = dodOwner1 let voter1 = dodOwner2 let voter2 = dodOperator1 withSender proposer $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 20) withSender voter1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 40) withSender voter2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 40) -- Advance one voting period to a proposing stage. advanceToLevel (originationLevel + dodPeriod) -- Create sample proposal (key1, key2) <- createSampleProposals (1, 2) dodOwner1 dodDao let params1 = fmap NoPermit [ VoteParam { vVoteType = True , vVoteAmount = 5 , vProposalKey = key1 , vFrom = toAddress voter1 } , VoteParam { vVoteType = False , vVoteAmount = 3 , vProposalKey = key2 , vFrom = toAddress voter1 } ] let params2 = fmap NoPermit [ VoteParam { vVoteType = False , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress voter2 } , VoteParam { vVoteType = True , vVoteAmount = 4 , vProposalKey = key2 , vFrom = toAddress voter2 } ] let params3 = fmap NoPermit [ VoteParam { vVoteType = True , vVoteAmount = 3 , vProposalKey = key1 , vFrom = toAddress voter1 } , VoteParam { vVoteType = True , vVoteAmount = 3 , vProposalKey = key2 , vFrom = toAddress voter1 } ] -- Advance one voting period to a voting stage. advanceToLevel (originationLevel + 2*dodPeriod) withSender voter1 . inBatch $ do transfer dodDao $ calling (ep @"Vote") params1 transfer dodDao $ calling (ep @"Vote") params3 pure () withSender voter2 do transfer dodDao $ calling (ep @"Vote") params2 proposal1 <- fromMaybe (error "proposal not found") <$> getProposal dodDao key1 proposal2 <- fromMaybe (error "proposal not found") <$> getProposal dodDao key2 assert (plUpvotes proposal1 == 8) "proposal did not track upvotes correctly" assert (plDownvotes proposal1 == 2) "proposal did not track downvotes correctly" assert (plUpvotes proposal2 == 7) "proposal did not track upvotes correctly" assert (plDownvotes proposal2 == 3) "proposal did not track downvotes correctly" voter1key1 <- getVoter dodDao (voter1, key1) voter1key2 <- getVoter dodDao (voter1, key2) voter2key1 <- getVoter dodDao (voter2, key1) voter2key2 <- getVoter dodDao (voter2, key2) 8 upvotes , 0 downvotes 3 upvotes , 3 downvotes 0 upvotes , 2 downvotes 4 upvotes , 0 downvotes voteOutdatedProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteOutdatedProposal originateFn = do let configDesc = ConfigDesc configConsts { cmPeriod = Just 40, cmQuorumThreshold = Just (mkQuorumThreshold 1 100) } DaoOriginateData{..} <- originateFn configDesc defaultQuorumThreshold withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 4) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) startLevel <- getOriginationLevel dodDao -- Advance one voting period to a proposing stage. advanceToLevel (startLevel + dodPeriod) -- Create sample proposal key1 <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } -- Advance one voting period to a voting stage. advanceToLevel (startLevel + 2*dodPeriod) withSender dodOwner2 $ do transfer dodDao $ calling (ep @"Vote") [params] Advance two voting period to another voting stage . advanceToLevel (startLevel + 4*dodPeriod) (transfer dodDao $ calling (ep @"Vote") [params]) & expectFailedWith votingStageOver voteValidProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteValidProposal originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 2) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) startLevel <- getOriginationLevel dodDao -- Advance three voting period to a proposing stage. We skip three , instead of just one , because the freeze operations might extend into the next period , when tests are run on real network . -- makeing it unable to use those frozen tokens in the same period. advanceToLevel (startLevel + 3*dodPeriod) Create sample proposal ( first proposal has i d = 0 ) key1 <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } -- Advance one voting period to a voting stage. advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Vote") [params] checkBalance dodDao dodOwner2 2 getProposal dodDao key1 >>= \case Just proposal -> assert ((plUpvotes proposal) == 2) "Proposal had unexpected votes" Nothing -> error "Did not find proposal" -- voteDeletedProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteDeletedProposal originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold startLevel <- getOriginationLevel dodDao withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 2) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) -- Advance three voting period to a proposing stage. advanceToLevel (startLevel + 3*dodPeriod) Create sample proposal ( first proposal has i d = 0 ) key1 <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } -- Advance one voting period to a voting stage. advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Drop_proposal") key1 withSender dodOwner2 $ (transfer dodDao $ calling (ep @"Vote") [params]) & expectFailedWith proposalNotExist voteWithPermit :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteWithPermit originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 12) -- Advance one voting period to a proposing stage. startLevel <- getOriginationLevel dodDao advanceToLevel (startLevel + dodPeriod) -- Create sample proposal key1 <- createSampleProposal 1 dodOwner1 dodDao params <- permitProtect dodOwner1 =<< addDataToSign dodDao (Nonce 0) VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner1 } -- Advance one voting period to a voting stage. advanceToLevel (startLevel + 2*dodPeriod) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Vote") [params] checkBalance dodDao dodOwner1 12 voteWithPermitNonce :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteWithPermitNonce originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold originationLevel <- getOriginationLevel dodDao withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 60) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 50) -- Advance one voting period to a proposing stage. advanceToLevel (originationLevel + dodPeriod) -- Create sample proposal key1 <- createSampleProposal 1 dodOwner1 dodDao let voteParam = VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner1 } -- Advance one voting period to a voting stage. advanceToLevel (originationLevel + 2*dodPeriod) -- Going to try calls with different nonces signed1@(_ , _) <- addDataToSign dodDao (Nonce 0) voteParam signed2@(dataToSign2, _) <- addDataToSign dodDao (Nonce 1) voteParam signed3@(_ , _) <- addDataToSign dodDao (Nonce 2) voteParam params1 <- permitProtect dodOwner1 signed1 params2 <- permitProtect dodOwner1 signed2 params3 <- permitProtect dodOwner1 signed3 withSender dodOwner2 $ do -- Good nonce transfer dodDao $ calling (ep @"Vote") [params1] -- Outdated nonce (transfer dodDao $ calling (ep @"Vote") [params1]) & expectFailedWith (missigned, (lPackValue dataToSign2)) -- Nonce from future (transfer dodDao $ calling (ep @"Vote") [params3]) & expectFailedWith (missigned, (lPackValue dataToSign2)) -- Good nonce after the previous successful entrypoint call transfer dodDao $ calling (ep @"Vote") [params2] -- Check counter (Nonce counter) <- getVotePermitsCounter dodDao counter @== 2
null
https://raw.githubusercontent.com/tezos-commons/baseDAO/c8cc03362b64e8f27432ec70cdb4c0df82abff35/haskell/test/Test/Ligo/BaseDAO/Proposal/Vote.hs
haskell
Create sample proposal Advance one voting period to a voting stage. Advance one voting period to a proposing stage. Create sample proposal Advance one voting period to a voting stage. Advance one voting period to a proposing stage. Create sample proposal Advance one voting period to a voting stage. Advance one voting period to a proposing stage. Create sample proposal Advance one voting period to a voting stage. Advance three voting period to a proposing stage. makeing it unable to use those frozen tokens in the same period. Advance one voting period to a voting stage. Advance three voting period to a proposing stage. Advance one voting period to a voting stage. Advance one voting period to a proposing stage. Create sample proposal Advance one voting period to a voting stage. Advance one voting period to a proposing stage. Create sample proposal Advance one voting period to a voting stage. Going to try calls with different nonces Good nonce Outdated nonce Nonce from future Good nonce after the previous successful entrypoint call Check counter
SPDX - FileCopyrightText : 2021 Tezos Commons SPDX - License - Identifier : LicenseRef - MIT - TC # LANGUAGE ApplicativeDo # | Contains test on @vote@ entrypoint for the LIGO contract . module Test.Ligo.BaseDAO.Proposal.Vote ( proposalCorrectlyTrackVotes , voteNonExistingProposal , voteDeletedProposal , voteMultiProposals , voteOutdatedProposal , voteValidProposal , voteWithPermit , voteWithPermitNonce ) where import Universum import Lorentz hiding (assert, (>>)) import Morley.Util.Named import Test.Cleveland import Ligo.BaseDAO.ErrorCodes import Ligo.BaseDAO.Types import Test.Ligo.BaseDAO.Common import Test.Ligo.BaseDAO.Proposal.Config # ANN module ( " HLint : ignore Reduce duplication " : : Text ) # voteNonExistingProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteNonExistingProposal originateFn = do DaoOriginateData{..} <- originateFn testConfig defaultQuorumThreshold startLevel <- getOriginationLevel dodDao withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 2) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) Advance three voting periods to a proposing stage . advanceToLevel (startLevel + 3*dodPeriod) _ <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = UnsafeHash "\11\12\13" , vFrom = toAddress dodOwner2 } advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner2 $ (transfer dodDao $ calling (ep @"Vote") [params]) & expectFailedWith proposalNotExist voteMultiProposals :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteMultiProposals originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold startLevel <- getOriginationLevel dodDao withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 20) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 5) advanceToLevel (startLevel + 3*dodPeriod) (key1, key2) <- createSampleProposals (1, 2) dodOwner1 dodDao let params = fmap NoPermit [ VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } , VoteParam { vVoteType = False , vVoteAmount = 3 , vProposalKey = key2 , vFrom = toAddress dodOwner2 } ] advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Vote") params checkBalance dodDao dodOwner2 5 getProposal dodDao key1 >>= \case Just proposal -> assert ((plUpvotes proposal) == 2) "Proposal had unexpected votes" Nothing -> error "Did not find proposal" getProposal dodDao key2 >>= \case Just proposal -> assert ((plDownvotes proposal) == 3) "Proposal had unexpected votes" Nothing -> error "Did not find proposal" proposalCorrectlyTrackVotes :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () proposalCorrectlyTrackVotes originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold originationLevel <- getOriginationLevel dodDao let proposer = dodOwner1 let voter1 = dodOwner2 let voter2 = dodOperator1 withSender proposer $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 20) withSender voter1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 40) withSender voter2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 40) advanceToLevel (originationLevel + dodPeriod) (key1, key2) <- createSampleProposals (1, 2) dodOwner1 dodDao let params1 = fmap NoPermit [ VoteParam { vVoteType = True , vVoteAmount = 5 , vProposalKey = key1 , vFrom = toAddress voter1 } , VoteParam { vVoteType = False , vVoteAmount = 3 , vProposalKey = key2 , vFrom = toAddress voter1 } ] let params2 = fmap NoPermit [ VoteParam { vVoteType = False , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress voter2 } , VoteParam { vVoteType = True , vVoteAmount = 4 , vProposalKey = key2 , vFrom = toAddress voter2 } ] let params3 = fmap NoPermit [ VoteParam { vVoteType = True , vVoteAmount = 3 , vProposalKey = key1 , vFrom = toAddress voter1 } , VoteParam { vVoteType = True , vVoteAmount = 3 , vProposalKey = key2 , vFrom = toAddress voter1 } ] advanceToLevel (originationLevel + 2*dodPeriod) withSender voter1 . inBatch $ do transfer dodDao $ calling (ep @"Vote") params1 transfer dodDao $ calling (ep @"Vote") params3 pure () withSender voter2 do transfer dodDao $ calling (ep @"Vote") params2 proposal1 <- fromMaybe (error "proposal not found") <$> getProposal dodDao key1 proposal2 <- fromMaybe (error "proposal not found") <$> getProposal dodDao key2 assert (plUpvotes proposal1 == 8) "proposal did not track upvotes correctly" assert (plDownvotes proposal1 == 2) "proposal did not track downvotes correctly" assert (plUpvotes proposal2 == 7) "proposal did not track upvotes correctly" assert (plDownvotes proposal2 == 3) "proposal did not track downvotes correctly" voter1key1 <- getVoter dodDao (voter1, key1) voter1key2 <- getVoter dodDao (voter1, key2) voter2key1 <- getVoter dodDao (voter2, key1) voter2key2 <- getVoter dodDao (voter2, key2) 8 upvotes , 0 downvotes 3 upvotes , 3 downvotes 0 upvotes , 2 downvotes 4 upvotes , 0 downvotes voteOutdatedProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteOutdatedProposal originateFn = do let configDesc = ConfigDesc configConsts { cmPeriod = Just 40, cmQuorumThreshold = Just (mkQuorumThreshold 1 100) } DaoOriginateData{..} <- originateFn configDesc defaultQuorumThreshold withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 4) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) startLevel <- getOriginationLevel dodDao advanceToLevel (startLevel + dodPeriod) key1 <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } advanceToLevel (startLevel + 2*dodPeriod) withSender dodOwner2 $ do transfer dodDao $ calling (ep @"Vote") [params] Advance two voting period to another voting stage . advanceToLevel (startLevel + 4*dodPeriod) (transfer dodDao $ calling (ep @"Vote") [params]) & expectFailedWith votingStageOver voteValidProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteValidProposal originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 2) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) startLevel <- getOriginationLevel dodDao We skip three , instead of just one , because the freeze operations might extend into the next period , when tests are run on real network . advanceToLevel (startLevel + 3*dodPeriod) Create sample proposal ( first proposal has i d = 0 ) key1 <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Vote") [params] checkBalance dodDao dodOwner2 2 getProposal dodDao key1 >>= \case Just proposal -> assert ((plUpvotes proposal) == 2) "Proposal had unexpected votes" Nothing -> error "Did not find proposal" voteDeletedProposal :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteDeletedProposal originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold startLevel <- getOriginationLevel dodDao withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 2) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 10) advanceToLevel (startLevel + 3*dodPeriod) Create sample proposal ( first proposal has i d = 0 ) key1 <- createSampleProposal 1 dodOwner1 dodDao let params = NoPermit VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner2 } advanceToLevel (startLevel + 4*dodPeriod) withSender dodOwner1 $ transfer dodDao $ calling (ep @"Drop_proposal") key1 withSender dodOwner2 $ (transfer dodDao $ calling (ep @"Vote") [params]) & expectFailedWith proposalNotExist voteWithPermit :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteWithPermit originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 12) startLevel <- getOriginationLevel dodDao advanceToLevel (startLevel + dodPeriod) key1 <- createSampleProposal 1 dodOwner1 dodDao params <- permitProtect dodOwner1 =<< addDataToSign dodDao (Nonce 0) VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner1 } advanceToLevel (startLevel + 2*dodPeriod) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Vote") [params] checkBalance dodDao dodOwner1 12 voteWithPermitNonce :: (MonadCleveland caps m, HasCallStack) => (ConfigDesc Config -> OriginateFn 'Base m) -> m () voteWithPermitNonce originateFn = do DaoOriginateData{..} <- originateFn voteConfig defaultQuorumThreshold originationLevel <- getOriginationLevel dodDao withSender dodOwner1 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 60) withSender dodOwner2 $ transfer dodDao $ calling (ep @"Freeze") (#amount :! 50) advanceToLevel (originationLevel + dodPeriod) key1 <- createSampleProposal 1 dodOwner1 dodDao let voteParam = VoteParam { vVoteType = True , vVoteAmount = 2 , vProposalKey = key1 , vFrom = toAddress dodOwner1 } advanceToLevel (originationLevel + 2*dodPeriod) signed1@(_ , _) <- addDataToSign dodDao (Nonce 0) voteParam signed2@(dataToSign2, _) <- addDataToSign dodDao (Nonce 1) voteParam signed3@(_ , _) <- addDataToSign dodDao (Nonce 2) voteParam params1 <- permitProtect dodOwner1 signed1 params2 <- permitProtect dodOwner1 signed2 params3 <- permitProtect dodOwner1 signed3 withSender dodOwner2 $ do transfer dodDao $ calling (ep @"Vote") [params1] (transfer dodDao $ calling (ep @"Vote") [params1]) & expectFailedWith (missigned, (lPackValue dataToSign2)) (transfer dodDao $ calling (ep @"Vote") [params3]) & expectFailedWith (missigned, (lPackValue dataToSign2)) transfer dodDao $ calling (ep @"Vote") [params2] (Nonce counter) <- getVotePermitsCounter dodDao counter @== 2
c13fad892a9d0a59b79463e9087b96f6bbb989e1808ef753ca33ab65e957c9ce
ghadishayban/pex
tree.clj
(ns com.champbacon.pex.impl.tree (:refer-clojure :exclude [cat char not and])) (def ^:dynamic *macros* {}) (defprotocol OpTree (pattern [_])) ;; make this work on pairs and do associativity fix inline? (defn choice [alternatives] (case (count alternatives) 0 (throw (ex-info "Empty ordered choice operator" {})) 1 (first alternatives) {:op :choice :children alternatives})) ;; make this work on pairs and do associativity fix inline? (defn cat [ps] (if (= 1 (count ps)) (first ps) {:op :cat :children ps})) (defn char-range [args] ;; checkargs {:op :charset :args args}) (defn char [codepoint] {:op :char :codepoint codepoint}) (defn string [s] (if (pos? (count s)) (cat (mapv (comp char int) s)) {:op :true})) (def fail {:op :fail}) (defn rep [patt] {:op :rep :children patt}) (defn any ([] {:op :any}) ([n] (cat (vec (repeat n {:op :any}))))) (defn not [patt] {:op :not :children patt}) (defn and [patt] {:op :and :children and}) (def end-of-input {:op :end-of-input}) (defn action [args] {:op :action :args args}) (defn non-terminal [s] {:op :open-call :target s}) (defn push [obj] {:op :push :value obj}) (defn capture [ps] {:op :capture :children ps}) (defn optional [ps] {:op :optional :children ps}) (def special '#{any EOI / * ? capture push and not class action reduce}) (extend-protocol OpTree String (pattern [s] (string s)) clojure.lang.IPersistentVector (pattern [v] (cat (mapv pattern v))) clojure.lang.Symbol (pattern [s] (condp = s 'any (any) 'EOI end-of-input (non-terminal s))) java.lang.Character (pattern [ch] (char (int ch))) java.lang.Boolean (pattern [b] (if b {:op :true} {:op :fail})) clojure.lang.IPersistentList ;; TODO Add macroexpansion (pattern [l] (when-first [call l] (if-let [macro (get *macros* call)] (pattern (apply macro (next l))) (let [args (next l) call-with-args #(%1 (mapv pattern args))] (condp = call '/ (call-with-args choice) 'any (call-with-args any) '* (call-with-args rep) '? (call-with-args optional) 'not (call-with-args not) 'and (call-with-args and) 'capture (call-with-args capture) 'push (push (fnext l)) 'class (char-range (next l)) ;;'reduce ;;(reduce-value-stack (next l)) 'action (action (next l)) :else (throw (ex-info "Unrecognized call" {:op call :form l})))))))) (defn parse-grammar [grammar macros] (when-not (every? keyword? (keys macros)) (throw (ex-info "PEG macros must all be keywords" macros))) (binding [*macros* macros] (into {} (map (fn [[kw p]] [kw (pattern p)])) grammar))) ;;; Optimizations (defn has-capture? [op] ) (defn empty-string-behavior [tree] ;; A pattern is *nullable* if it can match without consuming any character; ;; A pattern is *nofail* if it never fails for any string ;; (including the empty string). ) (defn fixed-length [tree] ;; number of characters to match a pattern (or nil if variable) ;; avoid infinite loop with a MAXRULES traversal count ) (defn first-set [tree] ;; #L246 ) (defn head-fail? [tree] ;; #L341 )
null
https://raw.githubusercontent.com/ghadishayban/pex/aa3255f6aa9086ca867d0ff401b8bbb2a306d86c/src/com/champbacon/pex/impl/tree.clj
clojure
make this work on pairs and do associativity fix inline? make this work on pairs and do associativity fix inline? checkargs TODO Add macroexpansion 'reduce (reduce-value-stack (next l)) Optimizations A pattern is *nullable* if it can match without consuming any character; A pattern is *nofail* if it never fails for any string (including the empty string). number of characters to match a pattern (or nil if variable) avoid infinite loop with a MAXRULES traversal count #L246 #L341
(ns com.champbacon.pex.impl.tree (:refer-clojure :exclude [cat char not and])) (def ^:dynamic *macros* {}) (defprotocol OpTree (pattern [_])) (defn choice [alternatives] (case (count alternatives) 0 (throw (ex-info "Empty ordered choice operator" {})) 1 (first alternatives) {:op :choice :children alternatives})) (defn cat [ps] (if (= 1 (count ps)) (first ps) {:op :cat :children ps})) (defn char-range [args] {:op :charset :args args}) (defn char [codepoint] {:op :char :codepoint codepoint}) (defn string [s] (if (pos? (count s)) (cat (mapv (comp char int) s)) {:op :true})) (def fail {:op :fail}) (defn rep [patt] {:op :rep :children patt}) (defn any ([] {:op :any}) ([n] (cat (vec (repeat n {:op :any}))))) (defn not [patt] {:op :not :children patt}) (defn and [patt] {:op :and :children and}) (def end-of-input {:op :end-of-input}) (defn action [args] {:op :action :args args}) (defn non-terminal [s] {:op :open-call :target s}) (defn push [obj] {:op :push :value obj}) (defn capture [ps] {:op :capture :children ps}) (defn optional [ps] {:op :optional :children ps}) (def special '#{any EOI / * ? capture push and not class action reduce}) (extend-protocol OpTree String (pattern [s] (string s)) clojure.lang.IPersistentVector (pattern [v] (cat (mapv pattern v))) clojure.lang.Symbol (pattern [s] (condp = s 'any (any) 'EOI end-of-input (non-terminal s))) java.lang.Character (pattern [ch] (char (int ch))) java.lang.Boolean (pattern [b] (if b {:op :true} {:op :fail})) clojure.lang.IPersistentList (pattern [l] (when-first [call l] (if-let [macro (get *macros* call)] (pattern (apply macro (next l))) (let [args (next l) call-with-args #(%1 (mapv pattern args))] (condp = call '/ (call-with-args choice) 'any (call-with-args any) '* (call-with-args rep) '? (call-with-args optional) 'not (call-with-args not) 'and (call-with-args and) 'capture (call-with-args capture) 'push (push (fnext l)) 'class (char-range (next l)) 'action (action (next l)) :else (throw (ex-info "Unrecognized call" {:op call :form l})))))))) (defn parse-grammar [grammar macros] (when-not (every? keyword? (keys macros)) (throw (ex-info "PEG macros must all be keywords" macros))) (binding [*macros* macros] (into {} (map (fn [[kw p]] [kw (pattern p)])) grammar))) (defn has-capture? [op] ) (defn empty-string-behavior [tree] ) (defn fixed-length [tree] ) (defn first-set [tree] ) (defn head-fail? [tree] )
ccbdfe319dcc0f50493a1c428283d00a666e006ad80ec0c8f3ce94e89a815d4b
karimarttila/clojure
users_dynamodb.clj
(ns simpleserver.userdb.users-dynamodb (:require [clojure.tools.logging :as log] [amazonica.aws.dynamodbv2 :as dynamodb] [environ.core :as environ] [simpleserver.userdb.users-service-interface :as ss-users-service-interface] [simpleserver.util.aws-utils :as ss-aws-utils] [simpleserver.userdb.users-common :as ss-users-common]) (:import (com.amazonaws.services.dynamodbv2.model AmazonDynamoDBException))) ;; NOTE: We are skipping the pagination here since this is an exercise and we know that the query results will always be less than 1 MB . ;; See: #Query.Pagination ;; In real life we should anticipate pagination and also test it. (defrecord Env-dynamodb [ssenv] ss-users-service-interface/UsersServiceInterface (email-already-exists? [ssenv email] (log/debug (str "ENTER email-already-exists?, email: " email)) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) my-table (str my-table-prefix "-" my-env "-users") ret (dynamodb/query (ss-aws-utils/get-dynamodb-config) :table-name my-table :select "COUNT" :key-conditions {:email {:attribute-value-list [email] :comparison-operator "EQ"}}) my-count (ret :count)] (not (= my-count 0)))) (add-new-user [ssenv email first-name last-name password] (log/debug (str "ENTER add-new-user, email: " email)) (let [already-exists (ss-users-service-interface/email-already-exists? ssenv email)] (if already-exists (do (log/debug (str "Failure: email already exists: " email)) {:email email, :ret :failed :msg "Email already exists"}) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) my-table (str my-table-prefix "-" my-env "-users") hashed-password (str (hash password)) ret (try (dynamodb/put-item (ss-aws-utils/get-dynamodb-config) :table-name my-table :item {:userid (ss-users-common/uuid) :email email :firstname first-name :lastname last-name :hpwd hashed-password}) (catch AmazonDynamoDBException e {:email email, :ret :failed :msg (str "Exception occured: " (.toString e))}))] If ret was empty then no errors . (if (empty? ret) {:email email, :ret :ok} ret))))) (credentials-ok? [ssenv email password] (log/debug (str "ENTER credentials-ok?, email: " email)) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) my-table (str my-table-prefix "-" my-env "-users") ret (dynamodb/query (ss-aws-utils/get-dynamodb-config) :table-name my-table :select "ALL_ATTRIBUTES" :key-conditions {:email {:attribute-value-list [email] :comparison-operator "EQ"}}) users (ret :items)] (if (empty? users) false (let [hashed-password (:hpwd (first users))] (= hashed-password (str (hash password))))))) (get-users [ssenv] (log/debug (str "ENTER get-users")) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) ret (dynamodb/scan (ss-aws-utils/get-dynamodb-config) :table-name (str my-table-prefix "-" my-env "-users")) items (ret :items)] (reduce (fn [users user] (assoc users (user :userid) {:userid (user :userid) :email (user :email) :first-name (user :firstname) :last-name (user :lastname) :hashed-password (user :hpwd)})) {} items))))
null
https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/clj-ring-cljs-reagent-demo/simple-server/src/simpleserver/userdb/users_dynamodb.clj
clojure
NOTE: We are skipping the pagination here since this is an exercise and See: #Query.Pagination In real life we should anticipate pagination and also test it.
(ns simpleserver.userdb.users-dynamodb (:require [clojure.tools.logging :as log] [amazonica.aws.dynamodbv2 :as dynamodb] [environ.core :as environ] [simpleserver.userdb.users-service-interface :as ss-users-service-interface] [simpleserver.util.aws-utils :as ss-aws-utils] [simpleserver.userdb.users-common :as ss-users-common]) (:import (com.amazonaws.services.dynamodbv2.model AmazonDynamoDBException))) we know that the query results will always be less than 1 MB . (defrecord Env-dynamodb [ssenv] ss-users-service-interface/UsersServiceInterface (email-already-exists? [ssenv email] (log/debug (str "ENTER email-already-exists?, email: " email)) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) my-table (str my-table-prefix "-" my-env "-users") ret (dynamodb/query (ss-aws-utils/get-dynamodb-config) :table-name my-table :select "COUNT" :key-conditions {:email {:attribute-value-list [email] :comparison-operator "EQ"}}) my-count (ret :count)] (not (= my-count 0)))) (add-new-user [ssenv email first-name last-name password] (log/debug (str "ENTER add-new-user, email: " email)) (let [already-exists (ss-users-service-interface/email-already-exists? ssenv email)] (if already-exists (do (log/debug (str "Failure: email already exists: " email)) {:email email, :ret :failed :msg "Email already exists"}) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) my-table (str my-table-prefix "-" my-env "-users") hashed-password (str (hash password)) ret (try (dynamodb/put-item (ss-aws-utils/get-dynamodb-config) :table-name my-table :item {:userid (ss-users-common/uuid) :email email :firstname first-name :lastname last-name :hpwd hashed-password}) (catch AmazonDynamoDBException e {:email email, :ret :failed :msg (str "Exception occured: " (.toString e))}))] If ret was empty then no errors . (if (empty? ret) {:email email, :ret :ok} ret))))) (credentials-ok? [ssenv email password] (log/debug (str "ENTER credentials-ok?, email: " email)) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) my-table (str my-table-prefix "-" my-env "-users") ret (dynamodb/query (ss-aws-utils/get-dynamodb-config) :table-name my-table :select "ALL_ATTRIBUTES" :key-conditions {:email {:attribute-value-list [email] :comparison-operator "EQ"}}) users (ret :items)] (if (empty? users) false (let [hashed-password (:hpwd (first users))] (= hashed-password (str (hash password))))))) (get-users [ssenv] (log/debug (str "ENTER get-users")) (let [my-env (environ/env :my-env) my-table-prefix (environ/env :ss-table-prefix) ret (dynamodb/scan (ss-aws-utils/get-dynamodb-config) :table-name (str my-table-prefix "-" my-env "-users")) items (ret :items)] (reduce (fn [users user] (assoc users (user :userid) {:userid (user :userid) :email (user :email) :first-name (user :firstname) :last-name (user :lastname) :hashed-password (user :hpwd)})) {} items))))
8c45fcabff927373e589a287acd45f56a78d7f17cc21acee7fc3e4ab0028ddbd
tonyg/kali-scheme
disasm.scm
; -*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*- Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . ; This is file assem.scm. ; This defines a command processor command ; dis <expression> ; that evaluates <expression> to obtain a procedure or lambda-expression, ; which is then disassembled. ; Needs: ; template? template-name template-code ; closure? closure-template ; code-vector-... ; location-name ; The assembly language is designed to be rereadable. See env/assem.scm. (define-command-syntax 'dis "[<exp>]" "disassemble procedure" '(&opt expression)) ; The command. The thing to be disassembled defaults to the focus object (##). (define (dis . maybe-exp) (disassemble (if (null? maybe-exp) (focus-object) (eval (car maybe-exp) (environment-for-commands))))) (define (disassemble obj) (really-disassemble (coerce-to-template obj) 0) (newline)) ; Instruction loop. WRITE-INSTRUCTION returns the new program counter. (define (really-disassemble tem level) (write (template-name tem)) (let ((length (template-code-length (template-code tem)))) (let loop ((pc 0)) (if (< pc length) (loop (write-instruction tem pc level #t)))))) The protocol used for procedures that require extra stack space uses three ; bytes at the end of the code vector. (define (template-code-length code) (if (and (= (enum op protocol) (code-vector-ref code 0)) (= big-stack-protocol (code-vector-ref code 1))) (- (code-vector-length code) 3) (code-vector-length code))) ; Write out the intstruction at PC in TEMPLATE. LEVEL is the nesting depth ; of TEMPLATE. If WRITE-SUB-TEMPLATES? is false we don't write out any ; templates found. ; ; Special handling is required for the few instructions that do not use a ; fixed number of code-stream arguments. (define (write-instruction template pc level write-sub-templates?) (let* ((code (template-code template)) (opcode (code-vector-ref code pc))) (newline-indent (* level 3)) (write-pc pc) (display " (") (write (enumerand->name opcode op)) (let ((pc (cond ((= opcode (enum op computed-goto)) (display-computed-goto pc code)) ((= opcode (enum op make-flat-env)) (display-flat-env (+ pc 1) code)) ((= opcode (enum op protocol)) (display-protocol (code-vector-ref code (+ pc 1)) pc code)) (else (print-opcode-args opcode pc code template level write-sub-templates?))))) (display #\)) pc))) ; Write out all of the branches of a computed goto. (define (display-computed-goto start-pc code) (display #\space) (let ((count (code-vector-ref code (+ start-pc 1)))) (write count) (do ((pc (+ start-pc 2) (+ pc 2)) (count count (- count 1))) ((= count 0) pc) (display #\space) (write `(=> ,(+ start-pc (get-offset pc code) 2)))))) ; Write out the environment specs for the make-flat-env opcode. (define (display-flat-env pc code) (let ((total-count (code-vector-ref code (+ 1 pc)))) (display #\space) (write total-count) (let loop ((pc (+ pc 2)) (count 0) (old-back 0)) (if (= count total-count) pc (let ((back (+ (code-vector-ref code pc) old-back)) (limit (+ pc 2 (code-vector-ref code (+ pc 1))))) (do ((pc (+ pc 2) (+ pc 1)) (count count (+ count 1)) (offsets '() (cons (code-vector-ref code pc) offsets))) ((= pc limit) (display #\space) (write `(,back ,(reverse offsets))) (loop pc count back)))))))) ; Display a protocol, returning the number of bytes of instruction stream that ; were consumed. (define (display-protocol protocol pc code) (display #\space) (+ pc (cond ((<= protocol maximum-stack-args) (display protocol) 2) ((= protocol two-byte-nargs-protocol) (display (get-offset (+ pc 2) code)) 4) ((= protocol two-byte-nargs+list-protocol) (display (get-offset (+ pc 2) code)) (display " +") 4) ((= protocol args+nargs-protocol) (display "args+nargs") 3) ((= protocol nary-dispatch-protocol) (display "nary-dispatch") (do ((i 0 (+ i 1))) ((= i 4)) (let ((offset (code-vector-ref code (+ pc 2 i)))) (if (not (= offset 0)) (begin (display #\space) (display (list (if (= i 3) '>2 i) '=> (+ pc offset))))))) 6) ((= protocol big-stack-protocol) (display "big-stack") (let ((size (display-protocol (code-vector-ref code (- (code-vector-length code) 3)) pc code))) (display #\space) (display (get-offset (- (code-vector-length code) 2) code)) size)) (else (error "unknown protocol" protocol))))) Generic opcode argument printer . (define (print-opcode-args op start-pc code template level write-templates?) (let ((specs (vector-ref opcode-arg-specs op))) (let loop ((specs specs) (pc (+ start-pc 1))) (cond ((or (null? specs) (= 0 (arg-spec-size (car specs) pc code))) pc) ((eq? (car specs) 'junk) ; avoid printing a space (loop (cdr specs) (+ pc 1))) (else (display #\space) (print-opcode-arg specs pc start-pc code template level write-templates?) (loop (cdr specs) (+ pc (arg-spec-size (car specs) pc code)))))))) ; The number of bytes required by an argument. (define (arg-spec-size spec pc code) (case spec ((nargs byte stob junk) 1) ((offset index small-index two-bytes) 2) ((env-data) (+ 1 (* 2 (code-vector-ref code pc)))) (else 0))) ; Print out the particular type of argument. (define (print-opcode-arg specs pc start-pc code template level write-templates?) (case (car specs) ((nargs byte) (write (code-vector-ref code pc))) ((two-bytes) (write (get-offset pc code))) ((index) (let ((thing (template-ref template (get-offset pc code)))) (write-literal-thing thing level write-templates?))) ((small-index) (let ((thing (template-ref template (code-vector-ref code pc)))) (write-literal-thing thing level write-templates?))) ((offset) (write `(=> ,(+ start-pc (get-offset pc code))))) ((stob) (write (enumerand->name (code-vector-ref code pc) stob))) ((env-data) (let ((nobjects (code-vector-ref code pc))) (let loop ((offset (+ pc 1)) (n nobjects)) (cond ((not (zero? n)) (display (list (code-vector-ref code offset) (code-vector-ref code (+ offset 1)))) (if (not (= n 1)) (write-char #\space)) (loop (+ offset 2) (- n 1))))))))) (define (write-literal-thing thing level write-templates?) (cond ((location? thing) (write (or (location-name thing) `(location ,(location-id thing))))) ((not (template? thing)) (display #\') (write thing)) (write-templates? (really-disassemble thing (+ level 1))) (else (display "...")))) ;---------------- Utilities . ; Turn OBJ into a template, if possible. (define (coerce-to-template obj) (cond ((template? obj) obj) ((closure? obj) (closure-template obj)) ((continuation? obj) (continuation-template obj)) (else (error "expected a procedure or continuation" obj)))) Fetch the two - byte value at PC in CODE . (define (get-offset pc code) (+ (* (code-vector-ref code pc) byte-limit) (code-vector-ref code (+ pc 1)))) ; Indenting and aligning the program counter. (define (newline-indent n) (newline) (do ((i n (- i 1))) ((= i 0)) (display #\space))) (define (write-pc pc) (if (< pc 100) (display " ")) (if (< pc 10) (display " ")) (write pc))
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/env/disasm.scm
scheme
-*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*- This is file assem.scm. This defines a command processor command dis <expression> that evaluates <expression> to obtain a procedure or lambda-expression, which is then disassembled. Needs: template? template-name template-code closure? closure-template code-vector-... location-name The assembly language is designed to be rereadable. See env/assem.scm. The command. The thing to be disassembled defaults to the focus object (##). Instruction loop. WRITE-INSTRUCTION returns the new program counter. bytes at the end of the code vector. Write out the intstruction at PC in TEMPLATE. LEVEL is the nesting depth of TEMPLATE. If WRITE-SUB-TEMPLATES? is false we don't write out any templates found. Special handling is required for the few instructions that do not use a fixed number of code-stream arguments. Write out all of the branches of a computed goto. Write out the environment specs for the make-flat-env opcode. Display a protocol, returning the number of bytes of instruction stream that were consumed. avoid printing a space The number of bytes required by an argument. Print out the particular type of argument. ---------------- Turn OBJ into a template, if possible. Indenting and aligning the program counter.
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . (define-command-syntax 'dis "[<exp>]" "disassemble procedure" '(&opt expression)) (define (dis . maybe-exp) (disassemble (if (null? maybe-exp) (focus-object) (eval (car maybe-exp) (environment-for-commands))))) (define (disassemble obj) (really-disassemble (coerce-to-template obj) 0) (newline)) (define (really-disassemble tem level) (write (template-name tem)) (let ((length (template-code-length (template-code tem)))) (let loop ((pc 0)) (if (< pc length) (loop (write-instruction tem pc level #t)))))) The protocol used for procedures that require extra stack space uses three (define (template-code-length code) (if (and (= (enum op protocol) (code-vector-ref code 0)) (= big-stack-protocol (code-vector-ref code 1))) (- (code-vector-length code) 3) (code-vector-length code))) (define (write-instruction template pc level write-sub-templates?) (let* ((code (template-code template)) (opcode (code-vector-ref code pc))) (newline-indent (* level 3)) (write-pc pc) (display " (") (write (enumerand->name opcode op)) (let ((pc (cond ((= opcode (enum op computed-goto)) (display-computed-goto pc code)) ((= opcode (enum op make-flat-env)) (display-flat-env (+ pc 1) code)) ((= opcode (enum op protocol)) (display-protocol (code-vector-ref code (+ pc 1)) pc code)) (else (print-opcode-args opcode pc code template level write-sub-templates?))))) (display #\)) pc))) (define (display-computed-goto start-pc code) (display #\space) (let ((count (code-vector-ref code (+ start-pc 1)))) (write count) (do ((pc (+ start-pc 2) (+ pc 2)) (count count (- count 1))) ((= count 0) pc) (display #\space) (write `(=> ,(+ start-pc (get-offset pc code) 2)))))) (define (display-flat-env pc code) (let ((total-count (code-vector-ref code (+ 1 pc)))) (display #\space) (write total-count) (let loop ((pc (+ pc 2)) (count 0) (old-back 0)) (if (= count total-count) pc (let ((back (+ (code-vector-ref code pc) old-back)) (limit (+ pc 2 (code-vector-ref code (+ pc 1))))) (do ((pc (+ pc 2) (+ pc 1)) (count count (+ count 1)) (offsets '() (cons (code-vector-ref code pc) offsets))) ((= pc limit) (display #\space) (write `(,back ,(reverse offsets))) (loop pc count back)))))))) (define (display-protocol protocol pc code) (display #\space) (+ pc (cond ((<= protocol maximum-stack-args) (display protocol) 2) ((= protocol two-byte-nargs-protocol) (display (get-offset (+ pc 2) code)) 4) ((= protocol two-byte-nargs+list-protocol) (display (get-offset (+ pc 2) code)) (display " +") 4) ((= protocol args+nargs-protocol) (display "args+nargs") 3) ((= protocol nary-dispatch-protocol) (display "nary-dispatch") (do ((i 0 (+ i 1))) ((= i 4)) (let ((offset (code-vector-ref code (+ pc 2 i)))) (if (not (= offset 0)) (begin (display #\space) (display (list (if (= i 3) '>2 i) '=> (+ pc offset))))))) 6) ((= protocol big-stack-protocol) (display "big-stack") (let ((size (display-protocol (code-vector-ref code (- (code-vector-length code) 3)) pc code))) (display #\space) (display (get-offset (- (code-vector-length code) 2) code)) size)) (else (error "unknown protocol" protocol))))) Generic opcode argument printer . (define (print-opcode-args op start-pc code template level write-templates?) (let ((specs (vector-ref opcode-arg-specs op))) (let loop ((specs specs) (pc (+ start-pc 1))) (cond ((or (null? specs) (= 0 (arg-spec-size (car specs) pc code))) pc) (loop (cdr specs) (+ pc 1))) (else (display #\space) (print-opcode-arg specs pc start-pc code template level write-templates?) (loop (cdr specs) (+ pc (arg-spec-size (car specs) pc code)))))))) (define (arg-spec-size spec pc code) (case spec ((nargs byte stob junk) 1) ((offset index small-index two-bytes) 2) ((env-data) (+ 1 (* 2 (code-vector-ref code pc)))) (else 0))) (define (print-opcode-arg specs pc start-pc code template level write-templates?) (case (car specs) ((nargs byte) (write (code-vector-ref code pc))) ((two-bytes) (write (get-offset pc code))) ((index) (let ((thing (template-ref template (get-offset pc code)))) (write-literal-thing thing level write-templates?))) ((small-index) (let ((thing (template-ref template (code-vector-ref code pc)))) (write-literal-thing thing level write-templates?))) ((offset) (write `(=> ,(+ start-pc (get-offset pc code))))) ((stob) (write (enumerand->name (code-vector-ref code pc) stob))) ((env-data) (let ((nobjects (code-vector-ref code pc))) (let loop ((offset (+ pc 1)) (n nobjects)) (cond ((not (zero? n)) (display (list (code-vector-ref code offset) (code-vector-ref code (+ offset 1)))) (if (not (= n 1)) (write-char #\space)) (loop (+ offset 2) (- n 1))))))))) (define (write-literal-thing thing level write-templates?) (cond ((location? thing) (write (or (location-name thing) `(location ,(location-id thing))))) ((not (template? thing)) (display #\') (write thing)) (write-templates? (really-disassemble thing (+ level 1))) (else (display "...")))) Utilities . (define (coerce-to-template obj) (cond ((template? obj) obj) ((closure? obj) (closure-template obj)) ((continuation? obj) (continuation-template obj)) (else (error "expected a procedure or continuation" obj)))) Fetch the two - byte value at PC in CODE . (define (get-offset pc code) (+ (* (code-vector-ref code pc) byte-limit) (code-vector-ref code (+ pc 1)))) (define (newline-indent n) (newline) (do ((i n (- i 1))) ((= i 0)) (display #\space))) (define (write-pc pc) (if (< pc 100) (display " ")) (if (< pc 10) (display " ")) (write pc))
33dd473e6fde7227d501afb50c714b2ee96a6de6b6450558bc9324945c7ae45f
caisah/sicp-exercises-and-examples
stream.scm
(define (stream-ref s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (define (stream-map proc s) (if (stream-null? s) the-empty-stream (cons-stream (proc (stream-car s)) (stream-map proc (stream-cdr s))))) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (display-stream s) (stream-for-each display-line s)) (define (display-line x) (newline) (display x)) ;; (define (stream-null? stream) ;; (null? stream)) ;; (define (stream-car stream) (car stream)) ;; (define (stream-cdr stream) (force (cdr stream))) ;; (define (cons-stream a b) (cons a (delay b))) ;; (define the-empty-stream '()) ;; (define (memo-proc proc) ;; (let ((already-run? false) (result false)) ;; (lambda () ;; (if (not already-run?) ;; (begin (set! result (proc)) ;; (set! already-run? true) ;; result) ;; result)))) ;; (define (delay x) ;; (memo-proc (memo-proc (lambda () x)))) ;; (define (force delayed-object) ;; (delayed-object))
null
https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/3.5.1-streams_are_delayed_lists/stream.scm
scheme
(define (stream-null? stream) (null? stream)) (define (stream-car stream) (car stream)) (define (stream-cdr stream) (force (cdr stream))) (define (cons-stream a b) (cons a (delay b))) (define the-empty-stream '()) (define (memo-proc proc) (let ((already-run? false) (result false)) (lambda () (if (not already-run?) (begin (set! result (proc)) (set! already-run? true) result) result)))) (define (delay x) (memo-proc (memo-proc (lambda () x)))) (define (force delayed-object) (delayed-object))
(define (stream-ref s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (define (stream-map proc s) (if (stream-null? s) the-empty-stream (cons-stream (proc (stream-car s)) (stream-map proc (stream-cdr s))))) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (display-stream s) (stream-for-each display-line s)) (define (display-line x) (newline) (display x))