_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
2fe970bae6b8016b41a3c30d78d0cda7a9b8ed5a4bfe0621571ec226e4cb16b3
zotonic/zotonic
z_trans_server.erl
@author < > 2010 - 2017 %% @doc Simple server to manage the translations, owns the ets table containing all translations. %% When new translations are read then the previous table is kept and the one before the previous is deleted. Copyright 2010 - 2017 %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(z_trans_server). -behaviour(gen_server). %% gen_server exports -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([start_tests/0,start_link/1]). %% interface functions -export([ load_translations/1, load_translations/2, table/1, set_context_table/1, observe_module_ready/2 ]). -include_lib("zotonic.hrl"). -record(state, {table, site}). %%==================================================================== %% API %%==================================================================== -spec start_tests() -> {ok, pid()} | {error, term()}. start_tests() -> io:format("Starting trans server.~n"), gen_server:start_link({local, 'z_trans_server$test'}, ?MODULE, test, []). %% @doc Starts the server -spec start_link(Site :: atom()) -> {ok, pid()} | {error, term()}. start_link(Site) -> Name = z_utils:name_for_site(?MODULE, Site), gen_server:start_link({local, Name}, ?MODULE, {Site, Name}, []). @doc Parse all .po files and reload the found translations in the trans server -spec load_translations(z:context()) -> ok. load_translations(Context) -> Ts = z_trans:parse_translations(Context), load_translations(Ts, Context). @doc Take a proplist with dicts and reload the translations table . %% After reloading the the template server is flushed. -spec load_translations(map(), z:context()) -> ok. load_translations(Trans, Context) -> Name = z_utils:name_for_site(?MODULE, z_context:site(Context)), gen_server:cast(Name, {load_translations, Trans}). %% @doc Return the name of the ets table holding all translations -spec table(atom()|z:context()) -> atom(). table(Site) when is_atom(Site) -> z_utils:name_for_site(?MODULE, Site); table(#context{} = Context) -> Context#context.translation_table. %% @doc Set the table id in the context to the newest table id -spec set_context_table(z:context()) -> z:context(). set_context_table(#context{} = Context) -> Context#context{translation_table=table(z_context:site(Context))}. %% @doc Reload the translations when modules are changed. -spec observe_module_ready(module_ready, z:context()) -> ok. observe_module_ready(module_ready, Context) -> load_translations(Context). %%==================================================================== %% gen_server callbacks %%==================================================================== %% @doc Initiates the server. -spec init({ Site :: atom(), Name :: atom() }) -> {ok, #state{}}. init({Site, Name}) -> logger:set_process_metadata(#{ site => Site, module => ?MODULE }), process_flag(trap_exit, true), ok = z_notifier:observe(module_ready, {?MODULE, observe_module_ready}, Site), Table = ets:new(Name, [named_table, set, protected, {read_concurrency, true}]), {ok, #state{table=Table, site=Site}}. %% @doc Trap unknown calls handle_call(Message, _From, State) -> {stop, {unknown_call, Message}, State}. %% @doc Rebuild the translations table. Call the template flush routines afterwards. Trans is a map with all translations per translatable string . handle_cast({load_translations, Trans}, State) -> F = fun(Key, Value, Acc) -> Value1 = case proplists:get_value(en, Value) of undefined -> [{en,Key}|Value]; _ -> Value end, [{Key,Value1}|Acc] end, List = maps:fold(F, [], Trans), sync_to_table(List, State#state.table), z_template:reset(State#state.site), {noreply, State, hibernate}; %% @doc Trap unknown casts handle_cast(Message, State) -> {stop, {unknown_cast, Message}, State}. %% @doc Handling all non call/cast messages handle_info(_Info, State) -> {noreply, State}. %% @doc This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. terminate(_Reason, State) -> z_notifier:detach(module_ready, State#state.site), ok. %% @doc Convert process state when code is changed code_change(_OldVsn, State, _Extra) -> case State of {state, Table, _OldTable} -> {ok, #state{table=Table}}; _ -> {ok, State} end. %%==================================================================== %% support functions %%==================================================================== %% @doc Sync a list of translations to the ets table containing all translations sync_to_table(List, Table) -> LT = lists:sort(ets:tab2list(Table)), List1 = lists:sort(List), sync(List1, LT, Table). sync([], [], _Table) -> ok; sync(L, [], Table) -> ets:insert(Table, L); sync([], L, Table) -> lists:map(fun({Key,_}) -> ets:delete(Table, Key) end, L); sync([H|NewList], [H|OldList], Table) -> sync(NewList, OldList, Table); sync([{K,V}|NewList], [{K,_}|OldList], Table) -> ets:insert(Table, [{K,V}]), sync(NewList, OldList, Table); sync([{K1,V1}|NewList], [{K2,_}|_] = OldList, Table) when K1 < K2 -> ets:insert(Table, [{K1,V1}]), sync(NewList, OldList, Table); sync([{K1,_}|_] = NewList, [{K2,_}|OldList], Table) when K1 > K2 -> ets:delete(Table, K2), sync(NewList, OldList, Table).
null
https://raw.githubusercontent.com/zotonic/zotonic/aa38d5bd01f20696a7c5230b97ea23d2d1678e79/apps/zotonic_core/src/i18n/z_trans_server.erl
erlang
@doc Simple server to manage the translations, owns the ets table containing all translations. When new translations are read then the previous table is kept and the one before the previous is deleted. 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. gen_server exports interface functions ==================================================================== API ==================================================================== @doc Starts the server After reloading the the template server is flushed. @doc Return the name of the ets table holding all translations @doc Set the table id in the context to the newest table id @doc Reload the translations when modules are changed. ==================================================================== gen_server callbacks ==================================================================== @doc Initiates the server. @doc Trap unknown calls @doc Rebuild the translations table. Call the template flush routines afterwards. @doc Trap unknown casts @doc Handling all non call/cast messages @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. @doc Convert process state when code is changed ==================================================================== support functions ==================================================================== @doc Sync a list of translations to the ets table containing all translations
@author < > 2010 - 2017 Copyright 2010 - 2017 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(z_trans_server). -behaviour(gen_server). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([start_tests/0,start_link/1]). -export([ load_translations/1, load_translations/2, table/1, set_context_table/1, observe_module_ready/2 ]). -include_lib("zotonic.hrl"). -record(state, {table, site}). -spec start_tests() -> {ok, pid()} | {error, term()}. start_tests() -> io:format("Starting trans server.~n"), gen_server:start_link({local, 'z_trans_server$test'}, ?MODULE, test, []). -spec start_link(Site :: atom()) -> {ok, pid()} | {error, term()}. start_link(Site) -> Name = z_utils:name_for_site(?MODULE, Site), gen_server:start_link({local, Name}, ?MODULE, {Site, Name}, []). @doc Parse all .po files and reload the found translations in the trans server -spec load_translations(z:context()) -> ok. load_translations(Context) -> Ts = z_trans:parse_translations(Context), load_translations(Ts, Context). @doc Take a proplist with dicts and reload the translations table . -spec load_translations(map(), z:context()) -> ok. load_translations(Trans, Context) -> Name = z_utils:name_for_site(?MODULE, z_context:site(Context)), gen_server:cast(Name, {load_translations, Trans}). -spec table(atom()|z:context()) -> atom(). table(Site) when is_atom(Site) -> z_utils:name_for_site(?MODULE, Site); table(#context{} = Context) -> Context#context.translation_table. -spec set_context_table(z:context()) -> z:context(). set_context_table(#context{} = Context) -> Context#context{translation_table=table(z_context:site(Context))}. -spec observe_module_ready(module_ready, z:context()) -> ok. observe_module_ready(module_ready, Context) -> load_translations(Context). -spec init({ Site :: atom(), Name :: atom() }) -> {ok, #state{}}. init({Site, Name}) -> logger:set_process_metadata(#{ site => Site, module => ?MODULE }), process_flag(trap_exit, true), ok = z_notifier:observe(module_ready, {?MODULE, observe_module_ready}, Site), Table = ets:new(Name, [named_table, set, protected, {read_concurrency, true}]), {ok, #state{table=Table, site=Site}}. handle_call(Message, _From, State) -> {stop, {unknown_call, Message}, State}. Trans is a map with all translations per translatable string . handle_cast({load_translations, Trans}, State) -> F = fun(Key, Value, Acc) -> Value1 = case proplists:get_value(en, Value) of undefined -> [{en,Key}|Value]; _ -> Value end, [{Key,Value1}|Acc] end, List = maps:fold(F, [], Trans), sync_to_table(List, State#state.table), z_template:reset(State#state.site), {noreply, State, hibernate}; handle_cast(Message, State) -> {stop, {unknown_cast, Message}, State}. handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, State) -> z_notifier:detach(module_ready, State#state.site), ok. code_change(_OldVsn, State, _Extra) -> case State of {state, Table, _OldTable} -> {ok, #state{table=Table}}; _ -> {ok, State} end. sync_to_table(List, Table) -> LT = lists:sort(ets:tab2list(Table)), List1 = lists:sort(List), sync(List1, LT, Table). sync([], [], _Table) -> ok; sync(L, [], Table) -> ets:insert(Table, L); sync([], L, Table) -> lists:map(fun({Key,_}) -> ets:delete(Table, Key) end, L); sync([H|NewList], [H|OldList], Table) -> sync(NewList, OldList, Table); sync([{K,V}|NewList], [{K,_}|OldList], Table) -> ets:insert(Table, [{K,V}]), sync(NewList, OldList, Table); sync([{K1,V1}|NewList], [{K2,_}|_] = OldList, Table) when K1 < K2 -> ets:insert(Table, [{K1,V1}]), sync(NewList, OldList, Table); sync([{K1,_}|_] = NewList, [{K2,_}|OldList], Table) when K1 > K2 -> ets:delete(Table, K2), sync(NewList, OldList, Table).
f65b829457cd1e74856589653a72145160573ff3fbc549524c26f8168ed21daf
vikram/lisplibraries
packages.lisp
;;; -*- lisp -*- ;;;; * The Packages (defpackage :it.bese.ucw (:nicknames :ucw) (:shadowing-import-from :trivial-garbage #:make-hash-table) (:use :common-lisp :it.bese.ucw.system :it.bese.arnesi :it.bese.yaclml :bordeaux-threads :local-time :trivial-garbage :cl-l10n :iterate :trivial-sockets) (:shadow #:parent) (:export ;; backend classes #:mod-lisp-backend #:multithread-mod-lisp-backend #:aserve-backend #:araneida-backend #:httpd-backend #:multithread-httpd-backend ;; random configuration options #:*inspect-components* #:external-format-for ;; rerl protocol #:*default-server* #:standard-server #:startup-server #:shutdown-server #:restart-server #:server.backend #:server.applications #:debug-on-error #:javascript-debug-level #:*debug-on-error* #:*context* #:context.window-component #:context.request #:context.response #:context.session #:context.application #:with-dummy-context #:make-request-context #:startup-application #:shutdown-application #:restart-application #:register-application #:unregister-application #:*default-application* #:standard-application #:cookie-session-application #:cookie-session-request-context #:lock-of #:with-lock-held-on-application #:with-lock-held-on-current-application #:with-lock-held-on-session ;; client-state #:register-client-state ;; application mixins #:cookie-session-application-mixin #:secure-application-mixin #:l10n-application-mixin #:single-frame-application-mixin #:dirty-component-tracking-application-mixin #:request-context-class #:session-class #:user-track-application-mixin #:application.online-users ;; accessing the request/response objects #:mime-part-p #:mime-part-headers #:mime-part-body #:request #:response #:html-stream #:close-request #:get-header #:get-parameter #:map-parameters #:send-headers #:send-response #:serve-sequence ;; backtracking #:backtrack #:backtrack-slot ;; components #:defcomponent #:compute-url #:update-url #:standard-component-class #:component #:parent #:widget-component #:standard-component #:template-component #:template-component-environment #:simple-template-component #:show #:show-window #:html-element #:widget-component #:inline-widget-component #:css-class #:css-style #:child-components #:component.place #:session-of ;; dojo widgets #:widget-id #:dojo-widget #:add-onload-script #:simple-dojo-widget #:dojo-content-pane #:dojo-tab-container #:dojo-tab #:dojo-date-picker #:dojo-time-picker #:dojo-dropdown-date-picker #:dojo-dropdown-time-picker #:dojo-timestamp-picker #:ajax-render-new-tab #:dojo-split-container #:rendering-dojo-tooltip-for ;; windows #:window-component #:simple-window-component #:basic-window-features-mixin #:window-component.icon #:window-component.stylesheet #:window-component.javascript #:window-component.title #:window-component.content-type generic componet actions #:refresh-component #:ok #:meta-refresh ;; error message component #:error-message #:error-component ;; login component #:login #:login.username #:login.password #:try-login #:check-credentials #:login-successful ;; collapsible-pane component #:collapsible-pane #:collapsedp #:render-standard-switch ;; info-message component #:info-message ;; option dialog component #:option-dialog #:respond ;; container component #:container #:switching-container #:list-container #:make-list-container #:component-at #:add-component #:remove-component #:clear-container #:container.current-component-key #:container.current-component #:container.key-test #:container.contents #:switch-component #:find-component #:initialize-container ;; ajax component #:ajax-component-mixin #:render-nearest-ajax-component #:render-ajax-stub #:ajax-render #:dirtyp #:visiblep #:mark-dirty #:without-dirtyness-tracking #:js-server-callback ;; inspector #:ucw-inspector #:inspect-anchor ;; forms #:form-field #:generic-html-input #:dom-id #:value #:client-value #:tabindex #:simple-form #:string-field #:textarea-field #:number-field #:integer-field #:password-field #:checkbox-field #:file-upload-field #:select-field #:mapping-select-field #:alist-select-field #:hash-table-select-field #:plist-select-field #:submit-button #:radio-group #:value-widget #:in-field-string-field #:date-field #:date-ymd #:is-a-date-validator #:is-a-date-time-validator #:time-range-validator #:dmy-date-field #:mdy-date-field #:validator #:validators #:generate-javascript #:generate-javascript-check #:javascript-check #:generate-javascript-valid-handler #:javascript-valid-handler #:generate-javascript-invalid-handler #:javascript-invalid-handler #:validp #:is-an-integer-validator #:number-range-validator #:length-validator #:min-length #:max-length #:not-empty-validator #:string=-validator #:integer-range-validator #:regex-validator #:regex #:hostname-validator #:e-mail-address-validator #:phone-number-validator ;; range-view component #:range-view #:render-range-view-item #:range-view.current-window #:range-view.current-window-items #:range-view.windows #:range-view.have-next-p #:range-view.have-previous-p ;; the date picker component #:generic-date-picker #:dropdown-date-picker #:date-picker.year #:date-picker.day #:date-picker.month #:date-picker.partial-date-p #:date-picker.complete-date-p #:redirect-component #:send-redirect ;; the tabbed-pane component #:tabbed-pane ;; the task component #:task-component #:start ;; status bar component #:status-bar #:add-message #:show-message ;; cache #:cached-component #:cached-output #:timeout #:component-dirty-p #:refresh-component-output #:timeout-cache-component #:num-hits-cache-component ;; transactions #:transaction-mixin #:open-transaction #:close-transaction ;; secure application #:secure-application-mixin #:secure-application-p #:application-find-user #:application-check-password #:application-authorize-call #:on-authorization-reject #:session-user #:session-authenticated-p #:user-login #:login-user #:logout-user #:exit-user ;; actions #:defaction #:defentry-point #:self #:call #:call-component #:call-as-window #:answer #:answer-component #:jump #:jump-to-component #:make-place #:action-href #:action-href-body #:handle-raw-request #:handle-ajax-request #:action-id ;; disptachers #:minimal-dispatcher #:make-minimal-dispatcher #:simple-dispatcher #:make-simple-dispatcher #:url-dispatcher #:make-url-dispatcher #:regexp-dispatcher #:make-regexp-dispatcher #:action-dispatcher #:*dispatcher-registers* #:tal-dispatcher #:parenscript-dispatcher #:make-parenscript-dispatcher #:make-standard-ucw-dispatchers #:make-standard-ucw-www-roots ; will be removed #:make-standard-ucw-www-root-list #:make-standard-ucw-tal-dir-list #:with-request-params ;; session #:get-session-value #:session.value #:make-new-session #:with-session-variables #:register-action #:register-ajax-action #:make-action #:make-action-body #:register-callback #:make-callback #:register-submit-callback #:inside-a-form-p #:current-form-id ;; l10n #:l10n-application #:reload-ucw-resources #:application.default-locale #:application.accepted-locales #:l10n-request-context #:context.locale #:l10n-tal-generator #:+missing-resource-css-class+ #:enable-js-sharpquote-reader #:enable-sharpquote<>-reader #:with-sharpquote<>-syntax #:define-js-resources yaclml / tal #:*ucw-tal-root* #:render #:render-template ;; publishing files, directories and other "stuff" #:publish-directory ;; Helper functions #:read-from-client-string ;; Control utilities #:start-swank #:create-server #:hello #:bye-bye)) (defpackage :it.bese.ucw-user (:nicknames :ucw-user) (:shadowing-import-from :trivial-garbage #:make-hash-table) (:shadowing-import-from :ucw #:parent) (:use :common-lisp :it.bese.ucw :it.bese.arnesi :iterate :local-time :bordeaux-threads :trivial-garbage :cl-l10n :it.bese.yaclml)) (defpackage :it.bese.ucw.lang (:nicknames :ucw.lang) (:import-from :ucw #:+missing-resource-css-class+ #:define-js-resources) (:export #:+missing-resource-css-class+ #:define-js-resources)) (defpackage :it.bese.ucw.tags (:documentation "UCW convience tags.") (:use) (:nicknames #:<ucw) (:export #:render-component #:a #:area #:form #:input #:button #:simple-select #:select #:option #:textarea #:integer-range-select #:month-day-select #:month-select #:text #:password #:submit #:simple-form #:simple-submit #:localized #:script)) ;;;;@include "rerl/protocol.lisp" ;;;; * Components ;;;;@include "components/login.lisp" ;;;;@include "components/error.lisp" ;;;;@include "components/message.lisp" ;;;;@include "components/option-dialog.lisp" ;;;;@include "components/range-view.lisp" ;;;;@include "components/redirect.lisp" ;;;;@include "components/tabbed-pane.lisp" ;;;;@include "components/task.lisp" ;;;;@include "components/ucw-inspector.lisp" ;;;; * Meta Components ;;;;@include "components/widget.lisp" ;;;;@include "components/window.lisp" ;;;;@include "components/template.lisp" ;;;;@include "components/container.lisp" ;;;; * Standard RERL Implementation ;;;;@include "rerl/standard-server.lisp" ;;;;@include "rerl/standard-application.lisp" ;;;;@include "rerl/standard-session.lisp" ;;;;@include "rerl/cookie-session.lisp" ;;;;@include "rerl/standard-session-frame.lisp" ;;;;@include "rerl/standard-action.lisp" ;;;;@include "rerl/backtracking.lisp" ;;;;@include "rerl/request-loop-error.lisp" @include " rerl / conditions.lisp " ;;;;@include "rerl/standard-vars.lisp" ;;;; ** Standard Component ;;;; * The Backends ;;;;@include "backend/httpd.lisp" Copyright ( c ) 2003 - 2005 ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are ;; met: ;; ;; - Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; ;; - Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; - Neither the name of , nor , nor the names ;; of its contributors may be used to endorse or promote products ;; derived from this software without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/ucw_ajax/src/packages.lisp
lisp
-*- lisp -*- * The Packages backend classes random configuration options rerl protocol client-state application mixins accessing the request/response objects backtracking components dojo widgets windows error message component login component collapsible-pane component info-message component option dialog component container component ajax component inspector forms range-view component the date picker component the tabbed-pane component the task component status bar component cache transactions secure application actions disptachers will be removed session l10n publishing files, directories and other "stuff" Helper functions Control utilities @include "rerl/protocol.lisp" * Components @include "components/login.lisp" @include "components/error.lisp" @include "components/message.lisp" @include "components/option-dialog.lisp" @include "components/range-view.lisp" @include "components/redirect.lisp" @include "components/tabbed-pane.lisp" @include "components/task.lisp" @include "components/ucw-inspector.lisp" * Meta Components @include "components/widget.lisp" @include "components/window.lisp" @include "components/template.lisp" @include "components/container.lisp" * Standard RERL Implementation @include "rerl/standard-server.lisp" @include "rerl/standard-application.lisp" @include "rerl/standard-session.lisp" @include "rerl/cookie-session.lisp" @include "rerl/standard-session-frame.lisp" @include "rerl/standard-action.lisp" @include "rerl/backtracking.lisp" @include "rerl/request-loop-error.lisp" @include "rerl/standard-vars.lisp" ** Standard Component * The Backends @include "backend/httpd.lisp" All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(defpackage :it.bese.ucw (:nicknames :ucw) (:shadowing-import-from :trivial-garbage #:make-hash-table) (:use :common-lisp :it.bese.ucw.system :it.bese.arnesi :it.bese.yaclml :bordeaux-threads :local-time :trivial-garbage :cl-l10n :iterate :trivial-sockets) (:shadow #:parent) (:export #:mod-lisp-backend #:multithread-mod-lisp-backend #:aserve-backend #:araneida-backend #:httpd-backend #:multithread-httpd-backend #:*inspect-components* #:external-format-for #:*default-server* #:standard-server #:startup-server #:shutdown-server #:restart-server #:server.backend #:server.applications #:debug-on-error #:javascript-debug-level #:*debug-on-error* #:*context* #:context.window-component #:context.request #:context.response #:context.session #:context.application #:with-dummy-context #:make-request-context #:startup-application #:shutdown-application #:restart-application #:register-application #:unregister-application #:*default-application* #:standard-application #:cookie-session-application #:cookie-session-request-context #:lock-of #:with-lock-held-on-application #:with-lock-held-on-current-application #:with-lock-held-on-session #:register-client-state #:cookie-session-application-mixin #:secure-application-mixin #:l10n-application-mixin #:single-frame-application-mixin #:dirty-component-tracking-application-mixin #:request-context-class #:session-class #:user-track-application-mixin #:application.online-users #:mime-part-p #:mime-part-headers #:mime-part-body #:request #:response #:html-stream #:close-request #:get-header #:get-parameter #:map-parameters #:send-headers #:send-response #:serve-sequence #:backtrack #:backtrack-slot #:defcomponent #:compute-url #:update-url #:standard-component-class #:component #:parent #:widget-component #:standard-component #:template-component #:template-component-environment #:simple-template-component #:show #:show-window #:html-element #:widget-component #:inline-widget-component #:css-class #:css-style #:child-components #:component.place #:session-of #:widget-id #:dojo-widget #:add-onload-script #:simple-dojo-widget #:dojo-content-pane #:dojo-tab-container #:dojo-tab #:dojo-date-picker #:dojo-time-picker #:dojo-dropdown-date-picker #:dojo-dropdown-time-picker #:dojo-timestamp-picker #:ajax-render-new-tab #:dojo-split-container #:rendering-dojo-tooltip-for #:window-component #:simple-window-component #:basic-window-features-mixin #:window-component.icon #:window-component.stylesheet #:window-component.javascript #:window-component.title #:window-component.content-type generic componet actions #:refresh-component #:ok #:meta-refresh #:error-message #:error-component #:login #:login.username #:login.password #:try-login #:check-credentials #:login-successful #:collapsible-pane #:collapsedp #:render-standard-switch #:info-message #:option-dialog #:respond #:container #:switching-container #:list-container #:make-list-container #:component-at #:add-component #:remove-component #:clear-container #:container.current-component-key #:container.current-component #:container.key-test #:container.contents #:switch-component #:find-component #:initialize-container #:ajax-component-mixin #:render-nearest-ajax-component #:render-ajax-stub #:ajax-render #:dirtyp #:visiblep #:mark-dirty #:without-dirtyness-tracking #:js-server-callback #:ucw-inspector #:inspect-anchor #:form-field #:generic-html-input #:dom-id #:value #:client-value #:tabindex #:simple-form #:string-field #:textarea-field #:number-field #:integer-field #:password-field #:checkbox-field #:file-upload-field #:select-field #:mapping-select-field #:alist-select-field #:hash-table-select-field #:plist-select-field #:submit-button #:radio-group #:value-widget #:in-field-string-field #:date-field #:date-ymd #:is-a-date-validator #:is-a-date-time-validator #:time-range-validator #:dmy-date-field #:mdy-date-field #:validator #:validators #:generate-javascript #:generate-javascript-check #:javascript-check #:generate-javascript-valid-handler #:javascript-valid-handler #:generate-javascript-invalid-handler #:javascript-invalid-handler #:validp #:is-an-integer-validator #:number-range-validator #:length-validator #:min-length #:max-length #:not-empty-validator #:string=-validator #:integer-range-validator #:regex-validator #:regex #:hostname-validator #:e-mail-address-validator #:phone-number-validator #:range-view #:render-range-view-item #:range-view.current-window #:range-view.current-window-items #:range-view.windows #:range-view.have-next-p #:range-view.have-previous-p #:generic-date-picker #:dropdown-date-picker #:date-picker.year #:date-picker.day #:date-picker.month #:date-picker.partial-date-p #:date-picker.complete-date-p #:redirect-component #:send-redirect #:tabbed-pane #:task-component #:start #:status-bar #:add-message #:show-message #:cached-component #:cached-output #:timeout #:component-dirty-p #:refresh-component-output #:timeout-cache-component #:num-hits-cache-component #:transaction-mixin #:open-transaction #:close-transaction #:secure-application-mixin #:secure-application-p #:application-find-user #:application-check-password #:application-authorize-call #:on-authorization-reject #:session-user #:session-authenticated-p #:user-login #:login-user #:logout-user #:exit-user #:defaction #:defentry-point #:self #:call #:call-component #:call-as-window #:answer #:answer-component #:jump #:jump-to-component #:make-place #:action-href #:action-href-body #:handle-raw-request #:handle-ajax-request #:action-id #:minimal-dispatcher #:make-minimal-dispatcher #:simple-dispatcher #:make-simple-dispatcher #:url-dispatcher #:make-url-dispatcher #:regexp-dispatcher #:make-regexp-dispatcher #:action-dispatcher #:*dispatcher-registers* #:tal-dispatcher #:parenscript-dispatcher #:make-parenscript-dispatcher #:make-standard-ucw-dispatchers #:make-standard-ucw-www-root-list #:make-standard-ucw-tal-dir-list #:with-request-params #:get-session-value #:session.value #:make-new-session #:with-session-variables #:register-action #:register-ajax-action #:make-action #:make-action-body #:register-callback #:make-callback #:register-submit-callback #:inside-a-form-p #:current-form-id #:l10n-application #:reload-ucw-resources #:application.default-locale #:application.accepted-locales #:l10n-request-context #:context.locale #:l10n-tal-generator #:+missing-resource-css-class+ #:enable-js-sharpquote-reader #:enable-sharpquote<>-reader #:with-sharpquote<>-syntax #:define-js-resources yaclml / tal #:*ucw-tal-root* #:render #:render-template #:publish-directory #:read-from-client-string #:start-swank #:create-server #:hello #:bye-bye)) (defpackage :it.bese.ucw-user (:nicknames :ucw-user) (:shadowing-import-from :trivial-garbage #:make-hash-table) (:shadowing-import-from :ucw #:parent) (:use :common-lisp :it.bese.ucw :it.bese.arnesi :iterate :local-time :bordeaux-threads :trivial-garbage :cl-l10n :it.bese.yaclml)) (defpackage :it.bese.ucw.lang (:nicknames :ucw.lang) (:import-from :ucw #:+missing-resource-css-class+ #:define-js-resources) (:export #:+missing-resource-css-class+ #:define-js-resources)) (defpackage :it.bese.ucw.tags (:documentation "UCW convience tags.") (:use) (:nicknames #:<ucw) (:export #:render-component #:a #:area #:form #:input #:button #:simple-select #:select #:option #:textarea #:integer-range-select #:month-day-select #:month-select #:text #:password #:submit #:simple-form #:simple-submit #:localized #:script)) @include " rerl / conditions.lisp " Copyright ( c ) 2003 - 2005 - Neither the name of , nor , nor the names " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
18053021e625cf4b02e30fc290c55395c6daba253b132f6e136ce7614e64f5ba
OCamlPro/techelson
clap.ml
(* CLAP stuff. *) open Base open Base.Common (** Type of arguments and modes descriptions. *) type description = formatter -> unit -> unit (** Exception thrown when `help` is asked. *) exception PrintHelp of Conf.mode (** Types and helper functions for the type of values accepted by arguments. *) module Value = struct (** Aggregates descriptors for values. *) module Desc = struct (** Description of the value expected for a string. *) let string_val_desc : string = "<string>" (** Description of the values expected for a boolean value. *) let bool_val_desc : string = "(on|true|True|no|off|false|False)" (** Description of the values expected for an integer value. *) let int_val_desc : string = "<int>" end (** Types and functions for the types of values. *) module Typ = struct (** Types of values the arguments can accept. *) type val_typ = | String (** Type of string values. *) | Bool (** Type of bool values. *) | Int (** Type of int values. *) (** Types of values the arguments can accept, with an `optional` flag. *) type t = { typ : val_typ ; (** Type of the values. *) opt : bool ; (** True if the argument is optional. *) } (** Value type constructor. Boolean argument specifies whether the argument is optional or not. *) let mk (opt : bool) (typ : val_typ) : t = { typ ; opt } (** Integer value type. Boolean argument specifies whether the argument is optional or not. *) let int (opt : bool) : t = mk opt Int (** String value type. Boolean argument specifies whether the argument is optional or not. *) let string (opt : bool) : t = mk opt String (** Bool value type. Boolean argument specifies whether the argument is optional or not. *) let bool (opt : bool) : t = mk opt Bool (** Formatter for `val_typ`. *) let fmt_val_typ (fmt : formatter) (val_typ : val_typ) : unit = match val_typ with | String -> fprintf fmt "%s" Desc.string_val_desc | Bool -> fprintf fmt "%s" Desc.bool_val_desc | Int -> fprintf fmt "%s" Desc.int_val_desc (** Formatter for `t`. *) let fmt (fmt : formatter) (self : t) : unit = fmt_val_typ fmt self.typ; if self.opt then fprintf fmt "?" end (** Conversions from string to a value. *) module To = struct (** Retrieves a boolean from a string. *) let bool (s : string) : bool = match s with | "on" | "true" | "True" -> true | "off" | "no" | "false" | "False" -> false | s -> Exc.throws [ sprintf "expected a boolean value %s" Desc.bool_val_desc ; sprintf "found `%s`" s ] (** Retrieves an integer from a string. *) let int (s : string) : int = (fun () -> int_of_string s) |> Exc.chain_err ( fun () -> sprintf "expected integer, found `%s`" s ) end end module Arg = struct (** Arguments: short (flag) or long. *) type t = | Short of char (** Flag: `-v`. *) | Long of string (** Option: `--verb`. *) | Val of string (** Value: some string. *) | Comma (** A comma separator. *) | Sep of string list (** Separator: everything after this point are values. Values appearing in this thing cannot be option arguments. *) | Mode of string (** Mode. *) let _fmt (fmt : formatter) (self : t) : unit = match self with | Short c -> fprintf fmt "(short '%c')" c | Long s -> fprintf fmt "(long \"%s\")" s | Val s -> fprintf fmt "(val \"%s\")" s | Comma -> fprintf fmt "comma" | Sep _ -> fprintf fmt "(sep ...)" | Mode s -> fprintf fmt "(mode \"%s\")" s (** Returns the head if it is a value, none otherwise. *) let next_value (l : t list) : string option * t list = match l with | (Val v) :: tail -> Some v, tail | _ -> None, l (** Returns the next value as a boolean. This function fails if the next value cannot be cast to a boolean. *) let next_bool_value (l : t list) : bool option * t list = let next, tail = next_value l in next |> Opt.map Value.To.bool, tail (** Returns the next value as an integer. This function fails if the next value cannot be cast to an integer. *) let next_int_value (l : t list) : int option * t list = let next, tail = next_value l in next |> Opt.map Value.To.int, tail (** Returns the next value if the list is a comma and a value. *) let next_sep_value (l : t list) : string option * t list = match l with | Comma :: (Val v) :: tail -> Some v, tail | _ -> None, l end module Cla = struct (** Type of command line arguments. *) type t = { short : char list; (** Short name of the argument. *) long : string list; (** Long name of the argument.*) values : Value.Typ.t list; (** Description of the values accepted by this argument. *) action : Arg.t list -> Conf.t -> Arg.t list; (** Effect of the argument on the configuration. *) help : description (** Help message. Does not include the description of the values the argument takes. *) } (** Argument constructor. *) let mk (short : char list) (long : string list) (values : Value.Typ.t list) (help : description) (action : Arg.t list -> Conf.t -> Arg.t list) : t = { short ; long ; values ; action ; help } (** Maps long/short arguments to the action they cause. *) type options = { long_map : (string, Arg.t list -> Conf.t -> Arg.t list) Hashtbl.t ; short_map : (char, Arg.t list -> Conf.t -> Arg.t list) Hashtbl.t ; } let empty_options () = { short_map = Hashtbl.create ~random:false 101 ; long_map = Hashtbl.create ~random:false 101 ; } let help : t = mk ['h'] ["help"] [] ( fun fmt () -> fprintf fmt "prints this help message" ) ( fun _ conf -> PrintHelp conf.mode |> raise ) let verb : t = mk ['v'] ["verb"] [Value.Typ.int true] ( fun fmt () -> fprintf fmt "increases or sets verbosity [default: %i]" (Conf.default ()).verb ) ( fun args conf -> match Arg.next_int_value args with | None, tail -> conf.verb <- conf.verb + 1; tail | Some i, tail -> conf.verb <- i; tail ) let quiet : t = mk ['q'] [] [] ( fun fmt () -> fprintf fmt "decreases verbosity" ) ( fun args conf -> conf.verb <- conf.verb - 1; args ) let step : t = mk ['s'] ["step"] [Value.Typ.bool true] ( fun fmt () -> fprintf fmt "(de)activates step-by-step evaluation [default: %b]" (Conf.default ()).step ) ( fun args conf -> let next, tail = Arg.next_bool_value args in match next with | None | Some true -> conf.step <- true; tail | Some false -> conf.step <- false; tail ) let skip : t = mk [] ["skip"] [Value.Typ.bool true] ( fun fmt () -> fprintf fmt "\ if true, all steps will automatically advance (and `--step` will be set to@ \ false) [default: %b]\ " (Conf.default ()).skip ) ( fun args conf -> let next, tail = Arg.next_bool_value args in match next with | None | Some true -> conf.skip <- true; conf.step <- false; tail | Some false -> conf.skip <- false; tail ) let contract : t = mk [] [ "contract" ] [Value.Typ.string false ; Value.Typ.string true] ( fun fmt () -> fprintf fmt "\ adds a contract to the test environment. The second optional argument is the@ \ contract's initializer.\ " ) ( fun args conf -> match Arg.next_value args with | None, _ -> Exc.throw ( "argument `--contract` expects at least one value" ) | Some file, tail -> let (init, tail) = Arg.next_sep_value tail in conf.contracts <- conf.contracts @ [ Conf.mk_contract file init ]; tail ) let options : t list = [ help ; verb ; quiet ; step ; skip ; contract ] let add_all (opts : options) (options : t list) = options |> List.iter ( fun { short ; long ; action ; _ } -> short |> List.iter ( fun (c : char) -> Hashtbl.add opts.short_map c action ); long |> List.iter ( fun (s : string) -> Hashtbl.add opts.long_map s action ); ) (* CLAP modes. *) module Modes = struct Testgen options . module Testgen = struct let test_count : t = mk ['n'] ["count"] [Value.Typ.int false] ( fun fmt () -> fprintf fmt "sets the number of testcases to generate [default: %i]" (Conf.default_testgen_mode ()).count ) ( fun args conf -> match Arg.next_int_value args with | None , _ -> Exc.throw ( "argument `--count` expects at least one value" ) | Some count, tail -> conf |> Conf.map_testgen_mode (fun conf -> conf.count <- count); tail ) let options : t list = [ help ; test_count ] let name : string = "testgen" let description (fmt : formatter) () : unit = fprintf fmt "activates and controls test generation" end let testgen : string * description * options * Conf.mode = let opts = empty_options () in add_all opts Testgen.options; Testgen.name, Testgen.description, opts, Conf.Testgen (Conf.default_testgen_mode ()) let all : (string * description * options * Conf.mode) list = [ testgen ] let add_all (modes : (string, (Conf.mode * options)) Hashtbl.t) : unit = all |> List.iter ( fun (name, _, options, mode) -> Hashtbl.add modes name (mode, options) ) end end (* Command line arguments. *) let args : string list = (Array.length Sys.argv) - 1 |> Array.sub Sys.argv 1 |> Array.to_list (* Options. *) let options : Cla.options = let opts = Cla.empty_options () in Cla.add_all opts Cla.options; opts (* Option modes. *) let modes : (string, (Conf.mode * Cla.options)) Hashtbl.t = let opts = Hashtbl.create ~random:false 101 in Cla.Modes.add_all opts; opts Preprocesses arguments to split arguments . Splits aggregated flags ` -vvvafg ` in ` ( short v ) : : ( short v ) : : ... ` . Splits aggregated flags `-vvvafg` in `(short v) :: (short v) :: ...`. *) let split_args (args : string list) : Arg.t list = (* Splits flags. The string must not have the `-` prefix for flags. *) let split_flags (acc : Arg.t list) (s : string) : Arg.t list = let rec loop (acc : Arg.t list) (cursor : int) (s : string) = if cursor >= String.length s then ( acc ) else ( let acc = (Arg.Short (String.get s cursor)) :: acc in loop acc (cursor + 1) s ) in loop acc 0 s in (* Actual short/long splitting. *) let rec loop (acc : Arg.t list) : string list -> Arg.t list = function | [] -> List.rev acc | "--" :: tail -> [ Arg.Sep tail ] |> List.rev_append acc | "," :: tail -> loop (Arg.Comma :: acc) tail | head :: tail -> ( let head, comma_trail = let head_len = String.length head in if head_len > 0 && String.sub head (head_len - 1) 1 = "," then ( String.sub head 0 (head_len - 1), true ) else ( head, false ) in let acc = if String.length head > 1 && String.get head 0 = '-' && String.get head 1 = '-' then ( let offset = 2 in let (start, finsh) = (offset, (String.length head - offset)) in (Arg.Long (String.sub head start finsh)) :: acc ) else if String.length head > 0 && String.get head 0 = '-' then ( let offset = 1 in let (start, finsh) = (offset, (String.length head - offset)) in String.sub head start finsh |> split_flags acc ) else if Hashtbl.mem modes head then ( Arg.Mode head :: acc ) else ( (Arg.Val head) :: acc ) in let acc = if comma_trail then Arg.Comma :: acc else acc in loop acc tail ) in loop [] args (* Handles a list of arguments. *) let rec handle_args (options : Cla.options) (conf : Conf.t) (args : Arg.t list) : Conf.t = let rec loop (args : Arg.t list) : Conf.t = match args with | [] -> ( conf.args <- List.rev conf.args; conf ) (* Comma should be eaten by options. *) | Arg.Comma :: _ -> ( Exc.throw "unexpected comma separator" ) (* Value that was not eaten by an option. Add to configuration's args. *) | (Arg.Val s) :: tail -> ( conf.args <- s :: conf.args; loop tail ) (* Flag, does not take arguments. *) | (Arg.Short c) :: tail -> (match Hashtbl.find_opt options.short_map c with | Some action -> (* Feed tail arguments, get new tail back. *) let tail = (fun () -> action tail conf) |> Exc.chain_err ( fun () -> asprintf "while processing short argument `-%c`" c ) in loop tail | None -> sprintf "unknown flag `-%c`" c |> Exc.throw ) (* Option, expected to take arguments. *) | (Arg.Long s) :: tail -> (match Hashtbl.find_opt options.long_map s with | Some action -> (* Feed tail arguments, get new tail back. *) let tail = (fun () -> action tail conf) |> Exc.chain_err ( fun () -> asprintf "while processing long argument `--%s`" s ) in loop tail | None -> sprintf "unknown option `--%s`" s |> Exc.throw ) | (Sep vals) :: tail -> ( assert (tail = []); conf.args <- List.rev_append conf.args vals; conf ) | (Mode mode_name) :: tail -> ( let mode, options = try Hashtbl.find modes mode_name with | Not_found -> sprintf "unknown mode `%s`" mode_name |> Exc.throw in Conf.set_mode mode conf; (fun () -> handle_args options conf tail) |> Exc.chain_err ( fun () -> asprintf "while processing options for mode %s" mode_name ) ) in loop args (** Formats some options. *) let rec fmt_options (fmt : formatter) (opts : Cla.t list) : unit = match opts with | { short ; long ; values ; help ; _ } :: opts -> ( fprintf fmt "@ @[<v 4>"; (* Returns `true` if `shorts` is empty. Used as `is_first` for `fmt_long`. *) let fmt_shorts (shorts : char list) : bool = let rec loop (shorts : char list) (is_first : bool) : bool = match shorts with | short :: shorts -> ( if not is_first then fprintf fmt ", "; fprintf fmt "-%c" short; loop shorts false ) | [] -> is_first in loop shorts true in (* Formats a list of values. *) let fmt_values (fmt : formatter) (values : Value.Typ.t list) = let rec loop (values : Value.Typ.t list) (is_first : bool) : unit = match values with | value :: values -> ( if not is_first then fprintf fmt " ','"; fprintf fmt " %a" Value.Typ.fmt value; loop values false ) | [] -> () in loop values true in let rec fmt_long (longs : string list) (is_first : bool) = match longs with | name :: longs -> ( if not is_first then fprintf fmt ", "; fprintf fmt "--%s" name; fmt_long longs false ) | [] -> () in fmt_shorts short |> fmt_long long; fmt_values fmt values; fprintf fmt "@ @[<v>%a@]" help (); fprintf fmt "@]"; fmt_options fmt opts ) | [] -> () (** Prints the test generation usage message. *) let print_testgen_usage (fmt : formatter) () : unit = fprintf fmt "%s [OPTIONS] testgen [TESTGEN_OPTIONS] [-- DIR]?" Sys.argv.(0) (** Prints the test generation help message. *) let print_testgen_help (fmt : formatter) : unit = fprintf fmt "\ Generates testcases for some contract(s). If a directory is provided, the testcases will@.\ be dumped there. Otherwise techelson will just run the testcases it generated.@.\ "; fprintf fmt "@.@[<v 4>USAGE:@ %a@]@." print_testgen_usage (); fprintf fmt "@.@[<v 4>TESTGEN_OPTIONS:"; fmt_options fmt Cla.Modes.Testgen.options; fprintf fmt "@]@." (** Prints the top (no mode) help message. *) let print_top_help (fmt : formatter) : unit = fprintf fmt "@[<v>techelson v%a@ @ \ @[<v 4>USAGE:@ \ %s [OPTIONS] -- [FILES]*@ \ %a\ @]\ @]@." Version.fmt Version.current Sys.argv.(0) print_testgen_usage (); fprintf fmt "@.@[<v 4>OPTIONS:"; fmt_options fmt Cla.options; fprintf fmt "@]@."; fprintf fmt "@.@[<v 4>MODES:"; let rec loop (modes : (string * description * Cla.options * Conf.mode) list) : unit = match modes with | (name, desc, _, _) :: modes -> ( fprintf fmt "@ @[<v 4>%s@ %a@]" name desc (); loop modes ) | [] -> () in loop Cla.Modes.all; fprintf fmt "@ \ run `%s <MODE> --help` to obtain help on a specific mode. For example: `%s testgen --help`\ " Sys.argv.(0) Sys.argv.(0); fprintf fmt "@]@." (** Prints the help message for a mode. *) let print_help (mode : Conf.mode) : unit = match mode with | Conf.Inactive -> formatter_of_out_channel stdout |> print_top_help | Conf.Testgen _ -> formatter_of_out_channel stdout |> print_testgen_help (* Runs CLAP on custom arguments. *) let run_on (args : string list) : Conf.t = try args |> split_args |> handle_args options (Conf.default ()) with | Exc.Exc (Exc.Error (_, Some (PrintHelp mode), _)) | PrintHelp mode -> ( print_help mode; exit 0 ) | e -> ( (fun () -> raise e) |> Exc.catch_print |> ignore; printf "@."; print_help Conf.Inactive; exit 2 ) (* Runs CLAP on CLAs. *) let run () : Conf.t = run_on args (* Sets the configuration in `Common`. *) let set_conf () : unit = let chained : unit -> Conf.t = fun () -> Exc.chain_err ( fun () -> "while parsing command-line arguments" ) (fun () -> run ()) in Exc.catch_fail chained |> Base.Common.set_conf
null
https://raw.githubusercontent.com/OCamlPro/techelson/932fbf08675cd13d34a07e3b3d77234bdafcf5bc/src/clap.ml
ocaml
CLAP stuff. * Type of arguments and modes descriptions. * Exception thrown when `help` is asked. * Types and helper functions for the type of values accepted by arguments. * Aggregates descriptors for values. * Description of the value expected for a string. * Description of the values expected for a boolean value. * Description of the values expected for an integer value. * Types and functions for the types of values. * Types of values the arguments can accept. * Type of string values. * Type of bool values. * Type of int values. * Types of values the arguments can accept, with an `optional` flag. * Type of the values. * True if the argument is optional. * Value type constructor. Boolean argument specifies whether the argument is optional or not. * Integer value type. Boolean argument specifies whether the argument is optional or not. * String value type. Boolean argument specifies whether the argument is optional or not. * Bool value type. Boolean argument specifies whether the argument is optional or not. * Formatter for `val_typ`. * Formatter for `t`. * Conversions from string to a value. * Retrieves a boolean from a string. * Retrieves an integer from a string. * Arguments: short (flag) or long. * Flag: `-v`. * Option: `--verb`. * Value: some string. * A comma separator. * Separator: everything after this point are values. Values appearing in this thing cannot be option arguments. * Mode. * Returns the head if it is a value, none otherwise. * Returns the next value as a boolean. This function fails if the next value cannot be cast to a boolean. * Returns the next value as an integer. This function fails if the next value cannot be cast to an integer. * Returns the next value if the list is a comma and a value. * Type of command line arguments. * Short name of the argument. * Long name of the argument. * Description of the values accepted by this argument. * Effect of the argument on the configuration. * Help message. Does not include the description of the values the argument takes. * Argument constructor. * Maps long/short arguments to the action they cause. CLAP modes. Command line arguments. Options. Option modes. Splits flags. The string must not have the `-` prefix for flags. Actual short/long splitting. Handles a list of arguments. Comma should be eaten by options. Value that was not eaten by an option. Add to configuration's args. Flag, does not take arguments. Feed tail arguments, get new tail back. Option, expected to take arguments. Feed tail arguments, get new tail back. * Formats some options. Returns `true` if `shorts` is empty. Used as `is_first` for `fmt_long`. Formats a list of values. * Prints the test generation usage message. * Prints the test generation help message. * Prints the top (no mode) help message. * Prints the help message for a mode. Runs CLAP on custom arguments. Runs CLAP on CLAs. Sets the configuration in `Common`.
open Base open Base.Common type description = formatter -> unit -> unit exception PrintHelp of Conf.mode module Value = struct module Desc = struct let string_val_desc : string = "<string>" let bool_val_desc : string = "(on|true|True|no|off|false|False)" let int_val_desc : string = "<int>" end module Typ = struct type val_typ = | String | Bool | Int type t = { typ : val_typ ; opt : bool ; } let mk (opt : bool) (typ : val_typ) : t = { typ ; opt } let int (opt : bool) : t = mk opt Int let string (opt : bool) : t = mk opt String let bool (opt : bool) : t = mk opt Bool let fmt_val_typ (fmt : formatter) (val_typ : val_typ) : unit = match val_typ with | String -> fprintf fmt "%s" Desc.string_val_desc | Bool -> fprintf fmt "%s" Desc.bool_val_desc | Int -> fprintf fmt "%s" Desc.int_val_desc let fmt (fmt : formatter) (self : t) : unit = fmt_val_typ fmt self.typ; if self.opt then fprintf fmt "?" end module To = struct let bool (s : string) : bool = match s with | "on" | "true" | "True" -> true | "off" | "no" | "false" | "False" -> false | s -> Exc.throws [ sprintf "expected a boolean value %s" Desc.bool_val_desc ; sprintf "found `%s`" s ] let int (s : string) : int = (fun () -> int_of_string s) |> Exc.chain_err ( fun () -> sprintf "expected integer, found `%s`" s ) end end module Arg = struct type t = | Short of char | Long of string | Val of string | Comma | Sep of string list | Mode of string let _fmt (fmt : formatter) (self : t) : unit = match self with | Short c -> fprintf fmt "(short '%c')" c | Long s -> fprintf fmt "(long \"%s\")" s | Val s -> fprintf fmt "(val \"%s\")" s | Comma -> fprintf fmt "comma" | Sep _ -> fprintf fmt "(sep ...)" | Mode s -> fprintf fmt "(mode \"%s\")" s let next_value (l : t list) : string option * t list = match l with | (Val v) :: tail -> Some v, tail | _ -> None, l let next_bool_value (l : t list) : bool option * t list = let next, tail = next_value l in next |> Opt.map Value.To.bool, tail let next_int_value (l : t list) : int option * t list = let next, tail = next_value l in next |> Opt.map Value.To.int, tail let next_sep_value (l : t list) : string option * t list = match l with | Comma :: (Val v) :: tail -> Some v, tail | _ -> None, l end module Cla = struct type t = { short : char list; long : string list; values : Value.Typ.t list; action : Arg.t list -> Conf.t -> Arg.t list; help : description } let mk (short : char list) (long : string list) (values : Value.Typ.t list) (help : description) (action : Arg.t list -> Conf.t -> Arg.t list) : t = { short ; long ; values ; action ; help } type options = { long_map : (string, Arg.t list -> Conf.t -> Arg.t list) Hashtbl.t ; short_map : (char, Arg.t list -> Conf.t -> Arg.t list) Hashtbl.t ; } let empty_options () = { short_map = Hashtbl.create ~random:false 101 ; long_map = Hashtbl.create ~random:false 101 ; } let help : t = mk ['h'] ["help"] [] ( fun fmt () -> fprintf fmt "prints this help message" ) ( fun _ conf -> PrintHelp conf.mode |> raise ) let verb : t = mk ['v'] ["verb"] [Value.Typ.int true] ( fun fmt () -> fprintf fmt "increases or sets verbosity [default: %i]" (Conf.default ()).verb ) ( fun args conf -> match Arg.next_int_value args with | None, tail -> conf.verb <- conf.verb + 1; tail | Some i, tail -> conf.verb <- i; tail ) let quiet : t = mk ['q'] [] [] ( fun fmt () -> fprintf fmt "decreases verbosity" ) ( fun args conf -> conf.verb <- conf.verb - 1; args ) let step : t = mk ['s'] ["step"] [Value.Typ.bool true] ( fun fmt () -> fprintf fmt "(de)activates step-by-step evaluation [default: %b]" (Conf.default ()).step ) ( fun args conf -> let next, tail = Arg.next_bool_value args in match next with | None | Some true -> conf.step <- true; tail | Some false -> conf.step <- false; tail ) let skip : t = mk [] ["skip"] [Value.Typ.bool true] ( fun fmt () -> fprintf fmt "\ if true, all steps will automatically advance (and `--step` will be set to@ \ false) [default: %b]\ " (Conf.default ()).skip ) ( fun args conf -> let next, tail = Arg.next_bool_value args in match next with | None | Some true -> conf.skip <- true; conf.step <- false; tail | Some false -> conf.skip <- false; tail ) let contract : t = mk [] [ "contract" ] [Value.Typ.string false ; Value.Typ.string true] ( fun fmt () -> fprintf fmt "\ adds a contract to the test environment. The second optional argument is the@ \ contract's initializer.\ " ) ( fun args conf -> match Arg.next_value args with | None, _ -> Exc.throw ( "argument `--contract` expects at least one value" ) | Some file, tail -> let (init, tail) = Arg.next_sep_value tail in conf.contracts <- conf.contracts @ [ Conf.mk_contract file init ]; tail ) let options : t list = [ help ; verb ; quiet ; step ; skip ; contract ] let add_all (opts : options) (options : t list) = options |> List.iter ( fun { short ; long ; action ; _ } -> short |> List.iter ( fun (c : char) -> Hashtbl.add opts.short_map c action ); long |> List.iter ( fun (s : string) -> Hashtbl.add opts.long_map s action ); ) module Modes = struct Testgen options . module Testgen = struct let test_count : t = mk ['n'] ["count"] [Value.Typ.int false] ( fun fmt () -> fprintf fmt "sets the number of testcases to generate [default: %i]" (Conf.default_testgen_mode ()).count ) ( fun args conf -> match Arg.next_int_value args with | None , _ -> Exc.throw ( "argument `--count` expects at least one value" ) | Some count, tail -> conf |> Conf.map_testgen_mode (fun conf -> conf.count <- count); tail ) let options : t list = [ help ; test_count ] let name : string = "testgen" let description (fmt : formatter) () : unit = fprintf fmt "activates and controls test generation" end let testgen : string * description * options * Conf.mode = let opts = empty_options () in add_all opts Testgen.options; Testgen.name, Testgen.description, opts, Conf.Testgen (Conf.default_testgen_mode ()) let all : (string * description * options * Conf.mode) list = [ testgen ] let add_all (modes : (string, (Conf.mode * options)) Hashtbl.t) : unit = all |> List.iter ( fun (name, _, options, mode) -> Hashtbl.add modes name (mode, options) ) end end let args : string list = (Array.length Sys.argv) - 1 |> Array.sub Sys.argv 1 |> Array.to_list let options : Cla.options = let opts = Cla.empty_options () in Cla.add_all opts Cla.options; opts let modes : (string, (Conf.mode * Cla.options)) Hashtbl.t = let opts = Hashtbl.create ~random:false 101 in Cla.Modes.add_all opts; opts Preprocesses arguments to split arguments . Splits aggregated flags ` -vvvafg ` in ` ( short v ) : : ( short v ) : : ... ` . Splits aggregated flags `-vvvafg` in `(short v) :: (short v) :: ...`. *) let split_args (args : string list) : Arg.t list = let split_flags (acc : Arg.t list) (s : string) : Arg.t list = let rec loop (acc : Arg.t list) (cursor : int) (s : string) = if cursor >= String.length s then ( acc ) else ( let acc = (Arg.Short (String.get s cursor)) :: acc in loop acc (cursor + 1) s ) in loop acc 0 s in let rec loop (acc : Arg.t list) : string list -> Arg.t list = function | [] -> List.rev acc | "--" :: tail -> [ Arg.Sep tail ] |> List.rev_append acc | "," :: tail -> loop (Arg.Comma :: acc) tail | head :: tail -> ( let head, comma_trail = let head_len = String.length head in if head_len > 0 && String.sub head (head_len - 1) 1 = "," then ( String.sub head 0 (head_len - 1), true ) else ( head, false ) in let acc = if String.length head > 1 && String.get head 0 = '-' && String.get head 1 = '-' then ( let offset = 2 in let (start, finsh) = (offset, (String.length head - offset)) in (Arg.Long (String.sub head start finsh)) :: acc ) else if String.length head > 0 && String.get head 0 = '-' then ( let offset = 1 in let (start, finsh) = (offset, (String.length head - offset)) in String.sub head start finsh |> split_flags acc ) else if Hashtbl.mem modes head then ( Arg.Mode head :: acc ) else ( (Arg.Val head) :: acc ) in let acc = if comma_trail then Arg.Comma :: acc else acc in loop acc tail ) in loop [] args let rec handle_args (options : Cla.options) (conf : Conf.t) (args : Arg.t list) : Conf.t = let rec loop (args : Arg.t list) : Conf.t = match args with | [] -> ( conf.args <- List.rev conf.args; conf ) | Arg.Comma :: _ -> ( Exc.throw "unexpected comma separator" ) | (Arg.Val s) :: tail -> ( conf.args <- s :: conf.args; loop tail ) | (Arg.Short c) :: tail -> (match Hashtbl.find_opt options.short_map c with | Some action -> let tail = (fun () -> action tail conf) |> Exc.chain_err ( fun () -> asprintf "while processing short argument `-%c`" c ) in loop tail | None -> sprintf "unknown flag `-%c`" c |> Exc.throw ) | (Arg.Long s) :: tail -> (match Hashtbl.find_opt options.long_map s with | Some action -> let tail = (fun () -> action tail conf) |> Exc.chain_err ( fun () -> asprintf "while processing long argument `--%s`" s ) in loop tail | None -> sprintf "unknown option `--%s`" s |> Exc.throw ) | (Sep vals) :: tail -> ( assert (tail = []); conf.args <- List.rev_append conf.args vals; conf ) | (Mode mode_name) :: tail -> ( let mode, options = try Hashtbl.find modes mode_name with | Not_found -> sprintf "unknown mode `%s`" mode_name |> Exc.throw in Conf.set_mode mode conf; (fun () -> handle_args options conf tail) |> Exc.chain_err ( fun () -> asprintf "while processing options for mode %s" mode_name ) ) in loop args let rec fmt_options (fmt : formatter) (opts : Cla.t list) : unit = match opts with | { short ; long ; values ; help ; _ } :: opts -> ( fprintf fmt "@ @[<v 4>"; let fmt_shorts (shorts : char list) : bool = let rec loop (shorts : char list) (is_first : bool) : bool = match shorts with | short :: shorts -> ( if not is_first then fprintf fmt ", "; fprintf fmt "-%c" short; loop shorts false ) | [] -> is_first in loop shorts true in let fmt_values (fmt : formatter) (values : Value.Typ.t list) = let rec loop (values : Value.Typ.t list) (is_first : bool) : unit = match values with | value :: values -> ( if not is_first then fprintf fmt " ','"; fprintf fmt " %a" Value.Typ.fmt value; loop values false ) | [] -> () in loop values true in let rec fmt_long (longs : string list) (is_first : bool) = match longs with | name :: longs -> ( if not is_first then fprintf fmt ", "; fprintf fmt "--%s" name; fmt_long longs false ) | [] -> () in fmt_shorts short |> fmt_long long; fmt_values fmt values; fprintf fmt "@ @[<v>%a@]" help (); fprintf fmt "@]"; fmt_options fmt opts ) | [] -> () let print_testgen_usage (fmt : formatter) () : unit = fprintf fmt "%s [OPTIONS] testgen [TESTGEN_OPTIONS] [-- DIR]?" Sys.argv.(0) let print_testgen_help (fmt : formatter) : unit = fprintf fmt "\ Generates testcases for some contract(s). If a directory is provided, the testcases will@.\ be dumped there. Otherwise techelson will just run the testcases it generated.@.\ "; fprintf fmt "@.@[<v 4>USAGE:@ %a@]@." print_testgen_usage (); fprintf fmt "@.@[<v 4>TESTGEN_OPTIONS:"; fmt_options fmt Cla.Modes.Testgen.options; fprintf fmt "@]@." let print_top_help (fmt : formatter) : unit = fprintf fmt "@[<v>techelson v%a@ @ \ @[<v 4>USAGE:@ \ %s [OPTIONS] -- [FILES]*@ \ %a\ @]\ @]@." Version.fmt Version.current Sys.argv.(0) print_testgen_usage (); fprintf fmt "@.@[<v 4>OPTIONS:"; fmt_options fmt Cla.options; fprintf fmt "@]@."; fprintf fmt "@.@[<v 4>MODES:"; let rec loop (modes : (string * description * Cla.options * Conf.mode) list) : unit = match modes with | (name, desc, _, _) :: modes -> ( fprintf fmt "@ @[<v 4>%s@ %a@]" name desc (); loop modes ) | [] -> () in loop Cla.Modes.all; fprintf fmt "@ \ run `%s <MODE> --help` to obtain help on a specific mode. For example: `%s testgen --help`\ " Sys.argv.(0) Sys.argv.(0); fprintf fmt "@]@." let print_help (mode : Conf.mode) : unit = match mode with | Conf.Inactive -> formatter_of_out_channel stdout |> print_top_help | Conf.Testgen _ -> formatter_of_out_channel stdout |> print_testgen_help let run_on (args : string list) : Conf.t = try args |> split_args |> handle_args options (Conf.default ()) with | Exc.Exc (Exc.Error (_, Some (PrintHelp mode), _)) | PrintHelp mode -> ( print_help mode; exit 0 ) | e -> ( (fun () -> raise e) |> Exc.catch_print |> ignore; printf "@."; print_help Conf.Inactive; exit 2 ) let run () : Conf.t = run_on args let set_conf () : unit = let chained : unit -> Conf.t = fun () -> Exc.chain_err ( fun () -> "while parsing command-line arguments" ) (fun () -> run ()) in Exc.catch_fail chained |> Base.Common.set_conf
935efd18f3641dc3b553b77d9954df7281dbf9d06ed514ae6601162e84c5a3eb
mistupv/cauder-core
tcp-fixed2.erl
-module('tcp-fixed2'). -export([main/0, server_fun/3, client_fun/4, ack/5]). main() -> Server_PID = spawn(?MODULE, server_fun, [self(), 50, 500]), spawn(?MODULE, client_fun, [Server_PID, 57, 100, client1]), spawn(?MODULE, client_fun, [Server_PID, 50, 200, client2]), receive {data,D} -> D end. server_fun(Main_PID, Port, Seq) -> receive {Client_PID, {syn, Port, SeqCl}} -> Ack_PID = spawn(?MODULE, ack, [Main_PID, Port, SeqCl+1, Seq+1, Client_PID]), Client_PID ! {Ack_PID, {syn_ack, SeqCl+1, Seq}}, server_fun(Main_PID, Port, Seq+1); {Client_PID, {syn, _, _}} -> Client_PID ! rst, server_fun(Main_PID,Port,Seq+1) end. ack(Main_PID, Port, Ack, Seq, Client_PID) -> receive {Client_PID, {ack, Port, Seq, Ack}} -> receive {Client_PID, {data, Port, D}} -> Main_PID ! {data, D}; _ -> Main_PID ! {data, error_data} end; _ -> Main_PID ! {data, error_ack} end. client_fun(Server_PID, Port, Seq, Data) -> Server_PID ! {self(), {syn, Port, Seq}}, syn_ack(Port, Data, Seq+1). syn_ack(Port, Data, Ack) -> receive rst -> {port_rejected, Port} ; {Ack_PID, {syn_ack, Ack, Seq}} -> Ack_PID ! {self(), {ack, Port, Seq+1, Ack}}, Ack_PID ! {self(), {data, Port, Data}}, {Seq+1, Ack, Port, Data} end.
null
https://raw.githubusercontent.com/mistupv/cauder-core/b676fccd1bbd629eb63f3cb5259f7a9a8c6da899/case-studies/tcp/tcp-fixed2.erl
erlang
-module('tcp-fixed2'). -export([main/0, server_fun/3, client_fun/4, ack/5]). main() -> Server_PID = spawn(?MODULE, server_fun, [self(), 50, 500]), spawn(?MODULE, client_fun, [Server_PID, 57, 100, client1]), spawn(?MODULE, client_fun, [Server_PID, 50, 200, client2]), receive {data,D} -> D end. server_fun(Main_PID, Port, Seq) -> receive {Client_PID, {syn, Port, SeqCl}} -> Ack_PID = spawn(?MODULE, ack, [Main_PID, Port, SeqCl+1, Seq+1, Client_PID]), Client_PID ! {Ack_PID, {syn_ack, SeqCl+1, Seq}}, server_fun(Main_PID, Port, Seq+1); {Client_PID, {syn, _, _}} -> Client_PID ! rst, server_fun(Main_PID,Port,Seq+1) end. ack(Main_PID, Port, Ack, Seq, Client_PID) -> receive {Client_PID, {ack, Port, Seq, Ack}} -> receive {Client_PID, {data, Port, D}} -> Main_PID ! {data, D}; _ -> Main_PID ! {data, error_data} end; _ -> Main_PID ! {data, error_ack} end. client_fun(Server_PID, Port, Seq, Data) -> Server_PID ! {self(), {syn, Port, Seq}}, syn_ack(Port, Data, Seq+1). syn_ack(Port, Data, Ack) -> receive rst -> {port_rejected, Port} ; {Ack_PID, {syn_ack, Ack, Seq}} -> Ack_PID ! {self(), {ack, Port, Seq+1, Ack}}, Ack_PID ! {self(), {data, Port, Data}}, {Seq+1, Ack, Port, Data} end.
552a274cb46c1bb12bc7e8b90d47a227255c131e87ed17b58599d6c3bd0bb80c
racket/redex
rvm-15.rkt
#lang racket/base (require redex/benchmark "util.rkt" redex/reduction-semantics) (provide (all-defined-out)) (define the-error "neglected to restrict case-lam to accept only 'val' arguments") (define-rewrite bug15v ((verify (case-lam (name l (lam (val ellipsis1) (n ellipsis2) e)) ellipsis3) s n_l b γ η f) . rest) ==> ((verify (case-lam (name l (lam (τ ellipsis1) (n ellipsis2) e)) ellipsis3) s n_l b γ η f) . rest) #:context (define-metafunction) #:variables (rest ellipsis1 ellipsis2 ellipsis3) #:exactly-once) (define-rewrite bug15rt `(case-lam ,@(map (curry recur depth #f) ls)) ==> `(case-lam ,@(map (curry recur depth #t) ls)) #:context (match) #:exactly-once) (define-rewrite bug15-jdg [(lam-verified?* ((lam τl nl e) el) sl m) (vals τl) (lam-verified? (lam τl nl e) sl m) (lam-verified?* el sl m)] ==> [(lam-verified?* ((lam τl nl e) el) sl m) (lam-verified? (lam τl nl e) sl m) (lam-verified?* el sl m)] #:context (define-judgment-form) #:exactly-once) (include/rewrite (lib "redex/examples/racket-machine/grammar.rkt") grammar) (include/rewrite (lib "redex/examples/racket-machine/verification.rkt") verification bug15v) (include/rewrite (lib "redex/examples/racket-machine/randomized-tests.rkt") randomized-tests rt-rw bug15rt) (include/rewrite (lib "redex/benchmark/models/rvm/verif-jdg.rkt") verif-jdg bug15-jdg) (include/rewrite "generators.rkt" generators bug-mod-rw) (define small-counter-example '(let-one 42 (boxenv 0 (application (case-lam (lam (ref) () (loc-box 0))) (loc-box 1))))) (test small-counter-example)
null
https://raw.githubusercontent.com/racket/redex/4c2dc96d90cedeb08ec1850575079b952c5ad396/redex-benchmark/redex/benchmark/models/rvm/rvm-15.rkt
racket
#lang racket/base (require redex/benchmark "util.rkt" redex/reduction-semantics) (provide (all-defined-out)) (define the-error "neglected to restrict case-lam to accept only 'val' arguments") (define-rewrite bug15v ((verify (case-lam (name l (lam (val ellipsis1) (n ellipsis2) e)) ellipsis3) s n_l b γ η f) . rest) ==> ((verify (case-lam (name l (lam (τ ellipsis1) (n ellipsis2) e)) ellipsis3) s n_l b γ η f) . rest) #:context (define-metafunction) #:variables (rest ellipsis1 ellipsis2 ellipsis3) #:exactly-once) (define-rewrite bug15rt `(case-lam ,@(map (curry recur depth #f) ls)) ==> `(case-lam ,@(map (curry recur depth #t) ls)) #:context (match) #:exactly-once) (define-rewrite bug15-jdg [(lam-verified?* ((lam τl nl e) el) sl m) (vals τl) (lam-verified? (lam τl nl e) sl m) (lam-verified?* el sl m)] ==> [(lam-verified?* ((lam τl nl e) el) sl m) (lam-verified? (lam τl nl e) sl m) (lam-verified?* el sl m)] #:context (define-judgment-form) #:exactly-once) (include/rewrite (lib "redex/examples/racket-machine/grammar.rkt") grammar) (include/rewrite (lib "redex/examples/racket-machine/verification.rkt") verification bug15v) (include/rewrite (lib "redex/examples/racket-machine/randomized-tests.rkt") randomized-tests rt-rw bug15rt) (include/rewrite (lib "redex/benchmark/models/rvm/verif-jdg.rkt") verif-jdg bug15-jdg) (include/rewrite "generators.rkt" generators bug-mod-rw) (define small-counter-example '(let-one 42 (boxenv 0 (application (case-lam (lam (ref) () (loc-box 0))) (loc-box 1))))) (test small-counter-example)
a01de44f166a6ac276850ad8711a874362444e0c3d97606d9014f1a4e2ff42e5
wdebeaum/step
utter.lisp
;;;; ;;;; w::utter ;;;; (define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL :words ( (W::utter (SENSES ((meta-data :origin "verbnet-2.0" :entry-date 20060315 :change-date 20090505 :comments nil :vn ("say-37.7")) (LF-PARENT ONT::say) (TEMPL AGENT-FORMAL-XP-TEMPL (xp (% w::cp (w::ctype w::s-that)))) ; like disclose (PREFERENCE 0.98) ) ) ) )) (define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL :words ( (W::UTTER (wordfeats (W::morph (:FORMS (-LY)))) (SENSES ((meta-data :origin cardiac :entry-date 20080508 :change-date 20090731 :comments LM-vocab) (lf-parent ont::whole-complete) ;; like total ) ) ) ))
null
https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/utter.lisp
lisp
w::utter like disclose like total
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL :words ( (W::utter (SENSES ((meta-data :origin "verbnet-2.0" :entry-date 20060315 :change-date 20090505 :comments nil :vn ("say-37.7")) (LF-PARENT ONT::say) (PREFERENCE 0.98) ) ) ) )) (define-words :pos W::adj :templ CENTRAL-ADJ-TEMPL :words ( (W::UTTER (wordfeats (W::morph (:FORMS (-LY)))) (SENSES ((meta-data :origin cardiac :entry-date 20080508 :change-date 20090731 :comments LM-vocab) ) ) ) ))
5ece310c0851f48c3348272a4f63e41a9e592f5264b7393b74b625bc6ec2a059
clojure-interop/aws-api
core.clj
(ns com.amazonaws.services.iotdata.core (:refer-clojure :only [require comment defn ->]) (:import )) (require '[com.amazonaws.services.iotdata.AWSIotData]) (require '[com.amazonaws.services.iotdata.AWSIotDataAsync]) (require '[com.amazonaws.services.iotdata.AWSIotDataAsyncClient]) (require '[com.amazonaws.services.iotdata.AWSIotDataAsyncClientBuilder]) (require '[com.amazonaws.services.iotdata.AWSIotDataClient]) (require '[com.amazonaws.services.iotdata.AWSIotDataClientBuilder]) (require '[com.amazonaws.services.iotdata.AbstractAWSIotData]) (require '[com.amazonaws.services.iotdata.AbstractAWSIotDataAsync])
null
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.iotdata/src/com/amazonaws/services/iotdata/core.clj
clojure
(ns com.amazonaws.services.iotdata.core (:refer-clojure :only [require comment defn ->]) (:import )) (require '[com.amazonaws.services.iotdata.AWSIotData]) (require '[com.amazonaws.services.iotdata.AWSIotDataAsync]) (require '[com.amazonaws.services.iotdata.AWSIotDataAsyncClient]) (require '[com.amazonaws.services.iotdata.AWSIotDataAsyncClientBuilder]) (require '[com.amazonaws.services.iotdata.AWSIotDataClient]) (require '[com.amazonaws.services.iotdata.AWSIotDataClientBuilder]) (require '[com.amazonaws.services.iotdata.AbstractAWSIotData]) (require '[com.amazonaws.services.iotdata.AbstractAWSIotDataAsync])
5f9b78b385def8f7b0c9245010f099b4286d353ce224e04ab3bc0aa5322e5275
drone-rites/clj-oauth
client_xauth_test.clj
(ns oauth.client-xauth-test (:require [oauth.client :as oc] [oauth.signature :as sig]) (:use clojure.test)) (def consumer (oc/make-consumer "JvyS7DO2qd6NNTsXJ4E7zA" "9z6157pUbOBqtbm0A0q4r29Y2EYzIHlUwbF4Cl9c" "" "" "" :hmac-sha1)) (deftest xauth-base-string-test (is (= "POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Faccess_token&oauth_consumer_key%3DJvyS7DO2qd6NNTsXJ4E7zA%26oauth_nonce%3D6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1284565601%26oauth_version%3D1.0%26x_auth_mode%3Dclient_auth%26x_auth_password%3Dtwitter-xauth%26x_auth_username%3Doauth_test_exec" (sig/base-string "POST" "" (merge {:x_auth_username "oauth_test_exec" :x_auth_password "twitter-xauth" :x_auth_mode "client_auth"} {:oauth_consumer_key "JvyS7DO2qd6NNTsXJ4E7zA" :oauth_nonce "6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo" :oauth_timestamp "1284565601" :oauth_version "1.0" :oauth_signature_method "HMAC-SHA1"}))))) (deftest build-xauth-access-token-request-test (is (= {:form-params {:x_auth_username "oauth_test_exec", :x_auth_password "twitter-xauth", :x_auth_mode "client_auth"}, :headers {"Authorization" "OAuth oauth_consumer_key=\"JvyS7DO2qd6NNTsXJ4E7zA\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1284565601\", oauth_nonce=\"6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo\", oauth_version=\"1.0\", oauth_signature=\"1L1oXQmawZAkQ47FHLwcOV%2Bkjwc%3D\""}} (oc/build-xauth-access-token-request consumer "oauth_test_exec" "twitter-xauth" "6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo" 1284565601))))
null
https://raw.githubusercontent.com/drone-rites/clj-oauth/dd8a05a78aa4eeb56d00dd5a0e17c2f02c5bec4d/test/oauth/client_xauth_test.clj
clojure
(ns oauth.client-xauth-test (:require [oauth.client :as oc] [oauth.signature :as sig]) (:use clojure.test)) (def consumer (oc/make-consumer "JvyS7DO2qd6NNTsXJ4E7zA" "9z6157pUbOBqtbm0A0q4r29Y2EYzIHlUwbF4Cl9c" "" "" "" :hmac-sha1)) (deftest xauth-base-string-test (is (= "POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Faccess_token&oauth_consumer_key%3DJvyS7DO2qd6NNTsXJ4E7zA%26oauth_nonce%3D6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1284565601%26oauth_version%3D1.0%26x_auth_mode%3Dclient_auth%26x_auth_password%3Dtwitter-xauth%26x_auth_username%3Doauth_test_exec" (sig/base-string "POST" "" (merge {:x_auth_username "oauth_test_exec" :x_auth_password "twitter-xauth" :x_auth_mode "client_auth"} {:oauth_consumer_key "JvyS7DO2qd6NNTsXJ4E7zA" :oauth_nonce "6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo" :oauth_timestamp "1284565601" :oauth_version "1.0" :oauth_signature_method "HMAC-SHA1"}))))) (deftest build-xauth-access-token-request-test (is (= {:form-params {:x_auth_username "oauth_test_exec", :x_auth_password "twitter-xauth", :x_auth_mode "client_auth"}, :headers {"Authorization" "OAuth oauth_consumer_key=\"JvyS7DO2qd6NNTsXJ4E7zA\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1284565601\", oauth_nonce=\"6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo\", oauth_version=\"1.0\", oauth_signature=\"1L1oXQmawZAkQ47FHLwcOV%2Bkjwc%3D\""}} (oc/build-xauth-access-token-request consumer "oauth_test_exec" "twitter-xauth" "6AN2dKRzxyGhmIXUKSmp1JcB4pckM8rD3frKMTmVAo" 1284565601))))
a1136b6510473911004d08922cc6fe80cf3b0cab37f14a8b78f2df63418564e8
jellelicht/guix
libcanberra.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 < > Copyright © 2014 , 2015 < > Copyright © 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages libcanberra) #:use-module ((guix licenses) #:select (lgpl2.1+ gpl2 gpl2+ cc-by-sa4.0 cc-by3.0)) #:use-module (gnu packages) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (guix build utils) #:use-module (gnu packages autotools) #:use-module (gnu packages gstreamer) #:use-module (gnu packages gtk) #:use-module (gnu packages glib) #:use-module (gnu packages linux) #:use-module (gnu packages pulseaudio) #:use-module (gnu packages pkg-config) #:use-module (gnu packages xiph)) (define-public libcanberra (package (name "libcanberra") (version "0.30") (source (origin (method url-fetch) This used to be at 0pointer.de but it vanished . (uri (string-append "-" version ".tar.xz/34cb7e4430afaf6f447c4ebdb9b42072/libcanberra-" version ".tar.xz")) (sha256 (base32 "0wps39h8rx2b00vyvkia5j40fkak3dpipp1kzilqla0cgvk73dn2")) ;; "sound-theme-freedesktop" is the default and fall-back sound theme for XDG desktops and should always be present . ;; -theme-spec/ ;; We make sure libcanberra will find it. ;; ;; We add the default sounds store directory to the code dealing with and not XDG_DATA_HOME . This is because XDG_DATA_HOME can only be a single directory and is inspected first . ;; can list an arbitrary number of directories and is only inspected ;; later. This is designed to allows the user to modify any theme at ;; his pleasure. (patch-flags '("-p0")) (patches (list (search-patch "libcanberra-sound-theme-freedesktop.patch"))))) (build-system gnu-build-system) (inputs `(("alsa-lib" ,alsa-lib) ("gstreamer" ,gstreamer) ("gtk+" ,gtk+) ("libltdl" ,libltdl) ("libvorbis" ,libvorbis) ("pulseaudio" ,pulseaudio) ("udev" ,eudev) ("sound-theme-freedesktop" ,sound-theme-freedesktop))) (native-inputs `(("pkg-config" ,pkg-config))) (arguments `(#:phases (alist-cons-before 'build 'patch-default-sounds-directory (lambda* (#:key inputs #:allow-other-keys) (substitute* "src/sound-theme-spec.c" (("@SOUND_THEME_DIRECTORY@") (string-append (assoc-ref inputs "sound-theme-freedesktop") "/share")))) %standard-phases))) (home-page "/") (synopsis "Implementation of the XDG Sound Theme and Name Specifications") (description "Libcanberra is an implementation of the XDG Sound Theme and Name Specifications, for generating event sounds on free desktops, such as GNOME. It comes with several backends (ALSA, PulseAudio, OSS, GStreamer, null) and is designed to be portable.") (license lgpl2.1+))) (define-public libcanberra/gtk+-2 (package (inherit libcanberra) (name "libcanberra-gtk2") (inputs `(,@(alist-delete "gtk+" (package-inputs libcanberra)) ("gtk+" ,gtk+-2))))) (define-public sound-theme-freedesktop (package (name "sound-theme-freedesktop") (version "0.8") (source (origin (method url-fetch) (uri (string-append "/~mccann/dist/" name "-" version ".tar.bz2")) (sha256 (base32 "054abv4gmfk9maw93fis0bf605rc56dah7ys5plc4pphxqh8nlfb")))) (build-system gnu-build-system) (native-inputs `(("intltool" ,intltool))) (synopsis "Audio samples for use as a desktop sound theme") (description "This package provides audio samples that can be used by libcanberra as sounds for various system events.") ;; The license of the various sounds is given in the 'CREDITS' file. (license (list cc-by-sa4.0 cc-by3.0 gpl2 gpl2+)) (home-page "-theme-spec/")))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/libcanberra.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. "sound-theme-freedesktop" is the default and fall-back sound theme for -theme-spec/ We make sure libcanberra will find it. We add the default sounds store directory to the code dealing with can list an arbitrary number of directories and is only inspected later. This is designed to allows the user to modify any theme at his pleasure. The license of the various sounds is given in the 'CREDITS' file.
Copyright © 2013 < > Copyright © 2014 , 2015 < > Copyright © 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages libcanberra) #:use-module ((guix licenses) #:select (lgpl2.1+ gpl2 gpl2+ cc-by-sa4.0 cc-by3.0)) #:use-module (gnu packages) #:use-module (guix packages) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (guix build utils) #:use-module (gnu packages autotools) #:use-module (gnu packages gstreamer) #:use-module (gnu packages gtk) #:use-module (gnu packages glib) #:use-module (gnu packages linux) #:use-module (gnu packages pulseaudio) #:use-module (gnu packages pkg-config) #:use-module (gnu packages xiph)) (define-public libcanberra (package (name "libcanberra") (version "0.30") (source (origin (method url-fetch) This used to be at 0pointer.de but it vanished . (uri (string-append "-" version ".tar.xz/34cb7e4430afaf6f447c4ebdb9b42072/libcanberra-" version ".tar.xz")) (sha256 (base32 "0wps39h8rx2b00vyvkia5j40fkak3dpipp1kzilqla0cgvk73dn2")) XDG desktops and should always be present . and not XDG_DATA_HOME . This is because XDG_DATA_HOME can only be a single directory and is inspected first . (patch-flags '("-p0")) (patches (list (search-patch "libcanberra-sound-theme-freedesktop.patch"))))) (build-system gnu-build-system) (inputs `(("alsa-lib" ,alsa-lib) ("gstreamer" ,gstreamer) ("gtk+" ,gtk+) ("libltdl" ,libltdl) ("libvorbis" ,libvorbis) ("pulseaudio" ,pulseaudio) ("udev" ,eudev) ("sound-theme-freedesktop" ,sound-theme-freedesktop))) (native-inputs `(("pkg-config" ,pkg-config))) (arguments `(#:phases (alist-cons-before 'build 'patch-default-sounds-directory (lambda* (#:key inputs #:allow-other-keys) (substitute* "src/sound-theme-spec.c" (("@SOUND_THEME_DIRECTORY@") (string-append (assoc-ref inputs "sound-theme-freedesktop") "/share")))) %standard-phases))) (home-page "/") (synopsis "Implementation of the XDG Sound Theme and Name Specifications") (description "Libcanberra is an implementation of the XDG Sound Theme and Name Specifications, for generating event sounds on free desktops, such as GNOME. It comes with several backends (ALSA, PulseAudio, OSS, GStreamer, null) and is designed to be portable.") (license lgpl2.1+))) (define-public libcanberra/gtk+-2 (package (inherit libcanberra) (name "libcanberra-gtk2") (inputs `(,@(alist-delete "gtk+" (package-inputs libcanberra)) ("gtk+" ,gtk+-2))))) (define-public sound-theme-freedesktop (package (name "sound-theme-freedesktop") (version "0.8") (source (origin (method url-fetch) (uri (string-append "/~mccann/dist/" name "-" version ".tar.bz2")) (sha256 (base32 "054abv4gmfk9maw93fis0bf605rc56dah7ys5plc4pphxqh8nlfb")))) (build-system gnu-build-system) (native-inputs `(("intltool" ,intltool))) (synopsis "Audio samples for use as a desktop sound theme") (description "This package provides audio samples that can be used by libcanberra as sounds for various system events.") (license (list cc-by-sa4.0 cc-by3.0 gpl2 gpl2+)) (home-page "-theme-spec/")))
25fb82f29d4aed997b9b43f49be9cdd2fdd6e8b380d2bc7da38ed7647a2474b4
input-output-hk/rscoin-haskell
Launcher.hs
-- | Launch Notary stuff. module RSCoin.Notary.Launcher ( ContextArgument (..) , launchNotaryReal ) where import Control.Monad (unless, when) import Control.Monad.Catch (bracket) import Control.Monad.Trans (MonadIO, liftIO) import Data.Optional (Optional) import Network.Wai (Middleware) import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev) import Control.TimeWarp.Timed (fork_) import RSCoin.Core (ContextArgument (..), NodeContext, PeriodId, PublicKey, SecretKey, Severity (..), getNodeContext, notaryLoggerName, runRealModeUntrusted) import RSCoin.Notary.AcidState (NotaryState, closeState, openMemState, openState) import RSCoin.Notary.Server (serveNotary) import RSCoin.Notary.Web.Servant (servantApp) import RSCoin.Notary.Worker (runFetchWorker) launchNotaryReal :: Severity -> Bool -> SecretKey -> Maybe FilePath -> ContextArgument -> Int -> [PublicKey] -> Optional PeriodId -> Optional PeriodId -> Bool -> IO () launchNotaryReal logSeverity deleteIfExists sk dbPath ca webPort trustedKeys allocationEndurance transactionEndurance isDisabled = do let openAction = maybe openMemState (openState deleteIfExists) dbPath runRealModeUntrusted notaryLoggerName ca $ bracket (openAction trustedKeys allocationEndurance transactionEndurance) closeState $ \st -> do fork_ $ runFetchWorker st when isDisabled $ serveNotary isDisabled sk st unless isDisabled $ do fork_ $ serveNotary isDisabled sk st launchWeb webPort logSeverity st =<< getNodeContext loggingMiddleware :: Severity -> Middleware loggingMiddleware Debug = logStdoutDev loggingMiddleware Info = logStdout loggingMiddleware _ = id launchWeb :: MonadIO m => Int -> Severity -> NotaryState -> NodeContext -> m () launchWeb port sev st nodeCtx = liftIO $ run port $ loggingMiddleware sev $ servantApp st nodeCtx
null
https://raw.githubusercontent.com/input-output-hk/rscoin-haskell/109d8f6f226e9d0b360fcaac14c5a90da112a810/src/RSCoin/Notary/Launcher.hs
haskell
| Launch Notary stuff.
module RSCoin.Notary.Launcher ( ContextArgument (..) , launchNotaryReal ) where import Control.Monad (unless, when) import Control.Monad.Catch (bracket) import Control.Monad.Trans (MonadIO, liftIO) import Data.Optional (Optional) import Network.Wai (Middleware) import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev) import Control.TimeWarp.Timed (fork_) import RSCoin.Core (ContextArgument (..), NodeContext, PeriodId, PublicKey, SecretKey, Severity (..), getNodeContext, notaryLoggerName, runRealModeUntrusted) import RSCoin.Notary.AcidState (NotaryState, closeState, openMemState, openState) import RSCoin.Notary.Server (serveNotary) import RSCoin.Notary.Web.Servant (servantApp) import RSCoin.Notary.Worker (runFetchWorker) launchNotaryReal :: Severity -> Bool -> SecretKey -> Maybe FilePath -> ContextArgument -> Int -> [PublicKey] -> Optional PeriodId -> Optional PeriodId -> Bool -> IO () launchNotaryReal logSeverity deleteIfExists sk dbPath ca webPort trustedKeys allocationEndurance transactionEndurance isDisabled = do let openAction = maybe openMemState (openState deleteIfExists) dbPath runRealModeUntrusted notaryLoggerName ca $ bracket (openAction trustedKeys allocationEndurance transactionEndurance) closeState $ \st -> do fork_ $ runFetchWorker st when isDisabled $ serveNotary isDisabled sk st unless isDisabled $ do fork_ $ serveNotary isDisabled sk st launchWeb webPort logSeverity st =<< getNodeContext loggingMiddleware :: Severity -> Middleware loggingMiddleware Debug = logStdoutDev loggingMiddleware Info = logStdout loggingMiddleware _ = id launchWeb :: MonadIO m => Int -> Severity -> NotaryState -> NodeContext -> m () launchWeb port sev st nodeCtx = liftIO $ run port $ loggingMiddleware sev $ servantApp st nodeCtx
5de910fff95be547bbf0abdbf4580de7e385d63b7aab90c6cf0db13f2ed48e00
purerl/purerl
JSON.hs
# LANGUAGE TemplateHaskell # # LANGUAGE CPP # module Language.PureScript.Erl.Errors.JSON where import Prelude.Compat import qualified Data.Aeson.TH as A import qualified Data.List.NonEmpty as NEL import Data.Text (Text) import qualified Language.PureScript as P import Language.PureScript.Erl.Errors.Types import Language.PureScript.Erl.Errors as E data ErrorPosition = ErrorPosition { startLine :: Int , startColumn :: Int , endLine :: Int , endColumn :: Int } deriving (Show, Eq, Ord) data ErrorSuggestion = ErrorSuggestion { replacement :: Text , replaceRange :: Maybe ErrorPosition } deriving (Show, Eq) data JSONError = JSONError { position :: Maybe ErrorPosition , message :: String , errorCode :: Text , errorLink :: Text , filename :: Maybe String , moduleName :: Maybe Text , allSpans :: [P.SourceSpan] } deriving (Show, Eq) data JSONResult = JSONResult { warnings :: [JSONError] , errors :: [JSONError] } deriving (Show, Eq) #ifndef __GHCIDE__ $(A.deriveJSON A.defaultOptions ''ErrorPosition) $(A.deriveJSON A.defaultOptions ''JSONError) $(A.deriveJSON A.defaultOptions ''JSONResult) #endif toJSONErrors :: Bool -> E.Level -> MultipleErrors -> [JSONError] toJSONErrors verbose level = map (toJSONError verbose level) . E.runMultipleErrors toJSONError :: Bool -> E.Level -> ErrorMessage -> JSONError toJSONError verbose level e = JSONError (toErrorPosition <$> fmap NEL.head spans) (E.renderBox (E.prettyPrintSingleError (E.PPEOptions Nothing verbose level False mempty []) (E.stripModuleAndSpan e))) (E.errorCode e) (E.errorDocUri e) (P.spanName <$> fmap NEL.head spans) (P.runModuleName <$> E.errorModule e) (maybe [] NEL.toList spans) where spans :: Maybe (NEL.NonEmpty P.SourceSpan) spans = E.errorSpan e toErrorPosition :: P.SourceSpan -> ErrorPosition toErrorPosition ss = ErrorPosition (P.sourcePosLine (P.spanStart ss)) (P.sourcePosColumn (P.spanStart ss)) (P.sourcePosLine (P.spanEnd ss)) (P.sourcePosColumn (P.spanEnd ss))
null
https://raw.githubusercontent.com/purerl/purerl/8fd0386f8470b987f2ec0a9acbfafd546f513fda/src/Language/PureScript/Erl/Errors/JSON.hs
haskell
# LANGUAGE TemplateHaskell # # LANGUAGE CPP # module Language.PureScript.Erl.Errors.JSON where import Prelude.Compat import qualified Data.Aeson.TH as A import qualified Data.List.NonEmpty as NEL import Data.Text (Text) import qualified Language.PureScript as P import Language.PureScript.Erl.Errors.Types import Language.PureScript.Erl.Errors as E data ErrorPosition = ErrorPosition { startLine :: Int , startColumn :: Int , endLine :: Int , endColumn :: Int } deriving (Show, Eq, Ord) data ErrorSuggestion = ErrorSuggestion { replacement :: Text , replaceRange :: Maybe ErrorPosition } deriving (Show, Eq) data JSONError = JSONError { position :: Maybe ErrorPosition , message :: String , errorCode :: Text , errorLink :: Text , filename :: Maybe String , moduleName :: Maybe Text , allSpans :: [P.SourceSpan] } deriving (Show, Eq) data JSONResult = JSONResult { warnings :: [JSONError] , errors :: [JSONError] } deriving (Show, Eq) #ifndef __GHCIDE__ $(A.deriveJSON A.defaultOptions ''ErrorPosition) $(A.deriveJSON A.defaultOptions ''JSONError) $(A.deriveJSON A.defaultOptions ''JSONResult) #endif toJSONErrors :: Bool -> E.Level -> MultipleErrors -> [JSONError] toJSONErrors verbose level = map (toJSONError verbose level) . E.runMultipleErrors toJSONError :: Bool -> E.Level -> ErrorMessage -> JSONError toJSONError verbose level e = JSONError (toErrorPosition <$> fmap NEL.head spans) (E.renderBox (E.prettyPrintSingleError (E.PPEOptions Nothing verbose level False mempty []) (E.stripModuleAndSpan e))) (E.errorCode e) (E.errorDocUri e) (P.spanName <$> fmap NEL.head spans) (P.runModuleName <$> E.errorModule e) (maybe [] NEL.toList spans) where spans :: Maybe (NEL.NonEmpty P.SourceSpan) spans = E.errorSpan e toErrorPosition :: P.SourceSpan -> ErrorPosition toErrorPosition ss = ErrorPosition (P.sourcePosLine (P.spanStart ss)) (P.sourcePosColumn (P.spanStart ss)) (P.sourcePosLine (P.spanEnd ss)) (P.sourcePosColumn (P.spanEnd ss))
1f88d23417a5d6bcc4472fbe3d9eac22bb026c5866bbd0c8353aa1440a69bb30
kupl/FixML
sub36.ml
type metro = STATION of name | AREA of name * metro | CONNECT of metro * metro and name = string let rec checkMetro: metro -> bool = fun m -> match m with | STATION _ -> false | CONNECT _ -> false | AREA(n', m') -> List.mem n' (listMetro(m')) and listMetro: metro -> 'a list = fun m -> match m with | STATION m' -> [m'] | CONNECT(m1, m2) -> (match (listMetro m1), (listMetro m2) with | (a::b, c::d) -> List.append (a::b) (c::d) | (_, _) -> []) | AREA(n', m') -> (match checkMetro m with | true -> listMetro m' | false -> [])
null
https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/wellformedness/wellformedness1/submissions/sub36.ml
ocaml
type metro = STATION of name | AREA of name * metro | CONNECT of metro * metro and name = string let rec checkMetro: metro -> bool = fun m -> match m with | STATION _ -> false | CONNECT _ -> false | AREA(n', m') -> List.mem n' (listMetro(m')) and listMetro: metro -> 'a list = fun m -> match m with | STATION m' -> [m'] | CONNECT(m1, m2) -> (match (listMetro m1), (listMetro m2) with | (a::b, c::d) -> List.append (a::b) (c::d) | (_, _) -> []) | AREA(n', m') -> (match checkMetro m with | true -> listMetro m' | false -> [])
22e68e614ceaedc07cd61ee8656856d36f0e56fc4b12abf19027a993c6c73f29
mirage/mirage-vnetif
config.ml
open Mirage let main = foreign "Iperf_self.Main" (console @-> job) let platform = match get_mode () with | `Xen -> "xen" | _ -> "unix" let () = add_to_opam_packages [ "mirage-vnetif" ; "mirage-net-" ^ platform; "mirage-clock-" ^ platform; "mirage-" ^ platform; "mirage-types" ; "tcpip" ]; add_to_ocamlfind_libraries [ "mirage-vnetif" ; "mirage-net-" ^ platform ; "mirage-" ^ platform; "mirage-clock-" ^ platform; "tcpip.stack-direct" ; "mirage-types" ]; register "unikernel" [ main $ default_console ]
null
https://raw.githubusercontent.com/mirage/mirage-vnetif/e33e44c987289b31571dbb5f836d43a3a6485120/examples/iperf_self/config.ml
ocaml
open Mirage let main = foreign "Iperf_self.Main" (console @-> job) let platform = match get_mode () with | `Xen -> "xen" | _ -> "unix" let () = add_to_opam_packages [ "mirage-vnetif" ; "mirage-net-" ^ platform; "mirage-clock-" ^ platform; "mirage-" ^ platform; "mirage-types" ; "tcpip" ]; add_to_ocamlfind_libraries [ "mirage-vnetif" ; "mirage-net-" ^ platform ; "mirage-" ^ platform; "mirage-clock-" ^ platform; "tcpip.stack-direct" ; "mirage-types" ]; register "unikernel" [ main $ default_console ]
5f89b42b15611724c1b9682c5ebe7d119ee4b37e7cbcf82241c4897d0c5969fb
pykello/racket-visualization
common.rkt
#lang racket (require metapict racket/math slideshow/latex) (provide (all-defined-out)) (latex-debug? #f) ;; Added to every tex file, before the document proper: (add-preamble #<<latex \usepackage{amsmath, amssymb} \newcommand{\targetlang}{\lambda_{\mathrm{ZFC}}} \newcommand{\meaningof}[1]{[\![{#1}]\!]} % use in semantic functions \newcommand{\A}{\mathcal{A}} \renewcommand{\P}{\mathbb{P}} \newcommand{\N}{\mathbb{N}} \newcommand{\Z}{\mathbb{Z}} \newcommand{\Q}{\mathbb{Q}} \newcommand{\R}{\mathbb{R}} latex ) (define ($ x) (scale 0.6 ($$ x))) (ahlength (px 5)) (define-syntax dashed-curve (syntax-rules () [(dashed-curve a ...) (dashed (draw (curve a ...)))])) (define (dot-node pos fill [size 4]) (circle-node #:at pos #:min-size (px size) #:fill fill)) (define (save-svg filename p) (when (file-exists? filename) (delete-file filename)) (save-pict filename p 'svg)) (define (save-png filename p) (when (file-exists? filename) (delete-file filename)) (save-pict filename p 'png)) (define (save-bmp filename p) (when (file-exists? filename) (delete-file filename)) (save-pict filename p 'bmp)) (define (draw-rec cs) (if (list? cs) (draw* (map draw-rec cs)) (draw cs))) (define current-curly-brace-indent (make-parameter 0.5)) (define current-curly-brace-label-func (make-parameter label-bot)) (define (curly-brace p1 p2 [label ""] [a (current-curly-brace-indent)] #:label-func [label-func (current-curly-brace-label-func)]) (define (hcurve p1 va vb) (curve p1 .. (pt+ p1 (vec* 0.15 va) (vec* 0.5 vb)) .. (pt+ p1 (vec* 0.6 va) (vec* 0.98 vb)) .. (pt+ p1 va vb))) (define v1 (pt- p2 p1)) (define vn (vec* (/ a (norm v1)) v1)) (define vp (rot90 vn)) (define vx (vec* 0.5 vn)) (define -vx (vec- (vec 0 0) vx)) (define vy (vec* 0.5 vp)) (define -vy (vec- (vec 0 0) vy)) (define p3 (pt+ (med 0.5 p1 p2) (vec* 2 vy))) (draw (hcurve p1 vx vy) (curve (pt+ p1 vx vy) -- (pt+ p3 -vx -vy)) (hcurve p3 -vx -vy) (hcurve p3 vx -vy) (curve (pt+ p3 (vec+ vx -vy)) -- (pt+ p2 -vx vy)) (hcurve p2 -vx vy) (label-func label p3)))
null
https://raw.githubusercontent.com/pykello/racket-visualization/7c4dccfd59123fcb7c144ad8ed89dffdc57290df/metapict-examples/common.rkt
racket
Added to every tex file, before the document proper:
#lang racket (require metapict racket/math slideshow/latex) (provide (all-defined-out)) (latex-debug? #f) (add-preamble #<<latex \usepackage{amsmath, amssymb} \newcommand{\targetlang}{\lambda_{\mathrm{ZFC}}} \newcommand{\meaningof}[1]{[\![{#1}]\!]} % use in semantic functions \newcommand{\A}{\mathcal{A}} \renewcommand{\P}{\mathbb{P}} \newcommand{\N}{\mathbb{N}} \newcommand{\Z}{\mathbb{Z}} \newcommand{\Q}{\mathbb{Q}} \newcommand{\R}{\mathbb{R}} latex ) (define ($ x) (scale 0.6 ($$ x))) (ahlength (px 5)) (define-syntax dashed-curve (syntax-rules () [(dashed-curve a ...) (dashed (draw (curve a ...)))])) (define (dot-node pos fill [size 4]) (circle-node #:at pos #:min-size (px size) #:fill fill)) (define (save-svg filename p) (when (file-exists? filename) (delete-file filename)) (save-pict filename p 'svg)) (define (save-png filename p) (when (file-exists? filename) (delete-file filename)) (save-pict filename p 'png)) (define (save-bmp filename p) (when (file-exists? filename) (delete-file filename)) (save-pict filename p 'bmp)) (define (draw-rec cs) (if (list? cs) (draw* (map draw-rec cs)) (draw cs))) (define current-curly-brace-indent (make-parameter 0.5)) (define current-curly-brace-label-func (make-parameter label-bot)) (define (curly-brace p1 p2 [label ""] [a (current-curly-brace-indent)] #:label-func [label-func (current-curly-brace-label-func)]) (define (hcurve p1 va vb) (curve p1 .. (pt+ p1 (vec* 0.15 va) (vec* 0.5 vb)) .. (pt+ p1 (vec* 0.6 va) (vec* 0.98 vb)) .. (pt+ p1 va vb))) (define v1 (pt- p2 p1)) (define vn (vec* (/ a (norm v1)) v1)) (define vp (rot90 vn)) (define vx (vec* 0.5 vn)) (define -vx (vec- (vec 0 0) vx)) (define vy (vec* 0.5 vp)) (define -vy (vec- (vec 0 0) vy)) (define p3 (pt+ (med 0.5 p1 p2) (vec* 2 vy))) (draw (hcurve p1 vx vy) (curve (pt+ p1 vx vy) -- (pt+ p3 -vx -vy)) (hcurve p3 -vx -vy) (hcurve p3 vx -vy) (curve (pt+ p3 (vec+ vx -vy)) -- (pt+ p2 -vx vy)) (hcurve p2 -vx vy) (label-func label p3)))
818691852deb079d93ee989a104a1aeb6592f0591486811c1cbcde3e2cef1ff7
threatgrid/ctia
identity_assertion_test.clj
(ns ctia.entity.identity-assertion-test (:require [clojure.test :refer [deftest is join-fixtures testing use-fixtures]] [ctia.entity.identity-assertion :as sut] [ctia.test-helpers.aggregate :refer [test-metric-routes]] [ctia.test-helpers.auth :refer [all-capabilities]] [ctia.test-helpers.core :as helpers :refer [GET]] [ctia.test-helpers.crud :refer [entity-crud-test]] [ctia.test-helpers.fake-whoami-service :as whoami-helpers] [ctia.test-helpers.http :refer [api-key]] [ctia.test-helpers.store :refer [test-for-each-store-with-app]] [ctim.examples.identity-assertions :refer [new-identity-assertion-maximal new-identity-assertion-minimal]] [schema.test :refer [validate-schemas]])) (use-fixtures :once (join-fixtures [validate-schemas whoami-helpers/fixture-server])) (def new-identity-assertion (-> new-identity-assertion-maximal (dissoc :id) (assoc :tlp "green" :external_ids ["-assertion/identity-assertion-123" "-assertion/identity-assertion-345"]))) (defn additional-tests [app identity-assertion-id _] (testing "GET /ctia/identity-assertion/search" (do (let [term "identity.observables.value:\"1.2.3.4\"" response (GET app (str "ctia/identity-assertion/search") :query-params {"query" term} :headers {"Authorization" "45c1f5e3f05d0"})] (is (= 200 (:status response)) "IP quoted term works")) (let [term "1.2.3.4" response (GET app (str "ctia/identity-assertion/search") :headers {"Authorization" "45c1f5e3f05d0"} :query-params {"query" term})] (is (= 200 (:status response)) "IP unquoted, term works")) (let [term "assertions.name:\"cisco:ctr:device:id\"" response (GET app (str "ctia/identity-assertion/search") :query-params {"query" term} :headers {"Authorization" "45c1f5e3f05d0"})] (is (= 200 (:status response)) "Search by Assertion name term works")) (let [term "*" response (GET app (str "ctia/identity-assertion/search") :query-params {"query" term "assertions.name" "cisco:ctr:device:id"} :headers {"Authorization" "45c1f5e3f05d0"})] (is (= 200 (:status response)) "Search by Assertion term works"))))) (deftest test-identity-assertion-routes (test-for-each-store-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app api-key "foouser" "foogroup" "user") (entity-crud-test (into sut/identity-assertion-entity {:app app :example new-identity-assertion-maximal :invalid-tests? false :update-tests? true :search-tests? false :update-field :source :additional-tests additional-tests :headers {:Authorization "45c1f5e3f05d0"}}))))) (deftest test-identity-assertion-metric-routes (test-metric-routes (into sut/identity-assertion-entity {:plural :identity_assertions :entity-minimal new-identity-assertion-minimal :enumerable-fields sut/identity-assertion-enumerable-fields :date-fields sut/identity-assertion-histogram-fields})))
null
https://raw.githubusercontent.com/threatgrid/ctia/43ff86881b099bfd5a86f6a24a7ec0e05e980c04/test/ctia/entity/identity_assertion_test.clj
clojure
(ns ctia.entity.identity-assertion-test (:require [clojure.test :refer [deftest is join-fixtures testing use-fixtures]] [ctia.entity.identity-assertion :as sut] [ctia.test-helpers.aggregate :refer [test-metric-routes]] [ctia.test-helpers.auth :refer [all-capabilities]] [ctia.test-helpers.core :as helpers :refer [GET]] [ctia.test-helpers.crud :refer [entity-crud-test]] [ctia.test-helpers.fake-whoami-service :as whoami-helpers] [ctia.test-helpers.http :refer [api-key]] [ctia.test-helpers.store :refer [test-for-each-store-with-app]] [ctim.examples.identity-assertions :refer [new-identity-assertion-maximal new-identity-assertion-minimal]] [schema.test :refer [validate-schemas]])) (use-fixtures :once (join-fixtures [validate-schemas whoami-helpers/fixture-server])) (def new-identity-assertion (-> new-identity-assertion-maximal (dissoc :id) (assoc :tlp "green" :external_ids ["-assertion/identity-assertion-123" "-assertion/identity-assertion-345"]))) (defn additional-tests [app identity-assertion-id _] (testing "GET /ctia/identity-assertion/search" (do (let [term "identity.observables.value:\"1.2.3.4\"" response (GET app (str "ctia/identity-assertion/search") :query-params {"query" term} :headers {"Authorization" "45c1f5e3f05d0"})] (is (= 200 (:status response)) "IP quoted term works")) (let [term "1.2.3.4" response (GET app (str "ctia/identity-assertion/search") :headers {"Authorization" "45c1f5e3f05d0"} :query-params {"query" term})] (is (= 200 (:status response)) "IP unquoted, term works")) (let [term "assertions.name:\"cisco:ctr:device:id\"" response (GET app (str "ctia/identity-assertion/search") :query-params {"query" term} :headers {"Authorization" "45c1f5e3f05d0"})] (is (= 200 (:status response)) "Search by Assertion name term works")) (let [term "*" response (GET app (str "ctia/identity-assertion/search") :query-params {"query" term "assertions.name" "cisco:ctr:device:id"} :headers {"Authorization" "45c1f5e3f05d0"})] (is (= 200 (:status response)) "Search by Assertion term works"))))) (deftest test-identity-assertion-routes (test-for-each-store-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" all-capabilities) (whoami-helpers/set-whoami-response app api-key "foouser" "foogroup" "user") (entity-crud-test (into sut/identity-assertion-entity {:app app :example new-identity-assertion-maximal :invalid-tests? false :update-tests? true :search-tests? false :update-field :source :additional-tests additional-tests :headers {:Authorization "45c1f5e3f05d0"}}))))) (deftest test-identity-assertion-metric-routes (test-metric-routes (into sut/identity-assertion-entity {:plural :identity_assertions :entity-minimal new-identity-assertion-minimal :enumerable-fields sut/identity-assertion-enumerable-fields :date-fields sut/identity-assertion-histogram-fields})))
93b4f1f52dae5d843362220338ec29392c2fe3b6e032b932272d4b3c852e74e0
scicloj/tablecloth
common_test.clj
(ns tablecloth.common-test (:require [tablecloth.api :as api])) (def DS (api/dataset {:V1 (take 9 (cycle [1 2])) :V2 (range 1 10) :V3 (take 9 (cycle [0.5 1.0 1.5])) :V4 (take 9 (cycle ["A" "B" "C"]))} {:dataset-name "DS"})) (defn approx ^double [^double v] (-> (Double/toString v) (BigDecimal.) (.setScale 4 BigDecimal/ROUND_HALF_UP) (.doubleValue)))
null
https://raw.githubusercontent.com/scicloj/tablecloth/e5f53bcfb5aab20a1807cecc3782cfba2b58476b/test/tablecloth/common_test.clj
clojure
(ns tablecloth.common-test (:require [tablecloth.api :as api])) (def DS (api/dataset {:V1 (take 9 (cycle [1 2])) :V2 (range 1 10) :V3 (take 9 (cycle [0.5 1.0 1.5])) :V4 (take 9 (cycle ["A" "B" "C"]))} {:dataset-name "DS"})) (defn approx ^double [^double v] (-> (Double/toString v) (BigDecimal.) (.setScale 4 BigDecimal/ROUND_HALF_UP) (.doubleValue)))
1be0b50662c04868c827ddfad286c4955cb98546f9337ea843b0a982fd97abec
msimon/chip8js
admin_mod.ml
{client{ exception Wrong_dom_value (* empty value is to handle correclty option for list and array When a value is missing from a list or an array, we don't want it to be set at None. We delete the value that generate a error, and keep the rest of the list/array *) exception Empty_value open Eliom_content open Html5 open D type 'a dom_value = [ | `Input of Html5_types.input Eliom_content.Html5.D.elt | `Textarea of Html5_types.textarea Eliom_content.Html5.D.elt | `Select of Html5_types.select Eliom_content.Html5.D.elt * ((string * ('a dom_ext Lazy.t) list) list) | `List of 'a dom_ext list | `Record of (string * 'a dom_ext) list ] and ('a) dom_ext = { node : 'a Eliom_content.Html5.D.elt ; mutable value_ : 'a dom_value ; error : Html5_types.p Eliom_content.Html5.D.elt option; } let node d = d.node let value d = d.value_ module type Admin_mod = sig type a val to_default : ?v:a -> unit -> [ Html5_types.div_content_fun ] dom_ext val to_dom : a -> [ Html5_types.div_content_fun ] dom_ext val save : [ Html5_types.div_content_fun ] dom_ext -> a end module Default(D : Admin_mod) : Admin_mod with type a = D.a = struct include D end let handle_exception error_dom t v f = try f v with exn -> begin match error_dom with | Some error_dom -> let error = Printf.sprintf "Expected value of type %s but '%s' was given" t (match v with | Some v -> v | None -> "") in Manip.SetCss.display error_dom "block" ; Manip.replaceAllChild error_dom [ pcdata error ] | None -> () end; raise exn module Admin_mod_int = Default(struct type a = int let to_default ?v () = let v = match v with | Some v -> a_value (string_of_int v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_int"] ] [ error; d ] ; value_ = `Input d; error = Some error; } let to_dom i = to_default ~v:i () let save d = match d.value_ with | `Input i -> let v = Dom_manip.get_opt_value i in handle_exception d.error "int" v ( function | Some i -> int_of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_int32 = Default(struct type a = int32 let to_default ?v () = let v = match v with | Some v -> a_value (Int32.to_string v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_int"; "dom_ext_int32"] ] [ error; d ] ; value_ = `Input d; error = Some error ; } let to_dom i = to_default ~v:i () let save d = match d.value_ with | `Input i -> let v = Dom_manip.get_opt_value i in handle_exception d.error "int32" v ( function | Some i -> Int32.of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_int64 = Default(struct type a = int64 let to_default ?v () = let v = match v with | Some v -> a_value (Int64.to_string v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_int"; "dom_ext_int64"] ] [ error; d ] ; value_ = `Input d; error = Some error ; } let to_dom i = Firebug.console##debug (Js.string "lol"); to_default ~v:i () let save d = match d.value_ with | `Input i -> let v = Dom_manip.get_opt_value i in handle_exception d.error "int64" v ( function | Some i -> Int64.of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_bool = Default(struct type a = bool let to_default ?v () = let sel = Raw.select [ option (pcdata ""); option ~a:[ a_value "true" ] (pcdata "true"); option ~a:[ a_value "false" ] (pcdata "false"); ] in begin match v with | Some v -> if v then Dom_manip.select_index sel 1 else Dom_manip.select_index sel 2 | None -> () end; { node = div ~a:[ a_class ["dom_ext_bool"]] [ sel ]; value_ = `Select (sel, []); error = None; } let to_dom b = to_default ~v:b () let save d = match d.value_ with | `Select (sel, []) -> begin match Dom_manip.get_value_select sel with | "true" -> true | "false" -> false | _ -> raise Empty_value end | _ -> raise Wrong_dom_value end) module Admin_mod_float = Default(struct type a = float let to_default ?v () = let v = match v with | Some v -> a_value (string_of_float v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_float"] ] [ error; d ] ; value_ = `Input d; error = Some error ; } let to_dom f = to_default ~v:f () let save d = match d.value_ with | `Input f -> let v = Dom_manip.get_opt_value f in handle_exception d.error "float" v ( function | Some i -> float_of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_string = Default(struct type a = string let to_default ?v () = let v = match v with | Some v -> v | None -> "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = Raw.textarea (pcdata v) in { node = div ~a:[ a_class ["dom_ext_string"] ] [ error; d ] ; value_ = `Textarea d; error = Some error ; } let to_dom s = to_default ~v:s () let save d = match d.value_ with | `Textarea s -> let v = Dom_manip.get_opt_value_textarea s in handle_exception d.error "string" v ( function | Some i -> i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) let display_list (type s) (module A : Admin_mod with type a = s) () = let nodes = div ~a:[ a_class ["dom_ext_list_elems"]] [] in let node = div ~a:[ a_class ["dom_ext_list"]] [ nodes ] in let v = { node ; value_ = `List []; error = None; } in let add_single_node ?d () = let d = match d with | Some d -> A.to_dom d | None -> A.to_default () in v.value_ <- begin match v.value_ with | `List l -> `List (l @ [ d ]) | _ -> assert false end; let single_node = div ~a:[ a_class ["dom_ext_list_elem"]] [ d.node ] in let btn = button ~a:[ a_onclick (fun _ -> Manip.removeChild nodes single_node; v.value_ <- begin match v.value_ with | `List l -> `List (List.filter (fun d2 -> d <> d2) l) | _ -> assert false end; raise Eliom_lib.False ); a_class [ "btn"; "btn-warning"] ] ~button_type:`Button [ pcdata "delete" ] in Manip.appendChild single_node btn ; Manip.appendChild nodes single_node ; in let add_btn = button ~a:[ a_onclick (fun _ -> add_single_node (); raise Eliom_lib.False); a_class [ "btn"; "btn-info" ]] ~button_type:`Button [ pcdata "add" ] in Manip.appendChild node add_btn ; v,add_single_node module Admin_mod_list (A : Admin_mod) = Default(struct type a = A.a list let to_default ?v () = let v,add_single_node = display_list (module A) () in add_single_node () ; v let to_dom l = let v,add_single_node = display_list (module A) () in List.iter ( fun el -> add_single_node ~d:el () ) l; v let save d = match d.value_ with | `List l -> List.fold_left ( fun acc e -> try (A.save e::acc) with Empty_value -> acc ) [] (List.rev l) | _ -> raise Wrong_dom_value end) module Admin_mod_array (A : Admin_mod) = Default(struct type a = A.a array let to_default ?v () = let v,add_single_node = display_list (module A) () in add_single_node () ; v let to_dom a = let v,add_single_node = display_list (module A) () in Array.iter ( fun el -> add_single_node ~d:el () ) a; v let save d = match d.value_ with | `List l -> let l = List.fold_left ( fun acc e -> try (A.save e::acc) with Empty_value -> acc ) [] (List.rev l) in Array.of_list l | _ -> raise Wrong_dom_value end) module Admin_mod_option (A : Admin_mod) = Default(struct type a = A.a option let to_default ?v () = let d = A.to_default () in let node = div ~a:[ a_class ["dom_ext_option"]] [ d.node ] in { d with node; } let to_dom o = match o with | Some s -> let d = A.to_dom s in let node = div ~a:[ a_class ["dom_ext_option"]] [ d.node ] in { d with node; } | None -> to_default () let save o = try Some (A.save o) with Empty_value -> None end) }}
null
https://raw.githubusercontent.com/msimon/chip8js/67f6ea0e25a2cc2287b6915c4ca2639a9d64c632/utils/lib/admin_mod.ml
ocaml
empty value is to handle correclty option for list and array When a value is missing from a list or an array, we don't want it to be set at None. We delete the value that generate a error, and keep the rest of the list/array
{client{ exception Wrong_dom_value exception Empty_value open Eliom_content open Html5 open D type 'a dom_value = [ | `Input of Html5_types.input Eliom_content.Html5.D.elt | `Textarea of Html5_types.textarea Eliom_content.Html5.D.elt | `Select of Html5_types.select Eliom_content.Html5.D.elt * ((string * ('a dom_ext Lazy.t) list) list) | `List of 'a dom_ext list | `Record of (string * 'a dom_ext) list ] and ('a) dom_ext = { node : 'a Eliom_content.Html5.D.elt ; mutable value_ : 'a dom_value ; error : Html5_types.p Eliom_content.Html5.D.elt option; } let node d = d.node let value d = d.value_ module type Admin_mod = sig type a val to_default : ?v:a -> unit -> [ Html5_types.div_content_fun ] dom_ext val to_dom : a -> [ Html5_types.div_content_fun ] dom_ext val save : [ Html5_types.div_content_fun ] dom_ext -> a end module Default(D : Admin_mod) : Admin_mod with type a = D.a = struct include D end let handle_exception error_dom t v f = try f v with exn -> begin match error_dom with | Some error_dom -> let error = Printf.sprintf "Expected value of type %s but '%s' was given" t (match v with | Some v -> v | None -> "") in Manip.SetCss.display error_dom "block" ; Manip.replaceAllChild error_dom [ pcdata error ] | None -> () end; raise exn module Admin_mod_int = Default(struct type a = int let to_default ?v () = let v = match v with | Some v -> a_value (string_of_int v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_int"] ] [ error; d ] ; value_ = `Input d; error = Some error; } let to_dom i = to_default ~v:i () let save d = match d.value_ with | `Input i -> let v = Dom_manip.get_opt_value i in handle_exception d.error "int" v ( function | Some i -> int_of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_int32 = Default(struct type a = int32 let to_default ?v () = let v = match v with | Some v -> a_value (Int32.to_string v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_int"; "dom_ext_int32"] ] [ error; d ] ; value_ = `Input d; error = Some error ; } let to_dom i = to_default ~v:i () let save d = match d.value_ with | `Input i -> let v = Dom_manip.get_opt_value i in handle_exception d.error "int32" v ( function | Some i -> Int32.of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_int64 = Default(struct type a = int64 let to_default ?v () = let v = match v with | Some v -> a_value (Int64.to_string v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_int"; "dom_ext_int64"] ] [ error; d ] ; value_ = `Input d; error = Some error ; } let to_dom i = Firebug.console##debug (Js.string "lol"); to_default ~v:i () let save d = match d.value_ with | `Input i -> let v = Dom_manip.get_opt_value i in handle_exception d.error "int64" v ( function | Some i -> Int64.of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_bool = Default(struct type a = bool let to_default ?v () = let sel = Raw.select [ option (pcdata ""); option ~a:[ a_value "true" ] (pcdata "true"); option ~a:[ a_value "false" ] (pcdata "false"); ] in begin match v with | Some v -> if v then Dom_manip.select_index sel 1 else Dom_manip.select_index sel 2 | None -> () end; { node = div ~a:[ a_class ["dom_ext_bool"]] [ sel ]; value_ = `Select (sel, []); error = None; } let to_dom b = to_default ~v:b () let save d = match d.value_ with | `Select (sel, []) -> begin match Dom_manip.get_value_select sel with | "true" -> true | "false" -> false | _ -> raise Empty_value end | _ -> raise Wrong_dom_value end) module Admin_mod_float = Default(struct type a = float let to_default ?v () = let v = match v with | Some v -> a_value (string_of_float v) | None -> a_value "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = input ~a:[ v ] ~input_type:`Text () in { node = div ~a:[ a_class ["dom_ext_float"] ] [ error; d ] ; value_ = `Input d; error = Some error ; } let to_dom f = to_default ~v:f () let save d = match d.value_ with | `Input f -> let v = Dom_manip.get_opt_value f in handle_exception d.error "float" v ( function | Some i -> float_of_string i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) module Admin_mod_string = Default(struct type a = string let to_default ?v () = let v = match v with | Some v -> v | None -> "" in let error = p ~a:[ a_class ["error"]; a_style "display:none"] [ ] in let d = Raw.textarea (pcdata v) in { node = div ~a:[ a_class ["dom_ext_string"] ] [ error; d ] ; value_ = `Textarea d; error = Some error ; } let to_dom s = to_default ~v:s () let save d = match d.value_ with | `Textarea s -> let v = Dom_manip.get_opt_value_textarea s in handle_exception d.error "string" v ( function | Some i -> i | None -> raise Empty_value ) | _ -> raise Wrong_dom_value end) let display_list (type s) (module A : Admin_mod with type a = s) () = let nodes = div ~a:[ a_class ["dom_ext_list_elems"]] [] in let node = div ~a:[ a_class ["dom_ext_list"]] [ nodes ] in let v = { node ; value_ = `List []; error = None; } in let add_single_node ?d () = let d = match d with | Some d -> A.to_dom d | None -> A.to_default () in v.value_ <- begin match v.value_ with | `List l -> `List (l @ [ d ]) | _ -> assert false end; let single_node = div ~a:[ a_class ["dom_ext_list_elem"]] [ d.node ] in let btn = button ~a:[ a_onclick (fun _ -> Manip.removeChild nodes single_node; v.value_ <- begin match v.value_ with | `List l -> `List (List.filter (fun d2 -> d <> d2) l) | _ -> assert false end; raise Eliom_lib.False ); a_class [ "btn"; "btn-warning"] ] ~button_type:`Button [ pcdata "delete" ] in Manip.appendChild single_node btn ; Manip.appendChild nodes single_node ; in let add_btn = button ~a:[ a_onclick (fun _ -> add_single_node (); raise Eliom_lib.False); a_class [ "btn"; "btn-info" ]] ~button_type:`Button [ pcdata "add" ] in Manip.appendChild node add_btn ; v,add_single_node module Admin_mod_list (A : Admin_mod) = Default(struct type a = A.a list let to_default ?v () = let v,add_single_node = display_list (module A) () in add_single_node () ; v let to_dom l = let v,add_single_node = display_list (module A) () in List.iter ( fun el -> add_single_node ~d:el () ) l; v let save d = match d.value_ with | `List l -> List.fold_left ( fun acc e -> try (A.save e::acc) with Empty_value -> acc ) [] (List.rev l) | _ -> raise Wrong_dom_value end) module Admin_mod_array (A : Admin_mod) = Default(struct type a = A.a array let to_default ?v () = let v,add_single_node = display_list (module A) () in add_single_node () ; v let to_dom a = let v,add_single_node = display_list (module A) () in Array.iter ( fun el -> add_single_node ~d:el () ) a; v let save d = match d.value_ with | `List l -> let l = List.fold_left ( fun acc e -> try (A.save e::acc) with Empty_value -> acc ) [] (List.rev l) in Array.of_list l | _ -> raise Wrong_dom_value end) module Admin_mod_option (A : Admin_mod) = Default(struct type a = A.a option let to_default ?v () = let d = A.to_default () in let node = div ~a:[ a_class ["dom_ext_option"]] [ d.node ] in { d with node; } let to_dom o = match o with | Some s -> let d = A.to_dom s in let node = div ~a:[ a_class ["dom_ext_option"]] [ d.node ] in { d with node; } | None -> to_default () let save o = try Some (A.save o) with Empty_value -> None end) }}
632e112d59977e672cf37a0db80e5d864c6cc5007176480adc06fc7e10aec367
racket/racket7
module-binding.rkt
#lang racket/base (require "../common/set.rkt" "../compile/serialize-property.rkt" "../compile/serialize-state.rkt" "full-binding.rkt") (provide make-module-binding module-binding-update module-binding? module-binding-module module-binding-phase module-binding-sym module-binding-nominal-module module-binding-nominal-phase module-binding-nominal-sym module-binding-nominal-require-phase module-binding-extra-inspector module-binding-extra-nominal-bindings deserialize-full-module-binding deserialize-simple-module-binding) ;; ---------------------------------------- (define (make-module-binding module phase sym #:wrt [wrt-sym sym] #:nominal-module [nominal-module module] #:nominal-phase [nominal-phase phase] #:nominal-sym [nominal-sym sym] #:nominal-require-phase [nominal-require-phase 0] #:frame-id [frame-id #f] #:free=id [free=id #f] #:extra-inspector [extra-inspector #f] #:extra-nominal-bindings [extra-nominal-bindings null]) (cond [(or frame-id free=id extra-inspector (not (and (eqv? nominal-phase phase) (eq? nominal-sym sym) (eqv? nominal-require-phase 0) (null? extra-nominal-bindings)))) (full-module-binding frame-id free=id module phase sym nominal-module nominal-phase nominal-sym nominal-require-phase extra-inspector extra-nominal-bindings)] [else (simple-module-binding module phase sym nominal-module)])) (define (module-binding-update b #:module [module (module-binding-module b)] #:phase [phase (module-binding-phase b)] #:sym [sym (module-binding-sym b)] #:nominal-module [nominal-module (module-binding-nominal-module b)] #:nominal-phase [nominal-phase (module-binding-nominal-phase b)] #:nominal-sym [nominal-sym (module-binding-nominal-sym b)] #:nominal-require-phase [nominal-require-phase (module-binding-nominal-require-phase b)] #:frame-id [frame-id (binding-frame-id b)] #:free=id [free=id (binding-free=id b)] #:extra-inspector [extra-inspector (module-binding-extra-inspector b)] #:extra-nominal-bindings [extra-nominal-bindings (module-binding-extra-nominal-bindings b)]) (make-module-binding module phase sym #:nominal-module nominal-module #:nominal-phase nominal-phase #:nominal-sym nominal-sym #:nominal-require-phase nominal-require-phase #:frame-id frame-id #:free=id free=id #:extra-inspector extra-inspector #:extra-nominal-bindings extra-nominal-bindings)) (define (module-binding? b) ;; must not overlap with `local-binding?` (or (simple-module-binding? b) (full-module-binding? b))) ;; See `identifier-binding` docs for information about these fields: (struct full-module-binding full-binding (module phase sym nominal-module nominal-phase nominal-sym nominal-require-phase extra-inspector ; preserves access to protected definitions extra-nominal-bindings) #:authentic #:transparent #:property prop:serialize (lambda (b ser-push! state) ;; Dropping the frame id may simplify the representation: (define simplified-b (if (full-binding-frame-id b) (module-binding-update b #:frame-id #f) b)) (cond [(full-module-binding? simplified-b) (ser-push! 'tag '#:module-binding) (ser-push! (full-module-binding-module b)) (ser-push! (full-module-binding-sym b)) (ser-push! (full-module-binding-phase b)) (ser-push! (full-module-binding-nominal-module b)) (ser-push! (full-module-binding-nominal-phase b)) (ser-push! (full-module-binding-nominal-sym b)) (ser-push! (full-module-binding-nominal-require-phase b)) (ser-push! (full-binding-free=id b)) (if (full-module-binding-extra-inspector b) (ser-push! 'tag '#:inspector) (ser-push! #f)) (ser-push! (full-module-binding-extra-nominal-bindings b))] [else (ser-push! simplified-b)]))) (struct simple-module-binding (module phase sym nominal-module) #:authentic #:transparent #:property prop:serialize (lambda (b ser-push! state) (ser-push! 'tag '#:simple-module-binding) (ser-push! (simple-module-binding-module b)) (ser-push! (simple-module-binding-sym b)) (ser-push! (simple-module-binding-phase b)) (ser-push! (simple-module-binding-nominal-module b)))) (define (deserialize-full-module-binding module sym phase nominal-module nominal-phase nominal-sym nominal-require-phase free=id extra-inspector extra-nominal-bindings) (make-module-binding module phase sym #:nominal-module nominal-module #:nominal-phase nominal-phase #:nominal-sym nominal-sym #:nominal-require-phase nominal-require-phase #:free=id free=id #:extra-inspector extra-inspector #:extra-nominal-bindings extra-nominal-bindings)) (define (deserialize-simple-module-binding module sym phase nominal-module) (simple-module-binding module phase sym nominal-module)) ;; ---------------------------------------- (define (module-binding-module b) (if (simple-module-binding? b) (simple-module-binding-module b) (full-module-binding-module b))) (define (module-binding-phase b) (if (simple-module-binding? b) (simple-module-binding-phase b) (full-module-binding-phase b))) (define (module-binding-sym b) (if (simple-module-binding? b) (simple-module-binding-sym b) (full-module-binding-sym b))) (define (module-binding-nominal-module b) (if (simple-module-binding? b) (simple-module-binding-nominal-module b) (full-module-binding-nominal-module b))) (define (module-binding-nominal-phase b) (if (simple-module-binding? b) (simple-module-binding-phase b) (full-module-binding-nominal-phase b))) (define (module-binding-nominal-sym b) (if (simple-module-binding? b) (simple-module-binding-sym b) (full-module-binding-nominal-sym b))) (define (module-binding-nominal-require-phase b) (if (simple-module-binding? b) 0 (full-module-binding-nominal-require-phase b))) (define (module-binding-extra-inspector b) (if (simple-module-binding? b) #f (full-module-binding-extra-inspector b))) (define (module-binding-extra-nominal-bindings b) (if (simple-module-binding? b) null (full-module-binding-extra-nominal-bindings b)))
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/expander/syntax/module-binding.rkt
racket
---------------------------------------- must not overlap with `local-binding?` See `identifier-binding` docs for information about these fields: preserves access to protected definitions Dropping the frame id may simplify the representation: ----------------------------------------
#lang racket/base (require "../common/set.rkt" "../compile/serialize-property.rkt" "../compile/serialize-state.rkt" "full-binding.rkt") (provide make-module-binding module-binding-update module-binding? module-binding-module module-binding-phase module-binding-sym module-binding-nominal-module module-binding-nominal-phase module-binding-nominal-sym module-binding-nominal-require-phase module-binding-extra-inspector module-binding-extra-nominal-bindings deserialize-full-module-binding deserialize-simple-module-binding) (define (make-module-binding module phase sym #:wrt [wrt-sym sym] #:nominal-module [nominal-module module] #:nominal-phase [nominal-phase phase] #:nominal-sym [nominal-sym sym] #:nominal-require-phase [nominal-require-phase 0] #:frame-id [frame-id #f] #:free=id [free=id #f] #:extra-inspector [extra-inspector #f] #:extra-nominal-bindings [extra-nominal-bindings null]) (cond [(or frame-id free=id extra-inspector (not (and (eqv? nominal-phase phase) (eq? nominal-sym sym) (eqv? nominal-require-phase 0) (null? extra-nominal-bindings)))) (full-module-binding frame-id free=id module phase sym nominal-module nominal-phase nominal-sym nominal-require-phase extra-inspector extra-nominal-bindings)] [else (simple-module-binding module phase sym nominal-module)])) (define (module-binding-update b #:module [module (module-binding-module b)] #:phase [phase (module-binding-phase b)] #:sym [sym (module-binding-sym b)] #:nominal-module [nominal-module (module-binding-nominal-module b)] #:nominal-phase [nominal-phase (module-binding-nominal-phase b)] #:nominal-sym [nominal-sym (module-binding-nominal-sym b)] #:nominal-require-phase [nominal-require-phase (module-binding-nominal-require-phase b)] #:frame-id [frame-id (binding-frame-id b)] #:free=id [free=id (binding-free=id b)] #:extra-inspector [extra-inspector (module-binding-extra-inspector b)] #:extra-nominal-bindings [extra-nominal-bindings (module-binding-extra-nominal-bindings b)]) (make-module-binding module phase sym #:nominal-module nominal-module #:nominal-phase nominal-phase #:nominal-sym nominal-sym #:nominal-require-phase nominal-require-phase #:frame-id frame-id #:free=id free=id #:extra-inspector extra-inspector #:extra-nominal-bindings extra-nominal-bindings)) (define (module-binding? b) (or (simple-module-binding? b) (full-module-binding? b))) (struct full-module-binding full-binding (module phase sym nominal-module nominal-phase nominal-sym nominal-require-phase extra-nominal-bindings) #:authentic #:transparent #:property prop:serialize (lambda (b ser-push! state) (define simplified-b (if (full-binding-frame-id b) (module-binding-update b #:frame-id #f) b)) (cond [(full-module-binding? simplified-b) (ser-push! 'tag '#:module-binding) (ser-push! (full-module-binding-module b)) (ser-push! (full-module-binding-sym b)) (ser-push! (full-module-binding-phase b)) (ser-push! (full-module-binding-nominal-module b)) (ser-push! (full-module-binding-nominal-phase b)) (ser-push! (full-module-binding-nominal-sym b)) (ser-push! (full-module-binding-nominal-require-phase b)) (ser-push! (full-binding-free=id b)) (if (full-module-binding-extra-inspector b) (ser-push! 'tag '#:inspector) (ser-push! #f)) (ser-push! (full-module-binding-extra-nominal-bindings b))] [else (ser-push! simplified-b)]))) (struct simple-module-binding (module phase sym nominal-module) #:authentic #:transparent #:property prop:serialize (lambda (b ser-push! state) (ser-push! 'tag '#:simple-module-binding) (ser-push! (simple-module-binding-module b)) (ser-push! (simple-module-binding-sym b)) (ser-push! (simple-module-binding-phase b)) (ser-push! (simple-module-binding-nominal-module b)))) (define (deserialize-full-module-binding module sym phase nominal-module nominal-phase nominal-sym nominal-require-phase free=id extra-inspector extra-nominal-bindings) (make-module-binding module phase sym #:nominal-module nominal-module #:nominal-phase nominal-phase #:nominal-sym nominal-sym #:nominal-require-phase nominal-require-phase #:free=id free=id #:extra-inspector extra-inspector #:extra-nominal-bindings extra-nominal-bindings)) (define (deserialize-simple-module-binding module sym phase nominal-module) (simple-module-binding module phase sym nominal-module)) (define (module-binding-module b) (if (simple-module-binding? b) (simple-module-binding-module b) (full-module-binding-module b))) (define (module-binding-phase b) (if (simple-module-binding? b) (simple-module-binding-phase b) (full-module-binding-phase b))) (define (module-binding-sym b) (if (simple-module-binding? b) (simple-module-binding-sym b) (full-module-binding-sym b))) (define (module-binding-nominal-module b) (if (simple-module-binding? b) (simple-module-binding-nominal-module b) (full-module-binding-nominal-module b))) (define (module-binding-nominal-phase b) (if (simple-module-binding? b) (simple-module-binding-phase b) (full-module-binding-nominal-phase b))) (define (module-binding-nominal-sym b) (if (simple-module-binding? b) (simple-module-binding-sym b) (full-module-binding-nominal-sym b))) (define (module-binding-nominal-require-phase b) (if (simple-module-binding? b) 0 (full-module-binding-nominal-require-phase b))) (define (module-binding-extra-inspector b) (if (simple-module-binding? b) #f (full-module-binding-extra-inspector b))) (define (module-binding-extra-nominal-bindings b) (if (simple-module-binding? b) null (full-module-binding-extra-nominal-bindings b)))
e5cad58394bd761b752218b2bdb33be70451f61d5621b5e874f565d52c156e96
kangj116/metabase-kylin-driver
project.clj
(defproject metabase/kylin-driver "1.0.0-SNAPSHOT-3.25.2" :min-lein-version "2.5.0" :dependencies [[org.apache.kylin/kylin-jdbc "2.6.4"]] :profiles {:provided {:dependencies [[org.clojure/clojure "1.10.1"] [metabase-core "1.0.0-SNAPSHOT"]]} :uberjar {:auto-clean true :aot :all :javac-options ["-target" "1.8", "-source" "1.8"] :target-path "target/%s" :uberjar-name "kylin.metabase-driver.jar"}})
null
https://raw.githubusercontent.com/kangj116/metabase-kylin-driver/165f6d0971be9fc746aae4933ab826287d08dee8/project.clj
clojure
(defproject metabase/kylin-driver "1.0.0-SNAPSHOT-3.25.2" :min-lein-version "2.5.0" :dependencies [[org.apache.kylin/kylin-jdbc "2.6.4"]] :profiles {:provided {:dependencies [[org.clojure/clojure "1.10.1"] [metabase-core "1.0.0-SNAPSHOT"]]} :uberjar {:auto-clean true :aot :all :javac-options ["-target" "1.8", "-source" "1.8"] :target-path "target/%s" :uberjar-name "kylin.metabase-driver.jar"}})
2aa3a8798d91dc82c694db598a6a15680a15814e399f601a0cdff53d87c02461
JPMoresmau/scion-class-browser
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Codec.Compression.Zlib as Zlib import Control.Monad.State.Strict import Data.Aeson import qualified Data.Aeson.Types as T import qualified Data.Attoparsec.ByteString as Atto import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.ByteString.UTF8 as BSU(fromString) import Server.PersistentCommands import System.Console.Haskeline import System.IO (hFlush, stdout, stderr) import System.Environment (getArgs) import Data.Version (showVersion) import Paths_scion_browser import Scion.PersistentBrowser.Util (logToStdout) import GHC.IO.Handle (hDuplicate,hDuplicateTo) main :: IO () main = do args <- getArgs case args of ("--version":_) -> putStrLn ("scion-browser executable, version " ++ showVersion version) ("--clear":_) -> run False _ -> run True run :: Bool -> IO() run doCompression=do runStateT (runInputT defaultSettings (loop doCompression)) initialState return () loop :: Bool -> InputT BrowserM () loop doCompression = do maybeLine <- getInputLine "" case maybeLine of ctrl+D or EOF Just line -> case Atto.parseOnly json (BSU.fromString line) of Left e -> liftIO (logToStdout ("error in command: " ++ e)) >> loop doCompression Right value -> case T.parse parseJSON value of Error e -> liftIO (logToStdout ("error in command: " ++ e)) >> loop doCompression Success cmd -> do stdout_excl <- liftIO $ hDuplicate stdout liftIO $ hDuplicateTo stderr stdout -- redirect stdout to stderr (res, continue) <- lift $ executeCommand cmd liftIO $ hDuplicateTo stdout_excl stdout -- redirect stdout to original stdout let encoded = LBS.append (encode res) "\n" compressed = if doCompression then Zlib.compressWith Zlib.defaultCompressParams { Zlib.compressLevel = Zlib.bestSpeed } encoded else encoded liftIO $ LBS.putStr compressed liftIO $ hFlush stdout when continue $ loop doCompression
null
https://raw.githubusercontent.com/JPMoresmau/scion-class-browser/572cc2c1177bdaa9558653cc1d941508cd4c7e5b/src/Main.hs
haskell
# LANGUAGE OverloadedStrings # redirect stdout to stderr redirect stdout to original stdout
module Main where import qualified Codec.Compression.Zlib as Zlib import Control.Monad.State.Strict import Data.Aeson import qualified Data.Aeson.Types as T import qualified Data.Attoparsec.ByteString as Atto import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.ByteString.UTF8 as BSU(fromString) import Server.PersistentCommands import System.Console.Haskeline import System.IO (hFlush, stdout, stderr) import System.Environment (getArgs) import Data.Version (showVersion) import Paths_scion_browser import Scion.PersistentBrowser.Util (logToStdout) import GHC.IO.Handle (hDuplicate,hDuplicateTo) main :: IO () main = do args <- getArgs case args of ("--version":_) -> putStrLn ("scion-browser executable, version " ++ showVersion version) ("--clear":_) -> run False _ -> run True run :: Bool -> IO() run doCompression=do runStateT (runInputT defaultSettings (loop doCompression)) initialState return () loop :: Bool -> InputT BrowserM () loop doCompression = do maybeLine <- getInputLine "" case maybeLine of ctrl+D or EOF Just line -> case Atto.parseOnly json (BSU.fromString line) of Left e -> liftIO (logToStdout ("error in command: " ++ e)) >> loop doCompression Right value -> case T.parse parseJSON value of Error e -> liftIO (logToStdout ("error in command: " ++ e)) >> loop doCompression Success cmd -> do stdout_excl <- liftIO $ hDuplicate stdout (res, continue) <- lift $ executeCommand cmd let encoded = LBS.append (encode res) "\n" compressed = if doCompression then Zlib.compressWith Zlib.defaultCompressParams { Zlib.compressLevel = Zlib.bestSpeed } encoded else encoded liftIO $ LBS.putStr compressed liftIO $ hFlush stdout when continue $ loop doCompression
ca3d9ae2f0868c1a239463b579c53679f2560cdf87254d10a69400bc782c450a
MaartenFaddegon/Hoed
Console.hs
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE LambdaCase #-} # LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedLists # # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # # LANGUAGE ViewPatterns # This file is part of the Haskell debugger Hoed . -- Copyright ( c ) Maarten Faddegon , 2014 - 2017 module Debug.Hoed.Console(debugSession, showGraph) where import Control.Monad import Control.Arrow (first, second) import Data.Char import Data.Foldable as F import Data.Graph.Libgraph as G import Data.List as List (foldl', group, mapAccumL, nub, sort) import qualified Data.Map.Strict as Map import qualified Data.IntMap.Strict as IntMap import Data.Maybe import Data.Sequence (Seq, ViewL (..), viewl, (<|)) import qualified Data.Sequence as Seq import qualified Data.Set as Set import Data.Text (Text, unpack) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import Data.Word import Debug.Hoed.Compat import Debug.Hoed.CompTree import Debug.Hoed.Observe import Debug.Hoed.Prop import Debug.Hoed.ReadLine import Debug.Hoed.Render import Debug.Hoed.Serialize import Prelude hiding (Right) import System.Directory import System.Exit import System.IO import System.Process import Text.PrettyPrint.FPretty hiding ((<$>)) import Text.Regex.TDFA import Text.Regex.TDFA.Text import Web.Browser # ANN module ( " HLint : ignore Use camelCase " : : String ) # -------------------------------------------------------------------------------- -- events type Id = Int -- | A representation of an event as a span data Span = Span { spanStart, spanEnd :: Id, polarity :: Bool } deriving (Eq, Ord, Show) -- | A representation of a trace as a span diagram: a list of columns of spans. type Spans = [ [Span] ] -- | The nesting depth of a span type Depth = Int -- | Recover the spans from the trace and arrange the columns such that they reflect span containment . A span is contained in another span @a@ if -- -- > start b > start a && end b < end a -- -- The span in column N is contained below N other spans. -- The renderer should draw the columns left to right. traceToSpans :: (UID -> EventWithId) -> Trace -> Spans traceToSpans lookupEvent = map sort . Map.elems . Map.fromListWith (++) . map (second (: [])) . snd . VG.ifoldl' (traceToSpans2' lookupEvent) ([], []) -- This version tries to distinguish between Fun events that terminate a span, and Fun events that signal a second application of a function traceToSpans2' :: (UID -> EventWithId) -> (Seq Id, [(Depth, Span)]) -> UID -> Event -> (Seq Id, [(Depth, Span)]) traceToSpans2' lookupEv (stack, result) uid e | isStart (change e) = (uid <| stack, result) | start :< stack' <- viewl stack , isEnd lookupEv uid e = ( stack' , (Seq.length stack', Span start uid (getPolarity e)) : result) | otherwise = (stack, result) where isStart Enter {} = True isStart _ = False getPolarity Event {change = Observe {}} = True getPolarity Event {eventParent = Parent p 0} | Event {change = Fun} <- event $ lookupEv p = not $ getPolarity (event $ lookupEv p) getPolarity Event {eventParent = Parent p _} = getPolarity (event $ lookupEv p) isEnd lookupEv _ Event {change = Cons {}} = True isEnd lookupEv uid me@(Event {change = Fun {}}) = case prevEv of Event{change = Enter{}} -> eventParent prevEv == eventParent me _ -> False where prevEv= event $ lookupEv (uid - 1) isEnd _ _ _ = False printTrace :: Trace -> IO () printTrace trace = putStrLn $ renderTrace' lookupEvent lookupDescs (traceToSpans lookupEvent trace, trace) -- fast lookup via an array where lookupEvent i = EventWithId i (trace VG.! i) lookupDescs = (fromMaybe [] . (`IntMap.lookup` (IntMap.fromListWith (++) [ (p, [EventWithId uid e]) | (uid, e@Event {eventParent = Parent p _}) <- VG.toList (VG.indexed trace) ]))) -- | TODO to be improved renderTrace :: (Spans, Trace) -> IO () renderTrace (spans, trace) = do putStrLn "Events" putStrLn "------" VG.mapM_ print trace putStrLn "" putStrLn "Spans" putStrLn "-----" mapM_ print spans renderTrace' :: (UID -> EventWithId) -> (UID -> [EventWithId]) -> (Spans, Trace) -> String renderTrace' lookupEvent lookupDescs (columns, events) = unlines renderedLines roll : : State - > ( Event , Maybe ColumnEvent ) - > ( State , String ) where depth = length columns ((_, evWidth), renderedLines) = mapAccumL roll (replicate (depth + 1) ' ', 0) $ align (uncurry EventWithId <$> VG.toList (VG.indexed events)) columnEvents -- Merge trace events and column events align (ev:evs) (colEv@(rowIx, colIx, pol, isStart):colEvs) | eventUID ev == rowIx = (ev, Just (colIx, pol, isStart)) : align evs colEvs | otherwise = (ev, Nothing) : align evs (colEv : colEvs) align [] [] = [] align ev [] = map (\x -> (x, Nothing)) ev Produce the output in three columns : spans , events , and explains -- For spans: keep a state of the open spans -- (the state is the rendering in characters) -- For events: keep a state of the widest event -- For explains: circularly reuse the widest event result roll (state, width) (ev, Nothing) | (w, s) <- showWithExplains ev = ((state, max width w), state ++ s) roll (state, width) (ev, Just (col, pol, True)) | state' <- update state col '|' , state'' <- update state col (if pol then '↑' else '┬') , (w, s) <- showWithExplains ev = ((state', max width w), state'' ++ s) roll (state, width) (ev, Just (col, pol, False)) | state' <- update state col ' ' , state'' <- update state col (if pol then '↓' else '┴') , (w, s) <- showWithExplains ev = ((state', max width w), state'' ++ s) columnEvents : : [ ( Line , ColIndex , StartOrEnd ) ] -- view the column spans as an event stream -- there's an event when a span starts or ends columnEvents = sortOn (\(a, b, c, d) -> a) [ (rowIx, colIx, pol, isStart) | (colIx, spans) <- zip [0 ..] columns , Span {..} <- spans , (rowIx, pol, isStart) <- [(spanStart, polarity, True), (spanEnd, polarity, False)] ] -- update element n of a list with a new value v update [] _ _ = [] update (_:xs) 0 v = v : xs update (x:xs) n v = x : update xs (n - 1) v -- show the event, add the necessary padding to fill the event col width, -- and append the explain. showWithExplains ev | showEv <- show ev , l <- length showEv = (l, showEv ++ replicate (evWidth - l) ' ' ++ explain (eventUID ev) (event ev)) -- Value requests explain uid Event {eventParent = Parent p 0, change = Enter} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- request arg of " ++ unpack name ++ "/" ++ show (dist + 1) explain uid Event {eventParent = Parent p 1, change = Enter} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- request result of " ++ unpack name ++ "/" ++ show (dist+1) explain uid Event {eventParent = Parent p 0, change = Enter} | Event {change = Observe name} <- event $ lookupEvent p = "-- request value of " ++ unpack name explain uid Event {eventParent = Parent p i, change = Enter} | Event {change = Cons ar name} <- event $ lookupEvent p = "-- request value of arg " ++ show i ++ " of constructor " ++ unpack name -- Arguments of functions explain uid me@Event {eventParent = Parent p 0, change = it@FunOrCons} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- arg " ++ show (dist+1) ++ " of " ++ unpack name ++ " is " ++ showChange it -- Results of functions explain uid Event {eventParent = Parent p 1, change = it@Fun} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- result of " ++ unpack name ++ "/" ++ show (dist+1) ++ " is a function" explain uid me@Event {eventParent = Parent p 1, change = Cons{}} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') , arg <- findArg p = "-- " ++ unpack name ++ "/" ++ show (dist+1) ++ " " ++ arg ++" = " ++ findValue lookupDescs (EventWithId uid me) -- Descendants of Cons events explain uid Event {eventParent = Parent p i, change = Cons _ name} | Event {change = Cons ar name'} <- event $ lookupEvent p = "-- arg " ++ show i ++ " of constructor " ++ unpack name' ++ " is " ++ unpack name -- Descendants of root events explain uid Event {eventParent = Parent p i, change = Fun} | Event {change = Observe name} <- event $ lookupEvent p = "-- " ++ unpack name ++ " is a function" explain uid me@Event {eventParent = Parent p i, change = Cons{}} | Event {change = Observe name} <- event $ lookupEvent p = "-- " ++ unpack name ++ " = " ++ findValue lookupDescs (EventWithId uid me) explain _ _ = "" -- Returns the root observation for this event, together with the distance to it findRoot Event{change = Observe name} = (name, 0) findRoot Event{eventParent} = succ <$> findRoot (event $ lookupEvent $ parentUID eventParent) variableNames = map (:[]) ['a'..'z'] showChange Fun = "a function" showChange (Cons ar name) = "constructor " ++ unpack name findArg eventUID = case [ e | e@(event -> Event{eventParent = Parent p 0, change = Cons{}}) <- lookupDescs eventUID] of [cons] -> findValue lookupDescs cons other -> error $ "Unexpected set of descendants of " ++ show eventUID ++ ": Fun - " ++ show other findValue :: (UID -> [EventWithId]) -> EventWithId -> String findValue lookupDescs = go where go :: EventWithId -> String go EventWithId {eventUID = me, event = Event {change = ConsChar c}} = show c go EventWithId {eventUID = me, event = Event {change = Cons ar name}} | ar == 0 = unpack name | isAlpha (T.head name) = unpack name ++ " " ++ unwords (map go $ sortOn (parentPosition . eventParent . event) [e | e@EventWithId {event = Event {change = Cons {}}} <- lookupDescs me]) | ar == 1 , [a] <- [e | e@EventWithId {event = Event {change = Cons {}}} <- lookupDescs me] = unpack name ++ go a | ar == 2 , [a, b] <- sortOn (parentPosition . eventParent . event) [e | e@(event -> Event {change = Cons {}}) <- lookupDescs me] = unwords [go a, unpack name, go b] go EventWithId {eventUID, event = Event {change = Enter {}}} | [e] <- lookupDescs eventUID = go e go other = error $ show other data RequestDetails = RD Int Explanation data ReturnDetails = ReturnFun | ReturnCons { constructor :: Text, arity :: Word8, value :: String} data Explanation = Observation String | Request RequestDetails | Return RequestDetails ReturnDetails instance Show Explanation where show (Observation obs) = "" show (Request r) = "request " ++ showRequest r show (Return r val) = showReturn r val showRequest (RD 0 (Observation name)) = unwords ["value of", name] showRequest (RD 0 (Return (RD _ (Observation name)) ReturnFun)) = unwords ["arg of", name] showRequest (RD 1 (Return (RD _ (Observation name)) ReturnFun)) = unwords ["result of", name] showRequest (RD n (Return _ (ReturnCons name ar _))) = unwords ["arg", show n, "of constructor", unpack name ] showReturn (RD p (Observation obs)) ReturnFun = unwords ["result of ", obs, "is a function"] showReturn (RD p req) (ReturnCons name ar val) = unwords [show req, "=", val] buildExplanation :: (UID -> EventWithId) -> (UID -> [EventWithId]) -> EventWithId -> Explanation buildExplanation lookupEvent lookupDescs = go . event where go Event{eventParent = Parent p pos, change = Enter} | par <- go (event $ lookupEvent p) = Request (RD 0 par) go Event{eventParent = Parent p pos, change = Fun} | Request rd <- go (event $ lookupEvent p) = Return rd ReturnFun go Event{eventParent = Parent p pos, change = Cons ar name} | Request rd <- go (event $ lookupEvent p) , value <- findValue lookupDescs (lookupEvent p) = Return rd (ReturnCons name ar value) eitherFunOrCons Fun{} = True eitherFunOrCons Cons {} = True eitherFunOrCons _ = False pattern FunOrCons <- (eitherFunOrCons -> True) -------------------------------------------------------------------------------- -- Debug session debugSession :: Trace -> CompTree -> [Propositions] -> IO () debugSession trace tree ps = case filter (not . isRootVertex) vs of [] -> putStrLn $ "No functions annotated with 'observe' expressions" ++ " or annotated functions not evaluated" (v:_) -> do noBuffering mainLoop v trace tree ps where (Graph _ vs _) = tree -------------------------------------------------------------------------------- -- Execution loop type Frame state = state -> IO (Transition state) data Transition state = Down (Frame state) | Up (Maybe state) | Next state | Same executionLoop :: [Frame state] -> state -> IO () executionLoop [] _ = return () executionLoop stack@(runFrame : parents) state = do transition <- runFrame state case transition of Same -> executionLoop stack state Next st -> executionLoop stack st Up Nothing -> executionLoop parents state Up (Just st) -> executionLoop parents st Down loop -> executionLoop (loop : stack) state -------------------------------------------------------------------------------- -- Commands type Args = [String] data Command state = Command { name :: String , argsDesc :: [String] , commandDesc :: Doc , parse :: Args -> Maybe (state -> IO (Transition state)) } interactiveFrame :: String -> [Command state] -> Frame state interactiveFrame prompt commands state = do input <- readLine (prompt ++ " ") (map name commands) let run = fromMaybe (\_ -> Same <$ showHelp commands) $ selectCommand input run state where selectCommand = selectFrom commands showHelp :: [Command state] -> IO () showHelp commands = putStrLn (pretty 80 $ vcat $ zipWith compose commandsBlock descriptionsBlock) where compose c d = text (pad c) <+> align d commandsBlock = [unwords (name : argsDesc) | Command {..} <- commands] descriptionsBlock = map commandDesc commands colWidth = maximum $ map length commandsBlock pad x = take (colWidth + 1) $ x ++ spaces spaces = repeat ' ' helpCommand :: [Command state1] -> Command state2 helpCommand commands = Command "help" [] "Shows this help screen." $ \case [] -> Just $ \_ -> Same <$ showHelp commands _ -> Nothing selectFrom :: [Command state] -> String -> Maybe (state -> IO (Transition state)) selectFrom commands = \case "" -> Nothing xx -> do let (h:t) = words xx c <- Map.lookup h commandsMap parse c t where commandsMap = Map.fromList [(name c, c) | c <- commands] -------------------------------------------------------------------------------- -- main menu data State = State { cv :: Vertex , trace :: Trace , compTree :: CompTree , ps :: [Propositions] } adbCommand, graphCommand, observeCommand, listCommand, exitCommand :: Command State adbCommand = Command "adb" [] "Start algorithmic debugging." $ \case [] -> Just $ \_ -> return $ Down adbFrame _ -> Nothing observeCommand = Command "observe" ["[regexp]"] ("Print computation statements that match the regular expression." </> "Omitting the expression prints all the statements.") $ \case args -> Just $ \State {..} -> let regexp = case args of [] -> ".*" ; _ -> unwords args in Same <$ printStmts compTree regexp listCommand = Command "list" [] "List all the observables collected." $ \args -> Just $ \State{..} -> let regexp = makeRegex $ case args of [] -> ".*" ; _ -> unwords args in Same <$ listStmts compTree regexp graphCommand = Command "graph" ["regexp"] ("Show the computation graph of an expression." </> "Requires graphviz dotp.") $ \case regexp -> Just $ \State{..} -> Same <$ graphStmts (unwords regexp) compTree eventsCommand = Command "events" [] "Print the Event trace (useful only for debugging Hoed)" $ \case [] -> Just $ \State{..} -> Same <$ printTrace trace _ -> Nothing exitCommand = Command "exit" [] "Leave the debugging session." $ \case [] -> Just $ \_ -> return (Up Nothing) _ -> Nothing mainLoopCommands :: [Command State] mainLoopCommands = sortOn name [ adbCommand #ifdef DEBUG , eventsCommand #endif , graphCommand , listCommand , observeCommand , exitCommand , helpCommand mainLoopCommands ] mainLoop :: Vertex -> Trace -> CompTree -> [Propositions] -> IO () mainLoop cv trace compTree ps = executionLoop [interactiveFrame "hdb>" mainLoopCommands] $ State cv trace compTree ps -------------------------------------------------------------------------------- -- list listStmts :: CompTree -> Regex -> IO () listStmts g regex = T.putStrLn $ T.unlines $ snub $ map (stmtLabel . vertexStmt . G.root) $ selectVertices (\v -> matchLabel v && isRelevantToUser g v) g where matchLabel RootVertex = False matchLabel v = match regex (unpack $ stmtLabel $ vertexStmt v) snub = map head . List.group . sort -- Restricted to statements for lambda functions or top level constants. -- Discards nested constant bindings isRelevantToUser :: Graph Vertex arc -> Vertex -> Bool isRelevantToUser _ Vertex {vertexStmt = CompStmt {stmtDetails = StmtLam {}}} = True isRelevantToUser g v@Vertex {vertexStmt = CompStmt {stmtDetails = StmtCon {}}} = RootVertex `elem` preds g v isRelevantToUser _ RootVertex = False -- | Returns the vertices satisfying the predicate. Doesn't alter the graph. selectVertices :: (Vertex->Bool) -> CompTree -> [CompTree] selectVertices pred g = [ g{G.root = v} | v <- vertices g, pred v] matchRegex :: Regex -> Vertex -> Bool matchRegex regex v = match regex $ noNewlines (vertexRes v) subGraphFromRoot :: Ord v => Graph v a -> Graph v a subGraphFromRoot g = subGraphFrom (G.root g) g subGraphFrom :: Ord v => v -> Graph v a -> Graph v a subGraphFrom v g = Graph {root = v, vertices = filteredV, arcs = filteredA} where filteredV = getPreorder $ getDfs g {G.root = v} filteredSet = Set.fromList filteredV filteredA = [ a | a <- arcs g , Set.member (source a) filteredSet && Set.member (target a) filteredSet ] -------------------------------------------------------------------------------- -- observe printStmts :: CompTree -> String -> IO () printStmts g regexp | null vs_filtered = putStrLn $ "There are no computation statements matching \"" ++ regexp ++ "\"." | otherwise = forM_ (zip [0..] $ nubOrd $ map printStmt vs_filtered) $ \(n,s) -> do putStrLn $ "--- stmt-" ++ show n ++ " ------------------------------------------" putStrLn s where vs_filtered = map subGraphFromRoot . sortOn (vertexRes . G.root) . selectVertices (\v -> matchRegex r v && isRelevantToUser g v) $ g r = makeRegex regexp nubOrd = nub -- We want nubOrd from the extra package printStmt :: CompTree -> String printStmt g = unlines $ show(vertexStmt $ G.root g) : concat [ " where" : map ((" " ++) . unpack) locals | not (null locals)] where locals = -- constants [ stmtRes c | Vertex {vertexStmt = c@CompStmt {stmtDetails = StmtCon{}}} <- succs g (G.root g) ] ++ -- function calls [ stmtRes c | Vertex {vertexStmt = c@CompStmt {stmtDetails = StmtLam{}}} <- succs g (G.root g) ] -------------------------------------------------------------------------- -- graph graphStmts :: String -> CompTree -> IO () graphStmts "" g = renderAndOpen g graphStmts (makeRegex -> r) g = do let matches = map subGraphFromRoot $ selectVertices (\v -> matchRegex r v && isRelevantToUser g v) g case matches of [one] -> renderAndOpen one _ -> putStrLn "More than one match, please select only one expression." renderAndOpen g = do tempDir <- getTemporaryDirectory (tempFile, hTempFile) <- openTempFile tempDir "hoed.svg" hClose hTempFile cmd "dot" ["-Tsvg", "-o", tempFile] (showGraph g) _success <- openBrowser ("file:///" ++ tempFile) return () showGraph g = showWith g showVertex showArc where showVertex RootVertex = ("\".\"", "shape=none") showVertex v = ("\"" ++ (escape . showCompStmt) v ++ "\"", "") showArc _ = "" showCompStmt = show . vertexStmt cmd line args inp = do putStrLn $ unwords (line:args) (exit, stdout, stderr) <- readProcessWithExitCode line args inp unless (exit == ExitSuccess) $ do putStrLn $ "Failed with code: " ++ show exit putStrLn stdout putStrLn stderr return exit -------------------------------------------------------------------------------- -- algorithmic debugging adbCommands :: [Command State] adbCommands = [judgeCommand Right, judgeCommand Wrong] judgeCommand :: Judgement -> Command State judgeCommand judgement = Command verbatim [] ("Judge computation statements" </> text verbatim </> " according to the intended behaviour/specification of the function.") $ \case [] -> Just $ \st -> adb_judge judgement st _ -> Nothing where verbatim | Right <- judgement = "right" | Wrong <- judgement = "wrong" adbFrame :: State -> IO (Transition State) adbFrame st@State{..} = case cv of RootVertex -> do putStrLn "Out of vertexes" return $ Up Nothing _ -> do adb_stats compTree print $ vertexStmt cv case lookupPropositions ps cv of Nothing -> interactive st Just prop -> do judgement <- judge trace prop cv unjudgedCharacterCount compTree case judgement of (Judge Right) -> adb_judge Right st (Judge Wrong) -> adb_judge Wrong st (Judge (Assisted msgs)) -> do mapM_ (putStrLn . toString) msgs interactive st (AlternativeTree newCompTree newTrace) -> do putStrLn "Discovered simpler tree!" let cv' = next RootVertex newCompTree return $ Next $ State cv' newTrace newCompTree ps where interactive = interactiveFrame "?" adbCommands toString (InconclusiveProperty s) = "inconclusive property: " ++ s toString (PassingProperty s) = "passing property: " ++ s adb_stats :: CompTree -> IO () adb_stats compTree = putStrLn $ "======================================================================= [" ++ show (length vs_w) ++ "-" ++ show (length vs_r) ++ "/" ++ show (length vs) ++ "]" where vs = filter (not . isRootVertex) (vertices compTree) vs_r = filter isRight vs vs_w = filter isWrong vs adb_judge :: Judgement -> State -> IO (Transition State) adb_judge jmt State{..} = case faultyVertices compTree' of (v:_) -> do adb_stats compTree' putStrLn $ "Fault located! In:\n" ++ vertexRes v return $ Up $ Just $ State cv trace compTree' ps [] -> return $ Next $ State cv_next trace compTree' ps where cv_next = next cv' compTree' compTree' = mapGraph replaceCV compTree replaceCV v = if vertexUID v === vertexUID cv' then cv' else v cv' = setJudgement cv jmt faultyVertices :: CompTree -> [Vertex] faultyVertices = findFaulty_dag getJudgement next :: Vertex -> CompTree -> Vertex next v ct = case getJudgement v of Right -> up Wrong -> down _ -> v where (up:_) = preds ct v (down:_) = filter unjudged (succs ct v) unjudged :: Vertex -> Bool unjudged = unjudged' . getJudgement where unjudged' Right = False unjudged' Wrong = False unjudged' _ = True
null
https://raw.githubusercontent.com/MaartenFaddegon/Hoed/8769d69e309928aab439b22bc3f3dbf5452acc77/Debug/Hoed/Console.hs
haskell
# LANGUAGE CPP # # LANGUAGE FlexibleContexts # # LANGUAGE PatternSynonyms # # LANGUAGE LambdaCase # ------------------------------------------------------------------------------ events | A representation of an event as a span | A representation of a trace as a span diagram: a list of columns of spans. | The nesting depth of a span | Recover the spans from the trace and arrange the columns such that they reflect > start b > start a && end b < end a The span in column N is contained below N other spans. The renderer should draw the columns left to right. This version tries to distinguish between Fun events that terminate a span, fast lookup via an array | TODO to be improved Merge trace events and column events For spans: keep a state of the open spans (the state is the rendering in characters) For events: keep a state of the widest event For explains: circularly reuse the widest event result view the column spans as an event stream there's an event when a span starts or ends update element n of a list with a new value v show the event, add the necessary padding to fill the event col width, and append the explain. Value requests Arguments of functions Results of functions Descendants of Cons events Descendants of root events Returns the root observation for this event, together with the distance to it ------------------------------------------------------------------------------ Debug session ------------------------------------------------------------------------------ Execution loop ------------------------------------------------------------------------------ Commands ------------------------------------------------------------------------------ main menu ------------------------------------------------------------------------------ list Restricted to statements for lambda functions or top level constants. Discards nested constant bindings | Returns the vertices satisfying the predicate. Doesn't alter the graph. ------------------------------------------------------------------------------ observe We want nubOrd from the extra package constants function calls ------------------------------------------------------------------------ graph ------------------------------------------------------------------------------ algorithmic debugging
# LANGUAGE NamedFieldPuns # # LANGUAGE OverloadedLists # # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # # LANGUAGE ViewPatterns # This file is part of the Haskell debugger Hoed . Copyright ( c ) Maarten Faddegon , 2014 - 2017 module Debug.Hoed.Console(debugSession, showGraph) where import Control.Monad import Control.Arrow (first, second) import Data.Char import Data.Foldable as F import Data.Graph.Libgraph as G import Data.List as List (foldl', group, mapAccumL, nub, sort) import qualified Data.Map.Strict as Map import qualified Data.IntMap.Strict as IntMap import Data.Maybe import Data.Sequence (Seq, ViewL (..), viewl, (<|)) import qualified Data.Sequence as Seq import qualified Data.Set as Set import Data.Text (Text, unpack) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import Data.Word import Debug.Hoed.Compat import Debug.Hoed.CompTree import Debug.Hoed.Observe import Debug.Hoed.Prop import Debug.Hoed.ReadLine import Debug.Hoed.Render import Debug.Hoed.Serialize import Prelude hiding (Right) import System.Directory import System.Exit import System.IO import System.Process import Text.PrettyPrint.FPretty hiding ((<$>)) import Text.Regex.TDFA import Text.Regex.TDFA.Text import Web.Browser # ANN module ( " HLint : ignore Use camelCase " : : String ) # type Id = Int data Span = Span { spanStart, spanEnd :: Id, polarity :: Bool } deriving (Eq, Ord, Show) type Spans = [ [Span] ] type Depth = Int span containment . A span is contained in another span @a@ if traceToSpans :: (UID -> EventWithId) -> Trace -> Spans traceToSpans lookupEvent = map sort . Map.elems . Map.fromListWith (++) . map (second (: [])) . snd . VG.ifoldl' (traceToSpans2' lookupEvent) ([], []) and Fun events that signal a second application of a function traceToSpans2' :: (UID -> EventWithId) -> (Seq Id, [(Depth, Span)]) -> UID -> Event -> (Seq Id, [(Depth, Span)]) traceToSpans2' lookupEv (stack, result) uid e | isStart (change e) = (uid <| stack, result) | start :< stack' <- viewl stack , isEnd lookupEv uid e = ( stack' , (Seq.length stack', Span start uid (getPolarity e)) : result) | otherwise = (stack, result) where isStart Enter {} = True isStart _ = False getPolarity Event {change = Observe {}} = True getPolarity Event {eventParent = Parent p 0} | Event {change = Fun} <- event $ lookupEv p = not $ getPolarity (event $ lookupEv p) getPolarity Event {eventParent = Parent p _} = getPolarity (event $ lookupEv p) isEnd lookupEv _ Event {change = Cons {}} = True isEnd lookupEv uid me@(Event {change = Fun {}}) = case prevEv of Event{change = Enter{}} -> eventParent prevEv == eventParent me _ -> False where prevEv= event $ lookupEv (uid - 1) isEnd _ _ _ = False printTrace :: Trace -> IO () printTrace trace = putStrLn $ renderTrace' lookupEvent lookupDescs (traceToSpans lookupEvent trace, trace) where lookupEvent i = EventWithId i (trace VG.! i) lookupDescs = (fromMaybe [] . (`IntMap.lookup` (IntMap.fromListWith (++) [ (p, [EventWithId uid e]) | (uid, e@Event {eventParent = Parent p _}) <- VG.toList (VG.indexed trace) ]))) renderTrace :: (Spans, Trace) -> IO () renderTrace (spans, trace) = do putStrLn "Events" putStrLn "------" VG.mapM_ print trace putStrLn "" putStrLn "Spans" putStrLn "-----" mapM_ print spans renderTrace' :: (UID -> EventWithId) -> (UID -> [EventWithId]) -> (Spans, Trace) -> String renderTrace' lookupEvent lookupDescs (columns, events) = unlines renderedLines roll : : State - > ( Event , Maybe ColumnEvent ) - > ( State , String ) where depth = length columns ((_, evWidth), renderedLines) = mapAccumL roll (replicate (depth + 1) ' ', 0) $ align (uncurry EventWithId <$> VG.toList (VG.indexed events)) columnEvents align (ev:evs) (colEv@(rowIx, colIx, pol, isStart):colEvs) | eventUID ev == rowIx = (ev, Just (colIx, pol, isStart)) : align evs colEvs | otherwise = (ev, Nothing) : align evs (colEv : colEvs) align [] [] = [] align ev [] = map (\x -> (x, Nothing)) ev Produce the output in three columns : spans , events , and explains roll (state, width) (ev, Nothing) | (w, s) <- showWithExplains ev = ((state, max width w), state ++ s) roll (state, width) (ev, Just (col, pol, True)) | state' <- update state col '|' , state'' <- update state col (if pol then '↑' else '┬') , (w, s) <- showWithExplains ev = ((state', max width w), state'' ++ s) roll (state, width) (ev, Just (col, pol, False)) | state' <- update state col ' ' , state'' <- update state col (if pol then '↓' else '┴') , (w, s) <- showWithExplains ev = ((state', max width w), state'' ++ s) columnEvents : : [ ( Line , ColIndex , StartOrEnd ) ] columnEvents = sortOn (\(a, b, c, d) -> a) [ (rowIx, colIx, pol, isStart) | (colIx, spans) <- zip [0 ..] columns , Span {..} <- spans , (rowIx, pol, isStart) <- [(spanStart, polarity, True), (spanEnd, polarity, False)] ] update [] _ _ = [] update (_:xs) 0 v = v : xs update (x:xs) n v = x : update xs (n - 1) v showWithExplains ev | showEv <- show ev , l <- length showEv = (l, showEv ++ replicate (evWidth - l) ' ' ++ explain (eventUID ev) (event ev)) explain uid Event {eventParent = Parent p 0, change = Enter} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- request arg of " ++ unpack name ++ "/" ++ show (dist + 1) explain uid Event {eventParent = Parent p 1, change = Enter} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- request result of " ++ unpack name ++ "/" ++ show (dist+1) explain uid Event {eventParent = Parent p 0, change = Enter} | Event {change = Observe name} <- event $ lookupEvent p = "-- request value of " ++ unpack name explain uid Event {eventParent = Parent p i, change = Enter} | Event {change = Cons ar name} <- event $ lookupEvent p = "-- request value of arg " ++ show i ++ " of constructor " ++ unpack name explain uid me@Event {eventParent = Parent p 0, change = it@FunOrCons} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- arg " ++ show (dist+1) ++ " of " ++ unpack name ++ " is " ++ showChange it explain uid Event {eventParent = Parent p 1, change = it@Fun} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') = "-- result of " ++ unpack name ++ "/" ++ show (dist+1) ++ " is a function" explain uid me@Event {eventParent = Parent p 1, change = Cons{}} | Event {change = Fun, eventParent = Parent p' _} <- event $ lookupEvent p , (name,dist) <- findRoot (event $ lookupEvent p') , arg <- findArg p = "-- " ++ unpack name ++ "/" ++ show (dist+1) ++ " " ++ arg ++" = " ++ findValue lookupDescs (EventWithId uid me) explain uid Event {eventParent = Parent p i, change = Cons _ name} | Event {change = Cons ar name'} <- event $ lookupEvent p = "-- arg " ++ show i ++ " of constructor " ++ unpack name' ++ " is " ++ unpack name explain uid Event {eventParent = Parent p i, change = Fun} | Event {change = Observe name} <- event $ lookupEvent p = "-- " ++ unpack name ++ " is a function" explain uid me@Event {eventParent = Parent p i, change = Cons{}} | Event {change = Observe name} <- event $ lookupEvent p = "-- " ++ unpack name ++ " = " ++ findValue lookupDescs (EventWithId uid me) explain _ _ = "" findRoot Event{change = Observe name} = (name, 0) findRoot Event{eventParent} = succ <$> findRoot (event $ lookupEvent $ parentUID eventParent) variableNames = map (:[]) ['a'..'z'] showChange Fun = "a function" showChange (Cons ar name) = "constructor " ++ unpack name findArg eventUID = case [ e | e@(event -> Event{eventParent = Parent p 0, change = Cons{}}) <- lookupDescs eventUID] of [cons] -> findValue lookupDescs cons other -> error $ "Unexpected set of descendants of " ++ show eventUID ++ ": Fun - " ++ show other findValue :: (UID -> [EventWithId]) -> EventWithId -> String findValue lookupDescs = go where go :: EventWithId -> String go EventWithId {eventUID = me, event = Event {change = ConsChar c}} = show c go EventWithId {eventUID = me, event = Event {change = Cons ar name}} | ar == 0 = unpack name | isAlpha (T.head name) = unpack name ++ " " ++ unwords (map go $ sortOn (parentPosition . eventParent . event) [e | e@EventWithId {event = Event {change = Cons {}}} <- lookupDescs me]) | ar == 1 , [a] <- [e | e@EventWithId {event = Event {change = Cons {}}} <- lookupDescs me] = unpack name ++ go a | ar == 2 , [a, b] <- sortOn (parentPosition . eventParent . event) [e | e@(event -> Event {change = Cons {}}) <- lookupDescs me] = unwords [go a, unpack name, go b] go EventWithId {eventUID, event = Event {change = Enter {}}} | [e] <- lookupDescs eventUID = go e go other = error $ show other data RequestDetails = RD Int Explanation data ReturnDetails = ReturnFun | ReturnCons { constructor :: Text, arity :: Word8, value :: String} data Explanation = Observation String | Request RequestDetails | Return RequestDetails ReturnDetails instance Show Explanation where show (Observation obs) = "" show (Request r) = "request " ++ showRequest r show (Return r val) = showReturn r val showRequest (RD 0 (Observation name)) = unwords ["value of", name] showRequest (RD 0 (Return (RD _ (Observation name)) ReturnFun)) = unwords ["arg of", name] showRequest (RD 1 (Return (RD _ (Observation name)) ReturnFun)) = unwords ["result of", name] showRequest (RD n (Return _ (ReturnCons name ar _))) = unwords ["arg", show n, "of constructor", unpack name ] showReturn (RD p (Observation obs)) ReturnFun = unwords ["result of ", obs, "is a function"] showReturn (RD p req) (ReturnCons name ar val) = unwords [show req, "=", val] buildExplanation :: (UID -> EventWithId) -> (UID -> [EventWithId]) -> EventWithId -> Explanation buildExplanation lookupEvent lookupDescs = go . event where go Event{eventParent = Parent p pos, change = Enter} | par <- go (event $ lookupEvent p) = Request (RD 0 par) go Event{eventParent = Parent p pos, change = Fun} | Request rd <- go (event $ lookupEvent p) = Return rd ReturnFun go Event{eventParent = Parent p pos, change = Cons ar name} | Request rd <- go (event $ lookupEvent p) , value <- findValue lookupDescs (lookupEvent p) = Return rd (ReturnCons name ar value) eitherFunOrCons Fun{} = True eitherFunOrCons Cons {} = True eitherFunOrCons _ = False pattern FunOrCons <- (eitherFunOrCons -> True) debugSession :: Trace -> CompTree -> [Propositions] -> IO () debugSession trace tree ps = case filter (not . isRootVertex) vs of [] -> putStrLn $ "No functions annotated with 'observe' expressions" ++ " or annotated functions not evaluated" (v:_) -> do noBuffering mainLoop v trace tree ps where (Graph _ vs _) = tree type Frame state = state -> IO (Transition state) data Transition state = Down (Frame state) | Up (Maybe state) | Next state | Same executionLoop :: [Frame state] -> state -> IO () executionLoop [] _ = return () executionLoop stack@(runFrame : parents) state = do transition <- runFrame state case transition of Same -> executionLoop stack state Next st -> executionLoop stack st Up Nothing -> executionLoop parents state Up (Just st) -> executionLoop parents st Down loop -> executionLoop (loop : stack) state type Args = [String] data Command state = Command { name :: String , argsDesc :: [String] , commandDesc :: Doc , parse :: Args -> Maybe (state -> IO (Transition state)) } interactiveFrame :: String -> [Command state] -> Frame state interactiveFrame prompt commands state = do input <- readLine (prompt ++ " ") (map name commands) let run = fromMaybe (\_ -> Same <$ showHelp commands) $ selectCommand input run state where selectCommand = selectFrom commands showHelp :: [Command state] -> IO () showHelp commands = putStrLn (pretty 80 $ vcat $ zipWith compose commandsBlock descriptionsBlock) where compose c d = text (pad c) <+> align d commandsBlock = [unwords (name : argsDesc) | Command {..} <- commands] descriptionsBlock = map commandDesc commands colWidth = maximum $ map length commandsBlock pad x = take (colWidth + 1) $ x ++ spaces spaces = repeat ' ' helpCommand :: [Command state1] -> Command state2 helpCommand commands = Command "help" [] "Shows this help screen." $ \case [] -> Just $ \_ -> Same <$ showHelp commands _ -> Nothing selectFrom :: [Command state] -> String -> Maybe (state -> IO (Transition state)) selectFrom commands = \case "" -> Nothing xx -> do let (h:t) = words xx c <- Map.lookup h commandsMap parse c t where commandsMap = Map.fromList [(name c, c) | c <- commands] data State = State { cv :: Vertex , trace :: Trace , compTree :: CompTree , ps :: [Propositions] } adbCommand, graphCommand, observeCommand, listCommand, exitCommand :: Command State adbCommand = Command "adb" [] "Start algorithmic debugging." $ \case [] -> Just $ \_ -> return $ Down adbFrame _ -> Nothing observeCommand = Command "observe" ["[regexp]"] ("Print computation statements that match the regular expression." </> "Omitting the expression prints all the statements.") $ \case args -> Just $ \State {..} -> let regexp = case args of [] -> ".*" ; _ -> unwords args in Same <$ printStmts compTree regexp listCommand = Command "list" [] "List all the observables collected." $ \args -> Just $ \State{..} -> let regexp = makeRegex $ case args of [] -> ".*" ; _ -> unwords args in Same <$ listStmts compTree regexp graphCommand = Command "graph" ["regexp"] ("Show the computation graph of an expression." </> "Requires graphviz dotp.") $ \case regexp -> Just $ \State{..} -> Same <$ graphStmts (unwords regexp) compTree eventsCommand = Command "events" [] "Print the Event trace (useful only for debugging Hoed)" $ \case [] -> Just $ \State{..} -> Same <$ printTrace trace _ -> Nothing exitCommand = Command "exit" [] "Leave the debugging session." $ \case [] -> Just $ \_ -> return (Up Nothing) _ -> Nothing mainLoopCommands :: [Command State] mainLoopCommands = sortOn name [ adbCommand #ifdef DEBUG , eventsCommand #endif , graphCommand , listCommand , observeCommand , exitCommand , helpCommand mainLoopCommands ] mainLoop :: Vertex -> Trace -> CompTree -> [Propositions] -> IO () mainLoop cv trace compTree ps = executionLoop [interactiveFrame "hdb>" mainLoopCommands] $ State cv trace compTree ps listStmts :: CompTree -> Regex -> IO () listStmts g regex = T.putStrLn $ T.unlines $ snub $ map (stmtLabel . vertexStmt . G.root) $ selectVertices (\v -> matchLabel v && isRelevantToUser g v) g where matchLabel RootVertex = False matchLabel v = match regex (unpack $ stmtLabel $ vertexStmt v) snub = map head . List.group . sort isRelevantToUser :: Graph Vertex arc -> Vertex -> Bool isRelevantToUser _ Vertex {vertexStmt = CompStmt {stmtDetails = StmtLam {}}} = True isRelevantToUser g v@Vertex {vertexStmt = CompStmt {stmtDetails = StmtCon {}}} = RootVertex `elem` preds g v isRelevantToUser _ RootVertex = False selectVertices :: (Vertex->Bool) -> CompTree -> [CompTree] selectVertices pred g = [ g{G.root = v} | v <- vertices g, pred v] matchRegex :: Regex -> Vertex -> Bool matchRegex regex v = match regex $ noNewlines (vertexRes v) subGraphFromRoot :: Ord v => Graph v a -> Graph v a subGraphFromRoot g = subGraphFrom (G.root g) g subGraphFrom :: Ord v => v -> Graph v a -> Graph v a subGraphFrom v g = Graph {root = v, vertices = filteredV, arcs = filteredA} where filteredV = getPreorder $ getDfs g {G.root = v} filteredSet = Set.fromList filteredV filteredA = [ a | a <- arcs g , Set.member (source a) filteredSet && Set.member (target a) filteredSet ] printStmts :: CompTree -> String -> IO () printStmts g regexp | null vs_filtered = putStrLn $ "There are no computation statements matching \"" ++ regexp ++ "\"." | otherwise = forM_ (zip [0..] $ nubOrd $ map printStmt vs_filtered) $ \(n,s) -> do putStrLn $ "--- stmt-" ++ show n ++ " ------------------------------------------" putStrLn s where vs_filtered = map subGraphFromRoot . sortOn (vertexRes . G.root) . selectVertices (\v -> matchRegex r v && isRelevantToUser g v) $ g r = makeRegex regexp printStmt :: CompTree -> String printStmt g = unlines $ show(vertexStmt $ G.root g) : concat [ " where" : map ((" " ++) . unpack) locals | not (null locals)] where locals = [ stmtRes c | Vertex {vertexStmt = c@CompStmt {stmtDetails = StmtCon{}}} <- succs g (G.root g) ] ++ [ stmtRes c | Vertex {vertexStmt = c@CompStmt {stmtDetails = StmtLam{}}} <- succs g (G.root g) ] graphStmts :: String -> CompTree -> IO () graphStmts "" g = renderAndOpen g graphStmts (makeRegex -> r) g = do let matches = map subGraphFromRoot $ selectVertices (\v -> matchRegex r v && isRelevantToUser g v) g case matches of [one] -> renderAndOpen one _ -> putStrLn "More than one match, please select only one expression." renderAndOpen g = do tempDir <- getTemporaryDirectory (tempFile, hTempFile) <- openTempFile tempDir "hoed.svg" hClose hTempFile cmd "dot" ["-Tsvg", "-o", tempFile] (showGraph g) _success <- openBrowser ("file:///" ++ tempFile) return () showGraph g = showWith g showVertex showArc where showVertex RootVertex = ("\".\"", "shape=none") showVertex v = ("\"" ++ (escape . showCompStmt) v ++ "\"", "") showArc _ = "" showCompStmt = show . vertexStmt cmd line args inp = do putStrLn $ unwords (line:args) (exit, stdout, stderr) <- readProcessWithExitCode line args inp unless (exit == ExitSuccess) $ do putStrLn $ "Failed with code: " ++ show exit putStrLn stdout putStrLn stderr return exit adbCommands :: [Command State] adbCommands = [judgeCommand Right, judgeCommand Wrong] judgeCommand :: Judgement -> Command State judgeCommand judgement = Command verbatim [] ("Judge computation statements" </> text verbatim </> " according to the intended behaviour/specification of the function.") $ \case [] -> Just $ \st -> adb_judge judgement st _ -> Nothing where verbatim | Right <- judgement = "right" | Wrong <- judgement = "wrong" adbFrame :: State -> IO (Transition State) adbFrame st@State{..} = case cv of RootVertex -> do putStrLn "Out of vertexes" return $ Up Nothing _ -> do adb_stats compTree print $ vertexStmt cv case lookupPropositions ps cv of Nothing -> interactive st Just prop -> do judgement <- judge trace prop cv unjudgedCharacterCount compTree case judgement of (Judge Right) -> adb_judge Right st (Judge Wrong) -> adb_judge Wrong st (Judge (Assisted msgs)) -> do mapM_ (putStrLn . toString) msgs interactive st (AlternativeTree newCompTree newTrace) -> do putStrLn "Discovered simpler tree!" let cv' = next RootVertex newCompTree return $ Next $ State cv' newTrace newCompTree ps where interactive = interactiveFrame "?" adbCommands toString (InconclusiveProperty s) = "inconclusive property: " ++ s toString (PassingProperty s) = "passing property: " ++ s adb_stats :: CompTree -> IO () adb_stats compTree = putStrLn $ "======================================================================= [" ++ show (length vs_w) ++ "-" ++ show (length vs_r) ++ "/" ++ show (length vs) ++ "]" where vs = filter (not . isRootVertex) (vertices compTree) vs_r = filter isRight vs vs_w = filter isWrong vs adb_judge :: Judgement -> State -> IO (Transition State) adb_judge jmt State{..} = case faultyVertices compTree' of (v:_) -> do adb_stats compTree' putStrLn $ "Fault located! In:\n" ++ vertexRes v return $ Up $ Just $ State cv trace compTree' ps [] -> return $ Next $ State cv_next trace compTree' ps where cv_next = next cv' compTree' compTree' = mapGraph replaceCV compTree replaceCV v = if vertexUID v === vertexUID cv' then cv' else v cv' = setJudgement cv jmt faultyVertices :: CompTree -> [Vertex] faultyVertices = findFaulty_dag getJudgement next :: Vertex -> CompTree -> Vertex next v ct = case getJudgement v of Right -> up Wrong -> down _ -> v where (up:_) = preds ct v (down:_) = filter unjudged (succs ct v) unjudged :: Vertex -> Bool unjudged = unjudged' . getJudgement where unjudged' Right = False unjudged' Wrong = False unjudged' _ = True
273b82f9329a124235d7a7da986d3b550ae8d435a6dd32c45a9b4fdcd3d5603d
xtendo-org/chips
Config.hs
module Config ( decode , encode , Config(..) , templateConfig , gitURLs ) where import Data.Maybe import Data.Text (Text) import Data.Monoid import System.Exit import Data.Aeson.TH import qualified Data.Yaml as Y templateConfig :: Text templateConfig = "\ \git:\n\ \# Add Git clone URLs for fish plugins here.\n\ \# For example, uncomment below to enable the fish-sensible plugin.\n\ \# - -sensible\n\ \github:\n\ \# Add GitHub repositories for fish plugins here.\n\ \# For example, uncomment below to enable the fish-sensible plugin.\n\ \# - simnalamburt/fish-sensible\n" data Config = Config { git :: Maybe [Text] , github :: Maybe [Text] } deriving Show -- DEBUG deriveJSON defaultOptions ''Config decode :: FilePath -> IO Config decode path = Y.decodeFileEither path >>= either (\ err -> die (errMsg ++ Y.prettyPrintParseException err)) return where errMsg = "Failed parsing " ++ path ++ ":\n" encode :: FilePath -> Config -> IO () encode = Y.encodeFile gitURLs :: Config -> [Text] gitURLs (Config mgits mgithubs) = gits ++ githubURLs where gits = fromMaybe [] mgits githubs = fromMaybe [] mgithubs githubURLs = ["/" <> url | url <- githubs]
null
https://raw.githubusercontent.com/xtendo-org/chips/54846413660536a24d4a9c884b6a33c2d86ad256/src/Config.hs
haskell
DEBUG
module Config ( decode , encode , Config(..) , templateConfig , gitURLs ) where import Data.Maybe import Data.Text (Text) import Data.Monoid import System.Exit import Data.Aeson.TH import qualified Data.Yaml as Y templateConfig :: Text templateConfig = "\ \git:\n\ \# Add Git clone URLs for fish plugins here.\n\ \# For example, uncomment below to enable the fish-sensible plugin.\n\ \# - -sensible\n\ \github:\n\ \# Add GitHub repositories for fish plugins here.\n\ \# For example, uncomment below to enable the fish-sensible plugin.\n\ \# - simnalamburt/fish-sensible\n" data Config = Config { git :: Maybe [Text] , github :: Maybe [Text] } deriveJSON defaultOptions ''Config decode :: FilePath -> IO Config decode path = Y.decodeFileEither path >>= either (\ err -> die (errMsg ++ Y.prettyPrintParseException err)) return where errMsg = "Failed parsing " ++ path ++ ":\n" encode :: FilePath -> Config -> IO () encode = Y.encodeFile gitURLs :: Config -> [Text] gitURLs (Config mgits mgithubs) = gits ++ githubURLs where gits = fromMaybe [] mgits githubs = fromMaybe [] mgithubs githubURLs = ["/" <> url | url <- githubs]
1258e348a6040fbdabc600cd7633ec5c58893b51f8caaa60e7ec833b02f66869
hakaru-dev/hakaru
Parser.hs
# LANGUAGE CPP , OverloadedStrings , {-# OPTIONS_GHC -Wall -fwarn-tabs -fno-warn-orphans #-} module Tests.Parser where import Prelude hiding (unlines) import Language.Hakaru.Parser.Parser (parseHakaru) import Language.Hakaru.Parser.AST import Data.String (IsString) import Data.Text import Test.HUnit import Test.QuickCheck.Arbitrary import Test.QuickCheck import Data.Function (on) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif arbNat :: Gen (Positive Integer) arbNat = arbitrary arbProb :: Gen (Positive Rational) arbProb = arbitrary instance Arbitrary Text where arbitrary = pack <$> ("x" ++) . show <$> getPositive <$> arbNat shrink xs = pack <$> shrink (unpack xs) instance Arbitrary Literal' where arbitrary = oneof [ Nat <$> getPositive <$> arbNat , Int <$> arbitrary , Prob <$> getPositive <$> arbProb , Real <$> arbitrary ] instance Arbitrary TypeAST' where arbitrary = frequency [ (20, TypeVar <$> arbitrary) , ( 1, TypeApp <$> arbitrary <*> arbitrary) , ( 1, TypeFun <$> arbitrary <*> arbitrary) ] instance Arbitrary NaryOp where arbitrary = elements [And, Or, Xor, Iff, Min, Max, Sum, Prod] instance Arbitrary a => Arbitrary (Pattern' a) where arbitrary = oneof [ PVar' <$> arbitrary , return PWild' , PData' <$> (DV <$> arbitrary <*> arbitrary) ] instance (Arbitrary a, IsString a) => Arbitrary (Branch' a) where arbitrary = Branch' <$> arbitrary <*> arbitrary instance (Arbitrary a, IsString a) => Arbitrary (AST' a) where arbitrary = frequency [ (10, Var <$> arbitrary) , ( 1, Lam <$> arbitrary <*> arbitrary <*> arbitrary) , ( 1, App <$> arbitrary <*> arbitrary) , ( 1, Let <$> arbitrary <*> arbitrary <*> arbitrary) , ( 1, If <$> arbitrary <*> arbitrary <*> arbitrary) , ( 1, Ann <$> arbitrary <*> arbitrary) , ( 1, return Infinity') , ( 1, ULiteral <$> arbitrary) , ( 1 , NaryOp < $ > arbitrary ) , ( 1, return (ArrayLiteral [])) , ( 1, Case <$> arbitrary <*> arbitrary) , ( 1, App (Var "dirac") <$> arbitrary) , ( 1, Bind <$> arbitrary <*> arbitrary <*> arbitrary) ] testParse :: Text -> AST' Text -> Assertion testParse s p = case parseHakaru s of Left m -> assertFailure (unpack s ++ "\n" ++ show m) Right p' -> assertEqual "" (withoutMetaE p) (withoutMetaE p') if1, if2, if3, if4, if5 :: Text ifAST1, ifAST2 :: AST' Text if1 = "if True: 1 else: 2" if2 = unlines ["if True: 1 else:" ,"2" ] if3 = unlines ["if True:" ," 1" ,"else:" ," 2" ] if4 = unlines ["if True:" ," 1 else: 2" ] if5 = unlines ["if True:" ," 4" ,"else:" ," if False:" ," 2" ," else:" ," 3" ] ifAST1 = If (Var "True") (ULiteral (Nat 1)) (ULiteral (Nat 2)) ifAST2 = If (Var "True") (ULiteral (Nat 4)) (If (Var "False") (ULiteral (Nat 2)) (ULiteral (Nat 3))) testIfs :: Test testIfs = test [ testParse if1 ifAST1 , testParse if2 ifAST1 , testParse if3 ifAST1 , testParse if4 ifAST1 , testParse if5 ifAST2 ] lam1 :: Text lam1 = "fn x nat: x+3" lam1AST :: AST' Text lam1AST = Lam "x" (TypeVar "nat") (NaryOp Sum [ Var "x" , ULiteral (Nat 3) ]) def1 :: Text def1 = unlines ["def foo(x nat):" ," x + 3" ,"foo(5)" ] def2 :: Text def2 = unlines ["def foo(x nat): x + 3" ,"foo(5)" ] def3 :: Text def3 = unlines ["def foo(x real):" ," y <~ normal(x,1.0)" ," return (y + y. real)" ,"foo(-(2.0))" ] def4 :: Text def4 = unlines ["def foo(x nat) nat:" ," x+3" ,"foo(5)" ] def1AST :: AST' Text def1AST = Let "foo" (Lam "x" (TypeVar "nat") (NaryOp Sum [Var "x", ULiteral (Nat 3)])) (App (Var "foo") (ULiteral (Nat 5))) def2AST :: AST' Text def2AST = Let "foo" (Lam "x" (TypeVar "real") (Bind "y" (App (App (Var "normal") (Var "x")) (ULiteral (Prob 1.0))) (App (Var "dirac") (Ann (NaryOp Sum [Var "y", Var "y"]) (TypeVar "real"))))) (App (Var "foo") (App (Var "negate") (ULiteral (Prob 2.0)))) def3AST :: AST' Text def3AST = Let "foo" (Ann (Lam "x" (TypeVar "nat") (NaryOp Sum [Var "x", ULiteral (Nat 3)])) (TypeFun (TypeVar "nat") (TypeVar "nat"))) (App (Var "foo") (ULiteral (Nat 5))) testLams :: Test testLams = test [ testParse lam1 lam1AST , testParse def1 def1AST , testParse def2 def1AST , testParse def3 def2AST , testParse def4 def3AST ] let1 :: Text let1 = unlines ["x = 3" ,"y = 2" ,"x + y" ] let1AST :: AST' Text let1AST = Let "x" (ULiteral (Nat 3)) (Let "y" (ULiteral (Nat 2)) (NaryOp Sum [Var "x", Var "y"])) testLets :: Test testLets = test [ testParse let1 let1AST ] bind1 :: Text bind1 = unlines ["x <~ uniform(0,1)" ,"y <~ normal(x, 1)" ,"dirac(y)" ] bind2 :: Text bind2 = unlines ["x <~ uniform(0,1)" ,"y <~ normal(x, 1)" ,"return y" ] bind1AST :: AST' Text bind1AST = Bind "x" (App (App (Var "uniform") (ULiteral (Nat 0))) (ULiteral (Nat 1))) (Bind "y" (App (App (Var "normal") (Var "x")) (ULiteral (Nat 1))) (App (Var "dirac") (Var "y"))) ret1 :: Text ret1 = "return return 3" ret1AST :: AST' Text ret1AST = App (Var "dirac") (App (Var "dirac") (ULiteral (Nat 3))) testBinds :: Test testBinds = test [ testParse bind1 bind1AST , testParse bind2 bind1AST , testParse ret1 ret1AST ] match1 :: Text match1 = unlines ["match e:" ," left(a): e1" ] match1AST :: AST' Text match1AST = Case (Var "e") [Branch' (PData' (DV "left" [PVar' "a"])) (Var "e1")] -- The space between _ and : is important match2 :: Text match2 = unlines ["match e:" ," _: e" ] match2AST :: AST' Text match2AST = Case (Var "e") [Branch' PWild' (Var "e")] match3 :: Text match3 = unlines ["match e:" ," a: e" ] match3AST :: AST' Text match3AST = Case (Var "e") [Branch' (PVar' "a") (Var "e")] match4 :: Text match4 = unlines ["match e:" ," left(a): e1" ," right(b): e2" ] match4AST :: AST' Text match4AST = Case (Var "e") [ Branch' (PData' (DV "left" [PVar' "a"])) (Var "e1") , Branch' (PData' (DV "right" [PVar' "b"])) (Var "e2") ] match5 :: Text match5 = unlines ["match e:" ," left(a):" ," e1" ," right(b):" ," e2" ] match5AST :: AST' Text match5AST = Case (Var "e") [ Branch' (PData' (DV "left" [PVar' "a"])) (Var "e1") , Branch' (PData' (DV "right" [PVar' "b"])) (Var "e2") ] match6 :: Text match6 = unlines ["match (2,3). pair(nat,nat):" ," (a,b): a+b" ] match6AST :: AST' Text match6AST = Case (Ann (Pair (ULiteral (Nat 2)) (ULiteral (Nat 3))) (TypeApp "pair" [TypeVar "nat",TypeVar "nat"])) [Branch' (PData' (DV "pair" [PVar' "a",PVar' "b"])) (NaryOp Sum [Var "a", Var "b"])] match7 :: Text match7 = unlines ["match (-2.0,1.0). pair(real,prob):" ," (a,b): normal(a,b)" ] match7AST :: AST' Text match7AST = Case (Ann (Pair (ULiteral (Real (-2.0))) (ULiteral (Prob 1.0))) (TypeApp "pair" [TypeVar "real",TypeVar "prob"])) [Branch' (PData' (DV "pair" [PVar' "a",PVar' "b"])) (App (App (Var "normal") (Var "a")) (Var "b"))] testMatches :: Test testMatches = test [ testParse match1 match1AST , testParse match2 match2AST , testParse match3 match3AST , testParse match4 match4AST , testParse match5 match5AST , testParse match6 match6AST , testParse match7 match7AST ] ann1 :: Text ann1 = "5. nat" ann1AST :: AST' Text ann1AST = Ann (ULiteral (Nat 5)) (TypeVar "nat") ann2 :: Text ann2 = "(2,3). pair(a,b)" ann2AST :: AST' Text ann2AST = Ann (Pair (ULiteral (Nat 2)) (ULiteral (Nat 3))) (TypeApp "pair" [TypeVar "a", TypeVar "b"]) ann3 :: Text ann3 = "f. a -> measure(a)" ann3AST :: AST' Text ann3AST = Ann (Var "f") (TypeFun (TypeVar "a") (TypeApp "measure" [(TypeVar "a")])) testAnn :: Test testAnn = test [ testParse ann1 ann1AST , testParse ann2 ann2AST , testParse ann3 ann3AST ] expect1 :: Text expect1 = unlines ["expect x <~ normal(0,1):" ," 1" ] expect1AST :: AST' Text expect1AST = _Expect "x" (App (App (Var "normal") (ULiteral (Nat 0))) (ULiteral (Nat 1))) (ULiteral (Nat 1)) expect2 :: Text expect2 = unlines ["expect x <~ normal(0,1):" ," unsafeProb(x*x)" ] expect2AST :: AST' Text expect2AST = _Expect "x" (App (App (Var "normal") (ULiteral (Nat 0))) (ULiteral (Nat 1))) (App (Var "unsafeProb") (NaryOp Prod [Var "x", Var "x"])) testExpect :: Test testExpect = test [ testParse expect1 expect1AST , testParse expect2 expect2AST ] array1 :: Text array1 = unlines ["array x of 12:" ," x + 1" ] array1AST :: AST' Text array1AST = Array "x" (ULiteral (Nat 12)) (NaryOp Sum [Var "x", ULiteral (Nat 1)]) array2 :: Text array2 = "2 + x[3][4]" array2AST :: AST' Text array2AST = NaryOp Sum [ ULiteral (Nat 2) , Index (Index (Var "x") (ULiteral (Nat 3))) (ULiteral (Nat 4)) ] array3 :: Text array3 = "[4, 0, 9]" array3AST :: AST' Text array3AST = ArrayLiteral [ ULiteral (Nat 4) , ULiteral (Nat 0) , ULiteral (Nat 9) ] testArray :: Test testArray = test [ testParse array1 array1AST , testParse array2 array2AST , testParse array3 array3AST ] easyRoad1 :: Text easyRoad1 = unlines ["noiseT <~ uniform(3, 8)" ,"noiseE <~ uniform(1, 4)" ,"x1 <~ normal( 0, noiseT)" ,"m1 <~ normal(x1, noiseE)" ,"x2 <~ normal(x1, noiseT)" ,"m2 <~ normal(x2, noiseE)" ,"return ((m1, m2), (noiseT, noiseE))" ] -- works in lax mode easyRoad2 :: Text easyRoad2 = unlines ["noiseT_ <~ uniform(3, 8)" ,"noiseE_ <~ uniform(1, 4)" ,"noiseT = unsafeProb(noiseT_)" ,"noiseE = unsafeProb(noiseE_)" ,"x1 <~ normal(0, noiseT)" ,"m1 <~ normal(x1, noiseE)" ,"x2 <~ normal(x1, noiseT)" ,"m2 <~ normal(x2, noiseE)" ,"return ((m1, m2), (noiseT, noiseE)). measure(pair(pair(real,real),pair(prob,prob)))" ] easyRoadAST :: AST' Text easyRoadAST = Bind "noiseT" (App (App (Var "uniform") (ULiteral (Nat 3))) (ULiteral (Nat 8))) (Bind "noiseE" (App (App (Var "uniform") (ULiteral (Nat 1))) (ULiteral (Nat 4))) (Bind "x1" (App (App (Var "normal") (ULiteral (Nat 0))) (Var "noiseT")) (Bind "m1" (App (App (Var "normal") (Var "x1")) (Var "noiseE")) (Bind "x2" (App (App (Var "normal") (Var "x1")) (Var "noiseT")) (Bind "m2" (App (App (Var "normal") (Var "x2")) (Var "noiseE")) (App (Var "dirac") (Pair (Pair (Var "m1") (Var "m2")) (Pair (Var "noiseT") (Var "noiseE"))))))))) testRoadmap :: Test testRoadmap = test [ testParse easyRoad1 easyRoadAST ] allTests :: Test allTests = test [ testIfs , testLams , testLets , testBinds , testMatches , testAnn , testExpect , testArray , testRoadmap ]
null
https://raw.githubusercontent.com/hakaru-dev/hakaru/94157c89ea136c3b654a85cce51f19351245a490/haskell/Tests/Parser.hs
haskell
# OPTIONS_GHC -Wall -fwarn-tabs -fno-warn-orphans # The space between _ and : is important works in lax mode
# LANGUAGE CPP , OverloadedStrings , module Tests.Parser where import Prelude hiding (unlines) import Language.Hakaru.Parser.Parser (parseHakaru) import Language.Hakaru.Parser.AST import Data.String (IsString) import Data.Text import Test.HUnit import Test.QuickCheck.Arbitrary import Test.QuickCheck import Data.Function (on) #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif arbNat :: Gen (Positive Integer) arbNat = arbitrary arbProb :: Gen (Positive Rational) arbProb = arbitrary instance Arbitrary Text where arbitrary = pack <$> ("x" ++) . show <$> getPositive <$> arbNat shrink xs = pack <$> shrink (unpack xs) instance Arbitrary Literal' where arbitrary = oneof [ Nat <$> getPositive <$> arbNat , Int <$> arbitrary , Prob <$> getPositive <$> arbProb , Real <$> arbitrary ] instance Arbitrary TypeAST' where arbitrary = frequency [ (20, TypeVar <$> arbitrary) , ( 1, TypeApp <$> arbitrary <*> arbitrary) , ( 1, TypeFun <$> arbitrary <*> arbitrary) ] instance Arbitrary NaryOp where arbitrary = elements [And, Or, Xor, Iff, Min, Max, Sum, Prod] instance Arbitrary a => Arbitrary (Pattern' a) where arbitrary = oneof [ PVar' <$> arbitrary , return PWild' , PData' <$> (DV <$> arbitrary <*> arbitrary) ] instance (Arbitrary a, IsString a) => Arbitrary (Branch' a) where arbitrary = Branch' <$> arbitrary <*> arbitrary instance (Arbitrary a, IsString a) => Arbitrary (AST' a) where arbitrary = frequency [ (10, Var <$> arbitrary) , ( 1, Lam <$> arbitrary <*> arbitrary <*> arbitrary) , ( 1, App <$> arbitrary <*> arbitrary) , ( 1, Let <$> arbitrary <*> arbitrary <*> arbitrary) , ( 1, If <$> arbitrary <*> arbitrary <*> arbitrary) , ( 1, Ann <$> arbitrary <*> arbitrary) , ( 1, return Infinity') , ( 1, ULiteral <$> arbitrary) , ( 1 , NaryOp < $ > arbitrary ) , ( 1, return (ArrayLiteral [])) , ( 1, Case <$> arbitrary <*> arbitrary) , ( 1, App (Var "dirac") <$> arbitrary) , ( 1, Bind <$> arbitrary <*> arbitrary <*> arbitrary) ] testParse :: Text -> AST' Text -> Assertion testParse s p = case parseHakaru s of Left m -> assertFailure (unpack s ++ "\n" ++ show m) Right p' -> assertEqual "" (withoutMetaE p) (withoutMetaE p') if1, if2, if3, if4, if5 :: Text ifAST1, ifAST2 :: AST' Text if1 = "if True: 1 else: 2" if2 = unlines ["if True: 1 else:" ,"2" ] if3 = unlines ["if True:" ," 1" ,"else:" ," 2" ] if4 = unlines ["if True:" ," 1 else: 2" ] if5 = unlines ["if True:" ," 4" ,"else:" ," if False:" ," 2" ," else:" ," 3" ] ifAST1 = If (Var "True") (ULiteral (Nat 1)) (ULiteral (Nat 2)) ifAST2 = If (Var "True") (ULiteral (Nat 4)) (If (Var "False") (ULiteral (Nat 2)) (ULiteral (Nat 3))) testIfs :: Test testIfs = test [ testParse if1 ifAST1 , testParse if2 ifAST1 , testParse if3 ifAST1 , testParse if4 ifAST1 , testParse if5 ifAST2 ] lam1 :: Text lam1 = "fn x nat: x+3" lam1AST :: AST' Text lam1AST = Lam "x" (TypeVar "nat") (NaryOp Sum [ Var "x" , ULiteral (Nat 3) ]) def1 :: Text def1 = unlines ["def foo(x nat):" ," x + 3" ,"foo(5)" ] def2 :: Text def2 = unlines ["def foo(x nat): x + 3" ,"foo(5)" ] def3 :: Text def3 = unlines ["def foo(x real):" ," y <~ normal(x,1.0)" ," return (y + y. real)" ,"foo(-(2.0))" ] def4 :: Text def4 = unlines ["def foo(x nat) nat:" ," x+3" ,"foo(5)" ] def1AST :: AST' Text def1AST = Let "foo" (Lam "x" (TypeVar "nat") (NaryOp Sum [Var "x", ULiteral (Nat 3)])) (App (Var "foo") (ULiteral (Nat 5))) def2AST :: AST' Text def2AST = Let "foo" (Lam "x" (TypeVar "real") (Bind "y" (App (App (Var "normal") (Var "x")) (ULiteral (Prob 1.0))) (App (Var "dirac") (Ann (NaryOp Sum [Var "y", Var "y"]) (TypeVar "real"))))) (App (Var "foo") (App (Var "negate") (ULiteral (Prob 2.0)))) def3AST :: AST' Text def3AST = Let "foo" (Ann (Lam "x" (TypeVar "nat") (NaryOp Sum [Var "x", ULiteral (Nat 3)])) (TypeFun (TypeVar "nat") (TypeVar "nat"))) (App (Var "foo") (ULiteral (Nat 5))) testLams :: Test testLams = test [ testParse lam1 lam1AST , testParse def1 def1AST , testParse def2 def1AST , testParse def3 def2AST , testParse def4 def3AST ] let1 :: Text let1 = unlines ["x = 3" ,"y = 2" ,"x + y" ] let1AST :: AST' Text let1AST = Let "x" (ULiteral (Nat 3)) (Let "y" (ULiteral (Nat 2)) (NaryOp Sum [Var "x", Var "y"])) testLets :: Test testLets = test [ testParse let1 let1AST ] bind1 :: Text bind1 = unlines ["x <~ uniform(0,1)" ,"y <~ normal(x, 1)" ,"dirac(y)" ] bind2 :: Text bind2 = unlines ["x <~ uniform(0,1)" ,"y <~ normal(x, 1)" ,"return y" ] bind1AST :: AST' Text bind1AST = Bind "x" (App (App (Var "uniform") (ULiteral (Nat 0))) (ULiteral (Nat 1))) (Bind "y" (App (App (Var "normal") (Var "x")) (ULiteral (Nat 1))) (App (Var "dirac") (Var "y"))) ret1 :: Text ret1 = "return return 3" ret1AST :: AST' Text ret1AST = App (Var "dirac") (App (Var "dirac") (ULiteral (Nat 3))) testBinds :: Test testBinds = test [ testParse bind1 bind1AST , testParse bind2 bind1AST , testParse ret1 ret1AST ] match1 :: Text match1 = unlines ["match e:" ," left(a): e1" ] match1AST :: AST' Text match1AST = Case (Var "e") [Branch' (PData' (DV "left" [PVar' "a"])) (Var "e1")] match2 :: Text match2 = unlines ["match e:" ," _: e" ] match2AST :: AST' Text match2AST = Case (Var "e") [Branch' PWild' (Var "e")] match3 :: Text match3 = unlines ["match e:" ," a: e" ] match3AST :: AST' Text match3AST = Case (Var "e") [Branch' (PVar' "a") (Var "e")] match4 :: Text match4 = unlines ["match e:" ," left(a): e1" ," right(b): e2" ] match4AST :: AST' Text match4AST = Case (Var "e") [ Branch' (PData' (DV "left" [PVar' "a"])) (Var "e1") , Branch' (PData' (DV "right" [PVar' "b"])) (Var "e2") ] match5 :: Text match5 = unlines ["match e:" ," left(a):" ," e1" ," right(b):" ," e2" ] match5AST :: AST' Text match5AST = Case (Var "e") [ Branch' (PData' (DV "left" [PVar' "a"])) (Var "e1") , Branch' (PData' (DV "right" [PVar' "b"])) (Var "e2") ] match6 :: Text match6 = unlines ["match (2,3). pair(nat,nat):" ," (a,b): a+b" ] match6AST :: AST' Text match6AST = Case (Ann (Pair (ULiteral (Nat 2)) (ULiteral (Nat 3))) (TypeApp "pair" [TypeVar "nat",TypeVar "nat"])) [Branch' (PData' (DV "pair" [PVar' "a",PVar' "b"])) (NaryOp Sum [Var "a", Var "b"])] match7 :: Text match7 = unlines ["match (-2.0,1.0). pair(real,prob):" ," (a,b): normal(a,b)" ] match7AST :: AST' Text match7AST = Case (Ann (Pair (ULiteral (Real (-2.0))) (ULiteral (Prob 1.0))) (TypeApp "pair" [TypeVar "real",TypeVar "prob"])) [Branch' (PData' (DV "pair" [PVar' "a",PVar' "b"])) (App (App (Var "normal") (Var "a")) (Var "b"))] testMatches :: Test testMatches = test [ testParse match1 match1AST , testParse match2 match2AST , testParse match3 match3AST , testParse match4 match4AST , testParse match5 match5AST , testParse match6 match6AST , testParse match7 match7AST ] ann1 :: Text ann1 = "5. nat" ann1AST :: AST' Text ann1AST = Ann (ULiteral (Nat 5)) (TypeVar "nat") ann2 :: Text ann2 = "(2,3). pair(a,b)" ann2AST :: AST' Text ann2AST = Ann (Pair (ULiteral (Nat 2)) (ULiteral (Nat 3))) (TypeApp "pair" [TypeVar "a", TypeVar "b"]) ann3 :: Text ann3 = "f. a -> measure(a)" ann3AST :: AST' Text ann3AST = Ann (Var "f") (TypeFun (TypeVar "a") (TypeApp "measure" [(TypeVar "a")])) testAnn :: Test testAnn = test [ testParse ann1 ann1AST , testParse ann2 ann2AST , testParse ann3 ann3AST ] expect1 :: Text expect1 = unlines ["expect x <~ normal(0,1):" ," 1" ] expect1AST :: AST' Text expect1AST = _Expect "x" (App (App (Var "normal") (ULiteral (Nat 0))) (ULiteral (Nat 1))) (ULiteral (Nat 1)) expect2 :: Text expect2 = unlines ["expect x <~ normal(0,1):" ," unsafeProb(x*x)" ] expect2AST :: AST' Text expect2AST = _Expect "x" (App (App (Var "normal") (ULiteral (Nat 0))) (ULiteral (Nat 1))) (App (Var "unsafeProb") (NaryOp Prod [Var "x", Var "x"])) testExpect :: Test testExpect = test [ testParse expect1 expect1AST , testParse expect2 expect2AST ] array1 :: Text array1 = unlines ["array x of 12:" ," x + 1" ] array1AST :: AST' Text array1AST = Array "x" (ULiteral (Nat 12)) (NaryOp Sum [Var "x", ULiteral (Nat 1)]) array2 :: Text array2 = "2 + x[3][4]" array2AST :: AST' Text array2AST = NaryOp Sum [ ULiteral (Nat 2) , Index (Index (Var "x") (ULiteral (Nat 3))) (ULiteral (Nat 4)) ] array3 :: Text array3 = "[4, 0, 9]" array3AST :: AST' Text array3AST = ArrayLiteral [ ULiteral (Nat 4) , ULiteral (Nat 0) , ULiteral (Nat 9) ] testArray :: Test testArray = test [ testParse array1 array1AST , testParse array2 array2AST , testParse array3 array3AST ] easyRoad1 :: Text easyRoad1 = unlines ["noiseT <~ uniform(3, 8)" ,"noiseE <~ uniform(1, 4)" ,"x1 <~ normal( 0, noiseT)" ,"m1 <~ normal(x1, noiseE)" ,"x2 <~ normal(x1, noiseT)" ,"m2 <~ normal(x2, noiseE)" ,"return ((m1, m2), (noiseT, noiseE))" ] easyRoad2 :: Text easyRoad2 = unlines ["noiseT_ <~ uniform(3, 8)" ,"noiseE_ <~ uniform(1, 4)" ,"noiseT = unsafeProb(noiseT_)" ,"noiseE = unsafeProb(noiseE_)" ,"x1 <~ normal(0, noiseT)" ,"m1 <~ normal(x1, noiseE)" ,"x2 <~ normal(x1, noiseT)" ,"m2 <~ normal(x2, noiseE)" ,"return ((m1, m2), (noiseT, noiseE)). measure(pair(pair(real,real),pair(prob,prob)))" ] easyRoadAST :: AST' Text easyRoadAST = Bind "noiseT" (App (App (Var "uniform") (ULiteral (Nat 3))) (ULiteral (Nat 8))) (Bind "noiseE" (App (App (Var "uniform") (ULiteral (Nat 1))) (ULiteral (Nat 4))) (Bind "x1" (App (App (Var "normal") (ULiteral (Nat 0))) (Var "noiseT")) (Bind "m1" (App (App (Var "normal") (Var "x1")) (Var "noiseE")) (Bind "x2" (App (App (Var "normal") (Var "x1")) (Var "noiseT")) (Bind "m2" (App (App (Var "normal") (Var "x2")) (Var "noiseE")) (App (Var "dirac") (Pair (Pair (Var "m1") (Var "m2")) (Pair (Var "noiseT") (Var "noiseE"))))))))) testRoadmap :: Test testRoadmap = test [ testParse easyRoad1 easyRoadAST ] allTests :: Test allTests = test [ testIfs , testLams , testLets , testBinds , testMatches , testAnn , testExpect , testArray , testRoadmap ]
ccae7743af2dea50d55b87fbec58c5df88cc647954d2ea82896d90029ce4df16
keera-studios/haskell-titan
Builder.hs
-- | -- Copyright : ( C ) Keera Studios Ltd , 2018 -- License : GPL-3 Maintainer : module Hails.Graphics.UI.Gtk.Builder where import Graphics.UI.Gtk -- | Returns a builder from which the objects in this part of the interface -- can be accessed. loadDefaultInterface :: (String -> IO String) -> IO Builder loadDefaultInterface getDataFileName = loadInterface =<< getDataFileName "Interface.glade" -- | Returns a builder from which the objects in this part of the interface -- can be accessed. loadInterface :: String -> IO Builder loadInterface builderPath = do builder <- builderNew builderAddFromFile builder builderPath return builder -- | Returns an element from a builder fromBuilder :: (GObjectClass cls) => (GObject -> cls) -> String -> Builder -> IO cls fromBuilder f s b = builderGetObject b f s
null
https://raw.githubusercontent.com/keera-studios/haskell-titan/958ddd2b468af00db46004a683c1c7aebe81526c/titan/src/Hails/Graphics/UI/Gtk/Builder.hs
haskell
| License : GPL-3 | Returns a builder from which the objects in this part of the interface can be accessed. | Returns a builder from which the objects in this part of the interface can be accessed. | Returns an element from a builder
Copyright : ( C ) Keera Studios Ltd , 2018 Maintainer : module Hails.Graphics.UI.Gtk.Builder where import Graphics.UI.Gtk loadDefaultInterface :: (String -> IO String) -> IO Builder loadDefaultInterface getDataFileName = loadInterface =<< getDataFileName "Interface.glade" loadInterface :: String -> IO Builder loadInterface builderPath = do builder <- builderNew builderAddFromFile builder builderPath return builder fromBuilder :: (GObjectClass cls) => (GObject -> cls) -> String -> Builder -> IO cls fromBuilder f s b = builderGetObject b f s
5425e85b44561f9d3715841cc5b0df052645425944fb83d6f7bbbe72114d3c2f
anishathalye/knox
main.rkt
#lang racket/base (require syntax/parse/define) (define-simple-macro (require+provide module-path:str ...) (begin (require module-path ...) (provide (all-from-out module-path) ...))) (require+provide "concretize.rkt" "convenience.rkt" "dependence.rkt" "addressable-struct.rkt" "lens.rkt" "subsumption.rkt" "serialization.rkt" "overapproximate.rkt" "substitution.rkt")
null
https://raw.githubusercontent.com/anishathalye/knox/161cda3e5274cc69012830f477749954ddcf736d/rosutil/main.rkt
racket
#lang racket/base (require syntax/parse/define) (define-simple-macro (require+provide module-path:str ...) (begin (require module-path ...) (provide (all-from-out module-path) ...))) (require+provide "concretize.rkt" "convenience.rkt" "dependence.rkt" "addressable-struct.rkt" "lens.rkt" "subsumption.rkt" "serialization.rkt" "overapproximate.rkt" "substitution.rkt")
3e5d36af8a8036666045e6d8c85203f20bb135a0e9fc0ebdc45b317e9a837865
qnikst/HaskellNet
pop3.hs
import System.IO import Network.HaskellNet.POP3 import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Char8 as BS import Data.Char import Data.ByteString (ByteString) popServer = "pop3.mail.org" username = "" password = "" main = do con <- connectPop3 popServer print "connected" userPass con username password num <- list con 4 print $ "num " ++ (show num) msg <- retr con 1 print msg closePop3 con
null
https://raw.githubusercontent.com/qnikst/HaskellNet/34e3ec8fb2e5071ecff574fc951dbfe356f87bed/example/pop3.hs
haskell
import System.IO import Network.HaskellNet.POP3 import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Char8 as BS import Data.Char import Data.ByteString (ByteString) popServer = "pop3.mail.org" username = "" password = "" main = do con <- connectPop3 popServer print "connected" userPass con username password num <- list con 4 print $ "num " ++ (show num) msg <- retr con 1 print msg closePop3 con
00f131281e61bb11ad3db32d11d6d774a844e389cb716c1c0a00f486a750c422
hiredman/clojurebot
pqueue.clj
(ns hiredman.pqueue (:refer-clojure :exclude [first conj seq pop peek empty]) (:require [clojure.core :as cc])) (def empty clojure.lang.PersistentQueue/EMPTY) (defn seq "returns a lazy sequence of the items in the priority queue" [pq] (cc/seq (map second pq))) (defn peek [pq] (cc/first (cc/peek pq))) (defn pop [pq] (pop pq)) (defn first "returns the first item in a priority queue" [pq] (peek pq)) (defn conj [que & values] (let [entries (cc/seq (apply hash-map values)) s (concat entries (cc/seq que))] (into empty (sort-by #(if-let [x (cc/first %)] x 0) s))))
null
https://raw.githubusercontent.com/hiredman/clojurebot/1e8bde92f2dd45bb7928d4db17de8ec48557ead1/src/hiredman/pqueue.clj
clojure
(ns hiredman.pqueue (:refer-clojure :exclude [first conj seq pop peek empty]) (:require [clojure.core :as cc])) (def empty clojure.lang.PersistentQueue/EMPTY) (defn seq "returns a lazy sequence of the items in the priority queue" [pq] (cc/seq (map second pq))) (defn peek [pq] (cc/first (cc/peek pq))) (defn pop [pq] (pop pq)) (defn first "returns the first item in a priority queue" [pq] (peek pq)) (defn conj [que & values] (let [entries (cc/seq (apply hash-map values)) s (concat entries (cc/seq que))] (into empty (sort-by #(if-let [x (cc/first %)] x 0) s))))
e9ad7cd2d283fc7641dd2d62e1369500f8085b8ed02f3bc4d693022401f89b89
serokell/qtah
SceneEventListener.hs
This file is part of Qtah . -- Copyright 2015 - 2018 The Qtah Authors . -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation , either version 3 of the License , or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . -- You should have received a copy of the GNU Lesser General Public License -- along with this program. If not, see </>. module Graphics.UI.Qtah.Generator.Interface.Internal.SceneEventListener ( aModule, ) where import Foreign.Hoppy.Generator.Spec ( Export (ExportClass), addReqIncludes, classSetEntityPrefix, ident2, includeLocal, makeClass, mkCtor, mkMethod, ) import Foreign.Hoppy.Generator.Types (callbackT, objT, ptrT, voidT) import Graphics.UI.Qtah.Generator.Interface.Internal.Callback (cb_PtrQGraphicsItemPtrQEventBool, cb_Void) import Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsItem (c_QGraphicsItem) import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule) import Graphics.UI.Qtah.Generator.Types {-# ANN module "HLint: ignore Use camelCase" #-} aModule = AQtModule $ makeQtModule ["Internal", "SceneEventListener"] [ QtExport $ ExportClass c_SceneEventListener ] c_SceneEventListener = addReqIncludes [includeLocal "event.hpp"] $ classSetEntityPrefix "" $ makeClass (ident2 "qtah" "event" "SceneEventListener") Nothing [c_QGraphicsItem] [ mkCtor "new" [ptrT $ objT c_QGraphicsItem, callbackT cb_PtrQGraphicsItemPtrQEventBool, callbackT cb_Void] , mkMethod "doNotNotifyOnDelete" [] voidT ]
null
https://raw.githubusercontent.com/serokell/qtah/abb4932248c82dc5c662a20d8f177acbc7cfa722/qtah-generator/src/Graphics/UI/Qtah/Generator/Interface/Internal/SceneEventListener.hs
haskell
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see </>. # ANN module "HLint: ignore Use camelCase" #
This file is part of Qtah . Copyright 2015 - 2018 The Qtah Authors . the Free Software Foundation , either version 3 of the License , or GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License module Graphics.UI.Qtah.Generator.Interface.Internal.SceneEventListener ( aModule, ) where import Foreign.Hoppy.Generator.Spec ( Export (ExportClass), addReqIncludes, classSetEntityPrefix, ident2, includeLocal, makeClass, mkCtor, mkMethod, ) import Foreign.Hoppy.Generator.Types (callbackT, objT, ptrT, voidT) import Graphics.UI.Qtah.Generator.Interface.Internal.Callback (cb_PtrQGraphicsItemPtrQEventBool, cb_Void) import Graphics.UI.Qtah.Generator.Interface.Widgets.QGraphicsItem (c_QGraphicsItem) import Graphics.UI.Qtah.Generator.Module (AModule (AQtModule), makeQtModule) import Graphics.UI.Qtah.Generator.Types aModule = AQtModule $ makeQtModule ["Internal", "SceneEventListener"] [ QtExport $ ExportClass c_SceneEventListener ] c_SceneEventListener = addReqIncludes [includeLocal "event.hpp"] $ classSetEntityPrefix "" $ makeClass (ident2 "qtah" "event" "SceneEventListener") Nothing [c_QGraphicsItem] [ mkCtor "new" [ptrT $ objT c_QGraphicsItem, callbackT cb_PtrQGraphicsItemPtrQEventBool, callbackT cb_Void] , mkMethod "doNotNotifyOnDelete" [] voidT ]
f7e52b2e8fa3e51ea6df5736141683db210fff4ce4f3473a1ee5cbd0cf1faa1f
xcoo/proton
string_test.cljc
(ns proton.string-test (:require #?(:clj [clojure.test :refer [are deftest is testing]] :cljs [cljs.test :refer-macros [are deftest is testing]]) [proton.string :as string])) (deftest prune-test (testing "prune" (are [args e] (= (apply string/prune args) e) ["Simple made easy"] "Simple ..." ["Simple made easy" 15] "Simple made ..." ["Simple made easy" 3] "..." ["Simple made easy" 10 :left] "Simple ..." ["Simple made easy" 10 :right] "...de easy" ["Simple made easy" 10 :both] "Simp...asy" ["Simple made easy" 9 :left "!!!"] "Simple!!!")) (testing "not prune" (are [args] (= (apply string/prune args) (first args)) ["Simple"] [""] [nil] ["Simple made easy" 20])) (testing "error" (are [args] (thrown? #?(:clj Throwable, :cljs js/Error) (apply string/prune args)) ["Simple made easy" 2] ["Simple made easy" 10 :front] ["Simple made easy" 3 :left "......"]))) (deftest split-at-test (testing "single splitting position" (are [s x e] (= (string/split-at s x) e) "clojure" 3 ["clo" "jure"] "clojure" 0 ["" "clojure"] "clojure" 7 ["clojure" ""] "clojure" -1 ["" "clojure"] "clojure" 8 ["clojure" ""] "" 3 ["" ""])) (testing "multiple splitting positions" (are [s x e] (= (string/split-at s x) e) "clojure" [3 5] ["clo" "ju" "re"] "clojure" [0 3] ["" "clo" "jure"] "clojure" [5 7] ["cloju" "re" ""] "clojure" [-1 3] ["" "clo" "jure"] "clojure" [5 8] ["cloju" "re" ""] "clojure" [] ["clojure"] "" [3 5] ["" "" ""])) (testing "error" (are [s x] (thrown? #?(:clj Throwable, :cljs js/Error) (string/split-at s x)) "clojure" "3" "clojure" nil nil 3))) (deftest rand-str-test (let [s (string/rand-str 8)] (is (string? s)) (is (= (count s) 8)) (is (re-matches #"[0-9A-Za-z]+" s))) (is (re-matches #"[0-9]+" (string/rand-str 8 :number))) (is (re-matches #"[0-9a-z]+" (string/rand-str 8 :number :lower-case-letter))) (is (not= (string/rand-str 40) (string/rand-str 40))) (is (= (string/rand-str 0) "")) (is (= (string/rand-str -1) "")))
null
https://raw.githubusercontent.com/xcoo/proton/9214ae5115b4f7fc6e2a902877751396152c0ff9/test/proton/string_test.cljc
clojure
(ns proton.string-test (:require #?(:clj [clojure.test :refer [are deftest is testing]] :cljs [cljs.test :refer-macros [are deftest is testing]]) [proton.string :as string])) (deftest prune-test (testing "prune" (are [args e] (= (apply string/prune args) e) ["Simple made easy"] "Simple ..." ["Simple made easy" 15] "Simple made ..." ["Simple made easy" 3] "..." ["Simple made easy" 10 :left] "Simple ..." ["Simple made easy" 10 :right] "...de easy" ["Simple made easy" 10 :both] "Simp...asy" ["Simple made easy" 9 :left "!!!"] "Simple!!!")) (testing "not prune" (are [args] (= (apply string/prune args) (first args)) ["Simple"] [""] [nil] ["Simple made easy" 20])) (testing "error" (are [args] (thrown? #?(:clj Throwable, :cljs js/Error) (apply string/prune args)) ["Simple made easy" 2] ["Simple made easy" 10 :front] ["Simple made easy" 3 :left "......"]))) (deftest split-at-test (testing "single splitting position" (are [s x e] (= (string/split-at s x) e) "clojure" 3 ["clo" "jure"] "clojure" 0 ["" "clojure"] "clojure" 7 ["clojure" ""] "clojure" -1 ["" "clojure"] "clojure" 8 ["clojure" ""] "" 3 ["" ""])) (testing "multiple splitting positions" (are [s x e] (= (string/split-at s x) e) "clojure" [3 5] ["clo" "ju" "re"] "clojure" [0 3] ["" "clo" "jure"] "clojure" [5 7] ["cloju" "re" ""] "clojure" [-1 3] ["" "clo" "jure"] "clojure" [5 8] ["cloju" "re" ""] "clojure" [] ["clojure"] "" [3 5] ["" "" ""])) (testing "error" (are [s x] (thrown? #?(:clj Throwable, :cljs js/Error) (string/split-at s x)) "clojure" "3" "clojure" nil nil 3))) (deftest rand-str-test (let [s (string/rand-str 8)] (is (string? s)) (is (= (count s) 8)) (is (re-matches #"[0-9A-Za-z]+" s))) (is (re-matches #"[0-9]+" (string/rand-str 8 :number))) (is (re-matches #"[0-9a-z]+" (string/rand-str 8 :number :lower-case-letter))) (is (not= (string/rand-str 40) (string/rand-str 40))) (is (= (string/rand-str 0) "")) (is (= (string/rand-str -1) "")))
537cba6966ac673faa611a52ab18a7472e0d3c96816c47858623c9699994bfe3
svobot/janus
Judgment.hs
-- | Defines a 'Judgment' monad transformer that holds the context of -- the judgment. module Janus.Judgment ( Binding(..) , Context , TypingConfig(TypingConfig) , Judgment , evalInEnv , context , with , newLocalVar ) where import Control.Monad.Reader ( ReaderT , asks ) import Janus.Evaluation import Janus.Semiring import Janus.Syntax -- | A context element grouping a variable name, its type, and quantity. data Binding n u t = Binding { bndName :: n , bndUsage :: u , bndType :: t } deriving Eq instance (Show n, Show u, Show t) => Show (Binding n u t) where show (Binding n u t) = show u <> " " <> show n <> " : " <> show t -- | Judgment context. type Context = [Binding Name ZeroOneMany Type] -- | Record of variables that are in scope. data TypingConfig = TypingConfig { -- | Variables which have been defined in some previous term. Their values are in ' ValueEnv ' and their types in the ' Context ' cfgGlobalContext :: (ValueEnv, Context) , -- | Variables which have a binding occurrence in the currently judged term. cfgBoundLocals :: Context } -- | Add new variable binding to the local environment. with :: Binding Name ZeroOneMany Type -> TypingConfig -> TypingConfig with b cfg = cfg { cfgBoundLocals = b : cfgBoundLocals cfg } -- | Combine the contexts with global and local variables. context :: TypingConfig -> Context context (TypingConfig (_, globals) locals) = locals ++ globals -- | A monad transformer which carries the context of a judgment. type Judgment = ReaderT TypingConfig -- | Evaluate the term in context provided by the judgment. evalInEnv :: Monad m => CTerm -> Judgment m Value evalInEnv m = asks (flip cEval m . (, []) . fst . cfgGlobalContext) -- | Create a local variable with a fresh name. newLocalVar :: Monad m => BindingName -> a -> b -> Judgment m (Binding Name a b) newLocalVar n s ty = do i <- asks $ length . cfgBoundLocals return $ Binding (Local n i) s ty
null
https://raw.githubusercontent.com/svobot/janus/68391b160903e967aa9c88d6b2f16b446fc7abee/src/Janus/Judgment.hs
haskell
| Defines a 'Judgment' monad transformer that holds the context of the judgment. | A context element grouping a variable name, its type, and quantity. | Judgment context. | Record of variables that are in scope. | Variables which have been defined in some previous term. Their values | Variables which have a binding occurrence in the currently judged term. | Add new variable binding to the local environment. | Combine the contexts with global and local variables. | A monad transformer which carries the context of a judgment. | Evaluate the term in context provided by the judgment. | Create a local variable with a fresh name.
module Janus.Judgment ( Binding(..) , Context , TypingConfig(TypingConfig) , Judgment , evalInEnv , context , with , newLocalVar ) where import Control.Monad.Reader ( ReaderT , asks ) import Janus.Evaluation import Janus.Semiring import Janus.Syntax data Binding n u t = Binding { bndName :: n , bndUsage :: u , bndType :: t } deriving Eq instance (Show n, Show u, Show t) => Show (Binding n u t) where show (Binding n u t) = show u <> " " <> show n <> " : " <> show t type Context = [Binding Name ZeroOneMany Type] data TypingConfig = TypingConfig are in ' ValueEnv ' and their types in the ' Context ' cfgGlobalContext :: (ValueEnv, Context) cfgBoundLocals :: Context } with :: Binding Name ZeroOneMany Type -> TypingConfig -> TypingConfig with b cfg = cfg { cfgBoundLocals = b : cfgBoundLocals cfg } context :: TypingConfig -> Context context (TypingConfig (_, globals) locals) = locals ++ globals type Judgment = ReaderT TypingConfig evalInEnv :: Monad m => CTerm -> Judgment m Value evalInEnv m = asks (flip cEval m . (, []) . fst . cfgGlobalContext) newLocalVar :: Monad m => BindingName -> a -> b -> Judgment m (Binding Name a b) newLocalVar n s ty = do i <- asks $ length . cfgBoundLocals return $ Binding (Local n i) s ty
a6902adb0f8d304b7833b067dcbf57e9b6f520ee60a955d69ecc1d220f9d865a
roburio/builder-web
builder_web_app.ml
open Lwt.Infix let safe_close fd = Lwt.catch (fun () -> Lwt_unix.close fd) (fun _ -> Lwt.return_unit) let connect addrtype sockaddr = let c = Lwt_unix.(socket addrtype SOCK_STREAM 0) in Lwt_unix.set_close_on_exec c ; Lwt.catch (fun () -> Lwt_unix.(connect c sockaddr) >|= fun () -> Some c) (fun e -> Logs.warn (fun m -> m "error %s connecting to influx" (Printexc.to_string e)); safe_close c >|= fun () -> None) let write_raw s buf = let rec w off l = Lwt.catch (fun () -> Lwt_unix.send s buf off l [] >>= fun n -> if n = l then Lwt.return (Ok ()) else w (off + n) (l - n)) (fun e -> Logs.err (fun m -> m "exception %s while writing" (Printexc.to_string e)) ; safe_close s >|= fun () -> Error `Exception) in ( fun m - > m " writing % a " ( Cstruct.of_bytes buf ) ) ; w 0 (Bytes.length buf) let process = Metrics.field ~doc:"name of the process" "vm" Metrics.String let init_influx name data = match data with | None -> () | Some (ip, port) -> Logs.info (fun m -> m "stats connecting to %a:%d" Ipaddr.V4.pp ip port); Metrics.enable_all (); Metrics_lwt.init_periodic (fun () -> Lwt_unix.sleep 10.); Metrics_lwt.periodically (Metrics_rusage.rusage_src ~tags:[]); Metrics_lwt.periodically (Metrics_rusage.kinfo_mem_src ~tags:[]); let get_cache, reporter = Metrics.cache_reporter () in Metrics.set_reporter reporter; let fd = ref None in let rec report () = let send () = (match !fd with | Some _ -> Lwt.return_unit | None -> let addr = Lwt_unix.ADDR_INET (Ipaddr_unix.V4.to_inet_addr ip, port) in connect Lwt_unix.PF_INET addr >|= function | None -> Logs.err (fun m -> m "connection failure to stats") | Some fd' -> fd := Some fd') >>= fun () -> match !fd with | None -> Lwt.return_unit | Some socket -> let tag = process name in let datas = Metrics.SM.fold (fun src (tags, data) acc -> let name = Metrics.Src.name src in Metrics_influx.encode_line_protocol (tag :: tags) data name :: acc) (get_cache ()) [] in let datas = String.concat "" datas in write_raw socket (Bytes.unsafe_of_string datas) >|= function | Ok () -> () | Error `Exception -> Logs.warn (fun m -> m "error on stats write"); fd := None and sleep () = Lwt_unix.sleep 10. in Lwt.join [ send () ; sleep () ] >>= report in Lwt.async report let run_batch_viz ~cachedir ~datadir ~configdir = let open Rresult.R.Infix in begin let script = Fpath.(configdir / "batch-viz.sh") and script_log = Fpath.(cachedir / "batch-viz.log") and viz_script = Fpath.(configdir / "upload-hooks" / "visualizations.sh") in Bos.OS.File.exists script >>= fun script_exists -> if not script_exists then begin Logs.warn (fun m -> m "Didn't find %s" (Fpath.to_string script)); Ok () end else let args = [ "--cache-dir=" ^ Fpath.to_string cachedir; "--data-dir=" ^ Fpath.to_string datadir; "--viz-script=" ^ Fpath.to_string viz_script ] |> List.map (fun s -> "\"" ^ String.escaped s ^ "\"") |> String.concat " " in (*> Note: The reason for appending, is that else a new startup could overwrite an existing running batch's log*) (Fpath.to_string script ^ " " ^ args ^ " 2>&1 >> " ^ Fpath.to_string script_log ^ " &") |> Sys.command |> ignore |> Result.ok end |> function | Ok () -> () | Error err -> Logs.warn (fun m -> m "Error while starting batch-viz.sh: %a" Rresult.R.pp_msg err) let setup_app level influx port host datadir cachedir configdir run_batch_viz_flag = let dbpath = Printf.sprintf "%s/builder.sqlite3" datadir in let datadir = Fpath.v datadir in let cachedir = cachedir |> Option.fold ~none:Fpath.(datadir / "_cache") ~some:Fpath.v in let configdir = Fpath.v configdir in let () = init_influx "builder-web" influx in let () = if run_batch_viz_flag then run_batch_viz ~cachedir ~datadir ~configdir in match Builder_web.init dbpath datadir with | exception Sqlite3.Error e -> Format.eprintf "Error: @[@,%s.\ @,Does the database file exist? Create with `builder-db migrate`.@]\n%!" e; exit 2 | Error (#Caqti_error.load as e) -> Format.eprintf "Error: %a\n%!" Caqti_error.pp e; exit 2 | Error (`Wrong_version _ as e) -> Format.eprintf "Error: @[@,%a.\ @,Migrate database version with `builder-migrations`,\ @,or start with a fresh database with `builder-db migrate`.@]\n%!" Builder_web.pp_error e; | Error ( #Caqti_error.connect | #Caqti_error.call_or_retrieve | `Msg _ as e ) -> Format.eprintf "Error: %a\n%!" Builder_web.pp_error e; exit 1 | Ok () -> let level = match level with | None -> None | Some Logs.Debug -> Some `Debug | Some Info -> Some `Info | Some Warning -> Some `Warning | Some Error -> Some `Error | Some App -> None in let error_handler = Dream.error_template Builder_web.error_template in Dream.initialize_log ?level (); let dream_routes = Builder_web.( routes ~datadir ~cachedir ~configdir |> to_dream_routes ) in Dream.run ~port ~interface:host ~tls:false ~error_handler @@ Dream.logger @@ Dream.sql_pool ("sqlite3:" ^ dbpath) @@ Http_status_metrics.handle @@ Builder_web.Middleware.remove_trailing_url_slash @@ Dream.router dream_routes open Cmdliner let ip_port : (Ipaddr.V4.t * int) Arg.conv = let default_port = 8094 in let parse s = match match String.split_on_char ':' s with | [ s ] -> Ok (s, default_port) | [ip; port] -> begin match int_of_string port with | exception Failure _ -> Error "non-numeric port" | port -> Ok (ip, port) end | _ -> Error "multiple : found" with | Error msg -> Error (`Msg msg) | Ok (ip, port) -> match Ipaddr.V4.of_string ip with | Ok ip -> Ok (ip, port) | Error `Msg msg -> Error (`Msg msg) in let printer ppf (ip, port) = Format.fprintf ppf "%a:%d" Ipaddr.V4.pp ip port in Arg.conv (parse, printer) let datadir = let doc = "data directory" in let docv = "DATA_DIR" in Arg.( value & opt dir Builder_system.default_datadir & info [ "d"; "datadir" ] ~doc ~docv ) let cachedir = let doc = "cache directory" in let docv = "CACHE_DIR" in Arg.( value & opt (some ~none:"DATADIR/_cache" dir) None & info [ "cachedir" ] ~doc ~docv) let configdir = let doc = "config directory" in let docv = "CONFIG_DIR" in Arg.( value & opt dir Builder_system.default_configdir & info [ "c"; "configdir" ] ~doc ~docv) let port = let doc = "port" in Arg.(value & opt int 3000 & info [ "p"; "port" ] ~doc) let host = let doc = "host" in Arg.(value & opt string "0.0.0.0" & info [ "h"; "host" ] ~doc) let influx = let doc = "IP address and port (default: 8094) to report metrics to \ influx line protocol" in Arg.( value & opt (some ip_port) None & info [ "influx" ] ~doc ~docv:"INFLUXHOST[:PORT]") let run_batch_viz = let doc = "Run CONFIG_DIR/batch-viz.sh on startup. \ Note that this is started in the background - so the user \ is in charge of not running several instances of this. A \ log is written to CACHE_DIR/batch-viz.log" in Arg.(value & flag & info [ "run-batch-viz" ] ~doc) let () = let term = Term.(const setup_app $ Logs_cli.level () $ influx $ port $ host $ datadir $ cachedir $ configdir $ run_batch_viz) in let info = Cmd.info "Builder web" ~doc:"Builder web" ~man:[] in Cmd.v info term |> Cmd.eval |> exit
null
https://raw.githubusercontent.com/roburio/builder-web/f666c9d0d1065e94cd401a493bbbd658d0b5b838/bin/builder_web_app.ml
ocaml
> Note: The reason for appending, is that else a new startup could overwrite an existing running batch's log
open Lwt.Infix let safe_close fd = Lwt.catch (fun () -> Lwt_unix.close fd) (fun _ -> Lwt.return_unit) let connect addrtype sockaddr = let c = Lwt_unix.(socket addrtype SOCK_STREAM 0) in Lwt_unix.set_close_on_exec c ; Lwt.catch (fun () -> Lwt_unix.(connect c sockaddr) >|= fun () -> Some c) (fun e -> Logs.warn (fun m -> m "error %s connecting to influx" (Printexc.to_string e)); safe_close c >|= fun () -> None) let write_raw s buf = let rec w off l = Lwt.catch (fun () -> Lwt_unix.send s buf off l [] >>= fun n -> if n = l then Lwt.return (Ok ()) else w (off + n) (l - n)) (fun e -> Logs.err (fun m -> m "exception %s while writing" (Printexc.to_string e)) ; safe_close s >|= fun () -> Error `Exception) in ( fun m - > m " writing % a " ( Cstruct.of_bytes buf ) ) ; w 0 (Bytes.length buf) let process = Metrics.field ~doc:"name of the process" "vm" Metrics.String let init_influx name data = match data with | None -> () | Some (ip, port) -> Logs.info (fun m -> m "stats connecting to %a:%d" Ipaddr.V4.pp ip port); Metrics.enable_all (); Metrics_lwt.init_periodic (fun () -> Lwt_unix.sleep 10.); Metrics_lwt.periodically (Metrics_rusage.rusage_src ~tags:[]); Metrics_lwt.periodically (Metrics_rusage.kinfo_mem_src ~tags:[]); let get_cache, reporter = Metrics.cache_reporter () in Metrics.set_reporter reporter; let fd = ref None in let rec report () = let send () = (match !fd with | Some _ -> Lwt.return_unit | None -> let addr = Lwt_unix.ADDR_INET (Ipaddr_unix.V4.to_inet_addr ip, port) in connect Lwt_unix.PF_INET addr >|= function | None -> Logs.err (fun m -> m "connection failure to stats") | Some fd' -> fd := Some fd') >>= fun () -> match !fd with | None -> Lwt.return_unit | Some socket -> let tag = process name in let datas = Metrics.SM.fold (fun src (tags, data) acc -> let name = Metrics.Src.name src in Metrics_influx.encode_line_protocol (tag :: tags) data name :: acc) (get_cache ()) [] in let datas = String.concat "" datas in write_raw socket (Bytes.unsafe_of_string datas) >|= function | Ok () -> () | Error `Exception -> Logs.warn (fun m -> m "error on stats write"); fd := None and sleep () = Lwt_unix.sleep 10. in Lwt.join [ send () ; sleep () ] >>= report in Lwt.async report let run_batch_viz ~cachedir ~datadir ~configdir = let open Rresult.R.Infix in begin let script = Fpath.(configdir / "batch-viz.sh") and script_log = Fpath.(cachedir / "batch-viz.log") and viz_script = Fpath.(configdir / "upload-hooks" / "visualizations.sh") in Bos.OS.File.exists script >>= fun script_exists -> if not script_exists then begin Logs.warn (fun m -> m "Didn't find %s" (Fpath.to_string script)); Ok () end else let args = [ "--cache-dir=" ^ Fpath.to_string cachedir; "--data-dir=" ^ Fpath.to_string datadir; "--viz-script=" ^ Fpath.to_string viz_script ] |> List.map (fun s -> "\"" ^ String.escaped s ^ "\"") |> String.concat " " in (Fpath.to_string script ^ " " ^ args ^ " 2>&1 >> " ^ Fpath.to_string script_log ^ " &") |> Sys.command |> ignore |> Result.ok end |> function | Ok () -> () | Error err -> Logs.warn (fun m -> m "Error while starting batch-viz.sh: %a" Rresult.R.pp_msg err) let setup_app level influx port host datadir cachedir configdir run_batch_viz_flag = let dbpath = Printf.sprintf "%s/builder.sqlite3" datadir in let datadir = Fpath.v datadir in let cachedir = cachedir |> Option.fold ~none:Fpath.(datadir / "_cache") ~some:Fpath.v in let configdir = Fpath.v configdir in let () = init_influx "builder-web" influx in let () = if run_batch_viz_flag then run_batch_viz ~cachedir ~datadir ~configdir in match Builder_web.init dbpath datadir with | exception Sqlite3.Error e -> Format.eprintf "Error: @[@,%s.\ @,Does the database file exist? Create with `builder-db migrate`.@]\n%!" e; exit 2 | Error (#Caqti_error.load as e) -> Format.eprintf "Error: %a\n%!" Caqti_error.pp e; exit 2 | Error (`Wrong_version _ as e) -> Format.eprintf "Error: @[@,%a.\ @,Migrate database version with `builder-migrations`,\ @,or start with a fresh database with `builder-db migrate`.@]\n%!" Builder_web.pp_error e; | Error ( #Caqti_error.connect | #Caqti_error.call_or_retrieve | `Msg _ as e ) -> Format.eprintf "Error: %a\n%!" Builder_web.pp_error e; exit 1 | Ok () -> let level = match level with | None -> None | Some Logs.Debug -> Some `Debug | Some Info -> Some `Info | Some Warning -> Some `Warning | Some Error -> Some `Error | Some App -> None in let error_handler = Dream.error_template Builder_web.error_template in Dream.initialize_log ?level (); let dream_routes = Builder_web.( routes ~datadir ~cachedir ~configdir |> to_dream_routes ) in Dream.run ~port ~interface:host ~tls:false ~error_handler @@ Dream.logger @@ Dream.sql_pool ("sqlite3:" ^ dbpath) @@ Http_status_metrics.handle @@ Builder_web.Middleware.remove_trailing_url_slash @@ Dream.router dream_routes open Cmdliner let ip_port : (Ipaddr.V4.t * int) Arg.conv = let default_port = 8094 in let parse s = match match String.split_on_char ':' s with | [ s ] -> Ok (s, default_port) | [ip; port] -> begin match int_of_string port with | exception Failure _ -> Error "non-numeric port" | port -> Ok (ip, port) end | _ -> Error "multiple : found" with | Error msg -> Error (`Msg msg) | Ok (ip, port) -> match Ipaddr.V4.of_string ip with | Ok ip -> Ok (ip, port) | Error `Msg msg -> Error (`Msg msg) in let printer ppf (ip, port) = Format.fprintf ppf "%a:%d" Ipaddr.V4.pp ip port in Arg.conv (parse, printer) let datadir = let doc = "data directory" in let docv = "DATA_DIR" in Arg.( value & opt dir Builder_system.default_datadir & info [ "d"; "datadir" ] ~doc ~docv ) let cachedir = let doc = "cache directory" in let docv = "CACHE_DIR" in Arg.( value & opt (some ~none:"DATADIR/_cache" dir) None & info [ "cachedir" ] ~doc ~docv) let configdir = let doc = "config directory" in let docv = "CONFIG_DIR" in Arg.( value & opt dir Builder_system.default_configdir & info [ "c"; "configdir" ] ~doc ~docv) let port = let doc = "port" in Arg.(value & opt int 3000 & info [ "p"; "port" ] ~doc) let host = let doc = "host" in Arg.(value & opt string "0.0.0.0" & info [ "h"; "host" ] ~doc) let influx = let doc = "IP address and port (default: 8094) to report metrics to \ influx line protocol" in Arg.( value & opt (some ip_port) None & info [ "influx" ] ~doc ~docv:"INFLUXHOST[:PORT]") let run_batch_viz = let doc = "Run CONFIG_DIR/batch-viz.sh on startup. \ Note that this is started in the background - so the user \ is in charge of not running several instances of this. A \ log is written to CACHE_DIR/batch-viz.log" in Arg.(value & flag & info [ "run-batch-viz" ] ~doc) let () = let term = Term.(const setup_app $ Logs_cli.level () $ influx $ port $ host $ datadir $ cachedir $ configdir $ run_batch_viz) in let info = Cmd.info "Builder web" ~doc:"Builder web" ~man:[] in Cmd.v info term |> Cmd.eval |> exit
080d73a6f5ee845d52af107e3fcdc0896406d0bbe916a729bded61a7d2443346
armedbear/abcl
url-pathname.lisp
(in-package #:abcl.test.lisp) ;; URL Pathname tests (deftest url-pathname.1 (let* ((p #p"") (host (pathname-host p))) (values (check-physical-pathname p '(:absolute "a" "b") "foo" "lisp") (and (consp host) (equal (getf host :scheme) "http") (equal (getf host :authority) "example.org")))) t t) (deftest url-pathname.2 (let* ((p (pathname "#that-fragment")) (host (pathname-host p))) (values (check-physical-pathname p '(:absolute "a" "b") "foo" "lisp") (consp host) (getf host :scheme) (getf host :authority) (getf host :query) (getf host :fragment))) t t "http" "example.org" "query=this" "that-fragment") (deftest url-pathname.3 (let* ((p (pathname "#that-fragment"))) (values (ext:url-pathname-scheme p) (ext:url-pathname-authority p) (ext:url-pathname-query p) (ext:url-pathname-fragment p))) "http" "example.org" "query=this" "that-fragment") (deftest url-pathname.file.1 (signals-error (let ((s "file with /spaces")) (equal s (namestring (pathname s)))) 'error) t) (deftest url-pathname.file.2 (let ((p "file-escaped/%3fcharacters/")) (pathname-directory p)) (:ABSOLUTE "path with" "uri-escaped" "?characters"))
null
https://raw.githubusercontent.com/armedbear/abcl/36a4b5994227d768882ff6458b3df9f79caac664/test/lisp/abcl/url-pathname.lisp
lisp
URL Pathname tests
(in-package #:abcl.test.lisp) (deftest url-pathname.1 (let* ((p #p"") (host (pathname-host p))) (values (check-physical-pathname p '(:absolute "a" "b") "foo" "lisp") (and (consp host) (equal (getf host :scheme) "http") (equal (getf host :authority) "example.org")))) t t) (deftest url-pathname.2 (let* ((p (pathname "#that-fragment")) (host (pathname-host p))) (values (check-physical-pathname p '(:absolute "a" "b") "foo" "lisp") (consp host) (getf host :scheme) (getf host :authority) (getf host :query) (getf host :fragment))) t t "http" "example.org" "query=this" "that-fragment") (deftest url-pathname.3 (let* ((p (pathname "#that-fragment"))) (values (ext:url-pathname-scheme p) (ext:url-pathname-authority p) (ext:url-pathname-query p) (ext:url-pathname-fragment p))) "http" "example.org" "query=this" "that-fragment") (deftest url-pathname.file.1 (signals-error (let ((s "file with /spaces")) (equal s (namestring (pathname s)))) 'error) t) (deftest url-pathname.file.2 (let ((p "file-escaped/%3fcharacters/")) (pathname-directory p)) (:ABSOLUTE "path with" "uri-escaped" "?characters"))
0cb0c28895ead1c383fb25048cf30d5f8ff624a0bbdb3cdb983d04ad70152563
johnwhitington/ocamli
array.ml
let x = [|1; 2; 3|] let y = x.(0) let p = match x with [|x; y; z|] -> x + y + z
null
https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/examples/array.ml
ocaml
let x = [|1; 2; 3|] let y = x.(0) let p = match x with [|x; y; z|] -> x + y + z
9bf3b3fba7440cf35ecc34775142ce2df91bbd2d85b53d794f04e7b972b8c6a5
essiene/smpp34
file_logger.erl
-module(file_logger). -behaviour(gen_event). -export([init/1,handle_event/2,handle_call/2, handle_info/2,terminate/2,code_change/3]). -record(st_flogger, {filename, io_device}). init([FileName]) -> {ok, IoDevice} = file:open(FileName, [append]), {ok, #st_flogger{filename=FileName, io_device=IoDevice}}. handle_event({'ERROR', Log}, #st_flogger{io_device=IoDev}=St) -> error_logger:error_msg("~s~n", [Log]), io:format(IoDev, "~s~n", [Log]), {ok, St}; handle_event({_, Log}, #st_flogger{io_device=IoDev}=St) -> io:format(IoDev, "~s~n", [Log]), {ok, St}; handle_event(_, St) -> {ok, St}. handle_call(_, St) -> {ok, ok, St}. handle_info(_, St) -> {ok, St}. terminate(_, #st_flogger{io_device=IoDev}) -> io:format(IoDev, "Logger terminating~n"), file:close(IoDev), ok. code_change(_OldVsn, St, _Extra) -> {ok, St}.
null
https://raw.githubusercontent.com/essiene/smpp34/9206b1d270dc77d65a64a539cbca41b8b003956a/examples/file_logger.erl
erlang
-module(file_logger). -behaviour(gen_event). -export([init/1,handle_event/2,handle_call/2, handle_info/2,terminate/2,code_change/3]). -record(st_flogger, {filename, io_device}). init([FileName]) -> {ok, IoDevice} = file:open(FileName, [append]), {ok, #st_flogger{filename=FileName, io_device=IoDevice}}. handle_event({'ERROR', Log}, #st_flogger{io_device=IoDev}=St) -> error_logger:error_msg("~s~n", [Log]), io:format(IoDev, "~s~n", [Log]), {ok, St}; handle_event({_, Log}, #st_flogger{io_device=IoDev}=St) -> io:format(IoDev, "~s~n", [Log]), {ok, St}; handle_event(_, St) -> {ok, St}. handle_call(_, St) -> {ok, ok, St}. handle_info(_, St) -> {ok, St}. terminate(_, #st_flogger{io_device=IoDev}) -> io:format(IoDev, "Logger terminating~n"), file:close(IoDev), ok. code_change(_OldVsn, St, _Extra) -> {ok, St}.
25005642672b83259177cbdaaade0a81f381e9d4813360f106987764c41b890d
jrm-code-project/LISP-Machine
auks.lisp
-*- Mode : LISP ; Package : STEVE ; : CL ; -*- Copyright ( c ) May 1983 by and Massachusetts Institute of Technology . ;Permission to copy all or part of this material is granted, provided that the copies are not made or distributed for resale , the MIT ; copyright notice and reference to the source file and the software ; distribution version appear, and that notice is given that copying is by permission of Massachusetts Institute of Technology . ; ;This file contains random functions used by the editor, which ;do not depend heavily on other functions in the editor. Some of ;them may depend upon its data formats however. This is certainly not ;a guarantee that anything here will work in another context. ; ;***************************************************************************** ;Compilation note. ;Before installation every file in the editor should be compiled in ;an environment where the whole editor is loaded. This ensures that DEFSUBSTs ;are expanded, and that macros work correctly. ;****************************************************************************** ; (defvar *query-line*) (defvar *notify-line*) (defvar *more-line*) (defvar *feedback-line*) (defvar *double-line*) (defvar *error-line*) (defvar *prefix-echo-line*) Now 135 spaces long for bigger TTYs . (defconstant 80spaces " ") (defconstant 80dashes "---------------------------------------------------------------------------------------------------------------------------------------") ; Ascii dependant cruft which helps fix the read stream . ; (eval-when (compile load) (defconstant *first-non-control-character-code* (char-int #\space)) (defconstant *first-meta-character-code* 128) (defconstant *tab-distance* 8) );eval-when (defconstant n-spaces #.(loop with vector = (make-vector 9) ;Initial value inconsequential for i from 0 to 8 do (setf (svref vector i) (make-string i :initial-element #\sp)) finally (return vector))) (defconstant control-character-translation-table #.(loop with vect = (make-vector (char-int #\space)) ;Initial value inconsequential for i from 0 below (char-int #\space) for char = (int-char i) if (memq char '(#\bell #\backspace #\tab #\line #\page #\return #\altmode)) do (setf (aref vect i) char) else do (setf (aref vect i) (code-char (logior& (char-code char) #o100) char-control-bit)) finally (return vect))) (defconstant character-translation-table #.(loop with vect = (make-vector 256) ;Initial value inconsequential for i from 0 to 255 for chr = (int-char i) do (cond ((memq chr '(#\bell #\backspace #\tab #\line #\page #\return #\altmode)) (setf (aref vect i) chr)) ((>=& i 128) (setf (aref vect i) (code-char (logandc2& i #o0200) char-meta-bit))) (t (setf (aref vect i) chr))) do (cond ((memq (make-char (setq chr (aref vect i))) '(#\bell #\backspace #\tab #\line #\page #\return #\altmode))) ((<& (char-code chr) (char-int #\space)) (setf (aref vect i) (code-char (logior& (char-code chr) #o100) (logior& (char-bits chr) char-control-bit))))) finally (return vect))) ;This is very much dependant upon the ASCII character set. (defsubst canonicalize-control-characters (char) (svref character-translation-table (char-int char))) (defun coerse-to-string-charp (char) (cond ((string-charp char) char) ((not (0p (char-font char))) nil) ((not (0p (logandc2 (char-bits char) #.(logior& char-control-bit char-meta-bit)))) nil) (t (let ((code (char-code char))) (when (not (0p (logand& (char-bits char) char-control-bit))) (setq code (logandc2& code #o100))) (when (not (0p (logand& (char-bits char) char-meta-bit))) (setq code (logior& code #o200))) (int-char code))))) (defparameter preknown-character-printed-representations #.(loop with v = (make-vector char-code-limit :initial-element nil) for i from 0 below char-code-limit as c = (code-char i) do (unless (graphic-charp c) (setf (svref v i) (format nil (if (and (<& i 32) (not (char-name c))) "~:C" "~@C") c))) finally (return v))) (defsubst stringify-tab (col) (let ((col1 col)) (svref n-spaces (-& (logandc1& 7 (+& col1 8)) col1)))) (defsubst stringify-non-tab (chr) (svref preknown-character-printed-representations (char-code chr))) (defsubst stringify-char (chr col) ;Normally a graphic-charp character will not be an argument. (let ((chrctr chr) (col1 col)) (if (eq chrctr #\tab) (svref n-spaces This depends upon tabs being 8 columns apart . (-& (logandc1& 7 (+& col1 8)) col1)) (svref preknown-character-printed-representations (char-code chrctr))))) ; ;Edit-cursors bind a buffer, a cursor and a window together. ; (defflavor edit-cursor (buffer line position window home-line home-pos) (bp) :ordered-instance-variables :initable-instance-variables ;;:gettable-instance-variables :outside-accessible-instance-variables) (defmethod (edit-cursor :print-self) (&optional (stream standard-output) ignore ignore) (format stream "#<~s ~a " 'edit-cursor (buffer-name buffer)) (print-bp-internal line position stream) (write-char #\> stream)) (defun create-edit-cursor (buffer &optional (line (buffer-content buffer)) (pos 0) (window nil)) (let ((new-bp (make-instance 'edit-cursor :line line :position pos :buffer buffer :window window :home-line line :home-pos 0))) (send line :add-bp new-bp) (push new-bp *all-edit-cursors*) new-bp)) ;This is how to make a new buffer. If the name is not unique, the ;existing buffer may be used however. (defun make-buffer (name) (let ((buffer (buffer name :create nil))) (when (not (null buffer)) (with-double-second-line (with-double-line (format terminal-io "A buffer named ~a (file ~a) already exists." name (send (buffer-file-name buffer) :string-for-editor)) (format terminal-io "~&Type buffer name to use, or CR to reuse ~a (or <DEL> to select it): " name) (let ((new-name (prescan #'read-buffer-name nil))) (cond ((null new-name) ) ((string= new-name "") (when (buffer-modified? buffer) (when (with-query-line (oustr "Save changes to buffer? " terminal-io) (ed-y-or-n-p "Save changes to ~a " (buffer-name buffer))) (save-file buffer))) (%kill-buffer-primitive buffer) (setq buffer nil)) (t (setq name new-name) (setq buffer (buffer name :create t)))))))) (when (null buffer) ;; This delays calculation of the environment until ;; it is actually needed. (setf buffer (make-instance 'buffer :name name :access buffer-access-any :environment nil :mark-ring (make-vector mark-ring-size :initial-element nil) :mark-ring-index 0 :narrow-info nil)) (setf (buffer-content buffer) (make-line buffer nil nil)) (setf (buffer-modified? buffer) nil) (push buffer *all-buffers*) (send buffer :set-file-name (editor-default name)) (when *buffer-creation-hook* (funcall *buffer-creation-hook* buffer))) buffer)) (defun make-point (name &optional (window nil)) (let ((buff (make-buffer name))) (create-edit-cursor buff (buffer-content buff) 0 window))) (defun select-point (point &aux (buffer (edit-cursor-buffer point))) (unless (eq *editor-buffer* buffer) (setq *last-buffer-selected* *editor-buffer*)) (unless (eq *editor-cursor* point) (setq *editor-cursor* point *.* point *editor-buffer* buffer *b* *editor-buffer* *context-change-flag* t)) (when (null (edit-cursor-window point)) (with-no-passall (oustr "Selected point has no associated window." echo-area-window) (oustr "I will try to fix it" echo-area-window) (one-window)))) (defun select-point-in-current-window (point) (unless (eq point *editor-cursor*) (setf (edit-cursor-window point) (edit-cursor-window *editor-cursor*) (edit-cursor-window *editor-cursor*) nil) (select-point point))) ; Character syntax for . ; ;What we need is a way to set/read the syntax for any STRING-CHAR ;For now we will assume there are at most 8 bits of information ;about any character. This will be stored in a 256 byte table . ; (defvar syntax-bit-map nil) (defvar *all-modes* nil) ;Type must be an symbol. ;When using the syntax base option, the base must be declared before it ;is used. (defmacro declare-syntax-type (type &optional (base nil)) `(progn (defvar ,type ,(if (null base) '(make-empty-syntax-table) `(copy-syntax-table ,base))) (defprop ,type t syntax-type) (or (memq ,type *all-modes*) (push ,type *all-modes*)))) (defun make-empty-syntax-table () (make-bits (* 256 8))) (defun copy-syntax-table (table) (bits-replace (make-empty-syntax-table) table 0 0 (* 256 8))) (defvar next-unused-syntax-bit 0) (defvar max-syntax-bit 7) (defmacro declare-syntax-bit (name) ;This allocates a bit automatically, and sets the name to reference it. `(progn (defvar ,name) (when (null (get ',name 'syntax-bit)) (when (>& next-unused-syntax-bit max-syntax-bit) (ed-lose "Too Many Syntax Bits Allocated")) (putprop ',name next-unused-syntax-bit 'syntax-bit) (setq next-unused-syntax-bit (1+& next-unused-syntax-bit)) (setq ,name (get ',name 'syntax-bit)) (defvar ,(intern (string-append name "-MASK")) (^& 2 ,name)) (push (list ,name ',name (^& 2 ,name)) syntax-bit-map)))) (defun syntax-description (table char &aux (byte (get-char-syntax table char))) (loop for (bit-number name) in syntax-bit-map if (logbitp& bit-number byte) collect name)) This can be expanded by SETF . (defmacro get-char-syntax (table char) `(get-a-byte ,table (char-code ,char))) This can be expanded by SETF . (defmacro get-char-syntax-bit (table char bit) `(bit ,table (+& (*& 8 (char-code ,char)) ,bit))) (defmacro of-syntax (char bit) `(=& 1 (get-char-syntax-bit syntax-table ,char ,bit))) ; ;Syntax table generation. ; Paren matching . Paren matching is more wired in than in emacs . ;We assume that: ; Open paren For Close paren ; ( ) ; [ ] ; { } ; < > ;And all others will either be illegal as parens, or match themselves. ;Any complaints? ; (defvar paren-matches '((#\) . #\() (#\] . #\[) (#\} . #\{) (#\> . #\<) (#\' . #\`) (#\( . #\)) (#\[ . #\]) (#\{ . #\}) (#\< . #\>) (#\` . #\'))) (defmacro get-paren-match (paren) `(cdr (assq ,paren paren-matches))) ;Syntax bit declarations. (declare-syntax-bit word-alphanumeric) (declare-syntax-bit lisp-alphanumeric) (declare-syntax-bit white-space) (declare-syntax-bit paren-open) (declare-syntax-bit paren-close) (declare-syntax-bit string-quote) (declare-syntax-bit character-quote) (declare-syntax-bit prefix) (defparameter lisp-word-chars ".") (defparameter text-word-chars "'") (defparameter lisp-atom-chars "!#&*+/<=>?@^`-_:\\[]") (defparameter extra-alphanumerics "$%") (defparameter white-space-chars #.(to-string '(#\space #\tab #\return))) (defparameter prefix-chars "':`,#;\\") (defun set-to-syntax (table string syntax) (loop for i from 0 below (string-length string) do (setf (get-char-syntax-bit table (char string i) syntax) 1))) (defun set-default-syntax (table) (loop for i from 0 below 256 for chr = (int-char i) if (alphanumericp chr) do (setf (get-char-syntax-bit table chr word-alphanumeric) 1 (get-char-syntax-bit table chr lisp-alphanumeric) 1)) (set-to-syntax table extra-alphanumerics word-alphanumeric) (set-to-syntax table extra-alphanumerics lisp-alphanumeric) (set-to-syntax table lisp-word-chars lisp-alphanumeric) (set-to-syntax table lisp-atom-chars lisp-alphanumeric) (set-to-syntax table white-space-chars white-space) (set-to-syntax table prefix-chars prefix) (setf (get-char-syntax-bit table #\( paren-open) 1) (setf (get-char-syntax-bit table #\) paren-close) 1) (setf (get-char-syntax-bit table #\" string-quote) 1) (setf (get-char-syntax-bit table #\| string-quote) 1) (setf (get-char-syntax-bit table #\\ character-quote) 1)) ; ; ;Syntax types. ; (declare-syntax-type *fundamental-syntax*) (set-default-syntax *fundamental-syntax*) (declare-syntax-type *text-syntax*) (set-default-syntax *text-syntax*) (set-to-syntax *text-syntax* text-word-chars word-alphanumeric) (declare-syntax-type *lisp-syntax*) (set-default-syntax *lisp-syntax*) (set-to-syntax *lisp-syntax* lisp-word-chars word-alphanumeric) The current value of SYNTAX - TABLE is the current syntax . (defvar syntax-table *lisp-syntax*) ; ;Syntax table usage. ; (defsubst atom-char? (chr) (=& 1 (get-char-syntax-bit syntax-table chr lisp-alphanumeric))) (defsubst word-char? (chr) (=& 1 (get-char-syntax-bit syntax-table chr word-alphanumeric))) (defsubst white-space? (chr) (=& 1 (get-char-syntax-bit syntax-table chr white-space))) (defsubst horizontal-white-space? (chr) (and (white-space? chr) (not (char= chr #\return)))) ; ;Macros to do some fancy line control stuff. ; (defmacro with-line (line &body forms) `(unwind-protect (progn (cursorpos ,line 0) (send terminal-io :clear-eol) ,@forms) (cursorpos ,line 0) (send terminal-io :clear-eol))) (defmacro with-line-remaining (line &body forms) `(progn (cursorpos ,line 0) (send terminal-io :clear-eol) ,@forms)) (defmacro declare-line (name line &aux (arg (gensym))) `(progn (defmacro ,(intern (string-append "WITH-" name "-LINE")) (&body ,arg) (list* 'with-line ',line ,arg)) (defmacro ,(intern (string-append "WITH-" name "-LINE-REMAINING")) (&body ,arg) (list* 'with-line-remaining ',line ,arg)))) (declare-line query *query-line*) (declare-line notify *notify-line*) (declare-line more *more-line*) (declare-line feedback *feedback-line*) (declare-line double *double-line*) (declare-line double-second (1+& *double-line*)) (declare-line error *error-line*) (declare-line prefix-echo *prefix-echo-line*) ; ;Functions to do overwritten displays. ;This has to be retro-fitted to the editor. ; (defvar *overwrite-line* 0) (defun overwrite-open-line (line) (cursorpos line 0 terminal-io) (send terminal-io :clear-eol) (setq creamed-tty-lines-to (max& (1+& line) creamed-tty-lines-to)) (setq *overwrite-line* line) t) (defun overwrite-home () (overwrite-open-line 0)) (defun overwrite-start () (overwrite-open-line *overwrite-line*)) (defun overwrite-done () (setq *overwrite-line* (1+& *overwrite-line*))) (defun overwrite-terpri () (setq *overwrite-line* (1+& *overwrite-line*)) (when (>& *overwrite-line* *last-overwrite-line*) (setq *overwrite-line* 0) (with-more-line (setq creamed-tty-lines-to (max& (send terminal-io :linenum) creamed-tty-lines-to)) (oustr "*more*" terminal-io) (cond ((char= (peek-char&save) #\space) (read-char&save)) (t (when (char= (peek-char&save) #\rubout) (read-char&save)) (ed-abort))))) (overwrite-open-line *overwrite-line*)) (defun editor-notify (string) (with-notify-line-remaining (princ string terminal-io))) ; Special purpose IO functions . ; The editor needs to save the last 60 chars for the help command . ;It also must be able to do keyboard macros. ;Any character read from the keyboard must be read by this function, ;which will take care of all such considerations. ; However , there is one problem with these functions . ;If the last character read is pushed back, it will still be in the buffer. ;If this is a problem, check the flag (pushback-flag). ; ;I wonder if this would be better done by defining a special purpose stream? (defvar 60char-buffer (make-string 60 :initial-element #\space)) (defvar 60char-index 0) (defvar 1char-buffer #\null) (defvar save-chars-for-keyboard-macros nil) (defvar pushback-flag nil) (defvar keyboard-macro-char-list nil) (defvar executing-keyboard-macro nil) (defun read-char&save (&optional (stream terminal-io)) (cond ((not (null pushback-flag)) (unless (if (not (null executing-keyboard-macro)) (char= (pop executing-keyboard-macro) 1char-buffer) (char= (send stream :read-char) 1char-buffer)) ;;(ed-warning "Character reader out of sync") nil)) ((not (null executing-keyboard-macro)) ;;Note that this ignores the stream. ;;This might screw somthing terribly, but what else ;;is there to do? (setq 1char-buffer (pop executing-keyboard-macro)) (when (null executing-keyboard-macro) (send terminal-io :set-device-mode :passall *editor-device-mode*))) (t (setq 1char-buffer (send stream :read-char)) (setf (char 60char-buffer 60char-index) 1char-buffer) (setq 60char-index (\\& (1+& 60char-index) 60)) (when save-chars-for-keyboard-macros (push 1char-buffer keyboard-macro-char-list)))) (setq pushback-flag nil) 1char-buffer) (defun string-read&save (char-list) (loop for char in char-list do (setf (char 60char-buffer 60char-index) char) do (setq 60char-index (\\& (1+& 60char-index) 60))) (setq pushback-flag nil) (setq 1char-buffer (car (last char-list)))) (defun unread-char&save (char &optional (stream terminal-io)) (cond ((not (null pushback-flag)) (ed-lose "Double Unread&save")) (executing-keyboard-macro (push char executing-keyboard-macro)) (t (send stream :unread-char char))) (setq pushback-flag t) char) (defun peek-char&save (&optional (stream terminal-io)) (unread-char&save (read-char&save stream) stream)) ; ;Functions to interact with the user. ;These should be used when possible, so that the interaction is ;as ritualized as possible. This does a great deal to make the editor ;(or any program) easy to use. ; (defresource reading-buffer () :constructor (make-array 100 :element-type 'string-char :fill-pointer 0 :adjustable t) :deinitializer (reset-fill-pointer object 0)) (defun readline-with-exit (stream) (using-resource (reading-buffer b) (loop for char = (read-char&save stream) do (case char (#\bell (ed-abort :echo terminal-io)) ((#\altmode #\return) (return (copy-seq b))) (t (vector-push-extend char b)))))) (defun read-symbol (stream) (using-resource (reading-buffer b) (loop for chr = (read-char&save stream) do (if (or (null chr) (white-space? chr)) (return (intern (copy-seq b))) (vector-push-extend (char-upcase chr) b))))) ;These should do completion etc. (defun read-file-name (&optional (stream terminal-io stream?) &aux name) (cond ((null stream?) (setq name (si:ttyscanner #'readline-with-exit terminal-io terminal-io #'(lambda (strm reason) (oustr "File: " strm)) T 0)) (if (not (stringp name)) (ed-warn :aborted) name)) (t (readline-with-exit stream)))) ; ;Completion of buffer names. ;This does not really belong in this file because it depends heavily upon ;being part of the editor. It is included here because it belongs with the ;previous functions. ; ;Is common lisp really so damned brain dead as to think that anyone ;will ever want STRING to return "NIL" for the empty list. I would like to see someone come up with three examples of natural uses for that type of mis - behavior . I can come up with 95 natural ;examples where that behavior has fucked me over. (defun steve-to-string (seq) (cond ((stringp seq) seq) ((null seq) (make-string 0)) ((symbolp seq) (get-pname seq)) ((characterp seq) ;Note we know the implication of string-charp here. (if (string-charp seq) (aref *:character-to-string-table (char-code seq)) (cerror t nil ':implementation-lossage "The character ~S can't go into a string" seq))) ((pairp seq) (let* ((n (list-length seq)) (s (make-string n :initial-element #\space))) (loop for c in seq for i from 0 do (rplachar s i (to-character c))) s)) ((bitsp seq) (let* ((n (bits-length seq)) (s (make-string n :initial-element #\space))) (dotimes (i n) (rplachar s i (char "01" (bit seq i)))) s)) ((vectorp seq) (let* ((n (vector-length seq)) (s (make-string n :initial-element #\space))) (dotimes (i n) (rplachar s i (to-character (aref seq i)))) s)) ((and (si:extendp seq) (send seq ':send-if-handles ':to-string))) (t (steve-to-string (cerror t () ':wrong-type-argument "~*~S not coercible to a string" 'string seq))))) (defun complete-buffer-name (name) (loop with completion = nil with length = (string-length name) for buffer in *all-buffers* for bname = (buffer-name buffer) if (string-equal name bname 0 0 length (min& (string-length bname) length)) do (cond ((null completion) (setq completion bname)) (t (setq completion (max-prefix (list completion bname))))) finally (return (if (or (null completion) (<=& (string-length completion) length)) name completion)))) (defun print-buffer-name-completions (name) (overwrite-start) (loop with length = (string-length name) for buffer in *all-buffers* for bname = (buffer-name buffer) if (string-equal name bname 0 0 length (min& (string-length bname) length)) do (progn (princ bname terminal-io) (overwrite-terpri))) (oustr "Done" terminal-io) (overwrite-terpri) (overwrite-done)) (defun read-buffer-name (stream &aux name) (loop for chr = (read-char&save stream) do (cond ((char= chr #\return) (return If the only buffers are named FOO and FROB ;;then completing "" will => "F" and so ^X ^B <CR> ;;will incorectly create a buffer named "F" if we are not ;;careful here. (cond ((not (null *buffer-name-completion-on-return*)) (setq name (complete-buffer-name (steve-to-string chrs))) (if (buffer name :create nil) name (steve-to-string chrs))) (t (steve-to-string chrs))))) ((char= chr #\altmode) (send stream :completion-string (setq name (complete-buffer-name (steve-to-string chrs))) (1+& (length chrs))) (when (buffer name :create nil) (send stream :send-if-handles :echo-false-char #\$)) (throw 'rubout-tag nil)) ((char= chr #\page) (make-screen-image) (send stream :rubout) (throw 'rubout-tag nil)) ((char= chr #\?) (print-buffer-name-completions (steve-to-string chrs)) (send stream :rubout) (throw 'rubout-tag nil))) collect chr into chrs)) ( defun beep ( ) ( write - char # \bell ) ) ; this in newmacros and renamed to avoid lossage . (defun ed-y-or-n-p (&optional (help "Type Y or N") &RESTV format-args) (do ((char) (c-pos (cursorpos terminal-io))) (nil) ;Forever. (cursorpos (car c-pos) (cdr c-pos) terminal-io) (setq char (read-char&save)) (send terminal-io :write-char char) (case char ((#\Y #\y) (oustr "es" terminal-io) (return t)) ((#\N #\n) (write-char #\o terminal-io) (return nil)) (#\? (with-notify-line-remaining (lexpr-funcall #'format terminal-io help format-args))) (#\bell (ed-abort :echo terminal-io)) (t (with-notify-line-remaining (format terminal-io "Type Y or N. ? for help")))))) Function to " bind " passall mode off . (defmacro with-no-passall (&body forms &aux (var (gentemp))) `(let ((,var (send terminal-io :get-device-mode :passall))) (unwind-protect (progn (send terminal-io :set-device-mode :passall nil) ,@forms) (send terminal-io :set-device-mode :passall ,var)))) ; Emacs rings . ; First some primatives . (defvar mark-ring-size 8) (defvar mark-ring (make-vector mark-ring-size :initial-element nil)) (defvar mark-ring-index 0) (defun push-mark (bp) (let ((mark-ring-index (buffer-mark-ring-index *editor-buffer*))) (setq mark-ring-index (1+& mark-ring-index)) (if (>=& mark-ring-index mark-ring-size) (setq mark-ring-index 0)) (setf (svref (buffer-mark-ring *editor-buffer*) mark-ring-index) (copy-bp bp) (buffer-mark-ring-index *editor-buffer*) mark-ring-index))) ;Use this when programing a function that sometimes pushes a mark. ;This will print a mark-set message when called, if appropriate. (defun auto-push-mark (bp) (unless (string= "" auto-push-point-notification) (with-error-line-remaining (oustr auto-push-point-notification terminal-io))) (push-mark bp)) (defun push-mark-no-copy (bp) (let ((mark-ring-index (buffer-mark-ring-index *editor-buffer*))) (setq mark-ring-index (1+& mark-ring-index)) (if (>=& mark-ring-index mark-ring-size) (setq mark-ring-index 0)) (setf (aref (buffer-mark-ring *editor-buffer*) mark-ring-index) bp (buffer-mark-ring-index *editor-buffer*) mark-ring-index))) (defun pop-mark () (let ((ring (buffer-mark-ring *editor-buffer*)) (index (buffer-mark-ring-index *editor-buffer*))) (prog1 (or (svref ring index) (ed-warn :no-mark)) ;;This code is only to keep narrowing from losing. (when (buffer-narrow-info (bp-buffer (svref ring index))) (when (loop with mark = (svref ring index) with target = (bp-line mark) for line first (buffer-content (bp-buffer mark)) then (line-next line) never (eq line target)) (ed-lose "Mark outside region"))) ;; (loop do (setq index (1-& index)) do (when (-p index) (setq index (1-& mark-ring-size))) until (svref ring index)) (setf (buffer-mark-ring-index *editor-buffer*) index)))) (defun get-mark (&aux ring index) (prog1 (or (aref (setq ring (buffer-mark-ring *editor-buffer*) ) (setq index (buffer-mark-ring-index *editor-buffer*))) (ed-warn :no-mark)) ;;This code is only to keep narrowing from losing. (when (buffer-narrow-info (bp-buffer (svref ring index))) (when (loop with mark = (svref ring index) with target = (bp-line mark) for line first (buffer-content (bp-buffer mark)) then (line-next line) never (eq line target)) (ed-lose "Mark outside region"))) ;; )) (defun edit-cursor-goto (buffer line position) (when (not (eq buffer (bp-buffer *editor-cursor*))) (point-selected buffer :create nil)) (send *editor-cursor* :move line position)) (defun goto-mark (mark) (unless (null mark) (edit-cursor-goto (bp-buffer mark) (bp-line mark) (bp-position mark)))) Some kill primitives have rightly been moved to KILLS.LSP ; ;String comparison. ; (defun string-search-for-substring (chars string &optional (start 0) (chars-length (string-length chars))) (or (string= string "") (let ((c1 (char string 0)) (c2) (len (string-length string)) (last)) (setq c2 (char-upcase c1) c1 (char-downcase c1) last (-& chars-length len)) (or (loop for pos first (%string-posq c1 chars start chars-length) then (%string-posq c1 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j)))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))) (loop for pos first (%string-posq c2 chars start chars-length) then (%string-posq c2 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j)))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))))))) (defun delimited-substring-search (chars string &optional (start 0) (chars-length (string-length chars))) (or (string= string "") (let ((c1 (char string 0)) (c2) (len (string-length string)) (last)) (setq c2 (char-upcase c1) c1 (char-downcase c1) last (-& chars-length len)) (or (loop for pos first (%string-posq c1 chars start chars-length) then (%string-posq c1 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (and (or (0p pos) (white-space? (char chars (1-& pos)))) (or (=& pos last) (white-space? (char chars (+& pos len)))) (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j))))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))) (loop for pos first (%string-posq c2 chars start chars-length) then (%string-posq c2 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (and (or (0p pos) (white-space? (char chars (1-& pos)))) (or (=& pos last) (white-space? (char chars (+& pos len)))) (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j))))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))))))) ;More randomness. ;The argument is not the default. (defmacro argument? () '(or (not (=& *argument* 1)) argument-supplied?)) ;The argument was C-U with no number. (defmacro c-u-only? () `(and (=& *argument* 4) (null argument-supplied?))) ;An argument is supplied, not just C-U. (defmacro real-arg-sup? () `(or argument-supplied? (and (not (=& *argument* 1)) (not (=& *argument* 4))))) (defmacro home-line () '(edit-cursor-home-line *editor-cursor*)) (defmacro current-line () '(edit-cursor-line *editor-cursor*)) (defmacro current-position () '(edit-cursor-position *editor-cursor*)) (defmacro current-window () '(edit-cursor-window *editor-cursor*)) (defmacro advance1 () '(send *editor-cursor* :advance-pos 1)) (defmacro -advance1 () '(send *editor-cursor* :advance-pos -1)) (defun buffer-begin? (&optional (bp *editor-cursor*)) (and (null (line-previous (bp-line bp))) (0p (bp-position bp)))) (defun buffer-end? (&optional (bp *editor-cursor*)) (and (null (line-next (bp-line bp))) (=& (bp-position bp) (line-char-count (bp-line bp))))) (defun last-line? (&optional (bp *editor-cursor*)) (null (line-next (bp-line bp)))) (defun first-line? (&optional (bp *editor-cursor*)) (null (line-previous (bp-line bp)))) (defun not-buffer-begin (&optional (bp *editor-cursor*)) (when (and (null (line-previous (bp-line bp))) (0p (bp-position bp))) (ed-warn :at-start))) (defun not-buffer-end (&optional (bp *editor-cursor*)) (when (and (null (line-next (bp-line bp))) (=& (bp-position bp) (line-char-count (bp-line bp)))) (ed-warn :at-end))) (defun not-first-line (&optional (bp *editor-cursor*)) (when (null (line-previous (bp-line bp))) (ed-warn :at-first-line))) (defun not-last-line (&optional (bp *editor-cursor*)) (when (null (line-next (bp-line bp))) (ed-warn :at-last-line))) (defun check-line-map-is-current (point) (loop with win = (edit-cursor-window point) for i from (window-y-pos win) below (+& (window-y-pos win) (window-y-size win)) with line = (edit-cursor-home-line point) for old-map-line first (aref *line-map* i) then map-line for map-line = (aref *line-map* i) always (or (eq map-line line) (eq map-line old-map-line)) if (eq map-line line) do (and line (setq line (line-next line))))) (defun buffer-end-on-screen? (&optional (point *editor-cursor*)) (let ((win (edit-cursor-window point))) (and (not (null win)) (if (not (check-line-map-is-current point)) (buffer-end? point) (let ((last (+& (window-y-pos win) (window-y-size win) -1))) (or (null (aref *line-map* last)) (null (line-next (aref *line-map* last))))))))) ;; ;;Some usefull functions. ;; (defun last-line (&optional (start-line (bp-line *editor-cursor*))) (loop for line first start-line then next for next = (line-next line) while (not (null next)) finally (return line))) (defun nth-next-line (start-line n) (if (-p n) (nth-previous-line start-line (-& n)) (loop for i from 0 to n for line first start-line then next for next = (line-next line) while next finally (return line)))) (defun nth-previous-line (start-line n) (if (-p n) (nth-next-line start-line (-& n)) (loop for i from 0 to n for line first start-line then prev for prev = (line-previous line) while prev finally (return line)))) ;;; PROCESS-WORDS-AS-STRINGS and PROCESS-REGION-AS-CHARACTERS moved to KILLS.LSP for no better reason than to put them ;;; closer to their loved ones (defun process-region-as-lines (function &RESTV args) (multiple-value-bind (bp1 bp2) (order-bps *editor-cursor* (get-mark)) (loop with limit-line = (line-next (bp-line bp2)) for line first (bp-line bp1) then (line-next line) until (or (null line) (eq line limit-line)) do (lexpr-funcall function line args)))) (defun process-region-as-lines-with-point (function &RESTV args) (multiple-value-bind (bp1 bp2) (order-bps *editor-cursor* (get-mark)) (loop with temp-bp = (copy-bp *editor-cursor*) with limit-line = (line-next (bp-line bp2)) for line first (bp-line bp1) then (line-next line) until (or (null line) (eq line limit-line)) do (send *editor-cursor* :move line 0) do (lexpr-funcall function line args) finally (send *editor-cursor* :move (bp-line temp-bp) (bp-position temp-bp)) finally (send temp-bp :send-if-handles :expire)))) ;Should BUFFER (below) call this on a list? (Using what name?) (defun list-to-buffer (name list-of-strings) (if (null list-of-strings) Fucking STRING interpretation of NIL . (loop with buffer = (buffer name :create t) with line-1 = (make-line buffer nil nil (string (car list-of-strings))) for string in list-of-strings for prev first line-1 then (make-line buffer prev nil (string string)) finally (setf (buffer-content buffer) line-1) finally (return buffer)))) ;Coerse any reasonable thing to be a buffer. ;Value is NIL if object cannot be interpreted as a buffer. (defun buffer (x &key (create t)) (cond ((null x) nil) ;Makes certain code easier. ((of-type x 'buffer) x) ((stringp x) (loop for buffer in *all-buffers* if (string-equal (buffer-name buffer) x) return buffer finally (unless (null create) (let ((buffer (make-buffer x))) (send buffer :set-file-name (editor-default x)) (return buffer))))) ((of-type x 'pathname) (setq x (editor-default x)) (let ((true (probe-file x))) (or (if (null true) (loop for buffer in *all-buffers* if (and (buffer-file-name buffer) (send (buffer-file-name buffer) :equal x)) return buffer) (loop for buffer in *all-buffers* if (and (buffer-file-name buffer) (send true :equal (probe-file (buffer-file-name buffer)))) return buffer)) (unless (null create) (let ((buffer (make-buffer (send x :name)))) (send buffer :set-file-name x) (if (not (null true)) (read-file-into-buffer x buffer) (editor-notify "New File")) buffer))))) ;;Note the funny coding. This could work for BPs, but I don't ;;want to encourage that unless it seems to be needed. ( I am thinking of eliminating the BUFFER field from BPs & LINEs . ) ((of-type x 'edit-cursor) (bp-buffer x)) (t nil))) ;Ditto for edit-cursors. (defun point (x &key (create t)) (cond ((null x) nil) ;Makes certain code easier. ((of-type x 'edit-cursor) x) ((or (stringp x) (of-type x 'pathname) (of-type x 'buffer)) (when (setq x (buffer x :create create)) (or (loop with p1 = nil for p in *all-edit-cursors* if (eq x (edit-cursor-buffer p)) do (progn (setq p1 p) (when (null (edit-cursor-window p)) (return p))) finally (when (not (null p1)) (return p1))) (and (not (null create)) (create-edit-cursor x))))) (t nil))) (defun point-selected (x &key (create t)) (let ((point (point x :create create))) (unless (null point) (if (edit-cursor-window point) (select-point point) (select-point-in-current-window point))) point))
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/gjcx/steve/auks.lisp
lisp
Package : STEVE ; : CL ; -*- Permission to copy all or part of this material is granted, provided copyright notice and reference to the source file and the software distribution version appear, and that notice is given that copying This file contains random functions used by the editor, which do not depend heavily on other functions in the editor. Some of them may depend upon its data formats however. This is certainly not a guarantee that anything here will work in another context. ***************************************************************************** Compilation note. Before installation every file in the editor should be compiled in an environment where the whole editor is loaded. This ensures that DEFSUBSTs are expanded, and that macros work correctly. ****************************************************************************** eval-when Initial value inconsequential Initial value inconsequential Initial value inconsequential This is very much dependant upon the ASCII character set. Normally a graphic-charp character will not be an argument. Edit-cursors bind a buffer, a cursor and a window together. :gettable-instance-variables This is how to make a new buffer. If the name is not unique, the existing buffer may be used however. This delays calculation of the environment until it is actually needed. What we need is a way to set/read the syntax for any STRING-CHAR For now we will assume there are at most 8 bits of information about any character. Type must be an symbol. When using the syntax base option, the base must be declared before it is used. This allocates a bit automatically, and sets the name to reference it. Syntax table generation. We assume that: Open paren For Close paren ( ) [ ] { } < > And all others will either be illegal as parens, or match themselves. Any complaints? Syntax bit declarations. Syntax types. Syntax table usage. Macros to do some fancy line control stuff. Functions to do overwritten displays. This has to be retro-fitted to the editor. It also must be able to do keyboard macros. Any character read from the keyboard must be read by this function, which will take care of all such considerations. If the last character read is pushed back, it will still be in the buffer. If this is a problem, check the flag (pushback-flag). I wonder if this would be better done by defining a special purpose stream? (ed-warning "Character reader out of sync") Note that this ignores the stream. This might screw somthing terribly, but what else is there to do? Functions to interact with the user. These should be used when possible, so that the interaction is as ritualized as possible. This does a great deal to make the editor (or any program) easy to use. These should do completion etc. Completion of buffer names. This does not really belong in this file because it depends heavily upon being part of the editor. It is included here because it belongs with the previous functions. Is common lisp really so damned brain dead as to think that anyone will ever want STRING to return "NIL" for the empty list. I would examples where that behavior has fucked me over. Note we know the implication of string-charp here. then completing "" will => "F" and so ^X ^B <CR> will incorectly create a buffer named "F" if we are not careful here. this in newmacros and renamed to avoid lossage . Forever. Use this when programing a function that sometimes pushes a mark. This will print a mark-set message when called, if appropriate. This code is only to keep narrowing from losing. This code is only to keep narrowing from losing. String comparison. More randomness. The argument is not the default. The argument was C-U with no number. An argument is supplied, not just C-U. Some usefull functions. PROCESS-WORDS-AS-STRINGS and PROCESS-REGION-AS-CHARACTERS closer to their loved ones Should BUFFER (below) call this on a list? (Using what name?) Coerse any reasonable thing to be a buffer. Value is NIL if object cannot be interpreted as a buffer. Makes certain code easier. Note the funny coding. This could work for BPs, but I don't want to encourage that unless it seems to be needed. Ditto for edit-cursors. Makes certain code easier.
Copyright ( c ) May 1983 by and Massachusetts Institute of Technology . that the copies are not made or distributed for resale , the MIT is by permission of Massachusetts Institute of Technology . (defvar *query-line*) (defvar *notify-line*) (defvar *more-line*) (defvar *feedback-line*) (defvar *double-line*) (defvar *error-line*) (defvar *prefix-echo-line*) Now 135 spaces long for bigger TTYs . (defconstant 80spaces " ") (defconstant 80dashes "---------------------------------------------------------------------------------------------------------------------------------------") Ascii dependant cruft which helps fix the read stream . (eval-when (compile load) (defconstant *first-non-control-character-code* (char-int #\space)) (defconstant *first-meta-character-code* 128) (defconstant *tab-distance* 8) (defconstant n-spaces for i from 0 to 8 do (setf (svref vector i) (make-string i :initial-element #\sp)) finally (return vector))) (defconstant control-character-translation-table #.(loop with vect = (make-vector (char-int #\space)) for i from 0 below (char-int #\space) for char = (int-char i) if (memq char '(#\bell #\backspace #\tab #\line #\page #\return #\altmode)) do (setf (aref vect i) char) else do (setf (aref vect i) (code-char (logior& (char-code char) #o100) char-control-bit)) finally (return vect))) (defconstant character-translation-table for i from 0 to 255 for chr = (int-char i) do (cond ((memq chr '(#\bell #\backspace #\tab #\line #\page #\return #\altmode)) (setf (aref vect i) chr)) ((>=& i 128) (setf (aref vect i) (code-char (logandc2& i #o0200) char-meta-bit))) (t (setf (aref vect i) chr))) do (cond ((memq (make-char (setq chr (aref vect i))) '(#\bell #\backspace #\tab #\line #\page #\return #\altmode))) ((<& (char-code chr) (char-int #\space)) (setf (aref vect i) (code-char (logior& (char-code chr) #o100) (logior& (char-bits chr) char-control-bit))))) finally (return vect))) (defsubst canonicalize-control-characters (char) (svref character-translation-table (char-int char))) (defun coerse-to-string-charp (char) (cond ((string-charp char) char) ((not (0p (char-font char))) nil) ((not (0p (logandc2 (char-bits char) #.(logior& char-control-bit char-meta-bit)))) nil) (t (let ((code (char-code char))) (when (not (0p (logand& (char-bits char) char-control-bit))) (setq code (logandc2& code #o100))) (when (not (0p (logand& (char-bits char) char-meta-bit))) (setq code (logior& code #o200))) (int-char code))))) (defparameter preknown-character-printed-representations #.(loop with v = (make-vector char-code-limit :initial-element nil) for i from 0 below char-code-limit as c = (code-char i) do (unless (graphic-charp c) (setf (svref v i) (format nil (if (and (<& i 32) (not (char-name c))) "~:C" "~@C") c))) finally (return v))) (defsubst stringify-tab (col) (let ((col1 col)) (svref n-spaces (-& (logandc1& 7 (+& col1 8)) col1)))) (defsubst stringify-non-tab (chr) (svref preknown-character-printed-representations (char-code chr))) (defsubst stringify-char (chr col) (let ((chrctr chr) (col1 col)) (if (eq chrctr #\tab) (svref n-spaces This depends upon tabs being 8 columns apart . (-& (logandc1& 7 (+& col1 8)) col1)) (svref preknown-character-printed-representations (char-code chrctr))))) (defflavor edit-cursor (buffer line position window home-line home-pos) (bp) :ordered-instance-variables :initable-instance-variables :outside-accessible-instance-variables) (defmethod (edit-cursor :print-self) (&optional (stream standard-output) ignore ignore) (format stream "#<~s ~a " 'edit-cursor (buffer-name buffer)) (print-bp-internal line position stream) (write-char #\> stream)) (defun create-edit-cursor (buffer &optional (line (buffer-content buffer)) (pos 0) (window nil)) (let ((new-bp (make-instance 'edit-cursor :line line :position pos :buffer buffer :window window :home-line line :home-pos 0))) (send line :add-bp new-bp) (push new-bp *all-edit-cursors*) new-bp)) (defun make-buffer (name) (let ((buffer (buffer name :create nil))) (when (not (null buffer)) (with-double-second-line (with-double-line (format terminal-io "A buffer named ~a (file ~a) already exists." name (send (buffer-file-name buffer) :string-for-editor)) (format terminal-io "~&Type buffer name to use, or CR to reuse ~a (or <DEL> to select it): " name) (let ((new-name (prescan #'read-buffer-name nil))) (cond ((null new-name) ) ((string= new-name "") (when (buffer-modified? buffer) (when (with-query-line (oustr "Save changes to buffer? " terminal-io) (ed-y-or-n-p "Save changes to ~a " (buffer-name buffer))) (save-file buffer))) (%kill-buffer-primitive buffer) (setq buffer nil)) (t (setq name new-name) (setq buffer (buffer name :create t)))))))) (when (null buffer) (setf buffer (make-instance 'buffer :name name :access buffer-access-any :environment nil :mark-ring (make-vector mark-ring-size :initial-element nil) :mark-ring-index 0 :narrow-info nil)) (setf (buffer-content buffer) (make-line buffer nil nil)) (setf (buffer-modified? buffer) nil) (push buffer *all-buffers*) (send buffer :set-file-name (editor-default name)) (when *buffer-creation-hook* (funcall *buffer-creation-hook* buffer))) buffer)) (defun make-point (name &optional (window nil)) (let ((buff (make-buffer name))) (create-edit-cursor buff (buffer-content buff) 0 window))) (defun select-point (point &aux (buffer (edit-cursor-buffer point))) (unless (eq *editor-buffer* buffer) (setq *last-buffer-selected* *editor-buffer*)) (unless (eq *editor-cursor* point) (setq *editor-cursor* point *.* point *editor-buffer* buffer *b* *editor-buffer* *context-change-flag* t)) (when (null (edit-cursor-window point)) (with-no-passall (oustr "Selected point has no associated window." echo-area-window) (oustr "I will try to fix it" echo-area-window) (one-window)))) (defun select-point-in-current-window (point) (unless (eq point *editor-cursor*) (setf (edit-cursor-window point) (edit-cursor-window *editor-cursor*) (edit-cursor-window *editor-cursor*) nil) (select-point point))) Character syntax for . This will be stored in a 256 byte table . (defvar syntax-bit-map nil) (defvar *all-modes* nil) (defmacro declare-syntax-type (type &optional (base nil)) `(progn (defvar ,type ,(if (null base) '(make-empty-syntax-table) `(copy-syntax-table ,base))) (defprop ,type t syntax-type) (or (memq ,type *all-modes*) (push ,type *all-modes*)))) (defun make-empty-syntax-table () (make-bits (* 256 8))) (defun copy-syntax-table (table) (bits-replace (make-empty-syntax-table) table 0 0 (* 256 8))) (defvar next-unused-syntax-bit 0) (defvar max-syntax-bit 7) (defmacro declare-syntax-bit (name) `(progn (defvar ,name) (when (null (get ',name 'syntax-bit)) (when (>& next-unused-syntax-bit max-syntax-bit) (ed-lose "Too Many Syntax Bits Allocated")) (putprop ',name next-unused-syntax-bit 'syntax-bit) (setq next-unused-syntax-bit (1+& next-unused-syntax-bit)) (setq ,name (get ',name 'syntax-bit)) (defvar ,(intern (string-append name "-MASK")) (^& 2 ,name)) (push (list ,name ',name (^& 2 ,name)) syntax-bit-map)))) (defun syntax-description (table char &aux (byte (get-char-syntax table char))) (loop for (bit-number name) in syntax-bit-map if (logbitp& bit-number byte) collect name)) This can be expanded by SETF . (defmacro get-char-syntax (table char) `(get-a-byte ,table (char-code ,char))) This can be expanded by SETF . (defmacro get-char-syntax-bit (table char bit) `(bit ,table (+& (*& 8 (char-code ,char)) ,bit))) (defmacro of-syntax (char bit) `(=& 1 (get-char-syntax-bit syntax-table ,char ,bit))) Paren matching . Paren matching is more wired in than in emacs . (defvar paren-matches '((#\) . #\() (#\] . #\[) (#\} . #\{) (#\> . #\<) (#\' . #\`) (#\( . #\)) (#\[ . #\]) (#\{ . #\}) (#\< . #\>) (#\` . #\'))) (defmacro get-paren-match (paren) `(cdr (assq ,paren paren-matches))) (declare-syntax-bit word-alphanumeric) (declare-syntax-bit lisp-alphanumeric) (declare-syntax-bit white-space) (declare-syntax-bit paren-open) (declare-syntax-bit paren-close) (declare-syntax-bit string-quote) (declare-syntax-bit character-quote) (declare-syntax-bit prefix) (defparameter lisp-word-chars ".") (defparameter text-word-chars "'") (defparameter lisp-atom-chars "!#&*+/<=>?@^`-_:\\[]") (defparameter extra-alphanumerics "$%") (defparameter white-space-chars #.(to-string '(#\space #\tab #\return))) (defparameter prefix-chars "':`,#;\\") (defun set-to-syntax (table string syntax) (loop for i from 0 below (string-length string) do (setf (get-char-syntax-bit table (char string i) syntax) 1))) (defun set-default-syntax (table) (loop for i from 0 below 256 for chr = (int-char i) if (alphanumericp chr) do (setf (get-char-syntax-bit table chr word-alphanumeric) 1 (get-char-syntax-bit table chr lisp-alphanumeric) 1)) (set-to-syntax table extra-alphanumerics word-alphanumeric) (set-to-syntax table extra-alphanumerics lisp-alphanumeric) (set-to-syntax table lisp-word-chars lisp-alphanumeric) (set-to-syntax table lisp-atom-chars lisp-alphanumeric) (set-to-syntax table white-space-chars white-space) (set-to-syntax table prefix-chars prefix) (setf (get-char-syntax-bit table #\( paren-open) 1) (setf (get-char-syntax-bit table #\) paren-close) 1) (setf (get-char-syntax-bit table #\" string-quote) 1) (setf (get-char-syntax-bit table #\| string-quote) 1) (setf (get-char-syntax-bit table #\\ character-quote) 1)) (declare-syntax-type *fundamental-syntax*) (set-default-syntax *fundamental-syntax*) (declare-syntax-type *text-syntax*) (set-default-syntax *text-syntax*) (set-to-syntax *text-syntax* text-word-chars word-alphanumeric) (declare-syntax-type *lisp-syntax*) (set-default-syntax *lisp-syntax*) (set-to-syntax *lisp-syntax* lisp-word-chars word-alphanumeric) The current value of SYNTAX - TABLE is the current syntax . (defvar syntax-table *lisp-syntax*) (defsubst atom-char? (chr) (=& 1 (get-char-syntax-bit syntax-table chr lisp-alphanumeric))) (defsubst word-char? (chr) (=& 1 (get-char-syntax-bit syntax-table chr word-alphanumeric))) (defsubst white-space? (chr) (=& 1 (get-char-syntax-bit syntax-table chr white-space))) (defsubst horizontal-white-space? (chr) (and (white-space? chr) (not (char= chr #\return)))) (defmacro with-line (line &body forms) `(unwind-protect (progn (cursorpos ,line 0) (send terminal-io :clear-eol) ,@forms) (cursorpos ,line 0) (send terminal-io :clear-eol))) (defmacro with-line-remaining (line &body forms) `(progn (cursorpos ,line 0) (send terminal-io :clear-eol) ,@forms)) (defmacro declare-line (name line &aux (arg (gensym))) `(progn (defmacro ,(intern (string-append "WITH-" name "-LINE")) (&body ,arg) (list* 'with-line ',line ,arg)) (defmacro ,(intern (string-append "WITH-" name "-LINE-REMAINING")) (&body ,arg) (list* 'with-line-remaining ',line ,arg)))) (declare-line query *query-line*) (declare-line notify *notify-line*) (declare-line more *more-line*) (declare-line feedback *feedback-line*) (declare-line double *double-line*) (declare-line double-second (1+& *double-line*)) (declare-line error *error-line*) (declare-line prefix-echo *prefix-echo-line*) (defvar *overwrite-line* 0) (defun overwrite-open-line (line) (cursorpos line 0 terminal-io) (send terminal-io :clear-eol) (setq creamed-tty-lines-to (max& (1+& line) creamed-tty-lines-to)) (setq *overwrite-line* line) t) (defun overwrite-home () (overwrite-open-line 0)) (defun overwrite-start () (overwrite-open-line *overwrite-line*)) (defun overwrite-done () (setq *overwrite-line* (1+& *overwrite-line*))) (defun overwrite-terpri () (setq *overwrite-line* (1+& *overwrite-line*)) (when (>& *overwrite-line* *last-overwrite-line*) (setq *overwrite-line* 0) (with-more-line (setq creamed-tty-lines-to (max& (send terminal-io :linenum) creamed-tty-lines-to)) (oustr "*more*" terminal-io) (cond ((char= (peek-char&save) #\space) (read-char&save)) (t (when (char= (peek-char&save) #\rubout) (read-char&save)) (ed-abort))))) (overwrite-open-line *overwrite-line*)) (defun editor-notify (string) (with-notify-line-remaining (princ string terminal-io))) Special purpose IO functions . The editor needs to save the last 60 chars for the help command . However , there is one problem with these functions . (defvar 60char-buffer (make-string 60 :initial-element #\space)) (defvar 60char-index 0) (defvar 1char-buffer #\null) (defvar save-chars-for-keyboard-macros nil) (defvar pushback-flag nil) (defvar keyboard-macro-char-list nil) (defvar executing-keyboard-macro nil) (defun read-char&save (&optional (stream terminal-io)) (cond ((not (null pushback-flag)) (unless (if (not (null executing-keyboard-macro)) (char= (pop executing-keyboard-macro) 1char-buffer) (char= (send stream :read-char) 1char-buffer)) nil)) ((not (null executing-keyboard-macro)) (setq 1char-buffer (pop executing-keyboard-macro)) (when (null executing-keyboard-macro) (send terminal-io :set-device-mode :passall *editor-device-mode*))) (t (setq 1char-buffer (send stream :read-char)) (setf (char 60char-buffer 60char-index) 1char-buffer) (setq 60char-index (\\& (1+& 60char-index) 60)) (when save-chars-for-keyboard-macros (push 1char-buffer keyboard-macro-char-list)))) (setq pushback-flag nil) 1char-buffer) (defun string-read&save (char-list) (loop for char in char-list do (setf (char 60char-buffer 60char-index) char) do (setq 60char-index (\\& (1+& 60char-index) 60))) (setq pushback-flag nil) (setq 1char-buffer (car (last char-list)))) (defun unread-char&save (char &optional (stream terminal-io)) (cond ((not (null pushback-flag)) (ed-lose "Double Unread&save")) (executing-keyboard-macro (push char executing-keyboard-macro)) (t (send stream :unread-char char))) (setq pushback-flag t) char) (defun peek-char&save (&optional (stream terminal-io)) (unread-char&save (read-char&save stream) stream)) (defresource reading-buffer () :constructor (make-array 100 :element-type 'string-char :fill-pointer 0 :adjustable t) :deinitializer (reset-fill-pointer object 0)) (defun readline-with-exit (stream) (using-resource (reading-buffer b) (loop for char = (read-char&save stream) do (case char (#\bell (ed-abort :echo terminal-io)) ((#\altmode #\return) (return (copy-seq b))) (t (vector-push-extend char b)))))) (defun read-symbol (stream) (using-resource (reading-buffer b) (loop for chr = (read-char&save stream) do (if (or (null chr) (white-space? chr)) (return (intern (copy-seq b))) (vector-push-extend (char-upcase chr) b))))) (defun read-file-name (&optional (stream terminal-io stream?) &aux name) (cond ((null stream?) (setq name (si:ttyscanner #'readline-with-exit terminal-io terminal-io #'(lambda (strm reason) (oustr "File: " strm)) T 0)) (if (not (stringp name)) (ed-warn :aborted) name)) (t (readline-with-exit stream)))) like to see someone come up with three examples of natural uses for that type of mis - behavior . I can come up with 95 natural (defun steve-to-string (seq) (cond ((stringp seq) seq) ((null seq) (make-string 0)) ((symbolp seq) (get-pname seq)) ((characterp seq) (if (string-charp seq) (aref *:character-to-string-table (char-code seq)) (cerror t nil ':implementation-lossage "The character ~S can't go into a string" seq))) ((pairp seq) (let* ((n (list-length seq)) (s (make-string n :initial-element #\space))) (loop for c in seq for i from 0 do (rplachar s i (to-character c))) s)) ((bitsp seq) (let* ((n (bits-length seq)) (s (make-string n :initial-element #\space))) (dotimes (i n) (rplachar s i (char "01" (bit seq i)))) s)) ((vectorp seq) (let* ((n (vector-length seq)) (s (make-string n :initial-element #\space))) (dotimes (i n) (rplachar s i (to-character (aref seq i)))) s)) ((and (si:extendp seq) (send seq ':send-if-handles ':to-string))) (t (steve-to-string (cerror t () ':wrong-type-argument "~*~S not coercible to a string" 'string seq))))) (defun complete-buffer-name (name) (loop with completion = nil with length = (string-length name) for buffer in *all-buffers* for bname = (buffer-name buffer) if (string-equal name bname 0 0 length (min& (string-length bname) length)) do (cond ((null completion) (setq completion bname)) (t (setq completion (max-prefix (list completion bname))))) finally (return (if (or (null completion) (<=& (string-length completion) length)) name completion)))) (defun print-buffer-name-completions (name) (overwrite-start) (loop with length = (string-length name) for buffer in *all-buffers* for bname = (buffer-name buffer) if (string-equal name bname 0 0 length (min& (string-length bname) length)) do (progn (princ bname terminal-io) (overwrite-terpri))) (oustr "Done" terminal-io) (overwrite-terpri) (overwrite-done)) (defun read-buffer-name (stream &aux name) (loop for chr = (read-char&save stream) do (cond ((char= chr #\return) (return If the only buffers are named FOO and FROB (cond ((not (null *buffer-name-completion-on-return*)) (setq name (complete-buffer-name (steve-to-string chrs))) (if (buffer name :create nil) name (steve-to-string chrs))) (t (steve-to-string chrs))))) ((char= chr #\altmode) (send stream :completion-string (setq name (complete-buffer-name (steve-to-string chrs))) (1+& (length chrs))) (when (buffer name :create nil) (send stream :send-if-handles :echo-false-char #\$)) (throw 'rubout-tag nil)) ((char= chr #\page) (make-screen-image) (send stream :rubout) (throw 'rubout-tag nil)) ((char= chr #\?) (print-buffer-name-completions (steve-to-string chrs)) (send stream :rubout) (throw 'rubout-tag nil))) collect chr into chrs)) (defun ed-y-or-n-p (&optional (help "Type Y or N") &RESTV format-args) (do ((char) (c-pos (cursorpos terminal-io))) (cursorpos (car c-pos) (cdr c-pos) terminal-io) (setq char (read-char&save)) (send terminal-io :write-char char) (case char ((#\Y #\y) (oustr "es" terminal-io) (return t)) ((#\N #\n) (write-char #\o terminal-io) (return nil)) (#\? (with-notify-line-remaining (lexpr-funcall #'format terminal-io help format-args))) (#\bell (ed-abort :echo terminal-io)) (t (with-notify-line-remaining (format terminal-io "Type Y or N. ? for help")))))) Function to " bind " passall mode off . (defmacro with-no-passall (&body forms &aux (var (gentemp))) `(let ((,var (send terminal-io :get-device-mode :passall))) (unwind-protect (progn (send terminal-io :set-device-mode :passall nil) ,@forms) (send terminal-io :set-device-mode :passall ,var)))) Emacs rings . First some primatives . (defvar mark-ring-size 8) (defvar mark-ring (make-vector mark-ring-size :initial-element nil)) (defvar mark-ring-index 0) (defun push-mark (bp) (let ((mark-ring-index (buffer-mark-ring-index *editor-buffer*))) (setq mark-ring-index (1+& mark-ring-index)) (if (>=& mark-ring-index mark-ring-size) (setq mark-ring-index 0)) (setf (svref (buffer-mark-ring *editor-buffer*) mark-ring-index) (copy-bp bp) (buffer-mark-ring-index *editor-buffer*) mark-ring-index))) (defun auto-push-mark (bp) (unless (string= "" auto-push-point-notification) (with-error-line-remaining (oustr auto-push-point-notification terminal-io))) (push-mark bp)) (defun push-mark-no-copy (bp) (let ((mark-ring-index (buffer-mark-ring-index *editor-buffer*))) (setq mark-ring-index (1+& mark-ring-index)) (if (>=& mark-ring-index mark-ring-size) (setq mark-ring-index 0)) (setf (aref (buffer-mark-ring *editor-buffer*) mark-ring-index) bp (buffer-mark-ring-index *editor-buffer*) mark-ring-index))) (defun pop-mark () (let ((ring (buffer-mark-ring *editor-buffer*)) (index (buffer-mark-ring-index *editor-buffer*))) (prog1 (or (svref ring index) (ed-warn :no-mark)) (when (buffer-narrow-info (bp-buffer (svref ring index))) (when (loop with mark = (svref ring index) with target = (bp-line mark) for line first (buffer-content (bp-buffer mark)) then (line-next line) never (eq line target)) (ed-lose "Mark outside region"))) (loop do (setq index (1-& index)) do (when (-p index) (setq index (1-& mark-ring-size))) until (svref ring index)) (setf (buffer-mark-ring-index *editor-buffer*) index)))) (defun get-mark (&aux ring index) (prog1 (or (aref (setq ring (buffer-mark-ring *editor-buffer*) ) (setq index (buffer-mark-ring-index *editor-buffer*))) (ed-warn :no-mark)) (when (buffer-narrow-info (bp-buffer (svref ring index))) (when (loop with mark = (svref ring index) with target = (bp-line mark) for line first (buffer-content (bp-buffer mark)) then (line-next line) never (eq line target)) (ed-lose "Mark outside region"))) )) (defun edit-cursor-goto (buffer line position) (when (not (eq buffer (bp-buffer *editor-cursor*))) (point-selected buffer :create nil)) (send *editor-cursor* :move line position)) (defun goto-mark (mark) (unless (null mark) (edit-cursor-goto (bp-buffer mark) (bp-line mark) (bp-position mark)))) Some kill primitives have rightly been moved to KILLS.LSP (defun string-search-for-substring (chars string &optional (start 0) (chars-length (string-length chars))) (or (string= string "") (let ((c1 (char string 0)) (c2) (len (string-length string)) (last)) (setq c2 (char-upcase c1) c1 (char-downcase c1) last (-& chars-length len)) (or (loop for pos first (%string-posq c1 chars start chars-length) then (%string-posq c1 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j)))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))) (loop for pos first (%string-posq c2 chars start chars-length) then (%string-posq c2 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j)))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))))))) (defun delimited-substring-search (chars string &optional (start 0) (chars-length (string-length chars))) (or (string= string "") (let ((c1 (char string 0)) (c2) (len (string-length string)) (last)) (setq c2 (char-upcase c1) c1 (char-downcase c1) last (-& chars-length len)) (or (loop for pos first (%string-posq c1 chars start chars-length) then (%string-posq c1 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (and (or (0p pos) (white-space? (char chars (1-& pos)))) (or (=& pos last) (white-space? (char chars (+& pos len)))) (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j))))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))) (loop for pos first (%string-posq c2 chars start chars-length) then (%string-posq c2 chars pos (-& chars-length pos)) never (or (null pos) (>& pos last)) if (and (or (0p pos) (white-space? (char chars (1-& pos)))) (or (=& pos last) (white-space? (char chars (+& pos len)))) (loop for j from 1 below len always (char-equal (char string j) (char chars (+& pos j))))) return (if (<& pos chars-length) pos nil) do (setq pos (1+& pos))))))) (defmacro argument? () '(or (not (=& *argument* 1)) argument-supplied?)) (defmacro c-u-only? () `(and (=& *argument* 4) (null argument-supplied?))) (defmacro real-arg-sup? () `(or argument-supplied? (and (not (=& *argument* 1)) (not (=& *argument* 4))))) (defmacro home-line () '(edit-cursor-home-line *editor-cursor*)) (defmacro current-line () '(edit-cursor-line *editor-cursor*)) (defmacro current-position () '(edit-cursor-position *editor-cursor*)) (defmacro current-window () '(edit-cursor-window *editor-cursor*)) (defmacro advance1 () '(send *editor-cursor* :advance-pos 1)) (defmacro -advance1 () '(send *editor-cursor* :advance-pos -1)) (defun buffer-begin? (&optional (bp *editor-cursor*)) (and (null (line-previous (bp-line bp))) (0p (bp-position bp)))) (defun buffer-end? (&optional (bp *editor-cursor*)) (and (null (line-next (bp-line bp))) (=& (bp-position bp) (line-char-count (bp-line bp))))) (defun last-line? (&optional (bp *editor-cursor*)) (null (line-next (bp-line bp)))) (defun first-line? (&optional (bp *editor-cursor*)) (null (line-previous (bp-line bp)))) (defun not-buffer-begin (&optional (bp *editor-cursor*)) (when (and (null (line-previous (bp-line bp))) (0p (bp-position bp))) (ed-warn :at-start))) (defun not-buffer-end (&optional (bp *editor-cursor*)) (when (and (null (line-next (bp-line bp))) (=& (bp-position bp) (line-char-count (bp-line bp)))) (ed-warn :at-end))) (defun not-first-line (&optional (bp *editor-cursor*)) (when (null (line-previous (bp-line bp))) (ed-warn :at-first-line))) (defun not-last-line (&optional (bp *editor-cursor*)) (when (null (line-next (bp-line bp))) (ed-warn :at-last-line))) (defun check-line-map-is-current (point) (loop with win = (edit-cursor-window point) for i from (window-y-pos win) below (+& (window-y-pos win) (window-y-size win)) with line = (edit-cursor-home-line point) for old-map-line first (aref *line-map* i) then map-line for map-line = (aref *line-map* i) always (or (eq map-line line) (eq map-line old-map-line)) if (eq map-line line) do (and line (setq line (line-next line))))) (defun buffer-end-on-screen? (&optional (point *editor-cursor*)) (let ((win (edit-cursor-window point))) (and (not (null win)) (if (not (check-line-map-is-current point)) (buffer-end? point) (let ((last (+& (window-y-pos win) (window-y-size win) -1))) (or (null (aref *line-map* last)) (null (line-next (aref *line-map* last))))))))) (defun last-line (&optional (start-line (bp-line *editor-cursor*))) (loop for line first start-line then next for next = (line-next line) while (not (null next)) finally (return line))) (defun nth-next-line (start-line n) (if (-p n) (nth-previous-line start-line (-& n)) (loop for i from 0 to n for line first start-line then next for next = (line-next line) while next finally (return line)))) (defun nth-previous-line (start-line n) (if (-p n) (nth-next-line start-line (-& n)) (loop for i from 0 to n for line first start-line then prev for prev = (line-previous line) while prev finally (return line)))) moved to KILLS.LSP for no better reason than to put them (defun process-region-as-lines (function &RESTV args) (multiple-value-bind (bp1 bp2) (order-bps *editor-cursor* (get-mark)) (loop with limit-line = (line-next (bp-line bp2)) for line first (bp-line bp1) then (line-next line) until (or (null line) (eq line limit-line)) do (lexpr-funcall function line args)))) (defun process-region-as-lines-with-point (function &RESTV args) (multiple-value-bind (bp1 bp2) (order-bps *editor-cursor* (get-mark)) (loop with temp-bp = (copy-bp *editor-cursor*) with limit-line = (line-next (bp-line bp2)) for line first (bp-line bp1) then (line-next line) until (or (null line) (eq line limit-line)) do (send *editor-cursor* :move line 0) do (lexpr-funcall function line args) finally (send *editor-cursor* :move (bp-line temp-bp) (bp-position temp-bp)) finally (send temp-bp :send-if-handles :expire)))) (defun list-to-buffer (name list-of-strings) (if (null list-of-strings) Fucking STRING interpretation of NIL . (loop with buffer = (buffer name :create t) with line-1 = (make-line buffer nil nil (string (car list-of-strings))) for string in list-of-strings for prev first line-1 then (make-line buffer prev nil (string string)) finally (setf (buffer-content buffer) line-1) finally (return buffer)))) (defun buffer (x &key (create t)) ((of-type x 'buffer) x) ((stringp x) (loop for buffer in *all-buffers* if (string-equal (buffer-name buffer) x) return buffer finally (unless (null create) (let ((buffer (make-buffer x))) (send buffer :set-file-name (editor-default x)) (return buffer))))) ((of-type x 'pathname) (setq x (editor-default x)) (let ((true (probe-file x))) (or (if (null true) (loop for buffer in *all-buffers* if (and (buffer-file-name buffer) (send (buffer-file-name buffer) :equal x)) return buffer) (loop for buffer in *all-buffers* if (and (buffer-file-name buffer) (send true :equal (probe-file (buffer-file-name buffer)))) return buffer)) (unless (null create) (let ((buffer (make-buffer (send x :name)))) (send buffer :set-file-name x) (if (not (null true)) (read-file-into-buffer x buffer) (editor-notify "New File")) buffer))))) ( I am thinking of eliminating the BUFFER field from BPs & LINEs . ) ((of-type x 'edit-cursor) (bp-buffer x)) (t nil))) (defun point (x &key (create t)) ((of-type x 'edit-cursor) x) ((or (stringp x) (of-type x 'pathname) (of-type x 'buffer)) (when (setq x (buffer x :create create)) (or (loop with p1 = nil for p in *all-edit-cursors* if (eq x (edit-cursor-buffer p)) do (progn (setq p1 p) (when (null (edit-cursor-window p)) (return p))) finally (when (not (null p1)) (return p1))) (and (not (null create)) (create-edit-cursor x))))) (t nil))) (defun point-selected (x &key (create t)) (let ((point (point x :create create))) (unless (null point) (if (edit-cursor-window point) (select-point point) (select-point-in-current-window point))) point))
2dd296046e6be11077c0591248f43a203adde06ade641505ffe60907d75a3f8b
srstrong/erlawys
aws_util.erl
%%% Copyright ( c ) 2007 %%% All rights reserved. %%% Developed by : at gmail dot com %%% / %%% %%% Permission is hereby granted, free of charge, to any person obtaining a %%% copy of this software and associated documentation files (the " Software " ) , to deal with the Software without restriction , including %%% without limitation the rights to use, copy, modify, merge, publish, distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to %%% the following conditions: %%% %%% Redistributions of source code must retain the above copyright %%% notice, this list of conditions and the following disclaimers. %%% Redistributions in binary form must reproduce the above %%% copyright notice, this list of conditions and the following disclaimers %%% in the documentation and/or other materials provided with the %%% distribution. Neither the names of , %%% nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior %%% written permission. %%% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS %%% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , %%% TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE %%% SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE. %%% -module(aws_util). -author(''). -vcn('0.1'). -date('2007/08/06'). -import(string, [to_lower/1]). %-compile(export_all). -export([filter_nulls/1, params_signature/2, add_default_params/3, create_ec2_param_list/2, create_ec2_param_list/3, tuple_3to2/1]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Helper Methods used to construct URLs to access AWS. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Remove nulls from parameter list. filter_nulls([{_,null}|T]) -> filter_nulls(T); filter_nulls([H|T]) -> [H|filter_nulls(T)]; filter_nulls([]) -> []. % Function to sort params list. sort_params(Params) -> lists:sort(fun({A, _}, {X, _}) -> to_lower(A) < to_lower(X) end, Params). % Make sure you call crypto:start() before using this code. params_signature(Key, Params) -> params_signature(Key, sort_params(Params), []). params_signature(Key, [{K, V}|T], Data) -> params_signature(Key, T, [V,K|Data]); params_signature(Key, [], Data) -> Signature = lists:flatten(lists:reverse(Data)), base64:encode_to_string(crypto:sha_mac(Key, Signature)). % Add default values to list. add_default_params(Params , AccessKey ) - > add_default_params(Params , AccessKey , " 2007 - 03 - 01 " ) . add_default_params(Params, AccessKey, Version) -> NewParams = [{"AWSAccessKeyId", AccessKey}, {"Timestamp", create_timestamp()}, {"SignatureVersion", "1"}, {"Version", Version} | Params], sort_params(NewParams). Time utility function add_zeros(L) -> if length(L) == 1 -> [$0|L]; true -> L end. to_str(L) -> add_zeros(integer_to_list(L)). create_timestamp() -> create_timestamp(calendar:now_to_universal_time(now())). create_timestamp({{Y, M, D}, {H, Mn, S}}) -> to_str(Y) ++ "-" ++ to_str(M) ++ "-" ++ to_str(D) ++ "T" ++ to_str(H) ++ ":" ++ to_str(Mn)++ ":" ++ to_str(S) ++ "Z". % Create a list of name/value pairs for ec2 parameters. create_ec2_param_list(Name, Params) -> create_ec2_param_list_1(Name, Params, 1). create_ec2_param_list(NamePrefix, NameSuffix, Params) -> create_ec2_param_list_2(NamePrefix, NameSuffix, Params, 1). create_ec2_param_list_1(_, null, _) -> []; create_ec2_param_list_1(Name, [H|T], C) -> [{Name ++ "." ++ integer_to_list(C), H} | create_ec2_param_list_1(Name, T, C + 1)]; create_ec2_param_list_1(_, [], _) -> []. create_ec2_param_list_2(_, _, null, _) -> []; create_ec2_param_list_2(NamePrefix, NameSuffix, [null|T], C) -> create_ec2_param_list_2(NamePrefix, NameSuffix, T, C + 1); create_ec2_param_list_2(NamePrefix, NameSuffix, [H|T], C) -> [{NamePrefix ++ "." ++ integer_to_list(C) ++ "." ++ NameSuffix, H} | create_ec2_param_list_2(NamePrefix, NameSuffix, T, C + 1)]; create_ec2_param_list_2(_, _, [], _) -> []. Strip 3 tuple to 2 . tuple_3to2({ok, X, _}) -> {ok, X}; tuple_3to2(T) -> T.
null
https://raw.githubusercontent.com/srstrong/erlawys/18bb4ffdc44710b08433bcab304a266a0ef81e5b/src/aws_util.erl
erlang
All rights reserved. / Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the without limitation the rights to use, copy, modify, merge, publish, the following conditions: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution. nor the names of its contributors may be used to endorse written permission. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE. -compile(export_all). Helper Methods used to construct URLs to access AWS. Remove nulls from parameter list. Function to sort params list. Make sure you call crypto:start() before using this code. Add default values to list. Create a list of name/value pairs for ec2 parameters.
Copyright ( c ) 2007 Developed by : at gmail dot com " Software " ) , to deal with the Software without restriction , including distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , subject to Neither the names of , or promote products derived from this Software without specific prior THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , -module(aws_util). -author(''). -vcn('0.1'). -date('2007/08/06'). -import(string, [to_lower/1]). -export([filter_nulls/1, params_signature/2, add_default_params/3, create_ec2_param_list/2, create_ec2_param_list/3, tuple_3to2/1]). filter_nulls([{_,null}|T]) -> filter_nulls(T); filter_nulls([H|T]) -> [H|filter_nulls(T)]; filter_nulls([]) -> []. sort_params(Params) -> lists:sort(fun({A, _}, {X, _}) -> to_lower(A) < to_lower(X) end, Params). params_signature(Key, Params) -> params_signature(Key, sort_params(Params), []). params_signature(Key, [{K, V}|T], Data) -> params_signature(Key, T, [V,K|Data]); params_signature(Key, [], Data) -> Signature = lists:flatten(lists:reverse(Data)), base64:encode_to_string(crypto:sha_mac(Key, Signature)). add_default_params(Params , AccessKey ) - > add_default_params(Params , AccessKey , " 2007 - 03 - 01 " ) . add_default_params(Params, AccessKey, Version) -> NewParams = [{"AWSAccessKeyId", AccessKey}, {"Timestamp", create_timestamp()}, {"SignatureVersion", "1"}, {"Version", Version} | Params], sort_params(NewParams). Time utility function add_zeros(L) -> if length(L) == 1 -> [$0|L]; true -> L end. to_str(L) -> add_zeros(integer_to_list(L)). create_timestamp() -> create_timestamp(calendar:now_to_universal_time(now())). create_timestamp({{Y, M, D}, {H, Mn, S}}) -> to_str(Y) ++ "-" ++ to_str(M) ++ "-" ++ to_str(D) ++ "T" ++ to_str(H) ++ ":" ++ to_str(Mn)++ ":" ++ to_str(S) ++ "Z". create_ec2_param_list(Name, Params) -> create_ec2_param_list_1(Name, Params, 1). create_ec2_param_list(NamePrefix, NameSuffix, Params) -> create_ec2_param_list_2(NamePrefix, NameSuffix, Params, 1). create_ec2_param_list_1(_, null, _) -> []; create_ec2_param_list_1(Name, [H|T], C) -> [{Name ++ "." ++ integer_to_list(C), H} | create_ec2_param_list_1(Name, T, C + 1)]; create_ec2_param_list_1(_, [], _) -> []. create_ec2_param_list_2(_, _, null, _) -> []; create_ec2_param_list_2(NamePrefix, NameSuffix, [null|T], C) -> create_ec2_param_list_2(NamePrefix, NameSuffix, T, C + 1); create_ec2_param_list_2(NamePrefix, NameSuffix, [H|T], C) -> [{NamePrefix ++ "." ++ integer_to_list(C) ++ "." ++ NameSuffix, H} | create_ec2_param_list_2(NamePrefix, NameSuffix, T, C + 1)]; create_ec2_param_list_2(_, _, [], _) -> []. Strip 3 tuple to 2 . tuple_3to2({ok, X, _}) -> {ok, X}; tuple_3to2(T) -> T.
7208c1ca22e0d35ef4da22a23868b497a2488e577a7775017d4a4b0e25859df2
lambdaisland/uri
poke.clj
(ns poke (:require [lambdaisland.uri :as uri] [lambdaisland.uri.normalize :as norm])) (:fragment (norm/normalize (uri/map->URI {:fragment "'#'schön"}))) "'%23'sch%C3%B6n" (norm/normalize-fragment "schön") = > " " (uri/map->query-string {:foo "bar"});; => "foo=bar" (uri/map->query-string {:foo/baz "bar"});; => "foo/baz=bar" (uri/query-string->map "foo=bar");; => {:foo "bar"} (uri/query-string->map "%3Afoo=bar" {:keywordize? false});; => {":foo" "bar"} ;; => #::foo{:baz "bar"} ;; => #:foo{:baz "bar"}
null
https://raw.githubusercontent.com/lambdaisland/uri/672bf7864eebd3656048ab35472cd9ea0d9fe0e1/repl_sessions/poke.clj
clojure
=> "foo=bar" => "foo/baz=bar" => {:foo "bar"} => {":foo" "bar"} => #::foo{:baz "bar"} => #:foo{:baz "bar"}
(ns poke (:require [lambdaisland.uri :as uri] [lambdaisland.uri.normalize :as norm])) (:fragment (norm/normalize (uri/map->URI {:fragment "'#'schön"}))) "'%23'sch%C3%B6n" (norm/normalize-fragment "schön") = > " "
83321f9541accb5fba5a9848c9108b04732f0779d0f1d6b0326c7c1872eac757
AdRoll/rebar3_format
binary_fields.erl
-module(binary_fields). -export([p/0]). -define(FOUR, 4). -define(SIX, 6). -define(seven, 7). -define(eight(X), X). -define(NINE(X), X - 1). -define(TEN, 5*2). p() -> Four = 4, <<1, 2:2, 3:3/integer, 4:Four, 5:begin 5 end, 6:?SIX, 7:?seven, 8:(?eight(8))/binary, 9:(?NINE(10))/binary, 10:(?TEN)>>.
null
https://raw.githubusercontent.com/AdRoll/rebar3_format/42a9d933176360f5c526a10d1f2408624b7033f5/test_app/src/binary_fields.erl
erlang
-module(binary_fields). -export([p/0]). -define(FOUR, 4). -define(SIX, 6). -define(seven, 7). -define(eight(X), X). -define(NINE(X), X - 1). -define(TEN, 5*2). p() -> Four = 4, <<1, 2:2, 3:3/integer, 4:Four, 5:begin 5 end, 6:?SIX, 7:?seven, 8:(?eight(8))/binary, 9:(?NINE(10))/binary, 10:(?TEN)>>.
ed5512e14f7d9480b97faf7528caaff5e76a1778ab93850a0980394971d543ab
chenyukang/eopl
eopl-without-exp.scm
(module eopl-without-exp (lib "eopl.ss" "eopl") ;; remove "exp" from the eopl language level, because we use it as ;; a mutable variable. (provide (all-from-except (lib "eopl.ss" "eopl") exp)) )
null
https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter5/letrec-lang/eopl-without-exp.scm
scheme
remove "exp" from the eopl language level, because we use it as a mutable variable.
(module eopl-without-exp (lib "eopl.ss" "eopl") (provide (all-from-except (lib "eopl.ss" "eopl") exp)) )
3e9462d1ace90427040228f4c8e44714693b9c35629737b02389d84a83f82a37
OCamlPro/SecurOCaml
bytecheck.ml
open Types open Rules open OByteLib open Normalised_instr let parse_type t = match t with |"Empty" -> Empty |"Unit" -> Unit |"Bool" -> Bool |"Int" -> Int |"String" -> String |"Char" -> Char |"Float" -> Float | _ -> let parse_fun env ret = let open Scanf in let envt = ref [] in let ic = Scanning.from_string env in while not (Scanning.end_of_input ic) do bscanf ic "%s@;" (fun t -> envt := parse_type t :: !envt) done (!envt, parse_type ret) let read_funs filename = let open Scanf in let ic = Scanning.open_in filename in let funs = AddrMap.empty while not (Scanning.end_of_input ic) do bscanf ic "%d [%s@] %s@\n" (fun p env ret -> funs := AddrMap.add p (parse_fun env ret) !funs) done Scanning.close_in ic !funs let main () = if Array.length (Sys.argv) < 2 then prerr_endline ("Error: " ^ Sys.argv.(0) ^ ": expected two filenames") else begin let cmo = Cmofile.read Sys.argv.(1) in let (data, symb, prim, code) = Cmofile.reloc cmo in let lencode = Array.length code in let funs = read_funs Sys.argv.(2) and globals = [||] and cfuns = [||] in checkcode globals cfuns funs code end ;; main ()
null
https://raw.githubusercontent.com/OCamlPro/SecurOCaml/1d89e065884a935cd8e38b9670522dda6383f77c/Livrables/WorkPackage5/bytecheck/bytecheck.ml
ocaml
open Types open Rules open OByteLib open Normalised_instr let parse_type t = match t with |"Empty" -> Empty |"Unit" -> Unit |"Bool" -> Bool |"Int" -> Int |"String" -> String |"Char" -> Char |"Float" -> Float | _ -> let parse_fun env ret = let open Scanf in let envt = ref [] in let ic = Scanning.from_string env in while not (Scanning.end_of_input ic) do bscanf ic "%s@;" (fun t -> envt := parse_type t :: !envt) done (!envt, parse_type ret) let read_funs filename = let open Scanf in let ic = Scanning.open_in filename in let funs = AddrMap.empty while not (Scanning.end_of_input ic) do bscanf ic "%d [%s@] %s@\n" (fun p env ret -> funs := AddrMap.add p (parse_fun env ret) !funs) done Scanning.close_in ic !funs let main () = if Array.length (Sys.argv) < 2 then prerr_endline ("Error: " ^ Sys.argv.(0) ^ ": expected two filenames") else begin let cmo = Cmofile.read Sys.argv.(1) in let (data, symb, prim, code) = Cmofile.reloc cmo in let lencode = Array.length code in let funs = read_funs Sys.argv.(2) and globals = [||] and cfuns = [||] in checkcode globals cfuns funs code end ;; main ()
1cb29af93f40fd99d17789588978810187547596e6f22a81e36f20329ba08071
coord-e/mlml
format_string.ml
type kind = | Const of string | Int | Char | String let string_of_kind = function | Const s -> s | Int -> "(d)" | Char -> "(c)" | String -> "(s)" ;; let string_of_format_string l = List.map string_of_kind l |> String.concat ""
null
https://raw.githubusercontent.com/coord-e/mlml/ec34b1fe8766901fab6842b790267f32b77a2861/mlml/tree/format_string.ml
ocaml
type kind = | Const of string | Int | Char | String let string_of_kind = function | Const s -> s | Int -> "(d)" | Char -> "(c)" | String -> "(s)" ;; let string_of_format_string l = List.map string_of_kind l |> String.concat ""
d22176bcf72a6451736ab09a4074275430a96efa09398ab7d8b24fb1e43c65aa
mariari/Misc-ML-Scripts
interpreter-i.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE FlexibleContexts # import Control.Monad.Trans (lift) import Control.Monad.Trans.State.Strict (StateT, evalStateT) import Control.Monad.State.Class (MonadState, get, modify) import Data.Functor.Identity (Identity) import Data.Map.Strict hiding (foldr) import Data.Monoid type Id = String data Binop = Plus | Minus | Times | Div deriving Show data Stm = Compound Stm Stm | Assign Id Exp | Print [Exp] deriving Show data Exp = IdExp Id | NumExp Int | OpExp Exp Binop Exp | EseqExp Stm Exp deriving Show prog :: Stm prog = Compound (Assign "a" (OpExp (NumExp 5) Plus (NumExp 3))) (Compound (Assign "b" (EseqExp (Print [IdExp "a", OpExp (IdExp "a") Minus (NumExp 1)]) (OpExp (NumExp 10) Times (IdExp "a")))) (Print [IdExp "b"])) {---------------------------------------------------------} -- Gives the maximum number of arguments to a Print statement maxArgs :: Stm -> Int maxArgs (Compound s1 s2) = max (maxArgs s1) (maxArgs s2) maxArgs (Assign _ exp) = maxArgsExp exp maxArgs (Print xs) = maximum (length xs : fmap maxArgsExp xs) maxArgsExp :: Exp -> Int maxArgsExp (EseqExp stm _) = maxArgs stm maxArgsExp other = 0 binopToFn :: Integral a => Binop -> a -> a -> a binopToFn Minus = (-) binopToFn Plus = (+) binopToFn Times = (*) binopToFn Div = div class Monad m => MonadPrint m where puts :: String -> m () put :: Show a => a -> m () put = puts . show instance MonadPrint IO where puts = putStrLn instance MonadPrint m => MonadPrint (StateT s m) where puts = lift . puts instance MonadPrint Identity where puts _ = return () {---------------------------------------------------------} interpret :: Stm -> IO () interpret stm = evalStateT (interpStm stm) empty type Env = Map Id Int type MonadEval m = (MonadState Env m, MonadPrint m) interpStm :: MonadEval m => Stm -> m () interpStm (Compound s1 s2) = interpStm s1 >> interpStm s2 interpStm (Assign id exp) = interpExp exp >>= modify . insert id interpStm (Print xs) = traverse interpExp xs >>= putInts interpExp :: MonadEval m => Exp -> m Int interpExp (IdExp var) = (! var) <$> get interpExp (NumExp x) = return x interpExp (EseqExp s exp) = interpStm s >> interpExp exp interpExp (OpExp e1 b e2) = do eval1 <- interpExp e1 eval2 <- interpExp e2 return (binopToFn b eval1 eval2) putInts :: (Show a, MonadPrint m) => [a] -> m () putInts = puts . unwords . fmap show
null
https://raw.githubusercontent.com/mariari/Misc-ML-Scripts/d18aecf539c2d2ccf7ba9eb796f90e3ca809f5bf/Haskell/Moder-compilers/chapter-2/interpreter-i.hs
haskell
# LANGUAGE ConstraintKinds # ------------------------------------------------------- Gives the maximum number of arguments to a Print statement -------------------------------------------------------
# LANGUAGE FlexibleContexts # import Control.Monad.Trans (lift) import Control.Monad.Trans.State.Strict (StateT, evalStateT) import Control.Monad.State.Class (MonadState, get, modify) import Data.Functor.Identity (Identity) import Data.Map.Strict hiding (foldr) import Data.Monoid type Id = String data Binop = Plus | Minus | Times | Div deriving Show data Stm = Compound Stm Stm | Assign Id Exp | Print [Exp] deriving Show data Exp = IdExp Id | NumExp Int | OpExp Exp Binop Exp | EseqExp Stm Exp deriving Show prog :: Stm prog = Compound (Assign "a" (OpExp (NumExp 5) Plus (NumExp 3))) (Compound (Assign "b" (EseqExp (Print [IdExp "a", OpExp (IdExp "a") Minus (NumExp 1)]) (OpExp (NumExp 10) Times (IdExp "a")))) (Print [IdExp "b"])) maxArgs :: Stm -> Int maxArgs (Compound s1 s2) = max (maxArgs s1) (maxArgs s2) maxArgs (Assign _ exp) = maxArgsExp exp maxArgs (Print xs) = maximum (length xs : fmap maxArgsExp xs) maxArgsExp :: Exp -> Int maxArgsExp (EseqExp stm _) = maxArgs stm maxArgsExp other = 0 binopToFn :: Integral a => Binop -> a -> a -> a binopToFn Minus = (-) binopToFn Plus = (+) binopToFn Times = (*) binopToFn Div = div class Monad m => MonadPrint m where puts :: String -> m () put :: Show a => a -> m () put = puts . show instance MonadPrint IO where puts = putStrLn instance MonadPrint m => MonadPrint (StateT s m) where puts = lift . puts instance MonadPrint Identity where puts _ = return () interpret :: Stm -> IO () interpret stm = evalStateT (interpStm stm) empty type Env = Map Id Int type MonadEval m = (MonadState Env m, MonadPrint m) interpStm :: MonadEval m => Stm -> m () interpStm (Compound s1 s2) = interpStm s1 >> interpStm s2 interpStm (Assign id exp) = interpExp exp >>= modify . insert id interpStm (Print xs) = traverse interpExp xs >>= putInts interpExp :: MonadEval m => Exp -> m Int interpExp (IdExp var) = (! var) <$> get interpExp (NumExp x) = return x interpExp (EseqExp s exp) = interpStm s >> interpExp exp interpExp (OpExp e1 b e2) = do eval1 <- interpExp e1 eval2 <- interpExp e2 return (binopToFn b eval1 eval2) putInts :: (Show a, MonadPrint m) => [a] -> m () putInts = puts . unwords . fmap show
f748be4656ef90e288ee9bddef907d9702718820bc1b39164326c6f21fa3eb9b
google/clang-lens
Token.hs
Copyright 2014 Google Inc. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Clang.Token ( TokenSet() , Token() , tokenize , tokenSetTokens , indexTokenSet , tokenSpelling ) where import Clang.Internal.FFI import Clang.Internal.Types
null
https://raw.githubusercontent.com/google/clang-lens/09caa8fb234024af18706060085ef0fc1e8b6f5f/src/Clang/Token.hs
haskell
Copyright 2014 Google Inc. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Clang.Token ( TokenSet() , Token() , tokenize , tokenSetTokens , indexTokenSet , tokenSpelling ) where import Clang.Internal.FFI import Clang.Internal.Types
7117c699f65700887fbc4026e8362596302cc47c24d9e6071f27ecaa730070da
simnalamburt/snucse.pl
main.ml
(* * SNU 4190.310 Programming Languages * * SM5 *) open Translate open Pp open Sm5 open K let main () = let pp = ref false in let k = ref false in let src = ref "" in let _ = Arg.parse [("-pp", Arg.Set pp, "display parse tree"); ("-k", Arg.Set k, "run using K interpreter"); ("-gc", Arg.Set Sm5.gc_mode, "run with garbage collection")] (fun x -> src := x) ("Usage: " ^ (Filename.basename Sys.argv.(0)) ^ " [-ptree] [file]") in let lexbuf = Lexing.from_channel (if !src = "" then stdin else open_in !src) in let pgm = Parser.program Lexer.start lexbuf in if !pp then KParseTreePrinter.print pgm else if !k then ignore (K.run pgm) else ignore (Sm5.run(Translator.trans pgm)) let _ = main ()
null
https://raw.githubusercontent.com/simnalamburt/snucse.pl/a130f826c6f27224c88b0dd2e1588f35bccc9ebb/hw5/main.ml
ocaml
* SNU 4190.310 Programming Languages * * SM5
open Translate open Pp open Sm5 open K let main () = let pp = ref false in let k = ref false in let src = ref "" in let _ = Arg.parse [("-pp", Arg.Set pp, "display parse tree"); ("-k", Arg.Set k, "run using K interpreter"); ("-gc", Arg.Set Sm5.gc_mode, "run with garbage collection")] (fun x -> src := x) ("Usage: " ^ (Filename.basename Sys.argv.(0)) ^ " [-ptree] [file]") in let lexbuf = Lexing.from_channel (if !src = "" then stdin else open_in !src) in let pgm = Parser.program Lexer.start lexbuf in if !pp then KParseTreePrinter.print pgm else if !k then ignore (K.run pgm) else ignore (Sm5.run(Translator.trans pgm)) let _ = main ()
4f64e8e83295afa72fcfa27a5359869eb8fd54fd221b0abba5a1b88f18aedeb3
pat227/ocaml-pgsql-model
utilities.mli
module Bignum_extended = Bignum_extended.Bignum_extended module Date_extended = Date_extended.Date_extended module Date_time_extended = Date_time_extended.Date_time_extended module Postgresql = Postgresql module Utilities : sig val print_n_flush : string -> unit val print_n_flush_alist : sep:string -> string list -> unit val getcon : ?host:string -> dbname:string -> password:string -> user:string -> unit -> Postgresql.connection val getcon_defaults : unit -> Postgresql.connection val closecon : Postgresql.connection -> unit val serialize_optional_field : field:string option -> conn:Postgresql.connection -> string val serialize_optional_field_with_default : field:string option -> conn:Postgresql.connection -> default:string -> string val serialize_boolean_field : field:bool -> string val serialize_optional_bool_field : field:bool option -> string val serialize_optional_float_field_as_int : field:float option -> string val serialize_float_field_as_int : field:float -> string val serialize_optional_date_field : field:Date_extended.t option -> string val serialize_optional_date_time_field : field:Date_time_extended.t option -> string val parse_boolean_field_exn : field:string -> bool (* val parse_optional_boolean_field_exn : field:string option -> bool option*) val parse_int64_field_exn : string - > Core . Int64.t val parse_int_field_exn : string option - > int val parse_int_field_option : string option - > int option val parse_string_field : string - > string val parse_boolean_field : string - > parse_int_field : string - > int val parse_int64_field_exn : string -> Core.Int64.t val parse_int_field_exn : string option -> int val parse_int_field_option : string option -> int option val parse_string_field : string -> string val parse_boolean_field : string -> bool val parse_int_field : string -> int*) val extract_field_as_string_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> string val extract_optional_field : fieldname:string -> qresult:Postgresql.result -> tuple:int -> string option val parse_int64_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int64.t val parse_optional_int64_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int64.t option val parse_int32_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int32.t val parse_optional_int32_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int32.t option val parse_bignum_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Bignum_extended.t val parse_optional_bignum_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Bignum_extended.t option (*---bool---*) val parse_bool_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> bool val parse_optional_bool_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> bool option (*---float/double---*) val parse_float_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Float.t val parse_optional_float_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Float.t option (*---date/time---*) val parse_date_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Date.t val parse_optional_date_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Date.t option val parse_datetime_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Time.t val parse_optional_datetime_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Time.t option end
null
https://raw.githubusercontent.com/pat227/ocaml-pgsql-model/e0b33b19095e92029ac10842ebdf44a5435271ae/src/lib/utilities.mli
ocaml
val parse_optional_boolean_field_exn : field:string option -> bool option ---bool--- ---float/double--- ---date/time---
module Bignum_extended = Bignum_extended.Bignum_extended module Date_extended = Date_extended.Date_extended module Date_time_extended = Date_time_extended.Date_time_extended module Postgresql = Postgresql module Utilities : sig val print_n_flush : string -> unit val print_n_flush_alist : sep:string -> string list -> unit val getcon : ?host:string -> dbname:string -> password:string -> user:string -> unit -> Postgresql.connection val getcon_defaults : unit -> Postgresql.connection val closecon : Postgresql.connection -> unit val serialize_optional_field : field:string option -> conn:Postgresql.connection -> string val serialize_optional_field_with_default : field:string option -> conn:Postgresql.connection -> default:string -> string val serialize_boolean_field : field:bool -> string val serialize_optional_bool_field : field:bool option -> string val serialize_optional_float_field_as_int : field:float option -> string val serialize_float_field_as_int : field:float -> string val serialize_optional_date_field : field:Date_extended.t option -> string val serialize_optional_date_time_field : field:Date_time_extended.t option -> string val parse_boolean_field_exn : field:string -> bool val parse_int64_field_exn : string - > Core . Int64.t val parse_int_field_exn : string option - > int val parse_int_field_option : string option - > int option val parse_string_field : string - > string val parse_boolean_field : string - > parse_int_field : string - > int val parse_int64_field_exn : string -> Core.Int64.t val parse_int_field_exn : string option -> int val parse_int_field_option : string option -> int option val parse_string_field : string -> string val parse_boolean_field : string -> bool val parse_int_field : string -> int*) val extract_field_as_string_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> string val extract_optional_field : fieldname:string -> qresult:Postgresql.result -> tuple:int -> string option val parse_int64_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int64.t val parse_optional_int64_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int64.t option val parse_int32_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int32.t val parse_optional_int32_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Int32.t option val parse_bignum_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Bignum_extended.t val parse_optional_bignum_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Bignum_extended.t option val parse_bool_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> bool val parse_optional_bool_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> bool option val parse_float_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Float.t val parse_optional_float_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Float.t option val parse_date_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Date.t val parse_optional_date_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Date.t option val parse_datetime_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Time.t val parse_optional_datetime_field_exn : fieldname:string -> qresult:Postgresql.result -> tuple:int -> Core.Time.t option end
82da19baef41f53e01c9d518856eca54b0bf4c6fdbbc958135ef0374bb64415d
ctbarbour/swim
swim_pushpull_sup.erl
-module(swim_pushpull_sup). -behavior(supervisor). -export([start_link/2]). -export([init/1]). start_link(IpAddr, Port) -> supervisor:start_link({local, ?MODULE}, ?MODULE, [IpAddr, Port]). init([IpAddr, Port]) -> ListenerSpec = #{ id => pushpull, start => {swim_pushpull, start_link, [IpAddr, Port, #{}]}}, Flags = #{strategy => one_for_one, intensity => 10, period => 10}, {ok, {Flags, [ListenerSpec]}}.
null
https://raw.githubusercontent.com/ctbarbour/swim/fca6047ad313069667485369c452c31d0679dda0/src/swim_pushpull_sup.erl
erlang
-module(swim_pushpull_sup). -behavior(supervisor). -export([start_link/2]). -export([init/1]). start_link(IpAddr, Port) -> supervisor:start_link({local, ?MODULE}, ?MODULE, [IpAddr, Port]). init([IpAddr, Port]) -> ListenerSpec = #{ id => pushpull, start => {swim_pushpull, start_link, [IpAddr, Port, #{}]}}, Flags = #{strategy => one_for_one, intensity => 10, period => 10}, {ok, {Flags, [ListenerSpec]}}.
beb569740ca8fdcbf471a92c2271d3685c215637f8825278ffa6a5f10d7e8a20
roosta/tincture
slide.cljs
(ns tincture.slide (:require [tincture.transitions :refer [Transition TransitionGroup CSSTransition]] [clojure.spec.alpha :as s] [tincture.core :refer [easing-presets create-transition]] [tincture.spec :refer [check-spec]] [herb.core :refer [defgroup <class]] [reagent.debug :refer [log]] [clojure.string :as str] [reagent.core :as r])) (defn- base-style [duration easing] {:left 0 :top 0 :position "absolute" :transition (create-transition {:property [:transform :opacity] :duration duration :easing easing})}) (defn- enter-style [direction opacity] (cond-> {:transform (direction {:left "translate(100%, 0)" :right "translate(-100%, 0)" :up "translate(0, 100%)" :down "translate(0, -100%)"})} opacity (assoc :opacity 0))) (defn- enter-active-style [duration easing opacity] (with-meta (cond-> {:transform "translate(0, 0)"} opacity (assoc :opacity 1)) {:extend [base-style duration easing]})) (defn- exit-style [opacity] (cond-> {:transform "translate(0, 0)"} opacity (assoc :opacity 1))) (defn- exit-active-style [duration easing direction opacity] (with-meta (cond-> {:transform (direction {:left "translate(-100%, 0)" :right "translate(100%, 0)" :up "translate(0, -100%)" :down "translate(0, 100%)"})} opacity (assoc :opacity 0)) {:extend [base-style duration easing]})) (defn exit-done-style [] {:display "none"}) (defn- slide-child [{:keys [duration style timeout on-exit on-exited on-enter on-entered unmount-on-exit mount-on-enter easing appear direction children in child-container-class transition-class opacity]}] [CSSTransition {:in in :style style :timeout timeout :class transition-class :classNames {:enter (<class enter-style direction opacity) :enter-active (<class enter-active-style duration easing opacity) :exit (<class exit-style opacity) :exit-active (<class exit-active-style duration easing direction opacity) :exit-done (<class exit-done-style)} :unmountOnExit unmount-on-exit :mountOnEnter mount-on-enter :appear appear :onExit on-exit :onEnter on-enter :onExited on-exited :onEntered on-entered} (fn [state] (r/as-element (into [:div {:class child-container-class}] children)))]) (s/def ::direction #{:up :down :left :right}) (s/def ::duration pos-int?) (s/def ::timeout pos-int?) (s/def ::unmount-on-exit boolean?) (s/def ::mount-on-enter boolean?) (s/def ::class (s/nilable (s/or :str string? :vector vector?))) (s/def ::easing :tincture.core/valid-easings) (s/def ::appear boolean?) (s/def ::on-entered fn?) (s/def ::on-enter fn?) (s/def ::on-exit fn?) (s/def ::on-exited fn?) (s/def ::enter boolean?) (s/def ::exit boolean?) (s/def ::transition string?) (s/def ::child-container string?) (s/def ::classes (s/keys :opt [::transition ::child-container])) (s/def ::id (s/nilable string?)) (s/def ::opacity boolean?) (defn Slide "Slide components in and out based on mount status using [react-transition-group](-transition-group) **Properties** Slide takes a map of properties, many properties passed to the slide component are passed through to TransitionGroup (container) or Transition (child). * `:direction`. Pred: `#{:up :down :left :right}`. Default: `:left`. Which direction the component should be animated. * `:duration`. Pred: `pos-int?`. Default `500`. The duration used for the slide animation in milliseconds. * `:timeout`. Pred `pos-int?`. Default `500`. The duration of the transition, in milliseconds. This prop is passed to the `Transition` component. * `:unmount-on-exit`. Pred `boolean?`. Default `false`. By default the child component stays mounted after it reaches the `exited` state. Set this if you'd prefer to unmount the component after it finishes exiting. This prop is passed to the `Transition` component. * `:mount-on-enter`. Pred `boolean?`. Default `false`. By default the child component is mounted immediately along with the parent `Transition` component. If you want to `lazy mount` the component on the first `(= :in true)` you can set mount-on-enter. After the first enter transition the component will stay mounted, even on `exited` , unless you also specify unmount-on-exit. This prop is passed to the Transition component. * `:class`. Pred `string?`. Default `nil`. String classname to be applied to the outer `TransitionGroup` component. * `:easing`. Pred `#{:ease-in-quad :ease-in-cubic :ease-in-quart :ease-in-quint :ease-in-expo :ease-in-circ :ease-out-quad :ease-out-cubic :ease-out-quart :ease-out-quint :ease-out-expo :ease-out-circ :ease-in-out-quad :ease-in-out-cubic :ease-in-out-quart :ease-in-out-quint :ease-in-out-expo :ease-in-out-circ}`. Default `:ease-in-out-cubic`. Which easing function to use for the CSS transitions. * `:appear`. Pred `boolean?`. Default `false`. Normally a component is not transitioned if it is shown when the `Transition` component mounts. If you want to transition on the first mount set appear to `true`, and the component will transition in as soon as the `Transition` mounts. * `:enter`. Pred `boolean`. Default `true`. Enable or disable enter transitions. * `:exit`. Pred `boolean`. Default `true`. Enable or disable enter transitions. * `:on-exit`. Pred `fn?`. Default `noop`. Callback fired before the `exiting` status is applied. * `:on-exited`. Pred `fn?`. Default `noop`. Callback fired after the `exited` status is applied. * `:on-enter`. Pred `fn?` * `:on-entered`. Pred `fn?`. Default `noop`. Callback fired after the `entered` status is applied. This prop is passed to the inner `Transition` component. * `:classes`. Pred: keys `#{:transition :child-container}`, vals `string?`. Default `nil`. A map of override classes, one for the `Transition` component, and one for the `child-container`, which is the innermost child. * `:opacity`. Pred: `boolean`. Default `false` If you want opacity added to the slide animation **Important note** It is important that height is set with CSS on the `TransitionGroup`, by passing a string with the `:class` key value pair. It is deliberately not set by this component since the height can be one of any number of things like 100%, 100vh or a hardcoded size like 200px. This component will not work unless a height it set. It is also important that you set a `:key` on the children of this component since that's whats used to differentiate between children when animating. **Example usage** ```clojure (let [images [\"url1\" \"url2\" \"url3\"] image (r/atom (first images))] (fn [] [Slide {:direction :left :classes {:child-container \"my-child-class\"} :class \"my-main-class-with-included-height\"} [:div {:on-click #(swap! image (rand-nth images)) :key @image} [:img {:src @image}]]])) ``` " [{:keys [direction duration timeout unmount-on-exit mount-on-enter class easing appear enter exit on-exit on-exited on-enter on-entered classes id opacity] :or {direction :left duration 500 timeout 500 mount-on-enter false unmount-on-exit false easing :ease-in-out-cubic appear false enter true exit true on-enter #() on-exit #() on-exited #() on-entered #() classes {} opacity false}}] (let [direction (check-spec direction ::direction) duration (check-spec duration ::duration) timeout (check-spec timeout ::timeout) mount-on-enter (check-spec mount-on-enter ::mount-on-enter) class (check-spec class ::class) id (check-spec id ::id) easing (check-spec easing ::easing) appear (check-spec appear ::appear) enter (check-spec enter ::enter) exit (check-spec exit ::exit) on-exit (check-spec on-exit ::on-exit) on-exited (check-spec on-exited ::on-exited) on-enter (check-spec on-enter ::on-enter) on-entered (check-spec on-entered ::on-entered) {transition-class :transition child-container-class :child-container} (check-spec classes ::classes) opacity (check-spec opacity ::opacity) children (r/children (r/current-component)) k (or (-> children first meta :key) (-> children first second :key))] [TransitionGroup {:class class :id id :enter enter :exit exit :style {:position "relative" :overflow "hidden"} ;; Since the direction should change for exiting children ;; as well, we need to reactivly update them :childFactory (fn [child] (js/React.cloneElement child #js {:direction direction}))} ;; to access the passed props of transition group we need to create a react ;; component from the carousel-child transition. (let [child (r/reactify-component slide-child)] (r/create-element child #js {:key k :duration duration :child-container-class child-container-class :transition-class transition-class :timeout timeout :on-exit on-exit :on-exited on-exited :on-enter on-enter :on-entered on-entered :unmount-on-exit unmount-on-exit :mount-on-enter mount-on-enter :easing easing :appear appear :direction direction :children children :opacity opacity}))])) (def ^{:deprecated "0.3.0"} slide Slide)
null
https://raw.githubusercontent.com/roosta/tincture/587e68248dae09616942dc23bbd97cb9a1a4caa2/src/tincture/slide.cljs
clojure
Since the direction should change for exiting children as well, we need to reactivly update them to access the passed props of transition group we need to create a react component from the carousel-child transition.
(ns tincture.slide (:require [tincture.transitions :refer [Transition TransitionGroup CSSTransition]] [clojure.spec.alpha :as s] [tincture.core :refer [easing-presets create-transition]] [tincture.spec :refer [check-spec]] [herb.core :refer [defgroup <class]] [reagent.debug :refer [log]] [clojure.string :as str] [reagent.core :as r])) (defn- base-style [duration easing] {:left 0 :top 0 :position "absolute" :transition (create-transition {:property [:transform :opacity] :duration duration :easing easing})}) (defn- enter-style [direction opacity] (cond-> {:transform (direction {:left "translate(100%, 0)" :right "translate(-100%, 0)" :up "translate(0, 100%)" :down "translate(0, -100%)"})} opacity (assoc :opacity 0))) (defn- enter-active-style [duration easing opacity] (with-meta (cond-> {:transform "translate(0, 0)"} opacity (assoc :opacity 1)) {:extend [base-style duration easing]})) (defn- exit-style [opacity] (cond-> {:transform "translate(0, 0)"} opacity (assoc :opacity 1))) (defn- exit-active-style [duration easing direction opacity] (with-meta (cond-> {:transform (direction {:left "translate(-100%, 0)" :right "translate(100%, 0)" :up "translate(0, -100%)" :down "translate(0, 100%)"})} opacity (assoc :opacity 0)) {:extend [base-style duration easing]})) (defn exit-done-style [] {:display "none"}) (defn- slide-child [{:keys [duration style timeout on-exit on-exited on-enter on-entered unmount-on-exit mount-on-enter easing appear direction children in child-container-class transition-class opacity]}] [CSSTransition {:in in :style style :timeout timeout :class transition-class :classNames {:enter (<class enter-style direction opacity) :enter-active (<class enter-active-style duration easing opacity) :exit (<class exit-style opacity) :exit-active (<class exit-active-style duration easing direction opacity) :exit-done (<class exit-done-style)} :unmountOnExit unmount-on-exit :mountOnEnter mount-on-enter :appear appear :onExit on-exit :onEnter on-enter :onExited on-exited :onEntered on-entered} (fn [state] (r/as-element (into [:div {:class child-container-class}] children)))]) (s/def ::direction #{:up :down :left :right}) (s/def ::duration pos-int?) (s/def ::timeout pos-int?) (s/def ::unmount-on-exit boolean?) (s/def ::mount-on-enter boolean?) (s/def ::class (s/nilable (s/or :str string? :vector vector?))) (s/def ::easing :tincture.core/valid-easings) (s/def ::appear boolean?) (s/def ::on-entered fn?) (s/def ::on-enter fn?) (s/def ::on-exit fn?) (s/def ::on-exited fn?) (s/def ::enter boolean?) (s/def ::exit boolean?) (s/def ::transition string?) (s/def ::child-container string?) (s/def ::classes (s/keys :opt [::transition ::child-container])) (s/def ::id (s/nilable string?)) (s/def ::opacity boolean?) (defn Slide "Slide components in and out based on mount status using [react-transition-group](-transition-group) **Properties** Slide takes a map of properties, many properties passed to the slide component are passed through to TransitionGroup (container) or Transition (child). * `:direction`. Pred: `#{:up :down :left :right}`. Default: `:left`. Which direction the component should be animated. * `:duration`. Pred: `pos-int?`. Default `500`. The duration used for the slide animation in milliseconds. * `:timeout`. Pred `pos-int?`. Default `500`. The duration of the transition, in milliseconds. This prop is passed to the `Transition` component. * `:unmount-on-exit`. Pred `boolean?`. Default `false`. By default the child component stays mounted after it reaches the `exited` state. Set this if you'd prefer to unmount the component after it finishes exiting. This prop is passed to the `Transition` component. * `:mount-on-enter`. Pred `boolean?`. Default `false`. By default the child component is mounted immediately along with the parent `Transition` component. If you want to `lazy mount` the component on the first `(= :in true)` you can set mount-on-enter. After the first enter transition the component will stay mounted, even on `exited` , unless you also specify unmount-on-exit. This prop is passed to the Transition component. * `:class`. Pred `string?`. Default `nil`. String classname to be applied to the outer `TransitionGroup` component. * `:easing`. Pred `#{:ease-in-quad :ease-in-cubic :ease-in-quart :ease-in-quint :ease-in-expo :ease-in-circ :ease-out-quad :ease-out-cubic :ease-out-quart :ease-out-quint :ease-out-expo :ease-out-circ :ease-in-out-quad :ease-in-out-cubic :ease-in-out-quart :ease-in-out-quint :ease-in-out-expo :ease-in-out-circ}`. Default `:ease-in-out-cubic`. Which easing function to use for the CSS transitions. * `:appear`. Pred `boolean?`. Default `false`. Normally a component is not transitioned if it is shown when the `Transition` component mounts. If you want to transition on the first mount set appear to `true`, and the component will transition in as soon as the `Transition` mounts. * `:enter`. Pred `boolean`. Default `true`. Enable or disable enter transitions. * `:exit`. Pred `boolean`. Default `true`. Enable or disable enter transitions. * `:on-exit`. Pred `fn?`. Default `noop`. Callback fired before the `exiting` status is applied. * `:on-exited`. Pred `fn?`. Default `noop`. Callback fired after the `exited` status is applied. * `:on-enter`. Pred `fn?` * `:on-entered`. Pred `fn?`. Default `noop`. Callback fired after the `entered` status is applied. This prop is passed to the inner `Transition` component. * `:classes`. Pred: keys `#{:transition :child-container}`, vals `string?`. Default `nil`. A map of override classes, one for the `Transition` component, and one for the `child-container`, which is the innermost child. * `:opacity`. Pred: `boolean`. Default `false` If you want opacity added to the slide animation **Important note** It is important that height is set with CSS on the `TransitionGroup`, by passing a string with the `:class` key value pair. It is deliberately not set by this component since the height can be one of any number of things like 100%, 100vh or a hardcoded size like 200px. This component will not work unless a height it set. It is also important that you set a `:key` on the children of this component since that's whats used to differentiate between children when animating. **Example usage** ```clojure (let [images [\"url1\" \"url2\" \"url3\"] image (r/atom (first images))] (fn [] [Slide {:direction :left :classes {:child-container \"my-child-class\"} :class \"my-main-class-with-included-height\"} [:div {:on-click #(swap! image (rand-nth images)) :key @image} [:img {:src @image}]]])) ``` " [{:keys [direction duration timeout unmount-on-exit mount-on-enter class easing appear enter exit on-exit on-exited on-enter on-entered classes id opacity] :or {direction :left duration 500 timeout 500 mount-on-enter false unmount-on-exit false easing :ease-in-out-cubic appear false enter true exit true on-enter #() on-exit #() on-exited #() on-entered #() classes {} opacity false}}] (let [direction (check-spec direction ::direction) duration (check-spec duration ::duration) timeout (check-spec timeout ::timeout) mount-on-enter (check-spec mount-on-enter ::mount-on-enter) class (check-spec class ::class) id (check-spec id ::id) easing (check-spec easing ::easing) appear (check-spec appear ::appear) enter (check-spec enter ::enter) exit (check-spec exit ::exit) on-exit (check-spec on-exit ::on-exit) on-exited (check-spec on-exited ::on-exited) on-enter (check-spec on-enter ::on-enter) on-entered (check-spec on-entered ::on-entered) {transition-class :transition child-container-class :child-container} (check-spec classes ::classes) opacity (check-spec opacity ::opacity) children (r/children (r/current-component)) k (or (-> children first meta :key) (-> children first second :key))] [TransitionGroup {:class class :id id :enter enter :exit exit :style {:position "relative" :overflow "hidden"} :childFactory (fn [child] (js/React.cloneElement child #js {:direction direction}))} (let [child (r/reactify-component slide-child)] (r/create-element child #js {:key k :duration duration :child-container-class child-container-class :transition-class transition-class :timeout timeout :on-exit on-exit :on-exited on-exited :on-enter on-enter :on-entered on-entered :unmount-on-exit unmount-on-exit :mount-on-enter mount-on-enter :easing easing :appear appear :direction direction :children children :opacity opacity}))])) (def ^{:deprecated "0.3.0"} slide Slide)
d8da511dc8600f8108ec6e14c1a82831dd0842bf8736b661bfd5df416e16b7c0
savonet/ocaml-posix
posix_types_constants.ml
let number_types = [ "blkcnt_t"; "blksize_t"; "clock_t"; "clockid_t"; "dev_t"; "fsblkcnt_t"; "fsfilcnt_t"; "gid_t"; "id_t"; "ino_t"; "key_t"; "mode_t"; "nlink_t"; "off_t"; "pid_t"; "size_t"; "ssize_t"; "suseconds_t"; "time_t"; "uid_t"; ] let abstract_types = [ "useconds_t"; "pthread_attr_t"; "pthread_cond_t"; "pthread_condattr_t"; "pthread_key_t"; "pthread_mutex_t"; "pthread_mutexattr_t"; "pthread_once_t"; "pthread_rwlock_t"; "pthread_rwlockattr_t"; "pthread_t"; ] module Def (S : Cstubs.Types.TYPE) = struct let blkcnt_t_size = S.constant "BLKCNT_T_SIZE" S.int let blksize_t_size = S.constant "BLKSIZE_T_SIZE" S.int let clock_t_size = S.constant "CLOCK_T_SIZE" S.int let clockid_t_size = S.constant "CLOCKID_T_SIZE" S.int let is_clock_t_float = S.constant "IS_CLOCK_T_FLOAT" S.bool let dev_t_size = S.constant "DEV_T_SIZE" S.int let fsblkcnt_t_size = S.constant "FSBLKCNT_T_SIZE" S.int let fsfilcnt_t_size = S.constant "FSFILCNT_T_SIZE" S.int let gid_t_size = S.constant "GID_T_SIZE" S.int let id_t_size = S.constant "ID_T_SIZE" S.int let ino_t_size = S.constant "INO_T_SIZE" S.int let key_t_size = S.constant "KEY_T_SIZE" S.int let is_key_t_float = S.constant "IS_KEY_T_FLOAT" S.bool let mode_t_size = S.constant "MODE_T_SIZE" S.int let nlink_t_size = S.constant "NLINK_T_SIZE" S.int let off_t_size = S.constant "OFF_T_SIZE" S.int let pid_t_size = S.constant "PID_T_SIZE" S.int let size_t_size = S.constant "SIZE_T_SIZE" S.int let ssize_t_size = S.constant "SSIZE_T_SIZE" S.int let suseconds_t_size = S.constant "SUSECONDS_T_SIZE" S.int let time_t_size = S.constant "TIME_T_SIZE" S.int let is_time_t_float = S.constant "IS_TIME_T_FLOAT" S.bool let uid_t_size = S.constant "UID_T_SIZE" S.int let useconds_t_size = S.constant "USECONDS_T_SIZE" S.int let pthread_attr_t_alignment = S.constant "PTHREAD_ATTR_T_ALIGNMENT" S.int let pthread_cond_t_alignment = S.constant "PTHREAD_COND_T_ALIGNMENT" S.int let pthread_condattr_t_alignment = S.constant "PTHREAD_CONDATTR_T_ALIGNMENT" S.int let pthread_key_t_alignment = S.constant "PTHREAD_KEY_T_ALIGNMENT" S.int let pthread_mutex_t_alignment = S.constant "PTHREAD_MUTEX_T_ALIGNMENT" S.int let pthread_mutexattr_t_alignment = S.constant "PTHREAD_MUTEXATTR_T_ALIGNMENT" S.int let pthread_once_t_alignment = S.constant "PTHREAD_ONCE_T_ALIGNMENT" S.int let pthread_rwlock_t_alignment = S.constant "PTHREAD_RWLOCK_T_ALIGNMENT" S.int let pthread_rwlockattr_t_alignment = S.constant "PTHREAD_RWLOCKATTR_T_ALIGNMENT" S.int let pthread_t_alignment = S.constant "PTHREAD_T_ALIGNMENT" S.int let pthread_attr_t_size = S.constant "PTHREAD_ATTR_T_SIZE" S.int let pthread_cond_t_size = S.constant "PTHREAD_COND_T_SIZE" S.int let pthread_condattr_t_size = S.constant "PTHREAD_CONDATTR_T_SIZE" S.int let pthread_key_t_size = S.constant "PTHREAD_KEY_T_SIZE" S.int let pthread_mutex_t_size = S.constant "PTHREAD_MUTEX_T_SIZE" S.int let pthread_mutexattr_t_size = S.constant "PTHREAD_MUTEXATTR_T_SIZE" S.int let pthread_once_t_size = S.constant "PTHREAD_ONCE_T_SIZE" S.int let pthread_rwlock_t_size = S.constant "PTHREAD_RWLOCK_T_SIZE" S.int let pthread_rwlockattr_t_size = S.constant "PTHREAD_RWLOCKATTR_T_SIZE" S.int let pthread_t_size = S.constant "PTHREAD_T_SIZE" S.int end
null
https://raw.githubusercontent.com/savonet/ocaml-posix/d46d011de16154b34324eae6ee6e7010138cf4af/posix-types/src/constants/posix_types_constants.ml
ocaml
let number_types = [ "blkcnt_t"; "blksize_t"; "clock_t"; "clockid_t"; "dev_t"; "fsblkcnt_t"; "fsfilcnt_t"; "gid_t"; "id_t"; "ino_t"; "key_t"; "mode_t"; "nlink_t"; "off_t"; "pid_t"; "size_t"; "ssize_t"; "suseconds_t"; "time_t"; "uid_t"; ] let abstract_types = [ "useconds_t"; "pthread_attr_t"; "pthread_cond_t"; "pthread_condattr_t"; "pthread_key_t"; "pthread_mutex_t"; "pthread_mutexattr_t"; "pthread_once_t"; "pthread_rwlock_t"; "pthread_rwlockattr_t"; "pthread_t"; ] module Def (S : Cstubs.Types.TYPE) = struct let blkcnt_t_size = S.constant "BLKCNT_T_SIZE" S.int let blksize_t_size = S.constant "BLKSIZE_T_SIZE" S.int let clock_t_size = S.constant "CLOCK_T_SIZE" S.int let clockid_t_size = S.constant "CLOCKID_T_SIZE" S.int let is_clock_t_float = S.constant "IS_CLOCK_T_FLOAT" S.bool let dev_t_size = S.constant "DEV_T_SIZE" S.int let fsblkcnt_t_size = S.constant "FSBLKCNT_T_SIZE" S.int let fsfilcnt_t_size = S.constant "FSFILCNT_T_SIZE" S.int let gid_t_size = S.constant "GID_T_SIZE" S.int let id_t_size = S.constant "ID_T_SIZE" S.int let ino_t_size = S.constant "INO_T_SIZE" S.int let key_t_size = S.constant "KEY_T_SIZE" S.int let is_key_t_float = S.constant "IS_KEY_T_FLOAT" S.bool let mode_t_size = S.constant "MODE_T_SIZE" S.int let nlink_t_size = S.constant "NLINK_T_SIZE" S.int let off_t_size = S.constant "OFF_T_SIZE" S.int let pid_t_size = S.constant "PID_T_SIZE" S.int let size_t_size = S.constant "SIZE_T_SIZE" S.int let ssize_t_size = S.constant "SSIZE_T_SIZE" S.int let suseconds_t_size = S.constant "SUSECONDS_T_SIZE" S.int let time_t_size = S.constant "TIME_T_SIZE" S.int let is_time_t_float = S.constant "IS_TIME_T_FLOAT" S.bool let uid_t_size = S.constant "UID_T_SIZE" S.int let useconds_t_size = S.constant "USECONDS_T_SIZE" S.int let pthread_attr_t_alignment = S.constant "PTHREAD_ATTR_T_ALIGNMENT" S.int let pthread_cond_t_alignment = S.constant "PTHREAD_COND_T_ALIGNMENT" S.int let pthread_condattr_t_alignment = S.constant "PTHREAD_CONDATTR_T_ALIGNMENT" S.int let pthread_key_t_alignment = S.constant "PTHREAD_KEY_T_ALIGNMENT" S.int let pthread_mutex_t_alignment = S.constant "PTHREAD_MUTEX_T_ALIGNMENT" S.int let pthread_mutexattr_t_alignment = S.constant "PTHREAD_MUTEXATTR_T_ALIGNMENT" S.int let pthread_once_t_alignment = S.constant "PTHREAD_ONCE_T_ALIGNMENT" S.int let pthread_rwlock_t_alignment = S.constant "PTHREAD_RWLOCK_T_ALIGNMENT" S.int let pthread_rwlockattr_t_alignment = S.constant "PTHREAD_RWLOCKATTR_T_ALIGNMENT" S.int let pthread_t_alignment = S.constant "PTHREAD_T_ALIGNMENT" S.int let pthread_attr_t_size = S.constant "PTHREAD_ATTR_T_SIZE" S.int let pthread_cond_t_size = S.constant "PTHREAD_COND_T_SIZE" S.int let pthread_condattr_t_size = S.constant "PTHREAD_CONDATTR_T_SIZE" S.int let pthread_key_t_size = S.constant "PTHREAD_KEY_T_SIZE" S.int let pthread_mutex_t_size = S.constant "PTHREAD_MUTEX_T_SIZE" S.int let pthread_mutexattr_t_size = S.constant "PTHREAD_MUTEXATTR_T_SIZE" S.int let pthread_once_t_size = S.constant "PTHREAD_ONCE_T_SIZE" S.int let pthread_rwlock_t_size = S.constant "PTHREAD_RWLOCK_T_SIZE" S.int let pthread_rwlockattr_t_size = S.constant "PTHREAD_RWLOCKATTR_T_SIZE" S.int let pthread_t_size = S.constant "PTHREAD_T_SIZE" S.int end
93cd0b0d1951f41122810054a7edfbb73042f3d72b3b6aec1245474ad267b647
dmitryvk/sbcl-win32-threads
ir1tran.lisp
;;;; This file contains code which does the translation from Lisp code to the first intermediate representation ( IR1 ) . 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!C") (declaim (special *compiler-error-bailout*)) ;;; *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the ;;; form number to associate with a source path. This should be bound ;;; to an initial value of 0 before the processing of each truly ;;; top level form. (declaim (type index *current-form-number*)) (defvar *current-form-number*) ;;; *SOURCE-PATHS* is a hashtable from source code forms to the path ;;; taken through the source to reach the form. This provides a way to ;;; keep track of the location of original source forms, even when macroexpansions and other arbitary permutations of the code ;;; happen. This table is initialized by calling FIND-SOURCE-PATHS on ;;; the original source. ;;; ;;; It is fairly useless to store symbols, characters, or fixnums in this table , as 42 is EQ to 42 no matter where in the source it ;;; appears. GET-SOURCE-PATH and NOTE-SOURCE-PATH functions should be ;;; always used to access this table. (declaim (hash-table *source-paths*)) (defvar *source-paths*) (declaim (inline source-form-has-path-p)) (defun source-form-has-path-p (form) (not (typep form '(or symbol fixnum character)))) (defun get-source-path (form) (when (source-form-has-path-p form) (gethash form *source-paths*))) (defun simplify-source-path-form (form) (if (consp form) (let ((op (car form))) ;; In the compiler functions can be directly represented ;; by leaves. Having leaves in the source path is pretty ;; hard on the poor user, however, so replace with the ;; source-name when possible. (if (and (leaf-p op) (leaf-has-source-name-p op)) (cons (leaf-source-name op) (cdr form)) form)) form)) (defun note-source-path (form &rest arguments) (when (source-form-has-path-p form) (setf (gethash form *source-paths*) (apply #'list* 'original-source-start *current-form-number* arguments)))) ;;; *CURRENT-COMPONENT* is the COMPONENT structure which we link ;;; blocks into as we generate them. This just serves to glue the ;;; emitted blocks together until local call analysis and flow graph ;;; canonicalization figure out what is really going on. We need to ;;; keep track of all the blocks generated so that we can delete them ;;; if they turn out to be unreachable. ;;; FIXME : It 's confusing having one variable named * CURRENT - COMPONENT * and another named * COMPONENT - BEING - COMPILED * . ( In CMU CL they ;;; were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively, ;;; which was also confusing.) (declaim (type (or component null) *current-component*)) (defvar *current-component*) ;;; *CURRENT-PATH* is the source path of the form we are currently translating . See NODE - SOURCE - PATH in the NODE structure . (declaim (list *current-path*)) (defvar *current-path*) (defvar *derive-function-types* nil "Should the compiler assume that function types will never change, so that it can use type information inferred from current definitions to optimize code which uses those definitions? Setting this true gives non-ANSI, early-CMU-CL behavior. It can be useful for improving the efficiency of stable code.") (defvar *fun-names-in-this-file* nil) (defvar *post-binding-variable-lexenv* nil) ;;;; namespace management utilities (defun fun-lexically-notinline-p (name) (let ((fun (lexenv-find name funs :test #'equal))) ;; a declaration will trump a proclamation (if (and fun (defined-fun-p fun)) (eq (defined-fun-inlinep fun) :notinline) (eq (info :function :inlinep name) :notinline)))) This will get redefined in PCL boot . (declaim (notinline maybe-update-info-for-gf)) (defun maybe-update-info-for-gf (name) (declare (ignore name)) nil) (defun maybe-defined-here (name where) (if (and (eq :defined where) (member name *fun-names-in-this-file* :test #'equal)) :defined-here where)) ;;; Return a GLOBAL-VAR structure usable for referencing the global ;;; function NAME. (defun find-global-fun (name latep) (unless (info :function :kind name) (setf (info :function :kind name) :function) (setf (info :function :where-from name) :assumed)) (let ((where (info :function :where-from name))) (when (and (eq where :assumed) In the ordinary target , it 's silly to report ;; undefinedness when the function is defined in the running . But at cross - compile time , the current ;; definedness of a function is irrelevant to the ;; definedness at runtime, which is what matters. #-sb-xc-host (not (fboundp name)) LATEP is true when the user has indicated that ;; late-late binding is desired by using eg. a quoted ;; symbol -- in which case it makes little sense to ;; complain about undefined functions. (not latep)) (note-undefined-reference name :function)) (let ((ftype (info :function :type name)) (notinline (fun-lexically-notinline-p name))) (make-global-var :kind :global-function :%source-name name :type (if (or (eq where :declared) (and (not latep) (not notinline) *derive-function-types*)) ftype (specifier-type 'function)) :defined-type (if (and (not latep) (not notinline)) (or (maybe-update-info-for-gf name) ftype) (specifier-type 'function)) :where-from (if notinline where (maybe-defined-here name where)))))) Have some DEFINED - FUN - FUNCTIONALS of a * FREE - FUNS * entry become invalid ? ;;; Drop 'em. ;;; This was added to fix bug 138 in SBCL . It is possible for a * FREE - FUNS * ;;; entry to contain a DEFINED-FUN whose DEFINED-FUN-FUNCTIONAL object contained IR1 stuff ( NODEs , BLOCKs ... ) referring to an already compiled ;;; (aka "dead") component. When this IR1 stuff was reused in a new component, ;;; under further obscure circumstances it could be used by ;;; WITH-IR1-ENVIRONMENT-FROM-NODE to generate a binding for ;;; *CURRENT-COMPONENT*. At that point things got all confused, since IR1 ;;; conversion was sending code to a component which had already been compiled ;;; and would never be compiled again. ;;; Note : as of 1.0.24.41 this seems to happen only in XC , and the original ;;; BUGS entry also makes it seem like this might not be an issue at all on ;;; target. (defun clear-invalid-functionals (free-fun) ;; There might be other reasons that *FREE-FUN* entries could ;; become invalid, but the only one we've been bitten by so far ( sbcl-0.pre7.118 ) is this one : (when (defined-fun-p free-fun) (setf (defined-fun-functionals free-fun) (delete-if (lambda (functional) (or (eq (functional-kind functional) :deleted) (when (lambda-p functional) (or ( The main reason for this first test is to bail ;; out early in cases where the LAMBDA-COMPONENT call in the second test would fail because links ;; it needs are uninitialized or invalid.) ;; If the BIND node for this LAMBDA is null , then ;; according to the slot comments, the LAMBDA has ;; been deleted or its call has been deleted. In ;; that case, it seems rather questionable to reuse ;; it, and certainly it shouldn't be necessary to ;; reuse it, so we cheerfully declare it invalid. (not (lambda-bind functional)) ;; If this IR1 stuff belongs to a dead component, ;; then we can't reuse it without getting into ;; bizarre confusion. (eq (component-info (lambda-component functional)) :dead))))) (defined-fun-functionals free-fun))) nil)) ;;; If NAME already has a valid entry in *FREE-FUNS*, then return the value . Otherwise , make a new GLOBAL - VAR using information from ;;; the global environment and enter it in *FREE-FUNS*. If NAME ;;; names a macro or special form, then we error out using the ;;; supplied context which indicates what we were trying to do that ;;; demanded a function. (declaim (ftype (sfunction (t string) global-var) find-free-fun)) (defun find-free-fun (name context) (or (let ((old-free-fun (gethash name *free-funs*))) (when old-free-fun (clear-invalid-functionals old-free-fun) old-free-fun)) (ecase (info :function :kind name) ;; FIXME: The :MACRO and :SPECIAL-FORM cases could be merged. (:macro (compiler-error "The macro name ~S was found ~A." name context)) (:special-form (compiler-error "The special form name ~S was found ~A." name context)) ((:function nil) (check-fun-name name) (note-if-setf-fun-and-macro name) (let ((expansion (fun-name-inline-expansion name)) (inlinep (info :function :inlinep name))) (setf (gethash name *free-funs*) (if (or expansion inlinep) (let ((where (info :function :where-from name))) (make-defined-fun :%source-name name :inline-expansion expansion :inlinep inlinep :where-from (if (eq inlinep :notinline) where (maybe-defined-here name where)) :type (if (and (eq inlinep :notinline) (neq where :declared)) (specifier-type 'function) (info :function :type name)))) (find-global-fun name nil)))))))) Return the LEAF structure for the lexically apparent function ;;; definition of NAME. (declaim (ftype (sfunction (t string) leaf) find-lexically-apparent-fun)) (defun find-lexically-apparent-fun (name context) (let ((var (lexenv-find name funs :test #'equal))) (cond (var (unless (leaf-p var) (aver (and (consp var) (eq (car var) 'macro))) (compiler-error "found macro name ~S ~A" name context)) var) (t (find-free-fun name context))))) (defun maybe-find-free-var (name) (gethash name *free-vars*)) Return the LEAF node for a global variable reference to NAME . If ;;; NAME is already entered in *FREE-VARS*, then we just return the ;;; corresponding value. Otherwise, we make a new leaf using ;;; information from the global environment and enter it in ;;; *FREE-VARS*. If the variable is unknown, then we emit a warning. (declaim (ftype (sfunction (t) (or leaf cons heap-alien-info)) find-free-var)) (defun find-free-var (name) (unless (symbolp name) (compiler-error "Variable name is not a symbol: ~S." name)) (or (gethash name *free-vars*) (let ((kind (info :variable :kind name)) (type (info :variable :type name)) (where-from (info :variable :where-from name))) (when (eq kind :unknown) (note-undefined-reference name :variable)) (setf (gethash name *free-vars*) (case kind (:alien (info :variable :alien-info name)) ;; FIXME: The return value in this case should really be ;; of type SB!C::LEAF. I don't feel too badly about it, because the MACRO idiom is scattered throughout this ;; file, but it should be cleaned up so we're not throwing random conses around . --njf 2002 - 03 - 23 (:macro (let ((expansion (info :variable :macro-expansion name)) (type (type-specifier (info :variable :type name)))) `(macro . (the ,type ,expansion)))) (:constant (let ((value (symbol-value name))) Override the values of standard symbols in XC , ;; since we can't redefine them. #+sb-xc-host (when (eql (find-symbol (symbol-name name) :cl) name) (multiple-value-bind (xc-value foundp) (info :variable :xc-constant-value name) (cond (foundp (setf value xc-value)) ((not (eq value name)) (compiler-warn "Using cross-compilation host's definition of ~S: ~A~%" name (symbol-value name)))))) (find-constant value name))) (t (make-global-var :kind kind :%source-name name :type type :where-from where-from))))))) ;;; Grovel over CONSTANT checking for any sub-parts that need to be ;;; processed with MAKE-LOAD-FORM. We have to be careful, because ;;; CONSTANT might be circular. We also check that the constant (and ;;; any subparts) are dumpable at all. (defun maybe-emit-make-load-forms (constant &optional (name nil namep)) (let ((xset (alloc-xset))) (labels ((trivialp (value) (typep value '(or #-sb-xc-host unboxed-array #+sb-xc-host (simple-array (unsigned-byte 8) (*)) symbol number character string))) (grovel (value) Unless VALUE is an object which which obviously ;; can't contain other objects (unless (trivialp value) (if (xset-member-p value xset) (return-from grovel nil) (add-to-xset value xset)) (typecase value (cons (grovel (car value)) (grovel (cdr value))) (simple-vector (dotimes (i (length value)) (grovel (svref value i)))) ((vector t) (dotimes (i (length value)) (grovel (aref value i)))) ((simple-array t) ;; Even though the (ARRAY T) branch does the exact ;; same thing as this branch we do this separately ;; so that the compiler can use faster versions of ;; array-total-size and row-major-aref. (dotimes (i (array-total-size value)) (grovel (row-major-aref value i)))) ((array t) (dotimes (i (array-total-size value)) (grovel (row-major-aref value i)))) (#+sb-xc-host structure!object #-sb-xc-host instance In the target SBCL , we can dump any instance , but ;; in the cross-compilation host, %INSTANCE-FOO ;; functions don't work on general instances, only on STRUCTURE!OBJECTs . ;; ;; FIXME: What about funcallable instances with ;; user-defined MAKE-LOAD-FORM methods? (when (emit-make-load-form value) (dotimes (i (- (%instance-length value) #+sb-xc-host 0 #-sb-xc-host (layout-n-untagged-slots (%instance-ref value 0)))) (grovel (%instance-ref value i))))) (t (compiler-error "Objects of type ~S can't be dumped into fasl files." (type-of value))))))) ;; Dump all non-trivial named constants using the name. (if (and namep (not (typep constant '(or symbol character ;; FIXME: Cold init breaks if we try to reference FP constants ;; thru their names. #+sb-xc-host number #-sb-xc-host fixnum)))) (emit-make-load-form constant name) (grovel constant)))) (values)) ;;;; some flow-graph hacking utilities ;;; This function sets up the back link between the node and the ;;; ctran which continues at it. (defun link-node-to-previous-ctran (node ctran) (declare (type node node) (type ctran ctran)) (aver (not (ctran-next ctran))) (setf (ctran-next ctran) node) (setf (node-prev node) ctran)) ;;; This function is used to set the ctran for a node, and thus ;;; determine what is evaluated next. If the ctran has no block, then ;;; we make it be in the block that the node is in. If the ctran heads ;;; its block, we end our block and link it to that block. #!-sb-fluid (declaim (inline use-ctran)) (defun use-ctran (node ctran) (declare (type node node) (type ctran ctran)) (if (eq (ctran-kind ctran) :unused) (let ((node-block (ctran-block (node-prev node)))) (setf (ctran-block ctran) node-block) (setf (ctran-kind ctran) :inside-block) (setf (ctran-use ctran) node) (setf (node-next node) ctran)) (%use-ctran node ctran))) (defun %use-ctran (node ctran) (declare (type node node) (type ctran ctran) (inline member)) (let ((block (ctran-block ctran)) (node-block (ctran-block (node-prev node)))) (aver (eq (ctran-kind ctran) :block-start)) (when (block-last node-block) (error "~S has already ended." node-block)) (setf (block-last node-block) node) (when (block-succ node-block) (error "~S already has successors." node-block)) (setf (block-succ node-block) (list block)) (when (memq node-block (block-pred block)) (error "~S is already a predecessor of ~S." node-block block)) (push node-block (block-pred block)))) ;;; Insert NEW before OLD in the flow-graph. (defun insert-node-before (old new) (let ((prev (node-prev old)) (temp (make-ctran))) (ensure-block-start prev) (setf (ctran-next prev) nil) (link-node-to-previous-ctran new prev) (use-ctran new temp) (link-node-to-previous-ctran old temp)) (values)) ;;; This function is used to set the ctran for a node, and thus ;;; determine what receives the value. (defun use-lvar (node lvar) (declare (type valued-node node) (type (or lvar null) lvar)) (aver (not (node-lvar node))) (when lvar (setf (node-lvar node) lvar) (cond ((null (lvar-uses lvar)) (setf (lvar-uses lvar) node)) ((listp (lvar-uses lvar)) (aver (not (memq node (lvar-uses lvar)))) (push node (lvar-uses lvar))) (t (aver (neq node (lvar-uses lvar))) (setf (lvar-uses lvar) (list node (lvar-uses lvar))))) (reoptimize-lvar lvar))) #!-sb-fluid(declaim (inline use-continuation)) (defun use-continuation (node ctran lvar) (use-ctran node ctran) (use-lvar node lvar)) ;;;; exported functions ;;; This function takes a form and the top level form number for that ;;; form, and returns a lambda representing the translation of that ;;; form in the current global environment. The returned lambda is a ;;; top level lambda that can be called to cause evaluation of the ;;; forms. This lambda is in the initial component. If FOR-VALUE is T, ;;; then the value of the form is returned from the function, otherwise NIL is returned . ;;; ;;; This function may have arbitrary effects on the global environment due to processing of EVAL - WHENs . All syntax error checking is ;;; done, with erroneous forms being replaced by a proxy which signals ;;; an error if it is evaluated. Warnings about possibly inconsistent ;;; or illegal changes to the global environment will also be given. ;;; We make the initial component and convert the form in a PROGN ( and an optional NIL tacked on the end . ) We then return the lambda . We ;;; bind all of our state variables here, rather than relying on the ;;; global value (if any) so that IR1 conversion will be reentrant. This is necessary for EVAL - WHEN processing , etc . ;;; ;;; The hashtables used to hold global namespace info must be ;;; reallocated elsewhere. Note also that *LEXENV* is not bound, so ;;; that local macro definitions can be introduced by enclosing code. (defun ir1-toplevel (form path for-value &optional (allow-instrumenting t)) (declare (list path)) (let* ((*current-path* path) (component (make-empty-component)) (*current-component* component) (*allow-instrumenting* allow-instrumenting)) (setf (component-name component) 'initial-component) (setf (component-kind component) :initial) (let* ((forms (if for-value `(,form) `(,form nil))) (res (ir1-convert-lambda-body forms () :debug-name (debug-name 'top-level-form #+sb-xc-host nil #-sb-xc-host form)))) (setf (functional-entry-fun res) res (functional-arg-documentation res) () (functional-kind res) :toplevel) res))) ;;; This function is called on freshly read forms to record the ;;; initial location of each form (and subform.) Form is the form to find the paths in , and TLF - NUM is the top level form number of the ;;; truly top level form. ;;; ;;; This gets a bit interesting when the source code is circular. This ;;; can (reasonably?) happen in the case of circular list constants. (defun find-source-paths (form tlf-num) (declare (type index tlf-num)) (let ((*current-form-number* 0)) (sub-find-source-paths form (list tlf-num))) (values)) (defun sub-find-source-paths (form path) (unless (get-source-path form) (note-source-path form path) (incf *current-form-number*) (let ((pos 0) (subform form) (trail form)) (declare (fixnum pos)) (macrolet ((frob () `(progn (when (atom subform) (return)) (let ((fm (car subform))) (cond ((consp fm) ;; If it's a cons, recurse. (sub-find-source-paths fm (cons pos path))) ((eq 'quote fm) ;; Don't look into quoted constants. (return)) ((not (zerop pos)) ;; Otherwise store the containing form. It's not ;; perfect, but better than nothing. (note-source-path subform pos path))) (incf pos)) (setq subform (cdr subform)) (when (eq subform trail) (return))))) (loop (frob) (frob) (setq trail (cdr trail))))))) ;;;; IR1-CONVERT, macroexpansion and special form dispatching (declaim (ftype (sfunction (ctran ctran (or lvar null) t) (values)) ir1-convert)) (macrolet (;; Bind *COMPILER-ERROR-BAILOUT* to a function that throws ;; out of the body and converts a condition signalling form ;; instead. The source form is converted to a string since it ;; may contain arbitrary non-externalizable objects. (ir1-error-bailout ((start next result form) &body body) (with-unique-names (skip condition) `(block ,skip (let ((,condition (catch 'ir1-error-abort (let ((*compiler-error-bailout* (lambda (&optional e) (throw 'ir1-error-abort e)))) ,@body (return-from ,skip nil))))) (ir1-convert ,start ,next ,result (make-compiler-error-form ,condition ,form))))))) Translate FORM into IR1 . The code is inserted as the NEXT of the CTRAN START . RESULT is the LVAR which receives the value of the ;; FORM to be translated. The translators call this function ;; recursively to translate their subnodes. ;; As a special hack to make life easier in the compiler , a LEAF IR1 - converts into a reference to that LEAF structure . This allows ;; the creation using backquote of forms that contain leaf ;; references, without having to introduce dummy names into the ;; namespace. (defun ir1-convert (start next result form) (ir1-error-bailout (start next result form) (let* ((*current-path* (or (get-source-path form) (cons (simplify-source-path-form form) *current-path*))) (start (instrument-coverage start nil form))) (cond ((atom form) (cond ((and (symbolp form) (not (keywordp form))) (ir1-convert-var start next result form)) ((leaf-p form) (reference-leaf start next result form)) (t (reference-constant start next result form)))) (t (ir1-convert-functoid start next result form))))) (values)) ;; Generate a reference to a manifest constant, creating a new leaf ;; if necessary. (defun reference-constant (start next result value) (declare (type ctran start next) (type (or lvar null) result)) (ir1-error-bailout (start next result value) (let* ((leaf (find-constant value)) (res (make-ref leaf))) (push res (leaf-refs leaf)) (link-node-to-previous-ctran res start) (use-continuation res next result))) (values))) ;;; Add FUNCTIONAL to the COMPONENT-REANALYZE-FUNCTIONALS, unless it's ;;; some trivial type for which reanalysis is a trivial no-op, or ;;; unless it doesn't belong in this component at all. ;;; ;;; FUNCTIONAL is returned. (defun maybe-reanalyze-functional (functional) bug 148 (aver-live-component *current-component*) ;; When FUNCTIONAL is of a type for which reanalysis isn't a trivial no - op (when (typep functional '(or optional-dispatch clambda)) ;; When FUNCTIONAL knows its component (when (lambda-p functional) (aver (eql (lambda-component functional) *current-component*))) (pushnew functional (component-reanalyze-functionals *current-component*))) functional) Generate a REF node for LEAF , frobbing the LEAF structure as needed . If LEAF represents a defined function which has already been converted , and is not : NOTINLINE , then reference the ;;; functional instead. (defun reference-leaf (start next result leaf &optional (name '.anonymous.)) (declare (type ctran start next) (type (or lvar null) result) (type leaf leaf)) (assure-leaf-live-p leaf) (let* ((type (lexenv-find leaf type-restrictions)) (leaf (or (and (defined-fun-p leaf) (not (eq (defined-fun-inlinep leaf) :notinline)) (let ((functional (defined-fun-functional leaf))) (when (and functional (not (functional-kind functional))) (maybe-reanalyze-functional functional)))) (when (and (lambda-p leaf) (memq (functional-kind leaf) '(nil :optional))) (maybe-reanalyze-functional leaf)) leaf)) (ref (make-ref leaf name))) (push ref (leaf-refs leaf)) (setf (leaf-ever-used leaf) t) (link-node-to-previous-ctran ref start) (cond (type (let* ((ref-ctran (make-ctran)) (ref-lvar (make-lvar)) (cast (make-cast ref-lvar (make-single-value-type type) (lexenv-policy *lexenv*)))) (setf (lvar-dest ref-lvar) cast) (use-continuation ref ref-ctran ref-lvar) (link-node-to-previous-ctran cast ref-ctran) (use-continuation cast next result))) (t (use-continuation ref next result))))) ;;; Convert a reference to a symbolic constant or variable. If the ;;; symbol is entered in the LEXENV-VARS we use that definition, ;;; otherwise we find the current global definition. This is also ;;; where we pick off symbol macro and alien variable references. (defun ir1-convert-var (start next result name) (declare (type ctran start next) (type (or lvar null) result) (symbol name)) (let ((var (or (lexenv-find name vars) (find-free-var name)))) (if (and (global-var-p var) (not result)) : If the reference is dead , convert using SYMBOL - VALUE ;; which is not flushable, so that unbound dead variables signal an error ( bug 412 ) . (ir1-convert start next result (if (eq (global-var-kind var) :global) `(symbol-global-value ',name) `(symbol-value ',name))) (etypecase var (leaf (when (lambda-var-p var) (let ((home (ctran-home-lambda-or-null start))) (when home (sset-adjoin var (lambda-calls-or-closes home)))) (when (lambda-var-ignorep var) ( ANSI 's specification for the IGNORE declaration requires ;; that this be a STYLE-WARNING, not a full WARNING.) #-sb-xc-host (compiler-style-warn "reading an ignored variable: ~S" name) there 's no need for us to accept ANSI 's lameness when ;; processing our own code, though. #+sb-xc-host (warn "reading an ignored variable: ~S" name))) (reference-leaf start next result var name)) (cons (aver (eq (car var) 'macro)) FIXME : [ Free ] type declarations . -- APD , 2002 - 01 - 26 (ir1-convert start next result (cdr var))) (heap-alien-info (ir1-convert start next result `(%heap-alien ',var)))))) (values)) ;;; Find a compiler-macro for a form, taking FUNCALL into account. (defun find-compiler-macro (opname form) (if (eq opname 'funcall) (let ((fun-form (cadr form))) (cond ((and (consp fun-form) (eq 'function (car fun-form))) (let ((real-fun (cadr fun-form))) (if (legal-fun-name-p real-fun) (values (sb!xc:compiler-macro-function real-fun *lexenv*) real-fun) (values nil nil)))) ((sb!xc:constantp fun-form *lexenv*) (let ((fun (constant-form-value fun-form *lexenv*))) (if (legal-fun-name-p fun) ;; CLHS tells us that local functions must shadow ;; compiler-macro-functions, but since the call is ;; through a name, we are obviously interested ;; in the global function. (values (sb!xc:compiler-macro-function fun nil) fun) (values nil nil)))) (t (values nil nil)))) (if (legal-fun-name-p opname) (values (sb!xc:compiler-macro-function opname *lexenv*) opname) (values nil nil)))) ;;; Picks of special forms and compiler-macro expansions, and hands ;;; the rest to IR1-CONVERT-COMMON-FUNCTOID (defun ir1-convert-functoid (start next result form) (let* ((op (car form)) (translator (and (symbolp op) (info :function :ir1-convert op)))) (cond (translator (when (sb!xc:compiler-macro-function op *lexenv*) (compiler-warn "ignoring compiler macro for special form")) (funcall translator start next result form)) (t (multiple-value-bind (cmacro-fun cmacro-fun-name) (find-compiler-macro op form) (if (and cmacro-fun CLHS 3.2.2.1.3 specifies that NOTINLINE ;; suppresses compiler-macros. (not (fun-lexically-notinline-p cmacro-fun-name))) (let ((res (careful-expand-macro cmacro-fun form t))) (cond ((eq res form) (ir1-convert-common-functoid start next result form op)) (t (unless (policy *lexenv* (zerop store-xref-data)) (record-call cmacro-fun-name (ctran-block start) *current-path*)) (ir1-convert start next result res)))) (ir1-convert-common-functoid start next result form op))))))) ;;; Handles the "common" cases: any other forms except special forms ;;; and compiler-macros. (defun ir1-convert-common-functoid (start next result form op) (cond ((or (symbolp op) (leaf-p op)) (let ((lexical-def (if (leaf-p op) op (lexenv-find op funs)))) (typecase lexical-def (null (ir1-convert-global-functoid start next result form op)) (functional (ir1-convert-local-combination start next result form lexical-def)) (global-var (ir1-convert-srctran start next result lexical-def form)) (t (aver (and (consp lexical-def) (eq (car lexical-def) 'macro))) (ir1-convert start next result (careful-expand-macro (cdr lexical-def) form)))))) ((or (atom op) (not (eq (car op) 'lambda))) (compiler-error "illegal function call")) (t ;; implicitly (LAMBDA ..) because the LAMBDA expression is ;; the CAR of an executed form. (ir1-convert-combination start next result form (ir1-convert-lambda op :debug-name (debug-name 'inline-lambda op)))))) ;;; Convert anything that looks like a global function call. (defun ir1-convert-global-functoid (start next result form fun) (declare (type ctran start next) (type (or lvar null) result) (list form)) ;; FIXME: Couldn't all the INFO calls here be converted into standard CL functions , like MACRO - FUNCTION or something ? And what happens with lexically - defined ( MACROLET ) macros here , anyway ? (ecase (info :function :kind fun) (:macro (ir1-convert start next result (careful-expand-macro (info :function :macro-function fun) form)) (unless (policy *lexenv* (zerop store-xref-data)) (record-macroexpansion fun (ctran-block start) *current-path*))) ((nil :function) (ir1-convert-srctran start next result (find-free-fun fun "shouldn't happen! (no-cmacro)") form)))) (defun muffle-warning-or-die () (muffle-warning) (bug "no MUFFLE-WARNING restart")) Expand FORM using the macro whose MACRO - FUNCTION is FUN , trapping ;;; errors which occur during the macroexpansion. (defun careful-expand-macro (fun form &optional cmacro) (flet (;; Return a string to use as a prefix in error reporting, ;; telling something about which form caused the problem. (wherestring () (let (;; We rely on the printer to abbreviate FORM. (*print-length* 3) (*print-level* 3)) (format nil #-sb-xc-host "~@<~;during ~A of ~S. Use ~S to intercept:~%~:@>" ;; longer message to avoid ambiguity "Was it the xc host ;; or the cross-compiler which encountered the problem?" #+sb-xc-host "~@<~;during cross-compiler ~A of ~S. Use ~S to intercept:~%~:@>" (if cmacro "compiler-macroexpansion" "macroexpansion") form '*break-on-signals*)))) : CMU CL in its wisdom ( version 2.4.6 for Debian Linux , anyway ) raises a CL : WARNING condition ( not a CL : STYLE - WARNING ) for undefined symbols when converting interpreted functions , causing COMPILE - FILE to think the file has a real problem , causing COMPILE - FILE to return FAILURE - P set ( not just WARNINGS - P set ) . Since undefined ;; symbol warnings are often harmless forward references, ;; and since it'd be inordinately painful to try to ;; eliminate all such forward references, these warnings ;; are basically unavoidable. Thus, we need to coerce the ;; system to work through them, and this code does so, by ;; crudely suppressing all warnings in cross-compilation macroexpansion . -- WHN 19990412 #+(and cmu sb-xc-host) (warning (lambda (c) (compiler-notify "~@<~A~:@_~ ~A~:@_~ ~@<(KLUDGE: That was a non-STYLE WARNING. ~ Ordinarily that would cause compilation to ~ fail. However, since we're running under ~ CMU CL, and since CMU CL emits non-STYLE ~ warnings for safe, hard-to-fix things (e.g. ~ references to not-yet-defined functions) ~ we're going to have to ignore it and ~ proceed anyway. Hopefully we're not ~ ignoring anything horrible here..)~:@>~:>" (wherestring) c) (muffle-warning-or-die))) (error (lambda (c) (compiler-error "~@<~A~@:_ ~A~:>" (wherestring) c)))) (funcall sb!xc:*macroexpand-hook* fun form *lexenv*)))) ;;;; conversion utilities ;;; Convert a bunch of forms, discarding all the values except the ;;; last. If there aren't any forms, then translate a NIL. (declaim (ftype (sfunction (ctran ctran (or lvar null) list) (values)) ir1-convert-progn-body)) (defun ir1-convert-progn-body (start next result body) (if (endp body) (reference-constant start next result nil) (let ((this-start start) (forms body)) (loop (let ((form (car forms))) (setf this-start (maybe-instrument-progn-like this-start forms form)) (when (endp (cdr forms)) (ir1-convert this-start next result form) (return)) (let ((this-ctran (make-ctran))) (ir1-convert this-start this-ctran nil form) (setq this-start this-ctran forms (cdr forms))))))) (values)) ;;;; code coverage ;;; Check the policy for whether we should generate code coverage instrumentation . If not , just return the original START ;;; ctran. Otherwise insert code coverage instrumentation after START , and return the new ctran . (defun instrument-coverage (start mode form) ;; We don't actually use FORM for anything, it's just convenient to ;; have around when debugging the instrumentation. (declare (ignore form)) (if (and (policy *lexenv* (> store-coverage-data 0)) *code-coverage-records* *allow-instrumenting*) (let ((path (source-path-original-source *current-path*))) (when mode (push mode path)) (if (member (ctran-block start) (gethash path *code-coverage-blocks*)) ;; If this source path has already been instrumented in ;; this block, don't instrument it again. start (let ((store ;; Get an interned record cons for the path. A cons ;; with the same object identity must be used for ;; each instrument for the same block. (or (gethash path *code-coverage-records*) (setf (gethash path *code-coverage-records*) (cons path +code-coverage-unmarked+)))) (next (make-ctran)) (*allow-instrumenting* nil)) (push (ctran-block start) (gethash path *code-coverage-blocks*)) (let ((*allow-instrumenting* nil)) (ir1-convert start next nil `(locally (declare (optimize speed (safety 0) (debug 0) (check-constant-modification 0))) ;; We're being naughty here, and ;; modifying constant data. That's ok, ;; we know what we're doing. (%rplacd ',store t)))) next))) start)) ;;; In contexts where we don't have a source location for FORM ;;; e.g. due to it not being a cons, but where we have a source ;;; location for the enclosing cons, use the latter source location if available . This works pretty well in practice , since many PROGNish ;;; macroexpansions will just directly splice a block of forms into some enclosing form with ` ( progn , @body ) , thus retaining the ;;; EQness of the conses. (defun maybe-instrument-progn-like (start forms form) (or (when (and *allow-instrumenting* (not (get-source-path form))) (let ((*current-path* (get-source-path forms))) (when *current-path* (instrument-coverage start nil form)))) start)) (defun record-code-coverage (info cc) (setf (gethash info *code-coverage-info*) cc)) (defun clear-code-coverage () (clrhash *code-coverage-info*)) (defun reset-code-coverage () (maphash (lambda (info cc) (declare (ignore info)) (dolist (cc-entry cc) (setf (cdr cc-entry) +code-coverage-unmarked+))) *code-coverage-info*)) (defun code-coverage-record-marked (record) (aver (consp record)) (ecase (cdr record) ((#.+code-coverage-unmarked+) nil) ((t) t))) ;;;; converting combinations ;;; Does this form look like something that we should add single-stepping ;;; instrumentation for? (defun step-form-p (form) (flet ((step-symbol-p (symbol) (not (member (symbol-package symbol) (load-time-value : packages we 're not interested in ;; stepping. (mapcar #'find-package '(sb!c sb!int sb!impl sb!kernel sb!pcl))))))) (and *allow-instrumenting* (policy *lexenv* (= insert-step-conditions 3)) (listp form) (symbolp (car form)) (step-symbol-p (car form))))) Convert a function call where the function FUN is a LEAF . FORM is ;;; the source for the call. We return the COMBINATION node so that ;;; the caller can poke at it if it wants to. (declaim (ftype (sfunction (ctran ctran (or lvar null) list leaf) combination) ir1-convert-combination)) (defun ir1-convert-combination (start next result form fun) (let ((ctran (make-ctran)) (fun-lvar (make-lvar))) (ir1-convert start ctran fun-lvar `(the (or function symbol) ,fun)) (let ((combination (ir1-convert-combination-args fun-lvar ctran next result (cdr form)))) (when (step-form-p form) ;; Store a string representation of the form in the ;; combination node. This will let the IR2 translator know ;; that we want stepper instrumentation for this node. The ;; string will be stored in the debug-info by DUMP-1-LOCATION. (setf (combination-step-info combination) (let ((*print-pretty* t) (*print-circle* t) (*print-readably* nil)) (prin1-to-string form)))) combination))) ;;; Convert the arguments to a call and make the COMBINATION ;;; node. FUN-LVAR yields the function to call. ARGS is the list of ;;; arguments for the call, which defaults to the cdr of source. We ;;; return the COMBINATION node. (defun ir1-convert-combination-args (fun-lvar start next result args) (declare (type ctran start next) (type lvar fun-lvar) (type (or lvar null) result) (list args)) (let ((node (make-combination fun-lvar))) (setf (lvar-dest fun-lvar) node) (collect ((arg-lvars)) (let ((this-start start) (forms args)) (dolist (arg args) (setf this-start (maybe-instrument-progn-like this-start forms arg)) (setf forms (cdr forms)) (let ((this-ctran (make-ctran)) (this-lvar (make-lvar node))) (ir1-convert this-start this-ctran this-lvar arg) (setq this-start this-ctran) (arg-lvars this-lvar))) (link-node-to-previous-ctran node this-start) (use-continuation node next result) (setf (combination-args node) (arg-lvars)))) node)) Convert a call to a global function . If not : NOTINLINE , then we do ;;; source transforms and try out any inline expansion. If there is no ;;; expansion, but is :INLINE, then give an efficiency note (unless a ;;; known function which will quite possibly be open-coded.) Next, we ;;; go to ok-combination conversion. (defun ir1-convert-srctran (start next result var form) (declare (type ctran start next) (type (or lvar null) result) (type global-var var)) (let ((inlinep (when (defined-fun-p var) (defined-fun-inlinep var)))) (if (eq inlinep :notinline) (ir1-convert-combination start next result form var) (let* ((name (leaf-source-name var)) (transform (info :function :source-transform name))) (if transform (multiple-value-bind (transformed pass) (funcall transform form) (cond (pass (ir1-convert-maybe-predicate start next result form var)) (t (unless (policy *lexenv* (zerop store-xref-data)) (record-call name (ctran-block start) *current-path*)) (ir1-convert start next result transformed)))) (ir1-convert-maybe-predicate start next result form var)))))) : If we insert a synthetic IF for a function with the PREDICATE ;;; attribute, don't generate any branch coverage instrumentation for it. (defvar *instrument-if-for-code-coverage* t) ;;; If the function has the PREDICATE attribute, and the RESULT's DEST ;;; isn't an IF, then we convert (IF <form> T NIL), ensuring that a ;;; predicate always appears in a conditional context. ;;; ;;; If the function isn't a predicate, then we call ;;; IR1-CONVERT-COMBINATION-CHECKING-TYPE. (defun ir1-convert-maybe-predicate (start next result form var) (declare (type ctran start next) (type (or lvar null) result) (list form) (type global-var var)) (let ((info (info :function :info (leaf-source-name var)))) (if (and info (ir1-attributep (fun-info-attributes info) predicate) (not (if-p (and result (lvar-dest result))))) (let ((*instrument-if-for-code-coverage* nil)) (ir1-convert start next result `(if ,form t nil))) (ir1-convert-combination-checking-type start next result form var)))) ;;; Actually really convert a global function call that we are allowed ;;; to early-bind. ;;; ;;; If we know the function type of the function, then we check the ;;; call for syntactic legality with respect to the declared function ;;; type. If it is impossible to determine whether the call is correct ;;; due to non-constant keywords, then we give up, marking the call as ;;; :FULL to inhibit further error messages. We return true when the ;;; call is legal. ;;; ;;; If the call is legal, we also propagate type assertions from the ;;; function type to the arg and result lvars. We do this now so that ;;; IR1 optimize doesn't have to redundantly do the check later so ;;; that it can do the type propagation. (defun ir1-convert-combination-checking-type (start next result form var) (declare (type ctran start next) (type (or lvar null) result) (list form) (type leaf var)) (let* ((node (ir1-convert-combination start next result form var)) (fun-lvar (basic-combination-fun node)) (type (leaf-type var))) (when (validate-call-type node type var t) (setf (lvar-%derived-type fun-lvar) (make-single-value-type type)) (setf (lvar-reoptimize fun-lvar) nil))) (values)) ;;; Convert a call to a local function, or if the function has already been LET converted , then throw FUNCTIONAL to LOCALL - ALREADY - LET - CONVERTED . The THROW should only happen when we ;;; are converting inline expansions for local functions during ;;; optimization. (defun ir1-convert-local-combination (start next result form functional) (assure-functional-live-p functional) (ir1-convert-combination start next result form (maybe-reanalyze-functional functional))) ;;;; PROCESS-DECLS ;;; Given a list of LAMBDA-VARs and a variable name, return the for that name , or NIL if it is n't found . We return the ;;; *last* variable with that name, since LET* bindings may be ;;; duplicated, and declarations always apply to the last. (declaim (ftype (sfunction (list symbol) (or lambda-var list)) find-in-bindings)) (defun find-in-bindings (vars name) (let ((found nil)) (dolist (var vars) (cond ((leaf-p var) (when (eq (leaf-source-name var) name) (setq found var)) (let ((info (lambda-var-arg-info var))) (when info (let ((supplied-p (arg-info-supplied-p info))) (when (and supplied-p (eq (leaf-source-name supplied-p) name)) (setq found supplied-p)))))) ((and (consp var) (eq (car var) name)) (setf found (cdr var))))) found)) ;;; Called by PROCESS-DECLS to deal with a variable type declaration. ;;; If a LAMBDA-VAR being bound, we intersect the type with the var's ;;; type, otherwise we add a type restriction on the var. If a symbol ;;; macro, we just wrap a THE around the expansion. (defun process-type-decl (decl res vars context) (declare (list decl vars) (type lexenv res)) (let ((type (compiler-specifier-type (first decl)))) (collect ((restr nil cons) (new-vars nil cons)) (dolist (var-name (rest decl)) (when (boundp var-name) (program-assert-symbol-home-package-unlocked context var-name "declaring the type of ~A")) (let* ((bound-var (find-in-bindings vars var-name)) (var (or bound-var (lexenv-find var-name vars) (find-free-var var-name)))) (etypecase var (leaf (flet ((process-var (var bound-var) (let* ((old-type (or (lexenv-find var type-restrictions) (leaf-type var))) (int (if (or (fun-type-p type) (fun-type-p old-type)) type (type-approx-intersection2 old-type type)))) (cond ((eq int *empty-type*) (unless (policy *lexenv* (= inhibit-warnings 3)) (warn 'type-warning :format-control "The type declarations ~S and ~S for ~S conflict." :format-arguments (list (type-specifier old-type) (type-specifier type) var-name)))) (bound-var (setf (leaf-type bound-var) int (leaf-where-from bound-var) :declared)) (t (restr (cons var int))))))) (process-var var bound-var) (awhen (and (lambda-var-p var) (lambda-var-specvar var)) (process-var it nil)))) (cons ;; FIXME: non-ANSI weirdness (aver (eq (car var) 'macro)) (new-vars `(,var-name . (macro . (the ,(first decl) ,(cdr var)))))) (heap-alien-info (compiler-error "~S is an alien variable, so its type can't be declared." var-name))))) (if (or (restr) (new-vars)) (make-lexenv :default res :type-restrictions (restr) :vars (new-vars)) res)))) This is somewhat similar to PROCESS - TYPE - , but handles ;;; declarations for function variables. In addition to allowing ;;; declarations for functions being bound, we must also deal with ;;; declarations that constrain the type of lexically apparent ;;; functions. (defun process-ftype-decl (spec res names fvars context) (declare (type list names fvars) (type lexenv res)) (let ((type (compiler-specifier-type spec))) (collect ((res nil cons)) (dolist (name names) (when (fboundp name) (program-assert-symbol-home-package-unlocked context name "declaring the ftype of ~A")) (let ((found (find name fvars :key #'leaf-source-name :test #'equal))) (cond (found (setf (leaf-type found) type) (assert-definition-type found type :unwinnage-fun #'compiler-notify :where "FTYPE declaration")) (t (res (cons (find-lexically-apparent-fun name "in a function type declaration") type)))))) (if (res) (make-lexenv :default res :type-restrictions (res)) res)))) Process a special declaration , returning a new LEXENV . A non - bound ;;; special declaration is instantiated by throwing a special variable ;;; into the variables if BINDING-FORM-P is NIL, or otherwise into ;;; *POST-BINDING-VARIABLE-LEXENV*. (defun process-special-decl (spec res vars binding-form-p context) (declare (list spec vars) (type lexenv res)) (collect ((new-venv nil cons)) (dolist (name (cdr spec)) ;; While CLHS seems to allow local SPECIAL declarations for constants, ;; whatever the semantics are supposed to be is not at all clear to me ;; -- since constants aren't allowed to be bound it should be a no-op as ;; no-one can observe the difference portably, but specials are allowed ;; to be bound... yet nowhere does it say that the special declaration ;; removes the constantness. Call it a spec bug and prohibit it. Same ;; for GLOBAL variables. (let ((kind (info :variable :kind name))) (unless (member kind '(:special :unknown)) (error "Can't declare ~(~A~) variable locally special: ~S" kind name))) (program-assert-symbol-home-package-unlocked context name "declaring ~A special") (let ((var (find-in-bindings vars name))) (etypecase var (cons (aver (eq (car var) 'macro)) (compiler-error "~S is a symbol-macro and thus can't be declared special." name)) (lambda-var (when (lambda-var-ignorep var) ANSI 's definition for " Declaration IGNORE , IGNORABLE " ;; requires that this be a STYLE-WARNING, not a full WARNING. (compiler-style-warn "The ignored variable ~S is being declared special." name)) (setf (lambda-var-specvar var) (specvar-for-binding name))) (null (unless (or (assoc name (new-venv) :test #'eq)) (new-venv (cons name (specvar-for-binding name)))))))) (cond (binding-form-p (setf *post-binding-variable-lexenv* (append (new-venv) *post-binding-variable-lexenv*)) res) ((new-venv) (make-lexenv :default res :vars (new-venv))) (t res)))) Return a DEFINED - FUN which copies a GLOBAL - VAR but for its INLINEP ;;; (and TYPE if notinline), plus type-restrictions from the lexenv. (defun make-new-inlinep (var inlinep local-type) (declare (type global-var var) (type inlinep inlinep)) (let* ((type (if (and (eq inlinep :notinline) (not (eq (leaf-where-from var) :declared))) (specifier-type 'function) (leaf-type var))) (res (make-defined-fun :%source-name (leaf-source-name var) :where-from (leaf-where-from var) :type (if local-type (type-intersection local-type type) type) :inlinep inlinep))) (when (defined-fun-p var) (setf (defined-fun-inline-expansion res) (defined-fun-inline-expansion var)) (setf (defined-fun-functionals res) (defined-fun-functionals var))) ;; FIXME: Is this really right? Needs we not set the FUNCTIONAL ;; to the original global-var? res)) Parse an inline / notinline declaration . If it 's a local function we 're defining , set its INLINEP . If a global function , add a new FENV entry . (defun process-inline-decl (spec res fvars) (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq))) (new-fenv ())) (dolist (name (rest spec)) (let ((fvar (find name fvars :key #'leaf-source-name :test #'equal))) (if fvar (setf (functional-inlinep fvar) sense) (let ((found (find-lexically-apparent-fun name "in an inline or notinline declaration"))) (etypecase found (functional (when (policy *lexenv* (>= speed inhibit-warnings)) (compiler-notify "ignoring ~A declaration not at ~ definition of local function:~% ~S" sense name))) (global-var (let ((type (cdr (assoc found (lexenv-type-restrictions res))))) (push (cons name (make-new-inlinep found sense type)) new-fenv)))))))) (if new-fenv (make-lexenv :default res :funs new-fenv) res))) like FIND - IN - BINDINGS , but looks for # ' FOO in the FVARS (defun find-in-bindings-or-fbindings (name vars fvars) (declare (list vars fvars)) (if (consp name) (destructuring-bind (wot fn-name) name (unless (eq wot 'function) (compiler-error "The function or variable name ~S is unrecognizable." name)) (find fn-name fvars :key #'leaf-source-name :test #'equal)) (find-in-bindings vars name))) ;;; Process an ignore/ignorable declaration, checking for various losing ;;; conditions. (defun process-ignore-decl (spec vars fvars) (declare (list spec vars fvars)) (dolist (name (rest spec)) (let ((var (find-in-bindings-or-fbindings name vars fvars))) (cond ((not var) ANSI 's definition for " Declaration IGNORE , IGNORABLE " ;; requires that this be a STYLE-WARNING, not a full WARNING. (compiler-style-warn "declaring unknown variable ~S to be ignored" name)) ;; FIXME: This special case looks like non-ANSI weirdness. ((and (consp var) (eq (car var) 'macro)) Just ignore the IGNORE . ) ((functional-p var) (setf (leaf-ever-used var) t)) ((and (lambda-var-specvar var) (eq (first spec) 'ignore)) ANSI 's definition for " Declaration IGNORE , IGNORABLE " ;; requires that this be a STYLE-WARNING, not a full WARNING. (compiler-style-warn "declaring special variable ~S to be ignored" name)) ((eq (first spec) 'ignorable) (setf (leaf-ever-used var) t)) (t (setf (lambda-var-ignorep var) t))))) (values)) (defun process-dx-decl (names vars fvars kind) (let ((dx (cond ((eq 'truly-dynamic-extent kind) :truly) ((and (eq 'dynamic-extent kind) *stack-allocate-dynamic-extent*) t)))) (if dx (dolist (name names) (cond ((symbolp name) (let* ((bound-var (find-in-bindings vars name)) (var (or bound-var (lexenv-find name vars) (maybe-find-free-var name)))) (etypecase var (leaf (if bound-var (setf (leaf-dynamic-extent var) dx) (compiler-notify "Ignoring free DYNAMIC-EXTENT declaration: ~S" name))) (cons (compiler-error "DYNAMIC-EXTENT on symbol-macro: ~S" name)) (heap-alien-info (compiler-error "DYNAMIC-EXTENT on alien-variable: ~S" name)) (null (compiler-style-warn "Unbound variable declared DYNAMIC-EXTENT: ~S" name))))) ((and (consp name) (eq (car name) 'function) (null (cddr name)) (valid-function-name-p (cadr name))) (let* ((fname (cadr name)) (bound-fun (find fname fvars :key #'leaf-source-name :test #'equal)) (fun (or bound-fun (lexenv-find fname funs)))) (etypecase fun (leaf (if bound-fun #!+stack-allocatable-closures (setf (leaf-dynamic-extent bound-fun) dx) #!-stack-allocatable-closures (compiler-notify "Ignoring DYNAMIC-EXTENT declaration on function ~S ~ (not supported on this platform)." fname) (compiler-notify "Ignoring free DYNAMIC-EXTENT declaration: ~S" name))) (cons (compiler-error "DYNAMIC-EXTENT on macro: ~S" name)) (null (compiler-style-warn "Unbound function declared DYNAMIC-EXTENT: ~S" name))))) (t (compiler-error "DYNAMIC-EXTENT on a weird thing: ~S" name)))) (when (policy *lexenv* (= speed 3)) (compiler-notify "Ignoring DYNAMIC-EXTENT declarations: ~S" names))))) ;;; FIXME: This is non-ANSI, so the default should be T, or it should ;;; go away, I think. (defvar *suppress-values-declaration* nil #!+sb-doc "If true, processing of the VALUES declaration is inhibited.") Process a single declaration spec , augmenting the specified LEXENV RES . Return RES and result type . VARS and FVARS are as described ;;; PROCESS-DECLS. (defun process-1-decl (raw-spec res vars fvars binding-form-p context) (declare (type list raw-spec vars fvars)) (declare (type lexenv res)) (let ((spec (canonized-decl-spec raw-spec)) (result-type *wild-type*)) (values (case (first spec) (special (process-special-decl spec res vars binding-form-p context)) (ftype (unless (cdr spec) (compiler-error "no type specified in FTYPE declaration: ~S" spec)) (process-ftype-decl (second spec) res (cddr spec) fvars context)) ((inline notinline maybe-inline) (process-inline-decl spec res fvars)) ((ignore ignorable) (process-ignore-decl spec vars fvars) res) (optimize (make-lexenv :default res :policy (process-optimize-decl spec (lexenv-policy res)))) (muffle-conditions (make-lexenv :default res :handled-conditions (process-muffle-conditions-decl spec (lexenv-handled-conditions res)))) (unmuffle-conditions (make-lexenv :default res :handled-conditions (process-unmuffle-conditions-decl spec (lexenv-handled-conditions res)))) (type (process-type-decl (cdr spec) res vars context)) (values (unless *suppress-values-declaration* (let ((types (cdr spec))) (setq result-type (compiler-values-specifier-type (if (singleton-p types) (car types) `(values ,@types))))) res)) ((dynamic-extent truly-dynamic-extent) (process-dx-decl (cdr spec) vars fvars (first spec)) res) ((disable-package-locks enable-package-locks) (make-lexenv :default res :disabled-package-locks (process-package-lock-decl spec (lexenv-disabled-package-locks res)))) (t (unless (info :declaration :recognized (first spec)) (compiler-warn "unrecognized declaration ~S" raw-spec)) (let ((fn (info :declaration :handler (first spec)))) (if fn (funcall fn res spec vars fvars) res)))) result-type))) Use a list of DECLARE forms to annotate the lists of ;;; and FUNCTIONAL structures which are being bound. In addition to filling in slots in the leaf structures , we return a new LEXENV , ;;; which reflects pervasive special and function type declarations, ;;; (NOT)INLINE declarations and OPTIMIZE declarations, and type of VALUES declarations . If BINDING - FORM - P is true , the third return ;;; value is a list of VARs that should not apply to the lexenv of the ;;; initialization forms for the bindings, but should apply to the body. ;;; ;;; This is also called in main.lisp when PROCESS-FORM handles a use ;;; of LOCALLY. (defun process-decls (decls vars fvars &key (lexenv *lexenv*) (binding-form-p nil) (context :compile)) (declare (list decls vars fvars)) (let ((result-type *wild-type*) (*post-binding-variable-lexenv* nil)) (dolist (decl decls) (dolist (spec (rest decl)) (progv : EVAL calls this function to deal with LOCALLY . (when (eq context :compile) (list '*current-path*)) (when (eq context :compile) (list (or (get-source-path spec) (get-source-path decl) *current-path*))) (unless (consp spec) (compiler-error "malformed declaration specifier ~S in ~S" spec decl)) (multiple-value-bind (new-env new-result-type) (process-1-decl spec lexenv vars fvars binding-form-p context) (setq lexenv new-env) (unless (eq new-result-type *wild-type*) (setq result-type (values-type-intersection result-type new-result-type))))))) (values lexenv result-type *post-binding-variable-lexenv*))) (defun %processing-decls (decls vars fvars ctran lvar binding-form-p fun) (multiple-value-bind (*lexenv* result-type post-binding-lexenv) (process-decls decls vars fvars :binding-form-p binding-form-p) (cond ((eq result-type *wild-type*) (funcall fun ctran lvar post-binding-lexenv)) (t (let ((value-ctran (make-ctran)) (value-lvar (make-lvar))) (multiple-value-prog1 (funcall fun value-ctran value-lvar post-binding-lexenv) (let ((cast (make-cast value-lvar result-type (lexenv-policy *lexenv*)))) (link-node-to-previous-ctran cast value-ctran) (setf (lvar-dest value-lvar) cast) (use-continuation cast ctran lvar)))))))) (defmacro processing-decls ((decls vars fvars ctran lvar &optional post-binding-lexenv) &body forms) (check-type ctran symbol) (check-type lvar symbol) (let ((post-binding-lexenv-p (not (null post-binding-lexenv))) (post-binding-lexenv (or post-binding-lexenv (sb!xc:gensym "LEXENV")))) `(%processing-decls ,decls ,vars ,fvars ,ctran ,lvar ,post-binding-lexenv-p (lambda (,ctran ,lvar ,post-binding-lexenv) (declare (ignorable ,post-binding-lexenv)) ,@forms)))) Return the SPECVAR for NAME to use when we see a local SPECIAL ;;; declaration. If there is a global variable of that name, then ;;; check that it isn't a constant and return it. Otherwise, create an anonymous GLOBAL - VAR . (defun specvar-for-binding (name) (cond ((not (eq (info :variable :where-from name) :assumed)) (let ((found (find-free-var name))) (when (heap-alien-info-p found) (compiler-error "~S is an alien variable and so can't be declared special." name)) (unless (global-var-p found) (compiler-error "~S is a constant and so can't be declared special." name)) found)) (t (make-global-var :kind :special :%source-name name :where-from :declared))))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/ir1tran.lisp
lisp
This file contains code which does the translation from Lisp code 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. *CURRENT-FORM-NUMBER* is used in FIND-SOURCE-PATHS to compute the form number to associate with a source path. This should be bound to an initial value of 0 before the processing of each truly top level form. *SOURCE-PATHS* is a hashtable from source code forms to the path taken through the source to reach the form. This provides a way to keep track of the location of original source forms, even when happen. This table is initialized by calling FIND-SOURCE-PATHS on the original source. It is fairly useless to store symbols, characters, or fixnums in appears. GET-SOURCE-PATH and NOTE-SOURCE-PATH functions should be always used to access this table. In the compiler functions can be directly represented by leaves. Having leaves in the source path is pretty hard on the poor user, however, so replace with the source-name when possible. *CURRENT-COMPONENT* is the COMPONENT structure which we link blocks into as we generate them. This just serves to glue the emitted blocks together until local call analysis and flow graph canonicalization figure out what is really going on. We need to keep track of all the blocks generated so that we can delete them if they turn out to be unreachable. were called *CURRENT-COMPONENT* and *COMPILE-COMPONENT* respectively, which was also confusing.) *CURRENT-PATH* is the source path of the form we are currently namespace management utilities a declaration will trump a proclamation Return a GLOBAL-VAR structure usable for referencing the global function NAME. undefinedness when the function is defined in the definedness of a function is irrelevant to the definedness at runtime, which is what matters. late-late binding is desired by using eg. a quoted symbol -- in which case it makes little sense to complain about undefined functions. Drop 'em. entry to contain a DEFINED-FUN whose DEFINED-FUN-FUNCTIONAL object (aka "dead") component. When this IR1 stuff was reused in a new component, under further obscure circumstances it could be used by WITH-IR1-ENVIRONMENT-FROM-NODE to generate a binding for *CURRENT-COMPONENT*. At that point things got all confused, since IR1 conversion was sending code to a component which had already been compiled and would never be compiled again. BUGS entry also makes it seem like this might not be an issue at all on target. There might be other reasons that *FREE-FUN* entries could become invalid, but the only one we've been bitten by so far out early in cases where the LAMBDA-COMPONENT it needs are uninitialized or invalid.) according to the slot comments, the LAMBDA has been deleted or its call has been deleted. In that case, it seems rather questionable to reuse it, and certainly it shouldn't be necessary to reuse it, so we cheerfully declare it invalid. If this IR1 stuff belongs to a dead component, then we can't reuse it without getting into bizarre confusion. If NAME already has a valid entry in *FREE-FUNS*, then return the global environment and enter it in *FREE-FUNS*. If NAME names a macro or special form, then we error out using the supplied context which indicates what we were trying to do that demanded a function. FIXME: The :MACRO and :SPECIAL-FORM cases could be merged. definition of NAME. NAME is already entered in *FREE-VARS*, then we just return the corresponding value. Otherwise, we make a new leaf using information from the global environment and enter it in *FREE-VARS*. If the variable is unknown, then we emit a warning. FIXME: The return value in this case should really be of type SB!C::LEAF. I don't feel too badly about it, file, but it should be cleaned up so we're not since we can't redefine them. Grovel over CONSTANT checking for any sub-parts that need to be processed with MAKE-LOAD-FORM. We have to be careful, because CONSTANT might be circular. We also check that the constant (and any subparts) are dumpable at all. can't contain other objects Even though the (ARRAY T) branch does the exact same thing as this branch we do this separately so that the compiler can use faster versions of array-total-size and row-major-aref. in the cross-compilation host, %INSTANCE-FOO functions don't work on general instances, only on FIXME: What about funcallable instances with user-defined MAKE-LOAD-FORM methods? Dump all non-trivial named constants using the name. FIXME: Cold init breaks if we thru their names. some flow-graph hacking utilities This function sets up the back link between the node and the ctran which continues at it. This function is used to set the ctran for a node, and thus determine what is evaluated next. If the ctran has no block, then we make it be in the block that the node is in. If the ctran heads its block, we end our block and link it to that block. Insert NEW before OLD in the flow-graph. This function is used to set the ctran for a node, and thus determine what receives the value. exported functions This function takes a form and the top level form number for that form, and returns a lambda representing the translation of that form in the current global environment. The returned lambda is a top level lambda that can be called to cause evaluation of the forms. This lambda is in the initial component. If FOR-VALUE is T, then the value of the form is returned from the function, This function may have arbitrary effects on the global environment done, with erroneous forms being replaced by a proxy which signals an error if it is evaluated. Warnings about possibly inconsistent or illegal changes to the global environment will also be given. bind all of our state variables here, rather than relying on the global value (if any) so that IR1 conversion will be reentrant. The hashtables used to hold global namespace info must be reallocated elsewhere. Note also that *LEXENV* is not bound, so that local macro definitions can be introduced by enclosing code. This function is called on freshly read forms to record the initial location of each form (and subform.) Form is the form to truly top level form. This gets a bit interesting when the source code is circular. This can (reasonably?) happen in the case of circular list constants. If it's a cons, recurse. Don't look into quoted constants. Otherwise store the containing form. It's not perfect, but better than nothing. IR1-CONVERT, macroexpansion and special form dispatching Bind *COMPILER-ERROR-BAILOUT* to a function that throws out of the body and converts a condition signalling form instead. The source form is converted to a string since it may contain arbitrary non-externalizable objects. FORM to be translated. The translators call this function recursively to translate their subnodes. the creation using backquote of forms that contain leaf references, without having to introduce dummy names into the namespace. Generate a reference to a manifest constant, creating a new leaf if necessary. Add FUNCTIONAL to the COMPONENT-REANALYZE-FUNCTIONALS, unless it's some trivial type for which reanalysis is a trivial no-op, or unless it doesn't belong in this component at all. FUNCTIONAL is returned. When FUNCTIONAL is of a type for which reanalysis isn't a trivial When FUNCTIONAL knows its component functional instead. Convert a reference to a symbolic constant or variable. If the symbol is entered in the LEXENV-VARS we use that definition, otherwise we find the current global definition. This is also where we pick off symbol macro and alien variable references. which is not flushable, so that unbound dead variables signal that this be a STYLE-WARNING, not a full WARNING.) processing our own code, though. Find a compiler-macro for a form, taking FUNCALL into account. CLHS tells us that local functions must shadow compiler-macro-functions, but since the call is through a name, we are obviously interested in the global function. Picks of special forms and compiler-macro expansions, and hands the rest to IR1-CONVERT-COMMON-FUNCTOID suppresses compiler-macros. Handles the "common" cases: any other forms except special forms and compiler-macros. implicitly (LAMBDA ..) because the LAMBDA expression is the CAR of an executed form. Convert anything that looks like a global function call. FIXME: Couldn't all the INFO calls here be converted into errors which occur during the macroexpansion. Return a string to use as a prefix in error reporting, telling something about which form caused the problem. We rely on the printer to abbreviate FORM. longer message to avoid ambiguity "Was it the xc host or the cross-compiler which encountered the problem?" symbol warnings are often harmless forward references, and since it'd be inordinately painful to try to eliminate all such forward references, these warnings are basically unavoidable. Thus, we need to coerce the system to work through them, and this code does so, by crudely suppressing all warnings in cross-compilation conversion utilities Convert a bunch of forms, discarding all the values except the last. If there aren't any forms, then translate a NIL. code coverage Check the policy for whether we should generate code coverage ctran. Otherwise insert code coverage instrumentation after We don't actually use FORM for anything, it's just convenient to have around when debugging the instrumentation. If this source path has already been instrumented in this block, don't instrument it again. Get an interned record cons for the path. A cons with the same object identity must be used for each instrument for the same block. We're being naughty here, and modifying constant data. That's ok, we know what we're doing. In contexts where we don't have a source location for FORM e.g. due to it not being a cons, but where we have a source location for the enclosing cons, use the latter source location if macroexpansions will just directly splice a block of forms into EQness of the conses. converting combinations Does this form look like something that we should add single-stepping instrumentation for? stepping. the source for the call. We return the COMBINATION node so that the caller can poke at it if it wants to. Store a string representation of the form in the combination node. This will let the IR2 translator know that we want stepper instrumentation for this node. The string will be stored in the debug-info by DUMP-1-LOCATION. Convert the arguments to a call and make the COMBINATION node. FUN-LVAR yields the function to call. ARGS is the list of arguments for the call, which defaults to the cdr of source. We return the COMBINATION node. source transforms and try out any inline expansion. If there is no expansion, but is :INLINE, then give an efficiency note (unless a known function which will quite possibly be open-coded.) Next, we go to ok-combination conversion. attribute, don't generate any branch coverage instrumentation for it. If the function has the PREDICATE attribute, and the RESULT's DEST isn't an IF, then we convert (IF <form> T NIL), ensuring that a predicate always appears in a conditional context. If the function isn't a predicate, then we call IR1-CONVERT-COMBINATION-CHECKING-TYPE. Actually really convert a global function call that we are allowed to early-bind. If we know the function type of the function, then we check the call for syntactic legality with respect to the declared function type. If it is impossible to determine whether the call is correct due to non-constant keywords, then we give up, marking the call as :FULL to inhibit further error messages. We return true when the call is legal. If the call is legal, we also propagate type assertions from the function type to the arg and result lvars. We do this now so that IR1 optimize doesn't have to redundantly do the check later so that it can do the type propagation. Convert a call to a local function, or if the function has already are converting inline expansions for local functions during optimization. PROCESS-DECLS Given a list of LAMBDA-VARs and a variable name, return the *last* variable with that name, since LET* bindings may be duplicated, and declarations always apply to the last. Called by PROCESS-DECLS to deal with a variable type declaration. If a LAMBDA-VAR being bound, we intersect the type with the var's type, otherwise we add a type restriction on the var. If a symbol macro, we just wrap a THE around the expansion. FIXME: non-ANSI weirdness declarations for function variables. In addition to allowing declarations for functions being bound, we must also deal with declarations that constrain the type of lexically apparent functions. special declaration is instantiated by throwing a special variable into the variables if BINDING-FORM-P is NIL, or otherwise into *POST-BINDING-VARIABLE-LEXENV*. While CLHS seems to allow local SPECIAL declarations for constants, whatever the semantics are supposed to be is not at all clear to me -- since constants aren't allowed to be bound it should be a no-op as no-one can observe the difference portably, but specials are allowed to be bound... yet nowhere does it say that the special declaration removes the constantness. Call it a spec bug and prohibit it. Same for GLOBAL variables. requires that this be a STYLE-WARNING, not a full WARNING. (and TYPE if notinline), plus type-restrictions from the lexenv. FIXME: Is this really right? Needs we not set the FUNCTIONAL to the original global-var? Process an ignore/ignorable declaration, checking for various losing conditions. requires that this be a STYLE-WARNING, not a full WARNING. FIXME: This special case looks like non-ANSI weirdness. requires that this be a STYLE-WARNING, not a full WARNING. FIXME: This is non-ANSI, so the default should be T, or it should go away, I think. PROCESS-DECLS. and FUNCTIONAL structures which are being bound. In addition to which reflects pervasive special and function type declarations, (NOT)INLINE declarations and OPTIMIZE declarations, and type of value is a list of VARs that should not apply to the lexenv of the initialization forms for the bindings, but should apply to the body. This is also called in main.lisp when PROCESS-FORM handles a use of LOCALLY. declaration. If there is a global variable of that name, then check that it isn't a constant and return it. Otherwise, create an
to the first intermediate representation ( IR1 ) . 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!C") (declaim (special *compiler-error-bailout*)) (declaim (type index *current-form-number*)) (defvar *current-form-number*) macroexpansions and other arbitary permutations of the code this table , as 42 is EQ to 42 no matter where in the source it (declaim (hash-table *source-paths*)) (defvar *source-paths*) (declaim (inline source-form-has-path-p)) (defun source-form-has-path-p (form) (not (typep form '(or symbol fixnum character)))) (defun get-source-path (form) (when (source-form-has-path-p form) (gethash form *source-paths*))) (defun simplify-source-path-form (form) (if (consp form) (let ((op (car form))) (if (and (leaf-p op) (leaf-has-source-name-p op)) (cons (leaf-source-name op) (cdr form)) form)) form)) (defun note-source-path (form &rest arguments) (when (source-form-has-path-p form) (setf (gethash form *source-paths*) (apply #'list* 'original-source-start *current-form-number* arguments)))) FIXME : It 's confusing having one variable named * CURRENT - COMPONENT * and another named * COMPONENT - BEING - COMPILED * . ( In CMU CL they (declaim (type (or component null) *current-component*)) (defvar *current-component*) translating . See NODE - SOURCE - PATH in the NODE structure . (declaim (list *current-path*)) (defvar *current-path*) (defvar *derive-function-types* nil "Should the compiler assume that function types will never change, so that it can use type information inferred from current definitions to optimize code which uses those definitions? Setting this true gives non-ANSI, early-CMU-CL behavior. It can be useful for improving the efficiency of stable code.") (defvar *fun-names-in-this-file* nil) (defvar *post-binding-variable-lexenv* nil) (defun fun-lexically-notinline-p (name) (let ((fun (lexenv-find name funs :test #'equal))) (if (and fun (defined-fun-p fun)) (eq (defined-fun-inlinep fun) :notinline) (eq (info :function :inlinep name) :notinline)))) This will get redefined in PCL boot . (declaim (notinline maybe-update-info-for-gf)) (defun maybe-update-info-for-gf (name) (declare (ignore name)) nil) (defun maybe-defined-here (name where) (if (and (eq :defined where) (member name *fun-names-in-this-file* :test #'equal)) :defined-here where)) (defun find-global-fun (name latep) (unless (info :function :kind name) (setf (info :function :kind name) :function) (setf (info :function :where-from name) :assumed)) (let ((where (info :function :where-from name))) (when (and (eq where :assumed) In the ordinary target , it 's silly to report running . But at cross - compile time , the current #-sb-xc-host (not (fboundp name)) LATEP is true when the user has indicated that (not latep)) (note-undefined-reference name :function)) (let ((ftype (info :function :type name)) (notinline (fun-lexically-notinline-p name))) (make-global-var :kind :global-function :%source-name name :type (if (or (eq where :declared) (and (not latep) (not notinline) *derive-function-types*)) ftype (specifier-type 'function)) :defined-type (if (and (not latep) (not notinline)) (or (maybe-update-info-for-gf name) ftype) (specifier-type 'function)) :where-from (if notinline where (maybe-defined-here name where)))))) Have some DEFINED - FUN - FUNCTIONALS of a * FREE - FUNS * entry become invalid ? This was added to fix bug 138 in SBCL . It is possible for a * FREE - FUNS * contained IR1 stuff ( NODEs , BLOCKs ... ) referring to an already compiled Note : as of 1.0.24.41 this seems to happen only in XC , and the original (defun clear-invalid-functionals (free-fun) ( sbcl-0.pre7.118 ) is this one : (when (defined-fun-p free-fun) (setf (defined-fun-functionals free-fun) (delete-if (lambda (functional) (or (eq (functional-kind functional) :deleted) (when (lambda-p functional) (or ( The main reason for this first test is to bail call in the second test would fail because links If the BIND node for this LAMBDA is null , then (not (lambda-bind functional)) (eq (component-info (lambda-component functional)) :dead))))) (defined-fun-functionals free-fun))) nil)) the value . Otherwise , make a new GLOBAL - VAR using information from (declaim (ftype (sfunction (t string) global-var) find-free-fun)) (defun find-free-fun (name context) (or (let ((old-free-fun (gethash name *free-funs*))) (when old-free-fun (clear-invalid-functionals old-free-fun) old-free-fun)) (ecase (info :function :kind name) (:macro (compiler-error "The macro name ~S was found ~A." name context)) (:special-form (compiler-error "The special form name ~S was found ~A." name context)) ((:function nil) (check-fun-name name) (note-if-setf-fun-and-macro name) (let ((expansion (fun-name-inline-expansion name)) (inlinep (info :function :inlinep name))) (setf (gethash name *free-funs*) (if (or expansion inlinep) (let ((where (info :function :where-from name))) (make-defined-fun :%source-name name :inline-expansion expansion :inlinep inlinep :where-from (if (eq inlinep :notinline) where (maybe-defined-here name where)) :type (if (and (eq inlinep :notinline) (neq where :declared)) (specifier-type 'function) (info :function :type name)))) (find-global-fun name nil)))))))) Return the LEAF structure for the lexically apparent function (declaim (ftype (sfunction (t string) leaf) find-lexically-apparent-fun)) (defun find-lexically-apparent-fun (name context) (let ((var (lexenv-find name funs :test #'equal))) (cond (var (unless (leaf-p var) (aver (and (consp var) (eq (car var) 'macro))) (compiler-error "found macro name ~S ~A" name context)) var) (t (find-free-fun name context))))) (defun maybe-find-free-var (name) (gethash name *free-vars*)) Return the LEAF node for a global variable reference to NAME . If (declaim (ftype (sfunction (t) (or leaf cons heap-alien-info)) find-free-var)) (defun find-free-var (name) (unless (symbolp name) (compiler-error "Variable name is not a symbol: ~S." name)) (or (gethash name *free-vars*) (let ((kind (info :variable :kind name)) (type (info :variable :type name)) (where-from (info :variable :where-from name))) (when (eq kind :unknown) (note-undefined-reference name :variable)) (setf (gethash name *free-vars*) (case kind (:alien (info :variable :alien-info name)) because the MACRO idiom is scattered throughout this throwing random conses around . --njf 2002 - 03 - 23 (:macro (let ((expansion (info :variable :macro-expansion name)) (type (type-specifier (info :variable :type name)))) `(macro . (the ,type ,expansion)))) (:constant (let ((value (symbol-value name))) Override the values of standard symbols in XC , #+sb-xc-host (when (eql (find-symbol (symbol-name name) :cl) name) (multiple-value-bind (xc-value foundp) (info :variable :xc-constant-value name) (cond (foundp (setf value xc-value)) ((not (eq value name)) (compiler-warn "Using cross-compilation host's definition of ~S: ~A~%" name (symbol-value name)))))) (find-constant value name))) (t (make-global-var :kind kind :%source-name name :type type :where-from where-from))))))) (defun maybe-emit-make-load-forms (constant &optional (name nil namep)) (let ((xset (alloc-xset))) (labels ((trivialp (value) (typep value '(or #-sb-xc-host unboxed-array #+sb-xc-host (simple-array (unsigned-byte 8) (*)) symbol number character string))) (grovel (value) Unless VALUE is an object which which obviously (unless (trivialp value) (if (xset-member-p value xset) (return-from grovel nil) (add-to-xset value xset)) (typecase value (cons (grovel (car value)) (grovel (cdr value))) (simple-vector (dotimes (i (length value)) (grovel (svref value i)))) ((vector t) (dotimes (i (length value)) (grovel (aref value i)))) ((simple-array t) (dotimes (i (array-total-size value)) (grovel (row-major-aref value i)))) ((array t) (dotimes (i (array-total-size value)) (grovel (row-major-aref value i)))) (#+sb-xc-host structure!object #-sb-xc-host instance In the target SBCL , we can dump any instance , but STRUCTURE!OBJECTs . (when (emit-make-load-form value) (dotimes (i (- (%instance-length value) #+sb-xc-host 0 #-sb-xc-host (layout-n-untagged-slots (%instance-ref value 0)))) (grovel (%instance-ref value i))))) (t (compiler-error "Objects of type ~S can't be dumped into fasl files." (type-of value))))))) (if (and namep (not (typep constant '(or symbol character try to reference FP constants #+sb-xc-host number #-sb-xc-host fixnum)))) (emit-make-load-form constant name) (grovel constant)))) (values)) (defun link-node-to-previous-ctran (node ctran) (declare (type node node) (type ctran ctran)) (aver (not (ctran-next ctran))) (setf (ctran-next ctran) node) (setf (node-prev node) ctran)) #!-sb-fluid (declaim (inline use-ctran)) (defun use-ctran (node ctran) (declare (type node node) (type ctran ctran)) (if (eq (ctran-kind ctran) :unused) (let ((node-block (ctran-block (node-prev node)))) (setf (ctran-block ctran) node-block) (setf (ctran-kind ctran) :inside-block) (setf (ctran-use ctran) node) (setf (node-next node) ctran)) (%use-ctran node ctran))) (defun %use-ctran (node ctran) (declare (type node node) (type ctran ctran) (inline member)) (let ((block (ctran-block ctran)) (node-block (ctran-block (node-prev node)))) (aver (eq (ctran-kind ctran) :block-start)) (when (block-last node-block) (error "~S has already ended." node-block)) (setf (block-last node-block) node) (when (block-succ node-block) (error "~S already has successors." node-block)) (setf (block-succ node-block) (list block)) (when (memq node-block (block-pred block)) (error "~S is already a predecessor of ~S." node-block block)) (push node-block (block-pred block)))) (defun insert-node-before (old new) (let ((prev (node-prev old)) (temp (make-ctran))) (ensure-block-start prev) (setf (ctran-next prev) nil) (link-node-to-previous-ctran new prev) (use-ctran new temp) (link-node-to-previous-ctran old temp)) (values)) (defun use-lvar (node lvar) (declare (type valued-node node) (type (or lvar null) lvar)) (aver (not (node-lvar node))) (when lvar (setf (node-lvar node) lvar) (cond ((null (lvar-uses lvar)) (setf (lvar-uses lvar) node)) ((listp (lvar-uses lvar)) (aver (not (memq node (lvar-uses lvar)))) (push node (lvar-uses lvar))) (t (aver (neq node (lvar-uses lvar))) (setf (lvar-uses lvar) (list node (lvar-uses lvar))))) (reoptimize-lvar lvar))) #!-sb-fluid(declaim (inline use-continuation)) (defun use-continuation (node ctran lvar) (use-ctran node ctran) (use-lvar node lvar)) otherwise NIL is returned . due to processing of EVAL - WHENs . All syntax error checking is We make the initial component and convert the form in a PROGN ( and an optional NIL tacked on the end . ) We then return the lambda . We This is necessary for EVAL - WHEN processing , etc . (defun ir1-toplevel (form path for-value &optional (allow-instrumenting t)) (declare (list path)) (let* ((*current-path* path) (component (make-empty-component)) (*current-component* component) (*allow-instrumenting* allow-instrumenting)) (setf (component-name component) 'initial-component) (setf (component-kind component) :initial) (let* ((forms (if for-value `(,form) `(,form nil))) (res (ir1-convert-lambda-body forms () :debug-name (debug-name 'top-level-form #+sb-xc-host nil #-sb-xc-host form)))) (setf (functional-entry-fun res) res (functional-arg-documentation res) () (functional-kind res) :toplevel) res))) find the paths in , and TLF - NUM is the top level form number of the (defun find-source-paths (form tlf-num) (declare (type index tlf-num)) (let ((*current-form-number* 0)) (sub-find-source-paths form (list tlf-num))) (values)) (defun sub-find-source-paths (form path) (unless (get-source-path form) (note-source-path form path) (incf *current-form-number*) (let ((pos 0) (subform form) (trail form)) (declare (fixnum pos)) (macrolet ((frob () `(progn (when (atom subform) (return)) (let ((fm (car subform))) (cond ((consp fm) (sub-find-source-paths fm (cons pos path))) ((eq 'quote fm) (return)) ((not (zerop pos)) (note-source-path subform pos path))) (incf pos)) (setq subform (cdr subform)) (when (eq subform trail) (return))))) (loop (frob) (frob) (setq trail (cdr trail))))))) (declaim (ftype (sfunction (ctran ctran (or lvar null) t) (values)) ir1-convert)) (ir1-error-bailout ((start next result form) &body body) (with-unique-names (skip condition) `(block ,skip (let ((,condition (catch 'ir1-error-abort (let ((*compiler-error-bailout* (lambda (&optional e) (throw 'ir1-error-abort e)))) ,@body (return-from ,skip nil))))) (ir1-convert ,start ,next ,result (make-compiler-error-form ,condition ,form))))))) Translate FORM into IR1 . The code is inserted as the NEXT of the CTRAN START . RESULT is the LVAR which receives the value of the As a special hack to make life easier in the compiler , a LEAF IR1 - converts into a reference to that LEAF structure . This allows (defun ir1-convert (start next result form) (ir1-error-bailout (start next result form) (let* ((*current-path* (or (get-source-path form) (cons (simplify-source-path-form form) *current-path*))) (start (instrument-coverage start nil form))) (cond ((atom form) (cond ((and (symbolp form) (not (keywordp form))) (ir1-convert-var start next result form)) ((leaf-p form) (reference-leaf start next result form)) (t (reference-constant start next result form)))) (t (ir1-convert-functoid start next result form))))) (values)) (defun reference-constant (start next result value) (declare (type ctran start next) (type (or lvar null) result)) (ir1-error-bailout (start next result value) (let* ((leaf (find-constant value)) (res (make-ref leaf))) (push res (leaf-refs leaf)) (link-node-to-previous-ctran res start) (use-continuation res next result))) (values))) (defun maybe-reanalyze-functional (functional) bug 148 (aver-live-component *current-component*) no - op (when (typep functional '(or optional-dispatch clambda)) (when (lambda-p functional) (aver (eql (lambda-component functional) *current-component*))) (pushnew functional (component-reanalyze-functionals *current-component*))) functional) Generate a REF node for LEAF , frobbing the LEAF structure as needed . If LEAF represents a defined function which has already been converted , and is not : NOTINLINE , then reference the (defun reference-leaf (start next result leaf &optional (name '.anonymous.)) (declare (type ctran start next) (type (or lvar null) result) (type leaf leaf)) (assure-leaf-live-p leaf) (let* ((type (lexenv-find leaf type-restrictions)) (leaf (or (and (defined-fun-p leaf) (not (eq (defined-fun-inlinep leaf) :notinline)) (let ((functional (defined-fun-functional leaf))) (when (and functional (not (functional-kind functional))) (maybe-reanalyze-functional functional)))) (when (and (lambda-p leaf) (memq (functional-kind leaf) '(nil :optional))) (maybe-reanalyze-functional leaf)) leaf)) (ref (make-ref leaf name))) (push ref (leaf-refs leaf)) (setf (leaf-ever-used leaf) t) (link-node-to-previous-ctran ref start) (cond (type (let* ((ref-ctran (make-ctran)) (ref-lvar (make-lvar)) (cast (make-cast ref-lvar (make-single-value-type type) (lexenv-policy *lexenv*)))) (setf (lvar-dest ref-lvar) cast) (use-continuation ref ref-ctran ref-lvar) (link-node-to-previous-ctran cast ref-ctran) (use-continuation cast next result))) (t (use-continuation ref next result))))) (defun ir1-convert-var (start next result name) (declare (type ctran start next) (type (or lvar null) result) (symbol name)) (let ((var (or (lexenv-find name vars) (find-free-var name)))) (if (and (global-var-p var) (not result)) : If the reference is dead , convert using SYMBOL - VALUE an error ( bug 412 ) . (ir1-convert start next result (if (eq (global-var-kind var) :global) `(symbol-global-value ',name) `(symbol-value ',name))) (etypecase var (leaf (when (lambda-var-p var) (let ((home (ctran-home-lambda-or-null start))) (when home (sset-adjoin var (lambda-calls-or-closes home)))) (when (lambda-var-ignorep var) ( ANSI 's specification for the IGNORE declaration requires #-sb-xc-host (compiler-style-warn "reading an ignored variable: ~S" name) there 's no need for us to accept ANSI 's lameness when #+sb-xc-host (warn "reading an ignored variable: ~S" name))) (reference-leaf start next result var name)) (cons (aver (eq (car var) 'macro)) FIXME : [ Free ] type declarations . -- APD , 2002 - 01 - 26 (ir1-convert start next result (cdr var))) (heap-alien-info (ir1-convert start next result `(%heap-alien ',var)))))) (values)) (defun find-compiler-macro (opname form) (if (eq opname 'funcall) (let ((fun-form (cadr form))) (cond ((and (consp fun-form) (eq 'function (car fun-form))) (let ((real-fun (cadr fun-form))) (if (legal-fun-name-p real-fun) (values (sb!xc:compiler-macro-function real-fun *lexenv*) real-fun) (values nil nil)))) ((sb!xc:constantp fun-form *lexenv*) (let ((fun (constant-form-value fun-form *lexenv*))) (if (legal-fun-name-p fun) (values (sb!xc:compiler-macro-function fun nil) fun) (values nil nil)))) (t (values nil nil)))) (if (legal-fun-name-p opname) (values (sb!xc:compiler-macro-function opname *lexenv*) opname) (values nil nil)))) (defun ir1-convert-functoid (start next result form) (let* ((op (car form)) (translator (and (symbolp op) (info :function :ir1-convert op)))) (cond (translator (when (sb!xc:compiler-macro-function op *lexenv*) (compiler-warn "ignoring compiler macro for special form")) (funcall translator start next result form)) (t (multiple-value-bind (cmacro-fun cmacro-fun-name) (find-compiler-macro op form) (if (and cmacro-fun CLHS 3.2.2.1.3 specifies that NOTINLINE (not (fun-lexically-notinline-p cmacro-fun-name))) (let ((res (careful-expand-macro cmacro-fun form t))) (cond ((eq res form) (ir1-convert-common-functoid start next result form op)) (t (unless (policy *lexenv* (zerop store-xref-data)) (record-call cmacro-fun-name (ctran-block start) *current-path*)) (ir1-convert start next result res)))) (ir1-convert-common-functoid start next result form op))))))) (defun ir1-convert-common-functoid (start next result form op) (cond ((or (symbolp op) (leaf-p op)) (let ((lexical-def (if (leaf-p op) op (lexenv-find op funs)))) (typecase lexical-def (null (ir1-convert-global-functoid start next result form op)) (functional (ir1-convert-local-combination start next result form lexical-def)) (global-var (ir1-convert-srctran start next result lexical-def form)) (t (aver (and (consp lexical-def) (eq (car lexical-def) 'macro))) (ir1-convert start next result (careful-expand-macro (cdr lexical-def) form)))))) ((or (atom op) (not (eq (car op) 'lambda))) (compiler-error "illegal function call")) (t (ir1-convert-combination start next result form (ir1-convert-lambda op :debug-name (debug-name 'inline-lambda op)))))) (defun ir1-convert-global-functoid (start next result form fun) (declare (type ctran start next) (type (or lvar null) result) (list form)) standard CL functions , like MACRO - FUNCTION or something ? And what happens with lexically - defined ( MACROLET ) macros here , anyway ? (ecase (info :function :kind fun) (:macro (ir1-convert start next result (careful-expand-macro (info :function :macro-function fun) form)) (unless (policy *lexenv* (zerop store-xref-data)) (record-macroexpansion fun (ctran-block start) *current-path*))) ((nil :function) (ir1-convert-srctran start next result (find-free-fun fun "shouldn't happen! (no-cmacro)") form)))) (defun muffle-warning-or-die () (muffle-warning) (bug "no MUFFLE-WARNING restart")) Expand FORM using the macro whose MACRO - FUNCTION is FUN , trapping (defun careful-expand-macro (fun form &optional cmacro) (wherestring () (*print-length* 3) (*print-level* 3)) (format nil #-sb-xc-host "~@<~;during ~A of ~S. Use ~S to intercept:~%~:@>" #+sb-xc-host "~@<~;during cross-compiler ~A of ~S. Use ~S to intercept:~%~:@>" (if cmacro "compiler-macroexpansion" "macroexpansion") form '*break-on-signals*)))) : CMU CL in its wisdom ( version 2.4.6 for Debian Linux , anyway ) raises a CL : WARNING condition ( not a CL : STYLE - WARNING ) for undefined symbols when converting interpreted functions , causing COMPILE - FILE to think the file has a real problem , causing COMPILE - FILE to return FAILURE - P set ( not just WARNINGS - P set ) . Since undefined macroexpansion . -- WHN 19990412 #+(and cmu sb-xc-host) (warning (lambda (c) (compiler-notify "~@<~A~:@_~ ~A~:@_~ ~@<(KLUDGE: That was a non-STYLE WARNING. ~ Ordinarily that would cause compilation to ~ fail. However, since we're running under ~ CMU CL, and since CMU CL emits non-STYLE ~ warnings for safe, hard-to-fix things (e.g. ~ references to not-yet-defined functions) ~ we're going to have to ignore it and ~ proceed anyway. Hopefully we're not ~ ignoring anything horrible here..)~:@>~:>" (wherestring) c) (muffle-warning-or-die))) (error (lambda (c) (compiler-error "~@<~A~@:_ ~A~:>" (wherestring) c)))) (funcall sb!xc:*macroexpand-hook* fun form *lexenv*)))) (declaim (ftype (sfunction (ctran ctran (or lvar null) list) (values)) ir1-convert-progn-body)) (defun ir1-convert-progn-body (start next result body) (if (endp body) (reference-constant start next result nil) (let ((this-start start) (forms body)) (loop (let ((form (car forms))) (setf this-start (maybe-instrument-progn-like this-start forms form)) (when (endp (cdr forms)) (ir1-convert this-start next result form) (return)) (let ((this-ctran (make-ctran))) (ir1-convert this-start this-ctran nil form) (setq this-start this-ctran forms (cdr forms))))))) (values)) instrumentation . If not , just return the original START START , and return the new ctran . (defun instrument-coverage (start mode form) (declare (ignore form)) (if (and (policy *lexenv* (> store-coverage-data 0)) *code-coverage-records* *allow-instrumenting*) (let ((path (source-path-original-source *current-path*))) (when mode (push mode path)) (if (member (ctran-block start) (gethash path *code-coverage-blocks*)) start (let ((store (or (gethash path *code-coverage-records*) (setf (gethash path *code-coverage-records*) (cons path +code-coverage-unmarked+)))) (next (make-ctran)) (*allow-instrumenting* nil)) (push (ctran-block start) (gethash path *code-coverage-blocks*)) (let ((*allow-instrumenting* nil)) (ir1-convert start next nil `(locally (declare (optimize speed (safety 0) (debug 0) (check-constant-modification 0))) (%rplacd ',store t)))) next))) start)) available . This works pretty well in practice , since many PROGNish some enclosing form with ` ( progn , @body ) , thus retaining the (defun maybe-instrument-progn-like (start forms form) (or (when (and *allow-instrumenting* (not (get-source-path form))) (let ((*current-path* (get-source-path forms))) (when *current-path* (instrument-coverage start nil form)))) start)) (defun record-code-coverage (info cc) (setf (gethash info *code-coverage-info*) cc)) (defun clear-code-coverage () (clrhash *code-coverage-info*)) (defun reset-code-coverage () (maphash (lambda (info cc) (declare (ignore info)) (dolist (cc-entry cc) (setf (cdr cc-entry) +code-coverage-unmarked+))) *code-coverage-info*)) (defun code-coverage-record-marked (record) (aver (consp record)) (ecase (cdr record) ((#.+code-coverage-unmarked+) nil) ((t) t))) (defun step-form-p (form) (flet ((step-symbol-p (symbol) (not (member (symbol-package symbol) (load-time-value : packages we 're not interested in (mapcar #'find-package '(sb!c sb!int sb!impl sb!kernel sb!pcl))))))) (and *allow-instrumenting* (policy *lexenv* (= insert-step-conditions 3)) (listp form) (symbolp (car form)) (step-symbol-p (car form))))) Convert a function call where the function FUN is a LEAF . FORM is (declaim (ftype (sfunction (ctran ctran (or lvar null) list leaf) combination) ir1-convert-combination)) (defun ir1-convert-combination (start next result form fun) (let ((ctran (make-ctran)) (fun-lvar (make-lvar))) (ir1-convert start ctran fun-lvar `(the (or function symbol) ,fun)) (let ((combination (ir1-convert-combination-args fun-lvar ctran next result (cdr form)))) (when (step-form-p form) (setf (combination-step-info combination) (let ((*print-pretty* t) (*print-circle* t) (*print-readably* nil)) (prin1-to-string form)))) combination))) (defun ir1-convert-combination-args (fun-lvar start next result args) (declare (type ctran start next) (type lvar fun-lvar) (type (or lvar null) result) (list args)) (let ((node (make-combination fun-lvar))) (setf (lvar-dest fun-lvar) node) (collect ((arg-lvars)) (let ((this-start start) (forms args)) (dolist (arg args) (setf this-start (maybe-instrument-progn-like this-start forms arg)) (setf forms (cdr forms)) (let ((this-ctran (make-ctran)) (this-lvar (make-lvar node))) (ir1-convert this-start this-ctran this-lvar arg) (setq this-start this-ctran) (arg-lvars this-lvar))) (link-node-to-previous-ctran node this-start) (use-continuation node next result) (setf (combination-args node) (arg-lvars)))) node)) Convert a call to a global function . If not : NOTINLINE , then we do (defun ir1-convert-srctran (start next result var form) (declare (type ctran start next) (type (or lvar null) result) (type global-var var)) (let ((inlinep (when (defined-fun-p var) (defined-fun-inlinep var)))) (if (eq inlinep :notinline) (ir1-convert-combination start next result form var) (let* ((name (leaf-source-name var)) (transform (info :function :source-transform name))) (if transform (multiple-value-bind (transformed pass) (funcall transform form) (cond (pass (ir1-convert-maybe-predicate start next result form var)) (t (unless (policy *lexenv* (zerop store-xref-data)) (record-call name (ctran-block start) *current-path*)) (ir1-convert start next result transformed)))) (ir1-convert-maybe-predicate start next result form var)))))) : If we insert a synthetic IF for a function with the PREDICATE (defvar *instrument-if-for-code-coverage* t) (defun ir1-convert-maybe-predicate (start next result form var) (declare (type ctran start next) (type (or lvar null) result) (list form) (type global-var var)) (let ((info (info :function :info (leaf-source-name var)))) (if (and info (ir1-attributep (fun-info-attributes info) predicate) (not (if-p (and result (lvar-dest result))))) (let ((*instrument-if-for-code-coverage* nil)) (ir1-convert start next result `(if ,form t nil))) (ir1-convert-combination-checking-type start next result form var)))) (defun ir1-convert-combination-checking-type (start next result form var) (declare (type ctran start next) (type (or lvar null) result) (list form) (type leaf var)) (let* ((node (ir1-convert-combination start next result form var)) (fun-lvar (basic-combination-fun node)) (type (leaf-type var))) (when (validate-call-type node type var t) (setf (lvar-%derived-type fun-lvar) (make-single-value-type type)) (setf (lvar-reoptimize fun-lvar) nil))) (values)) been LET converted , then throw FUNCTIONAL to LOCALL - ALREADY - LET - CONVERTED . The THROW should only happen when we (defun ir1-convert-local-combination (start next result form functional) (assure-functional-live-p functional) (ir1-convert-combination start next result form (maybe-reanalyze-functional functional))) for that name , or NIL if it is n't found . We return the (declaim (ftype (sfunction (list symbol) (or lambda-var list)) find-in-bindings)) (defun find-in-bindings (vars name) (let ((found nil)) (dolist (var vars) (cond ((leaf-p var) (when (eq (leaf-source-name var) name) (setq found var)) (let ((info (lambda-var-arg-info var))) (when info (let ((supplied-p (arg-info-supplied-p info))) (when (and supplied-p (eq (leaf-source-name supplied-p) name)) (setq found supplied-p)))))) ((and (consp var) (eq (car var) name)) (setf found (cdr var))))) found)) (defun process-type-decl (decl res vars context) (declare (list decl vars) (type lexenv res)) (let ((type (compiler-specifier-type (first decl)))) (collect ((restr nil cons) (new-vars nil cons)) (dolist (var-name (rest decl)) (when (boundp var-name) (program-assert-symbol-home-package-unlocked context var-name "declaring the type of ~A")) (let* ((bound-var (find-in-bindings vars var-name)) (var (or bound-var (lexenv-find var-name vars) (find-free-var var-name)))) (etypecase var (leaf (flet ((process-var (var bound-var) (let* ((old-type (or (lexenv-find var type-restrictions) (leaf-type var))) (int (if (or (fun-type-p type) (fun-type-p old-type)) type (type-approx-intersection2 old-type type)))) (cond ((eq int *empty-type*) (unless (policy *lexenv* (= inhibit-warnings 3)) (warn 'type-warning :format-control "The type declarations ~S and ~S for ~S conflict." :format-arguments (list (type-specifier old-type) (type-specifier type) var-name)))) (bound-var (setf (leaf-type bound-var) int (leaf-where-from bound-var) :declared)) (t (restr (cons var int))))))) (process-var var bound-var) (awhen (and (lambda-var-p var) (lambda-var-specvar var)) (process-var it nil)))) (cons (aver (eq (car var) 'macro)) (new-vars `(,var-name . (macro . (the ,(first decl) ,(cdr var)))))) (heap-alien-info (compiler-error "~S is an alien variable, so its type can't be declared." var-name))))) (if (or (restr) (new-vars)) (make-lexenv :default res :type-restrictions (restr) :vars (new-vars)) res)))) This is somewhat similar to PROCESS - TYPE - , but handles (defun process-ftype-decl (spec res names fvars context) (declare (type list names fvars) (type lexenv res)) (let ((type (compiler-specifier-type spec))) (collect ((res nil cons)) (dolist (name names) (when (fboundp name) (program-assert-symbol-home-package-unlocked context name "declaring the ftype of ~A")) (let ((found (find name fvars :key #'leaf-source-name :test #'equal))) (cond (found (setf (leaf-type found) type) (assert-definition-type found type :unwinnage-fun #'compiler-notify :where "FTYPE declaration")) (t (res (cons (find-lexically-apparent-fun name "in a function type declaration") type)))))) (if (res) (make-lexenv :default res :type-restrictions (res)) res)))) Process a special declaration , returning a new LEXENV . A non - bound (defun process-special-decl (spec res vars binding-form-p context) (declare (list spec vars) (type lexenv res)) (collect ((new-venv nil cons)) (dolist (name (cdr spec)) (let ((kind (info :variable :kind name))) (unless (member kind '(:special :unknown)) (error "Can't declare ~(~A~) variable locally special: ~S" kind name))) (program-assert-symbol-home-package-unlocked context name "declaring ~A special") (let ((var (find-in-bindings vars name))) (etypecase var (cons (aver (eq (car var) 'macro)) (compiler-error "~S is a symbol-macro and thus can't be declared special." name)) (lambda-var (when (lambda-var-ignorep var) ANSI 's definition for " Declaration IGNORE , IGNORABLE " (compiler-style-warn "The ignored variable ~S is being declared special." name)) (setf (lambda-var-specvar var) (specvar-for-binding name))) (null (unless (or (assoc name (new-venv) :test #'eq)) (new-venv (cons name (specvar-for-binding name)))))))) (cond (binding-form-p (setf *post-binding-variable-lexenv* (append (new-venv) *post-binding-variable-lexenv*)) res) ((new-venv) (make-lexenv :default res :vars (new-venv))) (t res)))) Return a DEFINED - FUN which copies a GLOBAL - VAR but for its INLINEP (defun make-new-inlinep (var inlinep local-type) (declare (type global-var var) (type inlinep inlinep)) (let* ((type (if (and (eq inlinep :notinline) (not (eq (leaf-where-from var) :declared))) (specifier-type 'function) (leaf-type var))) (res (make-defined-fun :%source-name (leaf-source-name var) :where-from (leaf-where-from var) :type (if local-type (type-intersection local-type type) type) :inlinep inlinep))) (when (defined-fun-p var) (setf (defined-fun-inline-expansion res) (defined-fun-inline-expansion var)) (setf (defined-fun-functionals res) (defined-fun-functionals var))) res)) Parse an inline / notinline declaration . If it 's a local function we 're defining , set its INLINEP . If a global function , add a new FENV entry . (defun process-inline-decl (spec res fvars) (let ((sense (cdr (assoc (first spec) *inlinep-translations* :test #'eq))) (new-fenv ())) (dolist (name (rest spec)) (let ((fvar (find name fvars :key #'leaf-source-name :test #'equal))) (if fvar (setf (functional-inlinep fvar) sense) (let ((found (find-lexically-apparent-fun name "in an inline or notinline declaration"))) (etypecase found (functional (when (policy *lexenv* (>= speed inhibit-warnings)) (compiler-notify "ignoring ~A declaration not at ~ definition of local function:~% ~S" sense name))) (global-var (let ((type (cdr (assoc found (lexenv-type-restrictions res))))) (push (cons name (make-new-inlinep found sense type)) new-fenv)))))))) (if new-fenv (make-lexenv :default res :funs new-fenv) res))) like FIND - IN - BINDINGS , but looks for # ' FOO in the FVARS (defun find-in-bindings-or-fbindings (name vars fvars) (declare (list vars fvars)) (if (consp name) (destructuring-bind (wot fn-name) name (unless (eq wot 'function) (compiler-error "The function or variable name ~S is unrecognizable." name)) (find fn-name fvars :key #'leaf-source-name :test #'equal)) (find-in-bindings vars name))) (defun process-ignore-decl (spec vars fvars) (declare (list spec vars fvars)) (dolist (name (rest spec)) (let ((var (find-in-bindings-or-fbindings name vars fvars))) (cond ((not var) ANSI 's definition for " Declaration IGNORE , IGNORABLE " (compiler-style-warn "declaring unknown variable ~S to be ignored" name)) ((and (consp var) (eq (car var) 'macro)) Just ignore the IGNORE . ) ((functional-p var) (setf (leaf-ever-used var) t)) ((and (lambda-var-specvar var) (eq (first spec) 'ignore)) ANSI 's definition for " Declaration IGNORE , IGNORABLE " (compiler-style-warn "declaring special variable ~S to be ignored" name)) ((eq (first spec) 'ignorable) (setf (leaf-ever-used var) t)) (t (setf (lambda-var-ignorep var) t))))) (values)) (defun process-dx-decl (names vars fvars kind) (let ((dx (cond ((eq 'truly-dynamic-extent kind) :truly) ((and (eq 'dynamic-extent kind) *stack-allocate-dynamic-extent*) t)))) (if dx (dolist (name names) (cond ((symbolp name) (let* ((bound-var (find-in-bindings vars name)) (var (or bound-var (lexenv-find name vars) (maybe-find-free-var name)))) (etypecase var (leaf (if bound-var (setf (leaf-dynamic-extent var) dx) (compiler-notify "Ignoring free DYNAMIC-EXTENT declaration: ~S" name))) (cons (compiler-error "DYNAMIC-EXTENT on symbol-macro: ~S" name)) (heap-alien-info (compiler-error "DYNAMIC-EXTENT on alien-variable: ~S" name)) (null (compiler-style-warn "Unbound variable declared DYNAMIC-EXTENT: ~S" name))))) ((and (consp name) (eq (car name) 'function) (null (cddr name)) (valid-function-name-p (cadr name))) (let* ((fname (cadr name)) (bound-fun (find fname fvars :key #'leaf-source-name :test #'equal)) (fun (or bound-fun (lexenv-find fname funs)))) (etypecase fun (leaf (if bound-fun #!+stack-allocatable-closures (setf (leaf-dynamic-extent bound-fun) dx) #!-stack-allocatable-closures (compiler-notify "Ignoring DYNAMIC-EXTENT declaration on function ~S ~ (not supported on this platform)." fname) (compiler-notify "Ignoring free DYNAMIC-EXTENT declaration: ~S" name))) (cons (compiler-error "DYNAMIC-EXTENT on macro: ~S" name)) (null (compiler-style-warn "Unbound function declared DYNAMIC-EXTENT: ~S" name))))) (t (compiler-error "DYNAMIC-EXTENT on a weird thing: ~S" name)))) (when (policy *lexenv* (= speed 3)) (compiler-notify "Ignoring DYNAMIC-EXTENT declarations: ~S" names))))) (defvar *suppress-values-declaration* nil #!+sb-doc "If true, processing of the VALUES declaration is inhibited.") Process a single declaration spec , augmenting the specified LEXENV RES . Return RES and result type . VARS and FVARS are as described (defun process-1-decl (raw-spec res vars fvars binding-form-p context) (declare (type list raw-spec vars fvars)) (declare (type lexenv res)) (let ((spec (canonized-decl-spec raw-spec)) (result-type *wild-type*)) (values (case (first spec) (special (process-special-decl spec res vars binding-form-p context)) (ftype (unless (cdr spec) (compiler-error "no type specified in FTYPE declaration: ~S" spec)) (process-ftype-decl (second spec) res (cddr spec) fvars context)) ((inline notinline maybe-inline) (process-inline-decl spec res fvars)) ((ignore ignorable) (process-ignore-decl spec vars fvars) res) (optimize (make-lexenv :default res :policy (process-optimize-decl spec (lexenv-policy res)))) (muffle-conditions (make-lexenv :default res :handled-conditions (process-muffle-conditions-decl spec (lexenv-handled-conditions res)))) (unmuffle-conditions (make-lexenv :default res :handled-conditions (process-unmuffle-conditions-decl spec (lexenv-handled-conditions res)))) (type (process-type-decl (cdr spec) res vars context)) (values (unless *suppress-values-declaration* (let ((types (cdr spec))) (setq result-type (compiler-values-specifier-type (if (singleton-p types) (car types) `(values ,@types))))) res)) ((dynamic-extent truly-dynamic-extent) (process-dx-decl (cdr spec) vars fvars (first spec)) res) ((disable-package-locks enable-package-locks) (make-lexenv :default res :disabled-package-locks (process-package-lock-decl spec (lexenv-disabled-package-locks res)))) (t (unless (info :declaration :recognized (first spec)) (compiler-warn "unrecognized declaration ~S" raw-spec)) (let ((fn (info :declaration :handler (first spec)))) (if fn (funcall fn res spec vars fvars) res)))) result-type))) Use a list of DECLARE forms to annotate the lists of filling in slots in the leaf structures , we return a new LEXENV , VALUES declarations . If BINDING - FORM - P is true , the third return (defun process-decls (decls vars fvars &key (lexenv *lexenv*) (binding-form-p nil) (context :compile)) (declare (list decls vars fvars)) (let ((result-type *wild-type*) (*post-binding-variable-lexenv* nil)) (dolist (decl decls) (dolist (spec (rest decl)) (progv : EVAL calls this function to deal with LOCALLY . (when (eq context :compile) (list '*current-path*)) (when (eq context :compile) (list (or (get-source-path spec) (get-source-path decl) *current-path*))) (unless (consp spec) (compiler-error "malformed declaration specifier ~S in ~S" spec decl)) (multiple-value-bind (new-env new-result-type) (process-1-decl spec lexenv vars fvars binding-form-p context) (setq lexenv new-env) (unless (eq new-result-type *wild-type*) (setq result-type (values-type-intersection result-type new-result-type))))))) (values lexenv result-type *post-binding-variable-lexenv*))) (defun %processing-decls (decls vars fvars ctran lvar binding-form-p fun) (multiple-value-bind (*lexenv* result-type post-binding-lexenv) (process-decls decls vars fvars :binding-form-p binding-form-p) (cond ((eq result-type *wild-type*) (funcall fun ctran lvar post-binding-lexenv)) (t (let ((value-ctran (make-ctran)) (value-lvar (make-lvar))) (multiple-value-prog1 (funcall fun value-ctran value-lvar post-binding-lexenv) (let ((cast (make-cast value-lvar result-type (lexenv-policy *lexenv*)))) (link-node-to-previous-ctran cast value-ctran) (setf (lvar-dest value-lvar) cast) (use-continuation cast ctran lvar)))))))) (defmacro processing-decls ((decls vars fvars ctran lvar &optional post-binding-lexenv) &body forms) (check-type ctran symbol) (check-type lvar symbol) (let ((post-binding-lexenv-p (not (null post-binding-lexenv))) (post-binding-lexenv (or post-binding-lexenv (sb!xc:gensym "LEXENV")))) `(%processing-decls ,decls ,vars ,fvars ,ctran ,lvar ,post-binding-lexenv-p (lambda (,ctran ,lvar ,post-binding-lexenv) (declare (ignorable ,post-binding-lexenv)) ,@forms)))) Return the SPECVAR for NAME to use when we see a local SPECIAL anonymous GLOBAL - VAR . (defun specvar-for-binding (name) (cond ((not (eq (info :variable :where-from name) :assumed)) (let ((found (find-free-var name))) (when (heap-alien-info-p found) (compiler-error "~S is an alien variable and so can't be declared special." name)) (unless (global-var-p found) (compiler-error "~S is a constant and so can't be declared special." name)) found)) (t (make-global-var :kind :special :%source-name name :where-from :declared))))
ce661e2d3228498c14ff26938c3c5eaeb868088d6696a4bc54d089d8b7a0e6b8
clojurecup2014/parade-route
celsius.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ;;; A Celsius/Fahrenheit converter A WinForms equivalent to the Swing app shown here : If you are running on .Net 4 , you will have to change this . (System.Reflection.Assembly/Load "System.Windows.Forms,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") (import '(System.Drawing Size) '(System.Windows.Forms Form TableLayoutPanel Label Button TextBox PaintEventHandler PaintEventArgs) ) (defn celsius [] (let [form (Form.) panel (TableLayoutPanel.) p-controls (.Controls panel) tb (TextBox.) c-label (Label.) button (Button.) f-label (Label.)] (.set_Text form "Celsius Converter") (.set_Text c-label "Celsius") (.set_Text f-label "Fahrenheit") (.set_Text button "Convert") (.. form (Controls) (Add panel)) (.add_Click button (gen-delegate EventHandler [sender args] (let [c (Double/Parse (.Text tb)) ] (.set_Text f-label (str (+ 32 (* 1.8 c)) " Fahrenheit"))))) (doto panel (.set_ColumnCount 2) (.set_RowCount 2)) (doto p-controls (.Add tb) (.Add c-label) (.Add button) (.Add f-label)) (doto form (.set_Size (Size. 300 120)) .ShowDialog))) (celsius)
null
https://raw.githubusercontent.com/clojurecup2014/parade-route/adb2e1ea202228e3da07902849dee08f0bb8d81c/Assets/Clojure/Internal/Plugins/clojure/samples/celsius.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. A Celsius/Fahrenheit converter
Copyright ( c ) . All rights reserved . A WinForms equivalent to the Swing app shown here : If you are running on .Net 4 , you will have to change this . (System.Reflection.Assembly/Load "System.Windows.Forms,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") (import '(System.Drawing Size) '(System.Windows.Forms Form TableLayoutPanel Label Button TextBox PaintEventHandler PaintEventArgs) ) (defn celsius [] (let [form (Form.) panel (TableLayoutPanel.) p-controls (.Controls panel) tb (TextBox.) c-label (Label.) button (Button.) f-label (Label.)] (.set_Text form "Celsius Converter") (.set_Text c-label "Celsius") (.set_Text f-label "Fahrenheit") (.set_Text button "Convert") (.. form (Controls) (Add panel)) (.add_Click button (gen-delegate EventHandler [sender args] (let [c (Double/Parse (.Text tb)) ] (.set_Text f-label (str (+ 32 (* 1.8 c)) " Fahrenheit"))))) (doto panel (.set_ColumnCount 2) (.set_RowCount 2)) (doto p-controls (.Add tb) (.Add c-label) (.Add button) (.Add f-label)) (doto form (.set_Size (Size. 300 120)) .ShowDialog))) (celsius)
2b3d9063592823a8aa92dfac017e33282e3af863e4df14a330fdd12edde7fdf7
kappelmann/eidi2_repetitorium_tum
batteries.mli
val todo : 'a -> 'b val ( % ) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b val comp2 : ('a -> 'a -> 'b) -> ('c -> 'a) -> 'c -> 'c -> 'b val compareBy : ('a -> 'b) -> 'a -> 'a -> int val id : 'a -> 'a val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c val neg : ('a -> bool) -> 'a -> bool val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c module Tuple2 : sig val fst : 'a * 'b -> 'a val snd : 'a * 'b -> 'b val map1 : ('a -> 'b) -> 'a * 'c -> 'b * 'c val map2 : ('a -> 'b) -> 'c * 'a -> 'c * 'b val map : ('a -> 'b) -> ('c -> 'd) -> 'a * 'c -> 'b * 'd end module Option : sig val some : 'a -> 'a option val is_some : 'a option -> bool val is_none : 'a option -> bool val get_some : 'a option -> 'a val show : ('a -> string) -> 'a option -> string val map : ('a -> 'b) -> 'a option -> 'b option val bind : 'a option -> ('a -> 'b option) -> 'b option val ( >>= ) : 'a option -> ('a -> 'b option) -> 'b option val filter : ('a -> bool) -> 'a option -> 'a option val default : 'a -> 'a option -> 'a val ( |? ) : 'a option -> 'a -> 'a val try_some : ('a -> 'b) -> 'a -> 'b option end module List : sig val cons : 'a -> 'a list -> 'a list val head : 'a list -> 'a option val tail : 'a list -> 'a list option val last : 'a list -> 'a option val reverse : 'a list -> 'a list val length : 'a list -> int val map : ('a -> 'b) -> 'a list -> 'b list val iter : ('a -> unit) -> 'a list -> unit val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list val filter : ('a -> bool) -> 'a list -> 'a list val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b val exists : ('a -> bool) -> 'a list -> bool val for_all : ('a -> bool) -> 'a list -> bool val at : int -> 'a list -> 'a option val flatten : 'a list list -> 'a list val make : int -> 'a -> 'a list val range : int -> int -> int list val init : int -> (int -> 'a) -> 'a list val reduce : ('a -> 'a -> 'a) -> 'a list -> 'a option val max_el : 'a list -> 'a option val min_max : 'a list -> ('a * 'a) option val mem : 'a -> 'a list -> bool val find : ('a -> bool) -> 'a list -> 'a option val filter_map : ('a -> 'b option) -> 'a list -> 'b list val partition : ('a -> bool) -> 'a list -> 'a list * 'a list val index_of : 'a -> 'a list -> int option val split_at : int -> 'a list -> 'a list * 'a list val remove_all : ('a -> bool) -> 'a list -> 'a list val remove_first : ('a -> bool) -> 'a list -> 'a list val take : int -> 'a list -> 'a list val drop : int -> 'a list -> 'a list val interleave : 'a -> 'a list -> 'a list val split : ('a * 'b) list -> 'a list * 'b list val combine : 'a list -> 'b list -> ('a * 'b) list option val merge : ?cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list val sort : ?cmp:('a -> 'a -> int) -> 'a list -> 'a list end module Set : sig type 'a t = 'a list val from_list : 'a list -> 'a t val to_list : 'a -> 'a val union : 'a list -> 'a list -> 'a t val inter : 'a list -> 'a list -> 'a t val diff : 'a list -> 'a list -> 'a list end module String : sig val concat : string -> string list -> string val escaped : 'a -> 'a end
null
https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/2016/trees/batteries.mli
ocaml
val todo : 'a -> 'b val ( % ) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b val comp2 : ('a -> 'a -> 'b) -> ('c -> 'a) -> 'c -> 'c -> 'b val compareBy : ('a -> 'b) -> 'a -> 'a -> int val id : 'a -> 'a val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c val neg : ('a -> bool) -> 'a -> bool val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c module Tuple2 : sig val fst : 'a * 'b -> 'a val snd : 'a * 'b -> 'b val map1 : ('a -> 'b) -> 'a * 'c -> 'b * 'c val map2 : ('a -> 'b) -> 'c * 'a -> 'c * 'b val map : ('a -> 'b) -> ('c -> 'd) -> 'a * 'c -> 'b * 'd end module Option : sig val some : 'a -> 'a option val is_some : 'a option -> bool val is_none : 'a option -> bool val get_some : 'a option -> 'a val show : ('a -> string) -> 'a option -> string val map : ('a -> 'b) -> 'a option -> 'b option val bind : 'a option -> ('a -> 'b option) -> 'b option val ( >>= ) : 'a option -> ('a -> 'b option) -> 'b option val filter : ('a -> bool) -> 'a option -> 'a option val default : 'a -> 'a option -> 'a val ( |? ) : 'a option -> 'a -> 'a val try_some : ('a -> 'b) -> 'a -> 'b option end module List : sig val cons : 'a -> 'a list -> 'a list val head : 'a list -> 'a option val tail : 'a list -> 'a list option val last : 'a list -> 'a option val reverse : 'a list -> 'a list val length : 'a list -> int val map : ('a -> 'b) -> 'a list -> 'b list val iter : ('a -> unit) -> 'a list -> unit val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list val filter : ('a -> bool) -> 'a list -> 'a list val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a val fold_right : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b val exists : ('a -> bool) -> 'a list -> bool val for_all : ('a -> bool) -> 'a list -> bool val at : int -> 'a list -> 'a option val flatten : 'a list list -> 'a list val make : int -> 'a -> 'a list val range : int -> int -> int list val init : int -> (int -> 'a) -> 'a list val reduce : ('a -> 'a -> 'a) -> 'a list -> 'a option val max_el : 'a list -> 'a option val min_max : 'a list -> ('a * 'a) option val mem : 'a -> 'a list -> bool val find : ('a -> bool) -> 'a list -> 'a option val filter_map : ('a -> 'b option) -> 'a list -> 'b list val partition : ('a -> bool) -> 'a list -> 'a list * 'a list val index_of : 'a -> 'a list -> int option val split_at : int -> 'a list -> 'a list * 'a list val remove_all : ('a -> bool) -> 'a list -> 'a list val remove_first : ('a -> bool) -> 'a list -> 'a list val take : int -> 'a list -> 'a list val drop : int -> 'a list -> 'a list val interleave : 'a -> 'a list -> 'a list val split : ('a * 'b) list -> 'a list * 'b list val combine : 'a list -> 'b list -> ('a * 'b) list option val merge : ?cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list val sort : ?cmp:('a -> 'a -> int) -> 'a list -> 'a list end module Set : sig type 'a t = 'a list val from_list : 'a list -> 'a t val to_list : 'a -> 'a val union : 'a list -> 'a list -> 'a t val inter : 'a list -> 'a list -> 'a t val diff : 'a list -> 'a list -> 'a list end module String : sig val concat : string -> string list -> string val escaped : 'a -> 'a end
77d457bacc3cb4deaab1049739afc5f664532bdd49e622272c72a6f5294c728a
eerohele/enne
edn.cljc
(ns enne.edn #?(:clj (:require [clojure.edn :as edn] [clojure.java.io :as io])) #?(:clj (:import (java.io PushbackReader)))) #?(:clj (do (defmacro load-resource-m [source] (with-open [r (-> source io/resource io/reader)] (edn/read (PushbackReader. r)))) (defn load-resource-fn [source] (with-open [r (-> source io/resource io/reader)] (edn/read (PushbackReader. r))))))
null
https://raw.githubusercontent.com/eerohele/enne/3de679e01b617182d5694a78e8d8cd9afc78ec26/src/enne/edn.cljc
clojure
(ns enne.edn #?(:clj (:require [clojure.edn :as edn] [clojure.java.io :as io])) #?(:clj (:import (java.io PushbackReader)))) #?(:clj (do (defmacro load-resource-m [source] (with-open [r (-> source io/resource io/reader)] (edn/read (PushbackReader. r)))) (defn load-resource-fn [source] (with-open [r (-> source io/resource io/reader)] (edn/read (PushbackReader. r))))))
5b74c765092caacb3db69d4ddb39f0806b5a84cec51211fb7883b05fbd36e979
NorfairKing/hastory
GenChangeWrapper.hs
module Hastory.Cli.Commands.GenChangeWrapper where genChangeWrapperScript :: IO () genChangeWrapperScript = putStrLn $ unlines [ "hastory_change_directory_ () {", " local args=\"$@\"", " if [[ \"$args\" == \"\" ]]", " then", " hastory list-recent-directories", " else", " local dir=$(hastory change-directory \"$args\")", " cd \"$dir\"", " fi", "}" ]
null
https://raw.githubusercontent.com/NorfairKing/hastory/35abbc79155bc7c5a0f6e0f3618c8b8bcd3889a1/hastory-cli/src/Hastory/Cli/Commands/GenChangeWrapper.hs
haskell
module Hastory.Cli.Commands.GenChangeWrapper where genChangeWrapperScript :: IO () genChangeWrapperScript = putStrLn $ unlines [ "hastory_change_directory_ () {", " local args=\"$@\"", " if [[ \"$args\" == \"\" ]]", " then", " hastory list-recent-directories", " else", " local dir=$(hastory change-directory \"$args\")", " cd \"$dir\"", " fi", "}" ]
a6e91b3e2c44120a0c580d9bce247afd007f72d53a3e416920e62d2426fa9f1d
monadbobo/ocaml-core
selector.mli
open Core.Std Implements types to be used in selection languages using Blang . The many nested types serve partially as documentation , but mostly to ease the creation of custom sexp parsers to reduce the amount of noise in config files . While any amount of magic may be embedded in the sexp parsers exposed below , the following magic will be available : - constructors that take lists can be written as atoms for singletons - specific notes as detailed below There is an extension to this exposed in Sqml that has an additional to_expr method for converting these to SQL expressions . It also has additional selectors for Sqml specific types . The many nested types serve partially as documentation, but mostly to ease the creation of custom sexp parsers to reduce the amount of noise in config files. While any amount of magic may be embedded in the sexp parsers exposed below, the following magic will be available: - constructors that take lists can be written as atoms for singletons - specific notes as detailed below There is an extension to this exposed in Sqml that has an additional to_expr method for converting these to SQL expressions. It also has additional selectors for Sqml specific types. *) module type Selector = sig type selector type value val eval : selector -> value -> bool end module Date_selector : sig > , < , and = are allowed in place of GT , LT , and On . In addition > < can be used in place of Between and can be used infix ( e.g. ( date1 > < date2 ) ) . In addition , the special cases of on and between can be written as simply " date " and " ( date1 date2 ) " in place of Between and can be used infix (e.g. (date1 >< date2)). In addition, the special cases of on and between can be written as simply "date" and "(date1 date2)" *) type t = | GT of Date.t | LT of Date.t | Between of Date.t * Date.t | On of Date.t with of_sexp include Selector with type selector = t and type value = Date.t end (* regular expressions must be bounded with a '/' on both ends and this is used to automagically produce the correct type when parsing sexps, so that you can write any of the following: /.*foo/ foo (foo bar) (foo /bar[0-9]/) *) module String_selector : sig module Regexp : sig type t with sexp val of_regexp : string -> t val matches : t -> string -> bool val to_string : t -> string val to_regexp : t -> Pcre.regexp end type t = | Equal of string list | Matches of Regexp.t list | Mixed of [ `Regexp of Regexp.t | `Literal of string ] list with of_sexp include Selector with type selector = t and type value = String.t end module String_list_selector : sig type t = string list with sexp include Selector with type selector = t and type value = string end
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/extended/lib/selector.mli
ocaml
regular expressions must be bounded with a '/' on both ends and this is used to automagically produce the correct type when parsing sexps, so that you can write any of the following: /.*foo/ foo (foo bar) (foo /bar[0-9]/)
open Core.Std Implements types to be used in selection languages using Blang . The many nested types serve partially as documentation , but mostly to ease the creation of custom sexp parsers to reduce the amount of noise in config files . While any amount of magic may be embedded in the sexp parsers exposed below , the following magic will be available : - constructors that take lists can be written as atoms for singletons - specific notes as detailed below There is an extension to this exposed in Sqml that has an additional to_expr method for converting these to SQL expressions . It also has additional selectors for Sqml specific types . The many nested types serve partially as documentation, but mostly to ease the creation of custom sexp parsers to reduce the amount of noise in config files. While any amount of magic may be embedded in the sexp parsers exposed below, the following magic will be available: - constructors that take lists can be written as atoms for singletons - specific notes as detailed below There is an extension to this exposed in Sqml that has an additional to_expr method for converting these to SQL expressions. It also has additional selectors for Sqml specific types. *) module type Selector = sig type selector type value val eval : selector -> value -> bool end module Date_selector : sig > , < , and = are allowed in place of GT , LT , and On . In addition > < can be used in place of Between and can be used infix ( e.g. ( date1 > < date2 ) ) . In addition , the special cases of on and between can be written as simply " date " and " ( date1 date2 ) " in place of Between and can be used infix (e.g. (date1 >< date2)). In addition, the special cases of on and between can be written as simply "date" and "(date1 date2)" *) type t = | GT of Date.t | LT of Date.t | Between of Date.t * Date.t | On of Date.t with of_sexp include Selector with type selector = t and type value = Date.t end module String_selector : sig module Regexp : sig type t with sexp val of_regexp : string -> t val matches : t -> string -> bool val to_string : t -> string val to_regexp : t -> Pcre.regexp end type t = | Equal of string list | Matches of Regexp.t list | Mixed of [ `Regexp of Regexp.t | `Literal of string ] list with of_sexp include Selector with type selector = t and type value = String.t end module String_list_selector : sig type t = string list with sexp include Selector with type selector = t and type value = string end
6219b822fc1d8a23f4370e8fec0edaeb754f0f920f9bf9c06f480c55b858e0c7
facebook/infer
RacerDDomain.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 AccessExpression = HilExp.AccessExpression module F = Format module L = Logging module MF = MarkupFormatter let rec accexp_of_hilexp hil_exp = match (hil_exp : HilExp.t) with | AccessExpression access_expr -> Some access_expr | Cast (_, e) | Exception e -> accexp_of_hilexp e | _ -> None let accexp_of_first_hilexp actuals = List.hd actuals |> Option.bind ~f:accexp_of_hilexp let apply_to_first_actual actuals astate ~f = accexp_of_first_hilexp actuals |> Option.value_map ~default:astate ~f let pp_exp fmt exp = match !Language.curr_language with | Clang -> AccessExpression.pp fmt exp | Java -> AccessPath.pp fmt (AccessExpression.to_access_path exp) | CIL -> AccessPath.pp fmt (AccessExpression.to_access_path exp) | Erlang -> L.die InternalError "Erlang not supported" | Hack -> L.die InternalError "Hack not supported" let rec should_keep_exp formals (exp : AccessExpression.t) = match exp with | FieldOffset (prefix, fld) -> (not (String.is_substring ~substring:"$SwitchMap" (Fieldname.get_field_name fld))) && should_keep_exp formals prefix | ArrayOffset (prefix, _, _) | AddressOf prefix | Dereference prefix -> should_keep_exp formals prefix | Base (LogicalVar _, _) -> false | Base (((ProgramVar pvar as var), _) as base) -> Var.appears_in_source_code var && (not (Pvar.is_static_local pvar)) && (Pvar.is_global pvar || FormalMap.is_formal base formals) module Access = struct type t = | Read of {exp: AccessExpression.t} | Write of {exp: AccessExpression.t} | ContainerRead of {exp: AccessExpression.t; pname: Procname.t} | ContainerWrite of {exp: AccessExpression.t; pname: Procname.t} | InterfaceCall of {exp: AccessExpression.t; pname: Procname.t} [@@deriving compare] let make_field_access exp ~is_write = if is_write then Write {exp} else Read {exp} let make_container_access exp pname ~is_write = if is_write then ContainerWrite {exp; pname} else ContainerRead {exp; pname} let make_unannotated_call_access exp pname = InterfaceCall {exp; pname} let is_write = function | InterfaceCall _ | Read _ | ContainerRead _ -> false | ContainerWrite _ | Write _ -> true let is_container_write = function | InterfaceCall _ | Read _ | Write _ | ContainerRead _ -> false | ContainerWrite _ -> true let get_access_exp = function | Read {exp} | Write {exp} | ContainerWrite {exp} | ContainerRead {exp} | InterfaceCall {exp} -> exp let should_keep formals access = get_access_exp access |> should_keep_exp formals let map ~f access = match access with | Read {exp} -> let exp' = f exp in if phys_equal exp exp' then access else Read {exp= exp'} | Write {exp} -> let exp' = f exp in if phys_equal exp exp' then access else Write {exp= exp'} | ContainerWrite ({exp} as record) -> let exp' = f exp in if phys_equal exp exp' then access else ContainerWrite {record with exp= exp'} | ContainerRead ({exp} as record) -> let exp' = f exp in if phys_equal exp exp' then access else ContainerRead {record with exp= exp'} | InterfaceCall ({exp} as record) -> let exp' = f exp in if phys_equal exp exp' then access else InterfaceCall {record with exp= exp'} let pp fmt = function | Read {exp} -> F.fprintf fmt "Read of %a" AccessExpression.pp exp | Write {exp} -> F.fprintf fmt "Write to %a" AccessExpression.pp exp | ContainerRead {exp; pname} -> F.fprintf fmt "Read of container %a via %a" AccessExpression.pp exp Procname.pp pname | ContainerWrite {exp; pname} -> F.fprintf fmt "Write to container %a via %a" AccessExpression.pp exp Procname.pp pname | InterfaceCall {exp; pname} -> F.fprintf fmt "Call to un-annotated interface method %a.%a" AccessExpression.pp exp Procname.pp pname let mono_lang_pp = MF.wrap_monospaced pp_exp let describe fmt = function | Read {exp} | Write {exp} -> F.fprintf fmt "access to %a" mono_lang_pp exp | ContainerRead {exp; pname} -> F.fprintf fmt "Read of container %a via call to %s" mono_lang_pp exp (MF.monospaced_to_string (Procname.get_method pname)) | ContainerWrite {exp; pname} -> F.fprintf fmt "Write to container %a via call to %s" mono_lang_pp exp (MF.monospaced_to_string (Procname.get_method pname)) | InterfaceCall {pname} -> F.fprintf fmt "Call to un-annotated interface method %a" Procname.pp pname end module CallPrinter = struct type t = CallSite.t let pp fmt cs = F.fprintf fmt "call to %a" Procname.pp (CallSite.pname cs) end module LockDomain = struct include AbstractDomain.CountDomain (struct * arbitrary threshold for locks we expect to be held simultaneously let max = 5 end) let acquire_lock = increment let release_lock = decrement let integrate_summary ~caller_astate ~callee_astate = add caller_astate callee_astate let is_locked t = not (is_bottom t) end module ThreadsDomain = struct type t = NoThread | AnyThreadButSelf | AnyThread [@@deriving compare, equal, show {with_path= false}] let bottom = NoThread < AnyThreadButSelf < Any let leq ~lhs ~rhs = phys_equal lhs rhs || match (lhs, rhs) with | NoThread, _ -> true | _, NoThread -> false | _, AnyThread -> true | AnyThread, _ -> false | _ -> equal lhs rhs let join astate1 astate2 = if phys_equal astate1 astate2 then astate1 else match (astate1, astate2) with | NoThread, astate | astate, NoThread -> astate | AnyThread, _ | _, AnyThread -> AnyThread | AnyThreadButSelf, AnyThreadButSelf -> AnyThreadButSelf let widen ~prev ~next ~num_iters:_ = join prev next at least one access is known to occur on a background thread let can_conflict astate1 astate2 = match join astate1 astate2 with AnyThread -> true | NoThread | AnyThreadButSelf -> false let is_any_but_self = function AnyThreadButSelf -> true | _ -> false let is_any = function AnyThread -> true | _ -> false let integrate_summary ~caller_astate ~callee_astate = (* if we know the callee runs on the main thread, assume the caller does too. otherwise, keep the caller's thread context *) match callee_astate with AnyThreadButSelf -> callee_astate | _ -> caller_astate let update_for_lock_use = function AnyThreadButSelf -> AnyThreadButSelf | _ -> AnyThread end module OwnershipAbstractValue = struct type t = OwnedIf of IntSet.t | Unowned [@@deriving compare] let owned = OwnedIf IntSet.empty let is_owned = function OwnedIf set -> IntSet.is_empty set | Unowned -> false let unowned = Unowned let make_owned_if formal_index = OwnedIf (IntSet.singleton formal_index) let leq ~lhs ~rhs = phys_equal lhs rhs || match (lhs, rhs) with | _, Unowned -> Unowned is top | Unowned, _ -> false | OwnedIf s1, OwnedIf s2 -> IntSet.subset s1 s2 let join astate1 astate2 = if phys_equal astate1 astate2 then astate1 else match (astate1, astate2) with | _, Unowned | Unowned, _ -> Unowned | OwnedIf s1, OwnedIf s2 -> OwnedIf (IntSet.union s1 s2) let widen ~prev ~next ~num_iters:_ = join prev next let pp fmt = function | Unowned -> F.pp_print_string fmt "Unowned" | OwnedIf s -> if IntSet.is_empty s then F.pp_print_string fmt "Owned" else F.fprintf fmt "OwnedIf%a" (PrettyPrintable.pp_collection ~pp_item:Int.pp) (IntSet.elements s) end module AccessSnapshot = struct module AccessSnapshotElem = struct type t = { access: Access.t ; thread: ThreadsDomain.t ; lock: bool ; ownership_precondition: OwnershipAbstractValue.t } [@@deriving compare] let pp fmt {access; thread; lock; ownership_precondition} = F.fprintf fmt "Access: %a Thread: %a Lock: %b Pre: %a" Access.pp access ThreadsDomain.pp thread lock OwnershipAbstractValue.pp ownership_precondition let describe fmt {access} = Access.describe fmt access end include ExplicitTrace.MakeTraceElemModuloLocation (AccessSnapshotElem) (CallPrinter) let is_write {elem= {access}} = Access.is_write access let is_container_write {elem= {access}} = Access.is_container_write access let filter formals t = if (not (OwnershipAbstractValue.is_owned t.elem.ownership_precondition)) && Access.should_keep formals t.elem.access then Some t else None let make_if_not_owned formals access lock thread ownership_precondition loc = make {access; lock; thread; ownership_precondition} loc |> filter formals let make_unannotated_call_access formals exp pname lock ownership loc = let lock = LockDomain.is_locked lock in let access = Access.make_unannotated_call_access exp pname in make_if_not_owned formals access lock ownership loc let make_access formals acc_exp ~is_write loc lock thread ownership_precondition = let lock = LockDomain.is_locked lock in let access = Access.make_field_access acc_exp ~is_write in make_if_not_owned formals access lock thread ownership_precondition loc let make_container_access formals acc_exp ~is_write callee loc lock thread ownership_precondition = let lock = LockDomain.is_locked lock in let access = Access.make_container_access acc_exp callee ~is_write in make_if_not_owned formals access lock thread ownership_precondition loc let subst_actuals_into_formals callee_formals actuals_array (t : t) = let exp = Access.get_access_exp t.elem.access in match FormalMap.get_formal_index (AccessExpression.get_base exp) callee_formals with | None -> (* non-param base variable, leave unchanged *) Some t | Some formal_index when formal_index >= Array.length actuals_array -> vararg param which is missing , throw away None | Some formal_index -> ( match actuals_array.(formal_index) with | None -> (* no useful argument can be substituted, throw away *) None | Some actual -> AccessExpression.append ~onto:actual exp |> Option.map ~f:(fun new_exp -> map t ~f:(fun elem -> {elem with access= Access.map ~f:(fun _ -> new_exp) elem.access} ) ) ) let update_callee_access threads locks actuals_ownership (snapshot : t) = let update_ownership_precondition actual_index (acc : OwnershipAbstractValue.t) = if actual_index >= Array.length actuals_ownership then vararg methods can result into missing actuals so simply ignore acc else OwnershipAbstractValue.join acc actuals_ownership.(actual_index) in (* update precondition with caller ownership info *) let ownership_precondition = match snapshot.elem.ownership_precondition with | OwnedIf indexes -> IntSet.fold update_ownership_precondition indexes OwnershipAbstractValue.owned | Unowned -> snapshot.elem.ownership_precondition in let thread = ThreadsDomain.integrate_summary ~callee_astate:snapshot.elem.thread ~caller_astate:threads in let lock = snapshot.elem.lock || LockDomain.is_locked locks in map snapshot ~f:(fun elem -> {elem with lock; thread; ownership_precondition}) let integrate_summary ~caller_formals ~callee_formals callsite threads locks actuals_array actuals_ownership snapshot = subst_actuals_into_formals callee_formals actuals_array snapshot |> Option.map ~f:(update_callee_access threads locks actuals_ownership) |> Option.map ~f:(fun snapshot -> with_callsite snapshot callsite) |> Option.bind ~f:(filter caller_formals) let is_unprotected {elem= {thread; lock; ownership_precondition}} = (not (ThreadsDomain.is_any_but_self thread)) && (not lock) && not (OwnershipAbstractValue.is_owned ownership_precondition) end module AccessDomain = struct include AbstractDomain.FiniteSet (AccessSnapshot) let add_opt snapshot_opt astate = Option.fold snapshot_opt ~init:astate ~f:(fun acc s -> add s acc) end module OwnershipDomain = struct include AbstractDomain.Map (AccessExpression) (OwnershipAbstractValue) return the first non - Unowned ownership value found when checking progressively shorter prefixes of [ access_exp ] prefixes of [access_exp] *) let rec get_owned (access_exp : AccessExpression.t) astate = match find_opt access_exp astate with | Some (OwnershipAbstractValue.OwnedIf _ as v) -> v | _ -> ( match access_exp with | Base _ -> OwnershipAbstractValue.Unowned | AddressOf prefix | Dereference prefix | FieldOffset (prefix, _) | ArrayOffset (prefix, _, _) -> get_owned prefix astate ) let rec ownership_of_expr ownership (expr : HilExp.t) = match expr with | AccessExpression access_expr -> get_owned access_expr ownership | Constant _ -> OwnershipAbstractValue.owned treat exceptions as transparent wrt ownership ownership_of_expr ownership e | _ -> OwnershipAbstractValue.unowned let propagate_assignment lhs_access_exp rhs_exp ownership = if AccessExpression.get_base lhs_access_exp |> fst |> Var.is_global then (* do not assign ownership to access expressions rooted at globals *) ownership else let rhs_ownership_value = ownership_of_expr ownership rhs_exp in add lhs_access_exp rhs_ownership_value ownership let propagate_return ret_access_exp return_ownership actuals ownership = let get_ownership formal_index init = List.nth actuals formal_index (* simply skip formal if we cannot find its actual, as opposed to assuming non-ownership *) |> Option.fold ~init ~f:(fun acc expr -> OwnershipAbstractValue.join acc (ownership_of_expr ownership expr) ) in let ret_ownership_wrt_actuals = match return_ownership with | OwnershipAbstractValue.Unowned -> return_ownership | OwnershipAbstractValue.OwnedIf formal_indexes -> IntSet.fold get_ownership formal_indexes OwnershipAbstractValue.owned in add ret_access_exp ret_ownership_wrt_actuals ownership end module Attribute = struct type t = Nothing | Functional | OnMainThread | LockHeld | Synchronized [@@deriving equal] let pp fmt t = ( match t with | Nothing -> "Nothing" | Functional -> "Functional" | OnMainThread -> "OnMainThread" | LockHeld -> "LockHeld" | Synchronized -> "Synchronized" ) |> F.pp_print_string fmt let top = Nothing let is_top = function Nothing -> true | _ -> false let join t t' = if equal t t' then t else Nothing let leq ~lhs ~rhs = equal (join lhs rhs) rhs let widen ~prev ~next ~num_iters:_ = join prev next end module AttributeMapDomain = struct include AbstractDomain.SafeInvertedMap (AccessExpression) (Attribute) let get acc_exp t = find_opt acc_exp t |> Option.value ~default:Attribute.top let is_functional t access_expression = match find_opt access_expression t with Some Functional -> true | _ -> false let is_synchronized t access_expression = match find_opt access_expression t with Some Synchronized -> true | _ -> false let rec attribute_of_expr attribute_map (e : HilExp.t) = match e with | AccessExpression access_expr -> get access_expr attribute_map | Constant _ -> Attribute.Functional treat exceptions as transparent wrt attributes attribute_of_expr attribute_map expr | UnaryOperator (_, expr, _) -> attribute_of_expr attribute_map expr | BinaryOperator (_, expr1, expr2) -> let attribute1 = attribute_of_expr attribute_map expr1 in let attribute2 = attribute_of_expr attribute_map expr2 in Attribute.join attribute1 attribute2 | Closure _ | Sizeof _ -> Attribute.top let propagate_assignment lhs_access_expression rhs_exp attribute_map = let rhs_attribute = attribute_of_expr attribute_map rhs_exp in add lhs_access_expression rhs_attribute attribute_map end module NeverReturns = AbstractDomain.BooleanAnd type t = { threads: ThreadsDomain.t ; locks: LockDomain.t ; never_returns: NeverReturns.t ; accesses: AccessDomain.t ; ownership: OwnershipDomain.t ; attribute_map: AttributeMapDomain.t } let initial = let threads = ThreadsDomain.bottom in let locks = LockDomain.bottom in let never_returns = false in let accesses = AccessDomain.empty in let ownership = OwnershipDomain.empty in let attribute_map = AttributeMapDomain.empty in {threads; locks; never_returns; accesses; ownership; attribute_map} let leq ~lhs ~rhs = if phys_equal lhs rhs then true else ThreadsDomain.leq ~lhs:lhs.threads ~rhs:rhs.threads && LockDomain.leq ~lhs:lhs.locks ~rhs:rhs.locks && NeverReturns.leq ~lhs:lhs.never_returns ~rhs:rhs.never_returns && AccessDomain.leq ~lhs:lhs.accesses ~rhs:rhs.accesses && OwnershipDomain.leq ~lhs:lhs.ownership ~rhs:rhs.ownership && AttributeMapDomain.leq ~lhs:lhs.attribute_map ~rhs:rhs.attribute_map let join astate1 astate2 = if phys_equal astate1 astate2 then astate1 else let threads = ThreadsDomain.join astate1.threads astate2.threads in let locks = LockDomain.join astate1.locks astate2.locks in let never_returns = NeverReturns.join astate1.never_returns astate2.never_returns in let accesses = AccessDomain.join astate1.accesses astate2.accesses in let ownership = OwnershipDomain.join astate1.ownership astate2.ownership in let attribute_map = AttributeMapDomain.join astate1.attribute_map astate2.attribute_map in {threads; locks; never_returns; accesses; ownership; attribute_map} let widen ~prev ~next ~num_iters = if phys_equal prev next then prev else let threads = ThreadsDomain.widen ~prev:prev.threads ~next:next.threads ~num_iters in let locks = LockDomain.widen ~prev:prev.locks ~next:next.locks ~num_iters in let never_returns = NeverReturns.widen ~prev:prev.never_returns ~next:next.never_returns ~num_iters in let accesses = AccessDomain.widen ~prev:prev.accesses ~next:next.accesses ~num_iters in let ownership = OwnershipDomain.widen ~prev:prev.ownership ~next:next.ownership ~num_iters in let attribute_map = AttributeMapDomain.widen ~prev:prev.attribute_map ~next:next.attribute_map ~num_iters in {threads; locks; never_returns; accesses; ownership; attribute_map} type summary = { threads: ThreadsDomain.t ; locks: LockDomain.t ; never_returns: NeverReturns.t ; accesses: AccessDomain.t ; return_ownership: OwnershipAbstractValue.t ; return_attribute: Attribute.t ; attributes: AttributeMapDomain.t } let empty_summary = { threads= ThreadsDomain.bottom ; locks= LockDomain.bottom ; never_returns= false ; accesses= AccessDomain.bottom ; return_ownership= OwnershipAbstractValue.unowned ; return_attribute= Attribute.top ; attributes= AttributeMapDomain.top } let pp_summary fmt {threads; locks; never_returns; accesses; return_ownership; return_attribute; attributes} = F.fprintf fmt "@\n\ Threads: %a, Locks: %a, NeverReturns: %a @\n\ Accesses %a @\n\ Ownership: %a @\n\ Return Attribute: %a @\n\ Attributes: %a @\n" ThreadsDomain.pp threads LockDomain.pp locks NeverReturns.pp never_returns AccessDomain.pp accesses OwnershipAbstractValue.pp return_ownership Attribute.pp return_attribute AttributeMapDomain.pp attributes let pp fmt {threads; locks; never_returns; accesses; ownership; attribute_map} = F.fprintf fmt "Threads: %a, Locks: %a, NeverReturns: %a @\nAccesses %a @\nOwnership: %a @\nAttributes: %a @\n" ThreadsDomain.pp threads LockDomain.pp locks NeverReturns.pp never_returns AccessDomain.pp accesses OwnershipDomain.pp ownership AttributeMapDomain.pp attribute_map let add_unannotated_call_access formals pname actuals loc (astate : t) = apply_to_first_actual actuals astate ~f:(fun receiver -> let ownership = OwnershipDomain.get_owned receiver astate.ownership in let access_opt = AccessSnapshot.make_unannotated_call_access formals receiver pname astate.locks astate.threads ownership loc in {astate with accesses= AccessDomain.add_opt access_opt astate.accesses} ) let astate_to_summary proc_desc formals {threads; locks; never_returns; accesses; ownership; attribute_map} = let proc_name = Procdesc.get_proc_name proc_desc in let return_var_exp = AccessExpression.base (Var.of_pvar (Pvar.get_ret_pvar proc_name), Procdesc.get_ret_type proc_desc) in let return_ownership = OwnershipDomain.get_owned return_var_exp ownership in let return_attribute = AttributeMapDomain.get return_var_exp attribute_map in let locks = (* if method is [synchronized] released the lock once. *) if Procdesc.is_java_synchronized proc_desc || Procdesc.is_csharp_synchronized proc_desc then LockDomain.release_lock locks else locks in let attributes = (* store only the [Synchronized] attribute for class initializers/constructors *) if Procname.is_java_class_initializer proc_name || Procname.is_constructor proc_name then AttributeMapDomain.filter (fun exp attribute -> match attribute with Synchronized -> should_keep_exp formals exp | _ -> false ) attribute_map else AttributeMapDomain.top in {threads; locks; never_returns; accesses; return_ownership; return_attribute; attributes} let add_access tenv formals loc ~is_write (astate : t) exp = let rec add_field_accesses prefix_path acc = function | [] -> acc | access :: access_list -> let prefix_path' = Option.value_exn (AccessExpression.add_access prefix_path access) in if (not (HilExp.Access.is_field_or_array_access access)) || RacerDModels.is_safe_access access prefix_path tenv then add_field_accesses prefix_path' acc access_list else let is_write = is_write && List.is_empty access_list in let pre = OwnershipDomain.get_owned prefix_path astate.ownership in let snapshot_opt = AccessSnapshot.make_access formals prefix_path' ~is_write loc astate.locks astate.threads pre in let access_acc' = AccessDomain.add_opt snapshot_opt acc in add_field_accesses prefix_path' access_acc' access_list in let accesses = List.fold (HilExp.get_access_exprs exp) ~init:astate.accesses ~f:(fun acc access_expr -> let base, accesses = AccessExpression.to_accesses access_expr in add_field_accesses base acc accesses ) in {astate with accesses} let add_container_access tenv formals ~is_write ret_base callee_pname actuals loc (astate : t) = match accexp_of_first_hilexp actuals with | None -> L.internal_error "Call to %a is marked as a container access, but has no receiver" Procname.pp callee_pname ; astate | Some receiver_expr when AttributeMapDomain.is_synchronized astate.attribute_map receiver_expr || RacerDModels.is_synchronized_container callee_pname receiver_expr tenv -> astate | Some receiver_expr -> let ownership_pre = OwnershipDomain.get_owned receiver_expr astate.ownership in let callee_access_opt = AccessSnapshot.make_container_access formals receiver_expr ~is_write callee_pname loc astate.locks astate.threads ownership_pre in let ownership = OwnershipDomain.add (AccessExpression.base ret_base) ownership_pre astate.ownership in let accesses = AccessDomain.add_opt callee_access_opt astate.accesses in {astate with accesses; ownership} let add_reads_of_hilexps tenv formals exps loc astate = List.fold exps ~init:astate ~f:(add_access tenv formals loc ~is_write:false) let add_callee_accesses ~caller_formals ~callee_formals ~callee_accesses callee_pname actuals loc (caller_astate : t) = let callsite = CallSite.make callee_pname loc in (* precompute arrays for actuals and ownership for fast random access *) let actuals_array = Array.of_list_map actuals ~f:accexp_of_hilexp in let actuals_ownership = Array.of_list_map actuals ~f:(OwnershipDomain.ownership_of_expr caller_astate.ownership) in let process snapshot acc = AccessSnapshot.integrate_summary ~caller_formals ~callee_formals callsite caller_astate.threads caller_astate.locks actuals_array actuals_ownership snapshot |> fun snapshot_opt -> AccessDomain.add_opt snapshot_opt acc in let accesses = AccessDomain.fold process callee_accesses caller_astate.accesses in {caller_astate with accesses} let branch_never_returns () = (* Since this branch never returns but the successor node is the exit node as per [preanal.ml], we want to avoid changing the post at the exit node. Here we set all components to the appropriate identity element, except from those about not returning. *) { threads= ThreadsDomain.bottom ; locks= LockDomain.bottom ; never_returns= true ; accesses= AccessDomain.bottom ; ownership= OwnershipDomain.empty ; attribute_map= (* this is incorrect, as there is no identity element for an inverted set *) AttributeMapDomain.empty } let integrate_summary formals ~callee_proc_attrs summary ret_access_exp callee_pname actuals loc astate = let {threads; locks; never_returns; return_ownership; return_attribute} = summary in if never_returns then branch_never_returns () else let callee_formals = FormalMap.make callee_proc_attrs in let astate = add_callee_accesses ~caller_formals:formals ~callee_formals ~callee_accesses:summary.accesses callee_pname actuals loc astate in let locks = LockDomain.integrate_summary ~caller_astate:astate.locks ~callee_astate:locks in (* no treatment of [never_returns] as the callee's is [false] *) let ownership = OwnershipDomain.propagate_return ret_access_exp return_ownership actuals astate.ownership in let attribute_map = AttributeMapDomain.add ret_access_exp return_attribute astate.attribute_map in let threads = ThreadsDomain.integrate_summary ~caller_astate:astate.threads ~callee_astate:threads in {astate with locks; never_returns; threads; ownership; attribute_map} let acquire_lock (astate : t) = { astate with locks= LockDomain.acquire_lock astate.locks ; threads= ThreadsDomain.update_for_lock_use astate.threads } let release_lock (astate : t) = { astate with locks= LockDomain.release_lock astate.locks ; threads= ThreadsDomain.update_for_lock_use astate.threads } let lock_if_true ret_access_exp (astate : t) = { astate with attribute_map= AttributeMapDomain.add ret_access_exp Attribute.LockHeld astate.attribute_map ; threads= ThreadsDomain.update_for_lock_use astate.threads }
null
https://raw.githubusercontent.com/facebook/infer/28e867254f6dc8c2a26d749575b472ca0ae27a0f/infer/src/concurrency/RacerDDomain.ml
ocaml
if we know the callee runs on the main thread, assume the caller does too. otherwise, keep the caller's thread context non-param base variable, leave unchanged no useful argument can be substituted, throw away update precondition with caller ownership info do not assign ownership to access expressions rooted at globals simply skip formal if we cannot find its actual, as opposed to assuming non-ownership if method is [synchronized] released the lock once. store only the [Synchronized] attribute for class initializers/constructors precompute arrays for actuals and ownership for fast random access Since this branch never returns but the successor node is the exit node as per [preanal.ml], we want to avoid changing the post at the exit node. Here we set all components to the appropriate identity element, except from those about not returning. this is incorrect, as there is no identity element for an inverted set no treatment of [never_returns] as the callee's is [false]
* 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 AccessExpression = HilExp.AccessExpression module F = Format module L = Logging module MF = MarkupFormatter let rec accexp_of_hilexp hil_exp = match (hil_exp : HilExp.t) with | AccessExpression access_expr -> Some access_expr | Cast (_, e) | Exception e -> accexp_of_hilexp e | _ -> None let accexp_of_first_hilexp actuals = List.hd actuals |> Option.bind ~f:accexp_of_hilexp let apply_to_first_actual actuals astate ~f = accexp_of_first_hilexp actuals |> Option.value_map ~default:astate ~f let pp_exp fmt exp = match !Language.curr_language with | Clang -> AccessExpression.pp fmt exp | Java -> AccessPath.pp fmt (AccessExpression.to_access_path exp) | CIL -> AccessPath.pp fmt (AccessExpression.to_access_path exp) | Erlang -> L.die InternalError "Erlang not supported" | Hack -> L.die InternalError "Hack not supported" let rec should_keep_exp formals (exp : AccessExpression.t) = match exp with | FieldOffset (prefix, fld) -> (not (String.is_substring ~substring:"$SwitchMap" (Fieldname.get_field_name fld))) && should_keep_exp formals prefix | ArrayOffset (prefix, _, _) | AddressOf prefix | Dereference prefix -> should_keep_exp formals prefix | Base (LogicalVar _, _) -> false | Base (((ProgramVar pvar as var), _) as base) -> Var.appears_in_source_code var && (not (Pvar.is_static_local pvar)) && (Pvar.is_global pvar || FormalMap.is_formal base formals) module Access = struct type t = | Read of {exp: AccessExpression.t} | Write of {exp: AccessExpression.t} | ContainerRead of {exp: AccessExpression.t; pname: Procname.t} | ContainerWrite of {exp: AccessExpression.t; pname: Procname.t} | InterfaceCall of {exp: AccessExpression.t; pname: Procname.t} [@@deriving compare] let make_field_access exp ~is_write = if is_write then Write {exp} else Read {exp} let make_container_access exp pname ~is_write = if is_write then ContainerWrite {exp; pname} else ContainerRead {exp; pname} let make_unannotated_call_access exp pname = InterfaceCall {exp; pname} let is_write = function | InterfaceCall _ | Read _ | ContainerRead _ -> false | ContainerWrite _ | Write _ -> true let is_container_write = function | InterfaceCall _ | Read _ | Write _ | ContainerRead _ -> false | ContainerWrite _ -> true let get_access_exp = function | Read {exp} | Write {exp} | ContainerWrite {exp} | ContainerRead {exp} | InterfaceCall {exp} -> exp let should_keep formals access = get_access_exp access |> should_keep_exp formals let map ~f access = match access with | Read {exp} -> let exp' = f exp in if phys_equal exp exp' then access else Read {exp= exp'} | Write {exp} -> let exp' = f exp in if phys_equal exp exp' then access else Write {exp= exp'} | ContainerWrite ({exp} as record) -> let exp' = f exp in if phys_equal exp exp' then access else ContainerWrite {record with exp= exp'} | ContainerRead ({exp} as record) -> let exp' = f exp in if phys_equal exp exp' then access else ContainerRead {record with exp= exp'} | InterfaceCall ({exp} as record) -> let exp' = f exp in if phys_equal exp exp' then access else InterfaceCall {record with exp= exp'} let pp fmt = function | Read {exp} -> F.fprintf fmt "Read of %a" AccessExpression.pp exp | Write {exp} -> F.fprintf fmt "Write to %a" AccessExpression.pp exp | ContainerRead {exp; pname} -> F.fprintf fmt "Read of container %a via %a" AccessExpression.pp exp Procname.pp pname | ContainerWrite {exp; pname} -> F.fprintf fmt "Write to container %a via %a" AccessExpression.pp exp Procname.pp pname | InterfaceCall {exp; pname} -> F.fprintf fmt "Call to un-annotated interface method %a.%a" AccessExpression.pp exp Procname.pp pname let mono_lang_pp = MF.wrap_monospaced pp_exp let describe fmt = function | Read {exp} | Write {exp} -> F.fprintf fmt "access to %a" mono_lang_pp exp | ContainerRead {exp; pname} -> F.fprintf fmt "Read of container %a via call to %s" mono_lang_pp exp (MF.monospaced_to_string (Procname.get_method pname)) | ContainerWrite {exp; pname} -> F.fprintf fmt "Write to container %a via call to %s" mono_lang_pp exp (MF.monospaced_to_string (Procname.get_method pname)) | InterfaceCall {pname} -> F.fprintf fmt "Call to un-annotated interface method %a" Procname.pp pname end module CallPrinter = struct type t = CallSite.t let pp fmt cs = F.fprintf fmt "call to %a" Procname.pp (CallSite.pname cs) end module LockDomain = struct include AbstractDomain.CountDomain (struct * arbitrary threshold for locks we expect to be held simultaneously let max = 5 end) let acquire_lock = increment let release_lock = decrement let integrate_summary ~caller_astate ~callee_astate = add caller_astate callee_astate let is_locked t = not (is_bottom t) end module ThreadsDomain = struct type t = NoThread | AnyThreadButSelf | AnyThread [@@deriving compare, equal, show {with_path= false}] let bottom = NoThread < AnyThreadButSelf < Any let leq ~lhs ~rhs = phys_equal lhs rhs || match (lhs, rhs) with | NoThread, _ -> true | _, NoThread -> false | _, AnyThread -> true | AnyThread, _ -> false | _ -> equal lhs rhs let join astate1 astate2 = if phys_equal astate1 astate2 then astate1 else match (astate1, astate2) with | NoThread, astate | astate, NoThread -> astate | AnyThread, _ | _, AnyThread -> AnyThread | AnyThreadButSelf, AnyThreadButSelf -> AnyThreadButSelf let widen ~prev ~next ~num_iters:_ = join prev next at least one access is known to occur on a background thread let can_conflict astate1 astate2 = match join astate1 astate2 with AnyThread -> true | NoThread | AnyThreadButSelf -> false let is_any_but_self = function AnyThreadButSelf -> true | _ -> false let is_any = function AnyThread -> true | _ -> false let integrate_summary ~caller_astate ~callee_astate = match callee_astate with AnyThreadButSelf -> callee_astate | _ -> caller_astate let update_for_lock_use = function AnyThreadButSelf -> AnyThreadButSelf | _ -> AnyThread end module OwnershipAbstractValue = struct type t = OwnedIf of IntSet.t | Unowned [@@deriving compare] let owned = OwnedIf IntSet.empty let is_owned = function OwnedIf set -> IntSet.is_empty set | Unowned -> false let unowned = Unowned let make_owned_if formal_index = OwnedIf (IntSet.singleton formal_index) let leq ~lhs ~rhs = phys_equal lhs rhs || match (lhs, rhs) with | _, Unowned -> Unowned is top | Unowned, _ -> false | OwnedIf s1, OwnedIf s2 -> IntSet.subset s1 s2 let join astate1 astate2 = if phys_equal astate1 astate2 then astate1 else match (astate1, astate2) with | _, Unowned | Unowned, _ -> Unowned | OwnedIf s1, OwnedIf s2 -> OwnedIf (IntSet.union s1 s2) let widen ~prev ~next ~num_iters:_ = join prev next let pp fmt = function | Unowned -> F.pp_print_string fmt "Unowned" | OwnedIf s -> if IntSet.is_empty s then F.pp_print_string fmt "Owned" else F.fprintf fmt "OwnedIf%a" (PrettyPrintable.pp_collection ~pp_item:Int.pp) (IntSet.elements s) end module AccessSnapshot = struct module AccessSnapshotElem = struct type t = { access: Access.t ; thread: ThreadsDomain.t ; lock: bool ; ownership_precondition: OwnershipAbstractValue.t } [@@deriving compare] let pp fmt {access; thread; lock; ownership_precondition} = F.fprintf fmt "Access: %a Thread: %a Lock: %b Pre: %a" Access.pp access ThreadsDomain.pp thread lock OwnershipAbstractValue.pp ownership_precondition let describe fmt {access} = Access.describe fmt access end include ExplicitTrace.MakeTraceElemModuloLocation (AccessSnapshotElem) (CallPrinter) let is_write {elem= {access}} = Access.is_write access let is_container_write {elem= {access}} = Access.is_container_write access let filter formals t = if (not (OwnershipAbstractValue.is_owned t.elem.ownership_precondition)) && Access.should_keep formals t.elem.access then Some t else None let make_if_not_owned formals access lock thread ownership_precondition loc = make {access; lock; thread; ownership_precondition} loc |> filter formals let make_unannotated_call_access formals exp pname lock ownership loc = let lock = LockDomain.is_locked lock in let access = Access.make_unannotated_call_access exp pname in make_if_not_owned formals access lock ownership loc let make_access formals acc_exp ~is_write loc lock thread ownership_precondition = let lock = LockDomain.is_locked lock in let access = Access.make_field_access acc_exp ~is_write in make_if_not_owned formals access lock thread ownership_precondition loc let make_container_access formals acc_exp ~is_write callee loc lock thread ownership_precondition = let lock = LockDomain.is_locked lock in let access = Access.make_container_access acc_exp callee ~is_write in make_if_not_owned formals access lock thread ownership_precondition loc let subst_actuals_into_formals callee_formals actuals_array (t : t) = let exp = Access.get_access_exp t.elem.access in match FormalMap.get_formal_index (AccessExpression.get_base exp) callee_formals with | None -> Some t | Some formal_index when formal_index >= Array.length actuals_array -> vararg param which is missing , throw away None | Some formal_index -> ( match actuals_array.(formal_index) with | None -> None | Some actual -> AccessExpression.append ~onto:actual exp |> Option.map ~f:(fun new_exp -> map t ~f:(fun elem -> {elem with access= Access.map ~f:(fun _ -> new_exp) elem.access} ) ) ) let update_callee_access threads locks actuals_ownership (snapshot : t) = let update_ownership_precondition actual_index (acc : OwnershipAbstractValue.t) = if actual_index >= Array.length actuals_ownership then vararg methods can result into missing actuals so simply ignore acc else OwnershipAbstractValue.join acc actuals_ownership.(actual_index) in let ownership_precondition = match snapshot.elem.ownership_precondition with | OwnedIf indexes -> IntSet.fold update_ownership_precondition indexes OwnershipAbstractValue.owned | Unowned -> snapshot.elem.ownership_precondition in let thread = ThreadsDomain.integrate_summary ~callee_astate:snapshot.elem.thread ~caller_astate:threads in let lock = snapshot.elem.lock || LockDomain.is_locked locks in map snapshot ~f:(fun elem -> {elem with lock; thread; ownership_precondition}) let integrate_summary ~caller_formals ~callee_formals callsite threads locks actuals_array actuals_ownership snapshot = subst_actuals_into_formals callee_formals actuals_array snapshot |> Option.map ~f:(update_callee_access threads locks actuals_ownership) |> Option.map ~f:(fun snapshot -> with_callsite snapshot callsite) |> Option.bind ~f:(filter caller_formals) let is_unprotected {elem= {thread; lock; ownership_precondition}} = (not (ThreadsDomain.is_any_but_self thread)) && (not lock) && not (OwnershipAbstractValue.is_owned ownership_precondition) end module AccessDomain = struct include AbstractDomain.FiniteSet (AccessSnapshot) let add_opt snapshot_opt astate = Option.fold snapshot_opt ~init:astate ~f:(fun acc s -> add s acc) end module OwnershipDomain = struct include AbstractDomain.Map (AccessExpression) (OwnershipAbstractValue) return the first non - Unowned ownership value found when checking progressively shorter prefixes of [ access_exp ] prefixes of [access_exp] *) let rec get_owned (access_exp : AccessExpression.t) astate = match find_opt access_exp astate with | Some (OwnershipAbstractValue.OwnedIf _ as v) -> v | _ -> ( match access_exp with | Base _ -> OwnershipAbstractValue.Unowned | AddressOf prefix | Dereference prefix | FieldOffset (prefix, _) | ArrayOffset (prefix, _, _) -> get_owned prefix astate ) let rec ownership_of_expr ownership (expr : HilExp.t) = match expr with | AccessExpression access_expr -> get_owned access_expr ownership | Constant _ -> OwnershipAbstractValue.owned treat exceptions as transparent wrt ownership ownership_of_expr ownership e | _ -> OwnershipAbstractValue.unowned let propagate_assignment lhs_access_exp rhs_exp ownership = if AccessExpression.get_base lhs_access_exp |> fst |> Var.is_global then ownership else let rhs_ownership_value = ownership_of_expr ownership rhs_exp in add lhs_access_exp rhs_ownership_value ownership let propagate_return ret_access_exp return_ownership actuals ownership = let get_ownership formal_index init = List.nth actuals formal_index |> Option.fold ~init ~f:(fun acc expr -> OwnershipAbstractValue.join acc (ownership_of_expr ownership expr) ) in let ret_ownership_wrt_actuals = match return_ownership with | OwnershipAbstractValue.Unowned -> return_ownership | OwnershipAbstractValue.OwnedIf formal_indexes -> IntSet.fold get_ownership formal_indexes OwnershipAbstractValue.owned in add ret_access_exp ret_ownership_wrt_actuals ownership end module Attribute = struct type t = Nothing | Functional | OnMainThread | LockHeld | Synchronized [@@deriving equal] let pp fmt t = ( match t with | Nothing -> "Nothing" | Functional -> "Functional" | OnMainThread -> "OnMainThread" | LockHeld -> "LockHeld" | Synchronized -> "Synchronized" ) |> F.pp_print_string fmt let top = Nothing let is_top = function Nothing -> true | _ -> false let join t t' = if equal t t' then t else Nothing let leq ~lhs ~rhs = equal (join lhs rhs) rhs let widen ~prev ~next ~num_iters:_ = join prev next end module AttributeMapDomain = struct include AbstractDomain.SafeInvertedMap (AccessExpression) (Attribute) let get acc_exp t = find_opt acc_exp t |> Option.value ~default:Attribute.top let is_functional t access_expression = match find_opt access_expression t with Some Functional -> true | _ -> false let is_synchronized t access_expression = match find_opt access_expression t with Some Synchronized -> true | _ -> false let rec attribute_of_expr attribute_map (e : HilExp.t) = match e with | AccessExpression access_expr -> get access_expr attribute_map | Constant _ -> Attribute.Functional treat exceptions as transparent wrt attributes attribute_of_expr attribute_map expr | UnaryOperator (_, expr, _) -> attribute_of_expr attribute_map expr | BinaryOperator (_, expr1, expr2) -> let attribute1 = attribute_of_expr attribute_map expr1 in let attribute2 = attribute_of_expr attribute_map expr2 in Attribute.join attribute1 attribute2 | Closure _ | Sizeof _ -> Attribute.top let propagate_assignment lhs_access_expression rhs_exp attribute_map = let rhs_attribute = attribute_of_expr attribute_map rhs_exp in add lhs_access_expression rhs_attribute attribute_map end module NeverReturns = AbstractDomain.BooleanAnd type t = { threads: ThreadsDomain.t ; locks: LockDomain.t ; never_returns: NeverReturns.t ; accesses: AccessDomain.t ; ownership: OwnershipDomain.t ; attribute_map: AttributeMapDomain.t } let initial = let threads = ThreadsDomain.bottom in let locks = LockDomain.bottom in let never_returns = false in let accesses = AccessDomain.empty in let ownership = OwnershipDomain.empty in let attribute_map = AttributeMapDomain.empty in {threads; locks; never_returns; accesses; ownership; attribute_map} let leq ~lhs ~rhs = if phys_equal lhs rhs then true else ThreadsDomain.leq ~lhs:lhs.threads ~rhs:rhs.threads && LockDomain.leq ~lhs:lhs.locks ~rhs:rhs.locks && NeverReturns.leq ~lhs:lhs.never_returns ~rhs:rhs.never_returns && AccessDomain.leq ~lhs:lhs.accesses ~rhs:rhs.accesses && OwnershipDomain.leq ~lhs:lhs.ownership ~rhs:rhs.ownership && AttributeMapDomain.leq ~lhs:lhs.attribute_map ~rhs:rhs.attribute_map let join astate1 astate2 = if phys_equal astate1 astate2 then astate1 else let threads = ThreadsDomain.join astate1.threads astate2.threads in let locks = LockDomain.join astate1.locks astate2.locks in let never_returns = NeverReturns.join astate1.never_returns astate2.never_returns in let accesses = AccessDomain.join astate1.accesses astate2.accesses in let ownership = OwnershipDomain.join astate1.ownership astate2.ownership in let attribute_map = AttributeMapDomain.join astate1.attribute_map astate2.attribute_map in {threads; locks; never_returns; accesses; ownership; attribute_map} let widen ~prev ~next ~num_iters = if phys_equal prev next then prev else let threads = ThreadsDomain.widen ~prev:prev.threads ~next:next.threads ~num_iters in let locks = LockDomain.widen ~prev:prev.locks ~next:next.locks ~num_iters in let never_returns = NeverReturns.widen ~prev:prev.never_returns ~next:next.never_returns ~num_iters in let accesses = AccessDomain.widen ~prev:prev.accesses ~next:next.accesses ~num_iters in let ownership = OwnershipDomain.widen ~prev:prev.ownership ~next:next.ownership ~num_iters in let attribute_map = AttributeMapDomain.widen ~prev:prev.attribute_map ~next:next.attribute_map ~num_iters in {threads; locks; never_returns; accesses; ownership; attribute_map} type summary = { threads: ThreadsDomain.t ; locks: LockDomain.t ; never_returns: NeverReturns.t ; accesses: AccessDomain.t ; return_ownership: OwnershipAbstractValue.t ; return_attribute: Attribute.t ; attributes: AttributeMapDomain.t } let empty_summary = { threads= ThreadsDomain.bottom ; locks= LockDomain.bottom ; never_returns= false ; accesses= AccessDomain.bottom ; return_ownership= OwnershipAbstractValue.unowned ; return_attribute= Attribute.top ; attributes= AttributeMapDomain.top } let pp_summary fmt {threads; locks; never_returns; accesses; return_ownership; return_attribute; attributes} = F.fprintf fmt "@\n\ Threads: %a, Locks: %a, NeverReturns: %a @\n\ Accesses %a @\n\ Ownership: %a @\n\ Return Attribute: %a @\n\ Attributes: %a @\n" ThreadsDomain.pp threads LockDomain.pp locks NeverReturns.pp never_returns AccessDomain.pp accesses OwnershipAbstractValue.pp return_ownership Attribute.pp return_attribute AttributeMapDomain.pp attributes let pp fmt {threads; locks; never_returns; accesses; ownership; attribute_map} = F.fprintf fmt "Threads: %a, Locks: %a, NeverReturns: %a @\nAccesses %a @\nOwnership: %a @\nAttributes: %a @\n" ThreadsDomain.pp threads LockDomain.pp locks NeverReturns.pp never_returns AccessDomain.pp accesses OwnershipDomain.pp ownership AttributeMapDomain.pp attribute_map let add_unannotated_call_access formals pname actuals loc (astate : t) = apply_to_first_actual actuals astate ~f:(fun receiver -> let ownership = OwnershipDomain.get_owned receiver astate.ownership in let access_opt = AccessSnapshot.make_unannotated_call_access formals receiver pname astate.locks astate.threads ownership loc in {astate with accesses= AccessDomain.add_opt access_opt astate.accesses} ) let astate_to_summary proc_desc formals {threads; locks; never_returns; accesses; ownership; attribute_map} = let proc_name = Procdesc.get_proc_name proc_desc in let return_var_exp = AccessExpression.base (Var.of_pvar (Pvar.get_ret_pvar proc_name), Procdesc.get_ret_type proc_desc) in let return_ownership = OwnershipDomain.get_owned return_var_exp ownership in let return_attribute = AttributeMapDomain.get return_var_exp attribute_map in let locks = if Procdesc.is_java_synchronized proc_desc || Procdesc.is_csharp_synchronized proc_desc then LockDomain.release_lock locks else locks in let attributes = if Procname.is_java_class_initializer proc_name || Procname.is_constructor proc_name then AttributeMapDomain.filter (fun exp attribute -> match attribute with Synchronized -> should_keep_exp formals exp | _ -> false ) attribute_map else AttributeMapDomain.top in {threads; locks; never_returns; accesses; return_ownership; return_attribute; attributes} let add_access tenv formals loc ~is_write (astate : t) exp = let rec add_field_accesses prefix_path acc = function | [] -> acc | access :: access_list -> let prefix_path' = Option.value_exn (AccessExpression.add_access prefix_path access) in if (not (HilExp.Access.is_field_or_array_access access)) || RacerDModels.is_safe_access access prefix_path tenv then add_field_accesses prefix_path' acc access_list else let is_write = is_write && List.is_empty access_list in let pre = OwnershipDomain.get_owned prefix_path astate.ownership in let snapshot_opt = AccessSnapshot.make_access formals prefix_path' ~is_write loc astate.locks astate.threads pre in let access_acc' = AccessDomain.add_opt snapshot_opt acc in add_field_accesses prefix_path' access_acc' access_list in let accesses = List.fold (HilExp.get_access_exprs exp) ~init:astate.accesses ~f:(fun acc access_expr -> let base, accesses = AccessExpression.to_accesses access_expr in add_field_accesses base acc accesses ) in {astate with accesses} let add_container_access tenv formals ~is_write ret_base callee_pname actuals loc (astate : t) = match accexp_of_first_hilexp actuals with | None -> L.internal_error "Call to %a is marked as a container access, but has no receiver" Procname.pp callee_pname ; astate | Some receiver_expr when AttributeMapDomain.is_synchronized astate.attribute_map receiver_expr || RacerDModels.is_synchronized_container callee_pname receiver_expr tenv -> astate | Some receiver_expr -> let ownership_pre = OwnershipDomain.get_owned receiver_expr astate.ownership in let callee_access_opt = AccessSnapshot.make_container_access formals receiver_expr ~is_write callee_pname loc astate.locks astate.threads ownership_pre in let ownership = OwnershipDomain.add (AccessExpression.base ret_base) ownership_pre astate.ownership in let accesses = AccessDomain.add_opt callee_access_opt astate.accesses in {astate with accesses; ownership} let add_reads_of_hilexps tenv formals exps loc astate = List.fold exps ~init:astate ~f:(add_access tenv formals loc ~is_write:false) let add_callee_accesses ~caller_formals ~callee_formals ~callee_accesses callee_pname actuals loc (caller_astate : t) = let callsite = CallSite.make callee_pname loc in let actuals_array = Array.of_list_map actuals ~f:accexp_of_hilexp in let actuals_ownership = Array.of_list_map actuals ~f:(OwnershipDomain.ownership_of_expr caller_astate.ownership) in let process snapshot acc = AccessSnapshot.integrate_summary ~caller_formals ~callee_formals callsite caller_astate.threads caller_astate.locks actuals_array actuals_ownership snapshot |> fun snapshot_opt -> AccessDomain.add_opt snapshot_opt acc in let accesses = AccessDomain.fold process callee_accesses caller_astate.accesses in {caller_astate with accesses} let branch_never_returns () = { threads= ThreadsDomain.bottom ; locks= LockDomain.bottom ; never_returns= true ; accesses= AccessDomain.bottom ; ownership= OwnershipDomain.empty ; attribute_map= AttributeMapDomain.empty } let integrate_summary formals ~callee_proc_attrs summary ret_access_exp callee_pname actuals loc astate = let {threads; locks; never_returns; return_ownership; return_attribute} = summary in if never_returns then branch_never_returns () else let callee_formals = FormalMap.make callee_proc_attrs in let astate = add_callee_accesses ~caller_formals:formals ~callee_formals ~callee_accesses:summary.accesses callee_pname actuals loc astate in let locks = LockDomain.integrate_summary ~caller_astate:astate.locks ~callee_astate:locks in let ownership = OwnershipDomain.propagate_return ret_access_exp return_ownership actuals astate.ownership in let attribute_map = AttributeMapDomain.add ret_access_exp return_attribute astate.attribute_map in let threads = ThreadsDomain.integrate_summary ~caller_astate:astate.threads ~callee_astate:threads in {astate with locks; never_returns; threads; ownership; attribute_map} let acquire_lock (astate : t) = { astate with locks= LockDomain.acquire_lock astate.locks ; threads= ThreadsDomain.update_for_lock_use astate.threads } let release_lock (astate : t) = { astate with locks= LockDomain.release_lock astate.locks ; threads= ThreadsDomain.update_for_lock_use astate.threads } let lock_if_true ret_access_exp (astate : t) = { astate with attribute_map= AttributeMapDomain.add ret_access_exp Attribute.LockHeld astate.attribute_map ; threads= ThreadsDomain.update_for_lock_use astate.threads }
b5f8097b33f1fd2061bed04f58a5a7c6726bc8b2dd4d5a05f2cf108b57720d96
ConsumerDataStandardsAustralia/validation-prototype
Transaction.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} module Web.ConsumerData.Au.Api.Types.Banking.Common.Transaction ( module Web.ConsumerData.Au.Api.Types.Banking.Common.Transaction ) where import Control.Lens (Prism', prism, ( # )) import Control.Monad.Except (throwError) import Data.Functor.Contravariant (contramap, (>$<)) import Data.Text (Text) import Servant.API (FromHttpApiData, ToHttpApiData, parseUrlPiece, toUrlPiece) import Waargonaut.Decode (Decoder) import qualified Waargonaut.Decode as D import qualified Waargonaut.Decode.Error as D import Waargonaut.Encode (Encoder) import qualified Waargonaut.Encode as E import Waargonaut.Generic (JsonDecode (..), JsonEncode (..)) import Waargonaut.Types (Json, MapLikeObj, WS) import Waargonaut.Helpers (atKeyOptional', maybeOrAbsentE) import Web.ConsumerData.Au.Api.Types.Banking.Common.Accounts (AccountId, accountIdDecoder, accountIdEncoder) import Web.ConsumerData.Au.Api.Types.Data.CommonFieldTypes (AmountString, AsciiString, CurrencyString, DateTimeString, amountStringDecoder, amountStringEncoder, asciiStringDecoder, asciiStringEncoder, currencyStringDecoder, currencyStringEncoder, dateTimeStringDecoder, dateTimeStringEncoder) import Web.ConsumerData.Au.Api.Types.Tag newtype Transactions = Transactions { unTransactions :: [Transaction] } deriving (Eq, Show) transactionsDecoder :: Monad f => Decoder f Transactions transactionsDecoder = D.atKey "transactions" (Transactions <$> D.list transactionDecoder) transactionsEncoder :: Applicative f => Encoder f Transactions transactionsEncoder = E.mapLikeObj $ E.atKey' "transactions" (E.list transactionEncoder) . unTransactions instance JsonDecode OB Transactions where mkDecoder = tagOb transactionsDecoder instance JsonEncode OB Transactions where mkEncoder = tagOb transactionsEncoder data Transaction = Transaction { _transactionAccountId :: AccountId , _transactionTransactionId :: Maybe TransactionId , _transactionIsDetailAvailable :: Bool , _transactionType :: TransactionType , _transactionStatus :: TransactionStatus , _transactionDescription :: Text , _transactionValueDateTime :: Maybe DateTimeString , _transactionExecutionDateTime :: Maybe DateTimeString , _transactionAmount :: Maybe AmountString , _transactionCurrency :: Maybe CurrencyString , _transactionReference :: Text , _transactionMerchantName :: Maybe Text , _transactionMerchantCategoryCode :: Maybe Text , _transactionBillerCode :: Maybe Text , _transactionBillerName :: Maybe Text , _transactionCrn :: Maybe Text , _transactionApcaNumber :: Maybe Text } deriving (Eq, Show) transactionDecoder :: (Monad f) => Decoder f Transaction transactionDecoder = Transaction <$> D.atKey "accountId" accountIdDecoder <*> atKeyOptional' "transactionId" transactionIdDecoder <*> D.atKey "isDetailAvailable" D.bool <*> D.atKey "type" transactionTypeDecoder <*> transactionStatusDecoder <*> D.atKey "description" D.text <*> atKeyOptional' "valueDateTime" dateTimeStringDecoder <*> atKeyOptional' "executionDateTime" dateTimeStringDecoder <*> atKeyOptional' "amount" amountStringDecoder <*> atKeyOptional' "currency" currencyStringDecoder <*> D.atKey "reference" D.text <*> atKeyOptional' "merchantName" D.text <*> atKeyOptional' "merchantCategoryCode" D.text <*> atKeyOptional' "billerCode" D.text <*> atKeyOptional' "billerName" D.text <*> atKeyOptional' "crn" D.text <*> atKeyOptional' "apcaNumber" D.text instance JsonDecode OB Transaction where mkDecoder = tagOb transactionDecoder transactionEncoder :: Applicative f => Encoder f Transaction transactionEncoder = E.mapLikeObj transactionMLO transactionMLO :: Transaction -> MapLikeObj WS Json -> MapLikeObj WS Json transactionMLO t = E.atKey' "accountId" accountIdEncoder (_transactionAccountId t) . maybeOrAbsentE "transactionId" transactionIdEncoder (_transactionTransactionId t) . E.atKey' "isDetailAvailable" E.bool (_transactionIsDetailAvailable t) . E.atKey' "type" transactionTypeEncoder (_transactionType t) . transactionStatusFields (_transactionStatus t) . E.atKey' "description" E.text (_transactionDescription t) . maybeOrAbsentE "valueDateTime" dateTimeStringEncoder (_transactionValueDateTime t) . maybeOrAbsentE "executionDateTime" dateTimeStringEncoder (_transactionExecutionDateTime t) . maybeOrAbsentE "amount" amountStringEncoder (_transactionAmount t) . maybeOrAbsentE "currency" currencyStringEncoder (_transactionCurrency t) . E.atKey' "reference" E.text (_transactionReference t) . maybeOrAbsentE "merchantName" E.text (_transactionMerchantName t) . maybeOrAbsentE "merchantCategoryCode" E.text (_transactionMerchantCategoryCode t) . maybeOrAbsentE "billerCode" E.text (_transactionBillerCode t) . maybeOrAbsentE "billerName" E.text (_transactionBillerName t) . maybeOrAbsentE "crn" E.text (_transactionCrn t) . maybeOrAbsentE "apcaNumber" E.text (_transactionApcaNumber t) instance JsonEncode OB Transaction where mkEncoder = tagOb transactionEncoder newtype TransactionId = TransactionId { unTransactionId :: AsciiString } deriving (Eq, Show) transactionIdDecoder :: Monad f => Decoder f TransactionId transactionIdDecoder = TransactionId <$> asciiStringDecoder transactionIdEncoder :: Applicative f => Encoder f TransactionId transactionIdEncoder = unTransactionId >$< asciiStringEncoder instance ToHttpApiData TransactionId where toUrlPiece = toUrlPiece . unTransactionId instance FromHttpApiData TransactionId where parseUrlPiece = fmap TransactionId . parseUrlPiece data TransactionType = TransactionTypeFee -- ^"FEE" | TransactionTypeInterestCharged -- ^"INTEREST_CHARGED" | TransactionTypeInterestPaid -- ^"INTEREST_PAID" | TransactionTypeTransferOutgoing -- ^"TRANSFER_OUTGOING" | TransactionTypeTransferIncoming -- ^"TRANSFER_INCOMING" | TransactionTypePayment -- ^"PAYMENT" | TransactionTypeOther -- ^"OTHER" deriving (Bounded, Enum, Eq, Ord, Show) transactionTypeText :: Prism' Text TransactionType transactionTypeText = prism (\case TransactionTypeFee -> "FEE" TransactionTypeInterestCharged -> "INTEREST_CHARGED" TransactionTypeInterestPaid -> "INTEREST_PAID" TransactionTypeTransferOutgoing -> "TRANSFER_OUTGOING" TransactionTypeTransferIncoming -> "TRANSFER_INCOMING" TransactionTypePayment -> "PAYMENT" TransactionTypeOther -> "OTHER" ) (\case "FEE" -> Right TransactionTypeFee "INTEREST_CHARGED" -> Right TransactionTypeInterestCharged "INTEREST_PAID" -> Right TransactionTypeInterestPaid "TRANSFER_OUTGOING" -> Right TransactionTypeTransferOutgoing "TRANSFER_INCOMING" -> Right TransactionTypeTransferIncoming "PAYMENT" -> Right TransactionTypePayment "OTHER" -> Right TransactionTypeOther t -> Left t ) transactionTypeEncoder :: E.Encoder' TransactionType transactionTypeEncoder = E.prismE transactionTypeText E.text' transactionTypeDecoder :: Monad m => D.Decoder m TransactionType transactionTypeDecoder = D.prismDOrFail (D._ConversionFailure # "Not a valid TransactionType") transactionTypeText D.text data TransactionStatus = TransactionStatusPending -- ^ "PENDING" | TransactionStatusPosted DateTimeString -- ^ "POSTED" deriving (Eq, Show) transactionStatusDecoder :: Monad f => Decoder f TransactionStatus transactionStatusDecoder = do status <- D.atKey "status" D.text postingDateTime <- case status of "PENDING" -> pure TransactionStatusPending "POSTED" -> TransactionStatusPosted <$> (D.atKey "postingDateTime" dateTimeStringDecoder) _ -> throwError (D._ConversionFailure # "Not a valid TransactionStatus") pure postingDateTime transactionStatus'ToText :: TransactionStatus' -> Text transactionStatus'ToText = \case TransactionStatusPending' -> "PENDING" TransactionStatusPosted' -> "POSTED" data TransactionStatus' = TransactionStatusPending' | TransactionStatusPosted' transactionStatus'Encoder :: Applicative f => Encoder f TransactionStatus' transactionStatus'Encoder = flip contramap E.text transactionStatus'ToText transactionStatusToType' :: TransactionStatus -> TransactionStatus' transactionStatusToType' (TransactionStatusPending {}) = TransactionStatusPending' transactionStatusToType' (TransactionStatusPosted {}) = TransactionStatusPosted' transactionStatusFields :: (Monoid ws, Semigroup ws) => TransactionStatus -> MapLikeObj ws Json -> MapLikeObj ws Json transactionStatusFields ts = case ts of TransactionStatusPending -> E.atKey' "status" transactionStatus'Encoder (transactionStatusToType' ts) TransactionStatusPosted v -> E.atKey' "status" transactionStatus'Encoder (transactionStatusToType' ts) . E.atKey' "postingDateTime" dateTimeStringEncoder v
null
https://raw.githubusercontent.com/ConsumerDataStandardsAustralia/validation-prototype/ff63338b77339ee49fa3e0be5bb9d7f74e50c28b/consumer-data-au-api-types/src/Web/ConsumerData/Au/Api/Types/Banking/Common/Transaction.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # # LANGUAGE RankNTypes # # LANGUAGE TypeOperators # ^"FEE" ^"INTEREST_CHARGED" ^"INTEREST_PAID" ^"TRANSFER_OUTGOING" ^"TRANSFER_INCOMING" ^"PAYMENT" ^"OTHER" ^ "PENDING" ^ "POSTED"
# LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # module Web.ConsumerData.Au.Api.Types.Banking.Common.Transaction ( module Web.ConsumerData.Au.Api.Types.Banking.Common.Transaction ) where import Control.Lens (Prism', prism, ( # )) import Control.Monad.Except (throwError) import Data.Functor.Contravariant (contramap, (>$<)) import Data.Text (Text) import Servant.API (FromHttpApiData, ToHttpApiData, parseUrlPiece, toUrlPiece) import Waargonaut.Decode (Decoder) import qualified Waargonaut.Decode as D import qualified Waargonaut.Decode.Error as D import Waargonaut.Encode (Encoder) import qualified Waargonaut.Encode as E import Waargonaut.Generic (JsonDecode (..), JsonEncode (..)) import Waargonaut.Types (Json, MapLikeObj, WS) import Waargonaut.Helpers (atKeyOptional', maybeOrAbsentE) import Web.ConsumerData.Au.Api.Types.Banking.Common.Accounts (AccountId, accountIdDecoder, accountIdEncoder) import Web.ConsumerData.Au.Api.Types.Data.CommonFieldTypes (AmountString, AsciiString, CurrencyString, DateTimeString, amountStringDecoder, amountStringEncoder, asciiStringDecoder, asciiStringEncoder, currencyStringDecoder, currencyStringEncoder, dateTimeStringDecoder, dateTimeStringEncoder) import Web.ConsumerData.Au.Api.Types.Tag newtype Transactions = Transactions { unTransactions :: [Transaction] } deriving (Eq, Show) transactionsDecoder :: Monad f => Decoder f Transactions transactionsDecoder = D.atKey "transactions" (Transactions <$> D.list transactionDecoder) transactionsEncoder :: Applicative f => Encoder f Transactions transactionsEncoder = E.mapLikeObj $ E.atKey' "transactions" (E.list transactionEncoder) . unTransactions instance JsonDecode OB Transactions where mkDecoder = tagOb transactionsDecoder instance JsonEncode OB Transactions where mkEncoder = tagOb transactionsEncoder data Transaction = Transaction { _transactionAccountId :: AccountId , _transactionTransactionId :: Maybe TransactionId , _transactionIsDetailAvailable :: Bool , _transactionType :: TransactionType , _transactionStatus :: TransactionStatus , _transactionDescription :: Text , _transactionValueDateTime :: Maybe DateTimeString , _transactionExecutionDateTime :: Maybe DateTimeString , _transactionAmount :: Maybe AmountString , _transactionCurrency :: Maybe CurrencyString , _transactionReference :: Text , _transactionMerchantName :: Maybe Text , _transactionMerchantCategoryCode :: Maybe Text , _transactionBillerCode :: Maybe Text , _transactionBillerName :: Maybe Text , _transactionCrn :: Maybe Text , _transactionApcaNumber :: Maybe Text } deriving (Eq, Show) transactionDecoder :: (Monad f) => Decoder f Transaction transactionDecoder = Transaction <$> D.atKey "accountId" accountIdDecoder <*> atKeyOptional' "transactionId" transactionIdDecoder <*> D.atKey "isDetailAvailable" D.bool <*> D.atKey "type" transactionTypeDecoder <*> transactionStatusDecoder <*> D.atKey "description" D.text <*> atKeyOptional' "valueDateTime" dateTimeStringDecoder <*> atKeyOptional' "executionDateTime" dateTimeStringDecoder <*> atKeyOptional' "amount" amountStringDecoder <*> atKeyOptional' "currency" currencyStringDecoder <*> D.atKey "reference" D.text <*> atKeyOptional' "merchantName" D.text <*> atKeyOptional' "merchantCategoryCode" D.text <*> atKeyOptional' "billerCode" D.text <*> atKeyOptional' "billerName" D.text <*> atKeyOptional' "crn" D.text <*> atKeyOptional' "apcaNumber" D.text instance JsonDecode OB Transaction where mkDecoder = tagOb transactionDecoder transactionEncoder :: Applicative f => Encoder f Transaction transactionEncoder = E.mapLikeObj transactionMLO transactionMLO :: Transaction -> MapLikeObj WS Json -> MapLikeObj WS Json transactionMLO t = E.atKey' "accountId" accountIdEncoder (_transactionAccountId t) . maybeOrAbsentE "transactionId" transactionIdEncoder (_transactionTransactionId t) . E.atKey' "isDetailAvailable" E.bool (_transactionIsDetailAvailable t) . E.atKey' "type" transactionTypeEncoder (_transactionType t) . transactionStatusFields (_transactionStatus t) . E.atKey' "description" E.text (_transactionDescription t) . maybeOrAbsentE "valueDateTime" dateTimeStringEncoder (_transactionValueDateTime t) . maybeOrAbsentE "executionDateTime" dateTimeStringEncoder (_transactionExecutionDateTime t) . maybeOrAbsentE "amount" amountStringEncoder (_transactionAmount t) . maybeOrAbsentE "currency" currencyStringEncoder (_transactionCurrency t) . E.atKey' "reference" E.text (_transactionReference t) . maybeOrAbsentE "merchantName" E.text (_transactionMerchantName t) . maybeOrAbsentE "merchantCategoryCode" E.text (_transactionMerchantCategoryCode t) . maybeOrAbsentE "billerCode" E.text (_transactionBillerCode t) . maybeOrAbsentE "billerName" E.text (_transactionBillerName t) . maybeOrAbsentE "crn" E.text (_transactionCrn t) . maybeOrAbsentE "apcaNumber" E.text (_transactionApcaNumber t) instance JsonEncode OB Transaction where mkEncoder = tagOb transactionEncoder newtype TransactionId = TransactionId { unTransactionId :: AsciiString } deriving (Eq, Show) transactionIdDecoder :: Monad f => Decoder f TransactionId transactionIdDecoder = TransactionId <$> asciiStringDecoder transactionIdEncoder :: Applicative f => Encoder f TransactionId transactionIdEncoder = unTransactionId >$< asciiStringEncoder instance ToHttpApiData TransactionId where toUrlPiece = toUrlPiece . unTransactionId instance FromHttpApiData TransactionId where parseUrlPiece = fmap TransactionId . parseUrlPiece data TransactionType = deriving (Bounded, Enum, Eq, Ord, Show) transactionTypeText :: Prism' Text TransactionType transactionTypeText = prism (\case TransactionTypeFee -> "FEE" TransactionTypeInterestCharged -> "INTEREST_CHARGED" TransactionTypeInterestPaid -> "INTEREST_PAID" TransactionTypeTransferOutgoing -> "TRANSFER_OUTGOING" TransactionTypeTransferIncoming -> "TRANSFER_INCOMING" TransactionTypePayment -> "PAYMENT" TransactionTypeOther -> "OTHER" ) (\case "FEE" -> Right TransactionTypeFee "INTEREST_CHARGED" -> Right TransactionTypeInterestCharged "INTEREST_PAID" -> Right TransactionTypeInterestPaid "TRANSFER_OUTGOING" -> Right TransactionTypeTransferOutgoing "TRANSFER_INCOMING" -> Right TransactionTypeTransferIncoming "PAYMENT" -> Right TransactionTypePayment "OTHER" -> Right TransactionTypeOther t -> Left t ) transactionTypeEncoder :: E.Encoder' TransactionType transactionTypeEncoder = E.prismE transactionTypeText E.text' transactionTypeDecoder :: Monad m => D.Decoder m TransactionType transactionTypeDecoder = D.prismDOrFail (D._ConversionFailure # "Not a valid TransactionType") transactionTypeText D.text data TransactionStatus = deriving (Eq, Show) transactionStatusDecoder :: Monad f => Decoder f TransactionStatus transactionStatusDecoder = do status <- D.atKey "status" D.text postingDateTime <- case status of "PENDING" -> pure TransactionStatusPending "POSTED" -> TransactionStatusPosted <$> (D.atKey "postingDateTime" dateTimeStringDecoder) _ -> throwError (D._ConversionFailure # "Not a valid TransactionStatus") pure postingDateTime transactionStatus'ToText :: TransactionStatus' -> Text transactionStatus'ToText = \case TransactionStatusPending' -> "PENDING" TransactionStatusPosted' -> "POSTED" data TransactionStatus' = TransactionStatusPending' | TransactionStatusPosted' transactionStatus'Encoder :: Applicative f => Encoder f TransactionStatus' transactionStatus'Encoder = flip contramap E.text transactionStatus'ToText transactionStatusToType' :: TransactionStatus -> TransactionStatus' transactionStatusToType' (TransactionStatusPending {}) = TransactionStatusPending' transactionStatusToType' (TransactionStatusPosted {}) = TransactionStatusPosted' transactionStatusFields :: (Monoid ws, Semigroup ws) => TransactionStatus -> MapLikeObj ws Json -> MapLikeObj ws Json transactionStatusFields ts = case ts of TransactionStatusPending -> E.atKey' "status" transactionStatus'Encoder (transactionStatusToType' ts) TransactionStatusPosted v -> E.atKey' "status" transactionStatus'Encoder (transactionStatusToType' ts) . E.atKey' "postingDateTime" dateTimeStringEncoder v
438bb97ed5710d6491f083d17d032c038d2b29c3eb39329a59c784c4e29d56d8
coq/coq
dune_file.mli
(************************************************************************) This file is licensed under The MIT License (* See LICENSE for more information *) (************************************************************************) type 'a pp = Format.formatter -> 'a -> unit module Rule : sig type t = { targets : string list ; deps : string list ; action : string ; alias : string option } val pp : t pp end module Install : sig type t = { section : string ; package : string ; files : (string * string) list (* (source as target) *) } val pp : t pp end module Subdir : sig type 'a t = { subdir : string; payload : 'a } val pp : 'a pp -> 'a t pp end
null
https://raw.githubusercontent.com/coq/coq/0973e012d615c0722d483cd5d814bde90c76d7d3/tools/dune_rule_gen/dune_file.mli
ocaml
********************************************************************** See LICENSE for more information ********************************************************************** (source as target)
This file is licensed under The MIT License type 'a pp = Format.formatter -> 'a -> unit module Rule : sig type t = { targets : string list ; deps : string list ; action : string ; alias : string option } val pp : t pp end module Install : sig type t = { section : string ; package : string ; files : (string * string) list } val pp : t pp end module Subdir : sig type 'a t = { subdir : string; payload : 'a } val pp : 'a pp -> 'a t pp end
7e3bdc2cb9f28d1c836e1ebadfc63ecc748bf6cf4294519da9a2cc8abfe7f915
sjl/newseasons
keys.clj
(ns newseasons.models.keys) (defn key-show [id] (str "shows:" id)) (defn key-user [email] (str "users:" email)) (defn key-user-shows [email] (str "users:" email ":shows")) (defn key-show-watchers [id] (str "shows:" id ":watchers"))
null
https://raw.githubusercontent.com/sjl/newseasons/9f3bce450b413ee065abcf1b6b5b7dbdd8728481/src/newseasons/models/keys.clj
clojure
(ns newseasons.models.keys) (defn key-show [id] (str "shows:" id)) (defn key-user [email] (str "users:" email)) (defn key-user-shows [email] (str "users:" email ":shows")) (defn key-show-watchers [id] (str "shows:" id ":watchers"))
ef3dc10ac029520378ea4d0c70e4a21157bfaca49c078156cb46d2410400581f
danr/hipspec
Tricky.hs
Lists and functions , many properties come from QuickSpec module Tricky where import Hip.Prelude import Prelude (Eq,Ord,Show,iterate,(!!),fmap,Bool(..),Int) data Nat = Z | S Nat -- PAPs Z + y = y (S x) + y = S (x + y) map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = (f x) : (map f xs) one = S Z ( + one ) and ( one + ) is not equal here . ( of course ) One is a finite theorem and the other is a theorem . The two - depth structural -- induction finds the finite theorem, but the simple induction fails -- to find this as it is not a theorem with : if the natural number is -- not total. incr = map (one +) incrrec (x:xs) = S x : incrrec xs incrrec [] = [] prop_equal :: [Nat] -> Prop [Nat] prop_equal xs = incrrec xs =:= incr xs -- double speed fpi ----------------------------------------------------------- iter :: (a -> a) -> a -> [a] iter f x = x : iter f (f x) doublemap :: (a -> b) -> [a] -> [b] doublemap f [] = [] doublemap f [x] = [f x] doublemap f (x:y:zs) = f x:f y:doublemap f zs prop_doublemap_iter :: (a -> a) -> a -> Prop [a] prop_doublemap_iter f x = doublemap f (iter f x) =:= iter f (f x) doublemap' :: (a -> b) -> [a] -> [b] doublemap' f [] = [] doublemap' f (x:xs) = f x : case xs of [] -> [] y:zs -> f y : doublemap' f zs prop_doublemap'_iter :: (a -> a) -> a -> Prop [a] prop_doublemap'_iter f x = doublemap' f (iter f x) =:= iter f (f x) This needs depth 2 on structural induction -- Is it possible to prove this with take lemma? Maybe it's time to upvote take lemma. prop_doublemaps :: Prop ((a -> b) -> [a] -> [b]) prop_doublemaps = doublemap =:= doublemap' finite :: [a] -> Bool finite [] = True finite (x:xs) = finite xs prop_all_lists_finite :: [a] -> Prop Bool prop_all_lists_finite xs = finite xs =:= True , which is true for total but not partial lists ------------- otherwise = True True == True = True False == False = True _ == _ = False nub :: [Bool] -> [Bool] nub (True :True :xs) = nub (True:xs) nub (False:False:xs) = nub (False:xs) nub (x:xs) = x:nub xs nub _ = [] nub' :: [Bool] -> [Bool] nub' (x:y:xs) | x == y = nub' (y:xs) | otherwise = x:nub' (y:xs) nub' xs = xs prop_nub_idem :: [Bool] -> Prop [Bool] prop_nub_idem xs = nub (nub xs) =:= nub xs prop_nub'_idem :: [Bool] -> Prop [Bool] prop_nub'_idem xs = nub' (nub' xs) =:= nub' xs prop_nub_equal :: Prop ([Bool] -> [Bool]) prop_nub_equal = nub =:= nub'
null
https://raw.githubusercontent.com/danr/hipspec/a114db84abd5fee8ce0b026abc5380da11147aa9/examples/old-examples/hip/Tricky.hs
haskell
PAPs induction finds the finite theorem, but the simple induction fails to find this as it is not a theorem with : if the natural number is not total. double speed fpi ----------------------------------------------------------- Is it possible to prove this with take lemma? Maybe it's time to upvote take lemma. -----------
Lists and functions , many properties come from QuickSpec module Tricky where import Hip.Prelude import Prelude (Eq,Ord,Show,iterate,(!!),fmap,Bool(..),Int) data Nat = Z | S Nat Z + y = y (S x) + y = S (x + y) map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = (f x) : (map f xs) one = S Z ( + one ) and ( one + ) is not equal here . ( of course ) One is a finite theorem and the other is a theorem . The two - depth structural incr = map (one +) incrrec (x:xs) = S x : incrrec xs incrrec [] = [] prop_equal :: [Nat] -> Prop [Nat] prop_equal xs = incrrec xs =:= incr xs iter :: (a -> a) -> a -> [a] iter f x = x : iter f (f x) doublemap :: (a -> b) -> [a] -> [b] doublemap f [] = [] doublemap f [x] = [f x] doublemap f (x:y:zs) = f x:f y:doublemap f zs prop_doublemap_iter :: (a -> a) -> a -> Prop [a] prop_doublemap_iter f x = doublemap f (iter f x) =:= iter f (f x) doublemap' :: (a -> b) -> [a] -> [b] doublemap' f [] = [] doublemap' f (x:xs) = f x : case xs of [] -> [] y:zs -> f y : doublemap' f zs prop_doublemap'_iter :: (a -> a) -> a -> Prop [a] prop_doublemap'_iter f x = doublemap' f (iter f x) =:= iter f (f x) This needs depth 2 on structural induction prop_doublemaps :: Prop ((a -> b) -> [a] -> [b]) prop_doublemaps = doublemap =:= doublemap' finite :: [a] -> Bool finite [] = True finite (x:xs) = finite xs prop_all_lists_finite :: [a] -> Prop Bool prop_all_lists_finite xs = finite xs =:= True otherwise = True True == True = True False == False = True _ == _ = False nub :: [Bool] -> [Bool] nub (True :True :xs) = nub (True:xs) nub (False:False:xs) = nub (False:xs) nub (x:xs) = x:nub xs nub _ = [] nub' :: [Bool] -> [Bool] nub' (x:y:xs) | x == y = nub' (y:xs) | otherwise = x:nub' (y:xs) nub' xs = xs prop_nub_idem :: [Bool] -> Prop [Bool] prop_nub_idem xs = nub (nub xs) =:= nub xs prop_nub'_idem :: [Bool] -> Prop [Bool] prop_nub'_idem xs = nub' (nub' xs) =:= nub' xs prop_nub_equal :: Prop ([Bool] -> [Bool]) prop_nub_equal = nub =:= nub'
e2da1382a6290307748e0ef712fd39f495407932c3defa0589783988f0763be5
CodyReichert/qi
test-datagram.lisp
(in-package :usocket-test) (defvar *echo-server*) (defvar *echo-server-port*) (defun start-server () (multiple-value-bind (thread socket) (usocket:socket-server "127.0.0.1" 0 #'identity nil :in-new-thread t :protocol :datagram) (setq *echo-server* thread *echo-server-port* (usocket:get-local-port socket)))) (defparameter *max-buffer-size* 32) (defvar *send-buffer* (make-array *max-buffer-size* :element-type '(unsigned-byte 8) :initial-element 0)) (defvar *receive-buffer* (make-array *max-buffer-size* :element-type '(unsigned-byte 8) :initial-element 0)) (defun clean-buffers () (fill *send-buffer* 0) (fill *receive-buffer* 0)) UDP Send Test # 1 : connected socket (deftest udp-send.1 (progn (unless (and *echo-server* *echo-server-port*) (start-server)) (let ((s (usocket:socket-connect "127.0.0.1" *echo-server-port* :protocol :datagram))) (clean-buffers) (replace *send-buffer* #(1 2 3 4 5)) (usocket:socket-send s *send-buffer* 5) (usocket:wait-for-input s :timeout 3) (multiple-value-bind (buffer size host port) (usocket:socket-receive s *receive-buffer* *max-buffer-size*) (declare (ignore buffer size host port)) (reduce #'+ *receive-buffer* :start 0 :end 5)))) 15) UDP Send Test # 2 : unconnected socket (deftest udp-send.2 (progn (unless (and *echo-server* *echo-server-port*) (start-server)) (let ((s (usocket:socket-connect nil nil :protocol :datagram))) (clean-buffers) (replace *send-buffer* #(1 2 3 4 5)) (usocket:socket-send s *send-buffer* 5 :host "127.0.0.1" :port *echo-server-port*) (usocket:wait-for-input s :timeout 3) (multiple-value-bind (buffer size host port) (usocket:socket-receive s *receive-buffer* *max-buffer-size*) (declare (ignore buffer size host port)) (reduce #'+ *receive-buffer* :start 0 :end 5)))) 15) remarkable UDP test code (let* ((host "localhost") (port 1111) (server-sock (usocket:socket-connect nil nil :protocol ':datagram :local-host host :local-port port)) (client-sock (usocket:socket-connect host port :protocol ':datagram)) (octet-vector (make-array 2 :element-type '(unsigned-byte 8) :initial-contents `(,(char-code #\O) ,(char-code #\K)))) (recv-octet-vector (make-array 2 :element-type '(unsigned-byte 8)))) (usocket:socket-send client-sock octet-vector 2) (usocket:socket-receive server-sock recv-octet-vector 2) (prog1 (and (equalp octet-vector recv-octet-vector) recv-octet-vector) (usocket:socket-close server-sock) (usocket:socket-close client-sock))) #(79 75)) test code for LispWorks / UDP (with-caught-conditions (#+win32 USOCKET:CONNECTION-RESET-ERROR #-win32 USOCKET:CONNECTION-REFUSED-ERROR nil) (let ((sock (usocket:socket-connect "localhost" 1234 :protocol ':datagram :element-type '(unsigned-byte 8)))) (unwind-protect (progn (usocket:socket-send sock (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0) 16) (let ((buffer (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0))) (usocket:socket-receive sock buffer 16))) (usocket:socket-close sock)))) nil) (defun frank-wfi-test () (let ((s (usocket:socket-connect nil nil :protocol :datagram :element-type '(unsigned-byte 8) :local-port 8001))) (unwind-protect (do ((i 0 (1+ i)) (buffer (make-array 1024 :element-type '(unsigned-byte 8) :initial-element 0)) (now (get-universal-time)) (done nil)) ((or done (= i 4)) nil) (format t "~Ds ~D Waiting state ~S~%" (- (get-universal-time) now) i (usocket::state s)) (when (usocket:wait-for-input s :ready-only t :timeout 5) (format t "~D state ~S~%" i (usocket::state s)) (handler-bind ((error (lambda (c) (format t "socket-receive error: ~A~%" c) (break) nil))) (multiple-value-bind (buffer count remote-host remote-port) (usocket:socket-receive s buffer 1024) (handler-bind ((error (lambda (c) (format t "socket-send error: ~A~%" c) (break)))) (when buffer (usocket:socket-send s (subseq buffer 0 count) count :host remote-host :port remote-port))))))) (usocket:socket-close s))))
null
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/usocket-latest/test/test-datagram.lisp
lisp
(in-package :usocket-test) (defvar *echo-server*) (defvar *echo-server-port*) (defun start-server () (multiple-value-bind (thread socket) (usocket:socket-server "127.0.0.1" 0 #'identity nil :in-new-thread t :protocol :datagram) (setq *echo-server* thread *echo-server-port* (usocket:get-local-port socket)))) (defparameter *max-buffer-size* 32) (defvar *send-buffer* (make-array *max-buffer-size* :element-type '(unsigned-byte 8) :initial-element 0)) (defvar *receive-buffer* (make-array *max-buffer-size* :element-type '(unsigned-byte 8) :initial-element 0)) (defun clean-buffers () (fill *send-buffer* 0) (fill *receive-buffer* 0)) UDP Send Test # 1 : connected socket (deftest udp-send.1 (progn (unless (and *echo-server* *echo-server-port*) (start-server)) (let ((s (usocket:socket-connect "127.0.0.1" *echo-server-port* :protocol :datagram))) (clean-buffers) (replace *send-buffer* #(1 2 3 4 5)) (usocket:socket-send s *send-buffer* 5) (usocket:wait-for-input s :timeout 3) (multiple-value-bind (buffer size host port) (usocket:socket-receive s *receive-buffer* *max-buffer-size*) (declare (ignore buffer size host port)) (reduce #'+ *receive-buffer* :start 0 :end 5)))) 15) UDP Send Test # 2 : unconnected socket (deftest udp-send.2 (progn (unless (and *echo-server* *echo-server-port*) (start-server)) (let ((s (usocket:socket-connect nil nil :protocol :datagram))) (clean-buffers) (replace *send-buffer* #(1 2 3 4 5)) (usocket:socket-send s *send-buffer* 5 :host "127.0.0.1" :port *echo-server-port*) (usocket:wait-for-input s :timeout 3) (multiple-value-bind (buffer size host port) (usocket:socket-receive s *receive-buffer* *max-buffer-size*) (declare (ignore buffer size host port)) (reduce #'+ *receive-buffer* :start 0 :end 5)))) 15) remarkable UDP test code (let* ((host "localhost") (port 1111) (server-sock (usocket:socket-connect nil nil :protocol ':datagram :local-host host :local-port port)) (client-sock (usocket:socket-connect host port :protocol ':datagram)) (octet-vector (make-array 2 :element-type '(unsigned-byte 8) :initial-contents `(,(char-code #\O) ,(char-code #\K)))) (recv-octet-vector (make-array 2 :element-type '(unsigned-byte 8)))) (usocket:socket-send client-sock octet-vector 2) (usocket:socket-receive server-sock recv-octet-vector 2) (prog1 (and (equalp octet-vector recv-octet-vector) recv-octet-vector) (usocket:socket-close server-sock) (usocket:socket-close client-sock))) #(79 75)) test code for LispWorks / UDP (with-caught-conditions (#+win32 USOCKET:CONNECTION-RESET-ERROR #-win32 USOCKET:CONNECTION-REFUSED-ERROR nil) (let ((sock (usocket:socket-connect "localhost" 1234 :protocol ':datagram :element-type '(unsigned-byte 8)))) (unwind-protect (progn (usocket:socket-send sock (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0) 16) (let ((buffer (make-array 16 :element-type '(unsigned-byte 8) :initial-element 0))) (usocket:socket-receive sock buffer 16))) (usocket:socket-close sock)))) nil) (defun frank-wfi-test () (let ((s (usocket:socket-connect nil nil :protocol :datagram :element-type '(unsigned-byte 8) :local-port 8001))) (unwind-protect (do ((i 0 (1+ i)) (buffer (make-array 1024 :element-type '(unsigned-byte 8) :initial-element 0)) (now (get-universal-time)) (done nil)) ((or done (= i 4)) nil) (format t "~Ds ~D Waiting state ~S~%" (- (get-universal-time) now) i (usocket::state s)) (when (usocket:wait-for-input s :ready-only t :timeout 5) (format t "~D state ~S~%" i (usocket::state s)) (handler-bind ((error (lambda (c) (format t "socket-receive error: ~A~%" c) (break) nil))) (multiple-value-bind (buffer count remote-host remote-port) (usocket:socket-receive s buffer 1024) (handler-bind ((error (lambda (c) (format t "socket-send error: ~A~%" c) (break)))) (when buffer (usocket:socket-send s (subseq buffer 0 count) count :host remote-host :port remote-port))))))) (usocket:socket-close s))))
4d01b0d3c617f05d17bc8d81de82ce70c6a5c358d61787b9f80b6b5f1ca8c7c3
jlouis/eministat
eministat_analysis.erl
-module(eministat_analysis). -include("eministat.hrl"). -export([outlier_variance/3]). -export([relative/3]). %% -- OUTLIER VARIANCE ------ %% @doc outlier_variance/3 computes the severity of the outlier variance %% %% %% %% @end outlier_variance(_, Sigma, _) when Sigma < 0.000000000000001 -> {0.0, unaffected}; outlier_variance(Mu, Sigma, A) -> MinBy = fun(F, Q, R) -> min(F(Q), F(R)) end, MuA = Mu / A, MugMin = MuA / 2, SigmaG = min(MugMin / 4, Sigma / math:sqrt(A)), SigmaG2 = SigmaG * SigmaG, Sigma2 = Sigma * Sigma, VarOut = fun(C) -> AC = A - C, (AC / A) * (Sigma2 - AC * SigmaG2) end, CMax = fun(X) -> K = MuA - X, D = K * K, AD = A * D, K0 = -A * AD, K1 = Sigma2 - A * SigmaG2 + AD, Det = K1 * K1 - 4 * SigmaG2 * K0, trunc(-2 * K0 / (K1 + math:sqrt(Det))) end, VarOutMin = MinBy(VarOut, 1, (MinBy(CMax, 0, MugMin))) / Sigma2, case VarOutMin of K when K < 0.01 -> {K, unaffected}; K when K < 0.1 -> {K, slight}; K when K < 0.5 -> {K, moderate}; K when K > 0.5 -> {K, severe} end. %% -- RELATIVE #dataset{} COMPARISONS ----- relative(#dataset { n = DsN } = Ds, #dataset { n = RsN } = Rs, ConfIdx) -> I = DsN + RsN - 2, T = element(ConfIdx, student_lookup(I)), Spool1 = (DsN - 1) * eministat_ds:variance(Ds) + (RsN - 1) * eministat_ds:variance(Rs), Spool = math:sqrt(Spool1 / I), S = Spool * math:sqrt(1.0 / DsN + 1.0 / RsN), D = eministat_ds:mean(Ds) - eministat_ds:mean(Rs), E = T * S, case abs(D) > E of false -> {no_difference, element(ConfIdx, student_pct())}; true -> {difference, #{ confidence_level => element(ConfIdx, student_pct()), difference => {D, E}, difference_pct => { D * 100 / eministat_ds:mean(Rs), E * 100 / eministat_ds:mean(Rs)}, pooled_s => Spool }} end. %% -- STUDENT's T TABLES ----- %% Constant tables, represented as tuples for O(1) lookup speeds student_pct() -> {80.0, 90.0, 95.0, 98.0, 99.0, 99.5}. student_inf() -> { 1.282, 1.645, 1.960, 2.326, 2.576, 3.090 }. %% inf -define(NSTUDENT, 100). %% Number of elements in the students distribution lookup table student() -> { 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 10 . 11 . 12 . 13 . 14 . 15 . 16 . 17 . 18 . 19 . 20 . 21 . 22 . 23 . 24 . 25 . 26 . 27 . 28 . 29 . 30 . 31 . 32 . 33 . 34 . 35 . 36 . 37 . 38 . 39 . 40 . 41 . 42 . 43 . 44 . 45 . 46 . 47 . 48 . 49 . 50 . 51 . 52 . 53 . 54 . 55 . 56 . 57 . 58 . 59 . 60 . 61 . 62 . 63 . 64 . 65 . 66 . 67 . 68 . 69 . 70 . 71 . 72 . 73 . 74 . 75 . 76 . 77 . 78 . 79 . 80 . 81 . 82 . 83 . 84 . 85 . 86 . 87 . 88 . 89 . 90 . 91 . 92 . 93 . 94 . 95 . 96 . 97 . 98 . 99 . 100 . }. student_lookup(I) when I > ?NSTUDENT -> student_inf(); student_lookup(I) -> element(I, student()).
null
https://raw.githubusercontent.com/jlouis/eministat/022764f2b8fa45909c38cdc9a28d199656e78526/src/eministat_analysis.erl
erlang
-- OUTLIER VARIANCE ------ @end -- RELATIVE #dataset{} COMPARISONS ----- -- STUDENT's T TABLES ----- Constant tables, represented as tuples for O(1) lookup speeds inf Number of elements in the students distribution lookup table
-module(eministat_analysis). -include("eministat.hrl"). -export([outlier_variance/3]). -export([relative/3]). @doc outlier_variance/3 computes the severity of the outlier variance outlier_variance(_, Sigma, _) when Sigma < 0.000000000000001 -> {0.0, unaffected}; outlier_variance(Mu, Sigma, A) -> MinBy = fun(F, Q, R) -> min(F(Q), F(R)) end, MuA = Mu / A, MugMin = MuA / 2, SigmaG = min(MugMin / 4, Sigma / math:sqrt(A)), SigmaG2 = SigmaG * SigmaG, Sigma2 = Sigma * Sigma, VarOut = fun(C) -> AC = A - C, (AC / A) * (Sigma2 - AC * SigmaG2) end, CMax = fun(X) -> K = MuA - X, D = K * K, AD = A * D, K0 = -A * AD, K1 = Sigma2 - A * SigmaG2 + AD, Det = K1 * K1 - 4 * SigmaG2 * K0, trunc(-2 * K0 / (K1 + math:sqrt(Det))) end, VarOutMin = MinBy(VarOut, 1, (MinBy(CMax, 0, MugMin))) / Sigma2, case VarOutMin of K when K < 0.01 -> {K, unaffected}; K when K < 0.1 -> {K, slight}; K when K < 0.5 -> {K, moderate}; K when K > 0.5 -> {K, severe} end. relative(#dataset { n = DsN } = Ds, #dataset { n = RsN } = Rs, ConfIdx) -> I = DsN + RsN - 2, T = element(ConfIdx, student_lookup(I)), Spool1 = (DsN - 1) * eministat_ds:variance(Ds) + (RsN - 1) * eministat_ds:variance(Rs), Spool = math:sqrt(Spool1 / I), S = Spool * math:sqrt(1.0 / DsN + 1.0 / RsN), D = eministat_ds:mean(Ds) - eministat_ds:mean(Rs), E = T * S, case abs(D) > E of false -> {no_difference, element(ConfIdx, student_pct())}; true -> {difference, #{ confidence_level => element(ConfIdx, student_pct()), difference => {D, E}, difference_pct => { D * 100 / eministat_ds:mean(Rs), E * 100 / eministat_ds:mean(Rs)}, pooled_s => Spool }} end. student_pct() -> {80.0, 90.0, 95.0, 98.0, 99.0, 99.5}. student_inf() -> student() -> { 1 . 2 . 3 . 4 . 5 . 6 . 7 . 8 . 9 . 10 . 11 . 12 . 13 . 14 . 15 . 16 . 17 . 18 . 19 . 20 . 21 . 22 . 23 . 24 . 25 . 26 . 27 . 28 . 29 . 30 . 31 . 32 . 33 . 34 . 35 . 36 . 37 . 38 . 39 . 40 . 41 . 42 . 43 . 44 . 45 . 46 . 47 . 48 . 49 . 50 . 51 . 52 . 53 . 54 . 55 . 56 . 57 . 58 . 59 . 60 . 61 . 62 . 63 . 64 . 65 . 66 . 67 . 68 . 69 . 70 . 71 . 72 . 73 . 74 . 75 . 76 . 77 . 78 . 79 . 80 . 81 . 82 . 83 . 84 . 85 . 86 . 87 . 88 . 89 . 90 . 91 . 92 . 93 . 94 . 95 . 96 . 97 . 98 . 99 . 100 . }. student_lookup(I) when I > ?NSTUDENT -> student_inf(); student_lookup(I) -> element(I, student()).
473429ccc4598ae11ceccc0d1b816fd262c209af028e383a7f6a02ab557bbc82
massung/parse
parse.lisp
Monadic parsing package for Common Lisp ;;;; Copyright ( c ) ;;;; 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. ;;;; (defpackage :parse (:use :cl) (:export #:parse ;; declare a parse combinator #:define-parser ;; monadic bind functions #:>>= #:>> ;; combinator macros #:.prog1 #:.progn #:.let #:.let* #:.do #:.or ;; monadic functions #:.ret #:.fail #:.get #:.put #:.modify #:.push #:.pop ;; parse combinators #:.any #:.eof #:.is #:.either #:.opt #:.ignore #:.all #:.maybe #:.many #:.many1 #:.many-until #:.sep-by #:.sep-by1 #:.skip-many #:.skip-many1 #:.between)) (in-package :parse) ;;; ---------------------------------------------------- (defstruct parse-state read-token tokens token-last data) ;;; ---------------------------------------------------- (defun parse-state-next-token (st) "Returns the next token in the token list as a cons pair." (cadr (parse-state-tokens st))) ;;; ---------------------------------------------------- (defun parse-state-token-class (st) "Returns the class of the current token." (car (parse-state-next-token st))) ;;; ---------------------------------------------------- (defun parse-state-token-value (st) "Returns the value of the current token." (cdr (parse-state-next-token st))) ;;; ---------------------------------------------------- (defun parse (p next-token &key initial-state (errorp t) error-value) "Create a parse-state and pass it through a parse combinator." (let* ((token-cache (list nil)) ;; create the initial parse state (st (make-parse-state :tokens token-cache :token-last token-cache :data initial-state))) ;; create a function that will read into the shared token list (setf (parse-state-read-token st) #'(lambda () (multiple-value-bind (class value) (funcall next-token) (car (setf (parse-state-token-last st) (cdr (rplacd (parse-state-token-last st) (list (cons class value))))))))) read the first token as the current token (funcall (parse-state-read-token st)) ;; parse the token stream (multiple-value-bind (x okp) (funcall p st) (cond (okp (values x t)) ;; should we error out? (errorp (error "Parse failure")) ;; return the error result and parse failure (t (values error-value nil)))))) ;;; ---------------------------------------------------- (defun satisfy (st pred) "Read the next token if necesary, test class, return value." (destructuring-bind (class . value) (let ((token (parse-state-next-token st))) (if token token (funcall (parse-state-read-token st)))) (when (funcall pred class) (let ((nst (copy-parse-state st))) (multiple-value-prog1 (values value nst) (pop (parse-state-tokens nst))))))) ;;; ---------------------------------------------------- (defmacro define-parser (name &body ps) "Create a parse combinator." (let ((st (gensym))) `(defun ,name (,st) ;; add a documentation string to the parser if provided ,(when (stringp (first ps)) (pop ps)) ;; parse the combinators, return the final result (funcall (.do ,@ps) ,st)))) ;;; ---------------------------------------------------- (defun >>= (p f) "Monadic bind combinator." #'(lambda (st) (multiple-value-bind (x nst) (funcall p st) (when nst (funcall (funcall f x) nst))))) ;;; ---------------------------------------------------- (defun >> (p m) "Monadic bind, ignore intermediate result." #'(lambda (st) (let ((nst (nth-value 1 (funcall p st)))) (when nst (funcall m nst))))) ;;; ---------------------------------------------------- (defmacro .prog1 (form &body rest) "Macro to execute Lisp expressions, returning the first result." `(.ret (prog1 ,form ,@rest))) ;;; ---------------------------------------------------- (defmacro .progn (&body rest) "Macro to execute Lisp expressions, returning the last result." `(.ret (progn ,@rest))) ;;; ---------------------------------------------------- (defmacro .let ((var p) &body body) "Macro for >>= to make it more readable." `(>>= ,p #'(lambda (,var) (declare (ignorable ,var)) ,@body))) ;;; ---------------------------------------------------- (defmacro .let* ((binding &rest bindings) &body body) "Macro for making multiple .let bindings more readable." (if (null bindings) `(.let ,binding ,@body) `(.let ,binding (.let* ,bindings ,@body)))) ;;; ---------------------------------------------------- (defmacro .do (p &rest ps) "Chained together >> combinators." (labels ((chain (p ps) (if (null ps) p `(>> ,p ,(chain (first ps) (rest ps)))))) (chain p ps))) ;;; ---------------------------------------------------- (defmacro .or (p &rest ps) "Chained together or combinators." (labels ((try (p ps) (if (null ps) p `(.either ,p ,(try (first ps) (rest ps)))))) (try p ps))) ;;; ---------------------------------------------------- (defun .ret (x) "Convert X into a monadic value." #'(lambda (st) (values x st))) ;;; ---------------------------------------------------- (defun .fail (datum &rest arguments) "Ensures that the parse combinator fails." #'(lambda (st) (declare (ignore st)) (apply #'error datum arguments))) ;;; ---------------------------------------------------- (defun .get () "Always succeeds, returns the current parse state data." #'(lambda (st) (values (parse-state-data st) st))) ;;; ---------------------------------------------------- (defun .put (x) "Always succeeds, puts data into the parse state." #'(lambda (st) (let ((nst (copy-parse-state st))) (values (setf (parse-state-data nst) x) nst)))) ;;; ---------------------------------------------------- (defun .modify (f) "Always succeeds, applys f with the parse state data." (.let (x (.get)) (.put (funcall f x)))) ;;; ---------------------------------------------------- (defun .push (x) "Always succeeds, assumes data is a list and pushes x onto it." (.let (xs (.get)) (.put (cons x xs)))) ;;; ---------------------------------------------------- (defun .pop () "Always succeeds, assumes data is a list an pops it." (.let (xs (.get)) (.do (.put (cdr xs)) (.ret (car xs))))) ;;; ---------------------------------------------------- (defun .any () "Succeeds if not at the end of the token stream." #'(lambda (st) (satisfy st #'identity))) ;;; ---------------------------------------------------- (defun .eof () "Succeeds if at the end of the token stream." #'(lambda (st) (satisfy st #'null))) ;;; ---------------------------------------------------- (defun .is (class &key (test #'eql)) "Checks if the current token is of a given class." #'(lambda (st) (satisfy st #'(lambda (c) (funcall test c class))))) ;;; ---------------------------------------------------- (defun .either (p1 p2) "Attempt to parse p1, if that fails, try p2." #'(lambda (st) (multiple-value-bind (x nst) (funcall p1 st) (if nst (values x nst) (funcall p2 st))))) ;;; ---------------------------------------------------- (defun .opt (x p) "Optionally match a parse combinator or return x." (.either p (.ret x))) ;;; ---------------------------------------------------- (defun .ignore (p) "Parse p, ignore the result." (.do p (.ret nil))) ;;; ---------------------------------------------------- (defun .all (p &rest ps) "Parse each combinator in order and return all as a list." (.let (first p) #'(lambda (st) (loop for p in ps ;; try the next combinator for (x nst) = (multiple-value-list (funcall p st)) while nst ;; update the parse state do (setf st nst) ;; keep all the matches in a list collect x into rest ;; return the matches and final state finally (return (values (cons first rest) st)))))) ;;; ---------------------------------------------------- (defun .maybe (p) "Try and parse p, ignore it if there." (.opt nil (.ignore p))) ;;; ---------------------------------------------------- (defun .many (p) "Try and parse a combinator zero or more times." (.opt nil (.many1 p))) ;;; ---------------------------------------------------- (defun .many1 (p) "Try and parse a combinator one or more times." (.let (first p) #'(lambda (st) (loop ;; keep repeating the parse combinator until it fails for (x nst) = (multiple-value-list (funcall p st)) while nst ;; update the parse state do (setf st nst) ;; keep all the matches in a list collect x into rest ;; return the matches and final state finally (return (values (cons first rest) st)))))) ;;; ---------------------------------------------------- (defun .many-until (p end) "Parse zero or more combinators until an end combinator is reached." #'(lambda (st) (loop ;; try and parse the end for nst = (nth-value 1 (funcall end st)) collect (if nst (loop-finish) (multiple-value-bind (x xst) (funcall p st) (if (null xst) (return nil) (prog1 x (setf st xst))))) ;; join all the results together into xs ;; return the results finally (return (values xs nst))))) ;;; ---------------------------------------------------- (defun .sep-by (p sep) "Zero or more occurances of p separated by sep." (.opt nil (.sep-by1 p sep))) ;;; ---------------------------------------------------- (defun .sep-by1 (p sep) "One or more occurances of p separated by sep." (.let (x p) (.let (xs (.many (.do sep p))) (.ret (cons x xs))))) ;;; ---------------------------------------------------- (defun .skip-many (p) "Optionally skip a parse combinator zero or more times." (.opt nil (.skip-many1 p))) ;;; ---------------------------------------------------- (defun .skip-many1 (p) "Try and parse a combinator one or more times, ignore it." (.maybe (.many1 p))) ;;; ---------------------------------------------------- (defun .between (open-guard close-guard p) "Capture a combinator between guards." (.do open-guard (.let (x p) (.do close-guard (.ret x)))))
null
https://raw.githubusercontent.com/massung/parse/2351ee78acac065fcf10b8713d3f404e2e910786/parse.lisp
lisp
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. declare a parse combinator monadic bind functions combinator macros monadic functions parse combinators ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- create the initial parse state create a function that will read into the shared token list parse the token stream should we error out? return the error result and parse failure ---------------------------------------------------- ---------------------------------------------------- add a documentation string to the parser if provided parse the combinators, return the final result ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- try the next combinator update the parse state keep all the matches in a list return the matches and final state ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- keep repeating the parse combinator until it fails update the parse state keep all the matches in a list return the matches and final state ---------------------------------------------------- try and parse the end join all the results together return the results ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ----------------------------------------------------
Monadic parsing package for Common Lisp Copyright ( c ) 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 (defpackage :parse (:use :cl) (:export #:parse #:define-parser #:>>= #:>> #:.prog1 #:.progn #:.let #:.let* #:.do #:.or #:.ret #:.fail #:.get #:.put #:.modify #:.push #:.pop #:.any #:.eof #:.is #:.either #:.opt #:.ignore #:.all #:.maybe #:.many #:.many1 #:.many-until #:.sep-by #:.sep-by1 #:.skip-many #:.skip-many1 #:.between)) (in-package :parse) (defstruct parse-state read-token tokens token-last data) (defun parse-state-next-token (st) "Returns the next token in the token list as a cons pair." (cadr (parse-state-tokens st))) (defun parse-state-token-class (st) "Returns the class of the current token." (car (parse-state-next-token st))) (defun parse-state-token-value (st) "Returns the value of the current token." (cdr (parse-state-next-token st))) (defun parse (p next-token &key initial-state (errorp t) error-value) "Create a parse-state and pass it through a parse combinator." (let* ((token-cache (list nil)) (st (make-parse-state :tokens token-cache :token-last token-cache :data initial-state))) (setf (parse-state-read-token st) #'(lambda () (multiple-value-bind (class value) (funcall next-token) (car (setf (parse-state-token-last st) (cdr (rplacd (parse-state-token-last st) (list (cons class value))))))))) read the first token as the current token (funcall (parse-state-read-token st)) (multiple-value-bind (x okp) (funcall p st) (cond (okp (values x t)) (errorp (error "Parse failure")) (t (values error-value nil)))))) (defun satisfy (st pred) "Read the next token if necesary, test class, return value." (destructuring-bind (class . value) (let ((token (parse-state-next-token st))) (if token token (funcall (parse-state-read-token st)))) (when (funcall pred class) (let ((nst (copy-parse-state st))) (multiple-value-prog1 (values value nst) (pop (parse-state-tokens nst))))))) (defmacro define-parser (name &body ps) "Create a parse combinator." (let ((st (gensym))) `(defun ,name (,st) ,(when (stringp (first ps)) (pop ps)) (funcall (.do ,@ps) ,st)))) (defun >>= (p f) "Monadic bind combinator." #'(lambda (st) (multiple-value-bind (x nst) (funcall p st) (when nst (funcall (funcall f x) nst))))) (defun >> (p m) "Monadic bind, ignore intermediate result." #'(lambda (st) (let ((nst (nth-value 1 (funcall p st)))) (when nst (funcall m nst))))) (defmacro .prog1 (form &body rest) "Macro to execute Lisp expressions, returning the first result." `(.ret (prog1 ,form ,@rest))) (defmacro .progn (&body rest) "Macro to execute Lisp expressions, returning the last result." `(.ret (progn ,@rest))) (defmacro .let ((var p) &body body) "Macro for >>= to make it more readable." `(>>= ,p #'(lambda (,var) (declare (ignorable ,var)) ,@body))) (defmacro .let* ((binding &rest bindings) &body body) "Macro for making multiple .let bindings more readable." (if (null bindings) `(.let ,binding ,@body) `(.let ,binding (.let* ,bindings ,@body)))) (defmacro .do (p &rest ps) "Chained together >> combinators." (labels ((chain (p ps) (if (null ps) p `(>> ,p ,(chain (first ps) (rest ps)))))) (chain p ps))) (defmacro .or (p &rest ps) "Chained together or combinators." (labels ((try (p ps) (if (null ps) p `(.either ,p ,(try (first ps) (rest ps)))))) (try p ps))) (defun .ret (x) "Convert X into a monadic value." #'(lambda (st) (values x st))) (defun .fail (datum &rest arguments) "Ensures that the parse combinator fails." #'(lambda (st) (declare (ignore st)) (apply #'error datum arguments))) (defun .get () "Always succeeds, returns the current parse state data." #'(lambda (st) (values (parse-state-data st) st))) (defun .put (x) "Always succeeds, puts data into the parse state." #'(lambda (st) (let ((nst (copy-parse-state st))) (values (setf (parse-state-data nst) x) nst)))) (defun .modify (f) "Always succeeds, applys f with the parse state data." (.let (x (.get)) (.put (funcall f x)))) (defun .push (x) "Always succeeds, assumes data is a list and pushes x onto it." (.let (xs (.get)) (.put (cons x xs)))) (defun .pop () "Always succeeds, assumes data is a list an pops it." (.let (xs (.get)) (.do (.put (cdr xs)) (.ret (car xs))))) (defun .any () "Succeeds if not at the end of the token stream." #'(lambda (st) (satisfy st #'identity))) (defun .eof () "Succeeds if at the end of the token stream." #'(lambda (st) (satisfy st #'null))) (defun .is (class &key (test #'eql)) "Checks if the current token is of a given class." #'(lambda (st) (satisfy st #'(lambda (c) (funcall test c class))))) (defun .either (p1 p2) "Attempt to parse p1, if that fails, try p2." #'(lambda (st) (multiple-value-bind (x nst) (funcall p1 st) (if nst (values x nst) (funcall p2 st))))) (defun .opt (x p) "Optionally match a parse combinator or return x." (.either p (.ret x))) (defun .ignore (p) "Parse p, ignore the result." (.do p (.ret nil))) (defun .all (p &rest ps) "Parse each combinator in order and return all as a list." (.let (first p) #'(lambda (st) (loop for p in ps for (x nst) = (multiple-value-list (funcall p st)) while nst do (setf st nst) collect x into rest finally (return (values (cons first rest) st)))))) (defun .maybe (p) "Try and parse p, ignore it if there." (.opt nil (.ignore p))) (defun .many (p) "Try and parse a combinator zero or more times." (.opt nil (.many1 p))) (defun .many1 (p) "Try and parse a combinator one or more times." (.let (first p) #'(lambda (st) (loop for (x nst) = (multiple-value-list (funcall p st)) while nst do (setf st nst) collect x into rest finally (return (values (cons first rest) st)))))) (defun .many-until (p end) "Parse zero or more combinators until an end combinator is reached." #'(lambda (st) (loop for nst = (nth-value 1 (funcall end st)) collect (if nst (loop-finish) (multiple-value-bind (x xst) (funcall p st) (if (null xst) (return nil) (prog1 x (setf st xst))))) into xs finally (return (values xs nst))))) (defun .sep-by (p sep) "Zero or more occurances of p separated by sep." (.opt nil (.sep-by1 p sep))) (defun .sep-by1 (p sep) "One or more occurances of p separated by sep." (.let (x p) (.let (xs (.many (.do sep p))) (.ret (cons x xs))))) (defun .skip-many (p) "Optionally skip a parse combinator zero or more times." (.opt nil (.skip-many1 p))) (defun .skip-many1 (p) "Try and parse a combinator one or more times, ignore it." (.maybe (.many1 p))) (defun .between (open-guard close-guard p) "Capture a combinator between guards." (.do open-guard (.let (x p) (.do close-guard (.ret x)))))
69064909c442762c4ba9c8aabfd3c580772b1d9196ee11959ee2c40d66cc7763
Bogdanp/racket-sentry
event.rkt
#lang racket/base (require gregor rackunit sentry/private/event threading) (provide event-tests) (define event-tests (test-suite "event" (test-suite "event->jsexpr" (test-case "converts events to json expressions" (parameterize ([current-clock (lambda () 0)] [current-timezone "UTC"]) (define expr (event->jsexpr (make-event (make-exn:fail "an error" (current-continuation-marks))))) (check-equal? (~> expr (hash-remove 'exception) (hash-remove 'contexts)) (hasheq 'platform "other" 'level "error" 'timestamp "1970-01-01T00:00:00Z" 'tags (hash)))))))) (module+ test (require rackunit/text-ui) (run-tests event-tests))
null
https://raw.githubusercontent.com/Bogdanp/racket-sentry/9794b2da9c4f3ca8c8094d6bc78d5ca8bf9b133b/sentry-test/tests/sentry/event.rkt
racket
#lang racket/base (require gregor rackunit sentry/private/event threading) (provide event-tests) (define event-tests (test-suite "event" (test-suite "event->jsexpr" (test-case "converts events to json expressions" (parameterize ([current-clock (lambda () 0)] [current-timezone "UTC"]) (define expr (event->jsexpr (make-event (make-exn:fail "an error" (current-continuation-marks))))) (check-equal? (~> expr (hash-remove 'exception) (hash-remove 'contexts)) (hasheq 'platform "other" 'level "error" 'timestamp "1970-01-01T00:00:00Z" 'tags (hash)))))))) (module+ test (require rackunit/text-ui) (run-tests event-tests))
ca30e67d9b47a31397687899f97782ad71a7567a26ea197db9b0db0d021ff4ab
owlbarn/owl_symbolic
owl_symbolic_specs.ml
* OWL - OCaml Scientific and Engineering Computing * Copyright ( c ) 2016 - 2020 < > * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <> *) (* Module aliases *) module PB = Onnx_pb module PP = Onnx_pp module PT = Onnx_types
null
https://raw.githubusercontent.com/owlbarn/owl_symbolic/dc853a016757d3f143c5e07e50075e7ae605d969/src/onnx_specs/owl_symbolic_specs.ml
ocaml
Module aliases
* OWL - OCaml Scientific and Engineering Computing * Copyright ( c ) 2016 - 2020 < > * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <> *) module PB = Onnx_pb module PP = Onnx_pp module PT = Onnx_types
fb56ec1bb47c87ad549e6e56fefe703ac90c792d74e9c1dc32e622deb44a7a4c
yummly/logentries-timbre-appender
logentries_timbre_appender_test.clj
(ns yummly.logentries-timbre-appender-test (:require [yummly.logentries-timbre-appender :as sut] [clojure.test :refer :all] [clojure.string] [cheshire.core :as cheshire])) (deftest error-to-stacktrace-test (let [test-error ((fn [] (java.lang.ArithmeticException. "Divide by fake-value"))) parsed-error (first (sut/error-to-stacktrace test-error))] (is (= "java.lang.ArithmeticException" (:class-name parsed-error))) (is (= "Divide by fake-value" (:message parsed-error))) (is (pos? (count (:stack-trace parsed-error))) "At the very least, we should have a stack trace from the nested function call") (is (every? string? (:stack-trace parsed-error))))) (deftest update-illegal-characters (let [test-line (cheshire/parse-string (sut/data->json-line {:msg_ {:test-data {:test-data 5 (keyword "casdf asdf") "dog"}}} {:user-data :dog} identity))] (is (= (get test-line "message") {"test_data" {"test_data" 5 "casdf_asdf" "dog"}})) (is (= (get test-line "user_data") "dog"))))
null
https://raw.githubusercontent.com/yummly/logentries-timbre-appender/016dbc2d3ce483b325595d149d66cde3cc28fe2b/test/yummly/logentries_timbre_appender_test.clj
clojure
(ns yummly.logentries-timbre-appender-test (:require [yummly.logentries-timbre-appender :as sut] [clojure.test :refer :all] [clojure.string] [cheshire.core :as cheshire])) (deftest error-to-stacktrace-test (let [test-error ((fn [] (java.lang.ArithmeticException. "Divide by fake-value"))) parsed-error (first (sut/error-to-stacktrace test-error))] (is (= "java.lang.ArithmeticException" (:class-name parsed-error))) (is (= "Divide by fake-value" (:message parsed-error))) (is (pos? (count (:stack-trace parsed-error))) "At the very least, we should have a stack trace from the nested function call") (is (every? string? (:stack-trace parsed-error))))) (deftest update-illegal-characters (let [test-line (cheshire/parse-string (sut/data->json-line {:msg_ {:test-data {:test-data 5 (keyword "casdf asdf") "dog"}}} {:user-data :dog} identity))] (is (= (get test-line "message") {"test_data" {"test_data" 5 "casdf_asdf" "dog"}})) (is (= (get test-line "user_data") "dog"))))
22db86d6bee2f58df2a28159139d043fc9dc31f2d5f3559dda374e0cf165a6ee
fumieval/discord-vc-notification
dvn-identify.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # module Main where import RIO import UnliftIO.Concurrent import Data.Aeson import Data.Aeson.Types import qualified Network.WebSockets as WS import qualified Wuss as WS import System.Environment data Env = Env { wsConn :: WS.Connection , botToken :: Text , logFunc :: LogFunc } instance HasLogFunc Env where logFuncL = lens logFunc (\s f -> s { logFunc = f }) send :: Value -> RIO Env () send v = ask >>= \Env{..} -> liftIO $ WS.sendTextData wsConn $ encode v sendHeartbeat :: Int -> RIO Env () sendHeartbeat period = forever $ do send $ object ["op" .= (1 :: Int), "d" .= (251 :: Int)] liftIO $ threadDelay $ 1000 * period hello :: Object -> Parser (RIO Env ()) hello obj = do op <- obj .: "op" guard $ op == (10 :: Int) dat <- obj .: "d" interval <- dat .: "heartbeat_interval" return $ do _ <- forkIO $ sendHeartbeat interval identify identify :: RIO Env () identify = do Env{..} <- ask send $ object [ "op" .= (2 :: Int) , "d" .= object [ "token" .= botToken , "properties" .= object [ "$os" .= ("linux" :: Text) , "$browser" .= ("discord-vc-notification" :: Text) , "$device" .= ("discord-vc-notification" :: Text) ] , "compress" .= False , "large_threshold" .= (250 :: Int) , "shard" .= [0 :: Int, 1] , "presence" .= object [ "game" .= Null , "status" .= ("online" :: Text) , "since" .= Null , "afk" .= False ] ] ] main :: IO () main = WS.runSecureClient "gateway.discord.gg" 443 "/?v=6&encoding=json" $ \wsConn -> do botToken <- fromString <$> getEnv "DISCORD_BOT_TOKEN" logOpts <- logOptionsHandle stderr True withLogFunc logOpts $ \logFunc -> forever $ do bs <- WS.receiveData wsConn obj <- case decode bs of Nothing -> fail "Failed to parse a JSON object" Just a -> pure a runRIO Env{..} $ case parse hello obj of Success m -> m Error _ -> logWarn $ "Unhandled: " <> displayBytesUtf8 (toStrictBytes bs)
null
https://raw.githubusercontent.com/fumieval/discord-vc-notification/5d08d62a5cd935702fd231731c689087f14e0488/tutorial/dvn-identify.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE NoImplicitPrelude # # LANGUAGE RecordWildCards # module Main where import RIO import UnliftIO.Concurrent import Data.Aeson import Data.Aeson.Types import qualified Network.WebSockets as WS import qualified Wuss as WS import System.Environment data Env = Env { wsConn :: WS.Connection , botToken :: Text , logFunc :: LogFunc } instance HasLogFunc Env where logFuncL = lens logFunc (\s f -> s { logFunc = f }) send :: Value -> RIO Env () send v = ask >>= \Env{..} -> liftIO $ WS.sendTextData wsConn $ encode v sendHeartbeat :: Int -> RIO Env () sendHeartbeat period = forever $ do send $ object ["op" .= (1 :: Int), "d" .= (251 :: Int)] liftIO $ threadDelay $ 1000 * period hello :: Object -> Parser (RIO Env ()) hello obj = do op <- obj .: "op" guard $ op == (10 :: Int) dat <- obj .: "d" interval <- dat .: "heartbeat_interval" return $ do _ <- forkIO $ sendHeartbeat interval identify identify :: RIO Env () identify = do Env{..} <- ask send $ object [ "op" .= (2 :: Int) , "d" .= object [ "token" .= botToken , "properties" .= object [ "$os" .= ("linux" :: Text) , "$browser" .= ("discord-vc-notification" :: Text) , "$device" .= ("discord-vc-notification" :: Text) ] , "compress" .= False , "large_threshold" .= (250 :: Int) , "shard" .= [0 :: Int, 1] , "presence" .= object [ "game" .= Null , "status" .= ("online" :: Text) , "since" .= Null , "afk" .= False ] ] ] main :: IO () main = WS.runSecureClient "gateway.discord.gg" 443 "/?v=6&encoding=json" $ \wsConn -> do botToken <- fromString <$> getEnv "DISCORD_BOT_TOKEN" logOpts <- logOptionsHandle stderr True withLogFunc logOpts $ \logFunc -> forever $ do bs <- WS.receiveData wsConn obj <- case decode bs of Nothing -> fail "Failed to parse a JSON object" Just a -> pure a runRIO Env{..} $ case parse hello obj of Success m -> m Error _ -> logWarn $ "Unhandled: " <> displayBytesUtf8 (toStrictBytes bs)
6d6379bf29cff67157352bbb7c5ddb5414e35a91705a46f048c4fd153f18d8af
dmitryvk/sbcl-win32-threads
custom-userinit.lisp
;;;; loaded by init.test.sh This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; While most of SBCL is derived from the CMU CL system , the test ;;;; files (like this one) were written from scratch after the fork from CMU CL . ;;;; ;;;; This software is in the public domain and is provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for ;;;; more information. (write-line "/loading custom userinit") (defun userinit-quit (x) (sb-ext:quit :unix-status x))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/tests/custom-userinit.lisp
lisp
loaded by init.test.sh more information. files (like this one) were written from scratch after the fork This software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information.
This software is part of the SBCL system . See the README file for While most of SBCL is derived from the CMU CL system , the test from CMU CL . (write-line "/loading custom userinit") (defun userinit-quit (x) (sb-ext:quit :unix-status x))
7c210f354040721a26aeef05e2a5acad371dfd61e0eebbfd5e16b4b761d37539
rd--/hsc3
peak.help.hs
-- peak let t = dustId 'α' ar 20 r = impulse ar 0.4 0 f = peak t r * 500 + 200 in sinOsc ar f 0 * 0.2
null
https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/peak.help.hs
haskell
peak
let t = dustId 'α' ar 20 r = impulse ar 0.4 0 f = peak t r * 500 + 200 in sinOsc ar f 0 * 0.2
6c5c9210b8314caa6721b9fcc99ef2c060655440d26f65a76b00de82a5b21386
3b/ps-webgl
lesson09.lisp
;;; -*- Mode: LISP; slime-proxy-proxy-connection: t -*- translated from -lessons/blob/master/lesson09/index.html ;;; (eval-when (:compile-toplevel :load-toplevel) (defpackage #:learningwebgl.com-09 (:use :ps :cl :example-utils) (:local-nicknames (:m :mjs-bindings) (:%gl :webgl-bindings) (:gl :webgl-ps))) (setf (ps:ps-package-prefix '#:learningwebgl.com-09) "lesson09_")) (in-package #:learningwebgl.com-09) these were in the html in the originally , but i code PS through ;; slime-proxy, so adding them here is more convenient (defvar *fragment-shader* " #ifdef GL_ES precision highp float; #endif varying vec2 vTextureCoord; uniform sampler2D uSampler; uniform vec3 uColor; void main(void) { vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); // gl_FragColor = textureColor * vec4(uColor, 1.0); gl_FragColor = textureColor * vec4(uColor, 1.0); }") (defvar *vertex-shader* " attribute vec3 aVertexPosition; attribute vec2 aTextureCoord; uniform mat4 uMVMatrix; uniform mat4 uPMatrix; varying vec2 vTextureCoord; void main(void) { gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); vTextureCoord = aTextureCoord; }") ;;; this name must match webgl-bindings::*webgl-context*, or else we need to wrap gl calls with webgl - bindings::with - gl - context (defvar #:*GL*) (defun init-gl (canvas) (try (progn (setf #:*GL* ((@ canvas #:get-context) "experimental-webgl")) (setf (@ #:*GL* viewport-width) (@ canvas #:width)) (setf (@ #:*GL* viewport-height) (@ canvas #:height))) (:catch (e) (gl::clog "error " ((@ e #:to-string))))) (unless #:*GL* (gl::clog "couldn't initialize webgl") #++(alert "could not initialize WebGL")) (gl::clog "GL init " (if #:*gl* "done" "failed"))) ;; (init-gl "canvas") (defun create-shader (type source) (let ((shader (gl:create-shader type))) (gl:shader-source shader source) (gl:compile-shader shader) (unless (gl:get-shader-parameter shader gl:+compile-status+) (gl::clog " couldn't create shader" (gl:get-shader-info-log shader)) (return nil)) (gl::clog "loaded shader:" (gl:get-shader-parameter shader gl:+compile-status+) " " (gl:get-shader-info-log shader)) shader)) (defvar shader-program) (defun init-shaders () (let ((fragment-shader (create-shader gl:+fragment-shader+ *fragment-shader*)) (vertex-shader (create-shader gl:+vertex-shader+ *vertex-shader*))) (setf shader-program (gl:create-program)) (gl:attach-shader shader-program vertex-shader) (gl:attach-shader shader-program fragment-shader) (gl:link-program shader-program) (unless (gl:get-program-parameter shader-program gl:+link-status+) (gl::clog (gl:get-program-info-log shader-program)) (return nil)) (gl::clog "program linked" (gl:get-program-info-log shader-program)) (gl:use-program shader-program) (setf (@ shader-program vertex-position-attribute) (gl:get-attrib-location shader-program "aVertexPosition")) (gl:enable-vertex-attrib-array (@ shader-program vertex-position-attribute)) (setf (@ shader-program texture-coord-attribute) (gl:get-attrib-location shader-program "aTextureCoord")) (gl:enable-vertex-attrib-array (@ shader-program texture-coord-attribute)) (setf (@ shader-program p-matrix-uniform) (gl:get-uniform-location shader-program "uPMatrix")) (setf (@ shader-program mv-matrix-uniform) (gl:get-uniform-location shader-program "uMVMatrix")) (setf (@ shader-program sampler-uniform) (gl:get-uniform-location shader-program "uSampler")) (setf (@ shader-program color-uniform) (gl:get-uniform-location shader-program "uColor")) (gl::clog "init shaders done "))) #++ (init-shaders) (defun handle-loaded-texture (texture) (gl:pixel-store-i gl:+unpack-flip-y-webgl+ t) (gl:bind-texture gl:+texture-2d+ texture) (gl:tex-image-2d gl:+texture-2d+ 0 gl:+rgba+ gl:+rgba+ gl:+unsigned-byte+ (@ texture image)) (gl:tex-parameter-i gl:+texture-2d+ gl:+texture-mag-filter+ gl:+linear+) (gl:tex-parameter-i gl:+texture-2d+ gl:+texture-min-filter+ gl:+linear+) (gl:bind-texture gl:+texture-2d+ null)) (defvar star-texture) (defun init-texture () (setf star-texture (gl:create-texture)) (setf (@ star-texture image) (new (#:*image))) (setf (@ star-texture image #:onload) (lambda () (handle-loaded-texture star-texture))) (setf (@ star-texture image #:src) "../../../webgl/examples/learningwebgl.com/lesson09/star.gif")) #++ (init-texture) (defvar mv-matrix (m:matrix)) (defvar mv-matrix-stack (array)) (defvar p-matrix (m:matrix)) (defun mv-push-matrix () ((@ mv-matrix-stack #:push) (m:matrix-clone mv-matrix))) (defun mv-pop-matrix () (when (= 0(length mv-matrix-stack)) (throw "Invalid pop-matrix")) (setf mv-matrix ((@ mv-matrix-stack #:pop)))) (defun set-matrix-uniforms () (gl:uniform-matrix-4fv (@ shader-program p-matrix-uniform) #:false p-matrix) (gl:uniform-matrix-4fv (@ shader-program mv-matrix-uniform) #:false mv-matrix)) (defun degrees-to-radians (degrees) (* degrees (/ pi 180))) (defvar currently-pressed-keys (create)) (defun handle-key-down (event) (setf (aref currently-pressed-keys (@ event #:key-code)) t)) (defun handle-key-up (event) (setf (aref currently-pressed-keys (@ event #:key-code)) #:false)) (defvar zoom -15) (defvar tilt 90) (defvar spin 0) (defun handle-keys () (when (aref currently-pressed-keys 33) ;; page up (decf zoom 0.1)) (when (aref currently-pressed-keys 34) ;; page down (incf zoom 0.1)) (when (aref currently-pressed-keys 38) ;; up (incf tilt 2)) (when (aref currently-pressed-keys 40) ;; down (decf tilt 2))) (defvar star-vertex-position-buffer) (defvar star-vertex-texture-coord-buffer) (defun init-buffers () (flet ((buffer-from-array (array size) (let ((b (gl:create-buffer)) (size (or size 3))) (gl:bind-buffer gl:+array-buffer+ b) (gl:buffer-data gl:+array-buffer+ (new (#:*float-32-array array)) gl:+static-draw+) (setf (@ b item-size) size (@ b num-items) (floor (length array) size)) b))) (setf star-vertex-position-buffer (buffer-from-array (array -1 -1 0 1 -1 0 -1 1 0 1 1 0))) (setf star-vertex-texture-coord-buffer (buffer-from-array (array 0 0 1 0 0 1 1 1) 2)) (return))) ; (init-buffers) (defun draw-star () (gl:active-texture gl:+texture0+) (gl:bind-texture gl:+texture-2d+ star-texture) (gl:uniform-1i (@ shader-program sampler-uniform) 0) (gl:bind-buffer gl:+array-buffer+ star-vertex-texture-coord-buffer) (gl:vertex-attrib-pointer (@ shader-program texture-coord-attribute) (@ star-vertex-texture-coord-buffer item-size) gl:+float+ #:false 0 0) (gl:bind-buffer gl:+array-buffer+ star-vertex-position-buffer) (gl:vertex-attrib-pointer (@ shader-program vertex-position-attribute) (@ star-vertex-position-buffer item-size) gl:+float+ #:false 0 0) (set-matrix-uniforms) (gl:draw-arrays gl:+triangle-strip+ 0 (@ star-vertex-position-buffer num-items))) (defun *star (starting-distance rotation-speed) (setf (@ this angle) 0 (@ this dist) starting-distance (@ this rotation-speed) rotation-speed) ((@ this randomize-colors)) #:this) (setf (@ *star #:prototype draw) (lambda (tilt spin twinkle) (mv-push-matrix) ;; move to star's position (m:rotate (degrees-to-radians (@ this angle)) (array 0 1 0) mv-matrix mv-matrix) (m:translate (array (@ this dist) 0 0) mv-matrix mv-matrix) ;; rotate back so star faces viewer (m:rotate (degrees-to-radians (- (@ this angle))) (array 0 1 0) mv-matrix mv-matrix) (m:rotate (degrees-to-radians (- tilt)) (array 1 0 0) mv-matrix mv-matrix) (when twinkle ;; draw a non-rotating star in the alternate 'twinkling' color (gl:uniform-3fv (@ shader-program color-uniform) (@ this twinkle-rgb)) (draw-star)) ;;all stars spin around the z axis at the same rate (m:rotate (degrees-to-radians spin) (array 0 0 1) mv-matrix mv-matrix) ;; draw star in its main color (gl:uniform-3fv (@ shader-program color-uniform) (@ this rgb)) (draw-star) (mv-pop-matrix))) (defvar effective-fpms (/ 60 1000)) (setf (@ *star #:prototype animate) (lambda (elapsed-time) (incf (@ this angle) (* (@ this rotation-speed) effective-fpms elapsed-time)) ;; fall towards center, reset to outside once it hits center (decf (@ this dist) (* 0.01 effective-fpms elapsed-time)) (when (< (@ this dist) 0) (incf (@ this dist) 5.0) ((@ this randomize-colors))))) (setf (@ *star #:prototype randomize-colors) (lambda () ;; random color for normal circumstances (setf (@ this rgb) (array (random) (random) (random)) ;; when star is twinkling, we draw it twice, once in ;; color below (and not spinning), and once as normal ;; in color defined above (@ this twinkle-rgb) (array (random) (random) (random))))) (defvar stars (array)) (defun init-world-objects (n) (setf stars (array)) (let ((num-stars (or n 50))) (dotimes (i num-stars) ((@ stars push) (new (*Star (* 5 (/ i num-stars)) (/ i num-stars))))))) (defun draw-scene () (gl:viewport 0 0 (@ #:*gl* viewport-width) (@ #:*gl* viewport-height)) (gl:clear (logior gl:+color-buffer-bit+ gl:+depth-buffer-bit+)) (m:make-perspective 45 (/ (@ #:*gl* viewport-width) (@ #:*gl* viewport-height)) 0.1 100 p-matrix) (gl:blend-func gl:+src-alpha+ gl:+one+) (gl:enable gl:+blend+) (setf mv-matrix (m:matrix-clone (@ #:*m4x4 #:*i))) (m:translate (array 0 0 zoom) mv-matrix mv-matrix) (m:rotate (degrees-to-radians tilt) (array 1 0 0) mv-matrix mv-matrix) (for-in (i stars) ((@ (aref stars i) draw) tilt spin twinkle) (incf spin 0.1))) (defvar last-time 0) (defun animate () (let ((now (funcall (@ (new (*date)) get-time)))) (unless (= last-time 0) (let ((elapsed-time (- now last-time))) (for-in (i stars) ((@ (aref stars i) animate) elapsed-time)))) (setf last-time now))) (defvar stop t) (defun one-tick () (handle-keys) (draw-scene) (animate) ) (defun tick () (one-tick) (unless stop (gl:request-animation-frame tick #++ gl:canvas)) (when stop (gl::clog "stopping ..."))) (defun webgl-start () (let ((canvas ((@ #:document #:get-element-by-id) "canvas"))) (init-gl canvas)) (init-shaders) (init-buffers) (init-texture) (init-world-objects 50) (gl:disable gl:+depth-test+) (gl:clear-color 0 0 0 1) (setf (@ #:document #:onkeydown) handle-key-down) (setf (@ #:document #:onkeyup) handle-key-up) (setf stop #:false) (tick) nil) (defvar twinkle t) #++ (webgl-start)
null
https://raw.githubusercontent.com/3b/ps-webgl/cf2832d2e814ac0b733d1914985aeadefdcc2a1c/examples/learningwebgl.com/lesson09/lesson09.lisp
lisp
-*- Mode: LISP; slime-proxy-proxy-connection: t -*- slime-proxy, so adding them here is more convenient this name must match webgl-bindings::*webgl-context*, or else (init-gl "canvas") page up page down up down (init-buffers) move to star's position rotate back so star faces viewer draw a non-rotating star in the alternate 'twinkling' color all stars spin around the z axis at the same rate draw star in its main color fall towards center, reset to outside once it hits center random color for normal circumstances when star is twinkling, we draw it twice, once in color below (and not spinning), and once as normal in color defined above
translated from -lessons/blob/master/lesson09/index.html (eval-when (:compile-toplevel :load-toplevel) (defpackage #:learningwebgl.com-09 (:use :ps :cl :example-utils) (:local-nicknames (:m :mjs-bindings) (:%gl :webgl-bindings) (:gl :webgl-ps))) (setf (ps:ps-package-prefix '#:learningwebgl.com-09) "lesson09_")) (in-package #:learningwebgl.com-09) these were in the html in the originally , but i code PS through (defvar *fragment-shader* " #ifdef GL_ES #endif void main(void) { }") (defvar *vertex-shader* " void main(void) { }") we need to wrap gl calls with webgl - bindings::with - gl - context (defvar #:*GL*) (defun init-gl (canvas) (try (progn (setf #:*GL* ((@ canvas #:get-context) "experimental-webgl")) (setf (@ #:*GL* viewport-width) (@ canvas #:width)) (setf (@ #:*GL* viewport-height) (@ canvas #:height))) (:catch (e) (gl::clog "error " ((@ e #:to-string))))) (unless #:*GL* (gl::clog "couldn't initialize webgl") #++(alert "could not initialize WebGL")) (gl::clog "GL init " (if #:*gl* "done" "failed"))) (defun create-shader (type source) (let ((shader (gl:create-shader type))) (gl:shader-source shader source) (gl:compile-shader shader) (unless (gl:get-shader-parameter shader gl:+compile-status+) (gl::clog " couldn't create shader" (gl:get-shader-info-log shader)) (return nil)) (gl::clog "loaded shader:" (gl:get-shader-parameter shader gl:+compile-status+) " " (gl:get-shader-info-log shader)) shader)) (defvar shader-program) (defun init-shaders () (let ((fragment-shader (create-shader gl:+fragment-shader+ *fragment-shader*)) (vertex-shader (create-shader gl:+vertex-shader+ *vertex-shader*))) (setf shader-program (gl:create-program)) (gl:attach-shader shader-program vertex-shader) (gl:attach-shader shader-program fragment-shader) (gl:link-program shader-program) (unless (gl:get-program-parameter shader-program gl:+link-status+) (gl::clog (gl:get-program-info-log shader-program)) (return nil)) (gl::clog "program linked" (gl:get-program-info-log shader-program)) (gl:use-program shader-program) (setf (@ shader-program vertex-position-attribute) (gl:get-attrib-location shader-program "aVertexPosition")) (gl:enable-vertex-attrib-array (@ shader-program vertex-position-attribute)) (setf (@ shader-program texture-coord-attribute) (gl:get-attrib-location shader-program "aTextureCoord")) (gl:enable-vertex-attrib-array (@ shader-program texture-coord-attribute)) (setf (@ shader-program p-matrix-uniform) (gl:get-uniform-location shader-program "uPMatrix")) (setf (@ shader-program mv-matrix-uniform) (gl:get-uniform-location shader-program "uMVMatrix")) (setf (@ shader-program sampler-uniform) (gl:get-uniform-location shader-program "uSampler")) (setf (@ shader-program color-uniform) (gl:get-uniform-location shader-program "uColor")) (gl::clog "init shaders done "))) #++ (init-shaders) (defun handle-loaded-texture (texture) (gl:pixel-store-i gl:+unpack-flip-y-webgl+ t) (gl:bind-texture gl:+texture-2d+ texture) (gl:tex-image-2d gl:+texture-2d+ 0 gl:+rgba+ gl:+rgba+ gl:+unsigned-byte+ (@ texture image)) (gl:tex-parameter-i gl:+texture-2d+ gl:+texture-mag-filter+ gl:+linear+) (gl:tex-parameter-i gl:+texture-2d+ gl:+texture-min-filter+ gl:+linear+) (gl:bind-texture gl:+texture-2d+ null)) (defvar star-texture) (defun init-texture () (setf star-texture (gl:create-texture)) (setf (@ star-texture image) (new (#:*image))) (setf (@ star-texture image #:onload) (lambda () (handle-loaded-texture star-texture))) (setf (@ star-texture image #:src) "../../../webgl/examples/learningwebgl.com/lesson09/star.gif")) #++ (init-texture) (defvar mv-matrix (m:matrix)) (defvar mv-matrix-stack (array)) (defvar p-matrix (m:matrix)) (defun mv-push-matrix () ((@ mv-matrix-stack #:push) (m:matrix-clone mv-matrix))) (defun mv-pop-matrix () (when (= 0(length mv-matrix-stack)) (throw "Invalid pop-matrix")) (setf mv-matrix ((@ mv-matrix-stack #:pop)))) (defun set-matrix-uniforms () (gl:uniform-matrix-4fv (@ shader-program p-matrix-uniform) #:false p-matrix) (gl:uniform-matrix-4fv (@ shader-program mv-matrix-uniform) #:false mv-matrix)) (defun degrees-to-radians (degrees) (* degrees (/ pi 180))) (defvar currently-pressed-keys (create)) (defun handle-key-down (event) (setf (aref currently-pressed-keys (@ event #:key-code)) t)) (defun handle-key-up (event) (setf (aref currently-pressed-keys (@ event #:key-code)) #:false)) (defvar zoom -15) (defvar tilt 90) (defvar spin 0) (defun handle-keys () (decf zoom 0.1)) (incf zoom 0.1)) (incf tilt 2)) (decf tilt 2))) (defvar star-vertex-position-buffer) (defvar star-vertex-texture-coord-buffer) (defun init-buffers () (flet ((buffer-from-array (array size) (let ((b (gl:create-buffer)) (size (or size 3))) (gl:bind-buffer gl:+array-buffer+ b) (gl:buffer-data gl:+array-buffer+ (new (#:*float-32-array array)) gl:+static-draw+) (setf (@ b item-size) size (@ b num-items) (floor (length array) size)) b))) (setf star-vertex-position-buffer (buffer-from-array (array -1 -1 0 1 -1 0 -1 1 0 1 1 0))) (setf star-vertex-texture-coord-buffer (buffer-from-array (array 0 0 1 0 0 1 1 1) 2)) (return))) (defun draw-star () (gl:active-texture gl:+texture0+) (gl:bind-texture gl:+texture-2d+ star-texture) (gl:uniform-1i (@ shader-program sampler-uniform) 0) (gl:bind-buffer gl:+array-buffer+ star-vertex-texture-coord-buffer) (gl:vertex-attrib-pointer (@ shader-program texture-coord-attribute) (@ star-vertex-texture-coord-buffer item-size) gl:+float+ #:false 0 0) (gl:bind-buffer gl:+array-buffer+ star-vertex-position-buffer) (gl:vertex-attrib-pointer (@ shader-program vertex-position-attribute) (@ star-vertex-position-buffer item-size) gl:+float+ #:false 0 0) (set-matrix-uniforms) (gl:draw-arrays gl:+triangle-strip+ 0 (@ star-vertex-position-buffer num-items))) (defun *star (starting-distance rotation-speed) (setf (@ this angle) 0 (@ this dist) starting-distance (@ this rotation-speed) rotation-speed) ((@ this randomize-colors)) #:this) (setf (@ *star #:prototype draw) (lambda (tilt spin twinkle) (mv-push-matrix) (m:rotate (degrees-to-radians (@ this angle)) (array 0 1 0) mv-matrix mv-matrix) (m:translate (array (@ this dist) 0 0) mv-matrix mv-matrix) (m:rotate (degrees-to-radians (- (@ this angle))) (array 0 1 0) mv-matrix mv-matrix) (m:rotate (degrees-to-radians (- tilt)) (array 1 0 0) mv-matrix mv-matrix) (when twinkle (gl:uniform-3fv (@ shader-program color-uniform) (@ this twinkle-rgb)) (draw-star)) (m:rotate (degrees-to-radians spin) (array 0 0 1) mv-matrix mv-matrix) (gl:uniform-3fv (@ shader-program color-uniform) (@ this rgb)) (draw-star) (mv-pop-matrix))) (defvar effective-fpms (/ 60 1000)) (setf (@ *star #:prototype animate) (lambda (elapsed-time) (incf (@ this angle) (* (@ this rotation-speed) effective-fpms elapsed-time)) (decf (@ this dist) (* 0.01 effective-fpms elapsed-time)) (when (< (@ this dist) 0) (incf (@ this dist) 5.0) ((@ this randomize-colors))))) (setf (@ *star #:prototype randomize-colors) (lambda () (setf (@ this rgb) (array (random) (random) (random)) (@ this twinkle-rgb) (array (random) (random) (random))))) (defvar stars (array)) (defun init-world-objects (n) (setf stars (array)) (let ((num-stars (or n 50))) (dotimes (i num-stars) ((@ stars push) (new (*Star (* 5 (/ i num-stars)) (/ i num-stars))))))) (defun draw-scene () (gl:viewport 0 0 (@ #:*gl* viewport-width) (@ #:*gl* viewport-height)) (gl:clear (logior gl:+color-buffer-bit+ gl:+depth-buffer-bit+)) (m:make-perspective 45 (/ (@ #:*gl* viewport-width) (@ #:*gl* viewport-height)) 0.1 100 p-matrix) (gl:blend-func gl:+src-alpha+ gl:+one+) (gl:enable gl:+blend+) (setf mv-matrix (m:matrix-clone (@ #:*m4x4 #:*i))) (m:translate (array 0 0 zoom) mv-matrix mv-matrix) (m:rotate (degrees-to-radians tilt) (array 1 0 0) mv-matrix mv-matrix) (for-in (i stars) ((@ (aref stars i) draw) tilt spin twinkle) (incf spin 0.1))) (defvar last-time 0) (defun animate () (let ((now (funcall (@ (new (*date)) get-time)))) (unless (= last-time 0) (let ((elapsed-time (- now last-time))) (for-in (i stars) ((@ (aref stars i) animate) elapsed-time)))) (setf last-time now))) (defvar stop t) (defun one-tick () (handle-keys) (draw-scene) (animate) ) (defun tick () (one-tick) (unless stop (gl:request-animation-frame tick #++ gl:canvas)) (when stop (gl::clog "stopping ..."))) (defun webgl-start () (let ((canvas ((@ #:document #:get-element-by-id) "canvas"))) (init-gl canvas)) (init-shaders) (init-buffers) (init-texture) (init-world-objects 50) (gl:disable gl:+depth-test+) (gl:clear-color 0 0 0 1) (setf (@ #:document #:onkeydown) handle-key-down) (setf (@ #:document #:onkeyup) handle-key-up) (setf stop #:false) (tick) nil) (defvar twinkle t) #++ (webgl-start)
3cbc9fed7d8ed58fb94419722ea063cdc235a140ddec8a8dc650bc10de75cdb3
jiangpengnju/htdp2e
ex67.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex67) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; Write down the names of the functions(constructors, selectors, and predicates) ; that the following structure type definitions introduce: (define-struct movie [title producer year]) ; constructor: make-movie ; selectors: movie-title movie-producer movie-year ; predicate: movie? (define-struct person [name hair eyes phone]) ; constructor: make-person ; selectors: person-name person-hair person-eyes person-phone ; predicate: person? (define-struct pet [name number]) ; constructor: make-pet ; selectors: pet-name pet-number ; predicate: pet? (define-struct CD [artist title price]) ; constructor: make-CD ; selectors: CD-artist CD-title CD-price ; predicate: CD? (define-struct sweater [material size producer]) ; constructor: make-sweater ; selectors: sweater-material sweater-size sweater-producer ; predicate: sweater? ; Make sensible guesses as to what kind of values go with which fields. Then create at least one instance per structure type definition ; and draw box representations for them. (make-movie "Ant-man" "Marvel" 2015) (make-person "Tyler" "black" "black" "11111111111") (make-pet "doggy" 2344) (make-CD "Li Keqin" "Red Sun" 12.23) (make-sweater "cotton" "XL" "Gap")
null
https://raw.githubusercontent.com/jiangpengnju/htdp2e/d41555519fbb378330f75c88141f72b00a9ab1d3/fixed-size-data/adding-structure/ex67.rkt
racket
about the language level of this file in a form that our tools can easily process. Write down the names of the functions(constructors, selectors, and predicates) that the following structure type definitions introduce: constructor: make-movie selectors: movie-title movie-producer movie-year predicate: movie? constructor: make-person selectors: person-name person-hair person-eyes person-phone predicate: person? constructor: make-pet selectors: pet-name pet-number predicate: pet? constructor: make-CD selectors: CD-artist CD-title CD-price predicate: CD? constructor: make-sweater selectors: sweater-material sweater-size sweater-producer predicate: sweater? Make sensible guesses as to what kind of values go with which fields. and draw box representations for them.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex67) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (define-struct movie [title producer year]) (define-struct person [name hair eyes phone]) (define-struct pet [name number]) (define-struct CD [artist title price]) (define-struct sweater [material size producer]) Then create at least one instance per structure type definition (make-movie "Ant-man" "Marvel" 2015) (make-person "Tyler" "black" "black" "11111111111") (make-pet "doggy" 2344) (make-CD "Li Keqin" "Red Sun" 12.23) (make-sweater "cotton" "XL" "Gap")
3295aed72288a6a7af76c666c18b677342bea5961be22d3f1f20aacaae537035
WormBase/wormbase_rest
location.clj
(ns rest-api.classes.variation.widgets.location (:require [rest-api.classes.sequence.core :as sequence-fns] [rest-api.classes.generic-fields :as generic])) (defn tracks [variation] {:data (cond (= "Caenorhabditis elegans" (:species/id (:variation/species variation))) ["GENES" "VARIATIONS_CLASSICAL_ALLELES" "VARIATIONS_HIGH_THROUGHPUT_ALLELES" "VARIATIONS_POLYMORPHISMS" "VARIATIONS_CHANGE_OF_FUNCTION_ALLELES" "VARIATIONS_CHANGE_OF_FUNCTION_POLYMORPHISMS" "VARIATIONS_TRANSPOSON_INSERTION_SITES" "VARIATIONS_MILLION_MUTATION_PROJECT"] (= "Caenorhabditis briggsae" (:species/id (:variation/species variation))) ["GENES" "VARIATIONS_POLYMORPHISMS"] :else ["GENES"]) :description "tracks displayed in GBrowse"}) (defn jbrowse-tracks [variation] {:data (cond (= "Caenorhabditis elegans" (:species/id (:variation/species variation))) "Curated_Genes,Classical_alleles,High-throughput alleles,Polymorphisms,Change-of-function alleles,Change-of-function polymorphisms,Transposon insert sites,Million Mutation Project" (= "Caenorhabditis briggsae" (:species/id (:variation/species variation))) "Curated_Genes,Polymorphisms" :else "Curated_Genes") :description "tracks displayed in JBrowse"}) (defn genomic-image [variation] {:data (first (:data (generic/genomic-position variation))) :description "The genomic location of the sequence to be displayed by GBrowse"}) (def widget {:name generic/name-field :genetic_position generic/genetic-position :tracks tracks :jbrowse_tracks jbrowse-tracks :genomic_position generic/genomic-position :genomic_image genomic-image})
null
https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/variation/widgets/location.clj
clojure
(ns rest-api.classes.variation.widgets.location (:require [rest-api.classes.sequence.core :as sequence-fns] [rest-api.classes.generic-fields :as generic])) (defn tracks [variation] {:data (cond (= "Caenorhabditis elegans" (:species/id (:variation/species variation))) ["GENES" "VARIATIONS_CLASSICAL_ALLELES" "VARIATIONS_HIGH_THROUGHPUT_ALLELES" "VARIATIONS_POLYMORPHISMS" "VARIATIONS_CHANGE_OF_FUNCTION_ALLELES" "VARIATIONS_CHANGE_OF_FUNCTION_POLYMORPHISMS" "VARIATIONS_TRANSPOSON_INSERTION_SITES" "VARIATIONS_MILLION_MUTATION_PROJECT"] (= "Caenorhabditis briggsae" (:species/id (:variation/species variation))) ["GENES" "VARIATIONS_POLYMORPHISMS"] :else ["GENES"]) :description "tracks displayed in GBrowse"}) (defn jbrowse-tracks [variation] {:data (cond (= "Caenorhabditis elegans" (:species/id (:variation/species variation))) "Curated_Genes,Classical_alleles,High-throughput alleles,Polymorphisms,Change-of-function alleles,Change-of-function polymorphisms,Transposon insert sites,Million Mutation Project" (= "Caenorhabditis briggsae" (:species/id (:variation/species variation))) "Curated_Genes,Polymorphisms" :else "Curated_Genes") :description "tracks displayed in JBrowse"}) (defn genomic-image [variation] {:data (first (:data (generic/genomic-position variation))) :description "The genomic location of the sequence to be displayed by GBrowse"}) (def widget {:name generic/name-field :genetic_position generic/genetic-position :tracks tracks :jbrowse_tracks jbrowse-tracks :genomic_position generic/genomic-position :genomic_image genomic-image})
4eebceb6b31f650f1c54a2852ee1f704eab7e10f3b7ca3bbc9fb811a96dadf26
IronScheme/IronScheme
ironscheme-buildscript.sps
Copyright ( c ) 2006 , 2007 and Copyright ( c ) 2007 - 2016 Llewellyn Pritchard ;;; ;;; Permission is hereby granted, free of charge, to any person obtaining a ;;; copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation ;;; the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the ;;; Software is furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR ;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL ;;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING ;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (import (rnrs base) (rnrs control) (rnrs io simple) (rnrs io ports) (rnrs lists) (rnrs files) (rnrs hashtables) (psyntax internal) (psyntax compat) (psyntax library-manager) (psyntax expander) (ironscheme unsafe) (ironscheme clr internal) (only (ironscheme core) compile-bootfile format) (only (ironscheme) time-it include import library)) (define scheme-library-files '( "build/predicates.sls" "build/records/procedural.sls" "build/conditions.sls" "build/exceptions.sls" "build/arithmetic/fixnums.sls" "build/primitive-numbers.sls" "build/hashtables.sls" "build/lists.sls" "build/base.sls" "build/numbers.sls" "build/bytevectors.sls" "psyntax/compat.sls" ;; needs make-parameter "build/io/ports.sls" "build/io/simple.sls" "build/vectors.sls" "build/generic-writer.sls" "build/files.sls" "build/mutable-pairs.sls" "build/programs.sls" "build/r5rs.sls" "build/sorting.sls" "build/unicode.sls" "build/arithmetic/bitwise.sls" "build/arithmetic/flonums.sls" "build/records/inspection.sls" ; depends on records - hashtables - bitwise "build/enums.sls" "build/format.sls" "build/trace.sls" "build/equal.sls" "build/pretty-print.sls" "build/misc.sls" "build/constant-fold.sls" "psyntax/internal.sls" "psyntax/library-manager.sls" "psyntax/builders.sls" "psyntax/expander.sls" "psyntax/main.sls" )) (define psyntax-system-macros '((define (define)) (define-syntax (define-syntax)) (define-fluid-syntax (define-fluid-syntax)) (module (module)) (begin (begin)) (library (library)) (import (import)) (export (export)) (set! (set!)) (let-syntax (let-syntax)) (letrec-syntax (letrec-syntax)) (stale-when (stale-when)) (foreign-call (core-macro . foreign-call)) (quote (core-macro . quote)) (syntax-case (core-macro . syntax-case)) (syntax (core-macro . syntax)) (lambda (core-macro . lambda)) (typed-lambda (core-macro . typed-lambda)) (case-lambda (core-macro . case-lambda)) (typed-case-lambda (core-macro . typed-case-lambda)) (type-descriptor (core-macro . type-descriptor)) (letrec (core-macro . letrec)) (letrec* (core-macro . letrec*)) (if (core-macro . if)) (when (macro . when)) (unless (macro . unless)) (parameterize (macro . parameterize)) (case (macro . case)) (fluid-let-syntax (core-macro . fluid-let-syntax)) (record-type-descriptor (core-macro . record-type-descriptor)) (record-constructor-descriptor (core-macro . record-constructor-descriptor)) (let*-values (macro . let*-values)) (let-values (macro . let-values)) (define-struct (macro . define-struct)) (include (macro . include)) (include-into (macro . include-into)) (syntax-rules (macro . syntax-rules)) (quasiquote (macro . quasiquote)) (quasisyntax (macro . quasisyntax)) (with-syntax (macro . with-syntax)) (identifier-syntax (macro . identifier-syntax)) (let (macro . let)) (let* (macro . let*)) (cond (macro . cond)) (do (macro . do)) (and (macro . and)) (or (macro . or)) (time (macro . time)) (delay (macro . delay)) (endianness (macro . endianness)) (assert (macro . assert)) (... (macro . ...)) (=> (macro . =>)) (else (macro . else)) (_ (macro . _)) (unquote (macro . unquote)) (unquote-splicing (macro . unquote-splicing)) (unsyntax (macro . unsyntax)) (unsyntax-splicing (macro . unsyntax-splicing)) (trace-lambda (macro . trace-lambda)) (trace-let (macro . trace-let)) (trace-define (macro . trace-define)) (trace-define-syntax (macro . trace-define-syntax)) (trace-let-syntax (macro . trace-let-syntax)) (trace-letrec-syntax (macro . trace-letrec-syntax)) ;;; new (guard (macro . guard)) (eol-style (macro . eol-style)) (buffer-mode (macro . buffer-mode)) (file-options (macro . file-options)) (error-handling-mode (macro . error-handling-mode)) (fields (macro . fields)) (mutable (macro . mutable)) (immutable (macro . immutable)) (parent (macro . parent)) (protocol (macro . protocol)) (sealed (macro . sealed)) (opaque (macro . opaque )) (nongenerative (macro . nongenerative)) (parent-rtd (macro . parent-rtd)) (define-record-type (macro . define-record-type)) (define-enumeration (macro . define-enumeration)) (define-condition-type (macro . define-condition-type)) ;;; for (record-type-descriptor &condition-type) and ;;; (record-constructor-descriptor &condition-type) to ;;; expand properly, the implementation must export ;;; the identifiers &condition-type-rtd, which must ;;; be bound to the run-time value of the rtd, and ;;; &condition-type-rcd which must be bound to the ;;; corresponding record-constructor-descriptor. (&condition ($core-rtd . (&condition-rtd &condition-rcd))) (&message ($core-rtd . (&message-rtd &message-rcd))) (&warning ($core-rtd . (&warning-rtd &warning-rcd ))) (&serious ($core-rtd . (&serious-rtd &serious-rcd))) (&error ($core-rtd . (&error-rtd &error-rcd))) (&violation ($core-rtd . (&violation-rtd &violation-rcd))) (&assertion ($core-rtd . (&assertion-rtd &assertion-rcd))) (&irritants ($core-rtd . (&irritants-rtd &irritants-rcd))) (&who ($core-rtd . (&who-rtd &who-rcd))) (&implementation-restriction ($core-rtd . (&implementation-restriction-rtd &implementation-restriction-rcd))) (&lexical ($core-rtd . (&lexical-rtd &lexical-rcd))) (&syntax ($core-rtd . (&syntax-rtd &syntax-rcd))) (&undefined ($core-rtd . (&undefined-rtd &undefined-rcd))) (&non-continuable ($core-rtd . (&non-continuable-rtd &non-continuable-rcd))) (&i/o ($core-rtd . (&i/o-rtd &i/o-rcd))) (&i/o-read ($core-rtd . (&i/o-read-rtd &i/o-read-rcd))) (&i/o-write ($core-rtd . (&i/o-write-rtd &i/o-write-rcd))) (&i/o-invalid-position ($core-rtd . (&i/o-invalid-position-rtd &i/o-invalid-position-rcd))) (&i/o-filename ($core-rtd . (&i/o-filename-rtd &i/o-filename-rcd))) (&i/o-file-protection ($core-rtd . (&i/o-file-protection-rtd &i/o-file-protection-rcd))) (&i/o-file-is-read-only ($core-rtd . (&i/o-file-is-read-only-rtd &i/o-fie-is-read-only-rcd))) (&i/o-file-already-exists ($core-rtd . (&i/o-file-already-exists-rtd &i/o-file-already-exists-rcd))) (&i/o-file-does-not-exist ($core-rtd . (&i/o-file-does-not-exist-rtd &i/o-file-does-not-exist-rcd))) (&i/o-port ($core-rtd . (&i/o-port-rtd &i/o-port-rcd))) (&i/o-decoding ($core-rtd . (&i/o-decoding-rtd &i/o-decoding-rcd))) (&i/o-encoding ($core-rtd . (&i/o-encoding-rtd &i/o-encoding-rcd))) (&no-infinities ($core-rtd . (&no-infinities-rtd &no-infinities-rcd))) (&no-nans ($core-rtd . (&no-nans-rtd &no-nans-rcd))) (&where ($core-rtd . (&where-rtd &where-rcd))) (&stacktrace ($core-rtd . (&stacktrace-rtd &stacktrace-rcd))) )) (define (macro-identifier x) (assq x psyntax-system-macros)) (define library-legend ;; abbr. name visible? required? '((i (ironscheme) #t #t) (il (ironscheme library) #f #t) (ir (ironscheme reader) #f #t) (iser (ironscheme serialization) #f #t) (ic (ironscheme core) #f #t) (iu (ironscheme unsafe) #t #t) (irp (ironscheme records printer) #t #t) (is-clr-int (ironscheme clr internal) #t #t) (ne (psyntax null-environment-5) #f #f) (se (psyntax scheme-report-environment-5) #f #f) (r (rnrs) #t #t) (r5 (rnrs r5rs) #t #t) (ct (rnrs control) #t #t) (ev (rnrs eval) #t #t) (mp (rnrs mutable-pairs) #t #t) (ms (rnrs mutable-strings) #t #t) (pr (rnrs programs) #t #t) (sc (rnrs syntax-case) #t #t) (fi (rnrs files) #t #t) (sr (rnrs sorting) #t #t) (ba (rnrs base) #t #t) (ls (rnrs lists) #t #t) (is (rnrs io simple) #t #t) (bv (rnrs bytevectors) #t #t) (uc (rnrs unicode) #t #t) (ex (rnrs exceptions) #t #t) (bw (rnrs arithmetic bitwise) #t #t) (fx (rnrs arithmetic fixnums) #t #t) (fl (rnrs arithmetic flonums) #t #t) (ht (rnrs hashtables) #t #t) (ip (rnrs io ports) #t #t) (en (rnrs enums) #t #t) (co (rnrs conditions) #t #t) (ri (rnrs records inspection) #t #t) (rp (rnrs records procedural) #t #t) (rs (rnrs records syntactic) #t #t) ($all (psyntax system $all) #f #t) ($boot (psyntax system $bootstrap) #f #t) )) ;;; required? flag means that said library is required for ;;; building the system. The only non-r6rs required libraries ;;; should be (psyntax system $bootstrap) and (psyntax system $all). ;;; (psyntax system $bootstrap) should export, at a minimum, the following procedures : , symbol - value , set - symbol - value ! , ;;; eval-core, and pretty-print. ;;; (psyntax system $all) is fabricated by the system to include ;;; every identifier in the system. (define identifier->library-map '( ;;; (load/unsafe i) (optimize ic) (compress-constants? ic) (clr-string? ic) (stringbuilder? ic) (bignum? ic) (rectnum? ic) (ratnum? ic) (complexnum? ic) (fx+internal ic) (fx-internal ic) (fx*internal ic) (fxarithmetic-shift-left-internal ic) (fxadd1 i) (fxsub1 i) (add1 i) (sub1 i) (displayln i) (writeln i) (flvector? i) (fxvector? i) (flvector-ref i) (fxvector-ref i) (flvector-set! i) (fxvector-set! i) (make-flvector i) (make-fxvector i) (flvector-length i) (fxvector-length i) (flvector->list i) (fxvector->list i) (list->flvector i) (list->fxvector i) (flvector-fill! i) (fxvector-fill! i) (valuetype-vector? i) (with-timeout i) (file-mtime i) (allow-library-redefinition i) (with-clr-exception-handler i) (typed-lambda i) (typed-case-lambda i) (pointer+ i) (expanded->core i) (import i) (export i) (library i) (include i) (stale-when i) (strict-mode? i) (debug-mode? i) (lw-debug-mode? i) (lw-debugger i) (lw-debugger-call-stack i) (lw-debugger-location-trace i) (lw-debugger-stackframe-variables i) (decompose-flonum i) (open-output-string i) (get-output-string i) (pretty-print i) (generic-write i) (initialize-default-printers i) (pretty-width i) (pretty-gensyms i) (uninstall-library i) (installed-libraries i) (make-where-condition i) (where-condition? i) (&where i) (condition-where i) (make-stacktrace-condition i) (display-stacktrace i) (stacktrace-condition? i) (condition-stacktrace i) (&stacktrace i) (generic+ ic) (generic- ic) (generic* ic) (generic/ ic) (generic-div ic) (bignum-sqrt ic) (bignum-sqrt-exact ic) (inexact=? ic) (convert->cps i) (syntax-transpose i) (emacs-mode? i) ;(expand-boot-cps i) (top-level-expander i) (core-library-expander i) (parse-top-level-program i) (parse-library i) (core-expand i) (expand->core i) (include-into i) (make-compile-time-value i) (library-path i ic) (interaction-environment-symbols i) (interaction-environment? i) (environment-symbols i) (environment-bindings i) (hashtable-map i) (hashtable-for-each i) (open-tcp-input/output-port i) (get-library-paths il ic) (file-locator il) (alternative-file-locator il) (make-parameter i) (parameterize i) (time i) (time-it i) (assertion-error ic) (trace-lambda i) (trace-let i) (trace-define i) (trace-define-syntax i) (trace-let-syntax i) (trace-letrec-syntax i) (make-traced-macro ic) (make-traced-procedure ic) (trace-printer i) (string-format i) (string-compare i) (string-ci-compare i) (vector-binary-search i) (vector-copy i) (vector-index-of i) (vector-contains? i) (vector-reverse! i) (vector-filter i) (vector-append i) (vector-fold-left i) (bytevector-fold-left i) (get-command-line ic) (get-clr-type i) (clr-type? i) (typeof i) (gc-collect i) (procedure-arity i) (procedure-name i) (procedure-environment i) (procedure-form i) (format i ic) (fprintf i) (shorthand-syntax-output i) (printf i) (load-port i) (load/args i) (load/unload i) (make-promise ic) (promise? i) (enum-set? i) (record-constructor-descriptor? i) (serialize-port i) (deserialize-port i) (reverse! ic) (eqv-hash ic) (add-record-printer! irp) ($break iu) ($throw iu) ($try/finally iu) ($and? iu) ($or? iu) ($car iu) ($cdr iu) ($vector-ref iu) ($vector-set! iu) ($fx=? iu) ($fx+ iu) ($fx* iu) ($fxdiv iu) ($fxmod iu) ($fx- iu) ($fx<? iu) ($fx<=? iu) ($fx>? iu) ($fx>=? iu) ($fxand iu) ($fxior iu) ($fxxor iu) ($fxnot iu) ($fxarithmetic-shift-left iu) ($fxarithmetic-shift-right iu) ($fxzero? iu) ($fxnegative? iu) ($fxpositive? iu) ($fxeven? iu) ($fxodd? iu) ($try iu) ($try/overflow iu) ($try/io iu) ($fl=? iu) ($fl+ iu) ($fl* iu) ($fl/ iu) ($fl- iu) ($fl<? iu) ($fl<=? iu) ($fl>? iu) ($fl>=? iu) ($bytevector-ref iu) ($bytevector-set! iu) (lambda i r ba se ne) (and i r ba se ne) (begin i r ba se ne) (case i r ba se ne) (cond i r ba se ne) (define i r ba se ne) (define-syntax i r ba se ne) (identifier-syntax i r ba) (if i r ba se ne) (let i r ba se ne) (let* i r ba se ne) (let*-values i r ba) (let-syntax i r ba se ne) (let-values i r ba) (letrec i r ba se ne) (letrec* i r ba) (letrec-syntax i r ba se ne) (define-fluid-syntax i) (fluid-let-syntax i) (or i r ba se ne) (quasiquote i r ba se ne) (quote i r ba se ne) (set! i r ba se ne) (syntax-rules i r ba se ne) (unquote i r ba se ne) (unquote-splicing i r ba se ne) (< i r ba se) (<= i r ba se) (= i r ba se) (> i r ba se) (>= i r ba se) (+ i r ba se) (- i r ba se) (* i r ba se) (/ i r ba se) (abs i r ba se) (acos i r ba se) (angle i r ba se) (append i r ba se) (apply i r ba se) (asin i r ba se) (assert i r ba) (assertion-violation i r ba) (atan i r ba se) (boolean=? i r ba) (boolean? i r ba se) (car i r ba se) (cdr i r ba se) (caar i r ba se) (cadr i r ba se) (cdar i r ba se) (cddr i r ba se) (caaar i r ba se) (caadr i r ba se) (cadar i r ba se) (caddr i r ba se) (cdaar i r ba se) (cdadr i r ba se) (cddar i r ba se) (cdddr i r ba se) (caaaar i r ba se) (caaadr i r ba se) (caadar i r ba se) (caaddr i r ba se) (cadaar i r ba se) (cadadr i r ba se) (caddar i r ba se) (cadddr i r ba se) (cdaaar i r ba se) (cdaadr i r ba se) (cdadar i r ba se) (cdaddr i r ba se) (cddaar i r ba se) (cddadr i r ba se) (cdddar i r ba se) (cddddr i r ba se) (call-with-current-continuation i r ba se) (call/cc i r ba) (call-with-values i r ba se) (ceiling i r ba se) (char->integer i r ba se) (char<=? i r ba se) (char<? i r ba se) (char=? i r ba se) (char>=? i r ba se) (char>? i r ba se) (char? i r ba se) (complex? i r ba se) (cons i r ba se) (cos i r ba se) (denominator i r ba se) (div i r ba) (mod i r ba) (div-and-mod i r ba) (div0 i r ba) (mod0 i r ba) (div0-and-mod0 i r ba) (dynamic-wind i r ba se) (eq? i r ba se) (equal? i r ba se) (eqv? i r ba se) (error i r ba) (even? i r ba se) (exact i r ba) (exact-integer-sqrt i r ba) (exact? i r ba se) (exp i r ba se) (expt i r ba se) (finite? i r ba) (floor i r ba se) (for-each i r ba se) (gcd i r ba se) (imag-part i r ba se) (inexact i r ba) (inexact? i r ba se) (infinite? i r ba) (integer->char i r ba se) (integer-valued? i r ba) (integer? i r ba se) (lcm i r ba se) (length i r ba se) (list i r ba se) (list->string i r ba se) (list->vector i r ba se) (list-ref i r ba se) (list-tail i r ba se) (list? i r ba se) (log i r ba se) (magnitude i r ba se) (make-polar i r ba se) (make-rectangular i r ba se) (make-string i r ba se) (make-vector i r ba se) (map i r ba se) (max i r ba se) (min i r ba se) (nan? i r ba) (negative? i r ba se) (not i r ba se) (null? i r ba se) (number->string i r ba se) (number? i r ba se) (numerator i r ba se) (odd? i r ba se) (pair? i r ba se) (positive? i r ba se) (procedure? i r ba se) (rational-valued? i r ba) (rational? i r ba se) (rationalize i r ba se) (real-part i r ba se) (real-valued? i r ba) (real? i r ba se) (reverse i r ba se) (round i r ba se) (sin i r ba se) (sqrt i r ba se) (string i r ba se) (string->list i r ba se) (string->number i r ba se) (string->symbol i r ba se) (string-append i r ba se) (string-copy i r ba se) (string-for-each i r ba) (string-length i r ba se) (string-ref i r ba se) (string<=? i r ba se) (string<? i r ba se) (string=? i r ba se) (string>=? i r ba se) (string>? i r ba se) (string? i r ba se) (substring i r ba se) (symbol->string i r ba se) (symbol=? i r ba) (symbol? i r ba se) (tan i r ba se) (truncate i r ba se) (values i r ba se) (vector i r ba se) (vector->list i r ba se) (vector-fill! i r ba se) (vector-for-each i r ba) (vector-length i r ba se) (vector-map i r ba) (vector-ref i r ba se) (vector-set! i r ba se) (vector? i r ba se) (zero? i r ba se) (... i r ba sc se) (=> i r ba ex se ne) (_ i r ba sc) (else i r ba ex se ne) ;;; (bitwise-arithmetic-shift i r bw) (bitwise-arithmetic-shift-left i r bw) (bitwise-arithmetic-shift-right i r bw) (bitwise-not i r bw) (bitwise-and i r bw) (bitwise-ior i r bw) (bitwise-xor i r bw) (bitwise-bit-count i r bw) (bitwise-bit-field i r bw) (bitwise-bit-set? i r bw) (bitwise-copy-bit i r bw) (bitwise-copy-bit-field i r bw) (bitwise-first-bit-set i r bw) (bitwise-if i r bw) (bitwise-length i r bw) (bitwise-reverse-bit-field i r bw) (bitwise-rotate-bit-field i r bw) ;;; (fixnum? i r fx) (fixnum-width i r fx) (least-fixnum i r fx) (greatest-fixnum i r fx) (fx* i r fx) (fx*/carry i r fx) (fx+ i r fx) (fx+/carry i r fx) (fx- i r fx) (fx-/carry i r fx) (fx<=? i r fx) (fx<? i r fx) (fx=? i r fx) (fx>=? i r fx) (fx>? i r fx) (fxand i r fx) (fxarithmetic-shift i r fx) (fxarithmetic-shift-left i r fx) (fxarithmetic-shift-right i r fx) (fxbit-count i r fx) (fxbit-field i r fx) (fxbit-set? i r fx) (fxcopy-bit i r fx) (fxcopy-bit-field i r fx) (fxdiv i r fx) (fxdiv-and-mod i r fx) (fxdiv0 i r fx) (fxdiv0-and-mod0 i r fx) (fxeven? i r fx) (fxfirst-bit-set i r fx) (fxif i r fx) (fxior i r fx) (fxlength i r fx) (fxmax i r fx) (fxmin i r fx) (fxmod i r fx) (fxmod0 i r fx) (fxnegative? i r fx) (fxnot i r fx) (fxodd? i r fx) (fxpositive? i r fx) (fxreverse-bit-field i r fx) (fxrotate-bit-field i r fx) (fxxor i r fx) (fxzero? i r fx) ;;; (fixnum->flonum i r fl) (fl* i r fl) (fl+ i r fl) (fl- i r fl) (fl/ i r fl) (fl<=? i r fl) (fl<? i r fl) (fl=? i r fl) (fl>=? i r fl) (fl>? i r fl) (flabs i r fl) (flacos i r fl) (flasin i r fl) (flatan i r fl) (flceiling i r fl) (flcos i r fl) (fldenominator i r fl) (fldiv i r fl) (fldiv-and-mod i r fl) (fldiv0 i r fl) (fldiv0-and-mod0 i r fl) (fleven? i r fl) (flexp i r fl) (flexpt i r fl) (flfinite? i r fl) (flfloor i r fl) (flinfinite? i r fl) (flinteger? i r fl) (fllog i r fl) (flmax i r fl) (flmin i r fl) (flmod i r fl) (flmod0 i r fl) (flnan? i r fl) (flnegative? i r fl) (flnumerator i r fl) (flodd? i r fl) (flonum? i r fl) (flpositive? i r fl) (flround i r fl) (flsin i r fl) (flsqrt i r fl) (fltan i r fl) (fltruncate i r fl) (flzero? i r fl) (real->flonum i r fl) (make-no-infinities-violation i r fl) (make-no-nans-violation i r fl) (&no-infinities i r fl) (no-infinities-violation? i r fl) (&no-nans i r fl) (no-nans-violation? i r fl) ;;; (bytevector->sint-list i r bv) (bytevector->u8-list i r bv) (bytevector->uint-list i r bv) (bytevector-copy i r bv) (bytevector-copy! i r bv) (bytevector-fill! i r bv) (bytevector-ieee-double-native-ref i r bv) (bytevector-ieee-double-native-set! i r bv) (bytevector-ieee-double-ref i r bv) (bytevector-ieee-double-set! i r bv) (bytevector-ieee-single-native-ref i r bv) (bytevector-ieee-single-native-set! i r bv) (bytevector-ieee-single-ref i r bv) (bytevector-ieee-single-set! i r bv) (bytevector-length i r bv) (bytevector-s16-native-ref i r bv) (bytevector-s16-native-set! i r bv) (bytevector-s16-ref i r bv) (bytevector-s16-set! i r bv) (bytevector-s32-native-ref i r bv) (bytevector-s32-native-set! i r bv) (bytevector-s32-ref i r bv) (bytevector-s32-set! i r bv) (bytevector-s64-native-ref i r bv) (bytevector-s64-native-set! i r bv) (bytevector-s64-ref i r bv) (bytevector-s64-set! i r bv) (bytevector-s8-ref i r bv) (bytevector-s8-set! i r bv) (bytevector-sint-ref i r bv) (bytevector-sint-set! i r bv) (bytevector-u16-native-ref i r bv) (bytevector-u16-native-set! i r bv) (bytevector-u16-ref i r bv) (bytevector-u16-set! i r bv) (bytevector-u32-native-ref i r bv) (bytevector-u32-native-set! i r bv) (bytevector-u32-ref i r bv) (bytevector-u32-set! i r bv) (bytevector-u64-native-ref i r bv) (bytevector-u64-native-set! i r bv) (bytevector-u64-ref i r bv) (bytevector-u64-set! i r bv) (bytevector-u8-ref i r bv) (bytevector-u8-set! i r bv) (bytevector-uint-ref i r bv) (bytevector-uint-set! i r bv) (bytevector=? i r bv) (bytevector? i r bv) (endianness i r bv) (native-endianness i r bv) (sint-list->bytevector i r bv) (string->utf16 i r bv) (string->utf32 i r bv) (string->utf8 i r bv) (u8-list->bytevector i r bv) (uint-list->bytevector i r bv) (utf8->string i r bv) (utf16->string i r bv) (utf32->string i r bv) ;;; (condition? i r co) (&assertion i r co) (assertion-violation? i r co) (&condition i r co) (condition i r co) (condition-accessor i r co) (condition-irritants i r co) (condition-message i r co) (condition-predicate i r co) (condition-who i r co) (define-condition-type i r co) (&error i r co) (error? i r co) (&implementation-restriction i r co) (implementation-restriction-violation? i r co) (&irritants i r co) (irritants-condition? i r co) (&lexical i r co) (lexical-violation? i r co) (make-assertion-violation i r co) (make-error i r co) (make-implementation-restriction-violation i r co) (make-irritants-condition i r co) (make-lexical-violation i r co) (make-message-condition i r co) (make-non-continuable-violation i r co) (make-serious-condition i r co) (make-syntax-violation i r co) (make-undefined-violation i r co) (make-violation i r co) (make-warning i r co) (make-who-condition i r co) (&message i r co) (message-condition? i r co) (&non-continuable i r co) (non-continuable-violation? i r co) (&serious i r co) (serious-condition? i r co) (simple-conditions i r co) (&syntax i r co) (syntax-violation i r sc) (syntax-violation-form i r co) (syntax-violation-subform i r co) (syntax-violation? i r co) (&undefined i r co) (undefined-violation? i r co) (&violation i r co) (violation? i r co) (&warning i r co) (warning? i r co) (&who i r co) (who-condition? i r co) ;;; (case-lambda i r ct) (do i r ct se ne) (unless i r ct) (when i r ct) ;;; (define-enumeration i r en) (enum-set->list i r en) (enum-set-complement i r en) (enum-set-constructor i r en) (enum-set-difference i r en) (enum-set-indexer i r en) (enum-set-intersection i r en) (enum-set-member? i r en) (enum-set-projection i r en) (enum-set-subset? i r en) (enum-set-union i r en) (enum-set-universe i r en) (enum-set=? i r en) (make-enumeration i r en) ;;; (environment i ev) (eval i ev se) ;;; (raise i r ex) (raise-continuable i r ex) (with-exception-handler i r ex) (guard i r ex) ;;; (assoc i r ls se) (assp i r ls) (assq i r ls se) (assv i r ls se) (cons* i r ls) (filter i r ls) (find i r ls) (fold-left i r ls) (fold-right i r ls) (for-all i r ls) (exists i r ls) (member i r ls se) (memp i r ls) (memq i r ls se) (memv i r ls se) (partition i r ls) (remq i r ls) (remp i r ls) (remv i r ls) (remove i r ls) ;;; (set-car! i mp se) (set-cdr! i mp se) ;;; (string-set! i ms se) (string-fill! i ms se) ;;; (command-line i r pr) (exit i r pr) ;;; (delay i r5 se ne) (exact->inexact i r5 se) (force i r5 se) (inexact->exact i r5 se) (modulo i r5 se) (remainder i r5 se) (null-environment i r5 se) (quotient i r5 se) (scheme-report-environment i r5 se) ;;; (binary-port? i r ip) (buffer-mode i r ip) (buffer-mode? i r ip) (bytevector->string i r ip) (call-with-bytevector-output-port i r ip) (call-with-port i r ip) (call-with-string-output-port i r ip) (close-port i r ip) (eol-style i r ip) (error-handling-mode i r ip) (file-options i r ip) (flush-output-port i r ip) (get-bytevector-all i r ip) (get-bytevector-n i r ip) (get-bytevector-n! i r ip) (get-bytevector-some i r ip) (get-char i r ip) (get-datum i r ip) (get-line i r ip) (get-string-all i r ip) (get-string-n i r ip) (get-string-n! i r ip) (get-u8 i r ip) (&i/o i r ip is fi) (&i/o-decoding i r ip) (i/o-decoding-error? i r ip) (&i/o-encoding i r ip) (i/o-encoding-error-char i r ip) (i/o-encoding-error? i r ip) (i/o-error-filename i r ip is fi) (i/o-error-port i r ip is fi) (i/o-error? i r ip is fi) (&i/o-file-already-exists i r ip is fi) (i/o-file-already-exists-error? i r ip is fi) (&i/o-file-does-not-exist i r ip is fi) (i/o-file-does-not-exist-error? i r ip is fi) (&i/o-file-is-read-only i r ip is fi) (i/o-file-is-read-only-error? i r ip is fi) (&i/o-file-protection i r ip is fi) (i/o-file-protection-error? i r ip is fi) (&i/o-filename i r ip is fi) (i/o-filename-error? i r ip is fi) (&i/o-invalid-position i r ip is fi) (i/o-error-position i r ip is fi) (i/o-invalid-position-error? i r ip is fi) (&i/o-port i r ip is fi) (i/o-port-error? i r ip is fi) (&i/o-read i r ip is fi) (i/o-read-error? i r ip is fi) (&i/o-write i r ip is fi) (i/o-write-error? i r ip is fi) (lookahead-char i r ip) (lookahead-u8 i r ip) (make-bytevector i r bv) (make-custom-binary-input-port i r ip) (make-custom-binary-input/output-port i r ip) (make-custom-binary-output-port i r ip) (make-custom-textual-input-port i r ip) (make-custom-textual-input/output-port i r ip) (make-custom-textual-output-port i r ip) (make-i/o-decoding-error i r ip) (make-i/o-encoding-error i r ip) (make-i/o-error i r ip is fi) (make-i/o-file-already-exists-error i r ip is fi) (make-i/o-file-does-not-exist-error i r ip is fi) (make-i/o-file-is-read-only-error i r ip is fi) (make-i/o-file-protection-error i r ip is fi) (make-i/o-filename-error i r ip is fi) (make-i/o-invalid-position-error i r ip is fi) (make-i/o-port-error i r ip is fi) (make-i/o-read-error i r ip is fi) (make-i/o-write-error i r ip is fi) (latin-1-codec i r ip) (make-transcoder i r ip) (native-eol-style i r ip) (native-transcoder i r ip) (open-bytevector-input-port i r ip) (open-bytevector-output-port i r ip) (open-file-input-port i r ip) (open-file-input/output-port i r ip) (open-file-output-port i r ip) (open-string-input-port i r ip) (open-string-output-port i r ip) (output-port-buffer-mode i r ip) (port-eof? i r ip) (port-has-port-position? i r ip) (port-has-set-port-position!? i r ip) (port-position i r ip) (port-transcoder i r ip) (port? i r ip) (put-bytevector i r ip) (put-char i r ip) (put-datum i r ip) (put-string i r ip) (put-u8 i r ip) (set-port-position! i r ip) (standard-error-port i r ip) (standard-input-port i r ip) (standard-output-port i r ip) (string->bytevector i r ip) (textual-port? i r ip) (transcoded-port i r ip) (transcoder-codec i r ip) (transcoder-eol-style i r ip) (transcoder-error-handling-mode i r ip) (utf-16-codec i r ip) (utf-8-codec i r ip) ;;; (input-port? i r is ip se) (output-port? i r is ip se) (current-input-port i r ip is se) (current-output-port i r ip is se) (current-error-port i r ip is se) (eof-object i r ip is) (eof-object? i r ip is se) (close-input-port i r is se) (close-output-port i r is se) (display i r is se) (newline i r is se) (open-input-file i r is se) (open-output-file i r is se) (peek-char i r is se) (read i r is se) (read-char i r is se) (with-input-from-file i r is se) (with-output-to-file i r is se) (write i r is se) (write-char i r is se) (call-with-input-file i r is se) (call-with-output-file i r is se) (textual-input-port? i) (textual-output-port? i) ;;; (hashtable-clear! i r ht) (hashtable-contains? i r ht) (hashtable-copy i r ht) (hashtable-delete! i r ht) (hashtable-entries i r ht) (hashtable-keys i r ht) (hashtable-mutable? i r ht) (hashtable-ref i r ht) (hashtable-set! i r ht) (hashtable-size i r ht) (hashtable-update! i r ht) (hashtable? i r ht) (make-eq-hashtable i r ht) (make-eqv-hashtable i r ht) (hashtable-hash-function i r ht) (make-hashtable i r ht) (hashtable-equivalence-function i r ht) (equal-hash i r ht) (string-hash i r ht) (string-ci-hash i r ht) (symbol-hash i r ht) ;;; (list-sort i r sr) (vector-sort i r sr) (vector-sort! i r sr) ;;; (file-exists? i r fi) (delete-file i r fi) ;;; (define-record-type i r rs) (fields i r rs) (immutable i r rs) (mutable i r rs) (opaque i r rs) (parent i r rs) (parent-rtd i r rs) (protocol i r rs) (record-constructor-descriptor i r rs) (record-type-descriptor i r rs) (sealed i r rs) (nongenerative i r rs) ;;; (record-field-mutable? i r ri) (record-rtd i r ri) (record-type-field-names i r ri) (record-type-generative? i r ri) (record-type-name i r ri) (record-type-opaque? i r ri) (record-type-parent i r ri) (record-type-sealed? i r ri) (record-type-uid i r ri) (record? i r ri) ;;; (make-record-constructor-descriptor i r rp) (make-record-type-descriptor i r rp) (record-accessor i r rp) (record-constructor i r rp) (record-mutator i r rp) (record-predicate i r rp) (record-type-descriptor? i r rp) ;;; (bound-identifier=? i r sc) (datum->syntax i r sc) (syntax i r sc) (syntax->datum i r sc) (syntax-case i r sc) (unsyntax i r sc) (unsyntax-splicing i r sc) (quasisyntax i r sc) (with-syntax i r sc) (free-identifier=? i r sc) (generate-temporaries i r sc) (identifier? i r sc) (make-variable-transformer i r sc) (variable-transformer? ic) (variable-transformer-procedure ic) ;;; (char-alphabetic? i r uc se) (char-ci<=? i r uc se) (char-ci<? i r uc se) (char-ci=? i r uc se) (char-ci>=? i r uc se) (char-ci>? i r uc se) (char-downcase i r uc se) (char-foldcase i r uc) (char-titlecase i r uc) (char-upcase i r uc se) (char-general-category i r uc) (char-lower-case? i r uc se) (char-numeric? i r uc se) (char-title-case? i r uc) (char-upper-case? i r uc se) (char-whitespace? i r uc se) (string-ci<=? i r uc se) (string-ci<? i r uc se) (string-ci=? i r uc se) (string-ci>=? i r uc se) (string-ci>? i r uc se) (string-downcase i r uc) (string-foldcase i r uc) (string-normalize-nfc i r uc) (string-normalize-nfd i r uc) (string-normalize-nfkc i r uc) (string-normalize-nfkd i r uc) (string-titlecase i r uc) (string-upcase i r uc) ;;; (char-ready? se) (interaction-environment i) (new-interaction-environment i) (string-normalize ic) (compile-bootfile ic) (compile-library ic) (stx? ic) (stx-expr ic) (library-name->file-name ic) (library-name->dll-name ic) (compiled-library-exists? ic) (library-exists? ic) (load i) (compile i) (compile-to-current-directory? i) (compile->closure i) (compile-system-libraries i) (serialize-library iser) (load-serialized-library iser) (load-library-dll ic) ;;; (void $boot i) (gensym $boot i) (ungensym $boot i) (symbol-bound? i) (symbol-value $boot i) (set-symbol-value! $boot i) (remove-location i) (eval-core $boot) (compile-core $boot) (module i) (syntax-dispatch ) ; only goes to $all (syntax-error ) ; only goes to $all (clr-type-of-internal is-clr-int) (clr-namespaces-internal is-clr-int) (clr-using-internal is-clr-int) (clr-reference-internal is-clr-int) (clr-is-internal is-clr-int) (clr-new-array-internal is-clr-int) (clr-new-internal is-clr-int) (clr-call-internal is-clr-int) (clr-cast-internal is-clr-int) (clr-field-get-internal is-clr-int) (clr-field-set!-internal is-clr-int) (define-clr-class-internal is-clr-int) (ffi-callout-internal is-clr-int) (ffi-callback-internal is-clr-int) (pinvoke-call-internal is-clr-int) (ironscheme-build i) (ironscheme-test i) (ironscheme-version i) (ironscheme-runtime i) (last-pair i) (make-list i) (unspecified? i) (make-guid i) (sinh i) (cosh i) (tanh i) (disassemble i) (read-annotated ir) (annotation? ir) (annotation-expression ir) (annotation-source ir) (annotation-stripped ir) (make-annotation ir) (library-letrec*) ;;; these should be assigned when creating the record types (&condition-rtd) (&condition-rcd) (&message-rtd) (&message-rcd) (&warning-rtd) (&warning-rcd) (&serious-rtd) (&serious-rcd) (&error-rtd) (&error-rcd) (&violation-rtd) (&violation-rcd) (&assertion-rtd) (&assertion-rcd) (&irritants-rtd) (&irritants-rcd) (&who-rtd) (&who-rcd) (&non-continuable-rtd) (&non-continuable-rcd) (&implementation-restriction-rtd) (&implementation-restriction-rcd) (&lexical-rtd) (&lexical-rcd) (&syntax-rtd) (&syntax-rcd) (&undefined-rtd) (&undefined-rcd) (&i/o-rtd) (&i/o-rcd) (&i/o-read-rtd) (&i/o-read-rcd) (&i/o-write-rtd) (&i/o-write-rcd) (&i/o-invalid-position-rtd) (&i/o-invalid-position-rcd) (&i/o-filename-rtd) (&i/o-filename-rcd) (&i/o-file-protection-rtd) (&i/o-file-protection-rcd) (&i/o-file-is-read-only-rtd) (&i/o-file-is-read-only-rcd) (&i/o-file-already-exists-rtd) (&i/o-file-already-exists-rcd) (&i/o-file-does-not-exist-rtd) (&i/o-file-does-not-exist-rcd) (&i/o-port-rtd) (&i/o-port-rcd) (&i/o-decoding-rtd) (&i/o-decoding-rcd) (&i/o-encoding-rtd) (&i/o-encoding-rcd) (&no-infinities-rtd) (&no-infinities-rcd) (&no-nans-rtd) (&no-nans-rcd) (&where-rtd) (&where-rcd) (&stacktrace-rtd) (&stacktrace-rcd) (ellipsis-map) )) (define (verify-map) (define (f x) (for-each (lambda (x) (unless (assq x library-legend) (error 'verify "not in the libraries list" x))) (cdr x))) (for-each f identifier->library-map)) (define (make-collection) (let ((set '())) (case-lambda (() set) ((x) (set! set (cons x set)))))) (define (make-system-data subst env) (define who 'make-system-data) (let ((export-subst (make-collection)) (export-env (make-collection)) (export-primlocs (make-collection))) (for-each (lambda (x) (let ((name (car x)) (binding (cadr x))) (let ((label (gensym))) (export-subst (cons name label)) (export-env (cons label binding))))) psyntax-system-macros) (for-each (lambda (x) (cond ((macro-identifier x) (values)) ((assq x (export-subst)) (error who "ambiguous export" x)) ((assq x subst) => ;;; primitive defined (exported) within the compiled libraries (lambda (p) (let ((label (cdr p))) (cond ((assq label env) => (lambda (p) (let ((binding (cdr p))) (case (car binding) ((global) (export-subst (cons x label)) (export-env (cons label (cons 'core-prim x))) (export-primlocs (cons x (cdr binding)))) (else (error #f "invalid binding for identifier" p x)))))) (else (error #f "cannot find binding" x label)))))) (else ;;; core primitive with no backing definition, assumed to ;;; be defined in other strata of the system (let ((label (gensym))) (export-subst (cons x label)) (export-env (cons label (cons 'core-prim x))))))) (map car identifier->library-map)) (values (export-subst) (export-env) (export-primlocs)))) (define identifier->library-map-hashtable (let ((ht (make-eq-hashtable))) (for-each (lambda (x) (hashtable-set! ht (car x) x)) identifier->library-map) ht)) (define (get-export-subset key subst) (let f ((ls subst)) (cond ((null? ls) '()) (else (let ((x (car ls))) (let ((name (car x))) (cond ((hashtable-ref identifier->library-map-hashtable name #f) => (lambda (q) (cond ((memq key (cdr q)) (cons x (f (cdr ls)))) (else (f (cdr ls)))))) (else ;;; not going to any library? (f (cdr ls)))))))))) (define (build-system-library export-subst export-env primlocs) (define (build-library legend-entry) (let ((key (car legend-entry)) (name (cadr legend-entry)) (visible? (caddr legend-entry))) (let ((id (gensym)) (name name) (version (if (eq? (car name) 'rnrs) '(6) '())) (import-libs '()) (visit-libs '()) (invoke-libs '())) (let-values (((subst env) (if (equal? name '(psyntax system $all)) (values export-subst export-env) (values (get-export-subset key export-subst) '())))) `(install-library ',id ',name ',version ',import-libs ',visit-libs ',invoke-libs ',subst ',env values values '#f '#f '#f '() ',visible? '#f))))) (let ((code `(library (psyntax primlocs) (export) ;;; must be empty (import (only (psyntax library-manager) install-library) (only (psyntax internal) current-primitive-locations) (only (ironscheme clr) clr-static-call) (rnrs hashtables) (rnrs base)) (current-primitive-locations (let ((ht (clr-static-call IronScheme.Runtime.Builtins MakePrimlocHashtable ',primlocs))) (lambda (x) (hashtable-ref ht x #f)))) ,@(map build-library library-legend)))) (let-values (((name code empty-subst empty-env) (boot-library-expand code))) code))) (define (make-init-code) (values '() '() '())) (define (expand-all files) ;;; remove all re-exported identifiers (those with labels in ;;; subst but not binding in env). (define (prune-subst subst env) (cond ((null? subst) '()) ((not (assq (cdar subst) env)) (prune-subst (cdr subst) env)) (else (cons (car subst) (prune-subst (cdr subst) env))))) (define (load file proc) (call-with-input-file file (lambda (p) (let f () (let ((x (read-annotated p))) (unless (eof-object? x) (proc x) (f))))))) (let-values (((code* subst env) (make-init-code))) (for-each (lambda (file) (display "expanding ") (display file) (newline) (load file (lambda (x) (let-values (((name code export-subst export-env) (boot-library-expand x))) (set! code* (cons code code*)) (set! subst (append export-subst subst)) (set! env (append export-env env)))))) files) (let-values (((export-subst export-env export-locs) (make-system-data (prune-subst subst env) env))) (let ((code (build-system-library export-subst export-env export-locs))) (values (reverse (cons* (car code*) code (cdr code*))) export-locs))))) (define bootstrap-collection (let ((ls '())) (case-lambda (() ls) ((x) (unless (memq x ls) (set! ls (cons x ls))))))) (verify-map) (library-path '("." "lib/")) (let ((all-names (map car identifier->library-map)) (all-labels (map (lambda (x) (gensym)) identifier->library-map)) (all-bindings (map (lambda (x) (cond ((macro-identifier x) => cadr) (else `(core-prim . ,x)))) (map car identifier->library-map)))) (let ((export-subst (map cons all-names all-labels)) (export-env (map cons all-labels all-bindings))) (define (build-library legend-entry) (let ((key (car legend-entry)) (name (cadr legend-entry)) (visible? (caddr legend-entry)) (required? (cadddr legend-entry))) (when required? (let ((id (gensym)) (name name) (version (if (eq? (car name) 'rnrs) '(6) '())) (import-libs '()) (visit-libs '()) (invoke-libs '())) (let-values (((subst env) (if (equal? name '(psyntax system $all)) (values export-subst export-env) (values (get-export-subset key export-subst) '())))) (parameterize ((current-library-collection bootstrap-collection)) (install-library id name version import-libs visit-libs invoke-libs subst env values values #f #f #f '() visible? #f))))))) (for-each build-library library-legend))) (let () (define-syntax define-prims (syntax-rules () ((_ name* ...) (let ((g* (map gensym '(name* ...))) (v* (list name* ...))) (for-each set-symbol-value! g* v*) (let ((ht (make-eq-hashtable))) (for-each (lambda (k v) (hashtable-set! ht k v)) '(name* ...) g*) (current-primitive-locations (lambda (x) (let ((op (hashtable-ref ht x #f))) (unless op (error #f "undefined prim" x)) op)))))))) (define-prims clr-call-internal clr-cast-internal zero? string-length vector-ref syntax-violation vector-length cons* cadr cddr filter syntax-dispatch apply cons append map list syntax-error reverse format not make-compile-time-value assertion-violation null? car cdr pair? bound-identifier=? list->vector generate-temporaries = + datum->syntax string->symbol void string-append symbol->string syntax->datum gensym length open-string-output-port identifier? free-identifier=? exists values call-with-values for-all ellipsis-map vector eq? eqv?)) (let-values (((core* locs) (time-it "macro expansion" (lambda () (parameterize ((current-library-collection bootstrap-collection)) (expand-all scheme-library-files)))))) (current-primitive-locations (lambda (x) (cond ((assq x locs) => cdr) (else #f)))) (time-it "code generation" (lambda () (compile-bootfile (map compile-core-expr core*)))))
null
https://raw.githubusercontent.com/IronScheme/IronScheme/4836f7eb5f8fe6ff18aa0ec2e9c314e63bc0b42b/IronScheme/IronScheme.Console/ironscheme-buildscript.sps
scheme
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. needs make-parameter depends on records - hashtables - bitwise new for (record-type-descriptor &condition-type) and (record-constructor-descriptor &condition-type) to expand properly, the implementation must export the identifiers &condition-type-rtd, which must be bound to the run-time value of the rtd, and &condition-type-rcd which must be bound to the corresponding record-constructor-descriptor. abbr. name visible? required? required? flag means that said library is required for building the system. The only non-r6rs required libraries should be (psyntax system $bootstrap) and (psyntax system $all). (psyntax system $bootstrap) should export, at a minimum, the eval-core, and pretty-print. (psyntax system $all) is fabricated by the system to include every identifier in the system. (expand-boot-cps i) only goes to $all only goes to $all these should be assigned when creating the record types primitive defined (exported) within the compiled libraries core primitive with no backing definition, assumed to be defined in other strata of the system not going to any library? must be empty remove all re-exported identifiers (those with labels in subst but not binding in env).
Copyright ( c ) 2006 , 2007 and Copyright ( c ) 2007 - 2016 Llewellyn Pritchard to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (import (rnrs base) (rnrs control) (rnrs io simple) (rnrs io ports) (rnrs lists) (rnrs files) (rnrs hashtables) (psyntax internal) (psyntax compat) (psyntax library-manager) (psyntax expander) (ironscheme unsafe) (ironscheme clr internal) (only (ironscheme core) compile-bootfile format) (only (ironscheme) time-it include import library)) (define scheme-library-files '( "build/predicates.sls" "build/records/procedural.sls" "build/conditions.sls" "build/exceptions.sls" "build/arithmetic/fixnums.sls" "build/primitive-numbers.sls" "build/hashtables.sls" "build/lists.sls" "build/base.sls" "build/numbers.sls" "build/bytevectors.sls" "psyntax/compat.sls" "build/io/ports.sls" "build/io/simple.sls" "build/vectors.sls" "build/generic-writer.sls" "build/files.sls" "build/mutable-pairs.sls" "build/programs.sls" "build/r5rs.sls" "build/sorting.sls" "build/unicode.sls" "build/arithmetic/bitwise.sls" "build/arithmetic/flonums.sls" "build/records/inspection.sls" "build/enums.sls" "build/format.sls" "build/trace.sls" "build/equal.sls" "build/pretty-print.sls" "build/misc.sls" "build/constant-fold.sls" "psyntax/internal.sls" "psyntax/library-manager.sls" "psyntax/builders.sls" "psyntax/expander.sls" "psyntax/main.sls" )) (define psyntax-system-macros '((define (define)) (define-syntax (define-syntax)) (define-fluid-syntax (define-fluid-syntax)) (module (module)) (begin (begin)) (library (library)) (import (import)) (export (export)) (set! (set!)) (let-syntax (let-syntax)) (letrec-syntax (letrec-syntax)) (stale-when (stale-when)) (foreign-call (core-macro . foreign-call)) (quote (core-macro . quote)) (syntax-case (core-macro . syntax-case)) (syntax (core-macro . syntax)) (lambda (core-macro . lambda)) (typed-lambda (core-macro . typed-lambda)) (case-lambda (core-macro . case-lambda)) (typed-case-lambda (core-macro . typed-case-lambda)) (type-descriptor (core-macro . type-descriptor)) (letrec (core-macro . letrec)) (letrec* (core-macro . letrec*)) (if (core-macro . if)) (when (macro . when)) (unless (macro . unless)) (parameterize (macro . parameterize)) (case (macro . case)) (fluid-let-syntax (core-macro . fluid-let-syntax)) (record-type-descriptor (core-macro . record-type-descriptor)) (record-constructor-descriptor (core-macro . record-constructor-descriptor)) (let*-values (macro . let*-values)) (let-values (macro . let-values)) (define-struct (macro . define-struct)) (include (macro . include)) (include-into (macro . include-into)) (syntax-rules (macro . syntax-rules)) (quasiquote (macro . quasiquote)) (quasisyntax (macro . quasisyntax)) (with-syntax (macro . with-syntax)) (identifier-syntax (macro . identifier-syntax)) (let (macro . let)) (let* (macro . let*)) (cond (macro . cond)) (do (macro . do)) (and (macro . and)) (or (macro . or)) (time (macro . time)) (delay (macro . delay)) (endianness (macro . endianness)) (assert (macro . assert)) (... (macro . ...)) (=> (macro . =>)) (else (macro . else)) (_ (macro . _)) (unquote (macro . unquote)) (unquote-splicing (macro . unquote-splicing)) (unsyntax (macro . unsyntax)) (unsyntax-splicing (macro . unsyntax-splicing)) (trace-lambda (macro . trace-lambda)) (trace-let (macro . trace-let)) (trace-define (macro . trace-define)) (trace-define-syntax (macro . trace-define-syntax)) (trace-let-syntax (macro . trace-let-syntax)) (trace-letrec-syntax (macro . trace-letrec-syntax)) (guard (macro . guard)) (eol-style (macro . eol-style)) (buffer-mode (macro . buffer-mode)) (file-options (macro . file-options)) (error-handling-mode (macro . error-handling-mode)) (fields (macro . fields)) (mutable (macro . mutable)) (immutable (macro . immutable)) (parent (macro . parent)) (protocol (macro . protocol)) (sealed (macro . sealed)) (opaque (macro . opaque )) (nongenerative (macro . nongenerative)) (parent-rtd (macro . parent-rtd)) (define-record-type (macro . define-record-type)) (define-enumeration (macro . define-enumeration)) (define-condition-type (macro . define-condition-type)) (&condition ($core-rtd . (&condition-rtd &condition-rcd))) (&message ($core-rtd . (&message-rtd &message-rcd))) (&warning ($core-rtd . (&warning-rtd &warning-rcd ))) (&serious ($core-rtd . (&serious-rtd &serious-rcd))) (&error ($core-rtd . (&error-rtd &error-rcd))) (&violation ($core-rtd . (&violation-rtd &violation-rcd))) (&assertion ($core-rtd . (&assertion-rtd &assertion-rcd))) (&irritants ($core-rtd . (&irritants-rtd &irritants-rcd))) (&who ($core-rtd . (&who-rtd &who-rcd))) (&implementation-restriction ($core-rtd . (&implementation-restriction-rtd &implementation-restriction-rcd))) (&lexical ($core-rtd . (&lexical-rtd &lexical-rcd))) (&syntax ($core-rtd . (&syntax-rtd &syntax-rcd))) (&undefined ($core-rtd . (&undefined-rtd &undefined-rcd))) (&non-continuable ($core-rtd . (&non-continuable-rtd &non-continuable-rcd))) (&i/o ($core-rtd . (&i/o-rtd &i/o-rcd))) (&i/o-read ($core-rtd . (&i/o-read-rtd &i/o-read-rcd))) (&i/o-write ($core-rtd . (&i/o-write-rtd &i/o-write-rcd))) (&i/o-invalid-position ($core-rtd . (&i/o-invalid-position-rtd &i/o-invalid-position-rcd))) (&i/o-filename ($core-rtd . (&i/o-filename-rtd &i/o-filename-rcd))) (&i/o-file-protection ($core-rtd . (&i/o-file-protection-rtd &i/o-file-protection-rcd))) (&i/o-file-is-read-only ($core-rtd . (&i/o-file-is-read-only-rtd &i/o-fie-is-read-only-rcd))) (&i/o-file-already-exists ($core-rtd . (&i/o-file-already-exists-rtd &i/o-file-already-exists-rcd))) (&i/o-file-does-not-exist ($core-rtd . (&i/o-file-does-not-exist-rtd &i/o-file-does-not-exist-rcd))) (&i/o-port ($core-rtd . (&i/o-port-rtd &i/o-port-rcd))) (&i/o-decoding ($core-rtd . (&i/o-decoding-rtd &i/o-decoding-rcd))) (&i/o-encoding ($core-rtd . (&i/o-encoding-rtd &i/o-encoding-rcd))) (&no-infinities ($core-rtd . (&no-infinities-rtd &no-infinities-rcd))) (&no-nans ($core-rtd . (&no-nans-rtd &no-nans-rcd))) (&where ($core-rtd . (&where-rtd &where-rcd))) (&stacktrace ($core-rtd . (&stacktrace-rtd &stacktrace-rcd))) )) (define (macro-identifier x) (assq x psyntax-system-macros)) (define library-legend '((i (ironscheme) #t #t) (il (ironscheme library) #f #t) (ir (ironscheme reader) #f #t) (iser (ironscheme serialization) #f #t) (ic (ironscheme core) #f #t) (iu (ironscheme unsafe) #t #t) (irp (ironscheme records printer) #t #t) (is-clr-int (ironscheme clr internal) #t #t) (ne (psyntax null-environment-5) #f #f) (se (psyntax scheme-report-environment-5) #f #f) (r (rnrs) #t #t) (r5 (rnrs r5rs) #t #t) (ct (rnrs control) #t #t) (ev (rnrs eval) #t #t) (mp (rnrs mutable-pairs) #t #t) (ms (rnrs mutable-strings) #t #t) (pr (rnrs programs) #t #t) (sc (rnrs syntax-case) #t #t) (fi (rnrs files) #t #t) (sr (rnrs sorting) #t #t) (ba (rnrs base) #t #t) (ls (rnrs lists) #t #t) (is (rnrs io simple) #t #t) (bv (rnrs bytevectors) #t #t) (uc (rnrs unicode) #t #t) (ex (rnrs exceptions) #t #t) (bw (rnrs arithmetic bitwise) #t #t) (fx (rnrs arithmetic fixnums) #t #t) (fl (rnrs arithmetic flonums) #t #t) (ht (rnrs hashtables) #t #t) (ip (rnrs io ports) #t #t) (en (rnrs enums) #t #t) (co (rnrs conditions) #t #t) (ri (rnrs records inspection) #t #t) (rp (rnrs records procedural) #t #t) (rs (rnrs records syntactic) #t #t) ($all (psyntax system $all) #f #t) ($boot (psyntax system $bootstrap) #f #t) )) following procedures : , symbol - value , set - symbol - value ! , (define identifier->library-map '( (load/unsafe i) (optimize ic) (compress-constants? ic) (clr-string? ic) (stringbuilder? ic) (bignum? ic) (rectnum? ic) (ratnum? ic) (complexnum? ic) (fx+internal ic) (fx-internal ic) (fx*internal ic) (fxarithmetic-shift-left-internal ic) (fxadd1 i) (fxsub1 i) (add1 i) (sub1 i) (displayln i) (writeln i) (flvector? i) (fxvector? i) (flvector-ref i) (fxvector-ref i) (flvector-set! i) (fxvector-set! i) (make-flvector i) (make-fxvector i) (flvector-length i) (fxvector-length i) (flvector->list i) (fxvector->list i) (list->flvector i) (list->fxvector i) (flvector-fill! i) (fxvector-fill! i) (valuetype-vector? i) (with-timeout i) (file-mtime i) (allow-library-redefinition i) (with-clr-exception-handler i) (typed-lambda i) (typed-case-lambda i) (pointer+ i) (expanded->core i) (import i) (export i) (library i) (include i) (stale-when i) (strict-mode? i) (debug-mode? i) (lw-debug-mode? i) (lw-debugger i) (lw-debugger-call-stack i) (lw-debugger-location-trace i) (lw-debugger-stackframe-variables i) (decompose-flonum i) (open-output-string i) (get-output-string i) (pretty-print i) (generic-write i) (initialize-default-printers i) (pretty-width i) (pretty-gensyms i) (uninstall-library i) (installed-libraries i) (make-where-condition i) (where-condition? i) (&where i) (condition-where i) (make-stacktrace-condition i) (display-stacktrace i) (stacktrace-condition? i) (condition-stacktrace i) (&stacktrace i) (generic+ ic) (generic- ic) (generic* ic) (generic/ ic) (generic-div ic) (bignum-sqrt ic) (bignum-sqrt-exact ic) (inexact=? ic) (convert->cps i) (syntax-transpose i) (emacs-mode? i) (top-level-expander i) (core-library-expander i) (parse-top-level-program i) (parse-library i) (core-expand i) (expand->core i) (include-into i) (make-compile-time-value i) (library-path i ic) (interaction-environment-symbols i) (interaction-environment? i) (environment-symbols i) (environment-bindings i) (hashtable-map i) (hashtable-for-each i) (open-tcp-input/output-port i) (get-library-paths il ic) (file-locator il) (alternative-file-locator il) (make-parameter i) (parameterize i) (time i) (time-it i) (assertion-error ic) (trace-lambda i) (trace-let i) (trace-define i) (trace-define-syntax i) (trace-let-syntax i) (trace-letrec-syntax i) (make-traced-macro ic) (make-traced-procedure ic) (trace-printer i) (string-format i) (string-compare i) (string-ci-compare i) (vector-binary-search i) (vector-copy i) (vector-index-of i) (vector-contains? i) (vector-reverse! i) (vector-filter i) (vector-append i) (vector-fold-left i) (bytevector-fold-left i) (get-command-line ic) (get-clr-type i) (clr-type? i) (typeof i) (gc-collect i) (procedure-arity i) (procedure-name i) (procedure-environment i) (procedure-form i) (format i ic) (fprintf i) (shorthand-syntax-output i) (printf i) (load-port i) (load/args i) (load/unload i) (make-promise ic) (promise? i) (enum-set? i) (record-constructor-descriptor? i) (serialize-port i) (deserialize-port i) (reverse! ic) (eqv-hash ic) (add-record-printer! irp) ($break iu) ($throw iu) ($try/finally iu) ($and? iu) ($or? iu) ($car iu) ($cdr iu) ($vector-ref iu) ($vector-set! iu) ($fx=? iu) ($fx+ iu) ($fx* iu) ($fxdiv iu) ($fxmod iu) ($fx- iu) ($fx<? iu) ($fx<=? iu) ($fx>? iu) ($fx>=? iu) ($fxand iu) ($fxior iu) ($fxxor iu) ($fxnot iu) ($fxarithmetic-shift-left iu) ($fxarithmetic-shift-right iu) ($fxzero? iu) ($fxnegative? iu) ($fxpositive? iu) ($fxeven? iu) ($fxodd? iu) ($try iu) ($try/overflow iu) ($try/io iu) ($fl=? iu) ($fl+ iu) ($fl* iu) ($fl/ iu) ($fl- iu) ($fl<? iu) ($fl<=? iu) ($fl>? iu) ($fl>=? iu) ($bytevector-ref iu) ($bytevector-set! iu) (lambda i r ba se ne) (and i r ba se ne) (begin i r ba se ne) (case i r ba se ne) (cond i r ba se ne) (define i r ba se ne) (define-syntax i r ba se ne) (identifier-syntax i r ba) (if i r ba se ne) (let i r ba se ne) (let* i r ba se ne) (let*-values i r ba) (let-syntax i r ba se ne) (let-values i r ba) (letrec i r ba se ne) (letrec* i r ba) (letrec-syntax i r ba se ne) (define-fluid-syntax i) (fluid-let-syntax i) (or i r ba se ne) (quasiquote i r ba se ne) (quote i r ba se ne) (set! i r ba se ne) (syntax-rules i r ba se ne) (unquote i r ba se ne) (unquote-splicing i r ba se ne) (< i r ba se) (<= i r ba se) (= i r ba se) (> i r ba se) (>= i r ba se) (+ i r ba se) (- i r ba se) (* i r ba se) (/ i r ba se) (abs i r ba se) (acos i r ba se) (angle i r ba se) (append i r ba se) (apply i r ba se) (asin i r ba se) (assert i r ba) (assertion-violation i r ba) (atan i r ba se) (boolean=? i r ba) (boolean? i r ba se) (car i r ba se) (cdr i r ba se) (caar i r ba se) (cadr i r ba se) (cdar i r ba se) (cddr i r ba se) (caaar i r ba se) (caadr i r ba se) (cadar i r ba se) (caddr i r ba se) (cdaar i r ba se) (cdadr i r ba se) (cddar i r ba se) (cdddr i r ba se) (caaaar i r ba se) (caaadr i r ba se) (caadar i r ba se) (caaddr i r ba se) (cadaar i r ba se) (cadadr i r ba se) (caddar i r ba se) (cadddr i r ba se) (cdaaar i r ba se) (cdaadr i r ba se) (cdadar i r ba se) (cdaddr i r ba se) (cddaar i r ba se) (cddadr i r ba se) (cdddar i r ba se) (cddddr i r ba se) (call-with-current-continuation i r ba se) (call/cc i r ba) (call-with-values i r ba se) (ceiling i r ba se) (char->integer i r ba se) (char<=? i r ba se) (char<? i r ba se) (char=? i r ba se) (char>=? i r ba se) (char>? i r ba se) (char? i r ba se) (complex? i r ba se) (cons i r ba se) (cos i r ba se) (denominator i r ba se) (div i r ba) (mod i r ba) (div-and-mod i r ba) (div0 i r ba) (mod0 i r ba) (div0-and-mod0 i r ba) (dynamic-wind i r ba se) (eq? i r ba se) (equal? i r ba se) (eqv? i r ba se) (error i r ba) (even? i r ba se) (exact i r ba) (exact-integer-sqrt i r ba) (exact? i r ba se) (exp i r ba se) (expt i r ba se) (finite? i r ba) (floor i r ba se) (for-each i r ba se) (gcd i r ba se) (imag-part i r ba se) (inexact i r ba) (inexact? i r ba se) (infinite? i r ba) (integer->char i r ba se) (integer-valued? i r ba) (integer? i r ba se) (lcm i r ba se) (length i r ba se) (list i r ba se) (list->string i r ba se) (list->vector i r ba se) (list-ref i r ba se) (list-tail i r ba se) (list? i r ba se) (log i r ba se) (magnitude i r ba se) (make-polar i r ba se) (make-rectangular i r ba se) (make-string i r ba se) (make-vector i r ba se) (map i r ba se) (max i r ba se) (min i r ba se) (nan? i r ba) (negative? i r ba se) (not i r ba se) (null? i r ba se) (number->string i r ba se) (number? i r ba se) (numerator i r ba se) (odd? i r ba se) (pair? i r ba se) (positive? i r ba se) (procedure? i r ba se) (rational-valued? i r ba) (rational? i r ba se) (rationalize i r ba se) (real-part i r ba se) (real-valued? i r ba) (real? i r ba se) (reverse i r ba se) (round i r ba se) (sin i r ba se) (sqrt i r ba se) (string i r ba se) (string->list i r ba se) (string->number i r ba se) (string->symbol i r ba se) (string-append i r ba se) (string-copy i r ba se) (string-for-each i r ba) (string-length i r ba se) (string-ref i r ba se) (string<=? i r ba se) (string<? i r ba se) (string=? i r ba se) (string>=? i r ba se) (string>? i r ba se) (string? i r ba se) (substring i r ba se) (symbol->string i r ba se) (symbol=? i r ba) (symbol? i r ba se) (tan i r ba se) (truncate i r ba se) (values i r ba se) (vector i r ba se) (vector->list i r ba se) (vector-fill! i r ba se) (vector-for-each i r ba) (vector-length i r ba se) (vector-map i r ba) (vector-ref i r ba se) (vector-set! i r ba se) (vector? i r ba se) (zero? i r ba se) (... i r ba sc se) (=> i r ba ex se ne) (_ i r ba sc) (else i r ba ex se ne) (bitwise-arithmetic-shift i r bw) (bitwise-arithmetic-shift-left i r bw) (bitwise-arithmetic-shift-right i r bw) (bitwise-not i r bw) (bitwise-and i r bw) (bitwise-ior i r bw) (bitwise-xor i r bw) (bitwise-bit-count i r bw) (bitwise-bit-field i r bw) (bitwise-bit-set? i r bw) (bitwise-copy-bit i r bw) (bitwise-copy-bit-field i r bw) (bitwise-first-bit-set i r bw) (bitwise-if i r bw) (bitwise-length i r bw) (bitwise-reverse-bit-field i r bw) (bitwise-rotate-bit-field i r bw) (fixnum? i r fx) (fixnum-width i r fx) (least-fixnum i r fx) (greatest-fixnum i r fx) (fx* i r fx) (fx*/carry i r fx) (fx+ i r fx) (fx+/carry i r fx) (fx- i r fx) (fx-/carry i r fx) (fx<=? i r fx) (fx<? i r fx) (fx=? i r fx) (fx>=? i r fx) (fx>? i r fx) (fxand i r fx) (fxarithmetic-shift i r fx) (fxarithmetic-shift-left i r fx) (fxarithmetic-shift-right i r fx) (fxbit-count i r fx) (fxbit-field i r fx) (fxbit-set? i r fx) (fxcopy-bit i r fx) (fxcopy-bit-field i r fx) (fxdiv i r fx) (fxdiv-and-mod i r fx) (fxdiv0 i r fx) (fxdiv0-and-mod0 i r fx) (fxeven? i r fx) (fxfirst-bit-set i r fx) (fxif i r fx) (fxior i r fx) (fxlength i r fx) (fxmax i r fx) (fxmin i r fx) (fxmod i r fx) (fxmod0 i r fx) (fxnegative? i r fx) (fxnot i r fx) (fxodd? i r fx) (fxpositive? i r fx) (fxreverse-bit-field i r fx) (fxrotate-bit-field i r fx) (fxxor i r fx) (fxzero? i r fx) (fixnum->flonum i r fl) (fl* i r fl) (fl+ i r fl) (fl- i r fl) (fl/ i r fl) (fl<=? i r fl) (fl<? i r fl) (fl=? i r fl) (fl>=? i r fl) (fl>? i r fl) (flabs i r fl) (flacos i r fl) (flasin i r fl) (flatan i r fl) (flceiling i r fl) (flcos i r fl) (fldenominator i r fl) (fldiv i r fl) (fldiv-and-mod i r fl) (fldiv0 i r fl) (fldiv0-and-mod0 i r fl) (fleven? i r fl) (flexp i r fl) (flexpt i r fl) (flfinite? i r fl) (flfloor i r fl) (flinfinite? i r fl) (flinteger? i r fl) (fllog i r fl) (flmax i r fl) (flmin i r fl) (flmod i r fl) (flmod0 i r fl) (flnan? i r fl) (flnegative? i r fl) (flnumerator i r fl) (flodd? i r fl) (flonum? i r fl) (flpositive? i r fl) (flround i r fl) (flsin i r fl) (flsqrt i r fl) (fltan i r fl) (fltruncate i r fl) (flzero? i r fl) (real->flonum i r fl) (make-no-infinities-violation i r fl) (make-no-nans-violation i r fl) (&no-infinities i r fl) (no-infinities-violation? i r fl) (&no-nans i r fl) (no-nans-violation? i r fl) (bytevector->sint-list i r bv) (bytevector->u8-list i r bv) (bytevector->uint-list i r bv) (bytevector-copy i r bv) (bytevector-copy! i r bv) (bytevector-fill! i r bv) (bytevector-ieee-double-native-ref i r bv) (bytevector-ieee-double-native-set! i r bv) (bytevector-ieee-double-ref i r bv) (bytevector-ieee-double-set! i r bv) (bytevector-ieee-single-native-ref i r bv) (bytevector-ieee-single-native-set! i r bv) (bytevector-ieee-single-ref i r bv) (bytevector-ieee-single-set! i r bv) (bytevector-length i r bv) (bytevector-s16-native-ref i r bv) (bytevector-s16-native-set! i r bv) (bytevector-s16-ref i r bv) (bytevector-s16-set! i r bv) (bytevector-s32-native-ref i r bv) (bytevector-s32-native-set! i r bv) (bytevector-s32-ref i r bv) (bytevector-s32-set! i r bv) (bytevector-s64-native-ref i r bv) (bytevector-s64-native-set! i r bv) (bytevector-s64-ref i r bv) (bytevector-s64-set! i r bv) (bytevector-s8-ref i r bv) (bytevector-s8-set! i r bv) (bytevector-sint-ref i r bv) (bytevector-sint-set! i r bv) (bytevector-u16-native-ref i r bv) (bytevector-u16-native-set! i r bv) (bytevector-u16-ref i r bv) (bytevector-u16-set! i r bv) (bytevector-u32-native-ref i r bv) (bytevector-u32-native-set! i r bv) (bytevector-u32-ref i r bv) (bytevector-u32-set! i r bv) (bytevector-u64-native-ref i r bv) (bytevector-u64-native-set! i r bv) (bytevector-u64-ref i r bv) (bytevector-u64-set! i r bv) (bytevector-u8-ref i r bv) (bytevector-u8-set! i r bv) (bytevector-uint-ref i r bv) (bytevector-uint-set! i r bv) (bytevector=? i r bv) (bytevector? i r bv) (endianness i r bv) (native-endianness i r bv) (sint-list->bytevector i r bv) (string->utf16 i r bv) (string->utf32 i r bv) (string->utf8 i r bv) (u8-list->bytevector i r bv) (uint-list->bytevector i r bv) (utf8->string i r bv) (utf16->string i r bv) (utf32->string i r bv) (condition? i r co) (&assertion i r co) (assertion-violation? i r co) (&condition i r co) (condition i r co) (condition-accessor i r co) (condition-irritants i r co) (condition-message i r co) (condition-predicate i r co) (condition-who i r co) (define-condition-type i r co) (&error i r co) (error? i r co) (&implementation-restriction i r co) (implementation-restriction-violation? i r co) (&irritants i r co) (irritants-condition? i r co) (&lexical i r co) (lexical-violation? i r co) (make-assertion-violation i r co) (make-error i r co) (make-implementation-restriction-violation i r co) (make-irritants-condition i r co) (make-lexical-violation i r co) (make-message-condition i r co) (make-non-continuable-violation i r co) (make-serious-condition i r co) (make-syntax-violation i r co) (make-undefined-violation i r co) (make-violation i r co) (make-warning i r co) (make-who-condition i r co) (&message i r co) (message-condition? i r co) (&non-continuable i r co) (non-continuable-violation? i r co) (&serious i r co) (serious-condition? i r co) (simple-conditions i r co) (&syntax i r co) (syntax-violation i r sc) (syntax-violation-form i r co) (syntax-violation-subform i r co) (syntax-violation? i r co) (&undefined i r co) (undefined-violation? i r co) (&violation i r co) (violation? i r co) (&warning i r co) (warning? i r co) (&who i r co) (who-condition? i r co) (case-lambda i r ct) (do i r ct se ne) (unless i r ct) (when i r ct) (define-enumeration i r en) (enum-set->list i r en) (enum-set-complement i r en) (enum-set-constructor i r en) (enum-set-difference i r en) (enum-set-indexer i r en) (enum-set-intersection i r en) (enum-set-member? i r en) (enum-set-projection i r en) (enum-set-subset? i r en) (enum-set-union i r en) (enum-set-universe i r en) (enum-set=? i r en) (make-enumeration i r en) (environment i ev) (eval i ev se) (raise i r ex) (raise-continuable i r ex) (with-exception-handler i r ex) (guard i r ex) (assoc i r ls se) (assp i r ls) (assq i r ls se) (assv i r ls se) (cons* i r ls) (filter i r ls) (find i r ls) (fold-left i r ls) (fold-right i r ls) (for-all i r ls) (exists i r ls) (member i r ls se) (memp i r ls) (memq i r ls se) (memv i r ls se) (partition i r ls) (remq i r ls) (remp i r ls) (remv i r ls) (remove i r ls) (set-car! i mp se) (set-cdr! i mp se) (string-set! i ms se) (string-fill! i ms se) (command-line i r pr) (exit i r pr) (delay i r5 se ne) (exact->inexact i r5 se) (force i r5 se) (inexact->exact i r5 se) (modulo i r5 se) (remainder i r5 se) (null-environment i r5 se) (quotient i r5 se) (scheme-report-environment i r5 se) (binary-port? i r ip) (buffer-mode i r ip) (buffer-mode? i r ip) (bytevector->string i r ip) (call-with-bytevector-output-port i r ip) (call-with-port i r ip) (call-with-string-output-port i r ip) (close-port i r ip) (eol-style i r ip) (error-handling-mode i r ip) (file-options i r ip) (flush-output-port i r ip) (get-bytevector-all i r ip) (get-bytevector-n i r ip) (get-bytevector-n! i r ip) (get-bytevector-some i r ip) (get-char i r ip) (get-datum i r ip) (get-line i r ip) (get-string-all i r ip) (get-string-n i r ip) (get-string-n! i r ip) (get-u8 i r ip) (&i/o i r ip is fi) (&i/o-decoding i r ip) (i/o-decoding-error? i r ip) (&i/o-encoding i r ip) (i/o-encoding-error-char i r ip) (i/o-encoding-error? i r ip) (i/o-error-filename i r ip is fi) (i/o-error-port i r ip is fi) (i/o-error? i r ip is fi) (&i/o-file-already-exists i r ip is fi) (i/o-file-already-exists-error? i r ip is fi) (&i/o-file-does-not-exist i r ip is fi) (i/o-file-does-not-exist-error? i r ip is fi) (&i/o-file-is-read-only i r ip is fi) (i/o-file-is-read-only-error? i r ip is fi) (&i/o-file-protection i r ip is fi) (i/o-file-protection-error? i r ip is fi) (&i/o-filename i r ip is fi) (i/o-filename-error? i r ip is fi) (&i/o-invalid-position i r ip is fi) (i/o-error-position i r ip is fi) (i/o-invalid-position-error? i r ip is fi) (&i/o-port i r ip is fi) (i/o-port-error? i r ip is fi) (&i/o-read i r ip is fi) (i/o-read-error? i r ip is fi) (&i/o-write i r ip is fi) (i/o-write-error? i r ip is fi) (lookahead-char i r ip) (lookahead-u8 i r ip) (make-bytevector i r bv) (make-custom-binary-input-port i r ip) (make-custom-binary-input/output-port i r ip) (make-custom-binary-output-port i r ip) (make-custom-textual-input-port i r ip) (make-custom-textual-input/output-port i r ip) (make-custom-textual-output-port i r ip) (make-i/o-decoding-error i r ip) (make-i/o-encoding-error i r ip) (make-i/o-error i r ip is fi) (make-i/o-file-already-exists-error i r ip is fi) (make-i/o-file-does-not-exist-error i r ip is fi) (make-i/o-file-is-read-only-error i r ip is fi) (make-i/o-file-protection-error i r ip is fi) (make-i/o-filename-error i r ip is fi) (make-i/o-invalid-position-error i r ip is fi) (make-i/o-port-error i r ip is fi) (make-i/o-read-error i r ip is fi) (make-i/o-write-error i r ip is fi) (latin-1-codec i r ip) (make-transcoder i r ip) (native-eol-style i r ip) (native-transcoder i r ip) (open-bytevector-input-port i r ip) (open-bytevector-output-port i r ip) (open-file-input-port i r ip) (open-file-input/output-port i r ip) (open-file-output-port i r ip) (open-string-input-port i r ip) (open-string-output-port i r ip) (output-port-buffer-mode i r ip) (port-eof? i r ip) (port-has-port-position? i r ip) (port-has-set-port-position!? i r ip) (port-position i r ip) (port-transcoder i r ip) (port? i r ip) (put-bytevector i r ip) (put-char i r ip) (put-datum i r ip) (put-string i r ip) (put-u8 i r ip) (set-port-position! i r ip) (standard-error-port i r ip) (standard-input-port i r ip) (standard-output-port i r ip) (string->bytevector i r ip) (textual-port? i r ip) (transcoded-port i r ip) (transcoder-codec i r ip) (transcoder-eol-style i r ip) (transcoder-error-handling-mode i r ip) (utf-16-codec i r ip) (utf-8-codec i r ip) (input-port? i r is ip se) (output-port? i r is ip se) (current-input-port i r ip is se) (current-output-port i r ip is se) (current-error-port i r ip is se) (eof-object i r ip is) (eof-object? i r ip is se) (close-input-port i r is se) (close-output-port i r is se) (display i r is se) (newline i r is se) (open-input-file i r is se) (open-output-file i r is se) (peek-char i r is se) (read i r is se) (read-char i r is se) (with-input-from-file i r is se) (with-output-to-file i r is se) (write i r is se) (write-char i r is se) (call-with-input-file i r is se) (call-with-output-file i r is se) (textual-input-port? i) (textual-output-port? i) (hashtable-clear! i r ht) (hashtable-contains? i r ht) (hashtable-copy i r ht) (hashtable-delete! i r ht) (hashtable-entries i r ht) (hashtable-keys i r ht) (hashtable-mutable? i r ht) (hashtable-ref i r ht) (hashtable-set! i r ht) (hashtable-size i r ht) (hashtable-update! i r ht) (hashtable? i r ht) (make-eq-hashtable i r ht) (make-eqv-hashtable i r ht) (hashtable-hash-function i r ht) (make-hashtable i r ht) (hashtable-equivalence-function i r ht) (equal-hash i r ht) (string-hash i r ht) (string-ci-hash i r ht) (symbol-hash i r ht) (list-sort i r sr) (vector-sort i r sr) (vector-sort! i r sr) (file-exists? i r fi) (delete-file i r fi) (define-record-type i r rs) (fields i r rs) (immutable i r rs) (mutable i r rs) (opaque i r rs) (parent i r rs) (parent-rtd i r rs) (protocol i r rs) (record-constructor-descriptor i r rs) (record-type-descriptor i r rs) (sealed i r rs) (nongenerative i r rs) (record-field-mutable? i r ri) (record-rtd i r ri) (record-type-field-names i r ri) (record-type-generative? i r ri) (record-type-name i r ri) (record-type-opaque? i r ri) (record-type-parent i r ri) (record-type-sealed? i r ri) (record-type-uid i r ri) (record? i r ri) (make-record-constructor-descriptor i r rp) (make-record-type-descriptor i r rp) (record-accessor i r rp) (record-constructor i r rp) (record-mutator i r rp) (record-predicate i r rp) (record-type-descriptor? i r rp) (bound-identifier=? i r sc) (datum->syntax i r sc) (syntax i r sc) (syntax->datum i r sc) (syntax-case i r sc) (unsyntax i r sc) (unsyntax-splicing i r sc) (quasisyntax i r sc) (with-syntax i r sc) (free-identifier=? i r sc) (generate-temporaries i r sc) (identifier? i r sc) (make-variable-transformer i r sc) (variable-transformer? ic) (variable-transformer-procedure ic) (char-alphabetic? i r uc se) (char-ci<=? i r uc se) (char-ci<? i r uc se) (char-ci=? i r uc se) (char-ci>=? i r uc se) (char-ci>? i r uc se) (char-downcase i r uc se) (char-foldcase i r uc) (char-titlecase i r uc) (char-upcase i r uc se) (char-general-category i r uc) (char-lower-case? i r uc se) (char-numeric? i r uc se) (char-title-case? i r uc) (char-upper-case? i r uc se) (char-whitespace? i r uc se) (string-ci<=? i r uc se) (string-ci<? i r uc se) (string-ci=? i r uc se) (string-ci>=? i r uc se) (string-ci>? i r uc se) (string-downcase i r uc) (string-foldcase i r uc) (string-normalize-nfc i r uc) (string-normalize-nfd i r uc) (string-normalize-nfkc i r uc) (string-normalize-nfkd i r uc) (string-titlecase i r uc) (string-upcase i r uc) (char-ready? se) (interaction-environment i) (new-interaction-environment i) (string-normalize ic) (compile-bootfile ic) (compile-library ic) (stx? ic) (stx-expr ic) (library-name->file-name ic) (library-name->dll-name ic) (compiled-library-exists? ic) (library-exists? ic) (load i) (compile i) (compile-to-current-directory? i) (compile->closure i) (compile-system-libraries i) (serialize-library iser) (load-serialized-library iser) (load-library-dll ic) (void $boot i) (gensym $boot i) (ungensym $boot i) (symbol-bound? i) (symbol-value $boot i) (set-symbol-value! $boot i) (remove-location i) (eval-core $boot) (compile-core $boot) (module i) (clr-type-of-internal is-clr-int) (clr-namespaces-internal is-clr-int) (clr-using-internal is-clr-int) (clr-reference-internal is-clr-int) (clr-is-internal is-clr-int) (clr-new-array-internal is-clr-int) (clr-new-internal is-clr-int) (clr-call-internal is-clr-int) (clr-cast-internal is-clr-int) (clr-field-get-internal is-clr-int) (clr-field-set!-internal is-clr-int) (define-clr-class-internal is-clr-int) (ffi-callout-internal is-clr-int) (ffi-callback-internal is-clr-int) (pinvoke-call-internal is-clr-int) (ironscheme-build i) (ironscheme-test i) (ironscheme-version i) (ironscheme-runtime i) (last-pair i) (make-list i) (unspecified? i) (make-guid i) (sinh i) (cosh i) (tanh i) (disassemble i) (read-annotated ir) (annotation? ir) (annotation-expression ir) (annotation-source ir) (annotation-stripped ir) (make-annotation ir) (library-letrec*) (&condition-rtd) (&condition-rcd) (&message-rtd) (&message-rcd) (&warning-rtd) (&warning-rcd) (&serious-rtd) (&serious-rcd) (&error-rtd) (&error-rcd) (&violation-rtd) (&violation-rcd) (&assertion-rtd) (&assertion-rcd) (&irritants-rtd) (&irritants-rcd) (&who-rtd) (&who-rcd) (&non-continuable-rtd) (&non-continuable-rcd) (&implementation-restriction-rtd) (&implementation-restriction-rcd) (&lexical-rtd) (&lexical-rcd) (&syntax-rtd) (&syntax-rcd) (&undefined-rtd) (&undefined-rcd) (&i/o-rtd) (&i/o-rcd) (&i/o-read-rtd) (&i/o-read-rcd) (&i/o-write-rtd) (&i/o-write-rcd) (&i/o-invalid-position-rtd) (&i/o-invalid-position-rcd) (&i/o-filename-rtd) (&i/o-filename-rcd) (&i/o-file-protection-rtd) (&i/o-file-protection-rcd) (&i/o-file-is-read-only-rtd) (&i/o-file-is-read-only-rcd) (&i/o-file-already-exists-rtd) (&i/o-file-already-exists-rcd) (&i/o-file-does-not-exist-rtd) (&i/o-file-does-not-exist-rcd) (&i/o-port-rtd) (&i/o-port-rcd) (&i/o-decoding-rtd) (&i/o-decoding-rcd) (&i/o-encoding-rtd) (&i/o-encoding-rcd) (&no-infinities-rtd) (&no-infinities-rcd) (&no-nans-rtd) (&no-nans-rcd) (&where-rtd) (&where-rcd) (&stacktrace-rtd) (&stacktrace-rcd) (ellipsis-map) )) (define (verify-map) (define (f x) (for-each (lambda (x) (unless (assq x library-legend) (error 'verify "not in the libraries list" x))) (cdr x))) (for-each f identifier->library-map)) (define (make-collection) (let ((set '())) (case-lambda (() set) ((x) (set! set (cons x set)))))) (define (make-system-data subst env) (define who 'make-system-data) (let ((export-subst (make-collection)) (export-env (make-collection)) (export-primlocs (make-collection))) (for-each (lambda (x) (let ((name (car x)) (binding (cadr x))) (let ((label (gensym))) (export-subst (cons name label)) (export-env (cons label binding))))) psyntax-system-macros) (for-each (lambda (x) (cond ((macro-identifier x) (values)) ((assq x (export-subst)) (error who "ambiguous export" x)) ((assq x subst) => (lambda (p) (let ((label (cdr p))) (cond ((assq label env) => (lambda (p) (let ((binding (cdr p))) (case (car binding) ((global) (export-subst (cons x label)) (export-env (cons label (cons 'core-prim x))) (export-primlocs (cons x (cdr binding)))) (else (error #f "invalid binding for identifier" p x)))))) (else (error #f "cannot find binding" x label)))))) (else (let ((label (gensym))) (export-subst (cons x label)) (export-env (cons label (cons 'core-prim x))))))) (map car identifier->library-map)) (values (export-subst) (export-env) (export-primlocs)))) (define identifier->library-map-hashtable (let ((ht (make-eq-hashtable))) (for-each (lambda (x) (hashtable-set! ht (car x) x)) identifier->library-map) ht)) (define (get-export-subset key subst) (let f ((ls subst)) (cond ((null? ls) '()) (else (let ((x (car ls))) (let ((name (car x))) (cond ((hashtable-ref identifier->library-map-hashtable name #f) => (lambda (q) (cond ((memq key (cdr q)) (cons x (f (cdr ls)))) (else (f (cdr ls)))))) (else (f (cdr ls)))))))))) (define (build-system-library export-subst export-env primlocs) (define (build-library legend-entry) (let ((key (car legend-entry)) (name (cadr legend-entry)) (visible? (caddr legend-entry))) (let ((id (gensym)) (name name) (version (if (eq? (car name) 'rnrs) '(6) '())) (import-libs '()) (visit-libs '()) (invoke-libs '())) (let-values (((subst env) (if (equal? name '(psyntax system $all)) (values export-subst export-env) (values (get-export-subset key export-subst) '())))) `(install-library ',id ',name ',version ',import-libs ',visit-libs ',invoke-libs ',subst ',env values values '#f '#f '#f '() ',visible? '#f))))) (let ((code `(library (psyntax primlocs) (import (only (psyntax library-manager) install-library) (only (psyntax internal) current-primitive-locations) (only (ironscheme clr) clr-static-call) (rnrs hashtables) (rnrs base)) (current-primitive-locations (let ((ht (clr-static-call IronScheme.Runtime.Builtins MakePrimlocHashtable ',primlocs))) (lambda (x) (hashtable-ref ht x #f)))) ,@(map build-library library-legend)))) (let-values (((name code empty-subst empty-env) (boot-library-expand code))) code))) (define (make-init-code) (values '() '() '())) (define (expand-all files) (define (prune-subst subst env) (cond ((null? subst) '()) ((not (assq (cdar subst) env)) (prune-subst (cdr subst) env)) (else (cons (car subst) (prune-subst (cdr subst) env))))) (define (load file proc) (call-with-input-file file (lambda (p) (let f () (let ((x (read-annotated p))) (unless (eof-object? x) (proc x) (f))))))) (let-values (((code* subst env) (make-init-code))) (for-each (lambda (file) (display "expanding ") (display file) (newline) (load file (lambda (x) (let-values (((name code export-subst export-env) (boot-library-expand x))) (set! code* (cons code code*)) (set! subst (append export-subst subst)) (set! env (append export-env env)))))) files) (let-values (((export-subst export-env export-locs) (make-system-data (prune-subst subst env) env))) (let ((code (build-system-library export-subst export-env export-locs))) (values (reverse (cons* (car code*) code (cdr code*))) export-locs))))) (define bootstrap-collection (let ((ls '())) (case-lambda (() ls) ((x) (unless (memq x ls) (set! ls (cons x ls))))))) (verify-map) (library-path '("." "lib/")) (let ((all-names (map car identifier->library-map)) (all-labels (map (lambda (x) (gensym)) identifier->library-map)) (all-bindings (map (lambda (x) (cond ((macro-identifier x) => cadr) (else `(core-prim . ,x)))) (map car identifier->library-map)))) (let ((export-subst (map cons all-names all-labels)) (export-env (map cons all-labels all-bindings))) (define (build-library legend-entry) (let ((key (car legend-entry)) (name (cadr legend-entry)) (visible? (caddr legend-entry)) (required? (cadddr legend-entry))) (when required? (let ((id (gensym)) (name name) (version (if (eq? (car name) 'rnrs) '(6) '())) (import-libs '()) (visit-libs '()) (invoke-libs '())) (let-values (((subst env) (if (equal? name '(psyntax system $all)) (values export-subst export-env) (values (get-export-subset key export-subst) '())))) (parameterize ((current-library-collection bootstrap-collection)) (install-library id name version import-libs visit-libs invoke-libs subst env values values #f #f #f '() visible? #f))))))) (for-each build-library library-legend))) (let () (define-syntax define-prims (syntax-rules () ((_ name* ...) (let ((g* (map gensym '(name* ...))) (v* (list name* ...))) (for-each set-symbol-value! g* v*) (let ((ht (make-eq-hashtable))) (for-each (lambda (k v) (hashtable-set! ht k v)) '(name* ...) g*) (current-primitive-locations (lambda (x) (let ((op (hashtable-ref ht x #f))) (unless op (error #f "undefined prim" x)) op)))))))) (define-prims clr-call-internal clr-cast-internal zero? string-length vector-ref syntax-violation vector-length cons* cadr cddr filter syntax-dispatch apply cons append map list syntax-error reverse format not make-compile-time-value assertion-violation null? car cdr pair? bound-identifier=? list->vector generate-temporaries = + datum->syntax string->symbol void string-append symbol->string syntax->datum gensym length open-string-output-port identifier? free-identifier=? exists values call-with-values for-all ellipsis-map vector eq? eqv?)) (let-values (((core* locs) (time-it "macro expansion" (lambda () (parameterize ((current-library-collection bootstrap-collection)) (expand-all scheme-library-files)))))) (current-primitive-locations (lambda (x) (cond ((assq x locs) => cdr) (else #f)))) (time-it "code generation" (lambda () (compile-bootfile (map compile-core-expr core*)))))
4e5752fca4cb5e303729cfc0ebc3e97dd1898a5dd5c0d4143f97199234f591bd
silky/myth
list_rev_fold.ml
type nat = | O | S of nat type list = | Nil | Cons of nat * list let rec fold (l:list) (f:list -> nat -> list) (acc:list) : list = match l with | Nil -> acc | Cons (x, l) -> fold l f (f acc x) ;; let snoc : list -> nat -> list = let rec f (l:list) : nat -> list = fun (n:nat) -> match l with | Nil -> Cons (n, Nil) | Cons (x, xs) -> Cons (x, f xs n) in f ;; let list_rev_fold : list -> list |> { [] => [] | [0] => [0] | [1] => [1] | [0;1] => [1;0] | [0;0;1] => [1;0;0] } = ?
null
https://raw.githubusercontent.com/silky/myth/b631edefb2a27a1d731daa6654517d91ca660b95/tests/pldi-2015-benchmarks/list_rev_fold.ml
ocaml
type nat = | O | S of nat type list = | Nil | Cons of nat * list let rec fold (l:list) (f:list -> nat -> list) (acc:list) : list = match l with | Nil -> acc | Cons (x, l) -> fold l f (f acc x) ;; let snoc : list -> nat -> list = let rec f (l:list) : nat -> list = fun (n:nat) -> match l with | Nil -> Cons (n, Nil) | Cons (x, xs) -> Cons (x, f xs n) in f ;; let list_rev_fold : list -> list |> { [] => [] | [0] => [0] | [1] => [1] | [0;1] => [1;0] | [0;0;1] => [1;0;0] } = ?
7f304cb05121ba77c867a6b80754bc586b018c4b8a1f3ca1d12e2fa11c1a4492
kalai-transpiler/kalai
util.clj
(ns kalai.util (:require [meander.epsilon :as m] [meander.syntax.epsilon :as syntax] [meander.match.syntax.epsilon :as match] [puget.printer :as puget] [kalai.types :as types] [camel-snake-kebab.core :as csk] [camel-snake-kebab.internals.string-separator :as csk-ss])) (def c "The counter used by `gensym2` to implement the auto-increment number suffix." (atom 0)) (defn gensym2 "Returns a symbol for an identifier whose name needs to be unique. The name is prefixed by `s`, and uses an auto-incrementing number as a suffix for uniqueness." [s] (symbol (str s (swap! c inc)))) (defn spy ([x] (spy x nil)) ([x label] (println (str "Spy: " label)) (flush) (binding [*print-meta* true] (doto x puget/pprint)))) (defn tmp "Creates a unique symbol (named via `gensym2`) with the metadata necessary for creating a temporary mutable variable." [type expr] (with-meta (gensym2 "tmp") {:t type :expr expr :mut true})) (defn tmp-for [expr] (tmp (types/get-type expr) expr)) (defn match-t? "Match the value for `t` in the :t key in the metadata map of `x`" [t x] (some-> x meta (#(= t (:t %))))) ;; Return whether `t` matches the value of :t of the metadata map (m/defsyntax of-t [t x] (case (::syntax/phase &env) :meander/match `(match/pred #(match-t? ~t %) ~x) &form)) ;; Matches a var (m/defsyntax var [v] (case (::syntax/phase &env) :meander/match `(m/app meta {:var ~v}) &form)) (defn maybe-meta-assoc "If v is truthy, sets k to v in meta of x" ([x k v] (if v (with-meta x (assoc (meta x) k v)) x)) ([x k v & more] {:pre [(even? (count more))]} (apply maybe-meta-assoc (maybe-meta-assoc x k v) more))) (defn sort-any-type "Provides a deterministic ordering of the entries/elements of the provided collection. Maps are ordered by their keys. Numbers come before strings, and numbers and strings are thusly sorted independently before concatenating in the return value." [coll] (if (map? coll) (let [{numbers true non-numbers false} (group-by (comp number? key) coll)] (concat (sort-by key numbers) (sort-by (comp str key) non-numbers))) (let [{numbers true non-numbers false} (group-by number? coll)] (concat (sort numbers) (sort-by str non-numbers))))) (defn generic-split "Modify camel-snake-kebab behavior to prevent segmenting identifier strings when a letter is followed by a number. Ex: `get_f32` should not be `get_f_32`." [ss] (let [cs (mapv csk-ss/classify-char ss) ss-length (.length ^String ss)] (loop [result (transient []), start 0, current 0] (let [next (inc current) result+new (fn [end] (if (> end start) (conj! result (.substring ^String ss start end)) result))] (cond (>= current ss-length) (or (seq (persistent! (result+new current))) ;; Return this instead of an empty seq: [""]) (= (nth cs current) :whitespace) (recur (result+new current) next next) (let [[a b c] (subvec cs current)] ;; This expression is not pretty, but it compiles down to sane JavaScript . (or (and (not= a :upper) (= b :upper)) ;; We changed the following line from the original to support not ;; putting underscores inside something like "u64" or "tmp1". (and (= a :number) (not= b :number)) (and (= a :upper) (= b :upper) (= c :lower)))) (recur (result+new next) next next) :else (recur result start next)))))) TODO : should use this in Java string emitters wherever csk/->snake - case is used so that we are consistent with identifiers across Java and rust (defn ->snake_case "Convert to snake_case using our override behavior for `generic_split`." [s] (with-redefs [csk-ss/generic-split generic-split] (csk/->snake_case s))) (defn thread-second [x & forms] "Returns forms (when given forms) like the 'thread-first' macro -> except that it puts each previous expression into the 3rd position of the new form/S-expression, not the second position like -> does." (loop [x x, forms forms] (if forms (let [form (first forms) threaded (if (seq? form) (with-meta `(~(first form) ~(second form) ~x ~@(next (next form))) (meta form)) (if form (list form x) x))] (recur threaded (next forms))) x))) (defn preserve-type "Preserves the type information on the replacement expr" [expr replacement-expr] (with-meta replacement-expr (or (meta expr) (when-let [t (get types/java-types (type expr))] {:t t}))))
null
https://raw.githubusercontent.com/kalai-transpiler/kalai/347cc1213bdd1eab12a093bb6abab9153cd23035/src/kalai/util.clj
clojure
Return whether `t` matches the value of :t of the metadata map Matches a var Return this instead of an empty seq: This expression is not pretty, We changed the following line from the original to support not putting underscores inside something like "u64" or "tmp1".
(ns kalai.util (:require [meander.epsilon :as m] [meander.syntax.epsilon :as syntax] [meander.match.syntax.epsilon :as match] [puget.printer :as puget] [kalai.types :as types] [camel-snake-kebab.core :as csk] [camel-snake-kebab.internals.string-separator :as csk-ss])) (def c "The counter used by `gensym2` to implement the auto-increment number suffix." (atom 0)) (defn gensym2 "Returns a symbol for an identifier whose name needs to be unique. The name is prefixed by `s`, and uses an auto-incrementing number as a suffix for uniqueness." [s] (symbol (str s (swap! c inc)))) (defn spy ([x] (spy x nil)) ([x label] (println (str "Spy: " label)) (flush) (binding [*print-meta* true] (doto x puget/pprint)))) (defn tmp "Creates a unique symbol (named via `gensym2`) with the metadata necessary for creating a temporary mutable variable." [type expr] (with-meta (gensym2 "tmp") {:t type :expr expr :mut true})) (defn tmp-for [expr] (tmp (types/get-type expr) expr)) (defn match-t? "Match the value for `t` in the :t key in the metadata map of `x`" [t x] (some-> x meta (#(= t (:t %))))) (m/defsyntax of-t [t x] (case (::syntax/phase &env) :meander/match `(match/pred #(match-t? ~t %) ~x) &form)) (m/defsyntax var [v] (case (::syntax/phase &env) :meander/match `(m/app meta {:var ~v}) &form)) (defn maybe-meta-assoc "If v is truthy, sets k to v in meta of x" ([x k v] (if v (with-meta x (assoc (meta x) k v)) x)) ([x k v & more] {:pre [(even? (count more))]} (apply maybe-meta-assoc (maybe-meta-assoc x k v) more))) (defn sort-any-type "Provides a deterministic ordering of the entries/elements of the provided collection. Maps are ordered by their keys. Numbers come before strings, and numbers and strings are thusly sorted independently before concatenating in the return value." [coll] (if (map? coll) (let [{numbers true non-numbers false} (group-by (comp number? key) coll)] (concat (sort-by key numbers) (sort-by (comp str key) non-numbers))) (let [{numbers true non-numbers false} (group-by number? coll)] (concat (sort numbers) (sort-by str non-numbers))))) (defn generic-split "Modify camel-snake-kebab behavior to prevent segmenting identifier strings when a letter is followed by a number. Ex: `get_f32` should not be `get_f_32`." [ss] (let [cs (mapv csk-ss/classify-char ss) ss-length (.length ^String ss)] (loop [result (transient []), start 0, current 0] (let [next (inc current) result+new (fn [end] (if (> end start) (conj! result (.substring ^String ss start end)) result))] (cond (>= current ss-length) (or (seq (persistent! (result+new current))) [""]) (= (nth cs current) :whitespace) (recur (result+new current) next next) (let [[a b c] (subvec cs current)] but it compiles down to sane JavaScript . (or (and (not= a :upper) (= b :upper)) (and (= a :number) (not= b :number)) (and (= a :upper) (= b :upper) (= c :lower)))) (recur (result+new next) next next) :else (recur result start next)))))) TODO : should use this in Java string emitters wherever csk/->snake - case is used so that we are consistent with identifiers across Java and rust (defn ->snake_case "Convert to snake_case using our override behavior for `generic_split`." [s] (with-redefs [csk-ss/generic-split generic-split] (csk/->snake_case s))) (defn thread-second [x & forms] "Returns forms (when given forms) like the 'thread-first' macro -> except that it puts each previous expression into the 3rd position of the new form/S-expression, not the second position like -> does." (loop [x x, forms forms] (if forms (let [form (first forms) threaded (if (seq? form) (with-meta `(~(first form) ~(second form) ~x ~@(next (next form))) (meta form)) (if form (list form x) x))] (recur threaded (next forms))) x))) (defn preserve-type "Preserves the type information on the replacement expr" [expr replacement-expr] (with-meta replacement-expr (or (meta expr) (when-let [t (get types/java-types (type expr))] {:t t}))))
d17d4db18e20af281636dc407dc74ff7dc6457c8af078060ad42aa6ab7a6efaa
haroldcarr/learn-haskell-coq-ml-etc
Main.hs
module Main where main :: IO () main = putStrLn "hello"
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/playpen/iceland-jack/app/Main.hs
haskell
module Main where main :: IO () main = putStrLn "hello"
217fa0adb26cad7e9829b8b24dffabc857a96e62647f4f387717a5d6f74ef51a
ghcjs/ghcjs
num009.hs
trac # 2059 # LANGUAGE ForeignFunctionInterface # module Main(main) where import Control.Monad import Foreign.C disable inaccurate single precision for GHCJS main = do let d = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Double] f = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Float] mapM_ (test "sind" sind sin) d -- mapM_ (test "sinf" sinf sin) f mapM_ (test "cosd" cosd cos) d -- mapM_ (test "cosf" cosf cos) f mapM_ (test "tand" tand tan) d -- mapM_ (test "tanf" tanf tan) f putStrLn "Done" test :: (RealFloat a, Floating a, RealFloat b, Floating b, Show b) => String -> (a -> a) -> (b -> b) -> b -> IO () test s f g x = do let y = realToFrac (f (realToFrac x)) z = g x unless (y == z) $ do putStrLn (s ++ ' ':show x) print y print z print $ decodeFloat y print $ decodeFloat z foreign import ccall "math.h sin" sind :: CDouble -> CDouble foreign import ccall "math.h sinf" sinf :: CFloat -> CFloat foreign import ccall "math.h cos" cosd :: CDouble -> CDouble foreign import ccall "math.h cosf" cosf :: CFloat -> CFloat foreign import ccall "math.h tan" tand :: CDouble -> CDouble foreign import ccall "math.h tanf" tanf :: CFloat -> CFloat
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/pkg/base/Numeric/num009.hs
haskell
mapM_ (test "sinf" sinf sin) f mapM_ (test "cosf" cosf cos) f mapM_ (test "tanf" tanf tan) f
trac # 2059 # LANGUAGE ForeignFunctionInterface # module Main(main) where import Control.Monad import Foreign.C disable inaccurate single precision for GHCJS main = do let d = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Double] f = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Float] mapM_ (test "sind" sind sin) d mapM_ (test "cosd" cosd cos) d mapM_ (test "tand" tand tan) d putStrLn "Done" test :: (RealFloat a, Floating a, RealFloat b, Floating b, Show b) => String -> (a -> a) -> (b -> b) -> b -> IO () test s f g x = do let y = realToFrac (f (realToFrac x)) z = g x unless (y == z) $ do putStrLn (s ++ ' ':show x) print y print z print $ decodeFloat y print $ decodeFloat z foreign import ccall "math.h sin" sind :: CDouble -> CDouble foreign import ccall "math.h sinf" sinf :: CFloat -> CFloat foreign import ccall "math.h cos" cosd :: CDouble -> CDouble foreign import ccall "math.h cosf" cosf :: CFloat -> CFloat foreign import ccall "math.h tan" tand :: CDouble -> CDouble foreign import ccall "math.h tanf" tanf :: CFloat -> CFloat
b849fe821af91920698e3e31561d9d0e83bb816bc5ee62af2e05d36669f0f4fb
ruricolist/cloture
fset-hacks.lisp
(in-package #:cloture) (defconst int-length 32) (defconst long-length 64) (deftype int () '(signed-byte #.int-length)) (deftype long () '(signed-byte #.long-length)) (defsubst mask-signed-field (size int) #+sbcl (sb-c::mask-signed-field size int) #-sbcl (cond ((zerop size) 0) ((logbitp (1- size) int) (dpb int (byte size 0) -1)) (t (ldb (byte size 0) int)))) (defsubst mask-int (int) (mask-signed-field int-length int)) (defsubst mask-long (int) (mask-signed-field long-length int)) (defmethod make-load-form ((seq seq) &optional env) (declare (ignore env)) `(seq ,@(mapcar (op `(quote ,_)) (convert 'list seq)))) (defmethod make-load-form ((map map) &optional env) (declare (ignore env)) `(map ,@(collecting (fset:do-map (k v map) (collect (list `(quote ,k) `(quote ,v))))))) (defmethod make-load-form ((set set) &optional env) (declare (ignore env)) `(set ,@(mapcar (op `(quote ,_)) (convert 'list set)))) (defpattern seq (&rest pats) (with-unique-names (it) `(guard1 (,it :type seq) (typep ,it 'seq) (size ,it) ,(length pats) ,@(loop for pat in pats for i from 0 collect `(lookup ,it ,i) collect pat)))) (defun murmurhash* (x) (mask-int (murmurhash x))) (defmethod murmurhash ((seq seq) &key (seed *default-seed*) mix-only) (mask-int (murmurhash (list* '%seq (size seq) (convert 'list seq)) :seed seed :mix-only mix-only))) (defmethod murmurhash ((set set) &key (seed *default-seed*) mix-only) (mask-int (murmurhash (list* '%set (size set) (convert 'list set)) :seed seed :mix-only mix-only))) (defmethod murmurhash ((map map) &key (seed *default-seed*) mix-only) (mask-int (murmurhash (list* '%set (size map) (map->alist map)) :seed seed :mix-only mix-only))) We want to be able to build on FSet 's idea of equality , but we also need FSet to take into account Clojure 's idea of equality ( so ;;; that maps have the correct behavior). The following hack lets that ;;; work by detecting and breaking recursion. (defmethod fset:compare (a b) (handler-case (without-recursion () (if (truthy? (|clojure.core|:|=| a b)) :equal :unequal)) (recursion-forbidden () (call-next-method)))) (defmethod fset:compare :around ((a symbol) (b symbol)) (flet ((compare-by-name (a b) (let ((name1 (symbol-name a)) (name2 (symbol-name b))) (eif (or (find #\/ name1) (find #\/ name2)) (call-next-method) (if (equal name1 name2) :equal (call-next-method)))))) (eif (keywordp a) (call-next-method) (eif (keywordp b) (call-next-method) (let ((package1 (symbol-package a))) (eif (clojure-package? package1) (let ((package2 (symbol-package b))) (eif (clojure-package? package2) (compare-by-name a b) (call-next-method))) (call-next-method)))))))
null
https://raw.githubusercontent.com/ruricolist/cloture/623c15c8d2e5e91eb87f46e3ecb3975880109948/fset-hacks.lisp
lisp
that maps have the correct behavior). The following hack lets that work by detecting and breaking recursion.
(in-package #:cloture) (defconst int-length 32) (defconst long-length 64) (deftype int () '(signed-byte #.int-length)) (deftype long () '(signed-byte #.long-length)) (defsubst mask-signed-field (size int) #+sbcl (sb-c::mask-signed-field size int) #-sbcl (cond ((zerop size) 0) ((logbitp (1- size) int) (dpb int (byte size 0) -1)) (t (ldb (byte size 0) int)))) (defsubst mask-int (int) (mask-signed-field int-length int)) (defsubst mask-long (int) (mask-signed-field long-length int)) (defmethod make-load-form ((seq seq) &optional env) (declare (ignore env)) `(seq ,@(mapcar (op `(quote ,_)) (convert 'list seq)))) (defmethod make-load-form ((map map) &optional env) (declare (ignore env)) `(map ,@(collecting (fset:do-map (k v map) (collect (list `(quote ,k) `(quote ,v))))))) (defmethod make-load-form ((set set) &optional env) (declare (ignore env)) `(set ,@(mapcar (op `(quote ,_)) (convert 'list set)))) (defpattern seq (&rest pats) (with-unique-names (it) `(guard1 (,it :type seq) (typep ,it 'seq) (size ,it) ,(length pats) ,@(loop for pat in pats for i from 0 collect `(lookup ,it ,i) collect pat)))) (defun murmurhash* (x) (mask-int (murmurhash x))) (defmethod murmurhash ((seq seq) &key (seed *default-seed*) mix-only) (mask-int (murmurhash (list* '%seq (size seq) (convert 'list seq)) :seed seed :mix-only mix-only))) (defmethod murmurhash ((set set) &key (seed *default-seed*) mix-only) (mask-int (murmurhash (list* '%set (size set) (convert 'list set)) :seed seed :mix-only mix-only))) (defmethod murmurhash ((map map) &key (seed *default-seed*) mix-only) (mask-int (murmurhash (list* '%set (size map) (map->alist map)) :seed seed :mix-only mix-only))) We want to be able to build on FSet 's idea of equality , but we also need FSet to take into account Clojure 's idea of equality ( so (defmethod fset:compare (a b) (handler-case (without-recursion () (if (truthy? (|clojure.core|:|=| a b)) :equal :unequal)) (recursion-forbidden () (call-next-method)))) (defmethod fset:compare :around ((a symbol) (b symbol)) (flet ((compare-by-name (a b) (let ((name1 (symbol-name a)) (name2 (symbol-name b))) (eif (or (find #\/ name1) (find #\/ name2)) (call-next-method) (if (equal name1 name2) :equal (call-next-method)))))) (eif (keywordp a) (call-next-method) (eif (keywordp b) (call-next-method) (let ((package1 (symbol-package a))) (eif (clojure-package? package1) (let ((package2 (symbol-package b))) (eif (clojure-package? package2) (compare-by-name a b) (call-next-method))) (call-next-method)))))))
fddd36811654004a45ee32707d7f44719fc4ca2944346f368141c28dc460f8be
shriphani/clj-lmdb
simple_test.clj
(ns clj-lmdb.simple-test (:require [clojure.test :refer :all] [clj-lmdb.simple :refer :all])) (deftest non-txn-test (testing "Put + get without using a txn" (let [db (make-db "/tmp")] (put! db "foo" "bar") (is (= (get! db "foo") "bar")) (delete! db "foo") (is (nil? (get! db "foo")))))) (deftest with-txn-test (testing "Results with a txn" (let [db (make-db "/tmp")] (with-txn [txn (write-txn db)] (put! db txn "foo" "bar") (put! db txn "foo1" "bar1")) (with-txn [txn (read-txn db)] (is (= (get! db txn "foo") "bar")) (is (= (get! db txn "foo1") "bar1"))) (delete! db "foo") (delete! db "foo1")))) (deftest iteration-test (testing "Iteration" (let [db (make-db "/tmp")] (with-txn [txn (write-txn db)] (doall (map (fn [i] (put! db txn (str i) (str i))) (range 1000)))) (with-txn [txn (read-txn db)] (let [num-items (count (doall (map (fn [[k v]] (is (= k v)) [k v]) (items db txn))))] (is (= num-items 1000)))) (with-txn [txn (read-txn db)] (let [num-items (count (doall (map (fn [[k v]] (is (= k v)) [k v]) (items-from db txn "500"))))] (is (= num-items 553)))) ; items are sorted in alphabetical order - not numerical (with-txn [txn (write-txn db)] (doall (map #(->> % str (delete! db txn)) (range 1000))) (is (= (count (items-from db txn "400")) 0)))))) (deftest named-db-test (testing "Create multiple databases in a single env." (let [db-record1 (make-named-db "/tmp" "db1") db-record2 (make-named-db "/tmp" "db2")] (put! db-record1 "foo" "bar") (put! db-record2 "foo" "baz") (is (= (get! db-record1 "foo") "bar")) (is (= (get! db-record2 "foo") "baz")) (drop-db! db-record1) (drop-db! db-record2))))
null
https://raw.githubusercontent.com/shriphani/clj-lmdb/dd842440088aa7fbe677c31c07ae56621d98a04d/test/clj_lmdb/simple_test.clj
clojure
items are sorted in alphabetical order - not numerical
(ns clj-lmdb.simple-test (:require [clojure.test :refer :all] [clj-lmdb.simple :refer :all])) (deftest non-txn-test (testing "Put + get without using a txn" (let [db (make-db "/tmp")] (put! db "foo" "bar") (is (= (get! db "foo") "bar")) (delete! db "foo") (is (nil? (get! db "foo")))))) (deftest with-txn-test (testing "Results with a txn" (let [db (make-db "/tmp")] (with-txn [txn (write-txn db)] (put! db txn "foo" "bar") (put! db txn "foo1" "bar1")) (with-txn [txn (read-txn db)] (is (= (get! db txn "foo") "bar")) (is (= (get! db txn "foo1") "bar1"))) (delete! db "foo") (delete! db "foo1")))) (deftest iteration-test (testing "Iteration" (let [db (make-db "/tmp")] (with-txn [txn (write-txn db)] (doall (map (fn [i] (put! db txn (str i) (str i))) (range 1000)))) (with-txn [txn (read-txn db)] (let [num-items (count (doall (map (fn [[k v]] (is (= k v)) [k v]) (items db txn))))] (is (= num-items 1000)))) (with-txn [txn (read-txn db)] (let [num-items (count (doall (map (fn [[k v]] (is (= k v)) [k v]) (items-from db txn "500"))))] (with-txn [txn (write-txn db)] (doall (map #(->> % str (delete! db txn)) (range 1000))) (is (= (count (items-from db txn "400")) 0)))))) (deftest named-db-test (testing "Create multiple databases in a single env." (let [db-record1 (make-named-db "/tmp" "db1") db-record2 (make-named-db "/tmp" "db2")] (put! db-record1 "foo" "bar") (put! db-record2 "foo" "baz") (is (= (get! db-record1 "foo") "bar")) (is (= (get! db-record2 "foo") "baz")) (drop-db! db-record1) (drop-db! db-record2))))
f14cf5795e5eecea3cca5968c95d35c6f7c2697f9c3ed5fe138fc1b56b85e4b1
chovencorp/erlangzmq
erlangzmq_acceptance_error_handler.erl
@copyright 2016 Choven Corp. %% This file is part of erlangzmq . %% erlangzmq 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. %% %% erlangzmq 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 erlangzmq . If not , see < / > -module(erlangzmq_acceptance_error_handler). -include_lib("eunit/include/eunit.hrl"). -define(PORT, 3010). single_test_() -> [ { "Should not start connection with invalid servers", {setup, fun start/0, fun stop/1, fun negotiate_messages/1} } ]. start() -> application:ensure_started(erlangzmq), {ok, ServerPid} = erlangzmq:socket(rep), {ok, _BindPid} = erlangzmq:bind(ServerPid, tcp, "localhost", ?PORT), ServerPid. invalid_client() -> Parent = self(), spawn( fun () -> process_flag(trap_exit, true), {ok, Socket} = erlangzmq:socket(push), {ok, PeerPid} = erlangzmq:connect(Socket, tcp, "localhost", ?PORT), link(PeerPid), %% to wait modifications client_loop(Parent, PeerPid) end ). client_loop(Parent, PeerPid) -> receive {'EXIT', PeerPid, {shutdown, Reason}} -> Parent ! {peer_finish, Reason} end. stop(Pid) -> gen_server:stop(Pid). negotiate_messages(_ServerPid) -> invalid_client(), Message = wait_for_msg(), [ ?_assertEqual(Message, {server_error, "Invalid socket-type push for rep server"}) ]. wait_for_msg() -> receive {peer_finish, Msg} -> Msg end.
null
https://raw.githubusercontent.com/chovencorp/erlangzmq/2be5c3b36dd78b010d1790a8f74ae2e823f5a424/test/erlangzmq_acceptance_error_handler.erl
erlang
(at your option) any later version. erlangzmq 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. to wait modifications
@copyright 2016 Choven Corp. This file is part of erlangzmq . erlangzmq 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 You should have received a copy of the GNU Affero General Public License along with erlangzmq . If not , see < / > -module(erlangzmq_acceptance_error_handler). -include_lib("eunit/include/eunit.hrl"). -define(PORT, 3010). single_test_() -> [ { "Should not start connection with invalid servers", {setup, fun start/0, fun stop/1, fun negotiate_messages/1} } ]. start() -> application:ensure_started(erlangzmq), {ok, ServerPid} = erlangzmq:socket(rep), {ok, _BindPid} = erlangzmq:bind(ServerPid, tcp, "localhost", ?PORT), ServerPid. invalid_client() -> Parent = self(), spawn( fun () -> process_flag(trap_exit, true), {ok, Socket} = erlangzmq:socket(push), {ok, PeerPid} = erlangzmq:connect(Socket, tcp, "localhost", ?PORT), client_loop(Parent, PeerPid) end ). client_loop(Parent, PeerPid) -> receive {'EXIT', PeerPid, {shutdown, Reason}} -> Parent ! {peer_finish, Reason} end. stop(Pid) -> gen_server:stop(Pid). negotiate_messages(_ServerPid) -> invalid_client(), Message = wait_for_msg(), [ ?_assertEqual(Message, {server_error, "Invalid socket-type push for rep server"}) ]. wait_for_msg() -> receive {peer_finish, Msg} -> Msg end.
e30da1e842636f3f2df929688542c4de6ea648447977b055bcef005d0f68acd4
SamB/coq
extend.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id$ i*) open Util (**********************************************************************) (* constr entry keys *) type side = Left | Right type production_position = | BorderProd of side * Gramext.g_assoc option (* true=left; false=right *) | InternalProd type production_level = | NextLevel | NumLevel of int type ('lev,'pos) constr_entry_key = | ETIdent | ETReference | ETBigint | ETConstr of ('lev * 'pos) | ETPattern | ETOther of string * string | ETConstrList of ('lev * 'pos) * Token.pattern list type constr_production_entry = (production_level,production_position) constr_entry_key type constr_entry = (int,unit) constr_entry_key type simple_constr_production_entry = (production_level,unit) constr_entry_key (**********************************************************************) (* syntax modifiers *) type syntax_modifier = | SetItemLevel of string list * production_level | SetLevel of int | SetAssoc of Gramext.g_assoc | SetEntryType of string * simple_constr_production_entry | SetOnlyParsing | SetFormat of string located
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/parsing/extend.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i $Id$ i ******************************************************************** constr entry keys true=left; false=right ******************************************************************** syntax modifiers
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Util type side = Left | Right type production_position = | InternalProd type production_level = | NextLevel | NumLevel of int type ('lev,'pos) constr_entry_key = | ETIdent | ETReference | ETBigint | ETConstr of ('lev * 'pos) | ETPattern | ETOther of string * string | ETConstrList of ('lev * 'pos) * Token.pattern list type constr_production_entry = (production_level,production_position) constr_entry_key type constr_entry = (int,unit) constr_entry_key type simple_constr_production_entry = (production_level,unit) constr_entry_key type syntax_modifier = | SetItemLevel of string list * production_level | SetLevel of int | SetAssoc of Gramext.g_assoc | SetEntryType of string * simple_constr_production_entry | SetOnlyParsing | SetFormat of string located
d042bd01dcff8d1d92cfa7f4cbca0026a82b10d3f7b33c922d33deb2e7998544
uw-unsat/leanette-popl22-artifact
synthesize.rkt
#lang rosette/safe (provide potential-program-exists? synthesize-program synthesize-program/no-generalization synthesize-program/inductive superoptimize-program sketch-covers?) (require (only-in racket local-require) rosette/solver/smt/z3 "cegis.rkt" "../core/core.rkt" "../nonograms/nonograms.rkt") (define (consistent-with-bindings? ctx binding-prog binding-list) (define b (find-binding-for-pattern binding-prog ctx)) (and b (&&map equal? b binding-list))) ; true iff the given binding determines the given output, and thus a program could exist (define (potential-program-exists? tctx actn bnding) (parameterize-solver (define slvr (current-solver)) (define ctx (line-transition-start tctx)) (define end (line-transition-end tctx)) ; create a symbolic context constrained to have the same concrete binding values as this transition. (define test-tctx (eval-with-solver slvr (symbolic-line-transition (line-length ctx)))) (solver-assert* slvr (consistent-with-bindings? (line-transition-start test-tctx) bnding (find-binding-for-pattern bnding ctx))) ; rule exists if any context with these bindings can have this action applied to it. ; so try to find one that breaks it! (solver-assert* slvr (not (action-compatible-with-transition? actn test-tctx))) (define soln (solver-check slvr)) (solver-clear slvr) (when (sat? soln) (printf "conflicting ctx: ~a\nbindings: ~a\n" (evaluate test-tctx soln) (find-binding-for-pattern bnding (line-transition-start (evaluate test-tctx soln))))) (when (unsat? soln) (printf "bindings: ~a\n" (find-binding-for-pattern bnding ctx))) (unsat? soln))) ; Implementation of the common bits of rule synthesis. ; Calls primary-guesser-assert-fn with the guess solver and program sktech ; so specific calls can enforce whatever existential constraints they want. This takes care of the CEGIS for rule soundness , plus some common extra ; exestential constrants such as forced-positive examples. (define (synthesize-program-impl primary-guesser-assert-fn ( int ? ) #:counter-example-parameters ce-parameters-seq ; whatever the parameters for a single sketch are #:sketch-parameters sketch-parameters #:objective-functions objective-functions-ctors #:program-eater eater #:counter-example-eater [eat-cex void] #:counter-example-functions [ce-func-ctors empty] #:optimization-state-update optimization-state-update ) (parameterize-solver (define guesser (z3)) (define verifiers (map create-verifier ce-parameters-seq)) (solver-clear guesser) ; our program sketch (define sktch (eval-with-solver guesser (apply program-sketch sketch-parameters))) (define objective-functions (map (λ (f) (f guesser verifiers sktch)) objective-functions-ctors)) ; symbolic assignment for finding counter-examples (no asserts) (define assn (map (λ (_) (??)) (Program-pattern sktch))) (define ce-funcs (map (λ (f) (f verifiers)) ce-func-ctors)) (define (find-counter-example guess) (or if the programs behaves unsoundly (find-program-unsound-example verifiers guess assn) ; or if any objective function says there is a problem ; this is always "active" even if the OF has not started optimizing yet, they are expected to deal with this reasonably. ; (we want them to keep checking after they have reached their optimal, so it's just easier to leave them all on all the time). (ormap (λ (cefn) (cefn guess)) ce-funcs) (ormap (λ (of) ((synthesis-objective-function-find-counter-example of) guess)) objective-functions))) ; assert the primary exestential stuff (primary-guesser-assert-fn guesser sktch) (define (synthesize) (run-cegis guesser sktch #:find-counter-example find-counter-example #:eater eater #:eat-counter-example eat-cex)) (define result (run-incremental-optimization guesser synthesize objective-functions #:notification-function optimization-state-update)) (solver-shutdown guesser) (for-each verifier-shutdown verifiers) result)) ; Program?, line-transition? -> boolean? ; Returns true iff the given program applies to and effects a non-trivial action on the given line transition. ; Either may be symbolic. (define (positive-example? program tctx assn) (define ctx (line-transition-start tctx)) (define action (interpret/nondeterministic program (create-environment ctx) #:binding-assignments assn)) (and action (action-compatible-with-and-impactful-for-transition? action tctx))) (define (negative-example? program tctx assn) (define ctx (line-transition-start tctx)) (define action (interpret/nondeterministic program (create-environment ctx) #:binding-assignments assn)) (not action)) (define (create-higher-generalization-optimization generalization-set-parameters) (λ (guesser verifiers sktch) ; can use same set of symbolic transitions the entire time because each better program engulfs the previous, so one transition should be new for every previous program (define transitions (eval-with-solver guesser (map symbolic-line-transition generalization-set-parameters))) ; symbolic assignment for finding counter-examples (this makes no assertions) (define assn (map (λ (_) (??)) (Program-pattern sktch))) ; either empty (at start) or the singleton list of the best program so far, used for cex finding (define programs-to-generalize empty) (synthesis-objective-function 'generalization (λ (prog) (dprintf "trying to increase generalization") (set! programs-to-generalize (list prog)) assert that at least one of these transitions is covered by the that is not covered by the found program (solver-assert* guesser (lormap (λ (tctx) (define assn (map (λ (_) (??)) (Program-pattern sktch))) (&& (positive-example? sktch tctx assn) (negative-example? prog tctx assn))) transitions))) (λ (guess) ; if there exists some input covered by a program we must generalize but not this one (find-program-uncovered-example verifiers guess programs-to-generalize assn))))) (define (create-lower-cost-optimization) (λ (guesser _ sktch) (synthesis-objective-function 'cost (λ (prog) (define c (program-cost prog)) (dprintf "trying to lower cost below ~a" c) (solver-assert* guesser (< (program-cost sktch) c))) (λ (_) #f)))) (define (synthesize-program #:input ctx #:output actn #:binding bnding #:counter-example-parameters ce-params #:generalization-set-parameters gs-params #:program-eater [eater void] #:optimization-state-update [optimization-state-update void] ) (define (assertfn guesser sktch) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment ctx)) actn))) (define objectives (list (create-higher-generalization-optimization gs-params) (create-lower-cost-optimization))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params ; TODO XXX ignoring features for now #:sketch-parameters (list empty ctx bnding) #:program-eater eater #:optimization-state-update optimization-state-update #:objective-functions objectives)) (define (synthesize-program/no-generalization #:input ctx #:output actn #:binding bnding #:counter-example-parameters ce-params #:program-eater [eater void] #:optimization-state-update [optimization-state-update void] #:debug-force-use-program [forced-program #f] ) (define (assertfn guesser sktch) (when forced-program (solver-assert* guesser (equal? sktch forced-program))) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment ctx)) actn))) (define objectives (list (create-lower-cost-optimization))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params ; TODO XXX ignoring features for now #:sketch-parameters (list empty ctx bnding) #:program-eater eater #:optimization-state-update optimization-state-update #:objective-functions objectives)) (define (synthesize-program/inductive ( listof ( pairof line ? line - action ? ) ) #:input io-examples #:pattern pat #:counter-example-parameters ce-params #:program-eater [eater void]) (local-require (only-in racket for)) (define (assertfn guesser sktch) (for ([pr io-examples]) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment (car pr))) (cdr pr))))) (define objectives (list (create-lower-cost-optimization))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params ; TODO XXX ignoring features for now #:sketch-parameters (list empty (car (first io-examples)) pat) #:program-eater eater #:optimization-state-update void #:objective-functions objectives)) ; finds the lowest-cost program that covers all the same programs as the given program while using the same bindings. ; Also behaves exactly the same on primary-input, returning the primary output (define (superoptimize-program #:primary-input ctx #:primary-output actn #:program prog #:counter-example-parameters ce-params #:program-eater eater) (define (assertfn guesser sktch) (solver-assert* guesser (< (program-cost sktch) (program-cost prog))) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment ctx)) actn))) (define objectives (list (create-lower-cost-optimization))) (define cefuncs (list (λ (verifiers) (define assn (map (λ (_) (??)) (Program-pattern prog))) (λ (guess) ; if there exists some input covered by a program we must generalize but not this one (find-program-uncovered-example verifiers guess (list prog) assn))))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params ; TODO XXX ignoring features for now #:sketch-parameters (list empty #f (Program-pattern prog)) #:program-eater eater #:counter-example-functions cefuncs #:optimization-state-update void #:objective-functions objectives)) (define (sketch-covers? prog sketch-parameters) (parameterize-solver (define sktch (program-sketch sketch-parameters #f (Program-pattern prog))) (define-syntax-rule (check f) (sat? (solve (assert (equal? (f sktch) (f prog)))))) ( ; (list ( check Program - pattern ) ; ;(check (compose first Program-pattern)) ; ( check ( compose second Program - pattern ) ) ; ( check ( compose third Program - pattern ) ) ( check Program - condition ) ; (check (compose Fill-offset Program-action)) ; (check (compose Fill-start Program-action)) ; (check (compose Fill-end Program-action)) ) ) ; ( check Program - action ) ) ) (sat? (solve (assert (equal? sktch prog))))))
null
https://raw.githubusercontent.com/uw-unsat/leanette-popl22-artifact/80fea2519e61b45a283fbf7903acdf6d5528dbe7/rosette-benchmarks-3/nonograms/puzzle/src/learn/synthesize.rkt
racket
true iff the given binding determines the given output, and thus a program could exist create a symbolic context constrained to have the same concrete binding values as this transition. rule exists if any context with these bindings can have this action applied to it. so try to find one that breaks it! Implementation of the common bits of rule synthesis. Calls primary-guesser-assert-fn with the guess solver and program sktech so specific calls can enforce whatever existential constraints they want. exestential constrants such as forced-positive examples. whatever the parameters for a single sketch are our program sketch symbolic assignment for finding counter-examples (no asserts) or if any objective function says there is a problem this is always "active" even if the OF has not started optimizing yet, they are expected to deal with this reasonably. (we want them to keep checking after they have reached their optimal, so it's just easier to leave them all on all the time). assert the primary exestential stuff Program?, line-transition? -> boolean? Returns true iff the given program applies to and effects a non-trivial action on the given line transition. Either may be symbolic. can use same set of symbolic transitions the entire time because each better program engulfs the previous, symbolic assignment for finding counter-examples (this makes no assertions) either empty (at start) or the singleton list of the best program so far, used for cex finding if there exists some input covered by a program we must generalize but not this one TODO XXX ignoring features for now TODO XXX ignoring features for now TODO XXX ignoring features for now finds the lowest-cost program that covers all the same programs as the given program while using the same bindings. Also behaves exactly the same on primary-input, returning the primary output if there exists some input covered by a program we must generalize but not this one TODO XXX ignoring features for now (list ;(check (compose first Program-pattern)) ( check ( compose second Program - pattern ) ) ( check ( compose third Program - pattern ) ) (check (compose Fill-offset Program-action)) (check (compose Fill-start Program-action)) (check (compose Fill-end Program-action)) ( check Program - action ) ) )
#lang rosette/safe (provide potential-program-exists? synthesize-program synthesize-program/no-generalization synthesize-program/inductive superoptimize-program sketch-covers?) (require (only-in racket local-require) rosette/solver/smt/z3 "cegis.rkt" "../core/core.rkt" "../nonograms/nonograms.rkt") (define (consistent-with-bindings? ctx binding-prog binding-list) (define b (find-binding-for-pattern binding-prog ctx)) (and b (&&map equal? b binding-list))) (define (potential-program-exists? tctx actn bnding) (parameterize-solver (define slvr (current-solver)) (define ctx (line-transition-start tctx)) (define end (line-transition-end tctx)) (define test-tctx (eval-with-solver slvr (symbolic-line-transition (line-length ctx)))) (solver-assert* slvr (consistent-with-bindings? (line-transition-start test-tctx) bnding (find-binding-for-pattern bnding ctx))) (solver-assert* slvr (not (action-compatible-with-transition? actn test-tctx))) (define soln (solver-check slvr)) (solver-clear slvr) (when (sat? soln) (printf "conflicting ctx: ~a\nbindings: ~a\n" (evaluate test-tctx soln) (find-binding-for-pattern bnding (line-transition-start (evaluate test-tctx soln))))) (when (unsat? soln) (printf "bindings: ~a\n" (find-binding-for-pattern bnding ctx))) (unsat? soln))) This takes care of the CEGIS for rule soundness , plus some common extra (define (synthesize-program-impl primary-guesser-assert-fn ( int ? ) #:counter-example-parameters ce-parameters-seq #:sketch-parameters sketch-parameters #:objective-functions objective-functions-ctors #:program-eater eater #:counter-example-eater [eat-cex void] #:counter-example-functions [ce-func-ctors empty] #:optimization-state-update optimization-state-update ) (parameterize-solver (define guesser (z3)) (define verifiers (map create-verifier ce-parameters-seq)) (solver-clear guesser) (define sktch (eval-with-solver guesser (apply program-sketch sketch-parameters))) (define objective-functions (map (λ (f) (f guesser verifiers sktch)) objective-functions-ctors)) (define assn (map (λ (_) (??)) (Program-pattern sktch))) (define ce-funcs (map (λ (f) (f verifiers)) ce-func-ctors)) (define (find-counter-example guess) (or if the programs behaves unsoundly (find-program-unsound-example verifiers guess assn) (ormap (λ (cefn) (cefn guess)) ce-funcs) (ormap (λ (of) ((synthesis-objective-function-find-counter-example of) guess)) objective-functions))) (primary-guesser-assert-fn guesser sktch) (define (synthesize) (run-cegis guesser sktch #:find-counter-example find-counter-example #:eater eater #:eat-counter-example eat-cex)) (define result (run-incremental-optimization guesser synthesize objective-functions #:notification-function optimization-state-update)) (solver-shutdown guesser) (for-each verifier-shutdown verifiers) result)) (define (positive-example? program tctx assn) (define ctx (line-transition-start tctx)) (define action (interpret/nondeterministic program (create-environment ctx) #:binding-assignments assn)) (and action (action-compatible-with-and-impactful-for-transition? action tctx))) (define (negative-example? program tctx assn) (define ctx (line-transition-start tctx)) (define action (interpret/nondeterministic program (create-environment ctx) #:binding-assignments assn)) (not action)) (define (create-higher-generalization-optimization generalization-set-parameters) (λ (guesser verifiers sktch) so one transition should be new for every previous program (define transitions (eval-with-solver guesser (map symbolic-line-transition generalization-set-parameters))) (define assn (map (λ (_) (??)) (Program-pattern sktch))) (define programs-to-generalize empty) (synthesis-objective-function 'generalization (λ (prog) (dprintf "trying to increase generalization") (set! programs-to-generalize (list prog)) assert that at least one of these transitions is covered by the that is not covered by the found program (solver-assert* guesser (lormap (λ (tctx) (define assn (map (λ (_) (??)) (Program-pattern sktch))) (&& (positive-example? sktch tctx assn) (negative-example? prog tctx assn))) transitions))) (λ (guess) (find-program-uncovered-example verifiers guess programs-to-generalize assn))))) (define (create-lower-cost-optimization) (λ (guesser _ sktch) (synthesis-objective-function 'cost (λ (prog) (define c (program-cost prog)) (dprintf "trying to lower cost below ~a" c) (solver-assert* guesser (< (program-cost sktch) c))) (λ (_) #f)))) (define (synthesize-program #:input ctx #:output actn #:binding bnding #:counter-example-parameters ce-params #:generalization-set-parameters gs-params #:program-eater [eater void] #:optimization-state-update [optimization-state-update void] ) (define (assertfn guesser sktch) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment ctx)) actn))) (define objectives (list (create-higher-generalization-optimization gs-params) (create-lower-cost-optimization))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params #:sketch-parameters (list empty ctx bnding) #:program-eater eater #:optimization-state-update optimization-state-update #:objective-functions objectives)) (define (synthesize-program/no-generalization #:input ctx #:output actn #:binding bnding #:counter-example-parameters ce-params #:program-eater [eater void] #:optimization-state-update [optimization-state-update void] #:debug-force-use-program [forced-program #f] ) (define (assertfn guesser sktch) (when forced-program (solver-assert* guesser (equal? sktch forced-program))) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment ctx)) actn))) (define objectives (list (create-lower-cost-optimization))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params #:sketch-parameters (list empty ctx bnding) #:program-eater eater #:optimization-state-update optimization-state-update #:objective-functions objectives)) (define (synthesize-program/inductive ( listof ( pairof line ? line - action ? ) ) #:input io-examples #:pattern pat #:counter-example-parameters ce-params #:program-eater [eater void]) (local-require (only-in racket for)) (define (assertfn guesser sktch) (for ([pr io-examples]) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment (car pr))) (cdr pr))))) (define objectives (list (create-lower-cost-optimization))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params #:sketch-parameters (list empty (car (first io-examples)) pat) #:program-eater eater #:optimization-state-update void #:objective-functions objectives)) (define (superoptimize-program #:primary-input ctx #:primary-output actn #:program prog #:counter-example-parameters ce-params #:program-eater eater) (define (assertfn guesser sktch) (solver-assert* guesser (< (program-cost sktch) (program-cost prog))) (solver-assert* guesser (equal? (interpret/nondeterministic sktch (create-environment ctx)) actn))) (define objectives (list (create-lower-cost-optimization))) (define cefuncs (list (λ (verifiers) (define assn (map (λ (_) (??)) (Program-pattern prog))) (λ (guess) (find-program-uncovered-example verifiers guess (list prog) assn))))) (synthesize-program-impl assertfn #:counter-example-parameters ce-params #:sketch-parameters (list empty #f (Program-pattern prog)) #:program-eater eater #:counter-example-functions cefuncs #:optimization-state-update void #:objective-functions objectives)) (define (sketch-covers? prog sketch-parameters) (parameterize-solver (define sktch (program-sketch sketch-parameters #f (Program-pattern prog))) (define-syntax-rule (check f) (sat? (solve (assert (equal? (f sktch) (f prog)))))) ( ( check Program - pattern ) ( check Program - condition ) (sat? (solve (assert (equal? sktch prog))))))
5a01f6637cbdde9b1107ff02aa5536073eb37db1fcd9697bca21e3e0d9cd77c0
day8/shadow-git-inject
core.clj
(ns shadow-git-inject.core (:require [clojure.walk :as walk] [clojure.string :as string] [clojure.java.shell :refer [sh]] [clojure.java.io :as io]) (:import (java.io BufferedReader StringReader IOException) (java.time LocalDateTime) (java.time.format DateTimeFormatter)) (:refer-clojure :exclude [boolean?])) (def default-config "The default configuration values." {:git "git" :describe-pattern "(?<tag>.*)-(?<ahead>\\d+)-g(?<ref>[0-9a-f]*)(?<dirty>(-dirty)?)" :version-pattern "^v(\\d+\\.\\d+\\.\\d+)$"}) (defmacro let-groups "Let for binding groups out of a j.u.r.Pattern j.u.r.Matcher." {:style/indent [1]} [[bindings m] & body] (let [s (with-meta (gensym "matcher") {:tag java.util.regex.Matcher})] `(let [~s ~m ~@(mapcat identity (for [b bindings] `[~b (.group ~s ~(name b))]))] ~@body))) Duplicate of clojure.core/boolean ? as it is only available in Clojure 1.9 + (defn boolean? "Return true if x is a Boolean" [x] (instance? Boolean x)) (defn ensure-pattern "Given a string, compiles it to a java.util.regex.Pattern." [x label] (cond (string? x) (re-pattern x) (instance? java.util.regex.Pattern x) x :else (throw (IllegalArgumentException. (str "shadow-git-inject " label " requires a string or a java.util.regex.Pattern!"))))) (defn initial-commit [{:keys [git] :as config}] (let [{:keys [exit out] :as child} (apply sh [git "rev-list" "--max-parents=0" "HEAD"])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) nil) (first (string/split-lines (string/trim out)))))) (defn parse-tags [config out] (reduce (fn [ret line] (if-let [[_ decorations] (re-find #"[0-9a-fA-F]{7} \(([^)]*)\) .*" line)] (reduce (fn [ret decoration] (if-let [[_ tag] (re-find #"tag: ([0-9a-zA-Z`!@#$%&()-_+={}|;'<>,./]+)" decoration)] (conj ret tag) ret)) ret (string/split decorations #",")) ret)) [] (string/split-lines (string/trim out)))) (defn tags [{:keys [git] :as config}] (let [{:keys [exit out] :as child} (apply sh [git "log" "--oneline" "--decorate" "--simplify-by-decoration" "--ancestry-path" (str (initial-commit config) "..HEAD")])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) nil) (parse-tags config out)))) (defn latest-version-tag [{:keys [version-pattern] :as config}] (let [pattern (ensure-pattern version-pattern ":version-pattern")] (first (filter #(re-matches pattern %) (tags config))))) (defn resolve-ref "Fetches the git ref of ref, being a tag or ref name." [{:keys [git] :as config} ref] (let [{:keys [exit out] :as child} (apply sh [git "rev-parse" "--verify" ref])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) nil) (string/trim out)))) (defn parse-describe "Used to parse the output of git-describe, using the configured `describe-pattern`. Returns a map `{:tag, :ahead, :ahead?, :ref, :ref-short, :dirty?}` if the pattern matches, otherwise returns the empty map." [{:keys [describe-pattern] :as config} out] (let [pattern (ensure-pattern describe-pattern ":describe-pattern") matcher (re-matcher pattern out)] (if-not (.matches matcher) (do (binding [*out* *err*] (printf (str "Warning: shadow-git-inject couldn't match the current repo status:\n%s\n\n" "Against pattern:\n%s\n\n") (pr-str out) pattern) (.flush *out*)) {}) (let-groups [[tag ahead ref dirty] matcher] {:tag tag :ahead (Integer/parseInt ahead) :ahead? (not= ahead "0") :ref (resolve-ref config "HEAD") :ref-short ref :dirty? (not= "" dirty)})))) (defn describe "Uses git-describe to parse the status of the repository. Using the configured `git` and `describe-pattern` to parse the output. Returns a map `{:tag, :ahead, :ahead?, :ref, :ref-short, :dirty?}` if the pattern matches, otherwise returns the empty map." [{:keys [git] :as config}] (let [version-tag (latest-version-tag config)] (if-not version-tag {} (let [{:keys [exit out] :as child} (apply sh [git "describe" "--tags" "--dirty" "--long" "--match" version-tag])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) {}) (parse-describe config (string/trim out))))))) (defn git-status-to-version [{:keys [version-pattern ignore-dirty?] :as config}] (try (let [{:keys [tag ahead ahead? dirty? ref-short]} (describe config) ignore-dirty?' (cond (and (keyword? ignore-dirty?) (= (namespace ignore-dirty?) "env")) (= "true" (System/getenv (string/upper-case (name ignore-dirty?)))) (boolean? ignore-dirty?) ignore-dirty? :default false)] (if-not (string? tag) ;; If git status is nil (e.g. IntelliJ evaluating project.clj): "git-version-tag-not-found" (let [[_ version] (re-find (re-pattern version-pattern) tag)] (if (and (not ahead?) (or ignore-dirty?' (not dirty?))) ;; If this is a release version: version (str version "-" ahead "-" ref-short "-SNAPSHOT"))))) (catch IOException _ ;; If git binary is not available (e.g. not in path): "git-command-not-found"))) (def x->f {:shadow-git-inject/build-iso-date-time (fn [_] (.format (LocalDateTime/now) DateTimeFormatter/ISO_DATE_TIME)) :shadow-git-inject/build-iso-week-date (fn [_] (.format (LocalDateTime/now) DateTimeFormatter/ISO_WEEK_DATE)) :shadow-git-inject/version git-status-to-version :shadow-git-inject/username (fn [_] (System/getProperty "user.name"))}) (defn inject [state config] (walk/prewalk (fn [x] (reduce-kv (fn [ret k f] (cond (keyword? x) (if (= x k) (f config) ret) (string? x) (let [s (str (namespace k) "/" (name k))] (if (string/includes? x s) (string/replace x (re-pattern s) (f config)) ret)) :default ret)) x x->f)) state)) (defn hook {:shadow.build/stage :configure} [{:keys [git-inject] :as build-state} & args] (let [config (merge default-config git-inject)] (update-in build-state [:compiler-options :closure-defines] inject config)))
null
https://raw.githubusercontent.com/day8/shadow-git-inject/3991b82d65fb3316306847d226f4bf488444735e/src/shadow_git_inject/core.clj
clojure
If git status is nil (e.g. IntelliJ evaluating project.clj): If this is a release version: If git binary is not available (e.g. not in path):
(ns shadow-git-inject.core (:require [clojure.walk :as walk] [clojure.string :as string] [clojure.java.shell :refer [sh]] [clojure.java.io :as io]) (:import (java.io BufferedReader StringReader IOException) (java.time LocalDateTime) (java.time.format DateTimeFormatter)) (:refer-clojure :exclude [boolean?])) (def default-config "The default configuration values." {:git "git" :describe-pattern "(?<tag>.*)-(?<ahead>\\d+)-g(?<ref>[0-9a-f]*)(?<dirty>(-dirty)?)" :version-pattern "^v(\\d+\\.\\d+\\.\\d+)$"}) (defmacro let-groups "Let for binding groups out of a j.u.r.Pattern j.u.r.Matcher." {:style/indent [1]} [[bindings m] & body] (let [s (with-meta (gensym "matcher") {:tag java.util.regex.Matcher})] `(let [~s ~m ~@(mapcat identity (for [b bindings] `[~b (.group ~s ~(name b))]))] ~@body))) Duplicate of clojure.core/boolean ? as it is only available in Clojure 1.9 + (defn boolean? "Return true if x is a Boolean" [x] (instance? Boolean x)) (defn ensure-pattern "Given a string, compiles it to a java.util.regex.Pattern." [x label] (cond (string? x) (re-pattern x) (instance? java.util.regex.Pattern x) x :else (throw (IllegalArgumentException. (str "shadow-git-inject " label " requires a string or a java.util.regex.Pattern!"))))) (defn initial-commit [{:keys [git] :as config}] (let [{:keys [exit out] :as child} (apply sh [git "rev-list" "--max-parents=0" "HEAD"])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) nil) (first (string/split-lines (string/trim out)))))) (defn parse-tags [config out] (reduce (fn [ret line] (if-let [[_ decorations] (re-find #"[0-9a-fA-F]{7} \(([^)]*)\) .*" line)] (reduce (fn [ret decoration] (if-let [[_ tag] (re-find #"tag: ([0-9a-zA-Z`!@#$%&()-_+={}|;'<>,./]+)" decoration)] (conj ret tag) ret)) ret (string/split decorations #",")) ret)) [] (string/split-lines (string/trim out)))) (defn tags [{:keys [git] :as config}] (let [{:keys [exit out] :as child} (apply sh [git "log" "--oneline" "--decorate" "--simplify-by-decoration" "--ancestry-path" (str (initial-commit config) "..HEAD")])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) nil) (parse-tags config out)))) (defn latest-version-tag [{:keys [version-pattern] :as config}] (let [pattern (ensure-pattern version-pattern ":version-pattern")] (first (filter #(re-matches pattern %) (tags config))))) (defn resolve-ref "Fetches the git ref of ref, being a tag or ref name." [{:keys [git] :as config} ref] (let [{:keys [exit out] :as child} (apply sh [git "rev-parse" "--verify" ref])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) nil) (string/trim out)))) (defn parse-describe "Used to parse the output of git-describe, using the configured `describe-pattern`. Returns a map `{:tag, :ahead, :ahead?, :ref, :ref-short, :dirty?}` if the pattern matches, otherwise returns the empty map." [{:keys [describe-pattern] :as config} out] (let [pattern (ensure-pattern describe-pattern ":describe-pattern") matcher (re-matcher pattern out)] (if-not (.matches matcher) (do (binding [*out* *err*] (printf (str "Warning: shadow-git-inject couldn't match the current repo status:\n%s\n\n" "Against pattern:\n%s\n\n") (pr-str out) pattern) (.flush *out*)) {}) (let-groups [[tag ahead ref dirty] matcher] {:tag tag :ahead (Integer/parseInt ahead) :ahead? (not= ahead "0") :ref (resolve-ref config "HEAD") :ref-short ref :dirty? (not= "" dirty)})))) (defn describe "Uses git-describe to parse the status of the repository. Using the configured `git` and `describe-pattern` to parse the output. Returns a map `{:tag, :ahead, :ahead?, :ref, :ref-short, :dirty?}` if the pattern matches, otherwise returns the empty map." [{:keys [git] :as config}] (let [version-tag (latest-version-tag config)] (if-not version-tag {} (let [{:keys [exit out] :as child} (apply sh [git "describe" "--tags" "--dirty" "--long" "--match" version-tag])] (if-not (= exit 0) (binding [*out* *err*] (printf "Warning: shadow-git-inject git exited %d\n%s\n\n" exit child) (.flush *out*) {}) (parse-describe config (string/trim out))))))) (defn git-status-to-version [{:keys [version-pattern ignore-dirty?] :as config}] (try (let [{:keys [tag ahead ahead? dirty? ref-short]} (describe config) ignore-dirty?' (cond (and (keyword? ignore-dirty?) (= (namespace ignore-dirty?) "env")) (= "true" (System/getenv (string/upper-case (name ignore-dirty?)))) (boolean? ignore-dirty?) ignore-dirty? :default false)] (if-not (string? tag) "git-version-tag-not-found" (let [[_ version] (re-find (re-pattern version-pattern) tag)] (if (and (not ahead?) (or ignore-dirty?' (not dirty?))) version (str version "-" ahead "-" ref-short "-SNAPSHOT"))))) (catch IOException _ "git-command-not-found"))) (def x->f {:shadow-git-inject/build-iso-date-time (fn [_] (.format (LocalDateTime/now) DateTimeFormatter/ISO_DATE_TIME)) :shadow-git-inject/build-iso-week-date (fn [_] (.format (LocalDateTime/now) DateTimeFormatter/ISO_WEEK_DATE)) :shadow-git-inject/version git-status-to-version :shadow-git-inject/username (fn [_] (System/getProperty "user.name"))}) (defn inject [state config] (walk/prewalk (fn [x] (reduce-kv (fn [ret k f] (cond (keyword? x) (if (= x k) (f config) ret) (string? x) (let [s (str (namespace k) "/" (name k))] (if (string/includes? x s) (string/replace x (re-pattern s) (f config)) ret)) :default ret)) x x->f)) state)) (defn hook {:shadow.build/stage :configure} [{:keys [git-inject] :as build-state} & args] (let [config (merge default-config git-inject)] (update-in build-state [:compiler-options :closure-defines] inject config)))
1d8eef6f902f52e8a924242337ef6c15748aaeed11789e300af6327419453041
rmloveland/scheme48-0.53
mini-command.scm
Copyright ( c ) 1993 - 1999 by and . See file COPYING . ; Miniature command processor. (define (command-processor ignore args) (let ((in (current-input-port)) (out (current-output-port)) (err (current-error-port)) (batch? (member "batch" args))) (let loop () ((call-with-current-continuation (lambda (go) (with-handler (lambda (c punt) (cond ((or (error? c) (interrupt? c)) (display-condition c err) (go (if batch? (lambda () 1) loop))) ((warning? c) (display-condition c err)) (else (punt)))) (lambda () (if (not batch?) (display "- " out)) (let ((form (read in))) (cond ((eof-object? form) (newline out) (go (lambda () 0))) ((and (pair? form) (eq? (car form) 'unquote)) (case (cadr form) ((load) (mini-load in) (go loop)) ((go) (let ((form (read in))) (go (lambda () (eval form (interaction-environment)))))) (else (error "unknown command" (cadr form))))) (else (call-with-values (lambda () (eval form (interaction-environment))) (lambda results (for-each (lambda (result) (write result out) (newline out)) results) (go loop)))))))))))))) (define (mini-load in) (let ((c (peek-char in))) (cond ((char=? c #\newline) (read-char in) #t) ((char-whitespace? c) (read-char in) (mini-load in)) (else (let ((filename (read-string in char-whitespace?))) (load filename) (mini-load in)))))) (define (read-string port delimiter?) (let loop ((l '()) (n 0)) (let ((c (peek-char port))) (cond ((or (eof-object? c) (delimiter? c)) (list->string (reverse l))) (else (loop (cons (read-char port) l) (+ n 1)))))))
null
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/scheme/debug/mini-command.scm
scheme
Miniature command processor.
Copyright ( c ) 1993 - 1999 by and . See file COPYING . (define (command-processor ignore args) (let ((in (current-input-port)) (out (current-output-port)) (err (current-error-port)) (batch? (member "batch" args))) (let loop () ((call-with-current-continuation (lambda (go) (with-handler (lambda (c punt) (cond ((or (error? c) (interrupt? c)) (display-condition c err) (go (if batch? (lambda () 1) loop))) ((warning? c) (display-condition c err)) (else (punt)))) (lambda () (if (not batch?) (display "- " out)) (let ((form (read in))) (cond ((eof-object? form) (newline out) (go (lambda () 0))) ((and (pair? form) (eq? (car form) 'unquote)) (case (cadr form) ((load) (mini-load in) (go loop)) ((go) (let ((form (read in))) (go (lambda () (eval form (interaction-environment)))))) (else (error "unknown command" (cadr form))))) (else (call-with-values (lambda () (eval form (interaction-environment))) (lambda results (for-each (lambda (result) (write result out) (newline out)) results) (go loop)))))))))))))) (define (mini-load in) (let ((c (peek-char in))) (cond ((char=? c #\newline) (read-char in) #t) ((char-whitespace? c) (read-char in) (mini-load in)) (else (let ((filename (read-string in char-whitespace?))) (load filename) (mini-load in)))))) (define (read-string port delimiter?) (let loop ((l '()) (n 0)) (let ((c (peek-char port))) (cond ((or (eof-object? c) (delimiter? c)) (list->string (reverse l))) (else (loop (cons (read-char port) l) (+ n 1)))))))
5965ced8b1645582fc0863a00146b1a1e30fd3d4eb51672186851a6c1bfb15c4
rwmjones/guestfs-tools
utils.ml
virt - builder * Copyright ( C ) 2013 - 2023 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License along * with this program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2013-2023 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) Utilities / common functions used in virt - builder only . open Printf open Std_utils open Tools_utils type gpgkey_type = | No_Key | Fingerprint of string | KeyFile of string and revision = | Rev_int of int | Rev_string of string let string_of_revision = function | Rev_int n -> string_of_int n | Rev_string s -> s let increment_revision = function | Rev_int n -> Rev_int (n + 1) | Rev_string s -> Rev_int ((int_of_string s) + 1) let get_image_infos filepath = let qemuimg_cmd = "qemu-img info --output json " ^ quote filepath in let lines = external_command qemuimg_cmd in let line = String.concat "\n" lines in JSON_parser.json_parser_tree_parse line
null
https://raw.githubusercontent.com/rwmjones/guestfs-tools/57423d907270526ea664ff15601cce956353820e/builder/utils.ml
ocaml
virt - builder * Copyright ( C ) 2013 - 2023 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License along * with this program ; if not , write to the Free Software Foundation , Inc. , * 51 Franklin Street , Fifth Floor , Boston , USA . * Copyright (C) 2013-2023 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *) Utilities / common functions used in virt - builder only . open Printf open Std_utils open Tools_utils type gpgkey_type = | No_Key | Fingerprint of string | KeyFile of string and revision = | Rev_int of int | Rev_string of string let string_of_revision = function | Rev_int n -> string_of_int n | Rev_string s -> s let increment_revision = function | Rev_int n -> Rev_int (n + 1) | Rev_string s -> Rev_int ((int_of_string s) + 1) let get_image_infos filepath = let qemuimg_cmd = "qemu-img info --output json " ^ quote filepath in let lines = external_command qemuimg_cmd in let line = String.concat "\n" lines in JSON_parser.json_parser_tree_parse line
275bc00e94a79db58f2f77d75d33803e21a923396b1f87e64da467246899f437
haskell-mafia/projector
Haskell.hs
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TupleSections # module Projector.Html.Backend.Haskell ( haskellBackend --- , renderModule , renderExpr , predicates , HaskellError (..) , renderHaskellError -- * guts , genModule , genTypeDecs , genTypeDec , genExpDec , genType , genExp , genMatch , genPat , genLit ) where import qualified Data.Char as Char import qualified Data.Map.Strict as M import Data.Set (Set) import qualified Data.Set as S import qualified Data.Text as T import qualified Language.Haskell.TH as TH import P import Projector.Core import Projector.Html.Core import Projector.Html.Core.Library import Projector.Html.Data.Backend hiding (Backend(..)) import qualified Projector.Html.Data.Backend as BE import Projector.Html.Data.Module import Projector.Html.Data.Prim import Projector.Html.Backend.Haskell.Prim import Projector.Html.Backend.Haskell.Rewrite import System.IO (FilePath) import X.Language.Haskell.TH.Syntax haskellBackend :: BE.Backend a HaskellError haskellBackend = BE.Backend { BE.renderModule = renderModule , BE.renderExpr = renderExpr , BE.predicates = predicates } -- ----------------------------------------------------------------------------- data HaskellError TODO should really return decorated parameterised error here | RecordTypeInvariant | TypeHolePresent deriving (Eq, Ord, Show) renderHaskellError :: HaskellError -> Text renderHaskellError e = case e of HtmlCase -> "Don't case on Html, pal!" RecordTypeInvariant -> "BUG: Invariant failure - expected a record type, but found something else." TypeHolePresent -> "BUG: Type hole was present for code generation. Should have been a type error." predicates :: [Predicate HaskellError] predicates = [ PatPredicate $ \case PCon _ c _ -> if S.member c htmlConstructors then PredError HtmlCase else PredOk _ -> PredOk ] -- | The set of constructors used for the Html library type. htmlConstructors :: Set Constructor htmlConstructors = fold [ sumCons dHtml , sumCons dTag , sumCons dAttribute , sumCons dAttributeKey , sumCons dAttributeValue ] where sumCons x = case x of DVariant _ps cts -> S.fromList (fmap fst cts) DRecord _ps _ -> mempty -- ----------------------------------------------------------------------------- renderModule :: HtmlDecls -> ModuleName -> Module HtmlType PrimT (HtmlType, a) -> Either HaskellError (FilePath, Text) renderModule _decls mn@(ModuleName n) m = do let pragmas = [ "{-# LANGUAGE NoImplicitPrelude #-}" , "{-# LANGUAGE OverloadedStrings #-}" , "{-# OPTIONS_GHC -fno-warn-unused-imports #-}" -- FIX This is because of each introducing a lambda with a constant variable "x" -- We should be writing the tree to stop shadowing in the output , "{-# OPTIONS_GHC -fno-warn-name-shadowing #-}" ] (_mn', m') = second toHaskellModule (rewriteModule mn m) modName = T.unwords ["module", n, "where"] importText = fmap (uncurry genImport) imports imports = (htmlRuntime, ImportQualified) : M.toList (moduleImports m') decls <- fmap (fmap (T.pack . TH.pprint)) (genModule m') pure (genFileName mn, T.unlines $ mconcat [ pragmas , [modName] , importText , decls ]) renderExpr :: HtmlDecls -> Name -> HtmlExpr (HtmlType, a) -> Either HaskellError Text renderExpr _decls n = fmap (T.pack . TH.pprint) . genExpDec n . toHaskellExpr . rewriteExpr genImport :: ModuleName -> Imports -> Text genImport (ModuleName n) imports = case imports of OpenImport -> "import " <> n OnlyImport funs -> "import " <> n <> " (" <> T.intercalate ", " (fmap unName funs) <> ")" ImportQualified -> "import qualified " <> n ImportQualifiedAs (ModuleName mn) -> "import qualified " <> n <> " as " <> mn genModule :: HaskellModule (HtmlType, a) -> Either HaskellError [TH.Dec] genModule (Module ts _ es) = do let tdecs = genTypeDecs ts decs <- for (M.toList es) $ \(n, ModuleExpr ty e) -> do d <- genExpDec n e pure [genTypeSig n ty, d] pure (tdecs <> fold decs) genFileName :: ModuleName -> FilePath genFileName (ModuleName n) = T.unpack (T.replace "." "/" n) <> ".hs" htmlRuntime :: ModuleName htmlRuntime = ModuleName "Projector.Html.Runtime" -- ----------------------------------------------------------------------------- -- | Type declarations. -- This should be done via eventually . -- They shouldn't even be a field in 'Module'. -- We only use this for testing: we generate a lot of datatypes for our expressions. genTypeDecs :: HaskellDecls -> [TH.Dec] genTypeDecs = fmap (uncurry genTypeDec) . M.toList . unTypeDecls genTypeDec :: TypeName -> HaskellDecl -> TH.Dec genTypeDec (TypeName n) ty = case ty of DVariant ps cts -> data_ (mkName_ n) (fmap (mkName_ . unTypeName) ps) (fmap (uncurry genCon) cts) DRecord ps fts -> data_ (mkName_ n) (fmap (mkName_ . unTypeName) ps) [recordCon (Constructor n) fts] -- | Constructor declarations. genCon :: Constructor -> [HaskellType] -> TH.Con genCon (Constructor n) ts = normalC_' (mkName_ n) (fmap genType ts) -- | Record declarations. recordCon :: Constructor -> [(FieldName, HaskellType)] -> TH.Con recordCon c@(Constructor n) fts = recC_' (mkName_ n) (fmap (uncurry (genRecordField c)) fts) genRecordField :: Constructor -> FieldName -> HaskellType -> (TH.Name, TH.Type) genRecordField c fn ft = (fieldNameHeuristic c fn, genType ft) -- | Decide on a field name. TODO this should probably be customisable . TODO this has to line up with machinator , dedupe needed fieldNameHeuristic :: Constructor -> FieldName -> TH.Name fieldNameHeuristic (Constructor c) (FieldName n) = mkName_ (T.singleton (Char.toLower (T.head c)) <> T.drop 1 c <> (T.toTitle n)) -- | Types. genType :: HaskellType -> TH.Type genType (Type ty) = case ty of TLitF l -> conT (mkName_ (ppGroundType l)) TVarF (TypeName n) -> conT (mkName_ n) TArrowF t1 t2 -> arrowT_ (genType t1) (genType t2) TAppF t1 t2 -> appT (genType t1) (genType t2) TListF t -> listT_ (genType t) TForallF _ts t1 -> -- Abuse implicit foralls genType t1 -- ----------------------------------------------------------------------------- -- | Expression declarations. genExpDec :: Name -> HaskellExpr (HtmlType, a) -> Either HaskellError TH.Dec genExpDec (Name n) expr = val_ (varP (mkName_ n)) <$> genExp expr genTypeSig :: Name -> HaskellType -> TH.Dec genTypeSig (Name n) ty = sig (mkName_ n) (genType ty) -- | Expressions. genExp :: HaskellExpr (HtmlType, a) -> Either HaskellError TH.Exp genExp expr = case expr of ELit _ v -> pure (litE (genLit v)) EVar _ (Name x) -> pure (varE (mkName_ x)) ELam _ (Name n) _ body -> lamE [varP (mkName_ n)] <$> genExp body EApp _ fun arg -> appE <$> genExp fun <*> genExp arg ECon _ (Constructor c) _ es -> applyE (conE (mkName_ c)) <$> traverse genExp es ECase _ e pats -> caseE <$> genExp e <*> traverse (uncurry genMatch) pats ERec _ (TypeName tn) fes -> do recConE (mkName_ tn) <$> traverse (\(fn, fe) -> (fieldNameHeuristic (Constructor tn) fn,) <$> genExp fe) fes EPrj _ e fn -> genRecordPrj e fn EList _ es -> listE <$> traverse genExp es EForeign _ (Name x) _ -> pure (varE (mkName_ x)) EMap _ f g -> do f' <- genExp f g' <- genExp g pure (applyE (varE (mkName_ "Projector.Html.Runtime.fmap")) [f', g']) EHole _ -> Left TypeHolePresent | Compile a Projector record projection to Haskell . -- -- This is type-directed, unlike everything else in this compiler! -- We need to look at the type of the expr, and use it to apply 'fieldNameHeuristic'. -- -- This is partial, but the failing branch can only occur if the -- typechecker doesn't work. genRecordPrj :: HaskellExpr (HtmlType, a) -> FieldName -> Either HaskellError TH.Exp genRecordPrj e fn = case extractAnnotation e of (TVar (TypeName recName), _) -> appE (varE (fieldNameHeuristic (Constructor recName) fn)) <$> genExp e (_, _) -> Left RecordTypeInvariant -- | Case alternatives. genMatch :: Pattern (HtmlType, a) -> HaskellExpr (HtmlType, a) -> Either HaskellError TH.Match genMatch p e = match_ (genPat p) <$> genExp e -- | Patterns. genPat :: Pattern (HtmlType, a) -> TH.Pat genPat p = case p of PVar _ (Name n) -> varP (mkName_ n) PCon _ (Constructor n) ps -> conP (mkName_ n) (fmap genPat ps) PWildcard _ -> varP (mkName_ "_") -- | Literals. genLit :: Value HaskellPrimT -> TH.Lit genLit v = case v of HTextV x -> stringL_ x
null
https://raw.githubusercontent.com/haskell-mafia/projector/6af7c7f1e8a428b14c2c5a508f7d4a3ac2decd52/projector-html-haskell/src/Projector/Html/Backend/Haskell.hs
haskell
# LANGUAGE OverloadedStrings # - * guts ----------------------------------------------------------------------------- | The set of constructors used for the Html library type. ----------------------------------------------------------------------------- FIX This is because of each introducing a lambda with a constant variable "x" We should be writing the tree to stop shadowing in the output ----------------------------------------------------------------------------- | Type declarations. They shouldn't even be a field in 'Module'. We only use this for testing: we generate a lot of datatypes for our expressions. | Constructor declarations. | Record declarations. | Decide on a field name. | Types. Abuse implicit foralls ----------------------------------------------------------------------------- | Expression declarations. | Expressions. This is type-directed, unlike everything else in this compiler! We need to look at the type of the expr, and use it to apply 'fieldNameHeuristic'. This is partial, but the failing branch can only occur if the typechecker doesn't work. | Case alternatives. | Patterns. | Literals.
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE NoImplicitPrelude # # LANGUAGE TupleSections # module Projector.Html.Backend.Haskell ( haskellBackend , renderModule , renderExpr , predicates , HaskellError (..) , renderHaskellError , genModule , genTypeDecs , genTypeDec , genExpDec , genType , genExp , genMatch , genPat , genLit ) where import qualified Data.Char as Char import qualified Data.Map.Strict as M import Data.Set (Set) import qualified Data.Set as S import qualified Data.Text as T import qualified Language.Haskell.TH as TH import P import Projector.Core import Projector.Html.Core import Projector.Html.Core.Library import Projector.Html.Data.Backend hiding (Backend(..)) import qualified Projector.Html.Data.Backend as BE import Projector.Html.Data.Module import Projector.Html.Data.Prim import Projector.Html.Backend.Haskell.Prim import Projector.Html.Backend.Haskell.Rewrite import System.IO (FilePath) import X.Language.Haskell.TH.Syntax haskellBackend :: BE.Backend a HaskellError haskellBackend = BE.Backend { BE.renderModule = renderModule , BE.renderExpr = renderExpr , BE.predicates = predicates } data HaskellError TODO should really return decorated parameterised error here | RecordTypeInvariant | TypeHolePresent deriving (Eq, Ord, Show) renderHaskellError :: HaskellError -> Text renderHaskellError e = case e of HtmlCase -> "Don't case on Html, pal!" RecordTypeInvariant -> "BUG: Invariant failure - expected a record type, but found something else." TypeHolePresent -> "BUG: Type hole was present for code generation. Should have been a type error." predicates :: [Predicate HaskellError] predicates = [ PatPredicate $ \case PCon _ c _ -> if S.member c htmlConstructors then PredError HtmlCase else PredOk _ -> PredOk ] htmlConstructors :: Set Constructor htmlConstructors = fold [ sumCons dHtml , sumCons dTag , sumCons dAttribute , sumCons dAttributeKey , sumCons dAttributeValue ] where sumCons x = case x of DVariant _ps cts -> S.fromList (fmap fst cts) DRecord _ps _ -> mempty renderModule :: HtmlDecls -> ModuleName -> Module HtmlType PrimT (HtmlType, a) -> Either HaskellError (FilePath, Text) renderModule _decls mn@(ModuleName n) m = do let pragmas = [ "{-# LANGUAGE NoImplicitPrelude #-}" , "{-# LANGUAGE OverloadedStrings #-}" , "{-# OPTIONS_GHC -fno-warn-unused-imports #-}" , "{-# OPTIONS_GHC -fno-warn-name-shadowing #-}" ] (_mn', m') = second toHaskellModule (rewriteModule mn m) modName = T.unwords ["module", n, "where"] importText = fmap (uncurry genImport) imports imports = (htmlRuntime, ImportQualified) : M.toList (moduleImports m') decls <- fmap (fmap (T.pack . TH.pprint)) (genModule m') pure (genFileName mn, T.unlines $ mconcat [ pragmas , [modName] , importText , decls ]) renderExpr :: HtmlDecls -> Name -> HtmlExpr (HtmlType, a) -> Either HaskellError Text renderExpr _decls n = fmap (T.pack . TH.pprint) . genExpDec n . toHaskellExpr . rewriteExpr genImport :: ModuleName -> Imports -> Text genImport (ModuleName n) imports = case imports of OpenImport -> "import " <> n OnlyImport funs -> "import " <> n <> " (" <> T.intercalate ", " (fmap unName funs) <> ")" ImportQualified -> "import qualified " <> n ImportQualifiedAs (ModuleName mn) -> "import qualified " <> n <> " as " <> mn genModule :: HaskellModule (HtmlType, a) -> Either HaskellError [TH.Dec] genModule (Module ts _ es) = do let tdecs = genTypeDecs ts decs <- for (M.toList es) $ \(n, ModuleExpr ty e) -> do d <- genExpDec n e pure [genTypeSig n ty, d] pure (tdecs <> fold decs) genFileName :: ModuleName -> FilePath genFileName (ModuleName n) = T.unpack (T.replace "." "/" n) <> ".hs" htmlRuntime :: ModuleName htmlRuntime = ModuleName "Projector.Html.Runtime" This should be done via eventually . genTypeDecs :: HaskellDecls -> [TH.Dec] genTypeDecs = fmap (uncurry genTypeDec) . M.toList . unTypeDecls genTypeDec :: TypeName -> HaskellDecl -> TH.Dec genTypeDec (TypeName n) ty = case ty of DVariant ps cts -> data_ (mkName_ n) (fmap (mkName_ . unTypeName) ps) (fmap (uncurry genCon) cts) DRecord ps fts -> data_ (mkName_ n) (fmap (mkName_ . unTypeName) ps) [recordCon (Constructor n) fts] genCon :: Constructor -> [HaskellType] -> TH.Con genCon (Constructor n) ts = normalC_' (mkName_ n) (fmap genType ts) recordCon :: Constructor -> [(FieldName, HaskellType)] -> TH.Con recordCon c@(Constructor n) fts = recC_' (mkName_ n) (fmap (uncurry (genRecordField c)) fts) genRecordField :: Constructor -> FieldName -> HaskellType -> (TH.Name, TH.Type) genRecordField c fn ft = (fieldNameHeuristic c fn, genType ft) TODO this should probably be customisable . TODO this has to line up with machinator , dedupe needed fieldNameHeuristic :: Constructor -> FieldName -> TH.Name fieldNameHeuristic (Constructor c) (FieldName n) = mkName_ (T.singleton (Char.toLower (T.head c)) <> T.drop 1 c <> (T.toTitle n)) genType :: HaskellType -> TH.Type genType (Type ty) = case ty of TLitF l -> conT (mkName_ (ppGroundType l)) TVarF (TypeName n) -> conT (mkName_ n) TArrowF t1 t2 -> arrowT_ (genType t1) (genType t2) TAppF t1 t2 -> appT (genType t1) (genType t2) TListF t -> listT_ (genType t) TForallF _ts t1 -> genType t1 genExpDec :: Name -> HaskellExpr (HtmlType, a) -> Either HaskellError TH.Dec genExpDec (Name n) expr = val_ (varP (mkName_ n)) <$> genExp expr genTypeSig :: Name -> HaskellType -> TH.Dec genTypeSig (Name n) ty = sig (mkName_ n) (genType ty) genExp :: HaskellExpr (HtmlType, a) -> Either HaskellError TH.Exp genExp expr = case expr of ELit _ v -> pure (litE (genLit v)) EVar _ (Name x) -> pure (varE (mkName_ x)) ELam _ (Name n) _ body -> lamE [varP (mkName_ n)] <$> genExp body EApp _ fun arg -> appE <$> genExp fun <*> genExp arg ECon _ (Constructor c) _ es -> applyE (conE (mkName_ c)) <$> traverse genExp es ECase _ e pats -> caseE <$> genExp e <*> traverse (uncurry genMatch) pats ERec _ (TypeName tn) fes -> do recConE (mkName_ tn) <$> traverse (\(fn, fe) -> (fieldNameHeuristic (Constructor tn) fn,) <$> genExp fe) fes EPrj _ e fn -> genRecordPrj e fn EList _ es -> listE <$> traverse genExp es EForeign _ (Name x) _ -> pure (varE (mkName_ x)) EMap _ f g -> do f' <- genExp f g' <- genExp g pure (applyE (varE (mkName_ "Projector.Html.Runtime.fmap")) [f', g']) EHole _ -> Left TypeHolePresent | Compile a Projector record projection to Haskell . genRecordPrj :: HaskellExpr (HtmlType, a) -> FieldName -> Either HaskellError TH.Exp genRecordPrj e fn = case extractAnnotation e of (TVar (TypeName recName), _) -> appE (varE (fieldNameHeuristic (Constructor recName) fn)) <$> genExp e (_, _) -> Left RecordTypeInvariant genMatch :: Pattern (HtmlType, a) -> HaskellExpr (HtmlType, a) -> Either HaskellError TH.Match genMatch p e = match_ (genPat p) <$> genExp e genPat :: Pattern (HtmlType, a) -> TH.Pat genPat p = case p of PVar _ (Name n) -> varP (mkName_ n) PCon _ (Constructor n) ps -> conP (mkName_ n) (fmap genPat ps) PWildcard _ -> varP (mkName_ "_") genLit :: Value HaskellPrimT -> TH.Lit genLit v = case v of HTextV x -> stringL_ x
a51f118bf98c1a3a849bbfe4c655b8c422085da369d067ee5181e279d1a30118
3b/cl-opengl
tess.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; tess.lisp --- Lisp version of tess.c (Red Book examples) ;;; ;;; Original C version contains the following copyright notice: Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc. ;;; ALL RIGHTS RESERVED ;;; ;;; This program demonstrates polygon tessellation. Two tesselated objects are drawn . The first is a rectangle with a triangular hole . The second is a ;;; smooth shaded, self-intersecting star. ;;; ;;; Note the exterior rectangle is drawn with its vertices ;;; in counter-clockwise order, but its interior clockwise. ;;; Note the combineCallback is needed for the self-intersecting star . Also note that removing the TessProperty for the ;;; star will make the interior unshaded (WINDING_ODD). (in-package #:cl-glut-examples) (defclass tess-window (glut:window) ((start-list :accessor start-list)) (:default-initargs :width 500 :height 500 :title "tess.lisp" :mode '(:single :rgb))) (defclass example-tessellator (glu:tessellator) ()) (defclass star-tessellator (glu:tessellator) ()) (defmethod glut:display-window :before ((window tess-window)) (let ((tobj (make-instance 'example-tessellator)) (rect '((50 50 0) (200 50 0) (200 200 0) (50 200 0))) (tri '((75 75 0) (125 175 0) (175 75 0))) (star '((250 50 0 1 0 1) (325 200 0 1 1 0) (400 50 0 0 1 1) (250 150 0 1 0 0) (400 150 0 0 1 0)))) (gl:clear-color 0 0 0 0) (setf (start-list window) (gl:gen-lists 2)) ;; need to initialize tess property in case it is messed up (glu:tess-property tobj :winding-rule :positive) ;;rectangle with triangular hole inside (gl:with-new-list ((start-list window) :compile) (gl:shade-model :flat) (glu:with-tess-polygon (tobj) (glu:with-tess-contour tobj (loop for coords in rect do (glu:tess-vertex tobj coords coords))) (glu:with-tess-contour tobj (loop for coords in tri do (glu:tess-vertex tobj coords coords))))) (glu:tess-delete tobj) ;;smooth shaded, self-intersecting star (setf tobj (make-instance 'star-tessellator)) (gl:with-new-list ((1+ (start-list window)) :compile) (gl:shade-model :smooth) (glu:tess-property tobj :winding-rule :positive) (glu:with-tess-polygon (tobj) (glu:with-tess-contour tobj (loop for coords in star do (glu:tess-vertex tobj coords coords))))) (glu:tess-delete tobj))) (defmethod glut:display ((window tess-window)) (gl:clear :color-buffer) (gl:color 1 1 1) (gl:call-list (start-list window)) (gl:call-list (1+ (start-list window))) (gl:flush)) (defmethod glut:reshape ((w tess-window) width height) (gl:viewport 0 0 width height) (gl:matrix-mode :projection) (gl:load-identity) (glu:ortho-2d 0 width 0 height)) (defmethod glut:keyboard ((w tess-window) key x y) (declare (ignore x y)) (when (eql key #\Esc) (glut:destroy-current-window))) (defmethod glu:vertex-data-callback ((tess example-tessellator) vertex-data polygon-data) (gl:vertex (first vertex-data) (second vertex-data) (third vertex-data))) (defmethod glu:vertex-data-callback ((tess star-tessellator) vertex-data polygon-data) (gl:color (fourth vertex-data) (fifth vertex-data) (sixth vertex-data)) (gl:vertex (first vertex-data) (second vertex-data) (third vertex-data))) (defmethod glu:combine-data-callback ((tess star-tessellator) coords vertex-data weight polygon-data) (nconc (loop for i from 0 below 3 collect (gl:glaref coords i)) (loop for i from 3 below 6 collect (+ (* (gl:glaref weight 0) (nth i (aref vertex-data 0))) (* (gl:glaref weight 1) (nth i (aref vertex-data 1))) (* (gl:glaref weight 2) (nth i (aref vertex-data 2))) (* (gl:glaref weight 3) (nth i (aref vertex-data 3))))))) (defun rb-tess () (glut:display-window (make-instance 'tess-window)))
null
https://raw.githubusercontent.com/3b/cl-opengl/e2d83e0977b7e7ac3f3d348d8ccc7ccd04e74d59/examples/redbook/tess.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- tess.lisp --- Lisp version of tess.c (Red Book examples) Original C version contains the following copyright notice: ALL RIGHTS RESERVED This program demonstrates polygon tessellation. smooth shaded, self-intersecting star. Note the exterior rectangle is drawn with its vertices in counter-clockwise order, but its interior clockwise. Note the combineCallback is needed for the self-intersecting star will make the interior unshaded (WINDING_ODD). need to initialize tess property in case it is messed up rectangle with triangular hole inside smooth shaded, self-intersecting star
Copyright ( c ) 1993 - 1997 , Silicon Graphics , Inc. Two tesselated objects are drawn . The first is a rectangle with a triangular hole . The second is a star . Also note that removing the TessProperty for the (in-package #:cl-glut-examples) (defclass tess-window (glut:window) ((start-list :accessor start-list)) (:default-initargs :width 500 :height 500 :title "tess.lisp" :mode '(:single :rgb))) (defclass example-tessellator (glu:tessellator) ()) (defclass star-tessellator (glu:tessellator) ()) (defmethod glut:display-window :before ((window tess-window)) (let ((tobj (make-instance 'example-tessellator)) (rect '((50 50 0) (200 50 0) (200 200 0) (50 200 0))) (tri '((75 75 0) (125 175 0) (175 75 0))) (star '((250 50 0 1 0 1) (325 200 0 1 1 0) (400 50 0 0 1 1) (250 150 0 1 0 0) (400 150 0 0 1 0)))) (gl:clear-color 0 0 0 0) (setf (start-list window) (gl:gen-lists 2)) (glu:tess-property tobj :winding-rule :positive) (gl:with-new-list ((start-list window) :compile) (gl:shade-model :flat) (glu:with-tess-polygon (tobj) (glu:with-tess-contour tobj (loop for coords in rect do (glu:tess-vertex tobj coords coords))) (glu:with-tess-contour tobj (loop for coords in tri do (glu:tess-vertex tobj coords coords))))) (glu:tess-delete tobj) (setf tobj (make-instance 'star-tessellator)) (gl:with-new-list ((1+ (start-list window)) :compile) (gl:shade-model :smooth) (glu:tess-property tobj :winding-rule :positive) (glu:with-tess-polygon (tobj) (glu:with-tess-contour tobj (loop for coords in star do (glu:tess-vertex tobj coords coords))))) (glu:tess-delete tobj))) (defmethod glut:display ((window tess-window)) (gl:clear :color-buffer) (gl:color 1 1 1) (gl:call-list (start-list window)) (gl:call-list (1+ (start-list window))) (gl:flush)) (defmethod glut:reshape ((w tess-window) width height) (gl:viewport 0 0 width height) (gl:matrix-mode :projection) (gl:load-identity) (glu:ortho-2d 0 width 0 height)) (defmethod glut:keyboard ((w tess-window) key x y) (declare (ignore x y)) (when (eql key #\Esc) (glut:destroy-current-window))) (defmethod glu:vertex-data-callback ((tess example-tessellator) vertex-data polygon-data) (gl:vertex (first vertex-data) (second vertex-data) (third vertex-data))) (defmethod glu:vertex-data-callback ((tess star-tessellator) vertex-data polygon-data) (gl:color (fourth vertex-data) (fifth vertex-data) (sixth vertex-data)) (gl:vertex (first vertex-data) (second vertex-data) (third vertex-data))) (defmethod glu:combine-data-callback ((tess star-tessellator) coords vertex-data weight polygon-data) (nconc (loop for i from 0 below 3 collect (gl:glaref coords i)) (loop for i from 3 below 6 collect (+ (* (gl:glaref weight 0) (nth i (aref vertex-data 0))) (* (gl:glaref weight 1) (nth i (aref vertex-data 1))) (* (gl:glaref weight 2) (nth i (aref vertex-data 2))) (* (gl:glaref weight 3) (nth i (aref vertex-data 3))))))) (defun rb-tess () (glut:display-window (make-instance 'tess-window)))
3ac269e06a7c996e728f80755695d247959cab4271e0ac0a46968f6a1f336832
xoken/xoken-core
Message.hs
| Module : Network . . Test . Message Copyright : Xoken Labs License : Open BSV License Stability : experimental Portability : POSIX Module : Network.Xoken.Test.Message Copyright : Xoken Labs License : Open BSV License Stability : experimental Portability : POSIX -} module Network.Xoken.Test.Message where import Network.Xoken.Constants import Network.Xoken.Network.Message import Network.Xoken.Test.Block import Network.Xoken.Test.Crypto import Network.Xoken.Test.Network import Network.Xoken.Test.Transaction import Test.QuickCheck | Arbitrary ' ' . arbitraryMessageHeader :: Gen MessageHeader arbitraryMessageHeader = MessageHeader <$> arbitrary <*> arbitraryMessageCommand <*> arbitrary <*> arbitraryCheckSum32 -- | Arbitrary 'Message'. arbitraryMessage :: Network -> Gen Message arbitraryMessage net = oneof [ MVersion <$> arbitraryVersion , return MVerAck , MAddr <$> arbitraryAddr1 , MInv <$> arbitraryInv1 , MGetData <$> arbitraryGetData , MNotFound <$> arbitraryNotFound , MGetBlocks <$> arbitraryGetBlocks , MGetHeaders <$> arbitraryGetHeaders , MTx <$> arbitraryTx net -- , MBlock <$> arbitraryBlock net , MMerkleBlock <$> arbitraryMerkleBlock , MHeaders <$> arbitraryHeaders , return MGetAddr , MPing <$> arbitraryPing , MPong <$> arbitraryPong , MAlert <$> arbitraryAlert , MReject <$> arbitraryReject , return MSendHeaders ]
null
https://raw.githubusercontent.com/xoken/xoken-core/34399655febdc8c0940da7983489f0c9d58c35d2/core/src/Network/Xoken/Test/Message.hs
haskell
| Arbitrary 'Message'. , MBlock <$> arbitraryBlock net
| Module : Network . . Test . Message Copyright : Xoken Labs License : Open BSV License Stability : experimental Portability : POSIX Module : Network.Xoken.Test.Message Copyright : Xoken Labs License : Open BSV License Stability : experimental Portability : POSIX -} module Network.Xoken.Test.Message where import Network.Xoken.Constants import Network.Xoken.Network.Message import Network.Xoken.Test.Block import Network.Xoken.Test.Crypto import Network.Xoken.Test.Network import Network.Xoken.Test.Transaction import Test.QuickCheck | Arbitrary ' ' . arbitraryMessageHeader :: Gen MessageHeader arbitraryMessageHeader = MessageHeader <$> arbitrary <*> arbitraryMessageCommand <*> arbitrary <*> arbitraryCheckSum32 arbitraryMessage :: Network -> Gen Message arbitraryMessage net = oneof [ MVersion <$> arbitraryVersion , return MVerAck , MAddr <$> arbitraryAddr1 , MInv <$> arbitraryInv1 , MGetData <$> arbitraryGetData , MNotFound <$> arbitraryNotFound , MGetBlocks <$> arbitraryGetBlocks , MGetHeaders <$> arbitraryGetHeaders , MTx <$> arbitraryTx net , MMerkleBlock <$> arbitraryMerkleBlock , MHeaders <$> arbitraryHeaders , return MGetAddr , MPing <$> arbitraryPing , MPong <$> arbitraryPong , MAlert <$> arbitraryAlert , MReject <$> arbitraryReject , return MSendHeaders ]
9784892aacc9643a2a4bafd2b9d97595f16550dc54e861dbd895cad1d4e2383f
aloiscochard/codex
Project.hs
module Codex.Project where import Control.Applicative ((<|>)) import Control.Exception (try, SomeException) import Control.Monad (filterM) import Data.Bool (bool) import Data.Function import Data.List (delete, isPrefixOf, union) import Data.Maybe import Distribution.InstalledPackageInfo import Distribution.Hackage.DB (HackageDB, cabalFile, readTarball) import Distribution.Package import Distribution.PackageDescription import Distribution.PackageDescription.Parsec import Distribution.Sandbox.Utils (findSandbox) import Distribution.Simple.Configure import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PackageIndex import Distribution.Verbosity import Distribution.Version import System.Directory import System.Environment (lookupEnv) import System.FilePath import Text.Read (readMaybe) import qualified Data.List as List import qualified Data.Map as Map import Codex.Internal (Builder(..), stackListDependencies) type Hackage = HackageDB newtype Workspace = Workspace [WorkspaceProject] deriving (Eq, Show) data WorkspaceProject = WorkspaceProject { workspaceProjectIdentifier :: PackageIdentifier, workspaceProjectPath :: FilePath } deriving (Eq, Show) type ProjectDependencies = (Maybe PackageIdentifier, [PackageIdentifier], [WorkspaceProject]) identifier :: GenericPackageDescription -> PackageIdentifier identifier = package . packageDescription allDependencies :: GenericPackageDescription -> [Dependency] allDependencies pd = List.filter (not . isCurrent) $ concat [lds, eds, tds, bds] where lds = condTreeConstraints =<< (maybeToList $ condLibrary pd) eds = (condTreeConstraints . snd) =<< condExecutables pd tds = (condTreeConstraints . snd) =<< condTestSuites pd bds = (condTreeConstraints . snd) =<< condBenchmarks pd isCurrent (Dependency n _ _) = n == (pkgName $ identifier pd) findPackageDescription :: FilePath -> IO (Maybe GenericPackageDescription) findPackageDescription root = do mpath <- findCabalFilePath root traverse ( readGenericPackageDescription silent) mpath -- | Find a regular file ending with ".cabal" within a directory. findCabalFilePath :: FilePath -> IO (Maybe FilePath) findCabalFilePath path = do paths <- getDirectoryContents path case List.find ((&&) <$> dotCabal <*> visible) paths of Just p -> do let p' = path </> p bool Nothing (Just p') <$> doesFileExist p' Nothing -> pure Nothing where dotCabal = (".cabal" ==) . takeExtension visible = not . List.isPrefixOf "." resolveCurrentProjectDependencies :: Builder -> FilePath -> IO ProjectDependencies resolveCurrentProjectDependencies bldr hackagePath = do mps <- localPackages case mps of Just ps -> resolveLocalDependencies bldr hackagePath ps Nothing -> do disableImplicitWorkspace <- isJust <$> lookupEnv "CODEX_DISABLE_WORKSPACE" ws <- if disableImplicitWorkspace then pure (Workspace []) else getWorkspace ".." resolveProjectDependencies bldr ws hackagePath "." where localPackages = do mpath <- case bldr of Cabal -> bool Nothing (Just ".") <$> doesFileExist "cabal.project" Stack _ -> pure (Just ".") case mpath of Nothing -> pure Nothing Just path -> Just <$> findLocalPackages 2 path -- | Resolve the dependencies of each local project package. resolveLocalDependencies :: Builder -> FilePath -> [WorkspaceProject] -> IO ProjectDependencies resolveLocalDependencies bldr hackagePath wps = do pids <- foldr mergeDependencies mempty <$> traverse resolve wps pure (Nothing, pids, wps) where resolve p@WorkspaceProject{workspaceProjectPath = packagePath} = let ws' = Workspace (delete p wps) in resolveProjectDependencies bldr ws' hackagePath packagePath mergeDependencies (_, pids, _) pids' = pids `union` pids' -- TODO Optimize resolveProjectDependencies :: Builder -> Workspace -> FilePath -> FilePath -> IO ProjectDependencies resolveProjectDependencies bldr ws hackagePath root = do pd <- maybe (error "No cabal file found.") id <$> findPackageDescription root xs <- resolvePackageDependencies bldr hackagePath root pd ys <- resolveSandboxDependencies root let zs = resolveWorkspaceDependencies ws pd let wsds = List.filter (shouldOverride xs) $ List.nubBy (on (==) prjId) $ concat [ys, zs] let pjds = List.filter (\x -> (((unPackageName . pkgName) x) /= "rts") && (List.notElem (pkgName x) $ fmap prjId wsds)) xs return (Just (identifier pd), pjds, wsds) where shouldOverride xs (WorkspaceProject x _) = maybe True (\y -> pkgVersion x >= pkgVersion y) $ List.find (\y -> pkgName x == pkgName y) xs prjId = pkgName . workspaceProjectIdentifier resolveInstalledDependencies :: Builder -> FilePath -> GenericPackageDescription -> IO (Either SomeException [PackageIdentifier]) resolveInstalledDependencies bldr root pd = try $ do case bldr of Cabal -> do lbi <- withCabal let ipkgs = installedPkgs lbi clbis = allComponentsInBuildOrder' lbi pkgs = componentPackageDeps =<< clbis ys = (maybeToList . lookupUnitId ipkgs) =<< fmap fst pkgs xs = fmap sourcePackageId $ ys return xs where withCabal = getPersistBuildConfig $ root </> "dist" Stack cmd -> filter (/= pid) <$> stackListDependencies cmd pname where pid = pd & packageDescription & package pname = pid & pkgName & unPackageName allComponentsInBuildOrder' :: LocalBuildInfo -> [ComponentLocalBuildInfo] allComponentsInBuildOrder' = allComponentsInBuildOrder resolveHackageDependencies :: Hackage -> GenericPackageDescription -> [GenericPackageDescription] resolveHackageDependencies db pd = maybeToList . resolveDependency db =<< allDependencies pd where resolveDependency _ (Dependency name versionRange _) = do pdsByVersion <- lookupName name latest <- List.find (\x -> withinRange' x versionRange) $ List.reverse $ List.sort $ Map.keys pdsByVersion lookupVersion latest pdsByVersion lookupName name = Map.lookup name db lookupVersion latest pdsByVersion = cabalFile <$> Map.lookup latest pdsByVersion withinRange' :: Version -> VersionRange -> Bool withinRange' = withinRange resolvePackageDependencies :: Builder -> FilePath -> FilePath -> GenericPackageDescription -> IO [PackageIdentifier] resolvePackageDependencies bldr hackagePath root pd = do xs <- either fallback return =<< resolveInstalledDependencies bldr root pd return xs where fallback e = do putStrLn $ concat ["codex: ", show e] putStrLn "codex: *warning* falling back on dependency resolution using hackage" resolveWithHackage resolveWithHackage = do db <- readTarball Nothing (hackagePath </> "00-index.tar") <|> readTarball Nothing hackagePath return $ identifier <$> resolveHackageDependencies db pd resolveSandboxDependencies :: FilePath -> IO [WorkspaceProject] resolveSandboxDependencies root = findSandbox root >>= maybe (return []) continue where continue cabalSandboxFolder = do fileExists <- doesFileExist sourcesFile if fileExists then readSources else return [] where sourcesFile = root </> cabalSandboxFolder </> "add-source-timestamps" readSources = do fileContent <- readFile sourcesFile xs <- traverse readWorkspaceProject $ projects fileContent return $ xs >>= maybeToList where projects :: String -> [FilePath] projects x = sources x >>= (\x' -> fst <$> snd x') sources :: String -> [(String, [(FilePath, Int)])] sources x = fromMaybe [] (readMaybe x) resolveWorkspaceDependencies :: Workspace -> GenericPackageDescription -> [WorkspaceProject] resolveWorkspaceDependencies (Workspace ws) pd = maybeToList . resolveDependency =<< allDependencies pd where resolveDependency (Dependency name versionRange _) = List.find (\(WorkspaceProject (PackageIdentifier n v) _) -> n == name && withinRange v versionRange) ws readWorkspaceProject :: FilePath -> IO (Maybe WorkspaceProject) readWorkspaceProject path = do pd <- findPackageDescription path return $ fmap (\x -> WorkspaceProject (identifier x) path) pd getWorkspace :: FilePath -> IO Workspace getWorkspace root = Workspace <$> findLocalPackages 1 root -- | Recursively find local packages in @root@, up to @depth@ layers deep. The @root@ directory has a depth of 0 . findLocalPackages :: Int -> FilePath -> IO [WorkspaceProject] findLocalPackages depth root = catMaybes <$> go depth root where go n path | n < 0 = pure [] | otherwise = (:) <$> readWorkspaceProject path <*> fmap mconcat (traverse (go (n - 1)) =<< listDirectories path) listDirectories path = do paths <- getDirectoryContents =<< canonicalizePath path filterM doesDirectoryExist ((path </>) <$> filter visible paths) visible path = (not . isPrefixOf ".") path && path `notElem` ["dist", "dist-new"]
null
https://raw.githubusercontent.com/aloiscochard/codex/6edbdc34357d13e52b434c19665725684cdd2dba/src/Codex/Project.hs
haskell
| Find a regular file ending with ".cabal" within a directory. | Resolve the dependencies of each local project package. TODO Optimize | Recursively find local packages in @root@, up to @depth@ layers deep. The
module Codex.Project where import Control.Applicative ((<|>)) import Control.Exception (try, SomeException) import Control.Monad (filterM) import Data.Bool (bool) import Data.Function import Data.List (delete, isPrefixOf, union) import Data.Maybe import Distribution.InstalledPackageInfo import Distribution.Hackage.DB (HackageDB, cabalFile, readTarball) import Distribution.Package import Distribution.PackageDescription import Distribution.PackageDescription.Parsec import Distribution.Sandbox.Utils (findSandbox) import Distribution.Simple.Configure import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PackageIndex import Distribution.Verbosity import Distribution.Version import System.Directory import System.Environment (lookupEnv) import System.FilePath import Text.Read (readMaybe) import qualified Data.List as List import qualified Data.Map as Map import Codex.Internal (Builder(..), stackListDependencies) type Hackage = HackageDB newtype Workspace = Workspace [WorkspaceProject] deriving (Eq, Show) data WorkspaceProject = WorkspaceProject { workspaceProjectIdentifier :: PackageIdentifier, workspaceProjectPath :: FilePath } deriving (Eq, Show) type ProjectDependencies = (Maybe PackageIdentifier, [PackageIdentifier], [WorkspaceProject]) identifier :: GenericPackageDescription -> PackageIdentifier identifier = package . packageDescription allDependencies :: GenericPackageDescription -> [Dependency] allDependencies pd = List.filter (not . isCurrent) $ concat [lds, eds, tds, bds] where lds = condTreeConstraints =<< (maybeToList $ condLibrary pd) eds = (condTreeConstraints . snd) =<< condExecutables pd tds = (condTreeConstraints . snd) =<< condTestSuites pd bds = (condTreeConstraints . snd) =<< condBenchmarks pd isCurrent (Dependency n _ _) = n == (pkgName $ identifier pd) findPackageDescription :: FilePath -> IO (Maybe GenericPackageDescription) findPackageDescription root = do mpath <- findCabalFilePath root traverse ( readGenericPackageDescription silent) mpath findCabalFilePath :: FilePath -> IO (Maybe FilePath) findCabalFilePath path = do paths <- getDirectoryContents path case List.find ((&&) <$> dotCabal <*> visible) paths of Just p -> do let p' = path </> p bool Nothing (Just p') <$> doesFileExist p' Nothing -> pure Nothing where dotCabal = (".cabal" ==) . takeExtension visible = not . List.isPrefixOf "." resolveCurrentProjectDependencies :: Builder -> FilePath -> IO ProjectDependencies resolveCurrentProjectDependencies bldr hackagePath = do mps <- localPackages case mps of Just ps -> resolveLocalDependencies bldr hackagePath ps Nothing -> do disableImplicitWorkspace <- isJust <$> lookupEnv "CODEX_DISABLE_WORKSPACE" ws <- if disableImplicitWorkspace then pure (Workspace []) else getWorkspace ".." resolveProjectDependencies bldr ws hackagePath "." where localPackages = do mpath <- case bldr of Cabal -> bool Nothing (Just ".") <$> doesFileExist "cabal.project" Stack _ -> pure (Just ".") case mpath of Nothing -> pure Nothing Just path -> Just <$> findLocalPackages 2 path resolveLocalDependencies :: Builder -> FilePath -> [WorkspaceProject] -> IO ProjectDependencies resolveLocalDependencies bldr hackagePath wps = do pids <- foldr mergeDependencies mempty <$> traverse resolve wps pure (Nothing, pids, wps) where resolve p@WorkspaceProject{workspaceProjectPath = packagePath} = let ws' = Workspace (delete p wps) in resolveProjectDependencies bldr ws' hackagePath packagePath mergeDependencies (_, pids, _) pids' = pids `union` pids' resolveProjectDependencies :: Builder -> Workspace -> FilePath -> FilePath -> IO ProjectDependencies resolveProjectDependencies bldr ws hackagePath root = do pd <- maybe (error "No cabal file found.") id <$> findPackageDescription root xs <- resolvePackageDependencies bldr hackagePath root pd ys <- resolveSandboxDependencies root let zs = resolveWorkspaceDependencies ws pd let wsds = List.filter (shouldOverride xs) $ List.nubBy (on (==) prjId) $ concat [ys, zs] let pjds = List.filter (\x -> (((unPackageName . pkgName) x) /= "rts") && (List.notElem (pkgName x) $ fmap prjId wsds)) xs return (Just (identifier pd), pjds, wsds) where shouldOverride xs (WorkspaceProject x _) = maybe True (\y -> pkgVersion x >= pkgVersion y) $ List.find (\y -> pkgName x == pkgName y) xs prjId = pkgName . workspaceProjectIdentifier resolveInstalledDependencies :: Builder -> FilePath -> GenericPackageDescription -> IO (Either SomeException [PackageIdentifier]) resolveInstalledDependencies bldr root pd = try $ do case bldr of Cabal -> do lbi <- withCabal let ipkgs = installedPkgs lbi clbis = allComponentsInBuildOrder' lbi pkgs = componentPackageDeps =<< clbis ys = (maybeToList . lookupUnitId ipkgs) =<< fmap fst pkgs xs = fmap sourcePackageId $ ys return xs where withCabal = getPersistBuildConfig $ root </> "dist" Stack cmd -> filter (/= pid) <$> stackListDependencies cmd pname where pid = pd & packageDescription & package pname = pid & pkgName & unPackageName allComponentsInBuildOrder' :: LocalBuildInfo -> [ComponentLocalBuildInfo] allComponentsInBuildOrder' = allComponentsInBuildOrder resolveHackageDependencies :: Hackage -> GenericPackageDescription -> [GenericPackageDescription] resolveHackageDependencies db pd = maybeToList . resolveDependency db =<< allDependencies pd where resolveDependency _ (Dependency name versionRange _) = do pdsByVersion <- lookupName name latest <- List.find (\x -> withinRange' x versionRange) $ List.reverse $ List.sort $ Map.keys pdsByVersion lookupVersion latest pdsByVersion lookupName name = Map.lookup name db lookupVersion latest pdsByVersion = cabalFile <$> Map.lookup latest pdsByVersion withinRange' :: Version -> VersionRange -> Bool withinRange' = withinRange resolvePackageDependencies :: Builder -> FilePath -> FilePath -> GenericPackageDescription -> IO [PackageIdentifier] resolvePackageDependencies bldr hackagePath root pd = do xs <- either fallback return =<< resolveInstalledDependencies bldr root pd return xs where fallback e = do putStrLn $ concat ["codex: ", show e] putStrLn "codex: *warning* falling back on dependency resolution using hackage" resolveWithHackage resolveWithHackage = do db <- readTarball Nothing (hackagePath </> "00-index.tar") <|> readTarball Nothing hackagePath return $ identifier <$> resolveHackageDependencies db pd resolveSandboxDependencies :: FilePath -> IO [WorkspaceProject] resolveSandboxDependencies root = findSandbox root >>= maybe (return []) continue where continue cabalSandboxFolder = do fileExists <- doesFileExist sourcesFile if fileExists then readSources else return [] where sourcesFile = root </> cabalSandboxFolder </> "add-source-timestamps" readSources = do fileContent <- readFile sourcesFile xs <- traverse readWorkspaceProject $ projects fileContent return $ xs >>= maybeToList where projects :: String -> [FilePath] projects x = sources x >>= (\x' -> fst <$> snd x') sources :: String -> [(String, [(FilePath, Int)])] sources x = fromMaybe [] (readMaybe x) resolveWorkspaceDependencies :: Workspace -> GenericPackageDescription -> [WorkspaceProject] resolveWorkspaceDependencies (Workspace ws) pd = maybeToList . resolveDependency =<< allDependencies pd where resolveDependency (Dependency name versionRange _) = List.find (\(WorkspaceProject (PackageIdentifier n v) _) -> n == name && withinRange v versionRange) ws readWorkspaceProject :: FilePath -> IO (Maybe WorkspaceProject) readWorkspaceProject path = do pd <- findPackageDescription path return $ fmap (\x -> WorkspaceProject (identifier x) path) pd getWorkspace :: FilePath -> IO Workspace getWorkspace root = Workspace <$> findLocalPackages 1 root @root@ directory has a depth of 0 . findLocalPackages :: Int -> FilePath -> IO [WorkspaceProject] findLocalPackages depth root = catMaybes <$> go depth root where go n path | n < 0 = pure [] | otherwise = (:) <$> readWorkspaceProject path <*> fmap mconcat (traverse (go (n - 1)) =<< listDirectories path) listDirectories path = do paths <- getDirectoryContents =<< canonicalizePath path filterM doesDirectoryExist ((path </>) <$> filter visible paths) visible path = (not . isPrefixOf ".") path && path `notElem` ["dist", "dist-new"]
58a5858b9ad59bb5f04f95aa743ded2e01d30f2039d695c2a6d890d8e231cc9d
cpichard/filesequence
IntervalTree.hs
| Module FileSequence . FrameList , | implement the DIET : discrete integer encoding tree -- See reference xxxxxxx module System.FileSequence.FrameList.IntervalTree where type FrameNumber = Int type FrameRange = (FrameNumber, FrameNumber) -- | We use a binary tree to store the frame intervals -- TODO : look for the function to fold this datastructure data IntervalTree = Empty | Node FrameRange IntervalTree IntervalTree deriving Show -- | Returns a new empty frame list emptyFrameList :: IntervalTree emptyFrameList = Empty -- | Insert a new frame insertFrame :: IntervalTree -> FrameNumber -> IntervalTree insertFrame Empty f = Node (f,f) Empty Empty insertFrame node@(Node (minx, maxx) left right) f | f == minx - 1 = joinRight (Node (f, maxx) left right) | f == maxx + 1 = joinLeft (Node (minx, f) left right) | f < minx - 1 = Node (minx, maxx) (insertFrame left f) right | f > maxx + 1 = Node (minx, maxx) left (insertFrame right f) | otherwise = node -- We should test for this condition | otherwise = error "trying to insert an already inserted value" where splitMin (Node (minx, maxx) Empty right) = (minx, maxx, right) splitMin (Node (minx, maxx) left right) = let (u,v,l') = splitMin left in (u, v, Node (minx, maxx) l' right) splitMax (Node (minx, maxx) left Empty) = (minx, maxx, left) splitMax (Node (minx, maxx) left right) = let (u,v,r') = splitMax right in (u, v, Node (minx, maxx) left r') joinRight node@(Node (_, _) _ Empty) = node joinRight node@(Node (minx, maxx) left right) = let (minx', maxx', right') = splitMin right in if minx'-1 == maxx then Node (minx, maxx') left right' else node joinLeft node@(Node (_, _) Empty _) = node joinLeft node@(Node (minx, maxx) left right) = let (minx', maxx', left') = splitMax left in if maxx'+1 == minx then Node (minx', maxx) left' right else node -- | Insert a list of frames insertFrames :: [FrameNumber] -> IntervalTree insertFrames = foldr (flip insertFrame) emptyFrameList -- | Test if the frame is inside the set of frames -- use `isElementOf` isElementOf :: FrameNumber -> IntervalTree -> Bool isElementOf _ Empty = False isElementOf f (Node (minx, maxx) left right) | f >= minx && f <= maxx = True | f < minx = isElementOf f left | f > maxx = isElementOf f right -- | List all the frames toList :: IntervalTree -> [FrameNumber] toList Empty = [] toList (Node (maxx, minx) Empty Empty) = [maxx .. minx] toList (Node (maxx, minx) left right) = toList left ++ [maxx .. minx] ++ toList right -- | List all the intervals intervals :: IntervalTree -> [(FrameNumber, FrameNumber)] intervals Empty = [] intervals (Node (maxx, minx) Empty Empty) = [(maxx, minx)] intervals (Node (maxx, minx) left right) = intervals left ++ [(maxx, minx)] ++ intervals right | First frame firstFrame :: IntervalTree -> FrameNumber firstFrame (Node (minx, _) Empty _) = minx firstFrame (Node (_, _) left _) = firstFrame left firstFrame Empty = 0 -- should be error ? shouldn't it ? -- | Last frame lastFrame :: IntervalTree -> FrameNumber lastFrame Empty = 0 -- should be error ? shouldn't it ? lastFrame (Node (_, maxx) _ Empty) = maxx lastFrame (Node (_, _) _ right) = lastFrame right | Construct a FrameList from a range fromRange :: FrameNumber -> FrameNumber -> IntervalTree fromRange ff lf | ff > lf = Node (ff,lf) Empty Empty | otherwise = Node (lf, ff) Empty Empty -- | Returns the list of missing frames ex :> holes [ ( 1,5 ) , ( 7,10 ) , ( 15,20 ) ] -- > [(6,6), (11,14)] -- FIXME : check complexity findMin (Node (l, r) Empty nr) = l findMin (Node (l,r) nl nr) = findMin nl findMin Empty = error "find min in empty" findMax (Node (l, r) nl Empty) = r findMax (Node (l, r) nl nr) = findMax nr findMax Empty = error "find max in empty" holes :: IntervalTree -> IntervalTree holes Empty = Empty holes (Node (l, r) Empty Empty) = Empty holes (Node (l, r) Empty nr) = Node (r+1, (findMin nr)-1) Empty (holes nr) holes (Node (l, r) nl Empty) = Node ((findMax nl)+1, l-1) (holes nl) Empty holes (Node (l, r) nl nr) = let rightNode = Node (r+1, (findMin nr)-1) (holes nr) Empty in Node ((findMax nl)+1, l-1) (holes nl) rightNode -- | Returns the number of frames nbFrames :: IntervalTree -> FrameNumber nbFrames Empty = 0 nbFrames fl = length $ toList fl -- TODO count nbFrames instead of creating a list of the number of frames nbFrames ( ( ff , ) = ( lf - ff+1 ) + ( nbFrames xs ) -- | Returns the number of missing frames nbMissing :: IntervalTree -> FrameNumber nbMissing fss = nbFrames $ holes fss --instance Arbitrary IntervalTree where -- arbitrary = do -- frames_ <- listOf1 arbitrary :: Gen [FrameNumber] -- return $ foldl insertFrame emptyFrameList frames_
null
https://raw.githubusercontent.com/cpichard/filesequence/39cd8eb7dd0bc494c181c5b04fc9ff2fae5202d0/src/System/FileSequence/FrameList/IntervalTree.hs
haskell
See reference xxxxxxx | We use a binary tree to store the frame intervals TODO : look for the function to fold this datastructure | Returns a new empty frame list | Insert a new frame We should test for this condition | otherwise = error "trying to insert an already inserted value" | Insert a list of frames | Test if the frame is inside the set of frames use `isElementOf` | List all the frames | List all the intervals should be error ? shouldn't it ? | Last frame should be error ? shouldn't it ? | Returns the list of missing frames > [(6,6), (11,14)] FIXME : check complexity | Returns the number of frames TODO count nbFrames instead of creating a list of the number of frames | Returns the number of missing frames instance Arbitrary IntervalTree where arbitrary = do frames_ <- listOf1 arbitrary :: Gen [FrameNumber] return $ foldl insertFrame emptyFrameList frames_
| Module FileSequence . FrameList , | implement the DIET : discrete integer encoding tree module System.FileSequence.FrameList.IntervalTree where type FrameNumber = Int type FrameRange = (FrameNumber, FrameNumber) data IntervalTree = Empty | Node FrameRange IntervalTree IntervalTree deriving Show emptyFrameList :: IntervalTree emptyFrameList = Empty insertFrame :: IntervalTree -> FrameNumber -> IntervalTree insertFrame Empty f = Node (f,f) Empty Empty insertFrame node@(Node (minx, maxx) left right) f | f == minx - 1 = joinRight (Node (f, maxx) left right) | f == maxx + 1 = joinLeft (Node (minx, f) left right) | f < minx - 1 = Node (minx, maxx) (insertFrame left f) right | f > maxx + 1 = Node (minx, maxx) left (insertFrame right f) | otherwise = node where splitMin (Node (minx, maxx) Empty right) = (minx, maxx, right) splitMin (Node (minx, maxx) left right) = let (u,v,l') = splitMin left in (u, v, Node (minx, maxx) l' right) splitMax (Node (minx, maxx) left Empty) = (minx, maxx, left) splitMax (Node (minx, maxx) left right) = let (u,v,r') = splitMax right in (u, v, Node (minx, maxx) left r') joinRight node@(Node (_, _) _ Empty) = node joinRight node@(Node (minx, maxx) left right) = let (minx', maxx', right') = splitMin right in if minx'-1 == maxx then Node (minx, maxx') left right' else node joinLeft node@(Node (_, _) Empty _) = node joinLeft node@(Node (minx, maxx) left right) = let (minx', maxx', left') = splitMax left in if maxx'+1 == minx then Node (minx', maxx) left' right else node insertFrames :: [FrameNumber] -> IntervalTree insertFrames = foldr (flip insertFrame) emptyFrameList isElementOf :: FrameNumber -> IntervalTree -> Bool isElementOf _ Empty = False isElementOf f (Node (minx, maxx) left right) | f >= minx && f <= maxx = True | f < minx = isElementOf f left | f > maxx = isElementOf f right toList :: IntervalTree -> [FrameNumber] toList Empty = [] toList (Node (maxx, minx) Empty Empty) = [maxx .. minx] toList (Node (maxx, minx) left right) = toList left ++ [maxx .. minx] ++ toList right intervals :: IntervalTree -> [(FrameNumber, FrameNumber)] intervals Empty = [] intervals (Node (maxx, minx) Empty Empty) = [(maxx, minx)] intervals (Node (maxx, minx) left right) = intervals left ++ [(maxx, minx)] ++ intervals right | First frame firstFrame :: IntervalTree -> FrameNumber firstFrame (Node (minx, _) Empty _) = minx firstFrame (Node (_, _) left _) = firstFrame left lastFrame :: IntervalTree -> FrameNumber lastFrame (Node (_, maxx) _ Empty) = maxx lastFrame (Node (_, _) _ right) = lastFrame right | Construct a FrameList from a range fromRange :: FrameNumber -> FrameNumber -> IntervalTree fromRange ff lf | ff > lf = Node (ff,lf) Empty Empty | otherwise = Node (lf, ff) Empty Empty ex :> holes [ ( 1,5 ) , ( 7,10 ) , ( 15,20 ) ] findMin (Node (l, r) Empty nr) = l findMin (Node (l,r) nl nr) = findMin nl findMin Empty = error "find min in empty" findMax (Node (l, r) nl Empty) = r findMax (Node (l, r) nl nr) = findMax nr findMax Empty = error "find max in empty" holes :: IntervalTree -> IntervalTree holes Empty = Empty holes (Node (l, r) Empty Empty) = Empty holes (Node (l, r) Empty nr) = Node (r+1, (findMin nr)-1) Empty (holes nr) holes (Node (l, r) nl Empty) = Node ((findMax nl)+1, l-1) (holes nl) Empty holes (Node (l, r) nl nr) = let rightNode = Node (r+1, (findMin nr)-1) (holes nr) Empty in Node ((findMax nl)+1, l-1) (holes nl) rightNode nbFrames :: IntervalTree -> FrameNumber nbFrames Empty = 0 nbFrames ( ( ff , ) = ( lf - ff+1 ) + ( nbFrames xs ) nbMissing :: IntervalTree -> FrameNumber nbMissing fss = nbFrames $ holes fss
d117f83c026deb2bfb5d7365052cefc92b65ea1c4e979b5b9b232d0bb48eefac
ollef/sixty
Representation.hs
# LANGUAGE BlockArguments # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} module Representation where import Data.Persist import Prettyprinter import Protolude data Signature = ConstantSignature !Representation | FunctionSignature [Representation] !Representation deriving (Eq, Show, Generic, Persist, Hashable) data Representation = Empty | Direct !ContainsHeapPointers | Indirect !ContainsHeapPointers deriving (Eq, Ord, Show, Generic, Persist, Hashable) data ContainsHeapPointers = Doesn'tContainHeapPointers | MightContainHeapPointers deriving (Eq, Ord, Show, Generic, Persist, Hashable) instance Semigroup Representation where Empty <> representation = representation representation <> Empty = representation representation1 <> representation2 = Indirect $ containsHeapPointers representation1 <> containsHeapPointers representation2 containsHeapPointers :: Representation -> ContainsHeapPointers containsHeapPointers Empty = Doesn'tContainHeapPointers containsHeapPointers (Direct cp) = cp containsHeapPointers (Indirect cp) = cp instance Monoid Representation where mempty = Empty instance Pretty Representation where pretty representation = case representation of Empty -> "empty" Direct MightContainHeapPointers -> "direct*" Direct Doesn'tContainHeapPointers -> "direct" Indirect MightContainHeapPointers -> "indirect*" Indirect Doesn'tContainHeapPointers -> "indirect" instance Semigroup ContainsHeapPointers where MightContainHeapPointers <> _ = MightContainHeapPointers _ <> MightContainHeapPointers = MightContainHeapPointers Doesn'tContainHeapPointers <> Doesn'tContainHeapPointers = Doesn'tContainHeapPointers instance Monoid ContainsHeapPointers where mempty = Doesn'tContainHeapPointers maxM :: Monad m => [m Representation] -> m Representation maxM [] = pure mempty maxM (m : ms) = do representation <- m case representation of Indirect MightContainHeapPointers -> pure representation _ -> max representation <$> maxM ms
null
https://raw.githubusercontent.com/ollef/sixty/5d630ca6fde91da5a691dc7cd195f5cbf6491eb0/src/Representation.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings #
# LANGUAGE BlockArguments # # LANGUAGE DeriveGeneric # module Representation where import Data.Persist import Prettyprinter import Protolude data Signature = ConstantSignature !Representation | FunctionSignature [Representation] !Representation deriving (Eq, Show, Generic, Persist, Hashable) data Representation = Empty | Direct !ContainsHeapPointers | Indirect !ContainsHeapPointers deriving (Eq, Ord, Show, Generic, Persist, Hashable) data ContainsHeapPointers = Doesn'tContainHeapPointers | MightContainHeapPointers deriving (Eq, Ord, Show, Generic, Persist, Hashable) instance Semigroup Representation where Empty <> representation = representation representation <> Empty = representation representation1 <> representation2 = Indirect $ containsHeapPointers representation1 <> containsHeapPointers representation2 containsHeapPointers :: Representation -> ContainsHeapPointers containsHeapPointers Empty = Doesn'tContainHeapPointers containsHeapPointers (Direct cp) = cp containsHeapPointers (Indirect cp) = cp instance Monoid Representation where mempty = Empty instance Pretty Representation where pretty representation = case representation of Empty -> "empty" Direct MightContainHeapPointers -> "direct*" Direct Doesn'tContainHeapPointers -> "direct" Indirect MightContainHeapPointers -> "indirect*" Indirect Doesn'tContainHeapPointers -> "indirect" instance Semigroup ContainsHeapPointers where MightContainHeapPointers <> _ = MightContainHeapPointers _ <> MightContainHeapPointers = MightContainHeapPointers Doesn'tContainHeapPointers <> Doesn'tContainHeapPointers = Doesn'tContainHeapPointers instance Monoid ContainsHeapPointers where mempty = Doesn'tContainHeapPointers maxM :: Monad m => [m Representation] -> m Representation maxM [] = pure mempty maxM (m : ms) = do representation <- m case representation of Indirect MightContainHeapPointers -> pure representation _ -> max representation <$> maxM ms
f30369507fa91b230c873c77ee3454b505f38a000572cf790a53f550417bf45d
jgoerzen/ftphs
Parser.hs
arch - tag : FTP protocol parser Copyright ( C ) 2004 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA Copyright (C) 2004 John Goerzen <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} | Module : Network . FTP.Client . Parser Copyright : Copyright ( C ) 2004 License : GNU LGPL , version 2.1 or above Maintainer : < > Stability : provisional Portability : systems with networking This module provides a parser that is used internally by " Network . FTP.Client " . You almost certainly do not want to use this module directly . Use " Network . FTP.Client " instead . Written by , jgoerzen\@complete.org Module : Network.FTP.Client.Parser Copyright : Copyright (C) 2004 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : John Goerzen <> Stability : provisional Portability: systems with networking This module provides a parser that is used internally by "Network.FTP.Client". You almost certainly do not want to use this module directly. Use "Network.FTP.Client" instead. Written by John Goerzen, jgoerzen\@complete.org -} module Network.FTP.Client.Parser(parseReply, parseGoodReply, toPortString, fromPortString, debugParseGoodReply, respToSockAddr, FTPResult, -- * Utilities unexpectedresp, isxresp, forcexresp, forceioresp, parseDirName) where import Data.Bits.Utils import Data.List.Utils import Data.String.Utils import Data.Word import Network.Socket import System.IO.Unsafe import System.Log.Logger import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Utils import Text.Regex type FTPResult = (Int, [String]) import Control . ) , throw ) logit :: String -> IO () logit m = debugM "Network.FTP.Client.Parser" ("FTP received: " ++ m) ---------------------------------------------------------------------- Utilities ---------------------------------------------------------------------- unexpectedresp m r = "FTP: Expected " ++ m ++ ", got " ++ (show r) isxresp desired (r, _) = r >= desired && r < (desired + 100) forcexresp desired r = if isxresp desired r then r else error ((unexpectedresp (show desired)) r) forceioresp :: Int -> FTPResult -> IO () forceioresp desired r = if isxresp desired r then return () else fail (unexpectedresp (show desired) r) crlf :: Parser String crlf = string "\r\n" <?> "CRLF" sp :: Parser Char sp = char ' ' code :: Parser Int code = do s <- codeString return (read s) codeString :: Parser String codeString = do first <- oneOf "123456789" <?> "3-digit reply code" remaining <- count 2 digit <?> "3-digit reply code" return (first : remaining) specificCode :: Int -> Parser Int specificCode exp = do s <- string (show exp) <?> ("Code " ++ (show exp)) return (read s) line :: Parser String line = do x <- many (noneOf "\r\n") crlf return $ unsafePerformIO $ putStrLn ( " line : " + + x ) return x ---------------------------------------------------------------------- -- The parsers ---------------------------------------------------------------------- singleReplyLine :: Parser (Int, String) singleReplyLine = do x <- code sp text <- line return (x, text) expectedReplyLine :: Int -> Parser (Int, String) expectedReplyLine expectedcode = do x <- specificCode expectedcode sp text <- line return (x, text) startOfMultiReply :: Parser (Int, String) startOfMultiReply = do x <- code char '-' text <- line return (x, text) multiReplyComponent :: Parser [String] multiReplyComponent = (try (do notMatching (do codeString sp ) "found unexpected code" thisLine <- line return ( ( " MRC : got " + + thisLine ) ) remainder <- multiReplyComponent return (thisLine : remainder) ) ) <|> return [] multiReply :: Parser FTPResult multiReply = try (do x <- singleReplyLine return (fst x, [snd x]) ) <|> (do start <- startOfMultiReply component <- multiReplyComponent end <- expectedReplyLine (fst start) return (fst start, snd start : (component ++ [snd end])) ) ---------------------------------------------------------------------- -- The real code ---------------------------------------------------------------------- -- | Parse a FTP reply. Returns a (result code, text) pair. parseReply :: String -> FTPResult parseReply input = case parse multiReply "(unknown)" input of Left err -> error ("FTP: " ++ (show err)) Right reply -> reply -- | Parse a FTP reply. Returns a (result code, text) pair. -- If the result code indicates an error, raise an exception instead -- of just passing it back. parseGoodReply :: String -> IO FTPResult parseGoodReply input = let reply = parseReply input in if (fst reply) >= 400 then fail ("FTP:" ++ (show (fst reply)) ++ ": " ++ (join "\n" (snd reply))) else return reply -- | Parse a FTP reply. Logs debug messages. debugParseGoodReply :: String -> IO FTPResult debugParseGoodReply contents = let logPlugin :: String -> String -> IO String logPlugin [] [] = return [] logPlugin [] accum = do logit accum return [] logPlugin (x:xs) accum = case x of '\n' -> do logit (strip (accum)) next <- unsafeInterleaveIO $ logPlugin xs [] return (x : next) y -> do next <- unsafeInterleaveIO $ logPlugin xs (accum ++ [x]) return (x : next) in do loggedStr <- logPlugin contents [] parseGoodReply loggedStr | Converts a socket address to a string suitable for a PORT command . Example : > toPortString ( SockAddrInet ( PortNum 0x1234 ) ( ) ) - > > " 170,187,204,221,18,52 " Example: > toPortString (SockAddrInet (PortNum 0x1234) (0xaabbccdd)) -> > "170,187,204,221,18,52" -} toPortString :: SockAddr -> IO String toPortString (SockAddrInet port hostaddr) = let wport = (fromIntegral (port))::Word16 (h1, h2, h3, h4) = hostAddressToTuple hostaddr in return . genericJoin "," $ map show [h1, h2, h3, h4] ++ map show (getBytes wport) toPortString _ = error "toPortString only works on AF_INET addresses" -- | Converts a port string to a socket address. This is the inverse calculation of 'toPortString'. fromPortString :: String -> IO SockAddr fromPortString instr = let inbytes = split "," instr [h1, h2, h3, h4] = map read (take 4 inbytes) addr = tupleToHostAddress (h1, h2, h3, h4) portbytes = map read (drop 4 inbytes) in return $ SockAddrInet (fromInteger $ fromBytes portbytes) addr respToSockAddrRe = mkRegex("([0-9]+,){5}[0-9]+") -- | Converts a response code to a socket address respToSockAddr :: FTPResult -> IO SockAddr respToSockAddr f = do forceioresp 200 f if (fst f) /= 227 then fail ("Not a 227 response: " ++ show f) else case matchRegexAll respToSockAddrRe (head (snd f)) of Nothing -> fail ("Could not find remote endpoint in " ++ (show f)) Just (_, x, _, _) -> fromPortString x parseDirName :: FTPResult -> Maybe String parseDirName (257, name:_) = let procq [] = [] procq ('"':_) = [] procq ('"' : '"' : xs) = '"' : procq xs procq (x:xs) = x : procq xs in if head name /= '"' then Nothing else Just (procq (tail name))
null
https://raw.githubusercontent.com/jgoerzen/ftphs/f4a4838e92ddd97c24f045b7901aa070165bfe3b/src/Network/FTP/Client/Parser.hs
haskell
* Utilities -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- The parsers -------------------------------------------------------------------- -------------------------------------------------------------------- The real code -------------------------------------------------------------------- | Parse a FTP reply. Returns a (result code, text) pair. | Parse a FTP reply. Returns a (result code, text) pair. If the result code indicates an error, raise an exception instead of just passing it back. | Parse a FTP reply. Logs debug messages. | Converts a port string to a socket address. This is the inverse calculation of 'toPortString'. | Converts a response code to a socket address
arch - tag : FTP protocol parser Copyright ( C ) 2004 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA Copyright (C) 2004 John Goerzen <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -} | Module : Network . FTP.Client . Parser Copyright : Copyright ( C ) 2004 License : GNU LGPL , version 2.1 or above Maintainer : < > Stability : provisional Portability : systems with networking This module provides a parser that is used internally by " Network . FTP.Client " . You almost certainly do not want to use this module directly . Use " Network . FTP.Client " instead . Written by , jgoerzen\@complete.org Module : Network.FTP.Client.Parser Copyright : Copyright (C) 2004 John Goerzen License : GNU LGPL, version 2.1 or above Maintainer : John Goerzen <> Stability : provisional Portability: systems with networking This module provides a parser that is used internally by "Network.FTP.Client". You almost certainly do not want to use this module directly. Use "Network.FTP.Client" instead. Written by John Goerzen, jgoerzen\@complete.org -} module Network.FTP.Client.Parser(parseReply, parseGoodReply, toPortString, fromPortString, debugParseGoodReply, respToSockAddr, FTPResult, unexpectedresp, isxresp, forcexresp, forceioresp, parseDirName) where import Data.Bits.Utils import Data.List.Utils import Data.String.Utils import Data.Word import Network.Socket import System.IO.Unsafe import System.Log.Logger import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Utils import Text.Regex type FTPResult = (Int, [String]) import Control . ) , throw ) logit :: String -> IO () logit m = debugM "Network.FTP.Client.Parser" ("FTP received: " ++ m) Utilities unexpectedresp m r = "FTP: Expected " ++ m ++ ", got " ++ (show r) isxresp desired (r, _) = r >= desired && r < (desired + 100) forcexresp desired r = if isxresp desired r then r else error ((unexpectedresp (show desired)) r) forceioresp :: Int -> FTPResult -> IO () forceioresp desired r = if isxresp desired r then return () else fail (unexpectedresp (show desired) r) crlf :: Parser String crlf = string "\r\n" <?> "CRLF" sp :: Parser Char sp = char ' ' code :: Parser Int code = do s <- codeString return (read s) codeString :: Parser String codeString = do first <- oneOf "123456789" <?> "3-digit reply code" remaining <- count 2 digit <?> "3-digit reply code" return (first : remaining) specificCode :: Int -> Parser Int specificCode exp = do s <- string (show exp) <?> ("Code " ++ (show exp)) return (read s) line :: Parser String line = do x <- many (noneOf "\r\n") crlf return $ unsafePerformIO $ putStrLn ( " line : " + + x ) return x singleReplyLine :: Parser (Int, String) singleReplyLine = do x <- code sp text <- line return (x, text) expectedReplyLine :: Int -> Parser (Int, String) expectedReplyLine expectedcode = do x <- specificCode expectedcode sp text <- line return (x, text) startOfMultiReply :: Parser (Int, String) startOfMultiReply = do x <- code char '-' text <- line return (x, text) multiReplyComponent :: Parser [String] multiReplyComponent = (try (do notMatching (do codeString sp ) "found unexpected code" thisLine <- line return ( ( " MRC : got " + + thisLine ) ) remainder <- multiReplyComponent return (thisLine : remainder) ) ) <|> return [] multiReply :: Parser FTPResult multiReply = try (do x <- singleReplyLine return (fst x, [snd x]) ) <|> (do start <- startOfMultiReply component <- multiReplyComponent end <- expectedReplyLine (fst start) return (fst start, snd start : (component ++ [snd end])) ) parseReply :: String -> FTPResult parseReply input = case parse multiReply "(unknown)" input of Left err -> error ("FTP: " ++ (show err)) Right reply -> reply parseGoodReply :: String -> IO FTPResult parseGoodReply input = let reply = parseReply input in if (fst reply) >= 400 then fail ("FTP:" ++ (show (fst reply)) ++ ": " ++ (join "\n" (snd reply))) else return reply debugParseGoodReply :: String -> IO FTPResult debugParseGoodReply contents = let logPlugin :: String -> String -> IO String logPlugin [] [] = return [] logPlugin [] accum = do logit accum return [] logPlugin (x:xs) accum = case x of '\n' -> do logit (strip (accum)) next <- unsafeInterleaveIO $ logPlugin xs [] return (x : next) y -> do next <- unsafeInterleaveIO $ logPlugin xs (accum ++ [x]) return (x : next) in do loggedStr <- logPlugin contents [] parseGoodReply loggedStr | Converts a socket address to a string suitable for a PORT command . Example : > toPortString ( SockAddrInet ( PortNum 0x1234 ) ( ) ) - > > " 170,187,204,221,18,52 " Example: > toPortString (SockAddrInet (PortNum 0x1234) (0xaabbccdd)) -> > "170,187,204,221,18,52" -} toPortString :: SockAddr -> IO String toPortString (SockAddrInet port hostaddr) = let wport = (fromIntegral (port))::Word16 (h1, h2, h3, h4) = hostAddressToTuple hostaddr in return . genericJoin "," $ map show [h1, h2, h3, h4] ++ map show (getBytes wport) toPortString _ = error "toPortString only works on AF_INET addresses" fromPortString :: String -> IO SockAddr fromPortString instr = let inbytes = split "," instr [h1, h2, h3, h4] = map read (take 4 inbytes) addr = tupleToHostAddress (h1, h2, h3, h4) portbytes = map read (drop 4 inbytes) in return $ SockAddrInet (fromInteger $ fromBytes portbytes) addr respToSockAddrRe = mkRegex("([0-9]+,){5}[0-9]+") respToSockAddr :: FTPResult -> IO SockAddr respToSockAddr f = do forceioresp 200 f if (fst f) /= 227 then fail ("Not a 227 response: " ++ show f) else case matchRegexAll respToSockAddrRe (head (snd f)) of Nothing -> fail ("Could not find remote endpoint in " ++ (show f)) Just (_, x, _, _) -> fromPortString x parseDirName :: FTPResult -> Maybe String parseDirName (257, name:_) = let procq [] = [] procq ('"':_) = [] procq ('"' : '"' : xs) = '"' : procq xs procq (x:xs) = x : procq xs in if head name /= '"' then Nothing else Just (procq (tail name))
604ce529236975e496b3f57580a62f74b2271d8b23de2302ee68ad37e4f6c780
pdincau/badalisk
badalisk_loglevel.erl
%%%------------------------------------------------------------------- %%% File : badalisk_loglevel.erl Author : < > %%% Description : %%% Created : 12 Aug 2011 by < > %%%------------------------------------------------------------------- -module(badalisk_loglevel). -author(""). -export([get/0, set/1]). -record(loglevel, {ordinal, name, description}). -include("../include/badalisk.hrl"). -define(LOG_MODULE, "error_logger"). -define(LOG_LEVELS, [ #loglevel{ordinal = 0, name = no_log, description = "No Logs (not reccomended)"}, #loglevel{ordinal = 1, name = critical, description = "Only critical logs"}, #loglevel{ordinal = 2, name = error, description = "Only errors and critical"}, #loglevel{ordinal = 3, name = warning, description = "Warnings, errors and critical"}, #loglevel{ordinal = 4, name = info, description = "Infos, warnings, errors and critical"}, #loglevel{ordinal = 5, name = debug, description = "Debug mode (developer only)"} ]). %%============================================================================================== %% Function: %% Description: %%============================================================================================== get() -> Level = badalisk_logger:get(), case lists:keysearch(Level, #loglevel.ordinal, ?LOG_LEVELS) of {value, Result} -> {Result#loglevel.ordinal, Result#loglevel.name, Result#loglevel.description}; _ -> erlang:error(no_such_level, Level) end. %%=============================================================================================== %% Function: %% Description: %%=============================================================================================== set(NewLevel) when is_atom(NewLevel) -> set(level_to_integer(NewLevel)); set(NewLevel) when is_integer(NewLevel) -> try {Module, Code} = dynamic_compile:from_string(badalisk_logger_src(NewLevel)), code:load_binary(Module, ?LOG_MODULE ++ ".erl", Code) catch Type:Error -> ?CRITICAL_MSG("Error compiling logger (~p): ~p", [Type, Error]) end; set(_) -> exit("Log Level must be an integer"). %%================================================================================================ %% Function: %% Description: %%================================================================================================ level_to_integer(Level) when is_integer(Level) -> Level; level_to_integer({Module, Level}) -> {Module, level_to_integer(Level)}; level_to_integer(Level) -> case lists:keysearch(Level, #loglevel.ordinal, ?LOG_LEVELS) of {value, #loglevel{ordinal = IntLevel}} -> IntLevel; _ -> erlang:error({no_such_level, Level}) end. %%------------------------------------------------------------------------------------------------- badalisk_logger code . I decided to chose the way of logging I have seen in ejabberd project . compiliing the module , we can reach a great optimization between logging verbosity %% switch. %%------------------------------------------------------------------------------------------------- badalisk_logger_src(LogLevel) -> L = integer_to_list(LogLevel), " -module(badalisk_logger). -author(''). -export([debug_msg/4, info_msg/4, warning_msg/4, error_msg/4, critical_msg/4, get/0]). get() -> " ++ L ++". %% Helper FUnctions debug_msg(Module, Line, Format, Args) when " ++ L ++ " >= 5 -> notify(info_msg, \"D(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); debug_msg(_,_,_,_) -> ok. info_msg(Module, Line, Format, Args) when " ++ L ++ " >= 4 -> notify(info_msg, \"I(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); info_msg(_,_,_,_) -> ok. warning_msg(Module, Line, Format, Args) when " ++ L ++ " >= 3 -> notify(error, \"W(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); warning_msg(_,_,_,_) -> ok. error_msg(Module, Line, Format, Args) when " ++ L ++ " >= 2 -> notify(error, \"E(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); error_msg(_,_,_,_) -> ok. critical_msg(Module, Line, Format, Args) when " ++ L ++ " >= 1 -> notify(error, \"C(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); critical_msg(_,_,_,_) -> ok. Distribute the message to the Erlang error logger notify(Type, Format, Args) -> LoggerMsg = {Type, group_leader(), {self(), Format, Args}}, gen_event:notify(error_logger, LoggerMsg). ".
null
https://raw.githubusercontent.com/pdincau/badalisk/ba08c63f0e09294a1719c2af1610bc4e91f99436/src/badalisk_loglevel.erl
erlang
------------------------------------------------------------------- File : badalisk_loglevel.erl Description : ------------------------------------------------------------------- ============================================================================================== Function: Description: ============================================================================================== =============================================================================================== Function: Description: =============================================================================================== ================================================================================================ Function: Description: ================================================================================================ ------------------------------------------------------------------------------------------------- switch. ------------------------------------------------------------------------------------------------- Helper FUnctions
Author : < > Created : 12 Aug 2011 by < > -module(badalisk_loglevel). -author(""). -export([get/0, set/1]). -record(loglevel, {ordinal, name, description}). -include("../include/badalisk.hrl"). -define(LOG_MODULE, "error_logger"). -define(LOG_LEVELS, [ #loglevel{ordinal = 0, name = no_log, description = "No Logs (not reccomended)"}, #loglevel{ordinal = 1, name = critical, description = "Only critical logs"}, #loglevel{ordinal = 2, name = error, description = "Only errors and critical"}, #loglevel{ordinal = 3, name = warning, description = "Warnings, errors and critical"}, #loglevel{ordinal = 4, name = info, description = "Infos, warnings, errors and critical"}, #loglevel{ordinal = 5, name = debug, description = "Debug mode (developer only)"} ]). get() -> Level = badalisk_logger:get(), case lists:keysearch(Level, #loglevel.ordinal, ?LOG_LEVELS) of {value, Result} -> {Result#loglevel.ordinal, Result#loglevel.name, Result#loglevel.description}; _ -> erlang:error(no_such_level, Level) end. set(NewLevel) when is_atom(NewLevel) -> set(level_to_integer(NewLevel)); set(NewLevel) when is_integer(NewLevel) -> try {Module, Code} = dynamic_compile:from_string(badalisk_logger_src(NewLevel)), code:load_binary(Module, ?LOG_MODULE ++ ".erl", Code) catch Type:Error -> ?CRITICAL_MSG("Error compiling logger (~p): ~p", [Type, Error]) end; set(_) -> exit("Log Level must be an integer"). level_to_integer(Level) when is_integer(Level) -> Level; level_to_integer({Module, Level}) -> {Module, level_to_integer(Level)}; level_to_integer(Level) -> case lists:keysearch(Level, #loglevel.ordinal, ?LOG_LEVELS) of {value, #loglevel{ordinal = IntLevel}} -> IntLevel; _ -> erlang:error({no_such_level, Level}) end. badalisk_logger code . I decided to chose the way of logging I have seen in ejabberd project . compiliing the module , we can reach a great optimization between logging verbosity badalisk_logger_src(LogLevel) -> L = integer_to_list(LogLevel), " -module(badalisk_logger). -author(''). -export([debug_msg/4, info_msg/4, warning_msg/4, error_msg/4, critical_msg/4, get/0]). get() -> " ++ L ++". debug_msg(Module, Line, Format, Args) when " ++ L ++ " >= 5 -> notify(info_msg, \"D(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); debug_msg(_,_,_,_) -> ok. info_msg(Module, Line, Format, Args) when " ++ L ++ " >= 4 -> notify(info_msg, \"I(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); info_msg(_,_,_,_) -> ok. warning_msg(Module, Line, Format, Args) when " ++ L ++ " >= 3 -> notify(error, \"W(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); warning_msg(_,_,_,_) -> ok. error_msg(Module, Line, Format, Args) when " ++ L ++ " >= 2 -> notify(error, \"E(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); error_msg(_,_,_,_) -> ok. critical_msg(Module, Line, Format, Args) when " ++ L ++ " >= 1 -> notify(error, \"C(~p:~p:~p) : \"++Format++\"~n\", [self(), Module, Line]++Args); critical_msg(_,_,_,_) -> ok. Distribute the message to the Erlang error logger notify(Type, Format, Args) -> LoggerMsg = {Type, group_leader(), {self(), Format, Args}}, gen_event:notify(error_logger, LoggerMsg). ".
7cae637d6a698a5d0be2ccaa90de3e31936e56c7c91939fda0611d903baf84a3
gedge-platform/gedge-platform
rabbit_federation_exchange_link_sup_sup.erl
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 /. %% Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . %% -module(rabbit_federation_exchange_link_sup_sup). -behaviour(mirrored_supervisor). -include_lib("rabbit_common/include/rabbit.hrl"). -define(SUPERVISOR, ?MODULE). %% Supervises the upstream links for all exchanges (but not queues). We need %% different handling here since exchanges want a mirrored sup. -export([start_link/0, start_child/1, adjust/1, stop_child/1]). -export([init/1]). %%---------------------------------------------------------------------------- start_link() -> _ = pg:start_link(), %% This scope is used by concurrently starting exchange and queue links, %% and other places, so we have to start it very early outside of the supervision tree. The scope is stopped in stop/1 . rabbit_federation_pg:start_scope(), mirrored_supervisor:start_link({local, ?SUPERVISOR}, ?SUPERVISOR, fun rabbit_misc:execute_mnesia_transaction/1, ?MODULE, []). %% Note that the next supervisor down, rabbit_federation_link_sup, is common %% between exchanges and queues. start_child(X) -> case mirrored_supervisor:start_child( ?SUPERVISOR, {id(X), {rabbit_federation_link_sup, start_link, [X]}, transient, ?SUPERVISOR_WAIT, supervisor, [rabbit_federation_link_sup]}) of {ok, _Pid} -> ok; {error, {already_started, _Pid}} -> #exchange{name = ExchangeName} = X, _ = rabbit_log_federation:debug("Federation link for exchange ~p was already started", [rabbit_misc:rs(ExchangeName)]), ok; %% A link returned {stop, gone}, the link_sup shut down, that's OK. {error, {shutdown, _}} -> ok end. adjust({clear_upstream, VHost, UpstreamName}) -> [rabbit_federation_link_sup:adjust(Pid, X, {clear_upstream, UpstreamName}) || {#exchange{name = Name} = X, Pid, _, _} <- mirrored_supervisor:which_children(?SUPERVISOR), Name#resource.virtual_host == VHost], ok; adjust(Reason) -> [rabbit_federation_link_sup:adjust(Pid, X, Reason) || {X, Pid, _, _} <- mirrored_supervisor:which_children(?SUPERVISOR)], ok. stop_child(X) -> case mirrored_supervisor:terminate_child(?SUPERVISOR, id(X)) of ok -> ok; {error, Err} -> #exchange{name = ExchangeName} = X, _ = rabbit_log_federation:warning( "Attempt to stop a federation link for exchange ~p failed: ~p", [rabbit_misc:rs(ExchangeName), Err]), ok end, ok = mirrored_supervisor:delete_child(?SUPERVISOR, id(X)). %%---------------------------------------------------------------------------- init([]) -> {ok, {{one_for_one, 1200, 60}, []}}. %% See comment in rabbit_federation_queue_link_sup_sup:id/1 id(X = #exchange{policy = Policy}) -> X1 = rabbit_exchange:immutable(X), X1#exchange{policy = Policy}.
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_federation/src/rabbit_federation_exchange_link_sup_sup.erl
erlang
Supervises the upstream links for all exchanges (but not queues). We need different handling here since exchanges want a mirrored sup. ---------------------------------------------------------------------------- This scope is used by concurrently starting exchange and queue links, and other places, so we have to start it very early outside of the supervision tree. Note that the next supervisor down, rabbit_federation_link_sup, is common between exchanges and queues. A link returned {stop, gone}, the link_sup shut down, that's OK. ---------------------------------------------------------------------------- See comment in rabbit_federation_queue_link_sup_sup:id/1
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 /. Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved . -module(rabbit_federation_exchange_link_sup_sup). -behaviour(mirrored_supervisor). -include_lib("rabbit_common/include/rabbit.hrl"). -define(SUPERVISOR, ?MODULE). -export([start_link/0, start_child/1, adjust/1, stop_child/1]). -export([init/1]). start_link() -> _ = pg:start_link(), The scope is stopped in stop/1 . rabbit_federation_pg:start_scope(), mirrored_supervisor:start_link({local, ?SUPERVISOR}, ?SUPERVISOR, fun rabbit_misc:execute_mnesia_transaction/1, ?MODULE, []). start_child(X) -> case mirrored_supervisor:start_child( ?SUPERVISOR, {id(X), {rabbit_federation_link_sup, start_link, [X]}, transient, ?SUPERVISOR_WAIT, supervisor, [rabbit_federation_link_sup]}) of {ok, _Pid} -> ok; {error, {already_started, _Pid}} -> #exchange{name = ExchangeName} = X, _ = rabbit_log_federation:debug("Federation link for exchange ~p was already started", [rabbit_misc:rs(ExchangeName)]), ok; {error, {shutdown, _}} -> ok end. adjust({clear_upstream, VHost, UpstreamName}) -> [rabbit_federation_link_sup:adjust(Pid, X, {clear_upstream, UpstreamName}) || {#exchange{name = Name} = X, Pid, _, _} <- mirrored_supervisor:which_children(?SUPERVISOR), Name#resource.virtual_host == VHost], ok; adjust(Reason) -> [rabbit_federation_link_sup:adjust(Pid, X, Reason) || {X, Pid, _, _} <- mirrored_supervisor:which_children(?SUPERVISOR)], ok. stop_child(X) -> case mirrored_supervisor:terminate_child(?SUPERVISOR, id(X)) of ok -> ok; {error, Err} -> #exchange{name = ExchangeName} = X, _ = rabbit_log_federation:warning( "Attempt to stop a federation link for exchange ~p failed: ~p", [rabbit_misc:rs(ExchangeName), Err]), ok end, ok = mirrored_supervisor:delete_child(?SUPERVISOR, id(X)). init([]) -> {ok, {{one_for_one, 1200, 60}, []}}. id(X = #exchange{policy = Policy}) -> X1 = rabbit_exchange:immutable(X), X1#exchange{policy = Policy}.
b5224e6c9d09645236ff5313fa417c2b6c03dbf3273089be15188da6b32f3bd7
4y8/esoo
flurry.ml
type token = Nil_paren | Nil_curly | Nil_brack | Nil_angle | Mon_paren of token list | Mon_curly of token list | Mon_brack of token list | Mon_angle of token list type combinator = I | K | S | T of combinator * combinator let rec church = function 0 -> T(K, I) | 1 -> I | n -> T(T(S, T(T(S, T(K, S)), K)), (church (n-1))) let eval input stack = let rec lex pos = let rec goto num chr alt_chr pos = match String.get input pos with c when alt_chr = c -> goto (num + 1) chr alt_chr (pos + 1) | c when (chr = c) && (num = 0) -> pos + 1 | c when chr = c -> goto (num - 1) chr alt_chr (pos + 1) | _ -> goto num chr alt_chr (pos + 1) in match pos with len when len = ((String.length input) - 1) -> begin match (String.get input pos) with '>' | '}' | ')' | ']' -> [] | _ -> raise (Invalid_argument "Unbalanced brackets") end | len when len > ((String.length input) - 1) -> [] | _ -> match (String.get input pos), (String.get input (pos + 1)) with '<', '>' -> Nil_angle :: lex (pos + 2) | '(', ')' -> Nil_paren :: lex (pos + 2) | '[', ']' -> Nil_brack :: lex (pos + 2) | '{', '}' -> Nil_curly :: lex (pos + 2) | '(', _ -> Mon_paren (lex (pos + 1)) :: lex (goto 0 ')' '(' (pos + 1)) | '{', _ -> Mon_curly (lex (pos + 1)) :: lex (goto 0 '}' '{' (pos + 1)) | '[', _ -> Mon_brack (lex (pos + 1)) :: lex (goto 0 ']' '[' (pos + 1)) | '<', _ -> Mon_angle (lex (pos + 1)) :: lex (goto 0 '>' '<' (pos + 1)) | '>', _ | '}', _ | ')', _ | ']', _ -> [] | _, _ -> lex (pos + 2) in (* This part is -stolen- inspired by : *) let rec simplify comb = match comb with I | K | S -> comb | T (I, x) -> simplify x | T (T (K, x), _) -> simplify x | T (T (T (S, K), K), x) -> simplify x | T (T (T (S, I), I), x) -> simplify (T(x, x)) | T (T (T (S, x), y), z) -> simplify (T ((T (x, z)), T(y, z))) | T (left, right) -> let left' = simplify left in let right' = simplify right in if left = left' && right = right' then T (left, right) else simplify (T (left', right')) in let rec reduce combs = let rec to_comb comb toks = match toks with [] -> comb | hd :: tl -> to_comb (T(comb, hd)) tl in let final_comb = to_comb (List.hd combs) (List.tl combs) in simplify final_comb in let rec exec tokens stack = match tokens with [] -> [], stack | Nil_angle :: tl -> let combtl, nstack = exec tl stack in S :: combtl, nstack | Nil_paren :: tl -> let combtl, nstack = exec tl stack in K :: combtl, nstack | Nil_brack :: tl -> let combtl, nstack = exec tl stack in (church (List.length stack)) :: combtl, nstack | Nil_curly :: tl -> begin match stack with [] -> let combtl, nstack = exec tl stack in I :: combtl, nstack | hd :: tl' -> let combtl, nstack = exec tl tl' in hd :: combtl, nstack end | Mon_paren (body) :: tl -> let n, nstack = exec body stack in let combtl, fstack = exec tl ((reduce n) :: nstack) in (reduce n) :: combtl, fstack | Mon_brack (body) :: tl -> let n, nstack = exec body stack in let combtl, fstack = exec tl nstack in (reduce n) :: combtl, fstack | Mon_curly (body) :: tl -> let n, nstack = exec body stack in let arg, argstack = exec [(List.hd tl)] nstack in let combtl, fstack = exec (List.tl tl) ((reduce arg)::argstack) in (reduce n) :: combtl, fstack | Mon_angle (body) :: tl -> let rec compose combs = match combs with hd :: [] -> hd | hd :: tl -> T(hd, (compose tl)) | _ -> raise Not_found in let n, nstack = exec body stack in let combtl, fstack = exec tl nstack in (simplify (compose n)) :: combtl, fstack in let tokens = lex 0 in let skis, fstack = exec tokens stack in let ski = reduce skis in ski, fstack let rec repl stack args = print_string "> "; let rec ski_to_str comb = match comb with I -> "I" | K -> "K" | S -> "S" | T(x, y) -> "(" ^ ski_to_str x ^ ski_to_str y ^ ")" in let ski, nstack = eval (read_line()) (stack @ (List.map church args)) in print_endline (ski_to_str ski); repl nstack []
null
https://raw.githubusercontent.com/4y8/esoo/49f9b8bd70c1f41bf2d4db044d0cfede4e1ff470/flurry/flurry.ml
ocaml
This part is -stolen- inspired by :
type token = Nil_paren | Nil_curly | Nil_brack | Nil_angle | Mon_paren of token list | Mon_curly of token list | Mon_brack of token list | Mon_angle of token list type combinator = I | K | S | T of combinator * combinator let rec church = function 0 -> T(K, I) | 1 -> I | n -> T(T(S, T(T(S, T(K, S)), K)), (church (n-1))) let eval input stack = let rec lex pos = let rec goto num chr alt_chr pos = match String.get input pos with c when alt_chr = c -> goto (num + 1) chr alt_chr (pos + 1) | c when (chr = c) && (num = 0) -> pos + 1 | c when chr = c -> goto (num - 1) chr alt_chr (pos + 1) | _ -> goto num chr alt_chr (pos + 1) in match pos with len when len = ((String.length input) - 1) -> begin match (String.get input pos) with '>' | '}' | ')' | ']' -> [] | _ -> raise (Invalid_argument "Unbalanced brackets") end | len when len > ((String.length input) - 1) -> [] | _ -> match (String.get input pos), (String.get input (pos + 1)) with '<', '>' -> Nil_angle :: lex (pos + 2) | '(', ')' -> Nil_paren :: lex (pos + 2) | '[', ']' -> Nil_brack :: lex (pos + 2) | '{', '}' -> Nil_curly :: lex (pos + 2) | '(', _ -> Mon_paren (lex (pos + 1)) :: lex (goto 0 ')' '(' (pos + 1)) | '{', _ -> Mon_curly (lex (pos + 1)) :: lex (goto 0 '}' '{' (pos + 1)) | '[', _ -> Mon_brack (lex (pos + 1)) :: lex (goto 0 ']' '[' (pos + 1)) | '<', _ -> Mon_angle (lex (pos + 1)) :: lex (goto 0 '>' '<' (pos + 1)) | '>', _ | '}', _ | ')', _ | ']', _ -> [] | _, _ -> lex (pos + 2) in let rec simplify comb = match comb with I | K | S -> comb | T (I, x) -> simplify x | T (T (K, x), _) -> simplify x | T (T (T (S, K), K), x) -> simplify x | T (T (T (S, I), I), x) -> simplify (T(x, x)) | T (T (T (S, x), y), z) -> simplify (T ((T (x, z)), T(y, z))) | T (left, right) -> let left' = simplify left in let right' = simplify right in if left = left' && right = right' then T (left, right) else simplify (T (left', right')) in let rec reduce combs = let rec to_comb comb toks = match toks with [] -> comb | hd :: tl -> to_comb (T(comb, hd)) tl in let final_comb = to_comb (List.hd combs) (List.tl combs) in simplify final_comb in let rec exec tokens stack = match tokens with [] -> [], stack | Nil_angle :: tl -> let combtl, nstack = exec tl stack in S :: combtl, nstack | Nil_paren :: tl -> let combtl, nstack = exec tl stack in K :: combtl, nstack | Nil_brack :: tl -> let combtl, nstack = exec tl stack in (church (List.length stack)) :: combtl, nstack | Nil_curly :: tl -> begin match stack with [] -> let combtl, nstack = exec tl stack in I :: combtl, nstack | hd :: tl' -> let combtl, nstack = exec tl tl' in hd :: combtl, nstack end | Mon_paren (body) :: tl -> let n, nstack = exec body stack in let combtl, fstack = exec tl ((reduce n) :: nstack) in (reduce n) :: combtl, fstack | Mon_brack (body) :: tl -> let n, nstack = exec body stack in let combtl, fstack = exec tl nstack in (reduce n) :: combtl, fstack | Mon_curly (body) :: tl -> let n, nstack = exec body stack in let arg, argstack = exec [(List.hd tl)] nstack in let combtl, fstack = exec (List.tl tl) ((reduce arg)::argstack) in (reduce n) :: combtl, fstack | Mon_angle (body) :: tl -> let rec compose combs = match combs with hd :: [] -> hd | hd :: tl -> T(hd, (compose tl)) | _ -> raise Not_found in let n, nstack = exec body stack in let combtl, fstack = exec tl nstack in (simplify (compose n)) :: combtl, fstack in let tokens = lex 0 in let skis, fstack = exec tokens stack in let ski = reduce skis in ski, fstack let rec repl stack args = print_string "> "; let rec ski_to_str comb = match comb with I -> "I" | K -> "K" | S -> "S" | T(x, y) -> "(" ^ ski_to_str x ^ ski_to_str y ^ ")" in let ski, nstack = eval (read_line()) (stack @ (List.map church args)) in print_endline (ski_to_str ski); repl nstack []
f769a9876fa37db09bf174efe0d8ca97e079eead4fa71630c1f13da1caffda05
haskell-servant/servant
Auth.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} -- | Authentication for clients module Servant.Client.Core.Auth ( AuthClientData, AuthenticatedRequest (..), mkAuthenticatedRequest, ) where import Servant.Client.Core.Request (Request) | For a resource protected by authentication ( e.g. AuthProtect ) , we need -- to provide the client with some data used to add authentication data -- to a request -- -- NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE type family AuthClientData a :: * -- | For better type inference and to avoid usage of a data family, we newtype -- wrap the combination of some 'AuthClientData' and a function to add authentication -- data to a request -- -- NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE newtype AuthenticatedRequest a = AuthenticatedRequest { unAuthReq :: (AuthClientData a, AuthClientData a -> Request -> Request) } -- | Handy helper to avoid wrapping datatypes in tuples everywhere. -- -- NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE mkAuthenticatedRequest :: AuthClientData a -> (AuthClientData a -> Request -> Request) -> AuthenticatedRequest a mkAuthenticatedRequest val func = AuthenticatedRequest (val, func)
null
https://raw.githubusercontent.com/haskell-servant/servant/d06b65c4e6116f992debbac2eeeb83eafb960321/servant-client-core/src/Servant/Client/Core/Auth.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # # LANGUAGE TypeSynonymInstances # | Authentication for clients to provide the client with some data used to add authentication data to a request NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE | For better type inference and to avoid usage of a data family, we newtype wrap the combination of some 'AuthClientData' and a function to add authentication data to a request NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE | Handy helper to avoid wrapping datatypes in tuples everywhere. NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE
module Servant.Client.Core.Auth ( AuthClientData, AuthenticatedRequest (..), mkAuthenticatedRequest, ) where import Servant.Client.Core.Request (Request) | For a resource protected by authentication ( e.g. AuthProtect ) , we need type family AuthClientData a :: * newtype AuthenticatedRequest a = AuthenticatedRequest { unAuthReq :: (AuthClientData a, AuthClientData a -> Request -> Request) } mkAuthenticatedRequest :: AuthClientData a -> (AuthClientData a -> Request -> Request) -> AuthenticatedRequest a mkAuthenticatedRequest val func = AuthenticatedRequest (val, func)
c5afbf1d6f630e625f5d17dec02be7432426d01bb9fe697ddd3464f765a81864
TrustInSoft/tis-interpreter
rgmap.mli
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 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 ) . (* *) (**************************************************************************) * Associative maps for _ ranges _ to _ values _ with overlaping . The maps register a collection of entries , and looks for all entries containing some specified range . For instance , this data structure is well suited to attach tags to AST - nodes in GUI , where each node is associated to buffer offset ranges . When seveal entries cover a range , precedence goes to the tightest ones . When overlapping entries with the same width applies , the result of lookup is not specified . Remark that for AST - based ranges , overlapping ranges are always included one in the order . Current implementation has average [ log(n ) ] complexity for adding [ n ] entries , and [ log(n)^2 ] for lookup ranges , which is far from better than current implementation used in [ Pretty_source ] for instance . The maps register a collection of entries, and looks for all entries containing some specified range. For instance, this data structure is well suited to attach tags to AST-nodes in GUI, where each node is associated to buffer offset ranges. When seveal entries cover a range, precedence goes to the tightest ones. When overlapping entries with the same width applies, the result of lookup is not specified. Remark that for AST-based ranges, overlapping ranges are always included one in the order. Current implementation has average [log(n)] complexity for adding [n] entries, and [log(n)^2] for lookup ranges, which is far from better than current implementation used in [Pretty_source] for instance. *) type 'a t (** The type of range maps, containing of collection of ['a entry]. *) type 'a entry = int * int * 'a (** Entry [(a,b,v)] maps range [a..b] (both inclued) to value [v] in the map. *) val empty : 'a t (** The empty map. *) val add : ?overlap:bool -> 'a entry -> 'a t -> 'a t * Returns a new map with the added entry . When [ ~overlap : true ] is specified , overlapping entries with the same width are removed first , avoiding under - specified results . It is safe to ignore this attribute for AST - based maps . overlapping entries with the same width are removed first, avoiding under-specified results. It is safe to ignore this attribute for AST-based maps. *) val find : int -> int -> 'a t -> 'a entry (** Find the tighest entry containing the specified range. @raise Not_found if no entry applies *) val find_all : int -> int -> 'a t -> 'a entry list * Find all entries containing the specified range . Returns the empty list is none applies . When overlapping entries with the same width are present in the map , only one for each width is returned . is none applies. When overlapping entries with the same width are present in the map, only one for each width is returned. *) val iter : ('a entry -> unit) -> 'a t -> unit (** Iter over all entries present in the map. Entries are present in increasing order of width. *)
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/libraries/utils/rgmap.mli
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. ************************************************************************ * The type of range maps, containing of collection of ['a entry]. * Entry [(a,b,v)] maps range [a..b] (both inclued) to value [v] in the map. * The empty map. * Find the tighest entry containing the specified range. @raise Not_found if no entry applies * Iter over all entries present in the map. Entries are present in increasing order of width.
This file is part of Frama - C. Copyright ( C ) 2007 - 2015 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 ) . * Associative maps for _ ranges _ to _ values _ with overlaping . The maps register a collection of entries , and looks for all entries containing some specified range . For instance , this data structure is well suited to attach tags to AST - nodes in GUI , where each node is associated to buffer offset ranges . When seveal entries cover a range , precedence goes to the tightest ones . When overlapping entries with the same width applies , the result of lookup is not specified . Remark that for AST - based ranges , overlapping ranges are always included one in the order . Current implementation has average [ log(n ) ] complexity for adding [ n ] entries , and [ log(n)^2 ] for lookup ranges , which is far from better than current implementation used in [ Pretty_source ] for instance . The maps register a collection of entries, and looks for all entries containing some specified range. For instance, this data structure is well suited to attach tags to AST-nodes in GUI, where each node is associated to buffer offset ranges. When seveal entries cover a range, precedence goes to the tightest ones. When overlapping entries with the same width applies, the result of lookup is not specified. Remark that for AST-based ranges, overlapping ranges are always included one in the order. Current implementation has average [log(n)] complexity for adding [n] entries, and [log(n)^2] for lookup ranges, which is far from better than current implementation used in [Pretty_source] for instance. *) type 'a t type 'a entry = int * int * 'a val empty : 'a t val add : ?overlap:bool -> 'a entry -> 'a t -> 'a t * Returns a new map with the added entry . When [ ~overlap : true ] is specified , overlapping entries with the same width are removed first , avoiding under - specified results . It is safe to ignore this attribute for AST - based maps . overlapping entries with the same width are removed first, avoiding under-specified results. It is safe to ignore this attribute for AST-based maps. *) val find : int -> int -> 'a t -> 'a entry val find_all : int -> int -> 'a t -> 'a entry list * Find all entries containing the specified range . Returns the empty list is none applies . When overlapping entries with the same width are present in the map , only one for each width is returned . is none applies. When overlapping entries with the same width are present in the map, only one for each width is returned. *) val iter : ('a entry -> unit) -> 'a t -> unit
66223d7bef82ae16fb9476e04f26b7212b83b532635acb54fbd23ca0b14dc236
ndmitchell/safe
Foldable.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE ConstraintKinds #-} {- | 'Foldable' functions, with wrappers like the "Safe" module. -} module Safe.Foldable( -- * New functions findJust, -- * Safe wrappers foldl1May, foldl1Def, foldl1Note, foldr1May, foldr1Def, foldr1Note, findJustDef, findJustNote, minimumMay, minimumNote, maximumMay, maximumNote, minimumByMay, minimumByNote, maximumByMay, maximumByNote, maximumBoundBy, minimumBoundBy, maximumBounded, maximumBound, minimumBounded, minimumBound, -- * Discouraged minimumDef, maximumDef, minimumByDef, maximumByDef, -- * Deprecated foldl1Safe, foldr1Safe, findJustSafe, ) where import Safe.Util import Data.Foldable as F import Data.Maybe import Data.Monoid import Prelude import Safe.Partial --------------------------------------------------------------------- UTILITIES fromNote :: Partial => String -> String -> Maybe a -> a fromNote = fromNoteModule "Safe.Foldable" --------------------------------------------------------------------- WRAPPERS foldl1May, foldr1May :: Foldable t => (a -> a -> a) -> t a -> Maybe a foldl1May = liftMay F.null . F.foldl1 foldr1May = liftMay F.null . F.foldr1 foldl1Note, foldr1Note :: (Partial, Foldable t) => String -> (a -> a -> a) -> t a -> a foldl1Note note f x = withFrozenCallStack $ fromNote note "foldl1Note on empty" $ foldl1May f x foldr1Note note f x = withFrozenCallStack $ fromNote note "foldr1Note on empty" $ foldr1May f x minimumMay, maximumMay :: (Foldable t, Ord a) => t a -> Maybe a minimumMay = liftMay F.null F.minimum maximumMay = liftMay F.null F.maximum minimumNote, maximumNote :: (Partial, Foldable t, Ord a) => String -> t a -> a minimumNote note x = withFrozenCallStack $ fromNote note "minimumNote on empty" $ minimumMay x maximumNote note x = withFrozenCallStack $ fromNote note "maximumNote on empty" $ maximumMay x minimumByMay, maximumByMay :: Foldable t => (a -> a -> Ordering) -> t a -> Maybe a minimumByMay = liftMay F.null . F.minimumBy maximumByMay = liftMay F.null . F.maximumBy minimumByNote, maximumByNote :: (Partial, Foldable t) => String -> (a -> a -> Ordering) -> t a -> a minimumByNote note f x = withFrozenCallStack $ fromNote note "minimumByNote on empty" $ minimumByMay f x maximumByNote note f x = withFrozenCallStack $ fromNote note "maximumByNote on empty" $ maximumByMay f x -- | The largest element of a foldable structure with respect to the given comparison function . The result is bounded by the value given as the first argument . maximumBoundBy :: Foldable f => a -> (a -> a -> Ordering) -> f a -> a maximumBoundBy x f xs = maximumBy f $ x : toList xs -- | The smallest element of a foldable structure with respect to the given comparison function . The result is bounded by the value given as the first argument . minimumBoundBy :: Foldable f => a -> (a -> a -> Ordering) -> f a -> a minimumBoundBy x f xs = minimumBy f $ x : toList xs -- | The largest element of a foldable structure. The result is bounded by the value given as the first argument . maximumBound :: (Foldable f, Ord a) => a -> f a -> a maximumBound x xs = maximum $ x : toList xs -- | The smallest element of a foldable structure. The result is bounded by the value given as the first argument . minimumBound :: (Foldable f, Ord a) => a -> f a -> a minimumBound x xs = minimum $ x : toList xs -- | The largest element of a foldable structure. The result is bounded by ' ' . maximumBounded :: (Foldable f, Ord a, Bounded a) => f a -> a maximumBounded = maximumBound minBound -- | The largest element of a foldable structure. The result is bounded by ' maxBound ' . minimumBounded :: (Foldable f, Ord a, Bounded a) => f a -> a minimumBounded = minimumBound maxBound -- | > findJust op = fromJust . find op findJust :: (Partial, Foldable t) => (a -> Bool) -> t a -> a findJust f x = withFrozenCallStack $ fromNote "" "findJust, no matching value" $ F.find f x findJustDef :: Foldable t => a -> (a -> Bool) -> t a -> a findJustDef def = fromMaybe def .^ F.find findJustNote :: (Partial, Foldable t) => String -> (a -> Bool) -> t a -> a findJustNote note f x = withFrozenCallStack $ fromNote note "findJustNote, no matching value" $ F.find f x --------------------------------------------------------------------- DISCOURAGED | New users are recommended to use ' ' or ' maximumBound ' instead . minimumDef, maximumDef :: (Foldable t, Ord a) => a -> t a -> a minimumDef def = fromMaybe def . minimumMay maximumDef def = fromMaybe def . maximumMay -- | New users are recommended to use 'minimumBoundBy' or 'maximumBoundBy' instead. minimumByDef, maximumByDef :: Foldable t => a -> (a -> a -> Ordering) -> t a -> a minimumByDef def = fromMaybe def .^ minimumByMay maximumByDef def = fromMaybe def .^ maximumByMay | New users are recommended to use ' foldr1May ' or ' foldl1May ' instead . foldl1Def, foldr1Def :: Foldable t => a -> (a -> a -> a) -> t a -> a foldl1Def def = fromMaybe def .^ foldl1May foldr1Def def = fromMaybe def .^ foldr1May --------------------------------------------------------------------- -- DEPRECATED {-# DEPRECATED foldl1Safe "Use @foldl f mempty@ instead." #-} foldl1Safe :: (Monoid m, Foldable t) => (m -> m -> m) -> t m -> m foldl1Safe fun = F.foldl fun mempty {-# DEPRECATED foldr1Safe "Use @foldr f mempty@ instead." #-} foldr1Safe :: (Monoid m, Foldable t) => (m -> m -> m) -> t m -> m foldr1Safe fun = F.foldr fun mempty {-# DEPRECATED findJustSafe "Use @findJustDef mempty@ instead." #-} findJustSafe :: (Monoid m, Foldable t) => (m -> Bool) -> t m -> m findJustSafe = findJustDef mempty
null
https://raw.githubusercontent.com/ndmitchell/safe/c490d6b36b461159ab29b3da9133948e4ec1db45/Safe/Foldable.hs
haskell
# LANGUAGE ConstraintKinds # | 'Foldable' functions, with wrappers like the "Safe" module. * New functions * Safe wrappers * Discouraged * Deprecated ------------------------------------------------------------------- ------------------------------------------------------------------- | The largest element of a foldable structure with respect to the | The smallest element of a foldable structure with respect to the | The largest element of a foldable structure. | The smallest element of a foldable structure. | The largest element of a foldable structure. | The largest element of a foldable structure. | ------------------------------------------------------------------- | New users are recommended to use 'minimumBoundBy' or 'maximumBoundBy' instead. ------------------------------------------------------------------- DEPRECATED # DEPRECATED foldl1Safe "Use @foldl f mempty@ instead." # # DEPRECATED foldr1Safe "Use @foldr f mempty@ instead." # # DEPRECATED findJustSafe "Use @findJustDef mempty@ instead." #
# LANGUAGE FlexibleContexts # module Safe.Foldable( findJust, foldl1May, foldl1Def, foldl1Note, foldr1May, foldr1Def, foldr1Note, findJustDef, findJustNote, minimumMay, minimumNote, maximumMay, maximumNote, minimumByMay, minimumByNote, maximumByMay, maximumByNote, maximumBoundBy, minimumBoundBy, maximumBounded, maximumBound, minimumBounded, minimumBound, minimumDef, maximumDef, minimumByDef, maximumByDef, foldl1Safe, foldr1Safe, findJustSafe, ) where import Safe.Util import Data.Foldable as F import Data.Maybe import Data.Monoid import Prelude import Safe.Partial UTILITIES fromNote :: Partial => String -> String -> Maybe a -> a fromNote = fromNoteModule "Safe.Foldable" WRAPPERS foldl1May, foldr1May :: Foldable t => (a -> a -> a) -> t a -> Maybe a foldl1May = liftMay F.null . F.foldl1 foldr1May = liftMay F.null . F.foldr1 foldl1Note, foldr1Note :: (Partial, Foldable t) => String -> (a -> a -> a) -> t a -> a foldl1Note note f x = withFrozenCallStack $ fromNote note "foldl1Note on empty" $ foldl1May f x foldr1Note note f x = withFrozenCallStack $ fromNote note "foldr1Note on empty" $ foldr1May f x minimumMay, maximumMay :: (Foldable t, Ord a) => t a -> Maybe a minimumMay = liftMay F.null F.minimum maximumMay = liftMay F.null F.maximum minimumNote, maximumNote :: (Partial, Foldable t, Ord a) => String -> t a -> a minimumNote note x = withFrozenCallStack $ fromNote note "minimumNote on empty" $ minimumMay x maximumNote note x = withFrozenCallStack $ fromNote note "maximumNote on empty" $ maximumMay x minimumByMay, maximumByMay :: Foldable t => (a -> a -> Ordering) -> t a -> Maybe a minimumByMay = liftMay F.null . F.minimumBy maximumByMay = liftMay F.null . F.maximumBy minimumByNote, maximumByNote :: (Partial, Foldable t) => String -> (a -> a -> Ordering) -> t a -> a minimumByNote note f x = withFrozenCallStack $ fromNote note "minimumByNote on empty" $ minimumByMay f x maximumByNote note f x = withFrozenCallStack $ fromNote note "maximumByNote on empty" $ maximumByMay f x given comparison function . The result is bounded by the value given as the first argument . maximumBoundBy :: Foldable f => a -> (a -> a -> Ordering) -> f a -> a maximumBoundBy x f xs = maximumBy f $ x : toList xs given comparison function . The result is bounded by the value given as the first argument . minimumBoundBy :: Foldable f => a -> (a -> a -> Ordering) -> f a -> a minimumBoundBy x f xs = minimumBy f $ x : toList xs The result is bounded by the value given as the first argument . maximumBound :: (Foldable f, Ord a) => a -> f a -> a maximumBound x xs = maximum $ x : toList xs The result is bounded by the value given as the first argument . minimumBound :: (Foldable f, Ord a) => a -> f a -> a minimumBound x xs = minimum $ x : toList xs The result is bounded by ' ' . maximumBounded :: (Foldable f, Ord a, Bounded a) => f a -> a maximumBounded = maximumBound minBound The result is bounded by ' maxBound ' . minimumBounded :: (Foldable f, Ord a, Bounded a) => f a -> a minimumBounded = minimumBound maxBound > findJust op = fromJust . find op findJust :: (Partial, Foldable t) => (a -> Bool) -> t a -> a findJust f x = withFrozenCallStack $ fromNote "" "findJust, no matching value" $ F.find f x findJustDef :: Foldable t => a -> (a -> Bool) -> t a -> a findJustDef def = fromMaybe def .^ F.find findJustNote :: (Partial, Foldable t) => String -> (a -> Bool) -> t a -> a findJustNote note f x = withFrozenCallStack $ fromNote note "findJustNote, no matching value" $ F.find f x DISCOURAGED | New users are recommended to use ' ' or ' maximumBound ' instead . minimumDef, maximumDef :: (Foldable t, Ord a) => a -> t a -> a minimumDef def = fromMaybe def . minimumMay maximumDef def = fromMaybe def . maximumMay minimumByDef, maximumByDef :: Foldable t => a -> (a -> a -> Ordering) -> t a -> a minimumByDef def = fromMaybe def .^ minimumByMay maximumByDef def = fromMaybe def .^ maximumByMay | New users are recommended to use ' foldr1May ' or ' foldl1May ' instead . foldl1Def, foldr1Def :: Foldable t => a -> (a -> a -> a) -> t a -> a foldl1Def def = fromMaybe def .^ foldl1May foldr1Def def = fromMaybe def .^ foldr1May foldl1Safe :: (Monoid m, Foldable t) => (m -> m -> m) -> t m -> m foldl1Safe fun = F.foldl fun mempty foldr1Safe :: (Monoid m, Foldable t) => (m -> m -> m) -> t m -> m foldr1Safe fun = F.foldr fun mempty findJustSafe :: (Monoid m, Foldable t) => (m -> Bool) -> t m -> m findJustSafe = findJustDef mempty
8c9b5e3faa0a78711dcd0220902c495c4aba0ff6b0f945e12b4f15240f7f2957
tommaisey/aeon
free-self.help.scm
;; (free-self src) ;; free enclosing synth when the input signal `src' crosses from ;; non-positive to positive. (audition (mrg2 (free-self (mouse-x kr -1 1 0 0.1)) (out 0 (mul (sin-osc ar 440 0) 0.1))))
null
https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/envelopes/free-self.help.scm
scheme
(free-self src) free enclosing synth when the input signal `src' crosses from non-positive to positive.
(audition (mrg2 (free-self (mouse-x kr -1 1 0 0.1)) (out 0 (mul (sin-osc ar 440 0) 0.1))))
473819f031b737177c472be042fde3c5bcba5890326054b234ceeb88243c1848
nobrakal/asak
partition.mli
This file is part of asak . * * Copyright ( C ) 2019 IRIF / OCaml Software Foundation . * * asak is distributed under the terms of the MIT license . See the * included LICENSE file for details . * * Copyright (C) 2019 IRIF / OCaml Software Foundation. * * asak is distributed under the terms of the MIT license. See the * included LICENSE file for details. *) (** Type used to represent a partition. *) type 'a partition = { bad_type : 'a list ; (** Keys identifying codes that either don't implement the searched function, or implement it with a bad type. *) clusters : ('a * string) list Wtree.wtree list (** Main result. Each class is composed of a tree representing a hierarchical clustering of "similar codes". Each leaf is a list of keys identifying "totally similar" codes, plus the considered code. *) } * Partitioning OCaml codes . Usage : [ create threshold name sol list ] . @param threshold Weight threshold required to keep a sub - AST . It is a percentage ( a number between 0 and 100 ) of the weight of the whole AST . - A value of 0 means " keep all sub - ASTs " - A value of 100 means " do n't keep any sub - AST " @param name The name of the searched function . @param sol A reference implementation , used only for typing . @param list List of valid OCaml codes , using only installed modules , that may contains the searched function . @return The partition . @param threshold Weight threshold required to keep a sub-AST. It is a percentage (a number between 0 and 100) of the weight of the whole AST. - A value of 0 means "keep all sub-ASTs" - A value of 100 means "don't keep any sub-AST" @param name The name of the searched function. @param sol A reference implementation, used only for typing. @param list List of valid OCaml codes, using only installed modules, that may contains the searched function. @return The partition. *) val create : int -> string -> string -> ('a * string) list -> 'a partition
null
https://raw.githubusercontent.com/nobrakal/asak/c1aaf985815563edd2463f8fe18e2d790f955f05/src/partition.mli
ocaml
* Type used to represent a partition. * Keys identifying codes that either don't implement the searched function, or implement it with a bad type. * Main result. Each class is composed of a tree representing a hierarchical clustering of "similar codes". Each leaf is a list of keys identifying "totally similar" codes, plus the considered code.
This file is part of asak . * * Copyright ( C ) 2019 IRIF / OCaml Software Foundation . * * asak is distributed under the terms of the MIT license . See the * included LICENSE file for details . * * Copyright (C) 2019 IRIF / OCaml Software Foundation. * * asak is distributed under the terms of the MIT license. See the * included LICENSE file for details. *) type 'a partition = { bad_type : 'a list ; clusters : ('a * string) list Wtree.wtree list } * Partitioning OCaml codes . Usage : [ create threshold name sol list ] . @param threshold Weight threshold required to keep a sub - AST . It is a percentage ( a number between 0 and 100 ) of the weight of the whole AST . - A value of 0 means " keep all sub - ASTs " - A value of 100 means " do n't keep any sub - AST " @param name The name of the searched function . @param sol A reference implementation , used only for typing . @param list List of valid OCaml codes , using only installed modules , that may contains the searched function . @return The partition . @param threshold Weight threshold required to keep a sub-AST. It is a percentage (a number between 0 and 100) of the weight of the whole AST. - A value of 0 means "keep all sub-ASTs" - A value of 100 means "don't keep any sub-AST" @param name The name of the searched function. @param sol A reference implementation, used only for typing. @param list List of valid OCaml codes, using only installed modules, that may contains the searched function. @return The partition. *) val create : int -> string -> string -> ('a * string) list -> 'a partition
6724e2c780de115576ff495f3dec7763d262e5e783a0d97599245c6d44cc4352
codinuum/cca
LCS.ml
Copyright 2012 - 2020 Codinuum Software Lab < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2012-2020 Codinuum Software Lab <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) (* An Algorithm for Longest Common Subsequence Problem *) let lcs a1 a2 = let max2 ( ( l0 , _ , _ , _ , _ ) as t0 ) ( ( l1 , _ , _ , _ , _ ) as t1 ) = if l0 > = l1 then t0 else t1 in let n1 = Array.length a1 in let n2 = Array.length a2 in let mat = Array.make_matrix ( n1 + 1 ) ( n2 + 1 ) ( -1 , -1 , -1 , -1 , -1 ) in for i = 0 to n1 do mat.(i).(0 ) < - ( 0 , -1 , -1 , -1 , -1 ) done ; for j = 0 to n2 do ) < - ( 0 , -1 , -1 , -1 , -1 ) done ; for i = 1 to n1 do for j = 1 to n2 do if a1.(i-1 ) = a2.(j-1 ) then begin let ( l , s1 , e1 , s2 , e2 ) = mat.(i-1).(j-1 ) in let st1 , st2 = if s1 < 0 & & s2 < 0 then i-1 , j-1 else s1 , s2 in let ed1 , ed2 = i-1 , j-1 in mat.(i).(j ) < - ( 1 + l , , ed1 , st2 , ed2 ) end else mat.(i).(j ) < - max2 mat.(i-1).(j ) mat.(i).(j-1 ) done done ; mat.(n1).(n2 ) let lcs a1 a2 = let max2 ((l0, _, _, _, _) as t0) ((l1, _, _, _, _) as t1) = if l0 >= l1 then t0 else t1 in let n1 = Array.length a1 in let n2 = Array.length a2 in let mat = Array.make_matrix (n1+1) (n2+1) (-1, -1, -1, -1, -1) in for i = 0 to n1 do mat.(i).(0) <- (0, -1, -1, -1, -1) done; for j = 0 to n2 do mat.(0).(j) <- (0, -1, -1, -1, -1) done; for i = 1 to n1 do for j = 1 to n2 do if a1.(i-1) = a2.(j-1) then begin let (l, s1, e1, s2, e2) = mat.(i-1).(j-1) in let st1, st2 = if s1 < 0 && s2 < 0 then i-1, j-1 else s1, s2 in let ed1, ed2 = i-1, j-1 in mat.(i).(j) <- (1 + l, st1, ed1, st2, ed2) end else mat.(i).(j) <- max2 mat.(i-1).(j) mat.(i).(j-1) done done; mat.(n1).(n2) *) ' a array - > ' a array - > ( int(nmatches ) * int(st_pos1 ) * int(ed_pos1 ) * int(st_pos2 ) * ) ) (int(nmatches) * int(st_pos1) * int(ed_pos1) * int(st_pos2) * int(ed_pos2)) *) let max2 ((l0, _, _, _, _) as t0) ((l1, _, _, _, _) as t1) = if l0 >= l1 then t0 else t1 in let n1 = Array.length a1 in let n2 = Array.length a2 in let mat_set, mat_get = if max n1 n2 > 65535 then let mkmat() = Bigarray.Array2.create Bigarray.int Bigarray.c_layout (n1+1) (n2+1) in let mat, mat_s1, mat_e1, mat_s2, mat_e2 = mkmat(), mkmat(), mkmat(), mkmat(), mkmat() in let set x y (n, s1, e1, s2, e2) = mat.{x, y} <- n; mat_s1.{x, y} <- s1; mat_e1.{x, y} <- e1; mat_s2.{x, y} <- s2; mat_e2.{x, y} <- e2 in let get x y = (mat.{x,y}, mat_s1.{x,y}, mat_e1.{x,y}, mat_s2.{x,y}, mat_e2.{x,y}) in set, get else let mkmat() = Bigarray.Array2.create Bigarray.int16_unsigned Bigarray.c_layout (n1+1) (n2+1) in let mat, mat_s1, mat_e1, mat_s2, mat_e2 = mkmat(), mkmat(), mkmat(), mkmat(), mkmat() in let set x y (n, s1, e1, s2, e2) = mat.{x, y} <- n + 1; mat_s1.{x, y} <- s1 + 1; mat_e1.{x, y} <- e1 + 1; mat_s2.{x, y} <- s2 + 1; mat_e2.{x, y} <- e2 + 1 in let get x y = (mat.{x,y}-1, mat_s1.{x,y}-1, mat_e1.{x,y}-1, mat_s2.{x,y}-1, mat_e2.{x,y}-1) in set, get in for i = 0 to n1 do mat_set i 0 (0, -1, -1, -1, -1) done; for j = 0 to n2 do mat_set 0 j (0, -1, -1, -1, -1) done; for i = 1 to n1 do for j = 1 to n2 do if eq a1.(i-1) a2.(j-1) then begin let (l, s1, e1, s2, e2) = mat_get (i-1) (j-1) in let st1, st2 = if s1 < 0 && s2 < 0 then i-1, j-1 else s1, s2 in let ed1, ed2 = i-1, j-1 in mat_set i j (1 + l, st1, ed1, st2, ed2) end else mat_set i j (max2 (mat_get (i-1) j) (mat_get i (j-1))) done done; mat_get n1 n2 let lcs_string s1 s2 = let n1 = String.length s1 in let n2 = String.length s2 in let a1 = Array.make n1 'a' in let a2 = Array.make n2 'a' in for i = 0 to n1 - 1 do a1.(i) <- s1.[i] done; for i = 0 to n2 - 1 do a2.(i) <- s2.[i] done; lcs a1 a2
null
https://raw.githubusercontent.com/codinuum/cca/88ea07f3fe3671b78518769d804fdebabcd28e90/src/util/LCS.ml
ocaml
An Algorithm for Longest Common Subsequence Problem
Copyright 2012 - 2020 Codinuum Software Lab < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing , software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied . See the License for the specific language governing permissions and limitations under the License . Copyright 2012-2020 Codinuum Software Lab <> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) let lcs a1 a2 = let max2 ( ( l0 , _ , _ , _ , _ ) as t0 ) ( ( l1 , _ , _ , _ , _ ) as t1 ) = if l0 > = l1 then t0 else t1 in let n1 = Array.length a1 in let n2 = Array.length a2 in let mat = Array.make_matrix ( n1 + 1 ) ( n2 + 1 ) ( -1 , -1 , -1 , -1 , -1 ) in for i = 0 to n1 do mat.(i).(0 ) < - ( 0 , -1 , -1 , -1 , -1 ) done ; for j = 0 to n2 do ) < - ( 0 , -1 , -1 , -1 , -1 ) done ; for i = 1 to n1 do for j = 1 to n2 do if a1.(i-1 ) = a2.(j-1 ) then begin let ( l , s1 , e1 , s2 , e2 ) = mat.(i-1).(j-1 ) in let st1 , st2 = if s1 < 0 & & s2 < 0 then i-1 , j-1 else s1 , s2 in let ed1 , ed2 = i-1 , j-1 in mat.(i).(j ) < - ( 1 + l , , ed1 , st2 , ed2 ) end else mat.(i).(j ) < - max2 mat.(i-1).(j ) mat.(i).(j-1 ) done done ; mat.(n1).(n2 ) let lcs a1 a2 = let max2 ((l0, _, _, _, _) as t0) ((l1, _, _, _, _) as t1) = if l0 >= l1 then t0 else t1 in let n1 = Array.length a1 in let n2 = Array.length a2 in let mat = Array.make_matrix (n1+1) (n2+1) (-1, -1, -1, -1, -1) in for i = 0 to n1 do mat.(i).(0) <- (0, -1, -1, -1, -1) done; for j = 0 to n2 do mat.(0).(j) <- (0, -1, -1, -1, -1) done; for i = 1 to n1 do for j = 1 to n2 do if a1.(i-1) = a2.(j-1) then begin let (l, s1, e1, s2, e2) = mat.(i-1).(j-1) in let st1, st2 = if s1 < 0 && s2 < 0 then i-1, j-1 else s1, s2 in let ed1, ed2 = i-1, j-1 in mat.(i).(j) <- (1 + l, st1, ed1, st2, ed2) end else mat.(i).(j) <- max2 mat.(i-1).(j) mat.(i).(j-1) done done; mat.(n1).(n2) *) ' a array - > ' a array - > ( int(nmatches ) * int(st_pos1 ) * int(ed_pos1 ) * int(st_pos2 ) * ) ) (int(nmatches) * int(st_pos1) * int(ed_pos1) * int(st_pos2) * int(ed_pos2)) *) let max2 ((l0, _, _, _, _) as t0) ((l1, _, _, _, _) as t1) = if l0 >= l1 then t0 else t1 in let n1 = Array.length a1 in let n2 = Array.length a2 in let mat_set, mat_get = if max n1 n2 > 65535 then let mkmat() = Bigarray.Array2.create Bigarray.int Bigarray.c_layout (n1+1) (n2+1) in let mat, mat_s1, mat_e1, mat_s2, mat_e2 = mkmat(), mkmat(), mkmat(), mkmat(), mkmat() in let set x y (n, s1, e1, s2, e2) = mat.{x, y} <- n; mat_s1.{x, y} <- s1; mat_e1.{x, y} <- e1; mat_s2.{x, y} <- s2; mat_e2.{x, y} <- e2 in let get x y = (mat.{x,y}, mat_s1.{x,y}, mat_e1.{x,y}, mat_s2.{x,y}, mat_e2.{x,y}) in set, get else let mkmat() = Bigarray.Array2.create Bigarray.int16_unsigned Bigarray.c_layout (n1+1) (n2+1) in let mat, mat_s1, mat_e1, mat_s2, mat_e2 = mkmat(), mkmat(), mkmat(), mkmat(), mkmat() in let set x y (n, s1, e1, s2, e2) = mat.{x, y} <- n + 1; mat_s1.{x, y} <- s1 + 1; mat_e1.{x, y} <- e1 + 1; mat_s2.{x, y} <- s2 + 1; mat_e2.{x, y} <- e2 + 1 in let get x y = (mat.{x,y}-1, mat_s1.{x,y}-1, mat_e1.{x,y}-1, mat_s2.{x,y}-1, mat_e2.{x,y}-1) in set, get in for i = 0 to n1 do mat_set i 0 (0, -1, -1, -1, -1) done; for j = 0 to n2 do mat_set 0 j (0, -1, -1, -1, -1) done; for i = 1 to n1 do for j = 1 to n2 do if eq a1.(i-1) a2.(j-1) then begin let (l, s1, e1, s2, e2) = mat_get (i-1) (j-1) in let st1, st2 = if s1 < 0 && s2 < 0 then i-1, j-1 else s1, s2 in let ed1, ed2 = i-1, j-1 in mat_set i j (1 + l, st1, ed1, st2, ed2) end else mat_set i j (max2 (mat_get (i-1) j) (mat_get i (j-1))) done done; mat_get n1 n2 let lcs_string s1 s2 = let n1 = String.length s1 in let n2 = String.length s2 in let a1 = Array.make n1 'a' in let a2 = Array.make n2 'a' in for i = 0 to n1 - 1 do a1.(i) <- s1.[i] done; for i = 0 to n2 - 1 do a2.(i) <- s2.[i] done; lcs a1 a2