_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 |
|---|---|---|---|---|---|---|---|---|
d4316c5be6c79a209c9ffe94f8b938cd28dbdbf83b14a40d37a30fd999b3a7dc | polyfy/polylith | ws_table.clj | (ns polylith.clj.core.workspace.text-table.ws-table
(:require [polylith.clj.core.text-table.interface :as text-table]
[polylith.clj.core.workspace.text-table.profile :as profile]
[polylith.clj.core.workspace.text-table.ws-table-column.ifc-column :as ifc-column]
[polylith.clj.core.workspace.text-table.ws-table-column.brick-column :as brick-column]
[polylith.clj.core.workspace.text-table.ws-table-column.loc-columns :as loc-columns]
[polylith.clj.core.workspace.text-table.ws-table-column.profile-columns :as profile-columns]
[polylith.clj.core.workspace.text-table.ws-table-column.project-columns :as proj-columns]))
(defn component-sorter [{:keys [interface name]}]
[(:name interface) name])
(defn table [{:keys [settings projects components bases paths changes]} is-show-loc is-show-resources]
(let [{:keys [color-mode thousand-separator]} settings
n#dev (count (filter :is-dev projects))
profiles (if (zero? n#dev) [] (profile/inactive-profiles settings))
sorted-components (sort-by component-sorter components)
bricks (concat sorted-components bases)
space-columns (range 2 (* 2 (+ 2 (count projects) (count profiles) (if is-show-loc 2 0))) 2)
spaces (concat (repeat (-> space-columns count dec) " ") (if is-show-loc [" "] [" "]))
profile-start-column (+ 5 (* 2 (count projects)))
loc-start-column (+ profile-start-column (* 2 (count profiles)))
ifc-column (ifc-column/column sorted-components bases)
brick-column (brick-column/column bricks changes color-mode)
project-columns (proj-columns/columns projects bricks paths changes is-show-loc is-show-resources thousand-separator)
profile-columns (profile-columns/columns profile-start-column bricks profiles paths settings is-show-resources)
loc-columns (loc-columns/columns is-show-loc bricks loc-start-column thousand-separator)
header-spaces (text-table/spaces 1 space-columns spaces)
cells (text-table/merge-cells ifc-column brick-column project-columns profile-columns loc-columns header-spaces)
line (text-table/line 2 cells)
section1 (if (or (zero? n#dev)
(= 1 (count projects)))
[] [(* 2 (+ (-> projects count) n#dev))])
section2 (if is-show-loc [(- (last space-columns) 2)] [])
line-space (text-table/spaces 2 (concat [4] section1 section2) (repeat " "))]
(text-table/table " " color-mode cells line line-space)))
(defn print-table [workspace is-show-loc is-show-resources]
(text-table/print-table (table workspace is-show-loc is-show-resources)))
(comment
(require '[dev.development :as dev])
(require '[dev.jocke :as dev])
(print-table dev/workspace false false)
#__)
| null | https://raw.githubusercontent.com/polyfy/polylith/febea3d8a9b30a60397594dda3cb0f25154b8d8d/components/workspace/src/polylith/clj/core/workspace/text_table/ws_table.clj | clojure | (ns polylith.clj.core.workspace.text-table.ws-table
(:require [polylith.clj.core.text-table.interface :as text-table]
[polylith.clj.core.workspace.text-table.profile :as profile]
[polylith.clj.core.workspace.text-table.ws-table-column.ifc-column :as ifc-column]
[polylith.clj.core.workspace.text-table.ws-table-column.brick-column :as brick-column]
[polylith.clj.core.workspace.text-table.ws-table-column.loc-columns :as loc-columns]
[polylith.clj.core.workspace.text-table.ws-table-column.profile-columns :as profile-columns]
[polylith.clj.core.workspace.text-table.ws-table-column.project-columns :as proj-columns]))
(defn component-sorter [{:keys [interface name]}]
[(:name interface) name])
(defn table [{:keys [settings projects components bases paths changes]} is-show-loc is-show-resources]
(let [{:keys [color-mode thousand-separator]} settings
n#dev (count (filter :is-dev projects))
profiles (if (zero? n#dev) [] (profile/inactive-profiles settings))
sorted-components (sort-by component-sorter components)
bricks (concat sorted-components bases)
space-columns (range 2 (* 2 (+ 2 (count projects) (count profiles) (if is-show-loc 2 0))) 2)
spaces (concat (repeat (-> space-columns count dec) " ") (if is-show-loc [" "] [" "]))
profile-start-column (+ 5 (* 2 (count projects)))
loc-start-column (+ profile-start-column (* 2 (count profiles)))
ifc-column (ifc-column/column sorted-components bases)
brick-column (brick-column/column bricks changes color-mode)
project-columns (proj-columns/columns projects bricks paths changes is-show-loc is-show-resources thousand-separator)
profile-columns (profile-columns/columns profile-start-column bricks profiles paths settings is-show-resources)
loc-columns (loc-columns/columns is-show-loc bricks loc-start-column thousand-separator)
header-spaces (text-table/spaces 1 space-columns spaces)
cells (text-table/merge-cells ifc-column brick-column project-columns profile-columns loc-columns header-spaces)
line (text-table/line 2 cells)
section1 (if (or (zero? n#dev)
(= 1 (count projects)))
[] [(* 2 (+ (-> projects count) n#dev))])
section2 (if is-show-loc [(- (last space-columns) 2)] [])
line-space (text-table/spaces 2 (concat [4] section1 section2) (repeat " "))]
(text-table/table " " color-mode cells line line-space)))
(defn print-table [workspace is-show-loc is-show-resources]
(text-table/print-table (table workspace is-show-loc is-show-resources)))
(comment
(require '[dev.development :as dev])
(require '[dev.jocke :as dev])
(print-table dev/workspace false false)
#__)
| |
ad46ffadb214b1e3c2ea6422ecf30d39f5820e34a69720a2cd1e99cc0022f57f | wireapp/wire-server | Options.hs | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
| Reading the Spar config .
module Spar.Options
( Opts' (..),
Opts,
DerivedOpts (..),
getOpts,
deriveOpts,
readOptsFile,
maxttlAuthreqDiffTime,
)
where
import Control.Exception
import Control.Lens
import Control.Monad.Except
import Data.Aeson hiding (fieldLabelModifier)
import qualified Data.ByteString as SBS
import Data.String.Conversions
import Data.Time
import qualified Data.Yaml as Yaml
import Imports
import Options.Applicative
import SAML2.WebSSO
import qualified SAML2.WebSSO as SAML
import System.Logger.Extended (LogFormat)
import Text.Ascii (ascii)
import URI.ByteString
import Util.Options
import Wire.API.Routes.Version
import Wire.API.User.Orphans ()
import Wire.API.User.Saml
type Opts = Opts' DerivedOpts
data Opts' a = Opts
{ saml :: !SAML.Config,
brig :: !Endpoint,
galley :: !Endpoint,
cassandra :: !CassandraOpts,
maxttlAuthreq :: !(TTL "authreq"),
maxttlAuthresp :: !(TTL "authresp"),
-- | The maximum number of SCIM tokens that we will allow teams to have.
maxScimTokens :: !Int,
-- | The maximum size of rich info. Should be in sync with 'Brig.Types.richInfoLimit'.
richInfoLimit :: !Int,
| Wire / AWS specific ; optional ; used to discover instance
-- IPs using describe-instances.
discoUrl :: !(Maybe Text),
logNetStrings :: !(Maybe (Last Bool)),
logFormat :: !(Maybe (Last LogFormat)),
disabledAPIVersions :: !(Maybe (Set Version)),
derivedOpts :: !a
}
deriving (Functor, Show, Generic)
instance FromJSON (Opts' (Maybe ()))
data DerivedOpts = DerivedOpts
{ derivedOptsScimBaseURI :: !URI
}
deriving (Show, Generic)
maxttlAuthreqDiffTime :: Opts -> NominalDiffTime
maxttlAuthreqDiffTime = ttlToNominalDiffTime . maxttlAuthreq
type OptsRaw = Opts' (Maybe ())
-- | Throws an exception if no config file is found.
getOpts :: IO Opts
getOpts = do
let desc = "Spar - SSO Service"
deriveOpts
=<< readOptsFile
=<< execParser (info (helper <*> cliOptsParser) (header desc <> fullDesc))
deriveOpts :: OptsRaw -> IO Opts
deriveOpts raw = do
derived <- do
-- We could also make this selectable in the config file, but it seems easier to derive it from
the SAML base uri .
let derivedOptsScimBaseURI = (saml raw ^. SAML.cfgSPSsoURI) & pathL %~ derive
where
derive path = case reverse
. filter (not . SBS.null)
. SBS.split (ascii '/')
$ path of
("sso" : path') -> compile path'
path' -> compile path'
compile path = "/" <> SBS.intercalate "/" (reverse ("v2" : "scim" : path))
pure DerivedOpts {..}
pure $ derived <$ raw
| This should not leave this module . It is only for callling ' sparResponseURI ' before the ' Spar '
-- monad is fully initialized.
newtype WithConfig a = WithConfig (Reader OptsRaw a)
deriving (Functor, Applicative, Monad)
instance SAML.HasConfig WithConfig where
getConfig = WithConfig $ asks saml
-- | Accept config file location as cli option.
--
FUTUREWORK : it would be nicer for the Parser to return the contents of the file , and return an
-- error that explains the cli options if it doesn't succeed.
cliOptsParser :: Parser FilePath
cliOptsParser =
strOption $
long "config-file"
<> short 'c'
<> help "Spar application config to load"
<> showDefault
<> value defaultSparPath
where
defaultSparPath = "/etc/wire/spar/conf/spar.yaml"
readOptsFile :: FilePath -> IO OptsRaw
readOptsFile path =
either err1 pure =<< Yaml.decodeFileEither path
where
err1 = throwIO . ErrorCall . ("no or bad config file: " <>) . show
| null | https://raw.githubusercontent.com/wireapp/wire-server/b83b5840f65c28475559646e1331b8e4e1e4591a/services/spar/src/Spar/Options.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>.
| The maximum number of SCIM tokens that we will allow teams to have.
| The maximum size of rich info. Should be in sync with 'Brig.Types.richInfoLimit'.
IPs using describe-instances.
| Throws an exception if no config file is found.
We could also make this selectable in the config file, but it seems easier to derive it from
monad is fully initialized.
| Accept config file location as cli option.
error that explains the cli options if it doesn't succeed. | # LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE RecordWildCards #
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
| Reading the Spar config .
module Spar.Options
( Opts' (..),
Opts,
DerivedOpts (..),
getOpts,
deriveOpts,
readOptsFile,
maxttlAuthreqDiffTime,
)
where
import Control.Exception
import Control.Lens
import Control.Monad.Except
import Data.Aeson hiding (fieldLabelModifier)
import qualified Data.ByteString as SBS
import Data.String.Conversions
import Data.Time
import qualified Data.Yaml as Yaml
import Imports
import Options.Applicative
import SAML2.WebSSO
import qualified SAML2.WebSSO as SAML
import System.Logger.Extended (LogFormat)
import Text.Ascii (ascii)
import URI.ByteString
import Util.Options
import Wire.API.Routes.Version
import Wire.API.User.Orphans ()
import Wire.API.User.Saml
type Opts = Opts' DerivedOpts
data Opts' a = Opts
{ saml :: !SAML.Config,
brig :: !Endpoint,
galley :: !Endpoint,
cassandra :: !CassandraOpts,
maxttlAuthreq :: !(TTL "authreq"),
maxttlAuthresp :: !(TTL "authresp"),
maxScimTokens :: !Int,
richInfoLimit :: !Int,
| Wire / AWS specific ; optional ; used to discover instance
discoUrl :: !(Maybe Text),
logNetStrings :: !(Maybe (Last Bool)),
logFormat :: !(Maybe (Last LogFormat)),
disabledAPIVersions :: !(Maybe (Set Version)),
derivedOpts :: !a
}
deriving (Functor, Show, Generic)
instance FromJSON (Opts' (Maybe ()))
data DerivedOpts = DerivedOpts
{ derivedOptsScimBaseURI :: !URI
}
deriving (Show, Generic)
maxttlAuthreqDiffTime :: Opts -> NominalDiffTime
maxttlAuthreqDiffTime = ttlToNominalDiffTime . maxttlAuthreq
type OptsRaw = Opts' (Maybe ())
getOpts :: IO Opts
getOpts = do
let desc = "Spar - SSO Service"
deriveOpts
=<< readOptsFile
=<< execParser (info (helper <*> cliOptsParser) (header desc <> fullDesc))
deriveOpts :: OptsRaw -> IO Opts
deriveOpts raw = do
derived <- do
the SAML base uri .
let derivedOptsScimBaseURI = (saml raw ^. SAML.cfgSPSsoURI) & pathL %~ derive
where
derive path = case reverse
. filter (not . SBS.null)
. SBS.split (ascii '/')
$ path of
("sso" : path') -> compile path'
path' -> compile path'
compile path = "/" <> SBS.intercalate "/" (reverse ("v2" : "scim" : path))
pure DerivedOpts {..}
pure $ derived <$ raw
| This should not leave this module . It is only for callling ' sparResponseURI ' before the ' Spar '
newtype WithConfig a = WithConfig (Reader OptsRaw a)
deriving (Functor, Applicative, Monad)
instance SAML.HasConfig WithConfig where
getConfig = WithConfig $ asks saml
FUTUREWORK : it would be nicer for the Parser to return the contents of the file , and return an
cliOptsParser :: Parser FilePath
cliOptsParser =
strOption $
long "config-file"
<> short 'c'
<> help "Spar application config to load"
<> showDefault
<> value defaultSparPath
where
defaultSparPath = "/etc/wire/spar/conf/spar.yaml"
readOptsFile :: FilePath -> IO OptsRaw
readOptsFile path =
either err1 pure =<< Yaml.decodeFileEither path
where
err1 = throwIO . ErrorCall . ("no or bad config file: " <>) . show
|
2b1d730e56ee123e0582ef612a48a9e4f4fded60a04e99d6fa003bdf615d8c23 | emqx/emqx | emqx_bridge_schema.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. 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(emqx_bridge_schema).
-include_lib("typerefl/include/types.hrl").
-include_lib("hocon/include/hoconsc.hrl").
-import(hoconsc, [mk/2, ref/2]).
-export([roots/0, fields/1, desc/1, namespace/0, tags/0]).
-export([
get_response/0,
put_request/0,
post_request/0
]).
-export([
common_bridge_fields/0,
status_fields/0,
metrics_fields/0
]).
%%======================================================================================
%% Hocon Schema Definitions
%%======================================================================================
%% For HTTP APIs
get_response() ->
api_schema("get").
put_request() ->
api_schema("put").
post_request() ->
api_schema("post").
api_schema(Method) ->
Broker = [
ref(Mod, Method)
|| Mod <- [emqx_bridge_webhook_schema, emqx_bridge_mqtt_schema]
],
EE = ee_api_schemas(Method),
hoconsc:union(Broker ++ EE).
-if(?EMQX_RELEASE_EDITION == ee).
ee_api_schemas(Method) ->
ensure_loaded(emqx_ee_bridge, emqx_ee_bridge),
case erlang:function_exported(emqx_ee_bridge, api_schemas, 1) of
true -> emqx_ee_bridge:api_schemas(Method);
false -> []
end.
ee_fields_bridges() ->
ensure_loaded(emqx_ee_bridge, emqx_ee_bridge),
case erlang:function_exported(emqx_ee_bridge, fields, 1) of
true -> emqx_ee_bridge:fields(bridges);
false -> []
end.
%% must ensure the app is loaded before checking if fn is defined.
ensure_loaded(App, Mod) ->
try
_ = application:load(App),
_ = Mod:module_info(),
ok
catch
_:_ ->
ok
end.
-else.
ee_api_schemas(_) -> [].
ee_fields_bridges() -> [].
-endif.
common_bridge_fields() ->
[
{enable,
mk(
boolean(),
#{
desc => ?DESC("desc_enable"),
default => true
}
)}
].
status_fields() ->
[
{"status", mk(status(), #{desc => ?DESC("desc_status")})},
{"node_status",
mk(
hoconsc:array(ref(?MODULE, "node_status")),
#{desc => ?DESC("desc_node_status")}
)}
].
metrics_fields() ->
[
{"metrics", mk(ref(?MODULE, "metrics"), #{desc => ?DESC("desc_metrics")})},
{"node_metrics",
mk(
hoconsc:array(ref(?MODULE, "node_metrics")),
#{desc => ?DESC("desc_node_metrics")}
)}
].
%%======================================================================================
%% For config files
namespace() -> "bridge".
tags() ->
[<<"Bridge">>].
roots() -> [bridges].
fields(bridges) ->
[
{webhook,
mk(
hoconsc:map(name, ref(emqx_bridge_webhook_schema, "config")),
#{
desc => ?DESC("bridges_webhook"),
required => false,
converter => fun(X, _HoconOpts) ->
emqx_bridge_compatible_config:upgrade_pre_ee(
X, fun emqx_bridge_compatible_config:webhook_maybe_upgrade/1
)
end
}
)},
{mqtt,
mk(
hoconsc:map(name, ref(emqx_bridge_mqtt_schema, "config")),
#{
desc => ?DESC("bridges_mqtt"),
required => false,
converter => fun(X, _HoconOpts) ->
emqx_bridge_compatible_config:upgrade_pre_ee(
X, fun emqx_bridge_compatible_config:maybe_upgrade/1
)
end
}
)}
] ++ ee_fields_bridges();
fields("metrics") ->
[
{"dropped", mk(integer(), #{desc => ?DESC("metric_dropped")})},
{"dropped.other", mk(integer(), #{desc => ?DESC("metric_dropped_other")})},
{"dropped.queue_full", mk(integer(), #{desc => ?DESC("metric_dropped_queue_full")})},
{"dropped.resource_not_found",
mk(integer(), #{desc => ?DESC("metric_dropped_resource_not_found")})},
{"dropped.resource_stopped",
mk(integer(), #{desc => ?DESC("metric_dropped_resource_stopped")})},
{"matched", mk(integer(), #{desc => ?DESC("metric_matched")})},
{"queuing", mk(integer(), #{desc => ?DESC("metric_queuing")})},
{"retried", mk(integer(), #{desc => ?DESC("metric_retried")})},
{"failed", mk(integer(), #{desc => ?DESC("metric_sent_failed")})},
{"inflight", mk(integer(), #{desc => ?DESC("metric_inflight")})},
{"success", mk(integer(), #{desc => ?DESC("metric_sent_success")})},
{"rate", mk(float(), #{desc => ?DESC("metric_rate")})},
{"rate_max", mk(float(), #{desc => ?DESC("metric_rate_max")})},
{"rate_last5m",
mk(
float(),
#{desc => ?DESC("metric_rate_last5m")}
)},
{"received", mk(float(), #{desc => ?DESC("metric_received")})}
];
fields("node_metrics") ->
[
node_name(),
{"metrics", mk(ref(?MODULE, "metrics"), #{})}
];
fields("node_status") ->
[
node_name(),
{"status", mk(status(), #{})}
].
desc(bridges) ->
?DESC("desc_bridges");
desc("metrics") ->
?DESC("desc_metrics");
desc("node_metrics") ->
?DESC("desc_node_metrics");
desc("node_status") ->
?DESC("desc_node_status");
desc(_) ->
undefined.
status() ->
hoconsc:enum([connected, disconnected, connecting, inconsistent]).
node_name() ->
{"node", mk(binary(), #{desc => ?DESC("desc_node_name"), example => "emqx@127.0.0.1"})}.
| null | https://raw.githubusercontent.com/emqx/emqx/d0f43bead3ed7fd26c125080bee2f51aecea1e25/apps/emqx_bridge/src/schema/emqx_bridge_schema.erl | erlang | --------------------------------------------------------------------
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.
--------------------------------------------------------------------
======================================================================================
Hocon Schema Definitions
======================================================================================
For HTTP APIs
must ensure the app is loaded before checking if fn is defined.
======================================================================================
For config files | Copyright ( c ) 2022 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_bridge_schema).
-include_lib("typerefl/include/types.hrl").
-include_lib("hocon/include/hoconsc.hrl").
-import(hoconsc, [mk/2, ref/2]).
-export([roots/0, fields/1, desc/1, namespace/0, tags/0]).
-export([
get_response/0,
put_request/0,
post_request/0
]).
-export([
common_bridge_fields/0,
status_fields/0,
metrics_fields/0
]).
get_response() ->
api_schema("get").
put_request() ->
api_schema("put").
post_request() ->
api_schema("post").
api_schema(Method) ->
Broker = [
ref(Mod, Method)
|| Mod <- [emqx_bridge_webhook_schema, emqx_bridge_mqtt_schema]
],
EE = ee_api_schemas(Method),
hoconsc:union(Broker ++ EE).
-if(?EMQX_RELEASE_EDITION == ee).
ee_api_schemas(Method) ->
ensure_loaded(emqx_ee_bridge, emqx_ee_bridge),
case erlang:function_exported(emqx_ee_bridge, api_schemas, 1) of
true -> emqx_ee_bridge:api_schemas(Method);
false -> []
end.
ee_fields_bridges() ->
ensure_loaded(emqx_ee_bridge, emqx_ee_bridge),
case erlang:function_exported(emqx_ee_bridge, fields, 1) of
true -> emqx_ee_bridge:fields(bridges);
false -> []
end.
ensure_loaded(App, Mod) ->
try
_ = application:load(App),
_ = Mod:module_info(),
ok
catch
_:_ ->
ok
end.
-else.
ee_api_schemas(_) -> [].
ee_fields_bridges() -> [].
-endif.
common_bridge_fields() ->
[
{enable,
mk(
boolean(),
#{
desc => ?DESC("desc_enable"),
default => true
}
)}
].
status_fields() ->
[
{"status", mk(status(), #{desc => ?DESC("desc_status")})},
{"node_status",
mk(
hoconsc:array(ref(?MODULE, "node_status")),
#{desc => ?DESC("desc_node_status")}
)}
].
metrics_fields() ->
[
{"metrics", mk(ref(?MODULE, "metrics"), #{desc => ?DESC("desc_metrics")})},
{"node_metrics",
mk(
hoconsc:array(ref(?MODULE, "node_metrics")),
#{desc => ?DESC("desc_node_metrics")}
)}
].
namespace() -> "bridge".
tags() ->
[<<"Bridge">>].
roots() -> [bridges].
fields(bridges) ->
[
{webhook,
mk(
hoconsc:map(name, ref(emqx_bridge_webhook_schema, "config")),
#{
desc => ?DESC("bridges_webhook"),
required => false,
converter => fun(X, _HoconOpts) ->
emqx_bridge_compatible_config:upgrade_pre_ee(
X, fun emqx_bridge_compatible_config:webhook_maybe_upgrade/1
)
end
}
)},
{mqtt,
mk(
hoconsc:map(name, ref(emqx_bridge_mqtt_schema, "config")),
#{
desc => ?DESC("bridges_mqtt"),
required => false,
converter => fun(X, _HoconOpts) ->
emqx_bridge_compatible_config:upgrade_pre_ee(
X, fun emqx_bridge_compatible_config:maybe_upgrade/1
)
end
}
)}
] ++ ee_fields_bridges();
fields("metrics") ->
[
{"dropped", mk(integer(), #{desc => ?DESC("metric_dropped")})},
{"dropped.other", mk(integer(), #{desc => ?DESC("metric_dropped_other")})},
{"dropped.queue_full", mk(integer(), #{desc => ?DESC("metric_dropped_queue_full")})},
{"dropped.resource_not_found",
mk(integer(), #{desc => ?DESC("metric_dropped_resource_not_found")})},
{"dropped.resource_stopped",
mk(integer(), #{desc => ?DESC("metric_dropped_resource_stopped")})},
{"matched", mk(integer(), #{desc => ?DESC("metric_matched")})},
{"queuing", mk(integer(), #{desc => ?DESC("metric_queuing")})},
{"retried", mk(integer(), #{desc => ?DESC("metric_retried")})},
{"failed", mk(integer(), #{desc => ?DESC("metric_sent_failed")})},
{"inflight", mk(integer(), #{desc => ?DESC("metric_inflight")})},
{"success", mk(integer(), #{desc => ?DESC("metric_sent_success")})},
{"rate", mk(float(), #{desc => ?DESC("metric_rate")})},
{"rate_max", mk(float(), #{desc => ?DESC("metric_rate_max")})},
{"rate_last5m",
mk(
float(),
#{desc => ?DESC("metric_rate_last5m")}
)},
{"received", mk(float(), #{desc => ?DESC("metric_received")})}
];
fields("node_metrics") ->
[
node_name(),
{"metrics", mk(ref(?MODULE, "metrics"), #{})}
];
fields("node_status") ->
[
node_name(),
{"status", mk(status(), #{})}
].
desc(bridges) ->
?DESC("desc_bridges");
desc("metrics") ->
?DESC("desc_metrics");
desc("node_metrics") ->
?DESC("desc_node_metrics");
desc("node_status") ->
?DESC("desc_node_status");
desc(_) ->
undefined.
status() ->
hoconsc:enum([connected, disconnected, connecting, inconsistent]).
node_name() ->
{"node", mk(binary(), #{desc => ?DESC("desc_node_name"), example => "emqx@127.0.0.1"})}.
|
581e6329272a217690ead0cad68258cd0225e556937eb7a68b65705989872e3f | danieljharvey/mimsa | Parser.hs | module Language.Mimsa.Core.Parser
( module Language.Mimsa.Core.Parser.Language,
module Language.Mimsa.Core.Parser.MonoType,
module Language.Mimsa.Core.Parser.TypeDecl,
module Language.Mimsa.Core.Parser.Module,
module Language.Mimsa.Core.Parser.Lexeme,
module Language.Mimsa.Core.Parser.Pattern,
module Language.Mimsa.Core.Parser.Identifiers,
)
where
import Language.Mimsa.Core.Parser.Identifiers
import Language.Mimsa.Core.Parser.Language
import Language.Mimsa.Core.Parser.Lexeme
import Language.Mimsa.Core.Parser.Module
import Language.Mimsa.Core.Parser.MonoType
import Language.Mimsa.Core.Parser.Pattern
import Language.Mimsa.Core.Parser.TypeDecl
| null | https://raw.githubusercontent.com/danieljharvey/mimsa/e6b177dd2c38e8a67d6e27063ca600406b3e6b56/core/src/Language/Mimsa/Core/Parser.hs | haskell | module Language.Mimsa.Core.Parser
( module Language.Mimsa.Core.Parser.Language,
module Language.Mimsa.Core.Parser.MonoType,
module Language.Mimsa.Core.Parser.TypeDecl,
module Language.Mimsa.Core.Parser.Module,
module Language.Mimsa.Core.Parser.Lexeme,
module Language.Mimsa.Core.Parser.Pattern,
module Language.Mimsa.Core.Parser.Identifiers,
)
where
import Language.Mimsa.Core.Parser.Identifiers
import Language.Mimsa.Core.Parser.Language
import Language.Mimsa.Core.Parser.Lexeme
import Language.Mimsa.Core.Parser.Module
import Language.Mimsa.Core.Parser.MonoType
import Language.Mimsa.Core.Parser.Pattern
import Language.Mimsa.Core.Parser.TypeDecl
| |
0ba833147759355e57397871f8e4c62aff396f5dda15ad16e378871b37096748 | johnwhitington/ocamli | mapp.ml | module IntPairs =
struct
type t = int * int
let compare (x0, y0) (x1, y1) =
match Pervasives.compare x0 x1 with
0 -> Pervasives.compare x0 x1
| x -> x
end
module PairsMap = Map.Make(IntPairs)
let m = PairsMap.empty
| null | https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/examples/mapp.ml | ocaml | module IntPairs =
struct
type t = int * int
let compare (x0, y0) (x1, y1) =
match Pervasives.compare x0 x1 with
0 -> Pervasives.compare x0 x1
| x -> x
end
module PairsMap = Map.Make(IntPairs)
let m = PairsMap.empty
| |
27b323123e3d7f6c66b2201062e2426c7da7e5a1cf7471c175ae1391d78b1375 | essandess/adblock2privoxy | Main.hs | module Main where
import InputParser
import ElementBlocker
import UrlBlocker
import Text.ParserCombinators.Parsec hiding (Line, many, optional)
import Task
import SourceInfo as Source
import ProgramOptions as Options
import System.Environment
import Templates
import Data.Time.Clock
import Network.HTTP.Conduit
import Network.URI
import System.Directory
import System.IO
import Network
import GHC.IO.Encoding
getFileContent :: String -> IO String
getFileContent url = do
handle <- openFile url ReadMode
hSetEncoding handle utf8
hGetContents handle
processSources :: Options -> String -> [SourceInfo]-> IO ()
processSources options taskFile sources = do
manager <- newManager tlsManagerSettings
(parsed, sourceInfo) <- unzip <$> mapM (parseSource manager) sources
let parsed' = concat parsed
sourceInfoText = showInfo sourceInfo
optionsText = logOptions options
createDirectoryIfMissing True $ _privoxyDir options
writeTask taskFile (sourceInfoText ++ optionsText) parsed'
if null._cssDomain $ options
then putStrLn "WARNING: CSS generation is not run because webserver domain is not specified"
else elemBlock (_webDir options) sourceInfoText parsed'
urlBlock (_privoxyDir options) sourceInfoText parsed'
writeTemplateFiles (_privoxyDir options) (_cssDomain options) (_useHTTP options)
putStrLn $ "Run 'adblock2privoxy -t " ++ taskFile ++ "' every 1-2 days to process data updates."
where
parseSource manager sourceInfo = do
let
url = _url sourceInfo
loader = if isURI url then downloadHttp manager 5 else getFileContent
putStrLn $ "process " ++ url
text <- loader url
now <- getCurrentTime
let strictParse = text `seq` parse adblockFile url text
case strictParse of
Right parsed ->
let sourceInfo' = updateInfo now parsed sourceInfo
url' = _url sourceInfo'
in if url == url'
then return (parsed, sourceInfo')
else parseSource manager sourceInfo'
Left msg -> return ([], sourceInfo) <$ putStrLn $ show msg
main::IO()
main = do
setLocaleEncoding utf8
setFileSystemEncoding utf8
setForeignEncoding utf8
now <- getCurrentTime
args <- getArgs
(options@(Options printVersion _ _ taskFile _ _ forced), urls) <- parseOptions args
(options', task) <- do
fileExists <- doesFileExist taskFile
if fileExists
then do task <- readTask taskFile
return (fillFromLog options task, Just task)
else return (options, Nothing)
let
action
| printVersion = putStrLn versionText
| not . null $ urls
= processSources options' taskFile (makeInfo <$> urls)
| otherwise = case task of
Nothing -> writeError "no input specified"
(Just task') -> do
let sources = Source.readLogInfos task'
if forced || or (infoExpired now <$> sources)
then processSources options' taskFile sources
else putStrLn "all sources are up to date"
action
now' <- getCurrentTime
putStrLn $ concat ["Execution done in ", show $ diffUTCTime now' now, " seconds."]
| null | https://raw.githubusercontent.com/essandess/adblock2privoxy/10bab4648887b31926516d61127411bab6af810b/adblock2privoxy/src/Main.hs | haskell | module Main where
import InputParser
import ElementBlocker
import UrlBlocker
import Text.ParserCombinators.Parsec hiding (Line, many, optional)
import Task
import SourceInfo as Source
import ProgramOptions as Options
import System.Environment
import Templates
import Data.Time.Clock
import Network.HTTP.Conduit
import Network.URI
import System.Directory
import System.IO
import Network
import GHC.IO.Encoding
getFileContent :: String -> IO String
getFileContent url = do
handle <- openFile url ReadMode
hSetEncoding handle utf8
hGetContents handle
processSources :: Options -> String -> [SourceInfo]-> IO ()
processSources options taskFile sources = do
manager <- newManager tlsManagerSettings
(parsed, sourceInfo) <- unzip <$> mapM (parseSource manager) sources
let parsed' = concat parsed
sourceInfoText = showInfo sourceInfo
optionsText = logOptions options
createDirectoryIfMissing True $ _privoxyDir options
writeTask taskFile (sourceInfoText ++ optionsText) parsed'
if null._cssDomain $ options
then putStrLn "WARNING: CSS generation is not run because webserver domain is not specified"
else elemBlock (_webDir options) sourceInfoText parsed'
urlBlock (_privoxyDir options) sourceInfoText parsed'
writeTemplateFiles (_privoxyDir options) (_cssDomain options) (_useHTTP options)
putStrLn $ "Run 'adblock2privoxy -t " ++ taskFile ++ "' every 1-2 days to process data updates."
where
parseSource manager sourceInfo = do
let
url = _url sourceInfo
loader = if isURI url then downloadHttp manager 5 else getFileContent
putStrLn $ "process " ++ url
text <- loader url
now <- getCurrentTime
let strictParse = text `seq` parse adblockFile url text
case strictParse of
Right parsed ->
let sourceInfo' = updateInfo now parsed sourceInfo
url' = _url sourceInfo'
in if url == url'
then return (parsed, sourceInfo')
else parseSource manager sourceInfo'
Left msg -> return ([], sourceInfo) <$ putStrLn $ show msg
main::IO()
main = do
setLocaleEncoding utf8
setFileSystemEncoding utf8
setForeignEncoding utf8
now <- getCurrentTime
args <- getArgs
(options@(Options printVersion _ _ taskFile _ _ forced), urls) <- parseOptions args
(options', task) <- do
fileExists <- doesFileExist taskFile
if fileExists
then do task <- readTask taskFile
return (fillFromLog options task, Just task)
else return (options, Nothing)
let
action
| printVersion = putStrLn versionText
| not . null $ urls
= processSources options' taskFile (makeInfo <$> urls)
| otherwise = case task of
Nothing -> writeError "no input specified"
(Just task') -> do
let sources = Source.readLogInfos task'
if forced || or (infoExpired now <$> sources)
then processSources options' taskFile sources
else putStrLn "all sources are up to date"
action
now' <- getCurrentTime
putStrLn $ concat ["Execution done in ", show $ diffUTCTime now' now, " seconds."]
| |
acc7a6b8d8e39ce65d3b7b04774ba2af24dff2bb6d9a5211bff6d17b20c1a962 | glguy/advent | 04.hs | {-# Language QuasiQuotes #-}
|
Module : Main
Description : Day 4 solution
Copyright : ( c ) , 2021
License : ISC
Maintainer :
< >
Today we played Bingo and picked the first and last winning cards
Module : Main
Description : Day 4 solution
Copyright : (c) Eric Mertens, 2021
License : ISC
Maintainer :
<>
Today we played Bingo and picked the first and last winning cards
-}
module Main (main) where
import Advent (format)
import Data.List (partition, transpose)
type Board = [[Int]]
-- | >>> :main
49686
26878
main :: IO ()
main =
do (calls, boards) <- [format|2021 4 %u&,%n(%n(( *%u)+%n)+)*|]
let outcomes = play calls boards
print (head outcomes)
print (last outcomes)
-- | Given the called numbers and initial boards return a list of
-- winning scores in order of winning.
play :: [Int] -> [Board] -> [Int]
play [] _ = []
play (c:calls) boards =
case partition isWinner (map (mark c) boards) of
(winners, losers) -> map (score c) winners ++ play calls losers
| off a called number on a board .
mark :: Int -> Board -> Board
mark c = map (map (\x -> if x == c then -1 else x))
-- | Compute the final score for a board given the last call and unmarked numbers.
score :: Int -> Board -> Int
score c b = c * sum (filter (-1 /=) (concat b))
-- | Predicate for boards with a completed row or column
isWinner :: Board -> Bool
isWinner b = f b || f (transpose b)
where f = any (all (-1 ==))
| null | https://raw.githubusercontent.com/glguy/advent/7ab9f9e47208fd5720e36bac33fee2b78d4ec50b/solutions/src/2021/04.hs | haskell | # Language QuasiQuotes #
| >>> :main
| Given the called numbers and initial boards return a list of
winning scores in order of winning.
| Compute the final score for a board given the last call and unmarked numbers.
| Predicate for boards with a completed row or column | |
Module : Main
Description : Day 4 solution
Copyright : ( c ) , 2021
License : ISC
Maintainer :
< >
Today we played Bingo and picked the first and last winning cards
Module : Main
Description : Day 4 solution
Copyright : (c) Eric Mertens, 2021
License : ISC
Maintainer :
<>
Today we played Bingo and picked the first and last winning cards
-}
module Main (main) where
import Advent (format)
import Data.List (partition, transpose)
type Board = [[Int]]
49686
26878
main :: IO ()
main =
do (calls, boards) <- [format|2021 4 %u&,%n(%n(( *%u)+%n)+)*|]
let outcomes = play calls boards
print (head outcomes)
print (last outcomes)
play :: [Int] -> [Board] -> [Int]
play [] _ = []
play (c:calls) boards =
case partition isWinner (map (mark c) boards) of
(winners, losers) -> map (score c) winners ++ play calls losers
| off a called number on a board .
mark :: Int -> Board -> Board
mark c = map (map (\x -> if x == c then -1 else x))
score :: Int -> Board -> Int
score c b = c * sum (filter (-1 /=) (concat b))
isWinner :: Board -> Bool
isWinner b = f b || f (transpose b)
where f = any (all (-1 ==))
|
5e9b27f508a08a5d1c1add6e6ae35d03249bc57e69f8f5d79d6d68d962989537 | Elzair/nazghul | prison.scm |
;;----------------------------------------------------------------------------
;; Map
;;----------------------------------------------------------------------------
(kern-mk-map
'm_prison 32 9 pal_expanded
(list
"xx xx xx xx xx xx xx xx xx xx xx xx xx rn xx xx xx xx xx xx xx xx xx xx xx xx xx rn rn rn rn rn "
"xx ,, ,, ,, xx xx xx xx xx ,, xx ,, xx rn xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx rn rn rn rn rn "
"xx ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, xx xx xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx xx xx xx xx xx "
"xx ,, ,, ,, xx xx xx ,, ,, ,, ,, ,, xx ee xx xx ,, xx xx xx ,, xx xx xx ,, xx xx xx ,, ,, ,, xx "
"xx ,, ,, ,, xx xx ,, ,, ,, x! ,, ,, ,, ee ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, xx "
"xx ,, ,, ,, xx xx xx ,, ,, ,, ,, ,, xx ee xx xx ,, xx xx xx ,, xx xx xx ,, xx xx xx ,, ,, ,, xx "
"xx ,, ,, ,, xx rn xx ,, ,, ,, ,, ,, xx xx xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx xx xx xx xx xx "
"xx ,, ,, ,, xx rn xx xx xx ,, xx ,, xx rn xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx rn rn rn rn rn "
"xx xx xx xx xx rn xx xx xx xx xx xx xx rn xx xx xx xx xx xx xx xx xx xx xx xx xx rn rn rn rn rn "
))
;;----------------------------------------------------------------------------
NPC 's
;;----------------------------------------------------------------------------
(kern-load "gholet.scm")
(kern-load "valus.scm")
;;----------------------------------------------------------------------------
;; Place
;;----------------------------------------------------------------------------
(kern-mk-place
'p_prison ; tag
"Prison" ; name
s_hamlet ; sprite
m_prison ; map
#f ; wraps
#t ; underground
#f ; large-scale (wilderness)
#f ; tmp combat place
nil ; subplaces
nil ; neighbors
(list ; objects
(put (mk-monman) 0 0)
(put (mk-ladder-up 'p_glasdrin 2 2) 6 4)
;; store room
(put (mk-locked-door) 6 2)
(put (mk-chest
'burn-trap
'(( 10 t_food)
)) 1 1)
(put (mk-chest
'burn-trap
'((1 t_cure_potion)
(1 t_heal_potion)
)) 2 1)
(put (mk-chest
'burn-trap
'((10 t_arrow)
)) 1 2)
(put (mk-chest
'burn-trap
'((10 t_bolt)
)) 2 7)
(put (mk-chest
'burn-trap
'((1 t_vas_mani_scroll)
)) 3 7)
(put (mk-chest
'burn-trap
'((10 sulphorous_ash)
(5 garlic)
(5 ginseng)
)) 3 6)
;; rats in store room
(put (spawn-pt 'rat) 1 1)
(put (spawn-pt 'rat) 1 3)
(put (spawn-pt 'rat) 2 4)
(put (spawn-pt 'rat) 3 7)
(put (spawn-pt 'rat) 1 6)
(put (spawn-pt 'rat) 4 2)
;; portcullises
(put (kern-tag 'pp1 (mk-portcullis)) 12 4)
(put (kern-tag 'pp2 (mk-portcullis)) 14 4)
;; energy fields for zorn
(put (kern-mk-obj F_energy_perm 1) 26 4)
(put (kern-mk-obj F_energy_perm 1) 28 3)
(put (kern-mk-obj F_energy_perm 1) 28 4)
(put (kern-mk-obj F_energy_perm 1) 28 5)
(put (kern-mk-obj F_energy_perm 1) 29 3)
(put (kern-mk-obj F_energy_perm 1) 29 5)
(put (kern-mk-obj F_energy_perm 1) 30 3)
(put (kern-mk-obj F_energy_perm 1) 30 4)
(put (kern-mk-obj F_energy_perm 1) 30 5)
;; cell doors
(put (mk-locked-windowed-door) 16 3)
(put (mk-locked-windowed-door) 20 3)
(put (mk-locked-windowed-door) 24 3)
(put (mk-locked-windowed-door) 16 5)
(put (mk-locked-windowed-door) 20 5)
(put (mk-locked-windowed-door) 24 5)
(put (mk-locked-door) 27 4)
;; levers
(put (mk-lever 'pp1) 11 1)
(put (mk-lever 'pp2) 11 7)
;; prisoners
(put (mk-gholet) 24 1)
(put (mk-npc 'zorn 8) 29 4)
(put (mk-npc 'footpad 8) 16 7)
(put (mk-valus) 24 6)
;; guards
(put (guard-pt 'halberdier) 9 1)
(put (guard-pt 'halberdier) 9 7)
)
(list 'on-entry-to-dungeon-room) ; on-entry hook(s)
nil ; edge entrances
)
(mk-place-music p_prison 'ml-dungeon-town)
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.002/prison.scm | scheme | ----------------------------------------------------------------------------
Map
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Place
----------------------------------------------------------------------------
tag
name
sprite
map
wraps
underground
large-scale (wilderness)
tmp combat place
subplaces
neighbors
objects
store room
rats in store room
portcullises
energy fields for zorn
cell doors
levers
prisoners
guards
on-entry hook(s)
edge entrances |
(kern-mk-map
'm_prison 32 9 pal_expanded
(list
"xx xx xx xx xx xx xx xx xx xx xx xx xx rn xx xx xx xx xx xx xx xx xx xx xx xx xx rn rn rn rn rn "
"xx ,, ,, ,, xx xx xx xx xx ,, xx ,, xx rn xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx rn rn rn rn rn "
"xx ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, xx xx xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx xx xx xx xx xx "
"xx ,, ,, ,, xx xx xx ,, ,, ,, ,, ,, xx ee xx xx ,, xx xx xx ,, xx xx xx ,, xx xx xx ,, ,, ,, xx "
"xx ,, ,, ,, xx xx ,, ,, ,, x! ,, ,, ,, ee ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, ,, xx "
"xx ,, ,, ,, xx xx xx ,, ,, ,, ,, ,, xx ee xx xx ,, xx xx xx ,, xx xx xx ,, xx xx xx ,, ,, ,, xx "
"xx ,, ,, ,, xx rn xx ,, ,, ,, ,, ,, xx xx xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx xx xx xx xx xx "
"xx ,, ,, ,, xx rn xx xx xx ,, xx ,, xx rn xx ,, ,, ,, xx ,, ,, ,, xx ,, ,, ,, xx rn rn rn rn rn "
"xx xx xx xx xx rn xx xx xx xx xx xx xx rn xx xx xx xx xx xx xx xx xx xx xx xx xx rn rn rn rn rn "
))
NPC 's
(kern-load "gholet.scm")
(kern-load "valus.scm")
(kern-mk-place
(put (mk-monman) 0 0)
(put (mk-ladder-up 'p_glasdrin 2 2) 6 4)
(put (mk-locked-door) 6 2)
(put (mk-chest
'burn-trap
'(( 10 t_food)
)) 1 1)
(put (mk-chest
'burn-trap
'((1 t_cure_potion)
(1 t_heal_potion)
)) 2 1)
(put (mk-chest
'burn-trap
'((10 t_arrow)
)) 1 2)
(put (mk-chest
'burn-trap
'((10 t_bolt)
)) 2 7)
(put (mk-chest
'burn-trap
'((1 t_vas_mani_scroll)
)) 3 7)
(put (mk-chest
'burn-trap
'((10 sulphorous_ash)
(5 garlic)
(5 ginseng)
)) 3 6)
(put (spawn-pt 'rat) 1 1)
(put (spawn-pt 'rat) 1 3)
(put (spawn-pt 'rat) 2 4)
(put (spawn-pt 'rat) 3 7)
(put (spawn-pt 'rat) 1 6)
(put (spawn-pt 'rat) 4 2)
(put (kern-tag 'pp1 (mk-portcullis)) 12 4)
(put (kern-tag 'pp2 (mk-portcullis)) 14 4)
(put (kern-mk-obj F_energy_perm 1) 26 4)
(put (kern-mk-obj F_energy_perm 1) 28 3)
(put (kern-mk-obj F_energy_perm 1) 28 4)
(put (kern-mk-obj F_energy_perm 1) 28 5)
(put (kern-mk-obj F_energy_perm 1) 29 3)
(put (kern-mk-obj F_energy_perm 1) 29 5)
(put (kern-mk-obj F_energy_perm 1) 30 3)
(put (kern-mk-obj F_energy_perm 1) 30 4)
(put (kern-mk-obj F_energy_perm 1) 30 5)
(put (mk-locked-windowed-door) 16 3)
(put (mk-locked-windowed-door) 20 3)
(put (mk-locked-windowed-door) 24 3)
(put (mk-locked-windowed-door) 16 5)
(put (mk-locked-windowed-door) 20 5)
(put (mk-locked-windowed-door) 24 5)
(put (mk-locked-door) 27 4)
(put (mk-lever 'pp1) 11 1)
(put (mk-lever 'pp2) 11 7)
(put (mk-gholet) 24 1)
(put (mk-npc 'zorn 8) 29 4)
(put (mk-npc 'footpad 8) 16 7)
(put (mk-valus) 24 6)
(put (guard-pt 'halberdier) 9 1)
(put (guard-pt 'halberdier) 9 7)
)
)
(mk-place-music p_prison 'ml-dungeon-town)
|
09bd1fba069f2ce9b3a45ac983d146c3a04f6eec9c961efbd2ef385914a43f03 | pink-gorilla/pinkie | pinkie_registry_test.cljs | (ns pinkie.pinkie-registry-test
(:require
[cljs.test :refer-macros [async deftest is testing]]
[pinkie.macros :refer-macros [fn-meta]]
[pinkie.pinkie :refer [component-list get-component get-renderer] :refer-macros [register-component]]
this registers jsrender
[pinkie.html :refer [html]]
[pinkie.text :refer [text]]
[pinkie.gtable :refer [gtable]]))
(defn ^{:category :pinkie-test
:doc "just used for testing"
:export true}
button
;"just testing"
[]
[:p "I am a button"])
(println "register-component"
(macroexpand '(register-component :p/testbutton2 button)))
(register-component :p/testbutton button)
(register-component :p/text text)
(register-component :p/phtml html)
(register-component :p/gtable gtable)
(deftest registry-lookup-test []
(is (= (get-renderer :p/text) text)) ; render fubctions in registry are identical
(is (= (get-renderer :p/phtml) html))
(is (= (get-renderer :p/gtable) gtable)))
(defn renderers-with-category []
(->> (component-list)
(filter #(get-in % [:meta :category]))))
(deftest registry-meta-test []
(is (> (count (renderers-with-category)) 0)) ; some components have to have valid category
(is (= (get-in (get-component :p/phtml) [:meta :category]) :ui)) ;checks if register/lookup works and meta storage
(is (= (:category (fn-meta render-js)) :pinkie))) ;render js has to be validly defined
| null | https://raw.githubusercontent.com/pink-gorilla/pinkie/f129cf6eb21d3822ef677bbbc0ef67bf785b197e/test/pinkie/pinkie_registry_test.cljs | clojure | "just testing"
render fubctions in registry are identical
some components have to have valid category
checks if register/lookup works and meta storage
render js has to be validly defined | (ns pinkie.pinkie-registry-test
(:require
[cljs.test :refer-macros [async deftest is testing]]
[pinkie.macros :refer-macros [fn-meta]]
[pinkie.pinkie :refer [component-list get-component get-renderer] :refer-macros [register-component]]
this registers jsrender
[pinkie.html :refer [html]]
[pinkie.text :refer [text]]
[pinkie.gtable :refer [gtable]]))
(defn ^{:category :pinkie-test
:doc "just used for testing"
:export true}
button
[]
[:p "I am a button"])
(println "register-component"
(macroexpand '(register-component :p/testbutton2 button)))
(register-component :p/testbutton button)
(register-component :p/text text)
(register-component :p/phtml html)
(register-component :p/gtable gtable)
(deftest registry-lookup-test []
(is (= (get-renderer :p/phtml) html))
(is (= (get-renderer :p/gtable) gtable)))
(defn renderers-with-category []
(->> (component-list)
(filter #(get-in % [:meta :category]))))
(deftest registry-meta-test []
|
3c133df179d8fdf93699ea6ec7a89aaf659216bcb28c398c568ae2a962144dc1 | nyu-acsys/drift | toChurch01.ml |
let rec bot _ = bot ()
let fail _ = assert false
let rec c10_COEFFICIENT_1129 = 0
let rec c9_COEFFICIENT_1128 = 0
let rec c8_COEFFICIENT_1127 = 0
let rec c7_COEFFICIENT_1125 = 0
let rec c6_COEFFICIENT_1124 = 0
let rec c5_COEFFICIENT_1123 = 0
let rec c4_COEFFICIENT_1122 = 0
let rec c3_COEFFICIENT_1121 = 0
let rec c2_COEFFICIENT_1120 = 0
let rec c1_COEFFICIENT_1117 = 0
let rec c0_COEFFICIENT_1116 = 0
let compose_1030 x_DO_NOT_CARE_1433 x_DO_NOT_CARE_1434 f_EXPARAM_1133 x_DO_NOT_CARE_1431 x_DO_NOT_CARE_1432 f_1031 x_DO_NOT_CARE_1429 x_DO_NOT_CARE_1430 g_EXPARAM_1134 x_DO_NOT_CARE_1427 x_DO_NOT_CARE_1428 g_1032 set_flag_id_1234 s_id_x_1231 x_1033 =
f_1031 set_flag_id_1234 s_id_x_1231
(g_1032 set_flag_id_1234 s_id_x_1231 x_1033)
let id_without_checking_1260 set_flag_id_1234 s_id_x_1231 x_1035 =
let set_flag_id_1234 = true
in
let s_id_x_1231 = x_1035
in
x_1035
let rec id_1034 prev_set_flag_id_1233 s_prev_id_x_1232 x_1035 =
let u = if prev_set_flag_id_1233 then
let u_6367 = fail ()
in
bot()
else () in
id_without_checking_1260 prev_set_flag_id_1233 s_prev_id_x_1232
x_1035
let succ_1036 set_flag_id_1234 s_id_x_1231 x_1037 = x_1037 + 1
let rec toChurch_1038 x_DO_NOT_CARE_1425 x_DO_NOT_CARE_1426 n_1039 x_DO_NOT_CARE_1423 x_DO_NOT_CARE_1424 f_EXPARAM_1119 set_flag_id_1234 s_id_x_1231 f_1040 =
if n_1039 = 0 then
id_1034
else
compose_1030 set_flag_id_1234 s_id_x_1231
((c2_COEFFICIENT_1120 * f_EXPARAM_1119) +
((c3_COEFFICIENT_1121 * n_1039) + c4_COEFFICIENT_1122))
set_flag_id_1234 s_id_x_1231 f_1040 set_flag_id_1234 s_id_x_1231
((c8_COEFFICIENT_1127 * f_EXPARAM_1119) +
((c9_COEFFICIENT_1128 * n_1039) + c10_COEFFICIENT_1129))
set_flag_id_1234 s_id_x_1231
(toChurch_1038 set_flag_id_1234 s_id_x_1231 (n_1039 - 1)
set_flag_id_1234 s_id_x_1231
((c5_COEFFICIENT_1123 * f_EXPARAM_1119) +
((c6_COEFFICIENT_1124 * n_1039) + c7_COEFFICIENT_1125))
set_flag_id_1234 s_id_x_1231 f_1040)
let main (x_1043:int(*-:{v:Int | true}*)) =
let set_flag_id_1234 = false in
let s_id_x_1231 = 0 in
if x_1043 >= 0 then
let tos_1044 =
toChurch_1038 set_flag_id_1234 s_id_x_1231 x_1043 set_flag_id_1234
s_id_x_1231 ((c0_COEFFICIENT_1116 * x_1043) + c1_COEFFICIENT_1117)
set_flag_id_1234 s_id_x_1231 succ_1036
in
()
else
()
| null | https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks/r_type/termination/toChurch01.ml | ocaml | -:{v:Int | true} |
let rec bot _ = bot ()
let fail _ = assert false
let rec c10_COEFFICIENT_1129 = 0
let rec c9_COEFFICIENT_1128 = 0
let rec c8_COEFFICIENT_1127 = 0
let rec c7_COEFFICIENT_1125 = 0
let rec c6_COEFFICIENT_1124 = 0
let rec c5_COEFFICIENT_1123 = 0
let rec c4_COEFFICIENT_1122 = 0
let rec c3_COEFFICIENT_1121 = 0
let rec c2_COEFFICIENT_1120 = 0
let rec c1_COEFFICIENT_1117 = 0
let rec c0_COEFFICIENT_1116 = 0
let compose_1030 x_DO_NOT_CARE_1433 x_DO_NOT_CARE_1434 f_EXPARAM_1133 x_DO_NOT_CARE_1431 x_DO_NOT_CARE_1432 f_1031 x_DO_NOT_CARE_1429 x_DO_NOT_CARE_1430 g_EXPARAM_1134 x_DO_NOT_CARE_1427 x_DO_NOT_CARE_1428 g_1032 set_flag_id_1234 s_id_x_1231 x_1033 =
f_1031 set_flag_id_1234 s_id_x_1231
(g_1032 set_flag_id_1234 s_id_x_1231 x_1033)
let id_without_checking_1260 set_flag_id_1234 s_id_x_1231 x_1035 =
let set_flag_id_1234 = true
in
let s_id_x_1231 = x_1035
in
x_1035
let rec id_1034 prev_set_flag_id_1233 s_prev_id_x_1232 x_1035 =
let u = if prev_set_flag_id_1233 then
let u_6367 = fail ()
in
bot()
else () in
id_without_checking_1260 prev_set_flag_id_1233 s_prev_id_x_1232
x_1035
let succ_1036 set_flag_id_1234 s_id_x_1231 x_1037 = x_1037 + 1
let rec toChurch_1038 x_DO_NOT_CARE_1425 x_DO_NOT_CARE_1426 n_1039 x_DO_NOT_CARE_1423 x_DO_NOT_CARE_1424 f_EXPARAM_1119 set_flag_id_1234 s_id_x_1231 f_1040 =
if n_1039 = 0 then
id_1034
else
compose_1030 set_flag_id_1234 s_id_x_1231
((c2_COEFFICIENT_1120 * f_EXPARAM_1119) +
((c3_COEFFICIENT_1121 * n_1039) + c4_COEFFICIENT_1122))
set_flag_id_1234 s_id_x_1231 f_1040 set_flag_id_1234 s_id_x_1231
((c8_COEFFICIENT_1127 * f_EXPARAM_1119) +
((c9_COEFFICIENT_1128 * n_1039) + c10_COEFFICIENT_1129))
set_flag_id_1234 s_id_x_1231
(toChurch_1038 set_flag_id_1234 s_id_x_1231 (n_1039 - 1)
set_flag_id_1234 s_id_x_1231
((c5_COEFFICIENT_1123 * f_EXPARAM_1119) +
((c6_COEFFICIENT_1124 * n_1039) + c7_COEFFICIENT_1125))
set_flag_id_1234 s_id_x_1231 f_1040)
let set_flag_id_1234 = false in
let s_id_x_1231 = 0 in
if x_1043 >= 0 then
let tos_1044 =
toChurch_1038 set_flag_id_1234 s_id_x_1231 x_1043 set_flag_id_1234
s_id_x_1231 ((c0_COEFFICIENT_1116 * x_1043) + c1_COEFFICIENT_1117)
set_flag_id_1234 s_id_x_1231 succ_1036
in
()
else
()
|
b2eae060c3edfab4f5ba23565717b2e7c9d0a706a103e1e751382c3e34c61e36 | kaznum/programming_in_ocaml_exercise | uncurry.ml | let curry f x y = f (x, y);;
let average (x, y) = (x +. y) /. 2.0;;
let curried_avg = curry average;;
curried_avg 1.0 2.0;;
let uncurry f (x, y) = f x y;;
let avg = uncurry curried_avg in
avg (4.0, 5.3);;
let add = uncurry (+.) in
add (3.1, 2.2);;
| null | https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ex4.1/uncurry.ml | ocaml | let curry f x y = f (x, y);;
let average (x, y) = (x +. y) /. 2.0;;
let curried_avg = curry average;;
curried_avg 1.0 2.0;;
let uncurry f (x, y) = f x y;;
let avg = uncurry curried_avg in
avg (4.0, 5.3);;
let add = uncurry (+.) in
add (3.1, 2.2);;
| |
43166d4f0bb896669c4ff87663c2cb57fa4b4ad85b2a90e7f51049402e8aeb82 | Dasudian/DSDIN | utils_time.erl | -module(utils_time).
%% API
-export([now_in_msecs/0,
msecs_to_secs/1]).
now_in_msecs() ->
{Megasecs, Secs, Microsecs} = os:timestamp(),
Megasecs * 1000000000 + Secs * 1000 + Microsecs div 1000.
msecs_to_secs(Msecs) ->
Msecs div 1000.
| null | https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/utils/src/utils_time.erl | erlang | API | -module(utils_time).
-export([now_in_msecs/0,
msecs_to_secs/1]).
now_in_msecs() ->
{Megasecs, Secs, Microsecs} = os:timestamp(),
Megasecs * 1000000000 + Secs * 1000 + Microsecs div 1000.
msecs_to_secs(Msecs) ->
Msecs div 1000.
|
15d4de6aa89940d25e89c7483ab7b70d262312edb716425ca6b90e80139ebccc | kongo2002/statser | statser_parser.erl | -module(statser_parser).
-export([parse/1,file/1]).
-define(p_anything,true).
-define(p_charclass,true).
-define(p_choose,true).
-define(p_label,true).
-define(p_not,true).
-define(p_one_or_more,true).
-define(p_optional,true).
-define(p_scan,true).
-define(p_seq,true).
-define(p_string,true).
-define(p_zero_or_more,true).
-spec file(file:name()) -> any().
file(Filename) -> case file:read_file(Filename) of {ok,Bin} -> parse(Bin); Err -> Err end.
-spec parse(binary() | list()) -> any().
parse(List) when is_list(List) -> parse(unicode:characters_to_binary(List));
parse(Input) when is_binary(Input) ->
_ = setup_memo(),
Result = case 'root'(Input,{{line,1},{column,1}}) of
{AST, <<>>, _Index} -> AST;
Any -> Any
end,
release_memo(), Result.
-spec 'root'(input(), index()) -> parse_result().
'root'(Input, Index) ->
p(Input, Index, 'root', fun(I,D) -> (p_choose([fun 'template'/2, fun 'function'/2, fun 'paths'/2]))(I,D) end, fun(Node, Idx) ->transform('root', Node, Idx) end).
-spec 'template'(input(), index()) -> parse_result().
'template'(Input, Index) ->
p(Input, Index, 'template', fun(I,D) -> (p_seq([p_string(<<"template(">>), fun 'expr'/2, fun 'spaces'/2, p_optional(p_seq([p_string(<<",">>), fun 'spaces'/2, fun 'arguments'/2])), fun 'spaces'/2, p_string(<<")">>)]))(I,D) end, fun(Node, _Idx) ->
case Node of
[_, Expr, _, [], _, _] -> {template, Expr, []};
[_, Expr, _, [_, _, Args], _, _] -> {template, Expr, Args}
end
end).
-spec 'expr'(input(), index()) -> parse_result().
'expr'(Input, Index) ->
p(Input, Index, 'expr', fun(I,D) -> (p_choose([fun 'function'/2, fun 'paths'/2]))(I,D) end, fun(Node, Idx) ->transform('expr', Node, Idx) end).
-spec 'function'(input(), index()) -> parse_result().
'function'(Input, Index) ->
p(Input, Index, 'function', fun(I,D) -> (p_seq([fun 'alphanum'/2, p_string(<<"(">>), fun 'arguments'/2, p_string(<<")">>)]))(I,D) end, fun(Node, _Idx) ->
[Fctn, _P1, Args, _P2] = Node, {call, iolist_to_binary(Fctn), Args}
end).
-spec 'arguments'(input(), index()) -> parse_result().
'arguments'(Input, Index) ->
p(Input, Index, 'arguments', fun(I,D) -> (p_seq([p_label('head', fun 'argument'/2), p_label('tail', p_zero_or_more(p_seq([fun 'spaces'/2, fun 'comma'/2, fun 'spaces'/2, fun 'argument'/2, fun 'spaces'/2])))]))(I,D) end, fun(Node, _Idx) ->
Head = proplists:get_value(head, Node),
Rest = [lists:nth(4, I) || I <- proplists:get_value(tail, Node)],
[Head | Rest]
end).
-spec 'argument'(input(), index()) -> parse_result().
'argument'(Input, Index) ->
p(Input, Index, 'argument', fun(I,D) -> (p_choose([fun 'number'/2, fun 'bool'/2, fun 'singleq_string'/2, fun 'doubleq_string'/2, fun 'function'/2, fun 'paths'/2]))(I,D) end, fun(Node, Idx) ->transform('argument', Node, Idx) end).
-spec 'paths'(input(), index()) -> parse_result().
'paths'(Input, Index) ->
p(Input, Index, 'paths', fun(I,D) -> (fun 'path'/2)(I,D) end, fun(Node, _Idx) ->{paths, Node} end).
-spec 'path'(input(), index()) -> parse_result().
'path'(Input, Index) ->
p(Input, Index, 'path', fun(I,D) -> (p_seq([p_label('head', fun 'path_elem'/2), p_label('tail', p_zero_or_more(p_seq([fun 'dot'/2, p_choose([fun 'path_elem'/2, fun 'path_alternatives'/2])])))]))(I,D) end, fun(Node, _Idx) ->
Head = proplists:get_value(head, Node),
Rest = [lists:nth(2, I) || I <- proplists:get_value(tail, Node)],
[Head | Rest]
end).
-spec 'path_elem'(input(), index()) -> parse_result().
'path_elem'(Input, Index) ->
p(Input, Index, 'path_elem', fun(I,D) -> (p_one_or_more(p_choose([fun 'wordchar'/2, p_seq([fun 'escape'/2, fun 'special'/2])])))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(Node) end).
-spec 'path_alternatives'(input(), index()) -> parse_result().
'path_alternatives'(Input, Index) ->
p(Input, Index, 'path_alternatives', fun(I,D) -> (p_seq([p_string(<<"{">>), fun 'path_alternative'/2, p_string(<<"}">>)]))(I,D) end, fun(Node, _Idx) ->{alternative, lists:nth(2, Node)} end).
-spec 'path_alternative'(input(), index()) -> parse_result().
'path_alternative'(Input, Index) ->
p(Input, Index, 'path_alternative', fun(I,D) -> (p_seq([fun 'spaces'/2, p_label('head', fun 'alternative'/2), p_label('tail', p_zero_or_more(p_seq([fun 'spaces'/2, fun 'comma'/2, fun 'spaces'/2, fun 'alternative'/2, fun 'spaces'/2])))]))(I,D) end, fun(Node, _Idx) ->
Head = proplists:get_value(head, Node),
Rest = [lists:nth(4, I) || I <- proplists:get_value(tail, Node)],
[Head | Rest]
end).
-spec 'alternative'(input(), index()) -> parse_result().
'alternative'(Input, Index) ->
p(Input, Index, 'alternative', fun(I,D) -> (p_one_or_more(fun 'wordchar'/2))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(Node) end).
-spec 'wordchar'(input(), index()) -> parse_result().
'wordchar'(Input, Index) ->
p(Input, Index, 'wordchar', fun(I,D) -> (p_charclass(<<"[a-zA-Z0-9*_-]">>))(I,D) end, fun(Node, Idx) ->transform('wordchar', Node, Idx) end).
-spec 'alphanum'(input(), index()) -> parse_result().
'alphanum'(Input, Index) ->
p(Input, Index, 'alphanum', fun(I,D) -> (p_seq([p_charclass(<<"[a-zA-Z]">>), p_zero_or_more(p_charclass(<<"[a-zA-Z0-9]">>))]))(I,D) end, fun(Node, Idx) ->transform('alphanum', Node, Idx) end).
-spec 'special'(input(), index()) -> parse_result().
'special'(Input, Index) ->
p(Input, Index, 'special', fun(I,D) -> (p_charclass(<<"[(){},=.\"]">>))(I,D) end, fun(Node, Idx) ->transform('special', Node, Idx) end).
-spec 'escape'(input(), index()) -> parse_result().
'escape'(Input, Index) ->
p(Input, Index, 'escape', fun(I,D) -> (p_string(<<"\\">>))(I,D) end, fun(Node, Idx) ->transform('escape', Node, Idx) end).
-spec 'dot'(input(), index()) -> parse_result().
'dot'(Input, Index) ->
p(Input, Index, 'dot', fun(I,D) -> (p_string(<<".">>))(I,D) end, fun(Node, Idx) ->transform('dot', Node, Idx) end).
-spec 'comma'(input(), index()) -> parse_result().
'comma'(Input, Index) ->
p(Input, Index, 'comma', fun(I,D) -> (p_string(<<",">>))(I,D) end, fun(Node, Idx) ->transform('comma', Node, Idx) end).
-spec 'bool'(input(), index()) -> parse_result().
'bool'(Input, Index) ->
p(Input, Index, 'bool', fun(I,D) -> (p_choose([fun 'true'/2, fun 'false'/2]))(I,D) end, fun(Node, Idx) ->transform('bool', Node, Idx) end).
-spec 'true'(input(), index()) -> parse_result().
'true'(Input, Index) ->
p(Input, Index, 'true', fun(I,D) -> (p_string(<<"true">>))(I,D) end, fun(_Node, _Idx) ->true end).
-spec 'false'(input(), index()) -> parse_result().
'false'(Input, Index) ->
p(Input, Index, 'false', fun(I,D) -> (p_string(<<"false">>))(I,D) end, fun(_Node, _Idx) ->false end).
-spec 'number'(input(), index()) -> parse_result().
'number'(Input, Index) ->
p(Input, Index, 'number', fun(I,D) -> (p_choose([fun 'float'/2, fun 'int'/2]))(I,D) end, fun(Node, Idx) ->transform('number', Node, Idx) end).
-spec 'float'(input(), index()) -> parse_result().
'float'(Input, Index) ->
p(Input, Index, 'float', fun(I,D) -> (p_seq([p_optional(p_string(<<"-">>)), p_one_or_more(fun 'digit'/2), p_string(<<".">>), p_one_or_more(fun 'digit'/2)]))(I,D) end, fun(Node, _Idx) ->list_to_float(binary_to_list(iolist_to_binary(Node))) end).
-spec 'int'(input(), index()) -> parse_result().
'int'(Input, Index) ->
p(Input, Index, 'int', fun(I,D) -> (p_seq([p_optional(p_string(<<"-">>)), p_one_or_more(fun 'digit'/2)]))(I,D) end, fun(Node, _Idx) ->list_to_integer(binary_to_list(iolist_to_binary(Node))) end).
-spec 'digit'(input(), index()) -> parse_result().
'digit'(Input, Index) ->
p(Input, Index, 'digit', fun(I,D) -> (p_charclass(<<"[0-9]">>))(I,D) end, fun(Node, Idx) ->transform('digit', Node, Idx) end).
-spec 'doubleq_string'(input(), index()) -> parse_result().
'doubleq_string'(Input, Index) ->
p(Input, Index, 'doubleq_string', fun(I,D) -> (p_seq([p_string(<<"\"">>), p_label('chars', p_zero_or_more(p_seq([p_not(p_string(<<"\"">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\"">>), p_anything()])]))), p_string(<<"\"">>)]))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(proplists:get_value(chars, Node)) end).
-spec 'singleq_string'(input(), index()) -> parse_result().
'singleq_string'(Input, Index) ->
p(Input, Index, 'singleq_string', fun(I,D) -> (p_seq([p_string(<<"\'">>), p_label('chars', p_zero_or_more(p_seq([p_not(p_string(<<"\'">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\'">>), p_anything()])]))), p_string(<<"\'">>)]))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(proplists:get_value(chars, Node)) end).
-spec 'spaces'(input(), index()) -> parse_result().
'spaces'(Input, Index) ->
p(Input, Index, 'spaces', fun(I,D) -> (p_zero_or_more(p_charclass(<<"[\s\t\n\s\r]">>)))(I,D) end, fun(Node, Idx) ->transform('spaces', Node, Idx) end).
transform(_,Node,_Index) -> Node.
-file("peg_includes.hrl", 1).
-type index() :: {{line, pos_integer()}, {column, pos_integer()}}.
-type input() :: binary().
-type parse_failure() :: {fail, term()}.
-type parse_success() :: {term(), input(), index()}.
-type parse_result() :: parse_failure() | parse_success().
-type parse_fun() :: fun((input(), index()) -> parse_result()).
-type xform_fun() :: fun((input(), index()) -> term()).
-spec p(input(), index(), atom(), parse_fun(), xform_fun()) -> parse_result().
p(Inp, StartIndex, Name, ParseFun, TransformFun) ->
case get_memo(StartIndex, Name) of % See if the current reduction is memoized
{ok, Memo} -> %Memo; % If it is, return the stored result
Memo;
_ -> % If not, attempt to parse
Result = case ParseFun(Inp, StartIndex) of
{fail,_} = Failure -> % If it fails, memoize the failure
Failure;
{Match, InpRem, NewIndex} -> % If it passes, transform and memoize the result.
Transformed = TransformFun(Match, StartIndex),
{Transformed, InpRem, NewIndex}
end,
memoize(StartIndex, Name, Result),
Result
end.
-spec setup_memo() -> ets:tid().
setup_memo() ->
put({parse_memo_table, ?MODULE}, ets:new(?MODULE, [set])).
-spec release_memo() -> true.
release_memo() ->
ets:delete(memo_table_name()).
-spec memoize(index(), atom(), parse_result()) -> true.
memoize(Index, Name, Result) ->
Memo = case ets:lookup(memo_table_name(), Index) of
[] -> [];
[{Index, Plist}] -> Plist
end,
ets:insert(memo_table_name(), {Index, [{Name, Result}|Memo]}).
-spec get_memo(index(), atom()) -> {ok, term()} | {error, not_found}.
get_memo(Index, Name) ->
case ets:lookup(memo_table_name(), Index) of
[] -> {error, not_found};
[{Index, Plist}] ->
case proplists:lookup(Name, Plist) of
{Name, Result} -> {ok, Result};
_ -> {error, not_found}
end
end.
-spec memo_table_name() -> ets:tid().
memo_table_name() ->
get({parse_memo_table, ?MODULE}).
-ifdef(p_eof).
-spec p_eof() -> parse_fun().
p_eof() ->
fun(<<>>, Index) -> {eof, [], Index};
(_, Index) -> {fail, {expected, eof, Index}} end.
-endif.
-ifdef(p_optional).
-spec p_optional(parse_fun()) -> parse_fun().
p_optional(P) ->
fun(Input, Index) ->
case P(Input, Index) of
{fail,_} -> {[], Input, Index};
{_, _, _} = Success -> Success
end
end.
-endif.
-ifdef(p_not).
-spec p_not(parse_fun()) -> parse_fun().
p_not(P) ->
fun(Input, Index)->
case P(Input,Index) of
{fail,_} ->
{[], Input, Index};
{Result, _, _} -> {fail, {expected, {no_match, Result},Index}}
end
end.
-endif.
-ifdef(p_assert).
-spec p_assert(parse_fun()) -> parse_fun().
p_assert(P) ->
fun(Input,Index) ->
case P(Input,Index) of
{fail,_} = Failure-> Failure;
_ -> {[], Input, Index}
end
end.
-endif.
-ifdef(p_seq).
-spec p_seq([parse_fun()]) -> parse_fun().
p_seq(P) ->
fun(Input, Index) ->
p_all(P, Input, Index, [])
end.
-spec p_all([parse_fun()], input(), index(), [term()]) -> parse_result().
p_all([], Inp, Index, Accum ) -> {lists:reverse( Accum ), Inp, Index};
p_all([P|Parsers], Inp, Index, Accum) ->
case P(Inp, Index) of
{fail, _} = Failure -> Failure;
{Result, InpRem, NewIndex} -> p_all(Parsers, InpRem, NewIndex, [Result|Accum])
end.
-endif.
-ifdef(p_choose).
-spec p_choose([parse_fun()]) -> parse_fun().
p_choose(Parsers) ->
fun(Input, Index) ->
p_attempt(Parsers, Input, Index, none)
end.
-spec p_attempt([parse_fun()], input(), index(), none | parse_failure()) -> parse_result().
p_attempt([], _Input, _Index, Failure) -> Failure;
p_attempt([P|Parsers], Input, Index, FirstFailure)->
case P(Input, Index) of
{fail, _} = Failure ->
case FirstFailure of
none -> p_attempt(Parsers, Input, Index, Failure);
_ -> p_attempt(Parsers, Input, Index, FirstFailure)
end;
Result -> Result
end.
-endif.
-ifdef(p_zero_or_more).
-spec p_zero_or_more(parse_fun()) -> parse_fun().
p_zero_or_more(P) ->
fun(Input, Index) ->
p_scan(P, Input, Index, [])
end.
-endif.
-ifdef(p_one_or_more).
-spec p_one_or_more(parse_fun()) -> parse_fun().
p_one_or_more(P) ->
fun(Input, Index)->
Result = p_scan(P, Input, Index, []),
case Result of
{[_|_], _, _} ->
Result;
_ ->
{fail, {expected, Failure, _}} = P(Input,Index),
{fail, {expected, {at_least_one, Failure}, Index}}
end
end.
-endif.
-ifdef(p_label).
-spec p_label(atom(), parse_fun()) -> parse_fun().
p_label(Tag, P) ->
fun(Input, Index) ->
case P(Input, Index) of
{fail,_} = Failure ->
Failure;
{Result, InpRem, NewIndex} ->
{{Tag, Result}, InpRem, NewIndex}
end
end.
-endif.
-ifdef(p_scan).
-spec p_scan(parse_fun(), input(), index(), [term()]) -> {[term()], input(), index()}.
p_scan(_, <<>>, Index, Accum) -> {lists:reverse(Accum), <<>>, Index};
p_scan(P, Inp, Index, Accum) ->
case P(Inp, Index) of
{fail,_} -> {lists:reverse(Accum), Inp, Index};
{Result, InpRem, NewIndex} -> p_scan(P, InpRem, NewIndex, [Result | Accum])
end.
-endif.
-ifdef(p_string).
-spec p_string(binary()) -> parse_fun().
p_string(S) ->
Length = erlang:byte_size(S),
fun(Input, Index) ->
try
<<S:Length/binary, Rest/binary>> = Input,
{S, Rest, p_advance_index(S, Index)}
catch
error:{badmatch,_} -> {fail, {expected, {string, S}, Index}}
end
end.
-endif.
-ifdef(p_anything).
-spec p_anything() -> parse_fun().
p_anything() ->
fun(<<>>, Index) -> {fail, {expected, any_character, Index}};
(Input, Index) when is_binary(Input) ->
<<C/utf8, Rest/binary>> = Input,
{<<C/utf8>>, Rest, p_advance_index(<<C/utf8>>, Index)}
end.
-endif.
-ifdef(p_charclass).
-spec p_charclass(string() | binary()) -> parse_fun().
p_charclass(Class) ->
{ok, RE} = re:compile(Class, [unicode, dotall]),
fun(Inp, Index) ->
case re:run(Inp, RE, [anchored]) of
{match, [{0, Length}|_]} ->
{Head, Tail} = erlang:split_binary(Inp, Length),
{Head, Tail, p_advance_index(Head, Index)};
_ -> {fail, {expected, {character_class, binary_to_list(Class)}, Index}}
end
end.
-endif.
-ifdef(p_regexp).
-spec p_regexp(binary()) -> parse_fun().
p_regexp(Regexp) ->
{ok, RE} = re:compile(Regexp, [unicode, dotall, anchored]),
fun(Inp, Index) ->
case re:run(Inp, RE) of
{match, [{0, Length}|_]} ->
{Head, Tail} = erlang:split_binary(Inp, Length),
{Head, Tail, p_advance_index(Head, Index)};
_ -> {fail, {expected, {regexp, binary_to_list(Regexp)}, Index}}
end
end.
-endif.
-ifdef(line).
-spec line(index() | term()) -> pos_integer() | undefined.
line({{line,L},_}) -> L;
line(_) -> undefined.
-endif.
-ifdef(column).
-spec column(index() | term()) -> pos_integer() | undefined.
column({_,{column,C}}) -> C;
column(_) -> undefined.
-endif.
-spec p_advance_index(input() | unicode:charlist() | pos_integer(), index()) -> index().
p_advance_index(MatchedInput, Index) when is_list(MatchedInput) orelse is_binary(MatchedInput)-> % strings
lists:foldl(fun p_advance_index/2, Index, unicode:characters_to_list(MatchedInput));
p_advance_index(MatchedInput, Index) when is_integer(MatchedInput) -> % single characters
{{line, Line}, {column, Col}} = Index,
case MatchedInput of
$\n -> {{line, Line+1}, {column, 1}};
_ -> {{line, Line}, {column, Col+1}}
end.
| null | https://raw.githubusercontent.com/kongo2002/statser/1cb0498f56c97d8a010b979c5163dd2750064e98/src/statser_parser.erl | erlang | See if the current reduction is memoized
Memo; % If it is, return the stored result
If not, attempt to parse
If it fails, memoize the failure
If it passes, transform and memoize the result.
strings
single characters | -module(statser_parser).
-export([parse/1,file/1]).
-define(p_anything,true).
-define(p_charclass,true).
-define(p_choose,true).
-define(p_label,true).
-define(p_not,true).
-define(p_one_or_more,true).
-define(p_optional,true).
-define(p_scan,true).
-define(p_seq,true).
-define(p_string,true).
-define(p_zero_or_more,true).
-spec file(file:name()) -> any().
file(Filename) -> case file:read_file(Filename) of {ok,Bin} -> parse(Bin); Err -> Err end.
-spec parse(binary() | list()) -> any().
parse(List) when is_list(List) -> parse(unicode:characters_to_binary(List));
parse(Input) when is_binary(Input) ->
_ = setup_memo(),
Result = case 'root'(Input,{{line,1},{column,1}}) of
{AST, <<>>, _Index} -> AST;
Any -> Any
end,
release_memo(), Result.
-spec 'root'(input(), index()) -> parse_result().
'root'(Input, Index) ->
p(Input, Index, 'root', fun(I,D) -> (p_choose([fun 'template'/2, fun 'function'/2, fun 'paths'/2]))(I,D) end, fun(Node, Idx) ->transform('root', Node, Idx) end).
-spec 'template'(input(), index()) -> parse_result().
'template'(Input, Index) ->
p(Input, Index, 'template', fun(I,D) -> (p_seq([p_string(<<"template(">>), fun 'expr'/2, fun 'spaces'/2, p_optional(p_seq([p_string(<<",">>), fun 'spaces'/2, fun 'arguments'/2])), fun 'spaces'/2, p_string(<<")">>)]))(I,D) end, fun(Node, _Idx) ->
case Node of
[_, Expr, _, [], _, _] -> {template, Expr, []};
[_, Expr, _, [_, _, Args], _, _] -> {template, Expr, Args}
end
end).
-spec 'expr'(input(), index()) -> parse_result().
'expr'(Input, Index) ->
p(Input, Index, 'expr', fun(I,D) -> (p_choose([fun 'function'/2, fun 'paths'/2]))(I,D) end, fun(Node, Idx) ->transform('expr', Node, Idx) end).
-spec 'function'(input(), index()) -> parse_result().
'function'(Input, Index) ->
p(Input, Index, 'function', fun(I,D) -> (p_seq([fun 'alphanum'/2, p_string(<<"(">>), fun 'arguments'/2, p_string(<<")">>)]))(I,D) end, fun(Node, _Idx) ->
[Fctn, _P1, Args, _P2] = Node, {call, iolist_to_binary(Fctn), Args}
end).
-spec 'arguments'(input(), index()) -> parse_result().
'arguments'(Input, Index) ->
p(Input, Index, 'arguments', fun(I,D) -> (p_seq([p_label('head', fun 'argument'/2), p_label('tail', p_zero_or_more(p_seq([fun 'spaces'/2, fun 'comma'/2, fun 'spaces'/2, fun 'argument'/2, fun 'spaces'/2])))]))(I,D) end, fun(Node, _Idx) ->
Head = proplists:get_value(head, Node),
Rest = [lists:nth(4, I) || I <- proplists:get_value(tail, Node)],
[Head | Rest]
end).
-spec 'argument'(input(), index()) -> parse_result().
'argument'(Input, Index) ->
p(Input, Index, 'argument', fun(I,D) -> (p_choose([fun 'number'/2, fun 'bool'/2, fun 'singleq_string'/2, fun 'doubleq_string'/2, fun 'function'/2, fun 'paths'/2]))(I,D) end, fun(Node, Idx) ->transform('argument', Node, Idx) end).
-spec 'paths'(input(), index()) -> parse_result().
'paths'(Input, Index) ->
p(Input, Index, 'paths', fun(I,D) -> (fun 'path'/2)(I,D) end, fun(Node, _Idx) ->{paths, Node} end).
-spec 'path'(input(), index()) -> parse_result().
'path'(Input, Index) ->
p(Input, Index, 'path', fun(I,D) -> (p_seq([p_label('head', fun 'path_elem'/2), p_label('tail', p_zero_or_more(p_seq([fun 'dot'/2, p_choose([fun 'path_elem'/2, fun 'path_alternatives'/2])])))]))(I,D) end, fun(Node, _Idx) ->
Head = proplists:get_value(head, Node),
Rest = [lists:nth(2, I) || I <- proplists:get_value(tail, Node)],
[Head | Rest]
end).
-spec 'path_elem'(input(), index()) -> parse_result().
'path_elem'(Input, Index) ->
p(Input, Index, 'path_elem', fun(I,D) -> (p_one_or_more(p_choose([fun 'wordchar'/2, p_seq([fun 'escape'/2, fun 'special'/2])])))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(Node) end).
-spec 'path_alternatives'(input(), index()) -> parse_result().
'path_alternatives'(Input, Index) ->
p(Input, Index, 'path_alternatives', fun(I,D) -> (p_seq([p_string(<<"{">>), fun 'path_alternative'/2, p_string(<<"}">>)]))(I,D) end, fun(Node, _Idx) ->{alternative, lists:nth(2, Node)} end).
-spec 'path_alternative'(input(), index()) -> parse_result().
'path_alternative'(Input, Index) ->
p(Input, Index, 'path_alternative', fun(I,D) -> (p_seq([fun 'spaces'/2, p_label('head', fun 'alternative'/2), p_label('tail', p_zero_or_more(p_seq([fun 'spaces'/2, fun 'comma'/2, fun 'spaces'/2, fun 'alternative'/2, fun 'spaces'/2])))]))(I,D) end, fun(Node, _Idx) ->
Head = proplists:get_value(head, Node),
Rest = [lists:nth(4, I) || I <- proplists:get_value(tail, Node)],
[Head | Rest]
end).
-spec 'alternative'(input(), index()) -> parse_result().
'alternative'(Input, Index) ->
p(Input, Index, 'alternative', fun(I,D) -> (p_one_or_more(fun 'wordchar'/2))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(Node) end).
-spec 'wordchar'(input(), index()) -> parse_result().
'wordchar'(Input, Index) ->
p(Input, Index, 'wordchar', fun(I,D) -> (p_charclass(<<"[a-zA-Z0-9*_-]">>))(I,D) end, fun(Node, Idx) ->transform('wordchar', Node, Idx) end).
-spec 'alphanum'(input(), index()) -> parse_result().
'alphanum'(Input, Index) ->
p(Input, Index, 'alphanum', fun(I,D) -> (p_seq([p_charclass(<<"[a-zA-Z]">>), p_zero_or_more(p_charclass(<<"[a-zA-Z0-9]">>))]))(I,D) end, fun(Node, Idx) ->transform('alphanum', Node, Idx) end).
-spec 'special'(input(), index()) -> parse_result().
'special'(Input, Index) ->
p(Input, Index, 'special', fun(I,D) -> (p_charclass(<<"[(){},=.\"]">>))(I,D) end, fun(Node, Idx) ->transform('special', Node, Idx) end).
-spec 'escape'(input(), index()) -> parse_result().
'escape'(Input, Index) ->
p(Input, Index, 'escape', fun(I,D) -> (p_string(<<"\\">>))(I,D) end, fun(Node, Idx) ->transform('escape', Node, Idx) end).
-spec 'dot'(input(), index()) -> parse_result().
'dot'(Input, Index) ->
p(Input, Index, 'dot', fun(I,D) -> (p_string(<<".">>))(I,D) end, fun(Node, Idx) ->transform('dot', Node, Idx) end).
-spec 'comma'(input(), index()) -> parse_result().
'comma'(Input, Index) ->
p(Input, Index, 'comma', fun(I,D) -> (p_string(<<",">>))(I,D) end, fun(Node, Idx) ->transform('comma', Node, Idx) end).
-spec 'bool'(input(), index()) -> parse_result().
'bool'(Input, Index) ->
p(Input, Index, 'bool', fun(I,D) -> (p_choose([fun 'true'/2, fun 'false'/2]))(I,D) end, fun(Node, Idx) ->transform('bool', Node, Idx) end).
-spec 'true'(input(), index()) -> parse_result().
'true'(Input, Index) ->
p(Input, Index, 'true', fun(I,D) -> (p_string(<<"true">>))(I,D) end, fun(_Node, _Idx) ->true end).
-spec 'false'(input(), index()) -> parse_result().
'false'(Input, Index) ->
p(Input, Index, 'false', fun(I,D) -> (p_string(<<"false">>))(I,D) end, fun(_Node, _Idx) ->false end).
-spec 'number'(input(), index()) -> parse_result().
'number'(Input, Index) ->
p(Input, Index, 'number', fun(I,D) -> (p_choose([fun 'float'/2, fun 'int'/2]))(I,D) end, fun(Node, Idx) ->transform('number', Node, Idx) end).
-spec 'float'(input(), index()) -> parse_result().
'float'(Input, Index) ->
p(Input, Index, 'float', fun(I,D) -> (p_seq([p_optional(p_string(<<"-">>)), p_one_or_more(fun 'digit'/2), p_string(<<".">>), p_one_or_more(fun 'digit'/2)]))(I,D) end, fun(Node, _Idx) ->list_to_float(binary_to_list(iolist_to_binary(Node))) end).
-spec 'int'(input(), index()) -> parse_result().
'int'(Input, Index) ->
p(Input, Index, 'int', fun(I,D) -> (p_seq([p_optional(p_string(<<"-">>)), p_one_or_more(fun 'digit'/2)]))(I,D) end, fun(Node, _Idx) ->list_to_integer(binary_to_list(iolist_to_binary(Node))) end).
-spec 'digit'(input(), index()) -> parse_result().
'digit'(Input, Index) ->
p(Input, Index, 'digit', fun(I,D) -> (p_charclass(<<"[0-9]">>))(I,D) end, fun(Node, Idx) ->transform('digit', Node, Idx) end).
-spec 'doubleq_string'(input(), index()) -> parse_result().
'doubleq_string'(Input, Index) ->
p(Input, Index, 'doubleq_string', fun(I,D) -> (p_seq([p_string(<<"\"">>), p_label('chars', p_zero_or_more(p_seq([p_not(p_string(<<"\"">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\"">>), p_anything()])]))), p_string(<<"\"">>)]))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(proplists:get_value(chars, Node)) end).
-spec 'singleq_string'(input(), index()) -> parse_result().
'singleq_string'(Input, Index) ->
p(Input, Index, 'singleq_string', fun(I,D) -> (p_seq([p_string(<<"\'">>), p_label('chars', p_zero_or_more(p_seq([p_not(p_string(<<"\'">>)), p_choose([p_string(<<"\\\\">>), p_string(<<"\\\'">>), p_anything()])]))), p_string(<<"\'">>)]))(I,D) end, fun(Node, _Idx) ->iolist_to_binary(proplists:get_value(chars, Node)) end).
-spec 'spaces'(input(), index()) -> parse_result().
'spaces'(Input, Index) ->
p(Input, Index, 'spaces', fun(I,D) -> (p_zero_or_more(p_charclass(<<"[\s\t\n\s\r]">>)))(I,D) end, fun(Node, Idx) ->transform('spaces', Node, Idx) end).
transform(_,Node,_Index) -> Node.
-file("peg_includes.hrl", 1).
-type index() :: {{line, pos_integer()}, {column, pos_integer()}}.
-type input() :: binary().
-type parse_failure() :: {fail, term()}.
-type parse_success() :: {term(), input(), index()}.
-type parse_result() :: parse_failure() | parse_success().
-type parse_fun() :: fun((input(), index()) -> parse_result()).
-type xform_fun() :: fun((input(), index()) -> term()).
-spec p(input(), index(), atom(), parse_fun(), xform_fun()) -> parse_result().
p(Inp, StartIndex, Name, ParseFun, TransformFun) ->
Memo;
Result = case ParseFun(Inp, StartIndex) of
Failure;
Transformed = TransformFun(Match, StartIndex),
{Transformed, InpRem, NewIndex}
end,
memoize(StartIndex, Name, Result),
Result
end.
-spec setup_memo() -> ets:tid().
setup_memo() ->
put({parse_memo_table, ?MODULE}, ets:new(?MODULE, [set])).
-spec release_memo() -> true.
release_memo() ->
ets:delete(memo_table_name()).
-spec memoize(index(), atom(), parse_result()) -> true.
memoize(Index, Name, Result) ->
Memo = case ets:lookup(memo_table_name(), Index) of
[] -> [];
[{Index, Plist}] -> Plist
end,
ets:insert(memo_table_name(), {Index, [{Name, Result}|Memo]}).
-spec get_memo(index(), atom()) -> {ok, term()} | {error, not_found}.
get_memo(Index, Name) ->
case ets:lookup(memo_table_name(), Index) of
[] -> {error, not_found};
[{Index, Plist}] ->
case proplists:lookup(Name, Plist) of
{Name, Result} -> {ok, Result};
_ -> {error, not_found}
end
end.
-spec memo_table_name() -> ets:tid().
memo_table_name() ->
get({parse_memo_table, ?MODULE}).
-ifdef(p_eof).
-spec p_eof() -> parse_fun().
p_eof() ->
fun(<<>>, Index) -> {eof, [], Index};
(_, Index) -> {fail, {expected, eof, Index}} end.
-endif.
-ifdef(p_optional).
-spec p_optional(parse_fun()) -> parse_fun().
p_optional(P) ->
fun(Input, Index) ->
case P(Input, Index) of
{fail,_} -> {[], Input, Index};
{_, _, _} = Success -> Success
end
end.
-endif.
-ifdef(p_not).
-spec p_not(parse_fun()) -> parse_fun().
p_not(P) ->
fun(Input, Index)->
case P(Input,Index) of
{fail,_} ->
{[], Input, Index};
{Result, _, _} -> {fail, {expected, {no_match, Result},Index}}
end
end.
-endif.
-ifdef(p_assert).
-spec p_assert(parse_fun()) -> parse_fun().
p_assert(P) ->
fun(Input,Index) ->
case P(Input,Index) of
{fail,_} = Failure-> Failure;
_ -> {[], Input, Index}
end
end.
-endif.
-ifdef(p_seq).
-spec p_seq([parse_fun()]) -> parse_fun().
p_seq(P) ->
fun(Input, Index) ->
p_all(P, Input, Index, [])
end.
-spec p_all([parse_fun()], input(), index(), [term()]) -> parse_result().
p_all([], Inp, Index, Accum ) -> {lists:reverse( Accum ), Inp, Index};
p_all([P|Parsers], Inp, Index, Accum) ->
case P(Inp, Index) of
{fail, _} = Failure -> Failure;
{Result, InpRem, NewIndex} -> p_all(Parsers, InpRem, NewIndex, [Result|Accum])
end.
-endif.
-ifdef(p_choose).
-spec p_choose([parse_fun()]) -> parse_fun().
p_choose(Parsers) ->
fun(Input, Index) ->
p_attempt(Parsers, Input, Index, none)
end.
-spec p_attempt([parse_fun()], input(), index(), none | parse_failure()) -> parse_result().
p_attempt([], _Input, _Index, Failure) -> Failure;
p_attempt([P|Parsers], Input, Index, FirstFailure)->
case P(Input, Index) of
{fail, _} = Failure ->
case FirstFailure of
none -> p_attempt(Parsers, Input, Index, Failure);
_ -> p_attempt(Parsers, Input, Index, FirstFailure)
end;
Result -> Result
end.
-endif.
-ifdef(p_zero_or_more).
-spec p_zero_or_more(parse_fun()) -> parse_fun().
p_zero_or_more(P) ->
fun(Input, Index) ->
p_scan(P, Input, Index, [])
end.
-endif.
-ifdef(p_one_or_more).
-spec p_one_or_more(parse_fun()) -> parse_fun().
p_one_or_more(P) ->
fun(Input, Index)->
Result = p_scan(P, Input, Index, []),
case Result of
{[_|_], _, _} ->
Result;
_ ->
{fail, {expected, Failure, _}} = P(Input,Index),
{fail, {expected, {at_least_one, Failure}, Index}}
end
end.
-endif.
-ifdef(p_label).
-spec p_label(atom(), parse_fun()) -> parse_fun().
p_label(Tag, P) ->
fun(Input, Index) ->
case P(Input, Index) of
{fail,_} = Failure ->
Failure;
{Result, InpRem, NewIndex} ->
{{Tag, Result}, InpRem, NewIndex}
end
end.
-endif.
-ifdef(p_scan).
-spec p_scan(parse_fun(), input(), index(), [term()]) -> {[term()], input(), index()}.
p_scan(_, <<>>, Index, Accum) -> {lists:reverse(Accum), <<>>, Index};
p_scan(P, Inp, Index, Accum) ->
case P(Inp, Index) of
{fail,_} -> {lists:reverse(Accum), Inp, Index};
{Result, InpRem, NewIndex} -> p_scan(P, InpRem, NewIndex, [Result | Accum])
end.
-endif.
-ifdef(p_string).
-spec p_string(binary()) -> parse_fun().
p_string(S) ->
Length = erlang:byte_size(S),
fun(Input, Index) ->
try
<<S:Length/binary, Rest/binary>> = Input,
{S, Rest, p_advance_index(S, Index)}
catch
error:{badmatch,_} -> {fail, {expected, {string, S}, Index}}
end
end.
-endif.
-ifdef(p_anything).
-spec p_anything() -> parse_fun().
p_anything() ->
fun(<<>>, Index) -> {fail, {expected, any_character, Index}};
(Input, Index) when is_binary(Input) ->
<<C/utf8, Rest/binary>> = Input,
{<<C/utf8>>, Rest, p_advance_index(<<C/utf8>>, Index)}
end.
-endif.
-ifdef(p_charclass).
-spec p_charclass(string() | binary()) -> parse_fun().
p_charclass(Class) ->
{ok, RE} = re:compile(Class, [unicode, dotall]),
fun(Inp, Index) ->
case re:run(Inp, RE, [anchored]) of
{match, [{0, Length}|_]} ->
{Head, Tail} = erlang:split_binary(Inp, Length),
{Head, Tail, p_advance_index(Head, Index)};
_ -> {fail, {expected, {character_class, binary_to_list(Class)}, Index}}
end
end.
-endif.
-ifdef(p_regexp).
-spec p_regexp(binary()) -> parse_fun().
p_regexp(Regexp) ->
{ok, RE} = re:compile(Regexp, [unicode, dotall, anchored]),
fun(Inp, Index) ->
case re:run(Inp, RE) of
{match, [{0, Length}|_]} ->
{Head, Tail} = erlang:split_binary(Inp, Length),
{Head, Tail, p_advance_index(Head, Index)};
_ -> {fail, {expected, {regexp, binary_to_list(Regexp)}, Index}}
end
end.
-endif.
-ifdef(line).
-spec line(index() | term()) -> pos_integer() | undefined.
line({{line,L},_}) -> L;
line(_) -> undefined.
-endif.
-ifdef(column).
-spec column(index() | term()) -> pos_integer() | undefined.
column({_,{column,C}}) -> C;
column(_) -> undefined.
-endif.
-spec p_advance_index(input() | unicode:charlist() | pos_integer(), index()) -> index().
lists:foldl(fun p_advance_index/2, Index, unicode:characters_to_list(MatchedInput));
{{line, Line}, {column, Col}} = Index,
case MatchedInput of
$\n -> {{line, Line+1}, {column, 1}};
_ -> {{line, Line}, {column, Col+1}}
end.
|
c92d94fc108c9e330723ea4c85a892a6444a6f049b4e8fbc1a453929a8ac41e6 | karlhof26/gimp-scheme | line-nova-gt.scm | ;;; line-nova-gt.scm for gimp-2.x -*-scheme-*-
Time - stamp : < 1998/11/25 13:26:44 >
Author < >
;;; Version 0.8 - Updated By GnuTux - 10-2014 -
Version 0.9 - Updated By Graechan 10 - 2014 - Path Select
Version 0.91 - Updated By Graechan 10 - 2014 - Gradient Nova
Version 0.92 - Updated By Graechan 10 - 2014 - Bug Fix
Version 0.93 - Updated by karlhof26 01 - 03 - 2020 - Fixed for Gimp 2.10.18
; line-nova-gt.scm
version 2.10.18 [ gimphelp.org ]
modified / tested by Graechan
10/2014 on GIMP-2.8.10
last modified / tested by karlhof26
; 01/03/2020 on GIMP-2.10.18
;
;==============================================================
;
; Installation:
; This script should be placed in the user or system-wide script folder.
;
; Windows Vista/7/8)
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
; or
C:\Users\YOUR - NAME\.gimp-2.8\scripts
;
Windows XP
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
; or
; C:\Documents and Settings\yourname\.gimp-2.8\scripts
;
; Linux
/home / yourname/.gimp-2.8 / scripts
; or
; Linux system-wide
; /usr/share/gimp/2.0/scripts
;
;==============================================================
;
; LICENSE
;
; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
; (at your option) any later version.
;
; This program is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
You should have received a copy of the GNU General Public License
; along with this program. If not, see </>.
;
;==============================================================
; Original information
; - Changelog -
version 0.1 2001/04/15 iccii < >
; - Initial relased
version 0.1a 2001/07/20 iccii < >
; - more simple
version 0.1b Receved as completely broken , doing just gausian blur . Fixed to
; do something that may have been the authors intent.
;==============================================================
(define (script-fu-line-nova-gt img lyr fill-type nova-color nova-gradient num-of-lines corn-deg offset variation feather invert ellipse)
(gimp-image-undo-group-start img) ;Graechan
(let* (
(copylyr 0)
(layer 0)
(inVectors 0) ;find the active path
(num-strokes 0) ;get the number of strokes
(stroke-list 0)
(stroke-id 0) ;get the stroke id
(num-points 0)
(control-points 0)
(anchor-point1x 0)
(anchor-point1y 0)
(anchor-point2x 0)
(anchor-point2y 0)
(co-ordCounter 0) ;prepare the co-ordinate counter for anchor-point routines
(f1 FALSE)
(lenx 0)
(leny 0)
(drw 0)
(saved-selection (car (gimp-selection-save img)))
(clearance-selection 0)
(layer-name 0)
)
(set! copylyr (car (gimp-layer-copy lyr TRUE)))
(gimp-image-insert-layer img copylyr 0 (+ (car (gimp-image-get-layer-position img lyr)) 1))
(set! layer copylyr)
(gimp-layer-resize-to-image-size lyr)
(if (not (= (car (gimp-image-get-active-vectors img)) -1))
(begin
(set! f1 TRUE)
(set! layer lyr)
(set! inVectors (car (gimp-image-get-active-vectors img))) ;find the active path
(set! num-strokes (car (gimp-vectors-get-strokes inVectors))) ;get the number of strokes
(set! stroke-list (vector->list (cadr (gimp-vectors-get-strokes inVectors))))
(set! stroke-id (car stroke-list)) ;get the stroke id
(set! num-points (cadr (gimp-vectors-stroke-get-points inVectors stroke-id)))
(set! control-points (vector->list (caddr (gimp-vectors-stroke-get-points inVectors stroke-id))))
(set! co-ordCounter 2)
(while (> co-ordCounter 0)
(set! anchor-point1x (car control-points))
(set! control-points (cdr control-points))
(set! anchor-point1y (car control-points))
(set! control-points (cdr control-points))
(set! co-ordCounter (- co-ordCounter 1))
)
(set! control-points (vector->list (caddr (gimp-vectors-stroke-get-points inVectors stroke-id))))
(set! co-ordCounter 5)
(while (> co-ordCounter 0)
(set! anchor-point2x (car control-points))
(set! control-points (cdr control-points))
(set! anchor-point2y (car control-points))
(set! control-points (cdr control-points))
(set! co-ordCounter (- co-ordCounter 1))
)
(set! control-points (vector->list (caddr (gimp-vectors-stroke-get-points inVectors stroke-id))))
(set! lenx (- (max anchor-point1x anchor-point2x) (min anchor-point1x anchor-point2x)))
(set! leny (- (max anchor-point1y anchor-point2y) (min anchor-point1y anchor-point2y)))
(set! offset (max lenx leny))
)
)
(set! drw (car (gimp-layer-new img (car (gimp-drawable-width layer)) (car (gimp-drawable-height layer)) (car (gimp-drawable-type-with-alpha lyr)) "Line Nova" 100 NORMAL-MODE))) ;Graechan
(gimp-image-insert-layer img drw 0 (+ (car (gimp-image-get-layer-position img lyr)) 0))
(gimp-layer-set-offsets drw (car (gimp-drawable-offsets layer)) (cadr (gimp-drawable-offsets layer))) ;Graechan
(if (= f1 FALSE)
(set! anchor-point1x (/ (car (gimp-drawable-width drw)) 2))
) ;Graechan
(if (= f1 FALSE) (set! anchor-point1y (/ (car (gimp-drawable-height drw)) 2))) ;Graechan
(gimp-layer-translate drw (- anchor-point1x (/ (car (gimp-drawable-width drw)) 2)) (- anchor-point1y (/ (car (gimp-drawable-height drw)) 2))) ;Graechan
( gimp - message " line 143 " )
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE
(car (gimp-drawable-offsets copylyr)) ;x
(cadr (gimp-drawable-offsets copylyr)) ;y
(car (gimp-drawable-width copylyr)) ;width
(car (gimp-drawable-height copylyr)) ;height
2 ; operation
;TRUE ;antialias
;TRUE ;feather
;feather
) ;feather-radius
(gimp-selection-invert img)
(set! clearance-selection (car (gimp-selection-save img)))
(gimp-selection-none img)
( gimp - message " line 158 " )
(gimp-selection-load saved-selection)
(gimp-image-remove-channel img saved-selection)
(let* (
(*points* (cons-array (* 3 2) 'double))
in R4RS way
(pi/2 (/ *pi* 2))
(pi/4 (/ *pi* 4))
(pi3/4 (* 3 pi/4))
(pi5/4 (* 5 pi/4))
(pi3/2 (* 3 pi/2))
(pi7/4 (* 7 pi/4))
(2pi (* 2 *pi*))
(rad/deg (/ 2pi 360))
(variation/2 (/ variation 2))
(drw-width (car (gimp-drawable-width drw)))
(drw-height (car (gimp-drawable-height drw)))
(drw-offsets (gimp-drawable-offsets drw))
(old-selection 0)
(f2 FALSE)
(radius (max drw-height drw-width))
(index 0)
(dir-deg/line (/ 360 num-of-lines))
)
(gimp-context-push)
(gimp-context-set-foreground nova-color)
(gimp-context-set-gradient nova-gradient)
(gimp-layer-resize-to-image-size drw) ;Graechan
( gimp - message " line 188 " )
(define (draw-vector beg-x beg-y direction)
(define (set-point! index x y)
(aset *points* (* 2 index) x)
(aset *points* (+ (* 2 index) 1) y)
)
(define (deg->rad rad)
(* (modulo rad 360) rad/deg)
)
(define (set-marginal-point beg-x beg-y direction)
(let (
(dir1 (deg->rad (+ direction corn-deg)))
(dir2 (deg->rad (- direction corn-deg)))
)
( gimp - message " line 204 " )
(define (aux dir index)
(set-point! index
(+ beg-x (* (cos dir) radius))
(+ beg-y (* (sin dir) radius)))
)
(aux dir1 1)
(aux dir2 2)
)
)
(let (
(dir0 (deg->rad direction))
(off (+ offset (- (modulo (rand) variation) variation/2)))
)
( gimp - message " line 221 " )
(set-point! 0
(+ beg-x (* off (cos dir0)))
(+ beg-y (* off (sin dir0)))
)
(set-marginal-point beg-x beg-y direction)
(gimp-image-select-polygon img CHANNEL-OP-ADD 6 *points*)
)
)
( gimp - message " line 233 " )
(if (= (car (gimp-selection-is-empty img)) FALSE)
(begin
(set! old-selection (car (gimp-selection-save img)))
(set! f2 TRUE)
)
)
(gimp-selection-none img)
(srand (realtime))
(while (< index num-of-lines)
(draw-vector (+ (nth 0 drw-offsets) (/ drw-width 2))
(+ (nth 1 drw-offsets) (/ drw-height 2))
(* index dir-deg/line)
)
(set! index (+ index 1))
)
( gimp - message " line 251 " )
(if (= invert FALSE)
(gimp-selection-invert img)
)
(gimp-edit-bucket-fill drw 0 0 100 0 FALSE 0 0)
(if (= fill-type 1)
(begin
(let* (
(x1 anchor-point1x)
(y1 anchor-point1y)
(x2 0)
(y2 0)
)
(set! x2 (cond ((> anchor-point1x (- (car (gimp-drawable-width layer)) anchor-point1x))
(car (gimp-drawable-offsets layer)))
(else
(car (gimp-drawable-width layer)))
)
)
(set! y2 (cond ((> anchor-point1y (- (car (gimp-drawable-height layer)) anchor-point1y))
(cadr (gimp-drawable-offsets layer)))
(else (car (gimp-drawable-height layer)))))
(gimp-edit-blend drw BLEND-CUSTOM LAYER-MODE-NORMAL GRADIENT-RADIAL 100 0 REPEAT-NONE FALSE
FALSE 3 0.2 TRUE x1 y1 x2 y2)
) ;end gradient fill
)
) ;endif
(gimp-image-select-rectangle img CHANNEL-OP-REPLACE
(car (gimp-drawable-offsets copylyr))
(cadr (gimp-drawable-offsets copylyr))
(car (gimp-drawable-width copylyr)) ;width
(car (gimp-drawable-height copylyr)) ;height
2 ; operation { CHANNEL - OP - ADD ( 0 ) , CHANNEL - OP - SUBTRACT ( 1 ) , CHANNEL - OP - REPLACE ( 2 ) , CHANNEL - OP - INTERSECT ( 3 ) }
;FALSE ;feather
0
)
(let ((pasted 0))
(gimp-edit-cut drw)
(gimp-image-remove-layer img drw)
(set! drw (car (gimp-layer-new img (car (gimp-drawable-width copylyr)) (car (gimp-drawable-height copylyr)) (car (gimp-drawable-type-with-alpha lyr)) "Line Nova" 100 NORMAL-MODE))) ;Graechan
(gimp-image-insert-layer img drw 0 -1) ;Graechan
(gimp-layer-set-offsets drw (car (gimp-drawable-offsets copylyr)) (cadr (gimp-drawable-offsets copylyr))) ;Graechan
(set! pasted (car (gimp-edit-paste drw FALSE)))
(gimp-floating-sel-anchor pasted)
)
(set! layer-name (car (gimp-drawable-get-name lyr)))
(set! lyr (car (gimp-image-merge-down img lyr CLIP-TO-BOTTOM-LAYER)))
(gimp-drawable-set-name lyr layer-name)
(gimp-image-set-active-layer img drw)
(if (or (= ellipse TRUE) (= f1 TRUE))
(begin
(gimp-selection-load clearance-selection)
(gimp-edit-clear drw)
)
)
(gimp-image-remove-channel img clearance-selection)
(gimp-selection-none img)
(if (= f2 TRUE)
(begin
(gimp-image-select-item img CHANNEL-OP-REPLACE old-selection)
(gimp-image-remove-channel img old-selection)
)
)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
(gimp-context-pop)
) ;end script variables
); end path variables
) ;end procedure
(script-fu-register "script-fu-line-nova-gt"
"Line Nova GT..."
"Fill a layer with rays emanating outward from its center using selected color. \nfile:line-nova-gt.scm"
"Shuji Narazaki <>"
"Shuji Narazaki - GnuTux - Graechan - karlhof26"
"1997,1998,2014,2020"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-OPTION "Nova Fill Type" '("Color" "Gradient")
SF-COLOR "Nova Color" '(255 231 72)
SF-GRADIENT "Nova Gradient" "Abstract 3"
SF-ADJUSTMENT "Number of lines" '(90 10 1000 1 1 0 1)
SF-ADJUSTMENT "Sharpness (gaps between)" '(1.0 0.0 10.0 0.1 1 1 1)
SF-ADJUSTMENT "Inner radius Offset" '(40 0 2000 1 1 0 1)
SF-ADJUSTMENT "Randomness" '(30 1 2000 1 1 0 1)
SF-ADJUSTMENT "Ellipse Feather Value" '(15 0 30 1 5 0 1)
SF-TOGGLE "Invert Nova" FALSE
SF-TOGGLE "Ellipse Default:(only if path = null)" FALSE
)
(script-fu-menu-register "script-fu-line-nova-gt"
"<Image>/Script-Fu2/Render")
;end of script | null | https://raw.githubusercontent.com/karlhof26/gimp-scheme/d9c23328ae9e965d1a0d59e20166d22a3ccf5872/line-nova-gt.scm | scheme | line-nova-gt.scm for gimp-2.x -*-scheme-*-
Version 0.8 - Updated By GnuTux - 10-2014 -
line-nova-gt.scm
01/03/2020 on GIMP-2.10.18
==============================================================
Installation:
This script should be placed in the user or system-wide script folder.
Windows Vista/7/8)
or
or
C:\Documents and Settings\yourname\.gimp-2.8\scripts
Linux
or
Linux system-wide
/usr/share/gimp/2.0/scripts
==============================================================
LICENSE
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
==============================================================
Original information
- Changelog -
- Initial relased
- more simple
do something that may have been the authors intent.
==============================================================
Graechan
find the active path
get the number of strokes
get the stroke id
prepare the co-ordinate counter for anchor-point routines
find the active path
get the number of strokes
get the stroke id
Graechan
Graechan
Graechan
Graechan
Graechan
x
y
width
height
operation
TRUE ;antialias
TRUE ;feather
feather
feather-radius
Graechan
end gradient fill
endif
width
height
operation { CHANNEL - OP - ADD ( 0 ) , CHANNEL - OP - SUBTRACT ( 1 ) , CHANNEL - OP - REPLACE ( 2 ) , CHANNEL - OP - INTERSECT ( 3 ) }
FALSE ;feather
Graechan
Graechan
Graechan
end script variables
end path variables
end procedure
end of script | Time - stamp : < 1998/11/25 13:26:44 >
Author < >
Version 0.9 - Updated By Graechan 10 - 2014 - Path Select
Version 0.91 - Updated By Graechan 10 - 2014 - Gradient Nova
Version 0.92 - Updated By Graechan 10 - 2014 - Bug Fix
Version 0.93 - Updated by karlhof26 01 - 03 - 2020 - Fixed for Gimp 2.10.18
version 2.10.18 [ gimphelp.org ]
modified / tested by Graechan
10/2014 on GIMP-2.8.10
last modified / tested by karlhof26
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
C:\Users\YOUR - NAME\.gimp-2.8\scripts
Windows XP
C:\Program Files\GIMP 2\share\gimp\2.0\scripts
/home / yourname/.gimp-2.8 / scripts
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
version 0.1 2001/04/15 iccii < >
version 0.1a 2001/07/20 iccii < >
version 0.1b Receved as completely broken , doing just gausian blur . Fixed to
(define (script-fu-line-nova-gt img lyr fill-type nova-color nova-gradient num-of-lines corn-deg offset variation feather invert ellipse)
(let* (
(copylyr 0)
(layer 0)
(stroke-list 0)
(num-points 0)
(control-points 0)
(anchor-point1x 0)
(anchor-point1y 0)
(anchor-point2x 0)
(anchor-point2y 0)
(f1 FALSE)
(lenx 0)
(leny 0)
(drw 0)
(saved-selection (car (gimp-selection-save img)))
(clearance-selection 0)
(layer-name 0)
)
(set! copylyr (car (gimp-layer-copy lyr TRUE)))
(gimp-image-insert-layer img copylyr 0 (+ (car (gimp-image-get-layer-position img lyr)) 1))
(set! layer copylyr)
(gimp-layer-resize-to-image-size lyr)
(if (not (= (car (gimp-image-get-active-vectors img)) -1))
(begin
(set! f1 TRUE)
(set! layer lyr)
(set! stroke-list (vector->list (cadr (gimp-vectors-get-strokes inVectors))))
(set! num-points (cadr (gimp-vectors-stroke-get-points inVectors stroke-id)))
(set! control-points (vector->list (caddr (gimp-vectors-stroke-get-points inVectors stroke-id))))
(set! co-ordCounter 2)
(while (> co-ordCounter 0)
(set! anchor-point1x (car control-points))
(set! control-points (cdr control-points))
(set! anchor-point1y (car control-points))
(set! control-points (cdr control-points))
(set! co-ordCounter (- co-ordCounter 1))
)
(set! control-points (vector->list (caddr (gimp-vectors-stroke-get-points inVectors stroke-id))))
(set! co-ordCounter 5)
(while (> co-ordCounter 0)
(set! anchor-point2x (car control-points))
(set! control-points (cdr control-points))
(set! anchor-point2y (car control-points))
(set! control-points (cdr control-points))
(set! co-ordCounter (- co-ordCounter 1))
)
(set! control-points (vector->list (caddr (gimp-vectors-stroke-get-points inVectors stroke-id))))
(set! lenx (- (max anchor-point1x anchor-point2x) (min anchor-point1x anchor-point2x)))
(set! leny (- (max anchor-point1y anchor-point2y) (min anchor-point1y anchor-point2y)))
(set! offset (max lenx leny))
)
)
(gimp-image-insert-layer img drw 0 (+ (car (gimp-image-get-layer-position img lyr)) 0))
(if (= f1 FALSE)
(set! anchor-point1x (/ (car (gimp-drawable-width drw)) 2))
( gimp - message " line 143 " )
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE
(gimp-selection-invert img)
(set! clearance-selection (car (gimp-selection-save img)))
(gimp-selection-none img)
( gimp - message " line 158 " )
(gimp-selection-load saved-selection)
(gimp-image-remove-channel img saved-selection)
(let* (
(*points* (cons-array (* 3 2) 'double))
in R4RS way
(pi/2 (/ *pi* 2))
(pi/4 (/ *pi* 4))
(pi3/4 (* 3 pi/4))
(pi5/4 (* 5 pi/4))
(pi3/2 (* 3 pi/2))
(pi7/4 (* 7 pi/4))
(2pi (* 2 *pi*))
(rad/deg (/ 2pi 360))
(variation/2 (/ variation 2))
(drw-width (car (gimp-drawable-width drw)))
(drw-height (car (gimp-drawable-height drw)))
(drw-offsets (gimp-drawable-offsets drw))
(old-selection 0)
(f2 FALSE)
(radius (max drw-height drw-width))
(index 0)
(dir-deg/line (/ 360 num-of-lines))
)
(gimp-context-push)
(gimp-context-set-foreground nova-color)
(gimp-context-set-gradient nova-gradient)
( gimp - message " line 188 " )
(define (draw-vector beg-x beg-y direction)
(define (set-point! index x y)
(aset *points* (* 2 index) x)
(aset *points* (+ (* 2 index) 1) y)
)
(define (deg->rad rad)
(* (modulo rad 360) rad/deg)
)
(define (set-marginal-point beg-x beg-y direction)
(let (
(dir1 (deg->rad (+ direction corn-deg)))
(dir2 (deg->rad (- direction corn-deg)))
)
( gimp - message " line 204 " )
(define (aux dir index)
(set-point! index
(+ beg-x (* (cos dir) radius))
(+ beg-y (* (sin dir) radius)))
)
(aux dir1 1)
(aux dir2 2)
)
)
(let (
(dir0 (deg->rad direction))
(off (+ offset (- (modulo (rand) variation) variation/2)))
)
( gimp - message " line 221 " )
(set-point! 0
(+ beg-x (* off (cos dir0)))
(+ beg-y (* off (sin dir0)))
)
(set-marginal-point beg-x beg-y direction)
(gimp-image-select-polygon img CHANNEL-OP-ADD 6 *points*)
)
)
( gimp - message " line 233 " )
(if (= (car (gimp-selection-is-empty img)) FALSE)
(begin
(set! old-selection (car (gimp-selection-save img)))
(set! f2 TRUE)
)
)
(gimp-selection-none img)
(srand (realtime))
(while (< index num-of-lines)
(draw-vector (+ (nth 0 drw-offsets) (/ drw-width 2))
(+ (nth 1 drw-offsets) (/ drw-height 2))
(* index dir-deg/line)
)
(set! index (+ index 1))
)
( gimp - message " line 251 " )
(if (= invert FALSE)
(gimp-selection-invert img)
)
(gimp-edit-bucket-fill drw 0 0 100 0 FALSE 0 0)
(if (= fill-type 1)
(begin
(let* (
(x1 anchor-point1x)
(y1 anchor-point1y)
(x2 0)
(y2 0)
)
(set! x2 (cond ((> anchor-point1x (- (car (gimp-drawable-width layer)) anchor-point1x))
(car (gimp-drawable-offsets layer)))
(else
(car (gimp-drawable-width layer)))
)
)
(set! y2 (cond ((> anchor-point1y (- (car (gimp-drawable-height layer)) anchor-point1y))
(cadr (gimp-drawable-offsets layer)))
(else (car (gimp-drawable-height layer)))))
(gimp-edit-blend drw BLEND-CUSTOM LAYER-MODE-NORMAL GRADIENT-RADIAL 100 0 REPEAT-NONE FALSE
FALSE 3 0.2 TRUE x1 y1 x2 y2)
)
(gimp-image-select-rectangle img CHANNEL-OP-REPLACE
(car (gimp-drawable-offsets copylyr))
(cadr (gimp-drawable-offsets copylyr))
0
)
(let ((pasted 0))
(gimp-edit-cut drw)
(gimp-image-remove-layer img drw)
(set! pasted (car (gimp-edit-paste drw FALSE)))
(gimp-floating-sel-anchor pasted)
)
(set! layer-name (car (gimp-drawable-get-name lyr)))
(set! lyr (car (gimp-image-merge-down img lyr CLIP-TO-BOTTOM-LAYER)))
(gimp-drawable-set-name lyr layer-name)
(gimp-image-set-active-layer img drw)
(if (or (= ellipse TRUE) (= f1 TRUE))
(begin
(gimp-selection-load clearance-selection)
(gimp-edit-clear drw)
)
)
(gimp-image-remove-channel img clearance-selection)
(gimp-selection-none img)
(if (= f2 TRUE)
(begin
(gimp-image-select-item img CHANNEL-OP-REPLACE old-selection)
(gimp-image-remove-channel img old-selection)
)
)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
(gimp-context-pop)
(script-fu-register "script-fu-line-nova-gt"
"Line Nova GT..."
"Fill a layer with rays emanating outward from its center using selected color. \nfile:line-nova-gt.scm"
"Shuji Narazaki <>"
"Shuji Narazaki - GnuTux - Graechan - karlhof26"
"1997,1998,2014,2020"
"*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-OPTION "Nova Fill Type" '("Color" "Gradient")
SF-COLOR "Nova Color" '(255 231 72)
SF-GRADIENT "Nova Gradient" "Abstract 3"
SF-ADJUSTMENT "Number of lines" '(90 10 1000 1 1 0 1)
SF-ADJUSTMENT "Sharpness (gaps between)" '(1.0 0.0 10.0 0.1 1 1 1)
SF-ADJUSTMENT "Inner radius Offset" '(40 0 2000 1 1 0 1)
SF-ADJUSTMENT "Randomness" '(30 1 2000 1 1 0 1)
SF-ADJUSTMENT "Ellipse Feather Value" '(15 0 30 1 5 0 1)
SF-TOGGLE "Invert Nova" FALSE
SF-TOGGLE "Ellipse Default:(only if path = null)" FALSE
)
(script-fu-menu-register "script-fu-line-nova-gt"
"<Image>/Script-Fu2/Render")
|
9fb370008157eee775aeead34ff7e12b1875c16f84ab08b9d8ff90745ced7ed4 | ygmpkk/house | ReceiverEvent.hs | module ReceiverEvent where
-- ********************************************************************************
Clean to Haskell Standard Object I / O library , version 1.2
--
-- ReceiverEvent defines the DeviceEventFunction for the receiver device.
-- This function is placed in a separate module because it is platform dependent.
-- ********************************************************************************
import DeviceEvents
import IOState
import OSEvent
{- receiverEvent filters the appropriate events for the receiver device.
These are only the message events (as long as receivers do not contain timers).
receiverEvent assumes that it is not applied to an empty IOSt.
Currently, in this implementation only asynchronous message events are supported.
-}
receiverEvent :: IOSt ps -> SchedulerEvent -> IO (Bool,Maybe DeviceEvent,SchedulerEvent)
receiverEvent ioState schedulerEvent@(ScheduleMsgEvent recLoc)
| ioStGetIOId ioState == rlIOId recLoc && ReceiverDevice==rlDevice recLoc
= return (True,Just (ReceiverEvent recLoc),schedulerEvent)
| otherwise
= return (False,Nothing,schedulerEvent)
receiverEvent ioState schedulerEvent = return (False,Nothing,schedulerEvent)
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/hslibs/object-io/OSWindows/ReceiverEvent.hs | haskell | ********************************************************************************
ReceiverEvent defines the DeviceEventFunction for the receiver device.
This function is placed in a separate module because it is platform dependent.
********************************************************************************
receiverEvent filters the appropriate events for the receiver device.
These are only the message events (as long as receivers do not contain timers).
receiverEvent assumes that it is not applied to an empty IOSt.
Currently, in this implementation only asynchronous message events are supported.
| module ReceiverEvent where
Clean to Haskell Standard Object I / O library , version 1.2
import DeviceEvents
import IOState
import OSEvent
receiverEvent :: IOSt ps -> SchedulerEvent -> IO (Bool,Maybe DeviceEvent,SchedulerEvent)
receiverEvent ioState schedulerEvent@(ScheduleMsgEvent recLoc)
| ioStGetIOId ioState == rlIOId recLoc && ReceiverDevice==rlDevice recLoc
= return (True,Just (ReceiverEvent recLoc),schedulerEvent)
| otherwise
= return (False,Nothing,schedulerEvent)
receiverEvent ioState schedulerEvent = return (False,Nothing,schedulerEvent)
|
00f5dd52eadba1c744675ff681873825b2c7366083886fad56a7c1757a08820c | ahrefs/devkit | files.mli | (** File system *)
val enum_dir : Unix.dir_handle -> string Enum.t
val with_readdir : string -> (Unix.dir_handle -> 'a) -> 'a
* [ f fd path rel ] gets invoked for each file under [ ] where
[ fd ] is a read - only [ Unix.file_descr ] , [ path ] is full path and [ rel ] - path relative to [ dirname ]
[fd] is a read-only [Unix.file_descr], [path] is full path and [rel] - path relative to [dirname] *)
val iter_names : string -> (Unix.file_descr -> string -> string -> unit) -> unit
* [ ( fun [ path ] [ rel ] - > ... ) ]
val iter_names_q : string -> (string -> string -> unit) -> unit
(** [iter_files dirname (fun [path] [ic] -> ...)] *)
val iter_files : string -> (string -> in_channel -> unit) -> unit
val open_out_append_bin : string -> out_channel
val open_out_append_text : string -> out_channel
(** [save_as filename ?mode f] is similar to
[Control.with_open_file_bin] except that writing is done to a
temporary file that will be renamed to [filename] after [f] has
succesfully terminated. Therefore this guarantee that either
[filename] will not be modified or will contain whatever [f] was
writing to it as a side-effect.
FIXME windows *)
val save_as : string -> ?mode:Unix.file_perm -> (out_channel -> unit) -> unit
| null | https://raw.githubusercontent.com/ahrefs/devkit/559c2df8f6eacb091e0eac38f508c45b6567bdd8/files.mli | ocaml | * File system
* [iter_files dirname (fun [path] [ic] -> ...)]
* [save_as filename ?mode f] is similar to
[Control.with_open_file_bin] except that writing is done to a
temporary file that will be renamed to [filename] after [f] has
succesfully terminated. Therefore this guarantee that either
[filename] will not be modified or will contain whatever [f] was
writing to it as a side-effect.
FIXME windows |
val enum_dir : Unix.dir_handle -> string Enum.t
val with_readdir : string -> (Unix.dir_handle -> 'a) -> 'a
* [ f fd path rel ] gets invoked for each file under [ ] where
[ fd ] is a read - only [ Unix.file_descr ] , [ path ] is full path and [ rel ] - path relative to [ dirname ]
[fd] is a read-only [Unix.file_descr], [path] is full path and [rel] - path relative to [dirname] *)
val iter_names : string -> (Unix.file_descr -> string -> string -> unit) -> unit
* [ ( fun [ path ] [ rel ] - > ... ) ]
val iter_names_q : string -> (string -> string -> unit) -> unit
val iter_files : string -> (string -> in_channel -> unit) -> unit
val open_out_append_bin : string -> out_channel
val open_out_append_text : string -> out_channel
val save_as : string -> ?mode:Unix.file_perm -> (out_channel -> unit) -> unit
|
5826fb1845120150c46b1c02222e672b636515a6559345608546ecf381fce314 | sky-big/RabbitMQ | rabbit_federation_exchange.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ Federation .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
%%
TODO rename this
-module(rabbit_federation_exchange).
-rabbit_boot_step({?MODULE,
[{description, "federation exchange decorator"},
{mfa, {rabbit_exchange_decorator, register,
[<<"federation">>, ?MODULE]}},
{requires, rabbit_registry},
{cleanup, {rabbit_exchange_decorator, unregister,
[<<"federation">>]}},
{enables, recovery}]}).
-include("amqp_client.hrl").
-behaviour(rabbit_exchange_decorator).
-export([description/0, serialise_events/1]).
-export([create/2, delete/3, policy_changed/2,
add_binding/3, remove_bindings/3, route/2, active_for/1]).
%%----------------------------------------------------------------------------
description() ->
[{description, <<"Federation exchange decorator">>}].
serialise_events(X) -> federate(X).
create(transaction, _X) ->
ok;
create(none, X) ->
maybe_start(X).
delete(transaction, _X, _Bs) ->
ok;
delete(none, X, _Bs) ->
maybe_stop(X).
policy_changed(OldX, NewX) ->
maybe_stop(OldX),
maybe_start(NewX).
add_binding(transaction, _X, _B) ->
ok;
add_binding(Serial, X = #exchange{name = XName}, B) ->
case federate(X) of
true -> rabbit_federation_exchange_link:add_binding(Serial, XName, B),
ok;
false -> ok
end.
remove_bindings(transaction, _X, _Bs) ->
ok;
remove_bindings(Serial, X = #exchange{name = XName}, Bs) ->
case federate(X) of
true -> rabbit_federation_exchange_link:remove_bindings(Serial, XName, Bs),
ok;
false -> ok
end.
route(_, _) -> [].
active_for(X) ->
case federate(X) of
true -> noroute;
false -> none
end.
%%----------------------------------------------------------------------------
%% Don't federate default exchange, we can't bind to it
federate(#exchange{name = #resource{name = <<"">>}}) ->
false;
%% Don't federate any of our intermediate exchanges. Note that we use
%% internal=true since older brokers may not declare
%% x-federation-upstream on us. Also other internal exchanges should
%% probably not be federated.
federate(#exchange{internal = true}) ->
false;
federate(X) ->
rabbit_federation_upstream:federate(X).
maybe_start(X = #exchange{name = XName})->
case federate(X) of
true -> ok = rabbit_federation_db:prune_scratch(
XName, rabbit_federation_upstream:for(X)),
ok = rabbit_federation_exchange_link_sup_sup:start_child(X),
ok;
false -> ok
end.
maybe_stop(X = #exchange{name = XName}) ->
case federate(X) of
true -> ok = rabbit_federation_exchange_link_sup_sup:stop_child(X),
rabbit_federation_status:remove_exchange_or_queue(XName);
false -> ok
end.
| null | https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-federation/src/rabbit_federation_exchange.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Don't federate default exchange, we can't bind to it
Don't federate any of our intermediate exchanges. Note that we use
internal=true since older brokers may not declare
x-federation-upstream on us. Also other internal exchanges should
probably not be federated. | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ Federation .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
TODO rename this
-module(rabbit_federation_exchange).
-rabbit_boot_step({?MODULE,
[{description, "federation exchange decorator"},
{mfa, {rabbit_exchange_decorator, register,
[<<"federation">>, ?MODULE]}},
{requires, rabbit_registry},
{cleanup, {rabbit_exchange_decorator, unregister,
[<<"federation">>]}},
{enables, recovery}]}).
-include("amqp_client.hrl").
-behaviour(rabbit_exchange_decorator).
-export([description/0, serialise_events/1]).
-export([create/2, delete/3, policy_changed/2,
add_binding/3, remove_bindings/3, route/2, active_for/1]).
description() ->
[{description, <<"Federation exchange decorator">>}].
serialise_events(X) -> federate(X).
create(transaction, _X) ->
ok;
create(none, X) ->
maybe_start(X).
delete(transaction, _X, _Bs) ->
ok;
delete(none, X, _Bs) ->
maybe_stop(X).
policy_changed(OldX, NewX) ->
maybe_stop(OldX),
maybe_start(NewX).
add_binding(transaction, _X, _B) ->
ok;
add_binding(Serial, X = #exchange{name = XName}, B) ->
case federate(X) of
true -> rabbit_federation_exchange_link:add_binding(Serial, XName, B),
ok;
false -> ok
end.
remove_bindings(transaction, _X, _Bs) ->
ok;
remove_bindings(Serial, X = #exchange{name = XName}, Bs) ->
case federate(X) of
true -> rabbit_federation_exchange_link:remove_bindings(Serial, XName, Bs),
ok;
false -> ok
end.
route(_, _) -> [].
active_for(X) ->
case federate(X) of
true -> noroute;
false -> none
end.
federate(#exchange{name = #resource{name = <<"">>}}) ->
false;
federate(#exchange{internal = true}) ->
false;
federate(X) ->
rabbit_federation_upstream:federate(X).
maybe_start(X = #exchange{name = XName})->
case federate(X) of
true -> ok = rabbit_federation_db:prune_scratch(
XName, rabbit_federation_upstream:for(X)),
ok = rabbit_federation_exchange_link_sup_sup:start_child(X),
ok;
false -> ok
end.
maybe_stop(X = #exchange{name = XName}) ->
case federate(X) of
true -> ok = rabbit_federation_exchange_link_sup_sup:stop_child(X),
rabbit_federation_status:remove_exchange_or_queue(XName);
false -> ok
end.
|
2d9f65c7dfb6cc89072dee64eeedb6822b2bd2436c81f833572963f83129c8ef | serokell/foundry | KeyCode.hs | # LANGUAGE PatternSynonyms #
{-# OPTIONS -Wno-missing-pattern-synonym-signatures #-}
module Source.Input.KeyCode where
pattern Backspace = 65288
pattern Delete = 65535
pattern Enter = 65293
pattern ArrowLeft = 65361
pattern ArrowRight = 65363
pattern ArrowUp = 65362
pattern ArrowDown = 65364
pattern Escape = 65307
pattern Space = 32
| null | https://raw.githubusercontent.com/serokell/foundry/dd5b9744a88f441559d254f868792956dc552037/src/driver/Source/Input/KeyCode.hs | haskell | # OPTIONS -Wno-missing-pattern-synonym-signatures # | # LANGUAGE PatternSynonyms #
module Source.Input.KeyCode where
pattern Backspace = 65288
pattern Delete = 65535
pattern Enter = 65293
pattern ArrowLeft = 65361
pattern ArrowRight = 65363
pattern ArrowUp = 65362
pattern ArrowDown = 65364
pattern Escape = 65307
pattern Space = 32
|
c9f500415e91d68abe4a994a714cce3678d173564e8299fd44166079bb431051 | whamtet/ctmx | click_to_load.clj | (ns demo.routes.click-to-load
(:require
[ctmx.core :as ctmx :refer [defcomponent make-routes defn-parse]]
[demo.middleware.formats :refer [page]]))
(def src "0123456789ABCDEF")
(defn rand-str []
(clojure.string/join (repeatedly 15 #(rand-nth src))))
(defn tr [i]
[:tr [:td "Agent Smith"] [:td (str "void" i "@null.org")] [:td (rand-str)]])
(defcomponent ^:endpoint rows-click [req ^:int page]
(list
(map tr (range (* 10 page) (* 10 (inc page))))
[:tr {:id id :hx-target "this"}
[:td {:colspan "3"}
[:button.btn
{:hx-get "rows-click"
:hx-vals {:page (inc page)}}
"Load More Agents..."
[:img.htmx-indicator {:src "/img/bars.svg"}]]]]))
(defn routes []
(make-routes
"/click-to-load"
(fn [req]
(page
:outer
[:table
[:thead
[:tr [:th "Name"] [:th "Email"] [:th "ID"]]]
[:tbody (rows-click req 0)]])))) | null | https://raw.githubusercontent.com/whamtet/ctmx/2a73b75d92f189bf4f685afb31beb4e84702f698/demo/src/clj/demo/routes/click_to_load.clj | clojure | (ns demo.routes.click-to-load
(:require
[ctmx.core :as ctmx :refer [defcomponent make-routes defn-parse]]
[demo.middleware.formats :refer [page]]))
(def src "0123456789ABCDEF")
(defn rand-str []
(clojure.string/join (repeatedly 15 #(rand-nth src))))
(defn tr [i]
[:tr [:td "Agent Smith"] [:td (str "void" i "@null.org")] [:td (rand-str)]])
(defcomponent ^:endpoint rows-click [req ^:int page]
(list
(map tr (range (* 10 page) (* 10 (inc page))))
[:tr {:id id :hx-target "this"}
[:td {:colspan "3"}
[:button.btn
{:hx-get "rows-click"
:hx-vals {:page (inc page)}}
"Load More Agents..."
[:img.htmx-indicator {:src "/img/bars.svg"}]]]]))
(defn routes []
(make-routes
"/click-to-load"
(fn [req]
(page
:outer
[:table
[:thead
[:tr [:th "Name"] [:th "Email"] [:th "ID"]]]
[:tbody (rows-click req 0)]])))) | |
91b8fae929f93daddff6923a3ab24c0ab9b7661dcc44d65edb7e96e9da5ccda7 | janestreet/base | blit.mli | * @inline
| null | https://raw.githubusercontent.com/janestreet/base/221b085f3fcd77597f8245b4d73de3970b238e71/src/blit.mli | ocaml | * @inline
| |
105bd675ea6a7c09b209c4940126b38db8518c483266af261ad0073e113b4f07 | reborg/parallel | xf.clj | (ns parallel.xf
(:refer-clojure :exclude [interleave pmap identity]))
(defn interleave
"Transducer version of core/interleave."
[coll]
(fn [rf]
(let [fillers (volatile! (seq coll))]
(fn
([] (rf))
([result] (rf result))
([result input]
(if-let [[filler] @fillers]
(let [step (rf result input)]
(if (reduced? step)
step
(do
(vswap! fillers next)
(rf step filler))))
(reduced result)))))))
(defn pmap
"Like map transducer, but items are processed in chunk of up to 32 items
in parallel. Only effective with computational intensive f. Unlike normal
map/pmap, it does not accept multiple inputs."
[f]
(comp
(partition-all 32)
(fn [rf]
(fn
([] (rf))
([result] (rf result))
([result input] (rf result (clojure.core/pmap f input)))))
cat))
(def identity
"Identity transducer. When multiple inputs are present,
it wraps them in a list similarly to what (map list) transducer
would produce."
(fn [rf]
(fn
([] (rf))
([res] (rf res))
([res in] (rf res in))
([res in & ins] (rf res (list* in ins))))))
| null | https://raw.githubusercontent.com/reborg/parallel/7fde6e48e49455f213c435239c35d31c60e08948/src/parallel/xf.clj | clojure | (ns parallel.xf
(:refer-clojure :exclude [interleave pmap identity]))
(defn interleave
"Transducer version of core/interleave."
[coll]
(fn [rf]
(let [fillers (volatile! (seq coll))]
(fn
([] (rf))
([result] (rf result))
([result input]
(if-let [[filler] @fillers]
(let [step (rf result input)]
(if (reduced? step)
step
(do
(vswap! fillers next)
(rf step filler))))
(reduced result)))))))
(defn pmap
"Like map transducer, but items are processed in chunk of up to 32 items
in parallel. Only effective with computational intensive f. Unlike normal
map/pmap, it does not accept multiple inputs."
[f]
(comp
(partition-all 32)
(fn [rf]
(fn
([] (rf))
([result] (rf result))
([result input] (rf result (clojure.core/pmap f input)))))
cat))
(def identity
"Identity transducer. When multiple inputs are present,
it wraps them in a list similarly to what (map list) transducer
would produce."
(fn [rf]
(fn
([] (rf))
([res] (rf res))
([res in] (rf res in))
([res in & ins] (rf res (list* in ins))))))
| |
3e7e27ac4bbb51b1be09102d930dd7f669aeef5fd9c0267bd59ddb7776e82205 | TrustInSoft/tis-kernel | GuiNavigator.ml | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* 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 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(* --- WP Lower Panel --- *)
(* -------------------------------------------------------------------------- *)
open Design
open Widget
open Property
open GuiSource
(* -------------------------------------------------------------------------- *)
(* --- Build the Reactive Behavior of GUI --- *)
(* -------------------------------------------------------------------------- *)
type filter = [ `All | `Module | `Select ]
type card = [ `List | `Goal ]
type focus =
[ `All
| `Index of Wpo.index
| `Call of GuiSource.call
| `Property of Property.t ]
let index_of_lemma (l,_,_,_,_) =
match LogicUsage.section_of_lemma l with
| LogicUsage.Toplevel _ -> Wpo.IAxiomatic None
| LogicUsage.Axiomatic a -> Wpo.IAxiomatic (Some a.LogicUsage.ax_name)
let focus_of_selection selection filter =
match selection , filter with
| S_none , _ | _ , `All -> `All
| S_call c , `Select -> `Call c
| S_call c , `Module -> `Index (Wpo.IFunction (c.s_caller, None))
| S_fun kf , (`Select | `Module) -> `Index (Wpo.IFunction (kf, None))
| S_prop (IPLemma ilem) , `Module -> `Index (index_of_lemma ilem)
| S_prop (IPAxiomatic (name, _)) , _ -> `Index (Wpo.IAxiomatic (Some name))
| S_prop ip , `Select -> `Property ip
| S_prop ip , `Module ->
begin
match Property.get_kf ip with
| None -> `All
| Some kf -> `Index(Wpo.IFunction (kf, None))
end
exception FIRST of Wpo.t
let first iter =
try iter (fun w -> raise (FIRST w)) ; None
with FIRST w -> Some w
let iter_kf kf f = Wpo.iter ~index:(Wpo.IFunction (kf, None)) ~on_goal:f ()
let iter_ip ip f = Wpo.iter ~ip ~on_goal:f ()
let iter_ips ips f = List.iter (fun ip -> Wpo.iter ~ip ~on_goal:f ()) ips
let calls c = List.map snd (Statuses_by_call.all_call_preconditions_at
~warn_missing:false c.s_caller c.s_stmt)
let goal_of_selection = function
| S_none -> None
| S_prop ip -> first (iter_ip ip)
| S_call c -> first (iter_ips (calls c))
| S_fun kf -> first (iter_kf kf)
class behavior
~(main : Design.main_window_extension_points)
~(filter : filter Widget.selector)
~(next : Widget.button)
~(prev : Widget.button)
~(index : Widget.button)
~(clear : Widget.button)
~(card : card Widget.selector)
~(list : GuiList.pane)
~(goal : GuiGoal.pane)
~(source : GuiSource.highlighter)
~(popup : GuiSource.popup)
=
object(self)
val mutable focus : focus = `All
val mutable currentgoal : Wpo.t option = None
method update () =
begin
list#update_all ;
source#update ;
goal#update ;
end
method reload () =
begin
list#reload ;
let on_goal = list#add in
begin
match focus with
| `All -> Wpo.iter ~on_goal ()
| `Index index -> Wpo.iter ~index ~on_goal ()
| `Property ip -> Wpo.iter ~ip ~on_goal ()
| `Call c -> iter_ips (calls c) on_goal
end ;
let n = list#size in
let k = match currentgoal with
| None -> (-1)
| Some w ->
try list#index w
with Not_found -> (-1)
in
index#set_enabled (n>0) ;
if n=0 then card#set `List ;
let src = if n=1 && k=0 then (card#set `Goal ; true) else false in
if k<0 then self#navigator false None
else self#navigator src (Some (list#get k)) ;
end
method private set_focus f =
focus <- f ; self#reload ()
method private set_filter f =
match f , currentgoal with
| `Module , Some w -> self#set_focus (`Index (Wpo.get_index w))
| `Select , Some w -> self#set_focus (`Property (Wpo.get_property w))
| _ , _ -> self#set_focus `All
method private set_selection s =
let f = filter#get in
currentgoal <- goal_of_selection s ;
self#set_focus (focus_of_selection s f)
(* -------------------------------------------------------------------------- *)
(* --- Navigation from Next/Prev/List --- *)
(* -------------------------------------------------------------------------- *)
method private details =
match card#get , currentgoal with
| `List , Some w -> list#show w
| `List , None -> ()
| `Goal , sw -> goal#select sw
method private navigator src = function
| None ->
begin
currentgoal <- None ;
next#set_enabled false ;
prev#set_enabled false ;
source#set None ;
self#details ;
end
| (Some w) as sw ->
try
currentgoal <- sw ;
let n = list#size in
let k = list#index w in
prev#set_enabled (k > 0) ;
next#set_enabled (succ k < n) ;
source#set (if src then sw else None) ;
self#details ;
with Not_found ->
self#navigator false None
method private next () = self#move succ
method private prev () = self#move pred
method private move dir =
try
match currentgoal with
| None -> ()
| Some w ->
begin
self#navigator true None ;
let k = list#index w in
let w = list#get (dir k) in
self#navigator true (Some w) ;
end
with Not_found ->
self#navigator true None
method private prove ?mode w prover =
begin
let callback w _prover _result =
begin match card#get with
| `List -> list#update w
| `Goal -> goal#update
end
in
if prover = VCS.Why3ide
then
let iter f = Wpo.iter ~on_goal:f () in
let task = ProverWhy3ide.prove ~callback ~iter in
let thread = Task.thread task in
let kill () =
Wpo.set_result w prover VCS.no_result ;
Task.cancel thread ;
in
Wpo.set_result w prover (VCS.computing kill) ;
let server = ProverTask.server () in
Task.spawn server thread ;
Task.launch server ;
else
let open VCS in
let mode = match mode , prover with
| Some m , _ -> m
| None , Coq -> EditMode
| None , AltErgo -> FixMode
| _ -> BatchMode in
let task = Prover.prove w ~mode ~callback prover in
let thread = Task.thread task in
let kill () =
Wpo.set_result w prover VCS.no_result ;
Task.cancel thread in
Wpo.set_result w prover (VCS.computing kill) ;
let server = ProverTask.server () in
Task.spawn server thread ;
Task.launch server ;
end
method private clear () =
begin
let title = "Delete Proof Obligations" in
let text = Printf.sprintf
"Confirm deletion of %d proof obligation(s)" list#count_selected in
let icon = GMisc.image ~stock:`DELETE () in
let response = GToolbox.question_box
~title ~buttons:["Delete POs" ; "Cancel"] ~default:1 ~icon text in
if response = 1 then
begin
list#iter_selected Wpo.remove ;
self#reload () ;
end
end
(* -------------------------------------------------------------------------- *)
(* --- Popup on Goals --- *)
(* -------------------------------------------------------------------------- *)
val popup_qed = new Widget.popup ()
val popup_ergo = new Widget.popup ()
val popup_coq = new Widget.popup ()
val popup_why3 = new Widget.popup ()
val mutable popup_target = None
method private popup_delete () =
match popup_target with
| Some(w,_) -> (popup_target <- None ; Wpo.remove w ; self#reload ())
| None -> ()
method private popup_run mode () =
match popup_target with
| Some(w,Some p) -> (popup_target <- None ; self#prove ~mode w p)
| _ -> popup_target <- None
method private popup_why3ide () =
match popup_target with
| Some(w,_) -> (popup_target <- None ; self#prove w VCS.Why3ide)
| _ -> popup_target <- None
method private popup_proofmodes popup modes =
List.iter
(fun (label,mode) ->
popup#add_item ~label ~callback:(self#popup_run mode))
modes
initializer
let open VCS in
begin
self#popup_proofmodes popup_why3
[ "Run",BatchMode ] ;
self#popup_proofmodes popup_ergo
[ "Run",BatchMode ; "Open Altgr-Ergo on Fail",EditMode ; "Open Altgr-Ergo",EditMode ] ;
self#popup_proofmodes popup_coq
[ "Check Proof",BatchMode ; "Edit on Fail",EditMode ; "Edit Proof",EditMode ] ;
List.iter
(fun menu ->
menu#add_item ~label:"Open Why3ide" ~callback:self#popup_why3ide ;
menu#add_separator ;
menu#add_item ~label:"Delete Goal" ~callback:self#popup_delete ;
) [ popup_qed ; popup_why3 ; popup_ergo ; popup_coq ] ;
end
method private popup w p =
let open VCS in
begin
popup_target <- Some (w,p) ;
match p with
| None
| Some (Qed|Why3ide) -> popup_qed#popup ()
| Some Coq -> popup_coq#popup ()
| Some AltErgo -> popup_ergo#popup ()
| Some (Why3 _) -> popup_why3#popup ()
end
(* -------------------------------------------------------------------------- *)
(* --- Popup on Goals --- *)
(* -------------------------------------------------------------------------- *)
initializer
begin
clear#set_enabled false ;
next#connect self#next ;
prev#connect self#prev ;
index#connect (fun () -> card#set `List) ;
list#on_click (fun w _p -> self#navigator true (Some w)) ;
list#on_right_click
(fun w p ->
begin
self#navigator true (Some w) ;
self#popup w p ;
list#update w ;
end
) ;
list#on_double_click
(fun w p ->
match p with
| None ->
begin
card#set `Goal ;
self#navigator true (Some w) ;
end
| Some p ->
begin
self#navigator true (Some w) ;
self#prove w p ;
list#update w ;
end
) ;
list#on_selection (fun n -> clear#set_enabled (n>0)) ;
goal#on_run self#prove ;
goal#on_src source#set ;
card#connect (fun _ -> self#details) ;
filter#connect self#set_filter ;
popup#on_click self#set_selection ;
popup#on_prove (GuiPanel.run_and_prove main) ;
clear#connect self#clear ;
end
end
(* -------------------------------------------------------------------------- *)
--- Make Panel and Extend Frama - C GUI ---
(* -------------------------------------------------------------------------- *)
let make (main : main_window_extension_points) =
begin
(* -------------------------------------------------------------------------- *)
(* --- Provers --- *)
(* -------------------------------------------------------------------------- *)
let available = new GuiConfig.provers "wp.available" in
let enabled = new GuiConfig.provers "wp.enabled" in
if Wp_parameters.Detect.get () then ProverWhy3.detect_provers available#set ;
let dp_chooser = new GuiConfig.dp_chooser ~main ~available ~enabled in
(* -------------------------------------------------------------------------- *)
--- Focus Bar ---
(* -------------------------------------------------------------------------- *)
let filter = new Widget.group (`All :> filter) in
let switch = new Widget.hbox [
filter#add_toggle ~label:"All" ~tooltip:"All goals" ~value:`All () ;
filter#add_toggle ~label:"Module"
~tooltip:"Goals of current function or axiomatics" ~value:`Module () ;
filter#add_toggle ~label:"Property"
~tooltip:"Goals of current property" ~value:`Select () ;
] in
let prev = new Widget.button ~icon:`GO_BACK ~tooltip:"Previous goal" () in
let next = new Widget.button ~icon:`GO_FORWARD ~tooltip:"Next goal" () in
let index = new Widget.button ~icon:`INDEX ~tooltip:"List of goals" () in
let navigation = new Widget.hbox [
(prev :> widget) ;
(index :> widget) ;
(next :> widget) ;
] in
let provers = new Widget.button ~label:"Provers..." () in
let clear = new Widget.button ~label:"Clear" ~icon:`DELETE () in
let focusbar = GPack.hbox ~spacing:0 () in
begin
focusbar#pack ~padding:0 ~expand:false navigation#coerce ;
focusbar#pack ~padding:20 ~expand:false switch#coerce ;
focusbar#pack ~from:`END ~expand:false clear#coerce ;
focusbar#pack ~from:`END ~expand:false provers#coerce ;
provers#connect dp_chooser#run ;
end ;
(* -------------------------------------------------------------------------- *)
(* --- List/Goal view --- *)
(* -------------------------------------------------------------------------- *)
let book = new Wpane.notebook ~default:`List () in
let list = new GuiList.pane enabled in
let goal = new GuiGoal.pane () in
begin
book#add `List list#coerce ;
book#add `Goal goal#coerce ;
end ;
(* -------------------------------------------------------------------------- *)
(* --- Source Feedback --- *)
(* -------------------------------------------------------------------------- *)
let source = new GuiSource.highlighter main in
let popup = new GuiSource.popup () in
(* -------------------------------------------------------------------------- *)
(* --- Panel Behavior --- *)
(* -------------------------------------------------------------------------- *)
let card = (book :> _ Widget.selector) in
let filter = (filter :> _ Widget.selector) in
let behavior = new behavior ~main
~next ~prev ~index ~filter ~clear
~list ~card ~goal ~source ~popup in
GuiPanel.on_reload behavior#reload ;
GuiPanel.on_update behavior#update ;
(* -------------------------------------------------------------------------- *)
(* --- Panel view --- *)
(* -------------------------------------------------------------------------- *)
let panel = GPack.vbox ~homogeneous:false () in
panel#pack ~expand:false focusbar#coerce ;
panel#pack ~expand:true ~fill:true book#coerce ;
let tab_label = (GMisc.label ~text:"WP Goals" ())#coerce in
ignore (panel#misc#connect#after#realize behavior#reload) ;
ignore (main#lower_notebook#append_page ~tab_label panel#coerce) ;
main#register_source_highlighter source#highlight ;
main#register_source_selector popup#register ;
GuiPanel.register ~main
~available_provers:available
~enabled_provers:enabled
~configure_provers:dp_chooser#run ;
end
let () = Design.register_extension make
let () = Design.register_reset_extension
(fun main -> main#protect ~cancelable:false GuiPanel.reload)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/wp/GuiNavigator.ml | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
--------------------------------------------------------------------------
--- WP Lower Panel ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Build the Reactive Behavior of GUI ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Navigation from Next/Prev/List ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Popup on Goals ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Popup on Goals ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Provers ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- List/Goal view ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Source Feedback ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Panel Behavior ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Panel view ---
-------------------------------------------------------------------------- | This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Design
open Widget
open Property
open GuiSource
type filter = [ `All | `Module | `Select ]
type card = [ `List | `Goal ]
type focus =
[ `All
| `Index of Wpo.index
| `Call of GuiSource.call
| `Property of Property.t ]
let index_of_lemma (l,_,_,_,_) =
match LogicUsage.section_of_lemma l with
| LogicUsage.Toplevel _ -> Wpo.IAxiomatic None
| LogicUsage.Axiomatic a -> Wpo.IAxiomatic (Some a.LogicUsage.ax_name)
let focus_of_selection selection filter =
match selection , filter with
| S_none , _ | _ , `All -> `All
| S_call c , `Select -> `Call c
| S_call c , `Module -> `Index (Wpo.IFunction (c.s_caller, None))
| S_fun kf , (`Select | `Module) -> `Index (Wpo.IFunction (kf, None))
| S_prop (IPLemma ilem) , `Module -> `Index (index_of_lemma ilem)
| S_prop (IPAxiomatic (name, _)) , _ -> `Index (Wpo.IAxiomatic (Some name))
| S_prop ip , `Select -> `Property ip
| S_prop ip , `Module ->
begin
match Property.get_kf ip with
| None -> `All
| Some kf -> `Index(Wpo.IFunction (kf, None))
end
exception FIRST of Wpo.t
let first iter =
try iter (fun w -> raise (FIRST w)) ; None
with FIRST w -> Some w
let iter_kf kf f = Wpo.iter ~index:(Wpo.IFunction (kf, None)) ~on_goal:f ()
let iter_ip ip f = Wpo.iter ~ip ~on_goal:f ()
let iter_ips ips f = List.iter (fun ip -> Wpo.iter ~ip ~on_goal:f ()) ips
let calls c = List.map snd (Statuses_by_call.all_call_preconditions_at
~warn_missing:false c.s_caller c.s_stmt)
let goal_of_selection = function
| S_none -> None
| S_prop ip -> first (iter_ip ip)
| S_call c -> first (iter_ips (calls c))
| S_fun kf -> first (iter_kf kf)
class behavior
~(main : Design.main_window_extension_points)
~(filter : filter Widget.selector)
~(next : Widget.button)
~(prev : Widget.button)
~(index : Widget.button)
~(clear : Widget.button)
~(card : card Widget.selector)
~(list : GuiList.pane)
~(goal : GuiGoal.pane)
~(source : GuiSource.highlighter)
~(popup : GuiSource.popup)
=
object(self)
val mutable focus : focus = `All
val mutable currentgoal : Wpo.t option = None
method update () =
begin
list#update_all ;
source#update ;
goal#update ;
end
method reload () =
begin
list#reload ;
let on_goal = list#add in
begin
match focus with
| `All -> Wpo.iter ~on_goal ()
| `Index index -> Wpo.iter ~index ~on_goal ()
| `Property ip -> Wpo.iter ~ip ~on_goal ()
| `Call c -> iter_ips (calls c) on_goal
end ;
let n = list#size in
let k = match currentgoal with
| None -> (-1)
| Some w ->
try list#index w
with Not_found -> (-1)
in
index#set_enabled (n>0) ;
if n=0 then card#set `List ;
let src = if n=1 && k=0 then (card#set `Goal ; true) else false in
if k<0 then self#navigator false None
else self#navigator src (Some (list#get k)) ;
end
method private set_focus f =
focus <- f ; self#reload ()
method private set_filter f =
match f , currentgoal with
| `Module , Some w -> self#set_focus (`Index (Wpo.get_index w))
| `Select , Some w -> self#set_focus (`Property (Wpo.get_property w))
| _ , _ -> self#set_focus `All
method private set_selection s =
let f = filter#get in
currentgoal <- goal_of_selection s ;
self#set_focus (focus_of_selection s f)
method private details =
match card#get , currentgoal with
| `List , Some w -> list#show w
| `List , None -> ()
| `Goal , sw -> goal#select sw
method private navigator src = function
| None ->
begin
currentgoal <- None ;
next#set_enabled false ;
prev#set_enabled false ;
source#set None ;
self#details ;
end
| (Some w) as sw ->
try
currentgoal <- sw ;
let n = list#size in
let k = list#index w in
prev#set_enabled (k > 0) ;
next#set_enabled (succ k < n) ;
source#set (if src then sw else None) ;
self#details ;
with Not_found ->
self#navigator false None
method private next () = self#move succ
method private prev () = self#move pred
method private move dir =
try
match currentgoal with
| None -> ()
| Some w ->
begin
self#navigator true None ;
let k = list#index w in
let w = list#get (dir k) in
self#navigator true (Some w) ;
end
with Not_found ->
self#navigator true None
method private prove ?mode w prover =
begin
let callback w _prover _result =
begin match card#get with
| `List -> list#update w
| `Goal -> goal#update
end
in
if prover = VCS.Why3ide
then
let iter f = Wpo.iter ~on_goal:f () in
let task = ProverWhy3ide.prove ~callback ~iter in
let thread = Task.thread task in
let kill () =
Wpo.set_result w prover VCS.no_result ;
Task.cancel thread ;
in
Wpo.set_result w prover (VCS.computing kill) ;
let server = ProverTask.server () in
Task.spawn server thread ;
Task.launch server ;
else
let open VCS in
let mode = match mode , prover with
| Some m , _ -> m
| None , Coq -> EditMode
| None , AltErgo -> FixMode
| _ -> BatchMode in
let task = Prover.prove w ~mode ~callback prover in
let thread = Task.thread task in
let kill () =
Wpo.set_result w prover VCS.no_result ;
Task.cancel thread in
Wpo.set_result w prover (VCS.computing kill) ;
let server = ProverTask.server () in
Task.spawn server thread ;
Task.launch server ;
end
method private clear () =
begin
let title = "Delete Proof Obligations" in
let text = Printf.sprintf
"Confirm deletion of %d proof obligation(s)" list#count_selected in
let icon = GMisc.image ~stock:`DELETE () in
let response = GToolbox.question_box
~title ~buttons:["Delete POs" ; "Cancel"] ~default:1 ~icon text in
if response = 1 then
begin
list#iter_selected Wpo.remove ;
self#reload () ;
end
end
val popup_qed = new Widget.popup ()
val popup_ergo = new Widget.popup ()
val popup_coq = new Widget.popup ()
val popup_why3 = new Widget.popup ()
val mutable popup_target = None
method private popup_delete () =
match popup_target with
| Some(w,_) -> (popup_target <- None ; Wpo.remove w ; self#reload ())
| None -> ()
method private popup_run mode () =
match popup_target with
| Some(w,Some p) -> (popup_target <- None ; self#prove ~mode w p)
| _ -> popup_target <- None
method private popup_why3ide () =
match popup_target with
| Some(w,_) -> (popup_target <- None ; self#prove w VCS.Why3ide)
| _ -> popup_target <- None
method private popup_proofmodes popup modes =
List.iter
(fun (label,mode) ->
popup#add_item ~label ~callback:(self#popup_run mode))
modes
initializer
let open VCS in
begin
self#popup_proofmodes popup_why3
[ "Run",BatchMode ] ;
self#popup_proofmodes popup_ergo
[ "Run",BatchMode ; "Open Altgr-Ergo on Fail",EditMode ; "Open Altgr-Ergo",EditMode ] ;
self#popup_proofmodes popup_coq
[ "Check Proof",BatchMode ; "Edit on Fail",EditMode ; "Edit Proof",EditMode ] ;
List.iter
(fun menu ->
menu#add_item ~label:"Open Why3ide" ~callback:self#popup_why3ide ;
menu#add_separator ;
menu#add_item ~label:"Delete Goal" ~callback:self#popup_delete ;
) [ popup_qed ; popup_why3 ; popup_ergo ; popup_coq ] ;
end
method private popup w p =
let open VCS in
begin
popup_target <- Some (w,p) ;
match p with
| None
| Some (Qed|Why3ide) -> popup_qed#popup ()
| Some Coq -> popup_coq#popup ()
| Some AltErgo -> popup_ergo#popup ()
| Some (Why3 _) -> popup_why3#popup ()
end
initializer
begin
clear#set_enabled false ;
next#connect self#next ;
prev#connect self#prev ;
index#connect (fun () -> card#set `List) ;
list#on_click (fun w _p -> self#navigator true (Some w)) ;
list#on_right_click
(fun w p ->
begin
self#navigator true (Some w) ;
self#popup w p ;
list#update w ;
end
) ;
list#on_double_click
(fun w p ->
match p with
| None ->
begin
card#set `Goal ;
self#navigator true (Some w) ;
end
| Some p ->
begin
self#navigator true (Some w) ;
self#prove w p ;
list#update w ;
end
) ;
list#on_selection (fun n -> clear#set_enabled (n>0)) ;
goal#on_run self#prove ;
goal#on_src source#set ;
card#connect (fun _ -> self#details) ;
filter#connect self#set_filter ;
popup#on_click self#set_selection ;
popup#on_prove (GuiPanel.run_and_prove main) ;
clear#connect self#clear ;
end
end
--- Make Panel and Extend Frama - C GUI ---
let make (main : main_window_extension_points) =
begin
let available = new GuiConfig.provers "wp.available" in
let enabled = new GuiConfig.provers "wp.enabled" in
if Wp_parameters.Detect.get () then ProverWhy3.detect_provers available#set ;
let dp_chooser = new GuiConfig.dp_chooser ~main ~available ~enabled in
--- Focus Bar ---
let filter = new Widget.group (`All :> filter) in
let switch = new Widget.hbox [
filter#add_toggle ~label:"All" ~tooltip:"All goals" ~value:`All () ;
filter#add_toggle ~label:"Module"
~tooltip:"Goals of current function or axiomatics" ~value:`Module () ;
filter#add_toggle ~label:"Property"
~tooltip:"Goals of current property" ~value:`Select () ;
] in
let prev = new Widget.button ~icon:`GO_BACK ~tooltip:"Previous goal" () in
let next = new Widget.button ~icon:`GO_FORWARD ~tooltip:"Next goal" () in
let index = new Widget.button ~icon:`INDEX ~tooltip:"List of goals" () in
let navigation = new Widget.hbox [
(prev :> widget) ;
(index :> widget) ;
(next :> widget) ;
] in
let provers = new Widget.button ~label:"Provers..." () in
let clear = new Widget.button ~label:"Clear" ~icon:`DELETE () in
let focusbar = GPack.hbox ~spacing:0 () in
begin
focusbar#pack ~padding:0 ~expand:false navigation#coerce ;
focusbar#pack ~padding:20 ~expand:false switch#coerce ;
focusbar#pack ~from:`END ~expand:false clear#coerce ;
focusbar#pack ~from:`END ~expand:false provers#coerce ;
provers#connect dp_chooser#run ;
end ;
let book = new Wpane.notebook ~default:`List () in
let list = new GuiList.pane enabled in
let goal = new GuiGoal.pane () in
begin
book#add `List list#coerce ;
book#add `Goal goal#coerce ;
end ;
let source = new GuiSource.highlighter main in
let popup = new GuiSource.popup () in
let card = (book :> _ Widget.selector) in
let filter = (filter :> _ Widget.selector) in
let behavior = new behavior ~main
~next ~prev ~index ~filter ~clear
~list ~card ~goal ~source ~popup in
GuiPanel.on_reload behavior#reload ;
GuiPanel.on_update behavior#update ;
let panel = GPack.vbox ~homogeneous:false () in
panel#pack ~expand:false focusbar#coerce ;
panel#pack ~expand:true ~fill:true book#coerce ;
let tab_label = (GMisc.label ~text:"WP Goals" ())#coerce in
ignore (panel#misc#connect#after#realize behavior#reload) ;
ignore (main#lower_notebook#append_page ~tab_label panel#coerce) ;
main#register_source_highlighter source#highlight ;
main#register_source_selector popup#register ;
GuiPanel.register ~main
~available_provers:available
~enabled_provers:enabled
~configure_provers:dp_chooser#run ;
end
let () = Design.register_extension make
let () = Design.register_reset_extension
(fun main -> main#protect ~cancelable:false GuiPanel.reload)
|
aeffdbfede8dce8222c2a6f9fa2ddda42722ee3acfd23df16c16faca16ab138e | ufasoft/lisp | loop.lisp | ;; ANSI CL Loop
( LOOP { loop - clause } * ) , CLtL2 p. 163,709 - 747
;; <-1.html>
;; <>
1991 - 2004
1999 - 2005
(in-package "COMMON-LISP")
(export '(loop loop-finish))
(pushnew ':loop *features*)
(in-package "SYSTEM")
Parser auxiliary functions
;; (loop-keywordp obj) determines whether OBJ is a loop keyword,
and then returns the appropriate unique symbol , otherwise NIL .
(defun loop-keywordp (obj)
(and (symbolp obj)
(gethash (symbol-name obj)
(load-time-value
(make-hash-table
:key-type 'string :value-type 'symbol
:test 'fasthash-equal :warn-if-needs-rehash-after-gc t
:initial-contents
(mapcar #'(lambda (s) (cons (symbol-name s) s))
'(named
for as and from downfrom upfrom to downto upto below
above by in on = then across being each the hash-key
hash-keys hash-value hash-values of using symbol
present-symbol internal-symbol external-symbol symbols
present-symbols internal-symbols external-symbols
repeat
while until always never thereis
collect collecting append appending nconc nconcing
count counting sum summing maximize maximizing
minimize minimizing into
with
if when unless else end it
do doing return
of-type
initially finally)))))))
(defvar *whole*) ; the entire form (LOOP ...)
;; (loop-syntax-error loop-keyword) reports a syntax error.
(defun loop-syntax-error (loop-keyword)
(error-of-type 'source-program-error
:form *whole*
:detail loop-keyword ; FIXME: should be something more useful
(TEXT "~S: syntax error after ~A in ~S")
'loop (symbol-name loop-keyword) *whole*))
;; destructuring:
;; (destructure-vars pattern) returns the list of variables occuring
;; in the pattern.
(defun destructure-vars (pattern)
(let ((vars '()))
(labels ((accumulate (pattern)
(cond ((null pattern))
((atom pattern) (push pattern vars))
(t
(accumulate (car pattern))
(accumulate (cdr pattern))))))
(accumulate pattern))
(nreverse vars)))
;; (empty-tree-p pattern) determine whether the pattern has no variables
;; at all.
(defun empty-tree-p (pattern)
(cond ((null pattern) t)
((atom pattern) nil)
(t (and (empty-tree-p (car pattern))
(empty-tree-p (cdr pattern))))))
;; (destructure-type pattern type) returns the list of declaration
;; specifiers, that declare that each variable in 'pattern' is of the
;; corresponding type in 'type'.
(defun destructure-type (pattern type)
(let ((declspecs '()))
(labels ((accumulate (pattern type)
(cond ((null pattern))
((atom pattern)
(push `(TYPE ,type ,pattern) declspecs))
((consp type)
(accumulate (car pattern) (car type))
(accumulate (cdr pattern) (cdr type)))
(t
(let ((vars (destructure-vars pattern)))
(when vars
(push `(TYPE ,type ,@vars) declspecs)))))))
(accumulate pattern type))
(nreverse declspecs)))
;; (simple-type-p type) determines whether 'type' contains, after
destructuring , only NIL , T , FIXNUM , FLOAT , and therefore can be
;; used without OF-TYPE.
(defun simple-type-p (type)
(if (atom type)
(case type
((NIL T FIXNUM FLOAT) t)
(t nil))
(and (simple-type-p (car type))
(simple-type-p (cdr type)))))
(defvar *helpvars*) ;; vector of auxiliary variables for destructuring
( helpvar n ) returns the ( n+1)-st auxiliary variable ( n>=0 ) .
;; At least n auxiliary variable must already have been used.
(defun helpvar (n)
;; '*helpvars*' is extended if necessary.
(when (= n (fill-pointer *helpvars*))
(vector-push-extend (gensym "PATTERN-") *helpvars*))
(aref *helpvars* n))
;; (destructure pattern form) returns a list of lists (variable_i form_i).
;; variable_i is a variable from 'pattern', form_i is a form, whose
;; result must be bound or assigned to variable_i. The order of the
;; bindings/assignments doesn't matter, i.e. both LET and LET*, or
;; both PSETQ and SETQ are possible.
(defun destructure (pattern form)
(labels ((destructure-tree (pattern form helpvar-count)
helpvar - count =
(cond ((empty-tree-p pattern) nil)
((atom pattern) (list (list pattern form)))
((empty-tree-p (car pattern))
(destructure-tree (cdr pattern) `(CDR ,form) helpvar-count))
((empty-tree-p (cdr pattern))
(destructure-tree (car pattern) `(CAR ,form) helpvar-count))
muss form zwischendurch einer Hilfsvariablen zuweisen
(let ((helpvar (helpvar helpvar-count)))
(nconc (destructure-tree (car pattern) `(CAR (SETQ ,helpvar ,form)) (1+ helpvar-count))
(destructure-tree (cdr pattern) `(CDR ,helpvar) helpvar-count)))))))
(or (destructure-tree pattern form 0)
; no variables -> must nevertheless evaluate form!
(list (list (helpvar 0) form)))))
;; (default-bindings vars declspecs).
;; vars = (var ...) is a list of variables without init forms.
;; Returns the binding list ((var var-init) ...), where var-init is
;; compatible with the declspecs.
(defun default-bindings (vars declspecs)
Use NIL or 0 or 0.0 if it fits the declarations .
Otherwise use NIL and extend the type declarations .
(let ((bindings (mapcar #'(lambda (var) (list var 'NIL)) vars)))
(dolist (declspec declspecs)
(when (eq (first declspec) 'TYPE)
declspec is of form ( TYPE type . vars )
(let* ((type (second declspec))
(dtype (type-for-discrimination type))
h)
(cond ((typep 'NIL dtype)) ; OK
((or (typep (setq h '0) dtype) (typep (setq h '0.0) dtype))
(dolist (var (cddr declspec))
(setf (second (find var bindings :key #'first)) h)))
(t (setf (second declspec) `(OR NULL ,type)))))))
bindings))
;; A loop-initialization describes at macro expansion time the task
to initialise one or more variables . The initialization may end up
;; generating code in the prologue or in the inner loop.
(defstruct (loop-initialization
(:copier nil)
(:conc-name "LI-")
(:predicate nil)
(:constructor make-loop-init))
;; How to generate the Lisp code.
special form : LET or MULTIPLE - VALUE - BIND or PROGN
bindings ; for LET: list of bindings,
for MULTIPLE - VALUE - BIND : varlist and form
declspecs ; list of declspecs
(endtest-forms nil) ; more forms to be inserted after the declarations,
; within the tagbody.
;; Properties of this initialization.
everytime ; If the assignment has to be evaluated in the prologue only: NIL.
; If the assignment has to be evaluated once for each iteration:
; a cons, pointing at the right place in the stepafter-code.
(requires-stepbefore nil) ; True if the variables can get their values only
in the stepbefore - code or preamble ,
false if the first assignment can be merged
; with the initial binding.
(depends-preceding nil) ; True if everytime=NIL and the values may depend
; on preceding variables, so that these preceding
; variables must get their values no later than in
; the preamble (= prologue + startup)
preamble ; cons = location in preamble
(later-depend nil)) ; True if some later variables depend on these values,
; so that these values
; must be computed no later than in the preamble.
(proclaim '(inline li-vars))
(defun li-vars (li)
(case (li-specform li)
((MULTIPLE-VALUE-BIND) (first (li-bindings li)))
((LET) (mapcar #'first (li-bindings li)))))
( wrap - initializations initializations form ) wickelt eine ( umgedrehte ! )
um form .
(defun wrap-initializations (initializations form)
(dolist (initialization initializations)
(let ((name (li-specform initialization))
(bindings (li-bindings initialization))
(declarations (li-declspecs initialization)))
(setq form
`(,name
,@(case name (MULTIPLE-VALUE-BIND bindings) (LET `(,bindings)))
,@(if declarations `((DECLARE ,@declarations)))
,@(li-endtest-forms initialization)
,form))))
form)
;; Variable containing the last test result, called "it".
(defvar *last-it*)
;; Flag whether this variable is used.
(defvar *used-it*)
;;; (revadd a b c d)) ==
( SETF A ( REVAPPEND B ( REVAPPEND C ( REVAPPEND D A ) ) ) )
(defmacro revadd (place &rest forms)
(labels ((expand (rest)
(if rest `(revappend ,(car rest) ,(expand (cdr rest))) place)))
`(setf ,place ,(expand forms))))
;; The bulk of the expander.
(defun expand-loop (*whole* body)
(let ((body-rest body) ; alle Parse-Funktionen verkürzen body-rest
(block-name 'NIL) ; Name des umgebenden BLOCKs
i m von { variables } * { main } * ?
(*helpvars* (make-array 1 :fill-pointer 0 :adjustable t))
(*last-it* nil)
(var-list nil) ; all variables seen so far
(acculist-var nil) ; Akkumulationsvariable für collect, append etc.
(accuvar-tailvar-alist nil) ; alist of (accu-var . tail-var)
(accunum-var nil) ; Akkumulationsvariable für count, sum etc.
(accu-vars-nil nil) ; Akkumulationsvariablen mit Initialwert NIL
(accu-vars-0 nil) ; Akkumulationsvariablen mit Initialwert 0
(accu-table (make-hash-table :warn-if-needs-rehash-after-gc t
:test 'stablehash-eq)) ; var --> clauses
(accu-declarations nil) ; Typdeklarationen (umgedrehte Liste von declspecs)
Bindungen : ( init ... ) ( umgedrehte Liste )
schon eine FOR - AS-= ?
(seen-endtest nil) ; schon eine FOR-AS Klausel mit Abbruchbedingung gesehen?
(preamble nil) ; annotated: ([:INITIALLY|:START] . code) (reversed)
Code zum Abbruch vor ( umgedrehte Liste )
Code i m ( umgedrehte Liste )
Code zur Vorbereitung des nächsten Schleifendurchlaufs ( umgedrehte Liste )
Akkumulationsvariablen , die am
finally - Code ( umgedrehte Liste )
(backward-consing-p ; is backward-consing possible?
(do ((rest *whole* (cdr rest)))
((endp rest) t)
(case (loop-keywordp (car rest))
((NCONC NCONCING APPEND APPENDING)
(unless (eq (loop-keywordp (caddr rest)) 'INTO)
(return nil))))))
(results nil)) ; alist (value-form . (clause list))
(labels
, .
, . , Ergebnis NIL .
(and (consp body-rest) (loop-keywordp (first body-rest))))
(preamble (kind &optional form) (car (push (cons kind form) preamble)))
(cons-forward (form accuvar accufuncsym)
(let ((tailvar
(cdr (or (assoc accuvar accuvar-tailvar-alist)
(car (setq accuvar-tailvar-alist
(acons accuvar
(gensym (symbol-name accuvar))
accuvar-tailvar-alist))))))
(incrementvar (gensym "ADDLIST-")))
(push accuvar accu-vars-nil)
(push tailvar accu-vars-nil)
`(LET ((,incrementvar
,(ecase accufuncsym
(CONS `(LIST ,form))
(REVAPPEND `(COPY-LIST ,form))
(NRECONC `,form))))
(IF ,accuvar
,(case accufuncsym
(CONS `(SETF ,tailvar (SETF (CDR ,tailvar) ,incrementvar)))
(t `(SETF ,tailvar (LAST (RPLACD ,tailvar ,incrementvar)))))
,(case accufuncsym
(CONS `(SETF ,tailvar (SETF ,accuvar ,incrementvar)))
(t `(SETF ,tailvar (LAST (SETF ,accuvar
,incrementvar)))))))))
(compatible-p (kw1 kw2)
;; <-1-3.html>
(let ((ht #,(make-hash-table
:warn-if-needs-rehash-after-gc t
:test 'stablehash-eq
:initial-contents
'((collect . list) (collecting . list)
(append . list) (appending . list)
(nconc . list) (nconcing . list)
(sum . sum-count) (summing . sum-count)
(count . sum-count) (counting . sum-count)
(maximize . max-min) (maximizing . max-min)
(minimize . max-min) (minimizing . max-min)))))
(eq (gethash kw1 ht) (gethash kw2 ht))))
(new-accu-var (var clause)
(let ((others (gethash var accu-table)) bad)
(when (setq bad (find (first clause) others
:key #'first :test-not #'compatible-p))
(error-of-type 'source-program-error
:form *whole* :detail clause
(TEXT "~S: variable ~S is used in incompatible clauses~{ ~A ~S~} and~{ ~A ~S~}")
*whole* var clause bad))
(setf (gethash var accu-table) (cons clause others))))
(new-result (form clause)
(let ((pair (assoc form results :test #'equal)))
(if pair
(push clause (cdr pair))
(push (list form clause) results))
results))
(acculist-var (keyword form)
(or acculist-var
(progn (setq acculist-var (gensym "ACCULIST-VAR-"))
(push acculist-var accu-vars-nil)
(let ((clause (list keyword form)))
(new-accu-var acculist-var clause)
(unless backward-consing-p
(new-result acculist-var clause)))
acculist-var)))
accuvar is NIL , accufuncsym is CONS
(let ((accuvar (acculist-var keyword form)))
(new-result `(SYS::LIST-NREVERSE ,accuvar) `(,keyword ,form))
`(SETQ ,accuvar (CONS ,form ,accuvar))))
, das Keyword kw .
, . , Ergebnis NIL .
(and (consp body-rest) (eq (loop-keywordp (first body-rest)) kw)
(progn (pop body-rest) t)))
Nach kw : expr
(unless (consp body-rest) (loop-syntax-error kw))
(pop body-rest))
Nach kw : expr , it ' sein kann
(unless (consp body-rest) (loop-syntax-error kw))
(let ((form (pop body-rest)))
(if (eq (loop-keywordp form) 'it)
(if *last-it*
(progn (setq *used-it* t) *last-it*)
form)
form)))
(parse-var-typespec () ;; parse var [typespec]
;; return the variable pattern and the list of declspecs
(unless (consp body-rest)
(error-of-type 'source-program-error
:form *whole* :detail body-rest
(TEXT "~S: missing variable.") 'loop))
(let ((pattern (pop body-rest))
(typedecl nil))
(block nil
(unless (consp body-rest) (return))
(case (loop-keywordp (first body-rest))
((NIL) ; no loop keyword ->interpret as typespec
(setq typedecl (pop body-rest))
(unless (simple-type-p typedecl)
(warn (TEXT "~S: After ~S, ~S is interpreted as a type specification")
'loop pattern typedecl)))
OF - TYPE - > expect a typespec
(pop body-rest)
(setq typedecl (parse-form 'of-type)))
(T (return))) ; other
(setq typedecl (destructure-type pattern typedecl)))
(values pattern typedecl)))
(parse-progn () ;; parses {expr}* and return the list of forms
(let ((list nil))
(loop
(unless (and (consp body-rest)
(not (loop-keywordp (first body-rest))))
(return))
(push (pop body-rest) list))
(nreverse list)))
(parse-nonempty-progn (kw) ;; after kw: [CLTS] {expr}+ or [CLTL2] {expr}*
(let ((exprs (parse-progn)))
(unless exprs
(if *loop-ansi*
(loop-syntax-error kw)
(warn (TEXT "~S: missing forms after ~A: permitted by CLtL2, forbidden by ANSI CL.") 'loop (symbol-name kw))))
exprs))
(parse-unconditional () ;; parse an unconditional
;; unconditional ::= {do | doing} {expr}*
;; unconditional ::= return expr
;; Returns a lisp form or NIL when no unconditional was parsed.
(let ((kw (next-kw)))
(case kw
((DO DOING)
(pop body-rest)
`(PROGN ,@(parse-nonempty-progn kw)))
((RETURN)
(pop body-rest)
`(RETURN-FROM ,block-name ,(parse-form-or-it kw)))
(t 'NIL))))
(parse-clause () ;; parses a clause
;; clause ::= accumulation | conditional | unconditional
;; accumulation ::= {collect | collecting | append | appending |
;; nconc | nconcing} expr [into var]
;; accumulation ::= {count | counting | sum | summing |
;; maximize | maximizing | minimize |
;; minimizing} expr [into var] [typespec]
;; conditional ::= {if | when | unless} expr clause {and clause}*
;; [else clause {and clause}*] [end]
;; Returns a lisp form or NIL when no clause was parsed.
(or (parse-unconditional)
(let ((kw (next-kw)))
(case kw
((COLLECT COLLECTING APPEND APPENDING NCONC NCONCING)
(pop body-rest)
;; It seems permitted to write
;; (loop ... collect i into c collect (copy-list c))
;; Therefore we must use forward-consing collection
;; (keeping the tail in a separate variable) if the
;; accumulation variable is named, and can use the more
efficient backward - consing ( with nreverse at the end )
;; only for unnamed accumulation.
Also , / NCONC require forward - consing because
REVAPPEND / NRECONC drop the last atom in dotted lists
(let ((form (parse-form-or-it kw))
(accuvar nil)
(accufuncsym
(case kw
((COLLECT COLLECTING) 'CONS)
((APPEND APPENDING) 'REVAPPEND)
((NCONC NCONCING) 'NRECONC))))
(when (parse-kw-p 'into)
(unless (and (consp body-rest)
(symbolp (setq accuvar (pop body-rest))))
(loop-syntax-error 'into)))
named > forward - consing .
(cons-forward form accuvar accufuncsym))
((or (eq accufuncsym 'REVAPPEND)
(eq accufuncsym 'NRECONC)
(null backward-consing-p))
REVAPPEND / NRECONC now or before
(when backward-consing-p
(error "~s: internal error: backward consing should be illegal!" *whole*))
(cons-forward form (acculist-var kw form)
accufuncsym))
Unnamed acc var & CONS - > cons - backward
(cons-backward kw form)))))
((COUNT COUNTING SUM SUMMING MAXIMIZE MAXIMIZING
MINIMIZE MINIMIZING)
(pop body-rest)
(let* ((form (parse-form-or-it kw)) (type 'fixnum)
(accuvar nil) (clause (list kw form)))
(when (parse-kw-p 'into)
(unless (and (consp body-rest)
(symbolp (setq accuvar (pop body-rest))))
(loop-syntax-error 'into)))
(unless accuvar
(setq accuvar
(or accunum-var
(setq accunum-var (gensym "ACCUNUM-VAR-"))))
(new-result accuvar clause))
(new-accu-var accuvar clause)
(when (consp body-rest)
(let ((kw2 (loop-keywordp (first body-rest))))
(when (or (not kw2) (eq kw2 'of-type))
(setq type
(if (not kw2) (pop body-rest)
(progn (pop body-rest)
(parse-form 'of-type))))
(case kw
((MAXIMIZE MAXIMIZING MINIMIZE MINIMIZING)
NIL
(push `(TYPE ,type ,accuvar) accu-declarations))))
(case kw
((MAXIMIZE MAXIMIZING MINIMIZE MINIMIZING)
(push accuvar accu-vars-nil))
((COUNT COUNTING SUM SUMMING)
(push (list accuvar (coerce 0 type)) accu-vars-0)))
(case kw
((COUNT COUNTING) `(WHEN ,form (INCF ,accuvar)))
((SUM SUMMING) `(SETQ ,accuvar (+ ,accuvar ,form)))
((MAXIMIZE MAXIMIZING) `(SETQ ,accuvar (MAX-IF ,form ,accuvar)))
((MINIMIZE MINIMIZING) `(SETQ ,accuvar (MIN-IF ,form ,accuvar))))))
((IF WHEN UNLESS)
(pop body-rest)
(let* ((condition (parse-form kw))
(it-var (gensym "IT-"))
used-it
(true-form
(let ((*last-it* it-var) (*used-it* nil))
(prog1
(parse-clauses kw)
(setq used-it *used-it*))))
(false-form 'NIL))
(when (parse-kw-p 'else)
(setq false-form
(let ((*last-it* it-var) (*used-it* nil))
(prog1
(parse-clauses 'else)
(setq used-it (or used-it *used-it*))))))
(parse-kw-p 'end)
(when used-it
(psetq it-var `((,it-var ,condition))
condition it-var))
(let ((form
`(IF ,(if (eq kw 'UNLESS)
`(NOT ,condition) ; UNLESS
`,condition) ; IF, WHEN
,true-form
,false-form)))
(if used-it `(LET ,it-var ,form) `,form))))
(t 'NIL)))))
Nach kw : clause { and clause } *
; oder kurz {clause}+{and}
; Liefert eine Lisp-Form.
(let ((clauses nil))
(loop
(let ((clause (parse-clause)))
(unless clause (loop-syntax-error kw))
(push clause clauses))
(unless (parse-kw-p 'and) (return))
(setq kw 'and)
' it ' ist nur in der ersten Klausel gültig
`(PROGN ,@(nreverse clauses))))
; Binden und Initialisieren von Variablen:
; Nach ANSI-CL 6.1.1.4 gelten zwei Grundregeln:
- ( außer FOR - AS-= ) sind
mindestens alle vorherigen FOR - AS Variablen sichtbar .
- Variablen sind alle FOR - AS Variablen
; sichtbar.
Zusätzlich ist die folgende Grundregel wünschenswert :
- Variablen sind mindestens alle
vorherigen FOR - AS Variablen initialisiert und deren Abbruch-
bedingungen abgeprüft .
Man könnte erst alle i m preamble
die .
Optimierungen durch :
- Falls vor der FOR - ,
braucht die Variable zum Zeitpunkt ihrer Initialisierung nicht
sichtbar zu sein , und nach
vorne , zur . Das ,
; keine FOR-AS Klausel mit Abbruchbedingung kommt.
- Falls eine Variable gar nicht sichtbar zu ,
FOR - AS-= und
stört , können die und die Initialiserung der
Variablen ins verschoben werden .
(note-initialization (initialization)
(when (or (li-bindings initialization)
(li-declspecs initialization)
(li-endtest-forms initialization))
(when seen-for-as-=
(setf (li-requires-stepbefore initialization) t))
(when (li-endtest-forms initialization)
(setq seen-endtest t))
(dolist (var (li-vars initialization))
(when (memq var var-list)
(error-of-type 'source-program-error
:form *whole* :detail var
(TEXT "~S: duplicate iteration variable ~S") *whole* var))
(push var var-list))
(push initialization initializations)))
(make-endtest (endtest-form)
(make-loop-init
:specform 'PROGN
:bindings nil
:declspecs nil
:endtest-forms (list endtest-form)
:everytime (setq stepafter-code (cons 'NIL stepafter-code))
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))
Los geht 's !
; parst: [named name]
(when (parse-kw-p 'named)
(unless (and (consp body-rest) (symbolp (first body-rest)))
(loop-syntax-error 'named))
(setq block-name (pop body-rest)))
(loop
; main ::= clause | termination | initially | finally |
; with | for-as | repeat
; termination ::= {while | until | always | never | thereis} expr
; initially ::= initially {expr}*
; finally ::= finally { unconditional | {expr}* }
; with ::= with {var-typespec [= expr]}+{and}
; for-as ::= {for | as} {var-typespec ...}+{and}
; repeat ::= repeat expr
(unless (consp body-rest) (return))
(let ((clause (parse-clause)))
(if clause
(progn (setq already-within-main t) (push clause main-code))
(let ((kw (loop-keywordp (first body-rest))))
(case kw
((WHILE UNTIL ALWAYS NEVER THEREIS)
(pop body-rest)
(setq already-within-main t)
(let ((form (parse-form kw)))
(push (case kw
(WHILE `(UNLESS ,form (LOOP-FINISH)))
(UNTIL `(WHEN ,form (LOOP-FINISH)))
(ALWAYS
(new-result 'T (list kw form))
`(UNLESS ,form (RETURN-FROM ,block-name 'NIL)))
(NEVER
(new-result 'T (list kw form))
`(WHEN ,form (RETURN-FROM ,block-name 'NIL)))
(THEREIS
(let ((dummy (gensym "THEREIS-")))
(new-result 'NIL (list kw form))
`(BLOCK ,dummy
(RETURN-FROM ,block-name
(OR ,form (RETURN-FROM ,dummy NIL)))))))
main-code)))
((INITIALLY)
(pop body-rest)
(preamble :INITIALLY `(PROGN ,@(parse-nonempty-progn kw))))
((FINALLY)
(pop body-rest)
(push (let ((form (parse-unconditional)))
(if form
(if *loop-ansi*
(loop-syntax-error 'FINALLY)
(warn (TEXT "~S: loop keyword immediately after ~A: permitted by CLtL2, forbidden by ANSI CL.") 'loop (symbol-name kw)))
(setq form `(PROGN ,@(parse-nonempty-progn kw))))
form)
finally-code))
((WITH FOR AS REPEAT)
(pop body-rest)
(when already-within-main
(warn (TEXT "~S: ~A clauses should occur before the loop's main body")
'loop (symbol-name kw)))
(case kw
((WITH)
(let ((bindings nil)
(declspecs nil))
(loop
(let (new-bindings)
(multiple-value-bind (pattern new-declspecs) (parse-var-typespec)
(if (parse-kw-p '=)
; Initialisierungsform angegeben.
(let ((form (parse-form '=)))
(setq new-bindings (destructure pattern form)))
keine Initialisierungsform angegeben .
(setq new-bindings (default-bindings (destructure-vars pattern) new-declspecs)))
(setq bindings (revappend new-bindings bindings))
(setq declspecs (revappend new-declspecs declspecs))))
(unless (parse-kw-p 'and) (return))
(setq kw 'and))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (nreverse bindings)
:declspecs (nreverse declspecs)
:everytime nil
;; WITH vars should always be bound on top
:requires-stepbefore nil ; seen-endtest
:preamble (preamble :start)
:depends-preceding t))))
((FOR AS)
; for-as ::= {for | as} for-as-clause {and [{for | as}] for-as-clause}*
; for-as-clause ::= var-typespec
[ { from | downfrom | upfrom } expr ]
; [{to | downto | upto | below | above} expr]
; [by expr]
; for-as-clause ::= var-typespec {in | on} expr [by expr]
; for-as-clause ::= var-typespec = expr [then expr]
; for-as-clause ::= var-typespec across expr
; for-as-clause ::= var-typespec being {each | the}
; {hash-key[s] | hash-value[s]}
; {in | of} expr
; [using ( {hash-value | hash-key} var ) ]
; for-as-clause ::= var-typespec being {each | the}
; {symbol[s] | present-symbol[s] | internal-symbol[s] | external-symbol[s]}
; {in | of} expr
(let ((bindings nil)
(declspecs nil)
(initializations nil)
(stepafter nil)
(old-seen-endtest seen-endtest)
;; remember the _CURRENT_ location in preamble
(preamble-entry (preamble :start))
(depends-preceding nil))
(flet ((note-initialization (initialization)
;; supersedes the outer definition!
;; Calls to note-initialization must temporarily be suspended.
(when (li-endtest-forms initialization)
(setq seen-endtest t))
(push initialization initializations)))
(loop
(multiple-value-bind (pattern new-declspecs) (parse-var-typespec)
(let ((preposition (next-kw)))
(case preposition
((IN ON)
(pop body-rest)
(let ((start-form (parse-form preposition))
(step-function-form '(FUNCTION CDR))
(step-function-var nil))
(when (parse-kw-p 'by)
(setq step-function-form (parse-form 'by))
(unless (and (function-form-p step-function-form)
(function-name-p (second step-function-form)))
(setq step-function-var (gensym "BY-"))))
(let ((var (if (and pattern (symbolp pattern)
(eq preposition 'ON))
pattern (gensym "LIST-"))))
(push `(,var ,start-form) bindings)
(when step-function-var
(push `(,step-function-var ,step-function-form)
bindings))
(note-initialization
(make-endtest
`(WHEN (,(if (eq preposition 'IN)
'ENDP 'ATOM)
,var)
(LOOP-FINISH))))
(unless (eq var pattern)
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern (if (eq preposition 'IN) `(CAR ,var) var))
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))
(push
(list var
(if step-function-var
`(FUNCALL ,step-function-var ,var)
`(,(second step-function-form) ,var)))
stepafter))))
(=
(pop body-rest)
(let* ((first-form (parse-form 'preposition))
(then-form first-form))
(when (parse-kw-p 'then)
(setq then-form (parse-form 'then)))
(setq bindings
(revappend (destructure pattern first-form)
bindings))
(setq declspecs (revappend new-declspecs declspecs))
(unless (and (constantp first-form)
(constantp then-form))
(setq seen-for-as-= t)
Even when ` first - form ' is constant but
;; `then-form' is not, we must set
;; `depends-preceding', because the
;; `stepafter-code' depends on the order of
;; the steppings, which forbids moving
;; some code from `preamble' +
` stepafter - code ' to ` stepbefore - code . '
(setq depends-preceding t))
(setq stepafter (revappend (destructure pattern then-form) stepafter))))
(ACROSS
(pop body-rest)
(let ((vector-form (parse-form preposition))
(vector-var (gensym "VECTOR-"))
(index-var (gensym "INDEX-")))
(push `(,vector-var ,vector-form) bindings)
(push `(,index-var 0) bindings)
(note-initialization
(make-endtest `(WHEN (>= ,index-var (LENGTH ,vector-var)) (LOOP-FINISH))))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern `(AREF ,vector-var ,index-var))
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(push (list index-var `(1+ ,index-var)) stepafter)))
(BEING
(pop body-rest)
(let ((plural (next-kw)))
(case plural
((EACH THE))
(t (loop-syntax-error 'being)))
(pop body-rest)
(let ((preposition (next-kw)))
(case preposition
((HASH-KEY HASH-VALUE
SYMBOL PRESENT-SYMBOL INTERNAL-SYMBOL EXTERNAL-SYMBOL)
(when (eq plural 'THE)
(warn (TEXT "~S: After ~S a plural loop keyword is required, not ~A")
'loop plural (symbol-name preposition))))
((HASH-KEYS HASH-VALUES
SYMBOLS PRESENT-SYMBOLS INTERNAL-SYMBOLS EXTERNAL-SYMBOLS)
(when (eq plural 'EACH)
(warn (TEXT "~S: After ~S a singular loop keyword is required, not ~A")
'loop plural (symbol-name preposition))))
(t (loop-syntax-error plural)))
(pop body-rest)
(case preposition
((HASH-KEY HASH-KEYS HASH-VALUE HASH-VALUES)
(let ((other-pattern nil)
(form
(case (next-kw)
((IN OF) (pop body-rest)
(parse-form preposition))
(t (loop-syntax-error
preposition)))))
(when (parse-kw-p 'using)
(unless (and (consp body-rest)
(consp (car body-rest))
(consp (cdar body-rest))
(null (cddar body-rest))
(case (loop-keywordp (caar body-rest))
((HASH-KEY HASH-KEYS)
(case preposition
((HASH-VALUE HASH-VALUES) t) (t nil)))
((HASH-VALUE HASH-VALUES)
(case preposition
((HASH-KEY HASH-KEYS) t) (t nil)))))
(loop-syntax-error 'using))
(setq other-pattern (second (pop body-rest))))
(let ((state-var (gensym "WHTI-"))
(nextp-var (gensym "MORE?"))
(nextkey-var (gensym "HASH-KEY-"))
(nextvalue-var (gensym "HASH-VALUE-")))
(multiple-value-bind (nextmain-var nextother-var)
(case preposition
((HASH-KEY HASH-KEYS) (values nextkey-var nextvalue-var))
((HASH-VALUE HASH-VALUES) (values nextvalue-var nextkey-var)))
(push `(,state-var (SYS::HASH-TABLE-ITERATOR ,form)) bindings)
(note-initialization
(make-loop-init
:specform 'MULTIPLE-VALUE-BIND
:bindings `((,nextp-var ,nextkey-var ,nextvalue-var)
(SYS::HASH-TABLE-ITERATE ,state-var))
:declspecs (unless other-pattern `((IGNORE ,nextother-var)))
:endtest-forms `((UNLESS ,nextp-var (LOOP-FINISH)))
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern nextmain-var)
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(when other-pattern
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure other-pattern nextother-var)
:declspecs nil
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))))))
((SYMBOL SYMBOLS PRESENT-SYMBOL PRESENT-SYMBOLS
INTERNAL-SYMBOL INTERNAL-SYMBOLS EXTERNAL-SYMBOL EXTERNAL-SYMBOLS)
(let ((flags (case preposition
((SYMBOL SYMBOLS) '(:internal :external :inherited))
((PRESENT-SYMBOL PRESENT-SYMBOLS) '(:internal :external))
((INTERNAL-SYMBOL INTERNAL-SYMBOLS) '(:internal))
((EXTERNAL-SYMBOL EXTERNAL-SYMBOLS) '(:external))))
(state-var (gensym "WPI-"))
(nextp-var (gensym "MORE?"))
(nextsym-var (gensym "SYMBOL-"))
(form
(case (next-kw)
((IN OF) (pop body-rest)
(parse-form preposition))
(t '*package*))))
(push `(,state-var (SYS::PACKAGE-ITERATOR ,form ',flags))
bindings)
(note-initialization
(make-loop-init
:specform 'MULTIPLE-VALUE-BIND
:bindings `((,nextp-var ,nextsym-var)
(SYS::PACKAGE-ITERATE ,state-var))
:declspecs nil
:endtest-forms `((UNLESS ,nextp-var (LOOP-FINISH)))
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern nextsym-var)
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))))))))
(t
(unless (symbolp pattern) (loop-syntax-error kw))
(unless pattern (setq pattern (gensym "FOR-NUM-")))
ANSI CL 6.1.2.1.1 implies that the
;; start/end/by clauses can come in any
order , but only one of each kind .
(let ((step-start-p nil)
(step-end-p nil)
(step-by-p nil)
step-start-form
step-end-form
step-by-form
step-end-preposition
dir)
(loop
(cond ((and (not step-start-p)
(setq dir (case preposition
(FROM 't)
(UPFROM 'up)
(DOWNFROM 'down)
(t nil))))
(setq step-start-p dir)
(pop body-rest)
(setq step-start-form (parse-form preposition))
(push `(,pattern ,step-start-form) bindings))
((and (not step-end-p)
(setq dir (case preposition
(TO 't)
((UPTO BELOW) 'up)
((DOWNTO ABOVE) 'down)
(t nil))))
(setq step-end-p dir)
(setq step-end-preposition preposition)
(pop body-rest)
(setq step-end-form (parse-form preposition))
(unless (constantp step-end-form)
(let ((step-end-var (gensym "LIMIT-")))
(push `(,step-end-var ,step-end-form) bindings)
(setq step-end-form step-end-var))))
((and (not step-by-p)
(eq preposition 'BY))
(setq step-by-p t)
(pop body-rest)
(setq step-by-form (parse-form 'by))
(unless (constantp step-by-form)
(let ((step-by-var (gensym "BY-")))
(push `(,step-by-var ,step-by-form) bindings)
(setq step-by-form step-by-var))))
(t (return)))
(setq preposition (next-kw)))
;; All parsing done, gather the declarations:
(setq declspecs (revappend new-declspecs declspecs))
;; Determine the direction of iteration:
(let ((step-direction
(if (or (eq step-start-p 'down) (eq step-end-p 'down))
(if (or (eq step-start-p 'up) (eq step-end-p 'up))
(error-of-type 'source-program-error
:form *whole* :detail kw
(TEXT "~S: questionable iteration direction after ~A")
'loop (symbol-name kw))
'down)
'up)))
;; Determine start, unless given:
(unless step-start-p
(when (eq step-direction 'down)
Abwärtsiteration ohne Startwert ist nicht erlaubt .
Die zweite optionale Klausel ( d.h . preposition ) muss .
(error-of-type 'source-program-error
:form *whole* :detail preposition
(TEXT "~S: specifying ~A requires FROM or DOWNFROM")
'loop (symbol-name preposition)))
; Aufwärtsiteration -> Startwert 0
(setq step-start-form '0)
(push `(,pattern ,step-start-form) bindings))
; Determine step, unless given:
(unless step-by-p (setq step-by-form '1))
; Determine end test:
(when step-end-p
(let* ((compfun
(if (eq step-direction 'up)
(if (eq step-end-preposition 'below) '>= '>) ; up
(if (eq step-end-preposition 'above) '<= '<))) ; down
(endtest
(if (and (constantp step-end-form) (zerop (eval step-end-form)))
(case compfun
(>= `(NOT (MINUSP ,pattern)))
(> `(PLUSP ,pattern))
(<= `(NOT (PLUSP ,pattern)))
(< `(MINUSP ,pattern)))
`(,compfun ,pattern ,step-end-form))))
(note-initialization
(make-endtest `(WHEN ,endtest (LOOP-FINISH))))))
(push
(list pattern `(,(if (eq step-direction 'up) '+ '-) ,pattern ,step-by-form))
stepafter)))))))
(unless (parse-kw-p 'and) (return))
(setq kw 'and)
(case (next-kw) ((FOR AS) (pop body-rest)))))
(when (setq stepafter (apply #'append (nreverse stepafter)))
(push `(PSETQ ,@stepafter) stepafter-code))
Markierung für spätere Initialisierungen
(note-initialization ; outer `note-initialization'!
(make-loop-init
:specform 'LET
:bindings (nreverse bindings)
:declspecs (nreverse declspecs)
:everytime nil
:requires-stepbefore old-seen-endtest
:preamble preamble-entry
:depends-preceding depends-preceding))
(dolist (initialization (nreverse initializations))
(when (li-everytime initialization)
(setf (li-everytime initialization) stepafter-code))
(note-initialization initialization))))
((REPEAT)
(let ((form (parse-form kw))
(var (gensym "COUNT-")))
(note-initialization
(make-loop-init
:specform 'LET
:bindings `((,var ,form))
:declspecs nil
:everytime nil
:requires-stepbefore seen-endtest
:preamble (preamble :start)
:depends-preceding t))
(push `(SETQ ,var (1- ,var)) stepafter-code)
(note-initialization
(make-endtest `(UNLESS (PLUSP ,var) (LOOP-FINISH))))))))
(t (error-of-type 'source-program-error
:form *whole* :detail *whole*
(TEXT "~S: illegal syntax near ~S in ~S")
'loop (first body-rest) *whole*)))))))
; Noch einige semantische Tests:
(when (> (length results) 1)
(error-of-type 'source-program-error
:form *whole* :detail *whole*
(TEXT "~S: ambiguous result:~:{~%~S from ~@{~{~A ~S~}~^, ~}~}")
*whole* results))
(unless (null results)
(push `(RETURN-FROM ,block-name ,(caar results)) finally-code))
Initialisierungen abarbeiten und optimieren :
(let ((initializations1
(unless (zerop (length *helpvars*))
;; `*helpvars*' must be bound first thing
(list (make-loop-init
:specform 'LET
:preamble (preamble :start)
:bindings
(map 'list #'(lambda (var) `(,var NIL)) *helpvars*))))))
; `depends-preceding' backpropagation:
(let ((later-depend nil))
(dolist (initialization initializations)
(when later-depend (setf (li-later-depend initialization) t))
(when (li-depends-preceding initialization)
(setq later-depend t))))
(dolist (initialization (nreverse initializations))
(let* ((everytime (li-everytime initialization))
(requires-stepbefore (li-requires-stepbefore initialization))
(name (li-specform initialization))
(bindings (li-bindings initialization))
(declarations (li-declspecs initialization))
(vars (case name
(MULTIPLE-VALUE-BIND (first bindings))
(LET (mapcar #'first bindings))))
(initforms
(case name
(MULTIPLE-VALUE-BIND `((MULTIPLE-VALUE-SETQ ,@bindings)))
(LET `((SETQ ,@(apply #'append bindings))))
(t '())))
(endtest-forms (li-endtest-forms initialization)))
(if requires-stepbefore
; wegen seen-for-as-= oder AREF nicht optimierbar
(progn
(push
(make-loop-init
:specform 'LET
:bindings (default-bindings vars declarations)
:preamble (preamble :start)
:declspecs declarations)
initializations1)
(if everytime
(if (li-later-depend initialization)
(progn ; double code: preamble and stepafter-code
(revadd (cdr (li-preamble initialization))
endtest-forms initforms)
(revadd (cdr everytime) endtest-forms initforms))
(revadd stepbefore-code endtest-forms initforms))
(revadd (cdr (li-preamble initialization))
endtest-forms initforms)))
Initialisierungsklausel nach initializations1 :
(progn
(push
(make-loop-init
:specform name
:bindings bindings
:preamble (preamble :start)
:declspecs declarations)
initializations1)
(if everytime
(progn
; put the initforms into the stepafter-code only.
(revadd (cdr everytime) initforms)
; handle the endtest-forms.
(if (li-later-depend initialization)
(progn ; double endtest: preamble and stepafter-code
(revadd (cdr (li-preamble initialization))
endtest-forms)
(revadd (cdr everytime) endtest-forms))
(revadd stepbefore-code endtest-forms)))
(revadd (cdr (li-preamble initialization)) endtest-forms))))))
(flet ((check-accu-var (var)
(when (memq var var-list)
(error-of-type 'source-program-error
:form *whole* :detail var
(TEXT "~S: accumulation variable ~S is already bound")
*whole* var))))
(push
(make-loop-init
:specform 'LET
:bindings
`(,@(mapcar #'(lambda (var) (check-accu-var var) `(,var NIL))
(delete-duplicates accu-vars-nil))
,@(mapcar #'(lambda (var) (check-accu-var (car var)) var)
(delete-duplicates accu-vars-0 :key #'car)))
:preamble (preamble :start)
:declspecs (nreverse accu-declarations))
initializations1))
(setq preamble
(mapcan (lambda (rec)
(case (car rec)
(:start (nreverse
(mapcar (lambda (f) (cons :start f))
(cdr rec))))
(:initially (list rec))))
preamble))
Remove the NIL placeholders in stepafter - code .
(setq stepafter-code (delete 'NIL stepafter-code))
;; If preamble and stepafter-code both end in the same
forms , drag these forms across the label to stepbefore - code .
(flet ((form-eq (form1 form2) ; Calling EQUAL on user-given forms would be wrong
(or (eql form1 form2)
(and (consp form1) (consp form2)
(eql (length form1) (length form2))
(or (eq (car form1) (car form2))
(and (case (length form1) ((1 3) t))
(case (car form1) ((SETQ PSETQ) t))
(case (car form2) ((SETQ PSETQ) t))))
(every #'eq (cdr form1) (cdr form2))))))
(loop
(unless (and (consp preamble) (consp stepafter-code)
(eq :start (caar preamble))
(form-eq (cdar preamble) (car stepafter-code)))
(return))
(setq stepbefore-code
(nconc stepbefore-code (list (pop stepafter-code))))
(pop preamble)))
;; Final macroexpansion.
`(MACROLET ((LOOP-FINISH () (LOOP-FINISH-ERROR)))
(BLOCK ,block-name
,(wrap-initializations initializations1
`(MACROLET ((LOOP-FINISH () '(GO END-LOOP)))
(TAGBODY
,@(if preamble (nreverse (mapcar #'cdr preamble)))
BEGIN-LOOP
,@(if stepbefore-code (nreverse stepbefore-code))
,(cons 'PROGN (nreverse main-code))
,@(if stepafter-code (nreverse stepafter-code))
(GO BEGIN-LOOP)
END-LOOP
,@(mapcar #'(lambda (var)
`(SETQ ,var (SYS::LIST-NREVERSE ,var)))
accu-vars-nreverse)
(MACROLET ((LOOP-FINISH () (LOOP-FINISH-WARN)
'(GO END-LOOP)))
,@(nreverse finally-code)))))))))))
;; Der eigentliche Macro:
(defmacro loop (&whole whole &body body)
(if (some #'atom body)
;; "extended" loop form
(expand-loop whole body)
;; "simple" loop form
(let ((tag (gensym "LOOP-")))
`(BLOCK NIL (TAGBODY ,tag ,@body (GO ,tag))))))
(defmacro loop-finish (&whole whole)
(error (TEXT "~S is possible only from within ~S")
whole 'loop))
(defun loop-finish-warn ()
(warn (TEXT "Use of ~S in FINALLY clauses is deprecated because it can lead to infinite loops.")
'(loop-finish)))
(defun loop-finish-error ()
(error (TEXT "~S is not possible here")
'(loop-finish)))
Run - Time - Support :
ABI
(if y (max x y) x))
ABI
(if y (min x y) x))
| null | https://raw.githubusercontent.com/ufasoft/lisp/bd5213fbd5e162ca7e8a4a9b5aeb6252f38a30fc/clisp/loop.lisp | lisp | ANSI CL Loop
<-1.html>
<>
(loop-keywordp obj) determines whether OBJ is a loop keyword,
the entire form (LOOP ...)
(loop-syntax-error loop-keyword) reports a syntax error.
FIXME: should be something more useful
destructuring:
(destructure-vars pattern) returns the list of variables occuring
in the pattern.
(empty-tree-p pattern) determine whether the pattern has no variables
at all.
(destructure-type pattern type) returns the list of declaration
specifiers, that declare that each variable in 'pattern' is of the
corresponding type in 'type'.
(simple-type-p type) determines whether 'type' contains, after
used without OF-TYPE.
vector of auxiliary variables for destructuring
At least n auxiliary variable must already have been used.
'*helpvars*' is extended if necessary.
(destructure pattern form) returns a list of lists (variable_i form_i).
variable_i is a variable from 'pattern', form_i is a form, whose
result must be bound or assigned to variable_i. The order of the
bindings/assignments doesn't matter, i.e. both LET and LET*, or
both PSETQ and SETQ are possible.
no variables -> must nevertheless evaluate form!
(default-bindings vars declspecs).
vars = (var ...) is a list of variables without init forms.
Returns the binding list ((var var-init) ...), where var-init is
compatible with the declspecs.
OK
A loop-initialization describes at macro expansion time the task
generating code in the prologue or in the inner loop.
How to generate the Lisp code.
for LET: list of bindings,
list of declspecs
more forms to be inserted after the declarations,
within the tagbody.
Properties of this initialization.
If the assignment has to be evaluated in the prologue only: NIL.
If the assignment has to be evaluated once for each iteration:
a cons, pointing at the right place in the stepafter-code.
True if the variables can get their values only
with the initial binding.
True if everytime=NIL and the values may depend
on preceding variables, so that these preceding
variables must get their values no later than in
the preamble (= prologue + startup)
cons = location in preamble
True if some later variables depend on these values,
so that these values
must be computed no later than in the preamble.
Variable containing the last test result, called "it".
Flag whether this variable is used.
(revadd a b c d)) ==
The bulk of the expander.
alle Parse-Funktionen verkürzen body-rest
Name des umgebenden BLOCKs
all variables seen so far
Akkumulationsvariable für collect, append etc.
alist of (accu-var . tail-var)
Akkumulationsvariable für count, sum etc.
Akkumulationsvariablen mit Initialwert NIL
Akkumulationsvariablen mit Initialwert 0
var --> clauses
Typdeklarationen (umgedrehte Liste von declspecs)
schon eine FOR-AS Klausel mit Abbruchbedingung gesehen?
annotated: ([:INITIALLY|:START] . code) (reversed)
is backward-consing possible?
alist (value-form . (clause list))
<-1-3.html>
parse var [typespec]
return the variable pattern and the list of declspecs
no loop keyword ->interpret as typespec
other
parses {expr}* and return the list of forms
after kw: [CLTS] {expr}+ or [CLTL2] {expr}*
parse an unconditional
unconditional ::= {do | doing} {expr}*
unconditional ::= return expr
Returns a lisp form or NIL when no unconditional was parsed.
parses a clause
clause ::= accumulation | conditional | unconditional
accumulation ::= {collect | collecting | append | appending |
nconc | nconcing} expr [into var]
accumulation ::= {count | counting | sum | summing |
maximize | maximizing | minimize |
minimizing} expr [into var] [typespec]
conditional ::= {if | when | unless} expr clause {and clause}*
[else clause {and clause}*] [end]
Returns a lisp form or NIL when no clause was parsed.
It seems permitted to write
(loop ... collect i into c collect (copy-list c))
Therefore we must use forward-consing collection
(keeping the tail in a separate variable) if the
accumulation variable is named, and can use the more
only for unnamed accumulation.
UNLESS
IF, WHEN
oder kurz {clause}+{and}
Liefert eine Lisp-Form.
Binden und Initialisieren von Variablen:
Nach ANSI-CL 6.1.1.4 gelten zwei Grundregeln:
sichtbar.
keine FOR-AS Klausel mit Abbruchbedingung kommt.
parst: [named name]
main ::= clause | termination | initially | finally |
with | for-as | repeat
termination ::= {while | until | always | never | thereis} expr
initially ::= initially {expr}*
finally ::= finally { unconditional | {expr}* }
with ::= with {var-typespec [= expr]}+{and}
for-as ::= {for | as} {var-typespec ...}+{and}
repeat ::= repeat expr
Initialisierungsform angegeben.
WITH vars should always be bound on top
seen-endtest
for-as ::= {for | as} for-as-clause {and [{for | as}] for-as-clause}*
for-as-clause ::= var-typespec
[{to | downto | upto | below | above} expr]
[by expr]
for-as-clause ::= var-typespec {in | on} expr [by expr]
for-as-clause ::= var-typespec = expr [then expr]
for-as-clause ::= var-typespec across expr
for-as-clause ::= var-typespec being {each | the}
{hash-key[s] | hash-value[s]}
{in | of} expr
[using ( {hash-value | hash-key} var ) ]
for-as-clause ::= var-typespec being {each | the}
{symbol[s] | present-symbol[s] | internal-symbol[s] | external-symbol[s]}
{in | of} expr
remember the _CURRENT_ location in preamble
supersedes the outer definition!
Calls to note-initialization must temporarily be suspended.
`then-form' is not, we must set
`depends-preceding', because the
`stepafter-code' depends on the order of
the steppings, which forbids moving
some code from `preamble' +
start/end/by clauses can come in any
All parsing done, gather the declarations:
Determine the direction of iteration:
Determine start, unless given:
Aufwärtsiteration -> Startwert 0
Determine step, unless given:
Determine end test:
up
down
outer `note-initialization'!
Noch einige semantische Tests:
`*helpvars*' must be bound first thing
`depends-preceding' backpropagation:
wegen seen-for-as-= oder AREF nicht optimierbar
double code: preamble and stepafter-code
put the initforms into the stepafter-code only.
handle the endtest-forms.
double endtest: preamble and stepafter-code
If preamble and stepafter-code both end in the same
Calling EQUAL on user-given forms would be wrong
Final macroexpansion.
Der eigentliche Macro:
"extended" loop form
"simple" loop form | ( LOOP { loop - clause } * ) , CLtL2 p. 163,709 - 747
1991 - 2004
1999 - 2005
(in-package "COMMON-LISP")
(export '(loop loop-finish))
(pushnew ':loop *features*)
(in-package "SYSTEM")
Parser auxiliary functions
and then returns the appropriate unique symbol , otherwise NIL .
(defun loop-keywordp (obj)
(and (symbolp obj)
(gethash (symbol-name obj)
(load-time-value
(make-hash-table
:key-type 'string :value-type 'symbol
:test 'fasthash-equal :warn-if-needs-rehash-after-gc t
:initial-contents
(mapcar #'(lambda (s) (cons (symbol-name s) s))
'(named
for as and from downfrom upfrom to downto upto below
above by in on = then across being each the hash-key
hash-keys hash-value hash-values of using symbol
present-symbol internal-symbol external-symbol symbols
present-symbols internal-symbols external-symbols
repeat
while until always never thereis
collect collecting append appending nconc nconcing
count counting sum summing maximize maximizing
minimize minimizing into
with
if when unless else end it
do doing return
of-type
initially finally)))))))
(defun loop-syntax-error (loop-keyword)
(error-of-type 'source-program-error
:form *whole*
(TEXT "~S: syntax error after ~A in ~S")
'loop (symbol-name loop-keyword) *whole*))
(defun destructure-vars (pattern)
(let ((vars '()))
(labels ((accumulate (pattern)
(cond ((null pattern))
((atom pattern) (push pattern vars))
(t
(accumulate (car pattern))
(accumulate (cdr pattern))))))
(accumulate pattern))
(nreverse vars)))
(defun empty-tree-p (pattern)
(cond ((null pattern) t)
((atom pattern) nil)
(t (and (empty-tree-p (car pattern))
(empty-tree-p (cdr pattern))))))
(defun destructure-type (pattern type)
(let ((declspecs '()))
(labels ((accumulate (pattern type)
(cond ((null pattern))
((atom pattern)
(push `(TYPE ,type ,pattern) declspecs))
((consp type)
(accumulate (car pattern) (car type))
(accumulate (cdr pattern) (cdr type)))
(t
(let ((vars (destructure-vars pattern)))
(when vars
(push `(TYPE ,type ,@vars) declspecs)))))))
(accumulate pattern type))
(nreverse declspecs)))
destructuring , only NIL , T , FIXNUM , FLOAT , and therefore can be
(defun simple-type-p (type)
(if (atom type)
(case type
((NIL T FIXNUM FLOAT) t)
(t nil))
(and (simple-type-p (car type))
(simple-type-p (cdr type)))))
( helpvar n ) returns the ( n+1)-st auxiliary variable ( n>=0 ) .
(defun helpvar (n)
(when (= n (fill-pointer *helpvars*))
(vector-push-extend (gensym "PATTERN-") *helpvars*))
(aref *helpvars* n))
(defun destructure (pattern form)
(labels ((destructure-tree (pattern form helpvar-count)
helpvar - count =
(cond ((empty-tree-p pattern) nil)
((atom pattern) (list (list pattern form)))
((empty-tree-p (car pattern))
(destructure-tree (cdr pattern) `(CDR ,form) helpvar-count))
((empty-tree-p (cdr pattern))
(destructure-tree (car pattern) `(CAR ,form) helpvar-count))
muss form zwischendurch einer Hilfsvariablen zuweisen
(let ((helpvar (helpvar helpvar-count)))
(nconc (destructure-tree (car pattern) `(CAR (SETQ ,helpvar ,form)) (1+ helpvar-count))
(destructure-tree (cdr pattern) `(CDR ,helpvar) helpvar-count)))))))
(or (destructure-tree pattern form 0)
(list (list (helpvar 0) form)))))
(defun default-bindings (vars declspecs)
Use NIL or 0 or 0.0 if it fits the declarations .
Otherwise use NIL and extend the type declarations .
(let ((bindings (mapcar #'(lambda (var) (list var 'NIL)) vars)))
(dolist (declspec declspecs)
(when (eq (first declspec) 'TYPE)
declspec is of form ( TYPE type . vars )
(let* ((type (second declspec))
(dtype (type-for-discrimination type))
h)
((or (typep (setq h '0) dtype) (typep (setq h '0.0) dtype))
(dolist (var (cddr declspec))
(setf (second (find var bindings :key #'first)) h)))
(t (setf (second declspec) `(OR NULL ,type)))))))
bindings))
to initialise one or more variables . The initialization may end up
(defstruct (loop-initialization
(:copier nil)
(:conc-name "LI-")
(:predicate nil)
(:constructor make-loop-init))
special form : LET or MULTIPLE - VALUE - BIND or PROGN
for MULTIPLE - VALUE - BIND : varlist and form
in the stepbefore - code or preamble ,
false if the first assignment can be merged
(proclaim '(inline li-vars))
(defun li-vars (li)
(case (li-specform li)
((MULTIPLE-VALUE-BIND) (first (li-bindings li)))
((LET) (mapcar #'first (li-bindings li)))))
( wrap - initializations initializations form ) wickelt eine ( umgedrehte ! )
um form .
(defun wrap-initializations (initializations form)
(dolist (initialization initializations)
(let ((name (li-specform initialization))
(bindings (li-bindings initialization))
(declarations (li-declspecs initialization)))
(setq form
`(,name
,@(case name (MULTIPLE-VALUE-BIND bindings) (LET `(,bindings)))
,@(if declarations `((DECLARE ,@declarations)))
,@(li-endtest-forms initialization)
,form))))
form)
(defvar *last-it*)
(defvar *used-it*)
( SETF A ( REVAPPEND B ( REVAPPEND C ( REVAPPEND D A ) ) ) )
(defmacro revadd (place &rest forms)
(labels ((expand (rest)
(if rest `(revappend ,(car rest) ,(expand (cdr rest))) place)))
`(setf ,place ,(expand forms))))
(defun expand-loop (*whole* body)
i m von { variables } * { main } * ?
(*helpvars* (make-array 1 :fill-pointer 0 :adjustable t))
(*last-it* nil)
(accu-table (make-hash-table :warn-if-needs-rehash-after-gc t
Bindungen : ( init ... ) ( umgedrehte Liste )
schon eine FOR - AS-= ?
Code zum Abbruch vor ( umgedrehte Liste )
Code i m ( umgedrehte Liste )
Code zur Vorbereitung des nächsten Schleifendurchlaufs ( umgedrehte Liste )
Akkumulationsvariablen , die am
finally - Code ( umgedrehte Liste )
(do ((rest *whole* (cdr rest)))
((endp rest) t)
(case (loop-keywordp (car rest))
((NCONC NCONCING APPEND APPENDING)
(unless (eq (loop-keywordp (caddr rest)) 'INTO)
(return nil))))))
(labels
, .
, . , Ergebnis NIL .
(and (consp body-rest) (loop-keywordp (first body-rest))))
(preamble (kind &optional form) (car (push (cons kind form) preamble)))
(cons-forward (form accuvar accufuncsym)
(let ((tailvar
(cdr (or (assoc accuvar accuvar-tailvar-alist)
(car (setq accuvar-tailvar-alist
(acons accuvar
(gensym (symbol-name accuvar))
accuvar-tailvar-alist))))))
(incrementvar (gensym "ADDLIST-")))
(push accuvar accu-vars-nil)
(push tailvar accu-vars-nil)
`(LET ((,incrementvar
,(ecase accufuncsym
(CONS `(LIST ,form))
(REVAPPEND `(COPY-LIST ,form))
(NRECONC `,form))))
(IF ,accuvar
,(case accufuncsym
(CONS `(SETF ,tailvar (SETF (CDR ,tailvar) ,incrementvar)))
(t `(SETF ,tailvar (LAST (RPLACD ,tailvar ,incrementvar)))))
,(case accufuncsym
(CONS `(SETF ,tailvar (SETF ,accuvar ,incrementvar)))
(t `(SETF ,tailvar (LAST (SETF ,accuvar
,incrementvar)))))))))
(compatible-p (kw1 kw2)
(let ((ht #,(make-hash-table
:warn-if-needs-rehash-after-gc t
:test 'stablehash-eq
:initial-contents
'((collect . list) (collecting . list)
(append . list) (appending . list)
(nconc . list) (nconcing . list)
(sum . sum-count) (summing . sum-count)
(count . sum-count) (counting . sum-count)
(maximize . max-min) (maximizing . max-min)
(minimize . max-min) (minimizing . max-min)))))
(eq (gethash kw1 ht) (gethash kw2 ht))))
(new-accu-var (var clause)
(let ((others (gethash var accu-table)) bad)
(when (setq bad (find (first clause) others
:key #'first :test-not #'compatible-p))
(error-of-type 'source-program-error
:form *whole* :detail clause
(TEXT "~S: variable ~S is used in incompatible clauses~{ ~A ~S~} and~{ ~A ~S~}")
*whole* var clause bad))
(setf (gethash var accu-table) (cons clause others))))
(new-result (form clause)
(let ((pair (assoc form results :test #'equal)))
(if pair
(push clause (cdr pair))
(push (list form clause) results))
results))
(acculist-var (keyword form)
(or acculist-var
(progn (setq acculist-var (gensym "ACCULIST-VAR-"))
(push acculist-var accu-vars-nil)
(let ((clause (list keyword form)))
(new-accu-var acculist-var clause)
(unless backward-consing-p
(new-result acculist-var clause)))
acculist-var)))
accuvar is NIL , accufuncsym is CONS
(let ((accuvar (acculist-var keyword form)))
(new-result `(SYS::LIST-NREVERSE ,accuvar) `(,keyword ,form))
`(SETQ ,accuvar (CONS ,form ,accuvar))))
, das Keyword kw .
, . , Ergebnis NIL .
(and (consp body-rest) (eq (loop-keywordp (first body-rest)) kw)
(progn (pop body-rest) t)))
Nach kw : expr
(unless (consp body-rest) (loop-syntax-error kw))
(pop body-rest))
Nach kw : expr , it ' sein kann
(unless (consp body-rest) (loop-syntax-error kw))
(let ((form (pop body-rest)))
(if (eq (loop-keywordp form) 'it)
(if *last-it*
(progn (setq *used-it* t) *last-it*)
form)
form)))
(unless (consp body-rest)
(error-of-type 'source-program-error
:form *whole* :detail body-rest
(TEXT "~S: missing variable.") 'loop))
(let ((pattern (pop body-rest))
(typedecl nil))
(block nil
(unless (consp body-rest) (return))
(case (loop-keywordp (first body-rest))
(setq typedecl (pop body-rest))
(unless (simple-type-p typedecl)
(warn (TEXT "~S: After ~S, ~S is interpreted as a type specification")
'loop pattern typedecl)))
OF - TYPE - > expect a typespec
(pop body-rest)
(setq typedecl (parse-form 'of-type)))
(setq typedecl (destructure-type pattern typedecl)))
(values pattern typedecl)))
(let ((list nil))
(loop
(unless (and (consp body-rest)
(not (loop-keywordp (first body-rest))))
(return))
(push (pop body-rest) list))
(nreverse list)))
(let ((exprs (parse-progn)))
(unless exprs
(if *loop-ansi*
(loop-syntax-error kw)
(warn (TEXT "~S: missing forms after ~A: permitted by CLtL2, forbidden by ANSI CL.") 'loop (symbol-name kw))))
exprs))
(let ((kw (next-kw)))
(case kw
((DO DOING)
(pop body-rest)
`(PROGN ,@(parse-nonempty-progn kw)))
((RETURN)
(pop body-rest)
`(RETURN-FROM ,block-name ,(parse-form-or-it kw)))
(t 'NIL))))
(or (parse-unconditional)
(let ((kw (next-kw)))
(case kw
((COLLECT COLLECTING APPEND APPENDING NCONC NCONCING)
(pop body-rest)
efficient backward - consing ( with nreverse at the end )
Also , / NCONC require forward - consing because
REVAPPEND / NRECONC drop the last atom in dotted lists
(let ((form (parse-form-or-it kw))
(accuvar nil)
(accufuncsym
(case kw
((COLLECT COLLECTING) 'CONS)
((APPEND APPENDING) 'REVAPPEND)
((NCONC NCONCING) 'NRECONC))))
(when (parse-kw-p 'into)
(unless (and (consp body-rest)
(symbolp (setq accuvar (pop body-rest))))
(loop-syntax-error 'into)))
named > forward - consing .
(cons-forward form accuvar accufuncsym))
((or (eq accufuncsym 'REVAPPEND)
(eq accufuncsym 'NRECONC)
(null backward-consing-p))
REVAPPEND / NRECONC now or before
(when backward-consing-p
(error "~s: internal error: backward consing should be illegal!" *whole*))
(cons-forward form (acculist-var kw form)
accufuncsym))
Unnamed acc var & CONS - > cons - backward
(cons-backward kw form)))))
((COUNT COUNTING SUM SUMMING MAXIMIZE MAXIMIZING
MINIMIZE MINIMIZING)
(pop body-rest)
(let* ((form (parse-form-or-it kw)) (type 'fixnum)
(accuvar nil) (clause (list kw form)))
(when (parse-kw-p 'into)
(unless (and (consp body-rest)
(symbolp (setq accuvar (pop body-rest))))
(loop-syntax-error 'into)))
(unless accuvar
(setq accuvar
(or accunum-var
(setq accunum-var (gensym "ACCUNUM-VAR-"))))
(new-result accuvar clause))
(new-accu-var accuvar clause)
(when (consp body-rest)
(let ((kw2 (loop-keywordp (first body-rest))))
(when (or (not kw2) (eq kw2 'of-type))
(setq type
(if (not kw2) (pop body-rest)
(progn (pop body-rest)
(parse-form 'of-type))))
(case kw
((MAXIMIZE MAXIMIZING MINIMIZE MINIMIZING)
NIL
(push `(TYPE ,type ,accuvar) accu-declarations))))
(case kw
((MAXIMIZE MAXIMIZING MINIMIZE MINIMIZING)
(push accuvar accu-vars-nil))
((COUNT COUNTING SUM SUMMING)
(push (list accuvar (coerce 0 type)) accu-vars-0)))
(case kw
((COUNT COUNTING) `(WHEN ,form (INCF ,accuvar)))
((SUM SUMMING) `(SETQ ,accuvar (+ ,accuvar ,form)))
((MAXIMIZE MAXIMIZING) `(SETQ ,accuvar (MAX-IF ,form ,accuvar)))
((MINIMIZE MINIMIZING) `(SETQ ,accuvar (MIN-IF ,form ,accuvar))))))
((IF WHEN UNLESS)
(pop body-rest)
(let* ((condition (parse-form kw))
(it-var (gensym "IT-"))
used-it
(true-form
(let ((*last-it* it-var) (*used-it* nil))
(prog1
(parse-clauses kw)
(setq used-it *used-it*))))
(false-form 'NIL))
(when (parse-kw-p 'else)
(setq false-form
(let ((*last-it* it-var) (*used-it* nil))
(prog1
(parse-clauses 'else)
(setq used-it (or used-it *used-it*))))))
(parse-kw-p 'end)
(when used-it
(psetq it-var `((,it-var ,condition))
condition it-var))
(let ((form
`(IF ,(if (eq kw 'UNLESS)
,true-form
,false-form)))
(if used-it `(LET ,it-var ,form) `,form))))
(t 'NIL)))))
Nach kw : clause { and clause } *
(let ((clauses nil))
(loop
(let ((clause (parse-clause)))
(unless clause (loop-syntax-error kw))
(push clause clauses))
(unless (parse-kw-p 'and) (return))
(setq kw 'and)
' it ' ist nur in der ersten Klausel gültig
`(PROGN ,@(nreverse clauses))))
- ( außer FOR - AS-= ) sind
mindestens alle vorherigen FOR - AS Variablen sichtbar .
- Variablen sind alle FOR - AS Variablen
Zusätzlich ist die folgende Grundregel wünschenswert :
- Variablen sind mindestens alle
vorherigen FOR - AS Variablen initialisiert und deren Abbruch-
bedingungen abgeprüft .
Man könnte erst alle i m preamble
die .
Optimierungen durch :
- Falls vor der FOR - ,
braucht die Variable zum Zeitpunkt ihrer Initialisierung nicht
sichtbar zu sein , und nach
vorne , zur . Das ,
- Falls eine Variable gar nicht sichtbar zu ,
FOR - AS-= und
stört , können die und die Initialiserung der
Variablen ins verschoben werden .
(note-initialization (initialization)
(when (or (li-bindings initialization)
(li-declspecs initialization)
(li-endtest-forms initialization))
(when seen-for-as-=
(setf (li-requires-stepbefore initialization) t))
(when (li-endtest-forms initialization)
(setq seen-endtest t))
(dolist (var (li-vars initialization))
(when (memq var var-list)
(error-of-type 'source-program-error
:form *whole* :detail var
(TEXT "~S: duplicate iteration variable ~S") *whole* var))
(push var var-list))
(push initialization initializations)))
(make-endtest (endtest-form)
(make-loop-init
:specform 'PROGN
:bindings nil
:declspecs nil
:endtest-forms (list endtest-form)
:everytime (setq stepafter-code (cons 'NIL stepafter-code))
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))
Los geht 's !
(when (parse-kw-p 'named)
(unless (and (consp body-rest) (symbolp (first body-rest)))
(loop-syntax-error 'named))
(setq block-name (pop body-rest)))
(loop
(unless (consp body-rest) (return))
(let ((clause (parse-clause)))
(if clause
(progn (setq already-within-main t) (push clause main-code))
(let ((kw (loop-keywordp (first body-rest))))
(case kw
((WHILE UNTIL ALWAYS NEVER THEREIS)
(pop body-rest)
(setq already-within-main t)
(let ((form (parse-form kw)))
(push (case kw
(WHILE `(UNLESS ,form (LOOP-FINISH)))
(UNTIL `(WHEN ,form (LOOP-FINISH)))
(ALWAYS
(new-result 'T (list kw form))
`(UNLESS ,form (RETURN-FROM ,block-name 'NIL)))
(NEVER
(new-result 'T (list kw form))
`(WHEN ,form (RETURN-FROM ,block-name 'NIL)))
(THEREIS
(let ((dummy (gensym "THEREIS-")))
(new-result 'NIL (list kw form))
`(BLOCK ,dummy
(RETURN-FROM ,block-name
(OR ,form (RETURN-FROM ,dummy NIL)))))))
main-code)))
((INITIALLY)
(pop body-rest)
(preamble :INITIALLY `(PROGN ,@(parse-nonempty-progn kw))))
((FINALLY)
(pop body-rest)
(push (let ((form (parse-unconditional)))
(if form
(if *loop-ansi*
(loop-syntax-error 'FINALLY)
(warn (TEXT "~S: loop keyword immediately after ~A: permitted by CLtL2, forbidden by ANSI CL.") 'loop (symbol-name kw)))
(setq form `(PROGN ,@(parse-nonempty-progn kw))))
form)
finally-code))
((WITH FOR AS REPEAT)
(pop body-rest)
(when already-within-main
(warn (TEXT "~S: ~A clauses should occur before the loop's main body")
'loop (symbol-name kw)))
(case kw
((WITH)
(let ((bindings nil)
(declspecs nil))
(loop
(let (new-bindings)
(multiple-value-bind (pattern new-declspecs) (parse-var-typespec)
(if (parse-kw-p '=)
(let ((form (parse-form '=)))
(setq new-bindings (destructure pattern form)))
keine Initialisierungsform angegeben .
(setq new-bindings (default-bindings (destructure-vars pattern) new-declspecs)))
(setq bindings (revappend new-bindings bindings))
(setq declspecs (revappend new-declspecs declspecs))))
(unless (parse-kw-p 'and) (return))
(setq kw 'and))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (nreverse bindings)
:declspecs (nreverse declspecs)
:everytime nil
:preamble (preamble :start)
:depends-preceding t))))
((FOR AS)
[ { from | downfrom | upfrom } expr ]
(let ((bindings nil)
(declspecs nil)
(initializations nil)
(stepafter nil)
(old-seen-endtest seen-endtest)
(preamble-entry (preamble :start))
(depends-preceding nil))
(flet ((note-initialization (initialization)
(when (li-endtest-forms initialization)
(setq seen-endtest t))
(push initialization initializations)))
(loop
(multiple-value-bind (pattern new-declspecs) (parse-var-typespec)
(let ((preposition (next-kw)))
(case preposition
((IN ON)
(pop body-rest)
(let ((start-form (parse-form preposition))
(step-function-form '(FUNCTION CDR))
(step-function-var nil))
(when (parse-kw-p 'by)
(setq step-function-form (parse-form 'by))
(unless (and (function-form-p step-function-form)
(function-name-p (second step-function-form)))
(setq step-function-var (gensym "BY-"))))
(let ((var (if (and pattern (symbolp pattern)
(eq preposition 'ON))
pattern (gensym "LIST-"))))
(push `(,var ,start-form) bindings)
(when step-function-var
(push `(,step-function-var ,step-function-form)
bindings))
(note-initialization
(make-endtest
`(WHEN (,(if (eq preposition 'IN)
'ENDP 'ATOM)
,var)
(LOOP-FINISH))))
(unless (eq var pattern)
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern (if (eq preposition 'IN) `(CAR ,var) var))
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))
(push
(list var
(if step-function-var
`(FUNCALL ,step-function-var ,var)
`(,(second step-function-form) ,var)))
stepafter))))
(=
(pop body-rest)
(let* ((first-form (parse-form 'preposition))
(then-form first-form))
(when (parse-kw-p 'then)
(setq then-form (parse-form 'then)))
(setq bindings
(revappend (destructure pattern first-form)
bindings))
(setq declspecs (revappend new-declspecs declspecs))
(unless (and (constantp first-form)
(constantp then-form))
(setq seen-for-as-= t)
Even when ` first - form ' is constant but
` stepafter - code ' to ` stepbefore - code . '
(setq depends-preceding t))
(setq stepafter (revappend (destructure pattern then-form) stepafter))))
(ACROSS
(pop body-rest)
(let ((vector-form (parse-form preposition))
(vector-var (gensym "VECTOR-"))
(index-var (gensym "INDEX-")))
(push `(,vector-var ,vector-form) bindings)
(push `(,index-var 0) bindings)
(note-initialization
(make-endtest `(WHEN (>= ,index-var (LENGTH ,vector-var)) (LOOP-FINISH))))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern `(AREF ,vector-var ,index-var))
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(push (list index-var `(1+ ,index-var)) stepafter)))
(BEING
(pop body-rest)
(let ((plural (next-kw)))
(case plural
((EACH THE))
(t (loop-syntax-error 'being)))
(pop body-rest)
(let ((preposition (next-kw)))
(case preposition
((HASH-KEY HASH-VALUE
SYMBOL PRESENT-SYMBOL INTERNAL-SYMBOL EXTERNAL-SYMBOL)
(when (eq plural 'THE)
(warn (TEXT "~S: After ~S a plural loop keyword is required, not ~A")
'loop plural (symbol-name preposition))))
((HASH-KEYS HASH-VALUES
SYMBOLS PRESENT-SYMBOLS INTERNAL-SYMBOLS EXTERNAL-SYMBOLS)
(when (eq plural 'EACH)
(warn (TEXT "~S: After ~S a singular loop keyword is required, not ~A")
'loop plural (symbol-name preposition))))
(t (loop-syntax-error plural)))
(pop body-rest)
(case preposition
((HASH-KEY HASH-KEYS HASH-VALUE HASH-VALUES)
(let ((other-pattern nil)
(form
(case (next-kw)
((IN OF) (pop body-rest)
(parse-form preposition))
(t (loop-syntax-error
preposition)))))
(when (parse-kw-p 'using)
(unless (and (consp body-rest)
(consp (car body-rest))
(consp (cdar body-rest))
(null (cddar body-rest))
(case (loop-keywordp (caar body-rest))
((HASH-KEY HASH-KEYS)
(case preposition
((HASH-VALUE HASH-VALUES) t) (t nil)))
((HASH-VALUE HASH-VALUES)
(case preposition
((HASH-KEY HASH-KEYS) t) (t nil)))))
(loop-syntax-error 'using))
(setq other-pattern (second (pop body-rest))))
(let ((state-var (gensym "WHTI-"))
(nextp-var (gensym "MORE?"))
(nextkey-var (gensym "HASH-KEY-"))
(nextvalue-var (gensym "HASH-VALUE-")))
(multiple-value-bind (nextmain-var nextother-var)
(case preposition
((HASH-KEY HASH-KEYS) (values nextkey-var nextvalue-var))
((HASH-VALUE HASH-VALUES) (values nextvalue-var nextkey-var)))
(push `(,state-var (SYS::HASH-TABLE-ITERATOR ,form)) bindings)
(note-initialization
(make-loop-init
:specform 'MULTIPLE-VALUE-BIND
:bindings `((,nextp-var ,nextkey-var ,nextvalue-var)
(SYS::HASH-TABLE-ITERATE ,state-var))
:declspecs (unless other-pattern `((IGNORE ,nextother-var)))
:endtest-forms `((UNLESS ,nextp-var (LOOP-FINISH)))
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern nextmain-var)
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(when other-pattern
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure other-pattern nextother-var)
:declspecs nil
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))))))
((SYMBOL SYMBOLS PRESENT-SYMBOL PRESENT-SYMBOLS
INTERNAL-SYMBOL INTERNAL-SYMBOLS EXTERNAL-SYMBOL EXTERNAL-SYMBOLS)
(let ((flags (case preposition
((SYMBOL SYMBOLS) '(:internal :external :inherited))
((PRESENT-SYMBOL PRESENT-SYMBOLS) '(:internal :external))
((INTERNAL-SYMBOL INTERNAL-SYMBOLS) '(:internal))
((EXTERNAL-SYMBOL EXTERNAL-SYMBOLS) '(:external))))
(state-var (gensym "WPI-"))
(nextp-var (gensym "MORE?"))
(nextsym-var (gensym "SYMBOL-"))
(form
(case (next-kw)
((IN OF) (pop body-rest)
(parse-form preposition))
(t '*package*))))
(push `(,state-var (SYS::PACKAGE-ITERATOR ,form ',flags))
bindings)
(note-initialization
(make-loop-init
:specform 'MULTIPLE-VALUE-BIND
:bindings `((,nextp-var ,nextsym-var)
(SYS::PACKAGE-ITERATE ,state-var))
:declspecs nil
:endtest-forms `((UNLESS ,nextp-var (LOOP-FINISH)))
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern nextsym-var)
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))))))))
(t
(unless (symbolp pattern) (loop-syntax-error kw))
(unless pattern (setq pattern (gensym "FOR-NUM-")))
ANSI CL 6.1.2.1.1 implies that the
order , but only one of each kind .
(let ((step-start-p nil)
(step-end-p nil)
(step-by-p nil)
step-start-form
step-end-form
step-by-form
step-end-preposition
dir)
(loop
(cond ((and (not step-start-p)
(setq dir (case preposition
(FROM 't)
(UPFROM 'up)
(DOWNFROM 'down)
(t nil))))
(setq step-start-p dir)
(pop body-rest)
(setq step-start-form (parse-form preposition))
(push `(,pattern ,step-start-form) bindings))
((and (not step-end-p)
(setq dir (case preposition
(TO 't)
((UPTO BELOW) 'up)
((DOWNTO ABOVE) 'down)
(t nil))))
(setq step-end-p dir)
(setq step-end-preposition preposition)
(pop body-rest)
(setq step-end-form (parse-form preposition))
(unless (constantp step-end-form)
(let ((step-end-var (gensym "LIMIT-")))
(push `(,step-end-var ,step-end-form) bindings)
(setq step-end-form step-end-var))))
((and (not step-by-p)
(eq preposition 'BY))
(setq step-by-p t)
(pop body-rest)
(setq step-by-form (parse-form 'by))
(unless (constantp step-by-form)
(let ((step-by-var (gensym "BY-")))
(push `(,step-by-var ,step-by-form) bindings)
(setq step-by-form step-by-var))))
(t (return)))
(setq preposition (next-kw)))
(setq declspecs (revappend new-declspecs declspecs))
(let ((step-direction
(if (or (eq step-start-p 'down) (eq step-end-p 'down))
(if (or (eq step-start-p 'up) (eq step-end-p 'up))
(error-of-type 'source-program-error
:form *whole* :detail kw
(TEXT "~S: questionable iteration direction after ~A")
'loop (symbol-name kw))
'down)
'up)))
(unless step-start-p
(when (eq step-direction 'down)
Abwärtsiteration ohne Startwert ist nicht erlaubt .
Die zweite optionale Klausel ( d.h . preposition ) muss .
(error-of-type 'source-program-error
:form *whole* :detail preposition
(TEXT "~S: specifying ~A requires FROM or DOWNFROM")
'loop (symbol-name preposition)))
(setq step-start-form '0)
(push `(,pattern ,step-start-form) bindings))
(unless step-by-p (setq step-by-form '1))
(when step-end-p
(let* ((compfun
(if (eq step-direction 'up)
(endtest
(if (and (constantp step-end-form) (zerop (eval step-end-form)))
(case compfun
(>= `(NOT (MINUSP ,pattern)))
(> `(PLUSP ,pattern))
(<= `(NOT (PLUSP ,pattern)))
(< `(MINUSP ,pattern)))
`(,compfun ,pattern ,step-end-form))))
(note-initialization
(make-endtest `(WHEN ,endtest (LOOP-FINISH))))))
(push
(list pattern `(,(if (eq step-direction 'up) '+ '-) ,pattern ,step-by-form))
stepafter)))))))
(unless (parse-kw-p 'and) (return))
(setq kw 'and)
(case (next-kw) ((FOR AS) (pop body-rest)))))
(when (setq stepafter (apply #'append (nreverse stepafter)))
(push `(PSETQ ,@stepafter) stepafter-code))
Markierung für spätere Initialisierungen
(make-loop-init
:specform 'LET
:bindings (nreverse bindings)
:declspecs (nreverse declspecs)
:everytime nil
:requires-stepbefore old-seen-endtest
:preamble preamble-entry
:depends-preceding depends-preceding))
(dolist (initialization (nreverse initializations))
(when (li-everytime initialization)
(setf (li-everytime initialization) stepafter-code))
(note-initialization initialization))))
((REPEAT)
(let ((form (parse-form kw))
(var (gensym "COUNT-")))
(note-initialization
(make-loop-init
:specform 'LET
:bindings `((,var ,form))
:declspecs nil
:everytime nil
:requires-stepbefore seen-endtest
:preamble (preamble :start)
:depends-preceding t))
(push `(SETQ ,var (1- ,var)) stepafter-code)
(note-initialization
(make-endtest `(UNLESS (PLUSP ,var) (LOOP-FINISH))))))))
(t (error-of-type 'source-program-error
:form *whole* :detail *whole*
(TEXT "~S: illegal syntax near ~S in ~S")
'loop (first body-rest) *whole*)))))))
(when (> (length results) 1)
(error-of-type 'source-program-error
:form *whole* :detail *whole*
(TEXT "~S: ambiguous result:~:{~%~S from ~@{~{~A ~S~}~^, ~}~}")
*whole* results))
(unless (null results)
(push `(RETURN-FROM ,block-name ,(caar results)) finally-code))
Initialisierungen abarbeiten und optimieren :
(let ((initializations1
(unless (zerop (length *helpvars*))
(list (make-loop-init
:specform 'LET
:preamble (preamble :start)
:bindings
(map 'list #'(lambda (var) `(,var NIL)) *helpvars*))))))
(let ((later-depend nil))
(dolist (initialization initializations)
(when later-depend (setf (li-later-depend initialization) t))
(when (li-depends-preceding initialization)
(setq later-depend t))))
(dolist (initialization (nreverse initializations))
(let* ((everytime (li-everytime initialization))
(requires-stepbefore (li-requires-stepbefore initialization))
(name (li-specform initialization))
(bindings (li-bindings initialization))
(declarations (li-declspecs initialization))
(vars (case name
(MULTIPLE-VALUE-BIND (first bindings))
(LET (mapcar #'first bindings))))
(initforms
(case name
(MULTIPLE-VALUE-BIND `((MULTIPLE-VALUE-SETQ ,@bindings)))
(LET `((SETQ ,@(apply #'append bindings))))
(t '())))
(endtest-forms (li-endtest-forms initialization)))
(if requires-stepbefore
(progn
(push
(make-loop-init
:specform 'LET
:bindings (default-bindings vars declarations)
:preamble (preamble :start)
:declspecs declarations)
initializations1)
(if everytime
(if (li-later-depend initialization)
(revadd (cdr (li-preamble initialization))
endtest-forms initforms)
(revadd (cdr everytime) endtest-forms initforms))
(revadd stepbefore-code endtest-forms initforms))
(revadd (cdr (li-preamble initialization))
endtest-forms initforms)))
Initialisierungsklausel nach initializations1 :
(progn
(push
(make-loop-init
:specform name
:bindings bindings
:preamble (preamble :start)
:declspecs declarations)
initializations1)
(if everytime
(progn
(revadd (cdr everytime) initforms)
(if (li-later-depend initialization)
(revadd (cdr (li-preamble initialization))
endtest-forms)
(revadd (cdr everytime) endtest-forms))
(revadd stepbefore-code endtest-forms)))
(revadd (cdr (li-preamble initialization)) endtest-forms))))))
(flet ((check-accu-var (var)
(when (memq var var-list)
(error-of-type 'source-program-error
:form *whole* :detail var
(TEXT "~S: accumulation variable ~S is already bound")
*whole* var))))
(push
(make-loop-init
:specform 'LET
:bindings
`(,@(mapcar #'(lambda (var) (check-accu-var var) `(,var NIL))
(delete-duplicates accu-vars-nil))
,@(mapcar #'(lambda (var) (check-accu-var (car var)) var)
(delete-duplicates accu-vars-0 :key #'car)))
:preamble (preamble :start)
:declspecs (nreverse accu-declarations))
initializations1))
(setq preamble
(mapcan (lambda (rec)
(case (car rec)
(:start (nreverse
(mapcar (lambda (f) (cons :start f))
(cdr rec))))
(:initially (list rec))))
preamble))
Remove the NIL placeholders in stepafter - code .
(setq stepafter-code (delete 'NIL stepafter-code))
forms , drag these forms across the label to stepbefore - code .
(or (eql form1 form2)
(and (consp form1) (consp form2)
(eql (length form1) (length form2))
(or (eq (car form1) (car form2))
(and (case (length form1) ((1 3) t))
(case (car form1) ((SETQ PSETQ) t))
(case (car form2) ((SETQ PSETQ) t))))
(every #'eq (cdr form1) (cdr form2))))))
(loop
(unless (and (consp preamble) (consp stepafter-code)
(eq :start (caar preamble))
(form-eq (cdar preamble) (car stepafter-code)))
(return))
(setq stepbefore-code
(nconc stepbefore-code (list (pop stepafter-code))))
(pop preamble)))
`(MACROLET ((LOOP-FINISH () (LOOP-FINISH-ERROR)))
(BLOCK ,block-name
,(wrap-initializations initializations1
`(MACROLET ((LOOP-FINISH () '(GO END-LOOP)))
(TAGBODY
,@(if preamble (nreverse (mapcar #'cdr preamble)))
BEGIN-LOOP
,@(if stepbefore-code (nreverse stepbefore-code))
,(cons 'PROGN (nreverse main-code))
,@(if stepafter-code (nreverse stepafter-code))
(GO BEGIN-LOOP)
END-LOOP
,@(mapcar #'(lambda (var)
`(SETQ ,var (SYS::LIST-NREVERSE ,var)))
accu-vars-nreverse)
(MACROLET ((LOOP-FINISH () (LOOP-FINISH-WARN)
'(GO END-LOOP)))
,@(nreverse finally-code)))))))))))
(defmacro loop (&whole whole &body body)
(if (some #'atom body)
(expand-loop whole body)
(let ((tag (gensym "LOOP-")))
`(BLOCK NIL (TAGBODY ,tag ,@body (GO ,tag))))))
(defmacro loop-finish (&whole whole)
(error (TEXT "~S is possible only from within ~S")
whole 'loop))
(defun loop-finish-warn ()
(warn (TEXT "Use of ~S in FINALLY clauses is deprecated because it can lead to infinite loops.")
'(loop-finish)))
(defun loop-finish-error ()
(error (TEXT "~S is not possible here")
'(loop-finish)))
Run - Time - Support :
ABI
(if y (max x y) x))
ABI
(if y (min x y) x))
|
8f2458a7c3cf66c7667b4845294ea13ea78aa2d0dd1d3b1c691bddf9e00cdd51 | vikram/lisplibraries | window.lisp | ;; -*- lisp -*-
(in-package :it.bese.ucw)
;;;; ** Simple Window
(defclass window-component ()
((content-type :accessor window-component.content-type
:initarg :content-type
:initform nil ; default is text/html with charset from current application
:documentation "The Content-Type header for the
http response (also used in the meta tag)")))
(defmethod window-component.content-type ((window window-component))
"Either use slot value, or compute content-type from current application charset."
(or (slot-value window 'content-type)
(format nil "text/html~@[; charset=~A~]"
(application.charset (context.application *context*)))))
(defmethod render :before ((window window-component))
(setf (get-header (context.response *context*) "Content-Type")
(window-component.content-type window)))
(defclass simple-window-component (window-component)
((title :accessor window-component.title
:initarg :title
:initform nil )
(stylesheet :accessor window-component.stylesheet
:initarg :stylesheet
:initform nil
:documentation "The URL of the css file to use as a stylesheet for this window.")
(icon :accessor window-component.icon
:initarg :icon
:initform nil
:documentation "Optional URL for an icon.")
(doctype :accessor window-component.doctype
:initarg :doctype
:initform "-//W3C//DTD XHTML 1.0 Transitional//EN\" \""
:documentation "Doctype for this window.")
(javascript :accessor window-component.javascript
:initarg :javascript
:initform nil
:documentation "List of javascript includes.
Each element must be a list whose first value is either the
symbol :SRC or :JS.
(:SRC url) - writes <script src=\"URL\"></script> tag.
(:JS form) - equivalent to (:SCRIPT (js:js* form))
(:SCRIPT string) - write <script>STRING</script>.
The elements will be rendered in order."))
(:metaclass standard-component-class)
(:documentation "A convenience class for writing window components."))
(defmethod render :wrapping ((window simple-window-component))
"This convience method assumes: 1) the stylesheet is
2 ) the script
file is javascript and is external or is no script is used and 3)
the title is simply the value of the title slot in the WINDOW (no
dynamic titles)."
(<:as-is "<!DOCTYPE html PUBLIC \"" (window-component.doctype window) "\">"
#\Newline)
(<:html :prologue nil
(<:head
(<:meta :http-equiv "Content-Type" :content (window-component.content-type window))
(<:title (<:as-html (window-component.title window)))
(awhen (window-component.icon window)
(<:link :rel "icon"
:type "image/x-icon"
:href it))
(dolist (stylesheet (ensure-list (window-component.stylesheet window)))
(<:link :rel "stylesheet"
:href stylesheet
:type "text/css"))
(let* ((app (context.application *context*))
(url-prefix (application.url-prefix app)))
(<ucw:script `(setf dj-config (create
:is-debug ,(if (debug-on-error app)
'true
'false)
:base-loader-uri ,(strcat url-prefix "dojo/"))))
(<:script :type "text/javascript" :src (strcat url-prefix "dojo/dojo.js"))
(<:script :type "text/javascript" :src (strcat url-prefix "ucw/js/per-application.js"))
(dolist* ((type value &key with-url-prefix) (window-component.javascript window))
(ecase type
(:src
most browsers ( firefox , safari and ie at least ) really ,
;; really, really don't like empty script tags. The "" forces
;; yaclml to generate a seperate closing tag.
(<:script :type "text/javascript" :src (if with-url-prefix
(strcat url-prefix value)
value)
""))
(:js
(<:script :type "text/javascript" (<:as-is (js:js* value))))
(:script
(<:script :type "text/javascript" (<:as-is value)))))))
(<:body (call-next-method))))
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_dev/src/components/window.lisp | lisp | -*- lisp -*-
** Simple Window
default is text/html with charset from current application
really, really don't like empty script tags. The "" forces
yaclml to generate a seperate closing tag.
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. |
(in-package :it.bese.ucw)
(defclass window-component ()
((content-type :accessor window-component.content-type
:initarg :content-type
:documentation "The Content-Type header for the
http response (also used in the meta tag)")))
(defmethod window-component.content-type ((window window-component))
"Either use slot value, or compute content-type from current application charset."
(or (slot-value window 'content-type)
(format nil "text/html~@[; charset=~A~]"
(application.charset (context.application *context*)))))
(defmethod render :before ((window window-component))
(setf (get-header (context.response *context*) "Content-Type")
(window-component.content-type window)))
(defclass simple-window-component (window-component)
((title :accessor window-component.title
:initarg :title
:initform nil )
(stylesheet :accessor window-component.stylesheet
:initarg :stylesheet
:initform nil
:documentation "The URL of the css file to use as a stylesheet for this window.")
(icon :accessor window-component.icon
:initarg :icon
:initform nil
:documentation "Optional URL for an icon.")
(doctype :accessor window-component.doctype
:initarg :doctype
:initform "-//W3C//DTD XHTML 1.0 Transitional//EN\" \""
:documentation "Doctype for this window.")
(javascript :accessor window-component.javascript
:initarg :javascript
:initform nil
:documentation "List of javascript includes.
Each element must be a list whose first value is either the
symbol :SRC or :JS.
(:SRC url) - writes <script src=\"URL\"></script> tag.
(:JS form) - equivalent to (:SCRIPT (js:js* form))
(:SCRIPT string) - write <script>STRING</script>.
The elements will be rendered in order."))
(:metaclass standard-component-class)
(:documentation "A convenience class for writing window components."))
(defmethod render :wrapping ((window simple-window-component))
"This convience method assumes: 1) the stylesheet is
2 ) the script
file is javascript and is external or is no script is used and 3)
the title is simply the value of the title slot in the WINDOW (no
dynamic titles)."
(<:as-is "<!DOCTYPE html PUBLIC \"" (window-component.doctype window) "\">"
#\Newline)
(<:html :prologue nil
(<:head
(<:meta :http-equiv "Content-Type" :content (window-component.content-type window))
(<:title (<:as-html (window-component.title window)))
(awhen (window-component.icon window)
(<:link :rel "icon"
:type "image/x-icon"
:href it))
(dolist (stylesheet (ensure-list (window-component.stylesheet window)))
(<:link :rel "stylesheet"
:href stylesheet
:type "text/css"))
(let* ((app (context.application *context*))
(url-prefix (application.url-prefix app)))
(<ucw:script `(setf dj-config (create
:is-debug ,(if (debug-on-error app)
'true
'false)
:base-loader-uri ,(strcat url-prefix "dojo/"))))
(<:script :type "text/javascript" :src (strcat url-prefix "dojo/dojo.js"))
(<:script :type "text/javascript" :src (strcat url-prefix "ucw/js/per-application.js"))
(dolist* ((type value &key with-url-prefix) (window-component.javascript window))
(ecase type
(:src
most browsers ( firefox , safari and ie at least ) really ,
(<:script :type "text/javascript" :src (if with-url-prefix
(strcat url-prefix value)
value)
""))
(:js
(<:script :type "text/javascript" (<:as-is (js:js* value))))
(:script
(<:script :type "text/javascript" (<:as-is value)))))))
(<:body (call-next-method))))
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
|
60c05da26d535528dfa0b1687463fdb21bd3fb80c0295dc95f602c45bee4ad91 | ekmett/data-lens | Lazy.hs | module Data.Lens.Lazy
( module Data.Lens.Common
-- * State API
getter -- : : = > Lens a b - > StateT a m b
setter -- : : = > Lens a b - > b - > StateT a m b
modify -- : : = > Lens a b - > ( b - > b ) - > StateT a m b
modify -- : : = > Lens a b - > ( b - > ( c , b ) ) - > StateT a m c
modify -- : : ( , ) = > Lens a b - > b - > StateT a m b
modify -- : : ( , ) = > Lens a b - > b - > StateT a m b
modify -- : : ( , ) = > Lens a b - > b - > StateT a m b
modify -- : : ( , Fractional b ) = > Lens a b - > b - > StateT a m b
modify -- : : = > Lens a Bool - > Bool - > StateT a m Bool
modify -- : : = > Lens a Bool - > Bool - > StateT a m Bool
modify -- : : = > Lens a b - > StateT m b c - > StateT m a c
) where
import Control.Comonad.Trans.Store
import Control.Monad.Trans.State
import Control.Monad (liftM)
import Data.Functor.Identity
import Data.Lens.Common
-- * State actions
-- | get the value of a lens into state
access :: Monad m => Lens a b -> StateT a m b
access (Lens f) = gets (pos . f)
# INLINE access #
focus :: Monad m => Lens a b -> StateT b m c -> StateT a m c
focus (Lens f) (StateT g) = StateT $ \a -> case f a of
StoreT (Identity h) b -> liftM (\(c, b') -> (c, h b')) (g b)
infixr 4 ~=, !=
-- | set a value using a lens into state
(~=), (!=) :: Monad m => Lens a b -> b -> StateT a m b
Lens f ~= b = StateT $ \a -> let c = peek b (f a) in
return (b, c)
Lens f != b = StateT $ \a -> case f a of
StoreT (Identity h) _ -> let c = h $! b in
return (b, c)
infixr 4 %=, !%=
-- | infix modification a value through a lens into state
(%=), (!%=) :: Monad m => Lens a b -> (b -> b) -> StateT a m b
Lens f %= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> let b' = g b in
return (b', h b')
Lens f !%= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> let b' = g b in
b' `seq` return (b', h b')
infixr 4 %%=, !%%=
-- | infix modification of a value through a lens into state
-- with a supplemental response
(%%=), (!%%=) :: Monad m => Lens a b -> (b -> (c, b)) -> StateT a m c
Lens f %%= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> case g b of
(c, b') -> return (c, h b')
Lens f !%%= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> case g b of
(c, b') -> return (c, h $! b')
infixr 4 +=, !+=, -=, !-=, *=, !*=
(+=), (!+=), (-=), (!-=), (*=), (!*=) :: (Monad m, Num b) => Lens a b -> b -> StateT a m b
f += b = f %= (+ b)
f -= b = f %= subtract b
f *= b = f %= (* b)
f !+= b = f !%= (+ b)
f !-= b = f !%= subtract b
f !*= b = f !%= (* b)
infixr 4 //=, !/=
(//=), (!/=) :: (Monad m, Fractional b) => Lens a b -> b -> StateT a m b
f //= b = f %= (/ b)
f !/= b = f !%= (/ b)
infixr 4 &&=, !&&=, ||=, !||=
(&&=), (||=), (!&&=), (!||=) :: Monad m => Lens a Bool -> Bool -> StateT a m Bool
f &&= b = f %= (&& b)
f ||= b = f %= (|| b)
f !&&= b = f !%= (&& b)
f !||= b = f !%= (|| b)
| null | https://raw.githubusercontent.com/ekmett/data-lens/7df83abbf3b55f08791733d41d676eac42d0adb9/Data/Lens/Lazy.hs | haskell | * State API
: : = > Lens a b - > StateT a m b
: : = > Lens a b - > b - > StateT a m b
: : = > Lens a b - > ( b - > b ) - > StateT a m b
: : = > Lens a b - > ( b - > ( c , b ) ) - > StateT a m c
: : ( , ) = > Lens a b - > b - > StateT a m b
: : ( , ) = > Lens a b - > b - > StateT a m b
: : ( , ) = > Lens a b - > b - > StateT a m b
: : ( , Fractional b ) = > Lens a b - > b - > StateT a m b
: : = > Lens a Bool - > Bool - > StateT a m Bool
: : = > Lens a Bool - > Bool - > StateT a m Bool
: : = > Lens a b - > StateT m b c - > StateT m a c
* State actions
| get the value of a lens into state
| set a value using a lens into state
| infix modification a value through a lens into state
| infix modification of a value through a lens into state
with a supplemental response | module Data.Lens.Lazy
( module Data.Lens.Common
) where
import Control.Comonad.Trans.Store
import Control.Monad.Trans.State
import Control.Monad (liftM)
import Data.Functor.Identity
import Data.Lens.Common
access :: Monad m => Lens a b -> StateT a m b
access (Lens f) = gets (pos . f)
# INLINE access #
focus :: Monad m => Lens a b -> StateT b m c -> StateT a m c
focus (Lens f) (StateT g) = StateT $ \a -> case f a of
StoreT (Identity h) b -> liftM (\(c, b') -> (c, h b')) (g b)
infixr 4 ~=, !=
(~=), (!=) :: Monad m => Lens a b -> b -> StateT a m b
Lens f ~= b = StateT $ \a -> let c = peek b (f a) in
return (b, c)
Lens f != b = StateT $ \a -> case f a of
StoreT (Identity h) _ -> let c = h $! b in
return (b, c)
infixr 4 %=, !%=
(%=), (!%=) :: Monad m => Lens a b -> (b -> b) -> StateT a m b
Lens f %= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> let b' = g b in
return (b', h b')
Lens f !%= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> let b' = g b in
b' `seq` return (b', h b')
infixr 4 %%=, !%%=
(%%=), (!%%=) :: Monad m => Lens a b -> (b -> (c, b)) -> StateT a m c
Lens f %%= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> case g b of
(c, b') -> return (c, h b')
Lens f !%%= g = StateT $ \a -> case f a of
StoreT (Identity h) b -> case g b of
(c, b') -> return (c, h $! b')
infixr 4 +=, !+=, -=, !-=, *=, !*=
(+=), (!+=), (-=), (!-=), (*=), (!*=) :: (Monad m, Num b) => Lens a b -> b -> StateT a m b
f += b = f %= (+ b)
f -= b = f %= subtract b
f *= b = f %= (* b)
f !+= b = f !%= (+ b)
f !-= b = f !%= subtract b
f !*= b = f !%= (* b)
infixr 4 //=, !/=
(//=), (!/=) :: (Monad m, Fractional b) => Lens a b -> b -> StateT a m b
f //= b = f %= (/ b)
f !/= b = f !%= (/ b)
infixr 4 &&=, !&&=, ||=, !||=
(&&=), (||=), (!&&=), (!||=) :: Monad m => Lens a Bool -> Bool -> StateT a m Bool
f &&= b = f %= (&& b)
f ||= b = f %= (|| b)
f !&&= b = f !%= (&& b)
f !||= b = f !%= (|| b)
|
8f40d78788ad775c86f69052cf3b918c7428da9d24de8bedb7cf40571fa075d3 | stonebuddha/eopl | main.ml | open Support
open Syntax
open Core
let main () =
try Stream.of_channel (open_in Sys.argv.(1)) |> parse |> value_of_program
with Invalid_argument msg -> print_endline "Usage: THIS filename"; exit 1
| Sys_error msg -> print_endline msg; exit 1
| Ploc.Exc (loc, Stream.Error msg) -> print_endline (string_of_loc loc ^ ": [bad syntax] " ^ msg); exit 1
| Interpreter_error (msg, loc) -> print_endline (string_of_loc loc ^ ": [runtime error] " ^ msg); exit 1
let () = main ()
| null | https://raw.githubusercontent.com/stonebuddha/eopl/88ea636110421706f900e753c30240ff1ea26f67/PROC-EXT/main.ml | ocaml | open Support
open Syntax
open Core
let main () =
try Stream.of_channel (open_in Sys.argv.(1)) |> parse |> value_of_program
with Invalid_argument msg -> print_endline "Usage: THIS filename"; exit 1
| Sys_error msg -> print_endline msg; exit 1
| Ploc.Exc (loc, Stream.Error msg) -> print_endline (string_of_loc loc ^ ": [bad syntax] " ^ msg); exit 1
| Interpreter_error (msg, loc) -> print_endline (string_of_loc loc ^ ": [runtime error] " ^ msg); exit 1
let () = main ()
| |
949c98a380ffab6a7240f78b79b4583ffc488149edacd6730ee5e4b75e4eaa15 | fractalide/fractalide | choice.rkt | #lang racket/base
(require fractalide/modules/rkt/rkt-fbp/agent
fractalide/modules/rkt/rkt-fbp/agents/gui/helper)
(require racket/gui/base
racket/match)
(require (prefix-in class: racket/class))
(define base-default
(hash 'label #f
'choices '()
'selection 0
'style '()
'font normal-control-font
'enabled #t
'vert-margin 2
'horiz-margin 2
'min-width #f
'min-height #f
'stretchable-width #f
'stretchable-height #f))
(define (generate input data)
(lambda (frame)
(define default (for/fold ([acc base-default])
([d data])
(hash-set acc (car d) (cdr d))))
(let* ([cb (class:new (with-event choice% input) [parent frame]
[label (hash-ref default 'label)]
[choices (hash-ref default 'choices)]
[selection (hash-ref default 'selection)]
[style (hash-ref default 'style)]
[font (hash-ref default 'font)]
[enabled (hash-ref default 'enabled)]
[vert-margin (hash-ref default 'vert-margin)]
[horiz-margin (hash-ref default 'horiz-margin)]
[min-width (hash-ref default 'min-width)]
[min-height (hash-ref default 'min-height)]
[stretchable-width (hash-ref default 'stretchable-width)]
[stretchable-height (hash-ref default 'stretchable-height)]
[callback (lambda (button event)
(send (input "in") (cons (class:send event get-event-type)
(class:send button get-string-selection))))])])
(send (input "acc") cb))))
(define (process-msg msg widget input output output-array)
(define managed #f)
(set! managed (area-manage widget msg output output-array))
(set! managed (or managed (subarea-manage widget msg output output-array)))
(set! managed (or managed (window-manage widget msg output output-array)))
(set! managed (or managed (list-control-manage widget msg output output-array)))
(if managed
(void)
(match msg
[(cons 'set-choices choices)
(class:send widget clear)
(for ([choice choices]) (class:send widget append choice))
(class:send widget refresh)]
[(cons 'get-selection act)
(send-action output output-array (cons act (class:send widget get-selection)))]
[(cons 'set-selection n)
(class:send widget set-selection n)]
[else (send-action output output-array msg)])))
(define-agent
#:input '("in") ; in port
#:output '("out") ; out port
#:output-array '("out")
(define acc (try-recv (input "acc")))
(define msg (recv (input "in")))
(set! acc (manage acc msg input output output-array generate process-msg))
(send (output "acc") acc))
| null | https://raw.githubusercontent.com/fractalide/fractalide/9c54ec2615fcc2a1f3363292d4eed2a0fcb9c3a5/modules/rkt/rkt-fbp/agents/gui/choice.rkt | racket | in port
out port | #lang racket/base
(require fractalide/modules/rkt/rkt-fbp/agent
fractalide/modules/rkt/rkt-fbp/agents/gui/helper)
(require racket/gui/base
racket/match)
(require (prefix-in class: racket/class))
(define base-default
(hash 'label #f
'choices '()
'selection 0
'style '()
'font normal-control-font
'enabled #t
'vert-margin 2
'horiz-margin 2
'min-width #f
'min-height #f
'stretchable-width #f
'stretchable-height #f))
(define (generate input data)
(lambda (frame)
(define default (for/fold ([acc base-default])
([d data])
(hash-set acc (car d) (cdr d))))
(let* ([cb (class:new (with-event choice% input) [parent frame]
[label (hash-ref default 'label)]
[choices (hash-ref default 'choices)]
[selection (hash-ref default 'selection)]
[style (hash-ref default 'style)]
[font (hash-ref default 'font)]
[enabled (hash-ref default 'enabled)]
[vert-margin (hash-ref default 'vert-margin)]
[horiz-margin (hash-ref default 'horiz-margin)]
[min-width (hash-ref default 'min-width)]
[min-height (hash-ref default 'min-height)]
[stretchable-width (hash-ref default 'stretchable-width)]
[stretchable-height (hash-ref default 'stretchable-height)]
[callback (lambda (button event)
(send (input "in") (cons (class:send event get-event-type)
(class:send button get-string-selection))))])])
(send (input "acc") cb))))
(define (process-msg msg widget input output output-array)
(define managed #f)
(set! managed (area-manage widget msg output output-array))
(set! managed (or managed (subarea-manage widget msg output output-array)))
(set! managed (or managed (window-manage widget msg output output-array)))
(set! managed (or managed (list-control-manage widget msg output output-array)))
(if managed
(void)
(match msg
[(cons 'set-choices choices)
(class:send widget clear)
(for ([choice choices]) (class:send widget append choice))
(class:send widget refresh)]
[(cons 'get-selection act)
(send-action output output-array (cons act (class:send widget get-selection)))]
[(cons 'set-selection n)
(class:send widget set-selection n)]
[else (send-action output output-array msg)])))
(define-agent
#:output-array '("out")
(define acc (try-recv (input "acc")))
(define msg (recv (input "in")))
(set! acc (manage acc msg input output output-array generate process-msg))
(send (output "acc") acc))
|
b393171cd000706014c275ebad5b7d44779a88aec3ff218366b6435b4127ef61 | facebook/flow | check_cache.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
The Hash_queue data structure contains a hash table for O(1 ) lookup as well
* as a doubly linked list , which we use to keep track of recency of use . When
* a file is created or accessed , we move it to the front of the list . When we
* exceed the capacity of the cache , entries at the back of the list are
* dropped .
* as a doubly linked list, which we use to keep track of recency of use. When
* a file is created or accessed, we move it to the front of the list. When we
* exceed the capacity of the cache, entries at the back of the list are
* dropped. *)
module Cache = Core_kernel.Hash_queue.Make (struct
type t = File_key.t
let hash = Hashtbl.hash
let sexp_of_t k = Core_kernel.Sexp.Atom (File_key.to_string k)
let compare = File_key.compare
end)
Files which form a dependency cycle will share the same component context .
* We will create a component context on demand for the first file in a given
* component , then re - use it for any future files in the cycle .
*
* We keep track of a reference count , so we can forget about a cached
* component context once every file referencing it has been removed .
* We will create a component context on demand for the first file in a given
* component, then re-use it for any future files in the cycle.
*
* We keep track of a reference count, so we can forget about a cached
* component context once every file referencing it has been removed. *)
type cached_ccx = {
leader: File_key.t;
ccx: Context.component_t;
mutable refcount: int;
}
(* Each cached file holds a reference to its associated cached component
* context so that we can decrement its reference count. *)
type cached_file = {
file: Type_sig_merge.file;
cached_ccx: cached_ccx;
}
type t = {
files: cached_file Cache.t;
ccxs: (File_key.t, cached_ccx) Hashtbl.t;
mutable size: int;
capacity: int;
}
let create ~capacity =
let files = Cache.create () in
let ccxs = Hashtbl.create 0 in
{ files; ccxs; size = 0; capacity }
(* When a file is dropped from the cache, we decrement the refcount on its
* cached component context. Once no more files reference a given component
* context, we remove it from the cache. *)
let release_ccx cache cached_ccx =
let refcount = cached_ccx.refcount in
if refcount = 1 then
Hashtbl.remove cache.ccxs cached_ccx.leader
else
cached_ccx.refcount <- pred refcount
(* Files are added to the front of the cache and moved to the front when
* accessed, so the least recently used file(s) are at the back. *)
let drop_least_recently_used cache =
match Cache.dequeue_back cache.files with
| None -> ()
| Some { cached_ccx; _ } ->
release_ccx cache cached_ccx;
cache.size <- pred cache.size
(* Files in a cycle share the same component context, so if we are creating a
* file in a cycle with an already cached file, its component context will
* also be cached. *)
let find_or_create_ccx cache ~master_cx leader =
match Hashtbl.find_opt cache.ccxs leader with
| Some cached_ccx ->
cached_ccx.refcount <- succ cached_ccx.refcount;
cached_ccx
| None ->
let ccx = Context.make_ccx master_cx in
let cached_ccx = { leader; ccx; refcount = 1 } in
Hashtbl.add cache.ccxs leader cached_ccx;
cached_ccx
(* If a file for the given file key is already in the cache, we move it to the
* front of the queue to indicate that it was recently used. Otherwise, we
* add a newly created file at the front of the queue. *)
let find_or_create cache ~leader ~master_cx ~create_file file_key =
match Cache.lookup_and_move_to_front cache.files file_key with
| Some { file; _ } -> file
| None ->
let cached_ccx = find_or_create_ccx cache ~master_cx (Lazy.force leader) in
let file = create_file cached_ccx.ccx in
if cache.size = cache.capacity then drop_least_recently_used cache;
Cache.enqueue_front_exn cache.files file_key { file; cached_ccx };
cache.size <- succ cache.size;
file
Clearing the cache does not need to worry about the reference counts for
* cached component contexts , since all cached files are also cleared .
* cached component contexts, since all cached files are also cleared. *)
let clear cache =
Cache.clear cache.files;
Hashtbl.clear cache.ccxs;
cache.size <- 0
| null | https://raw.githubusercontent.com/facebook/flow/34a9747fe44e88dfeac5c257349f4476220ac43a/src/services/inference/check_cache.ml | ocaml | Each cached file holds a reference to its associated cached component
* context so that we can decrement its reference count.
When a file is dropped from the cache, we decrement the refcount on its
* cached component context. Once no more files reference a given component
* context, we remove it from the cache.
Files are added to the front of the cache and moved to the front when
* accessed, so the least recently used file(s) are at the back.
Files in a cycle share the same component context, so if we are creating a
* file in a cycle with an already cached file, its component context will
* also be cached.
If a file for the given file key is already in the cache, we move it to the
* front of the queue to indicate that it was recently used. Otherwise, we
* add a newly created file at the front of the queue. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
The Hash_queue data structure contains a hash table for O(1 ) lookup as well
* as a doubly linked list , which we use to keep track of recency of use . When
* a file is created or accessed , we move it to the front of the list . When we
* exceed the capacity of the cache , entries at the back of the list are
* dropped .
* as a doubly linked list, which we use to keep track of recency of use. When
* a file is created or accessed, we move it to the front of the list. When we
* exceed the capacity of the cache, entries at the back of the list are
* dropped. *)
module Cache = Core_kernel.Hash_queue.Make (struct
type t = File_key.t
let hash = Hashtbl.hash
let sexp_of_t k = Core_kernel.Sexp.Atom (File_key.to_string k)
let compare = File_key.compare
end)
Files which form a dependency cycle will share the same component context .
* We will create a component context on demand for the first file in a given
* component , then re - use it for any future files in the cycle .
*
* We keep track of a reference count , so we can forget about a cached
* component context once every file referencing it has been removed .
* We will create a component context on demand for the first file in a given
* component, then re-use it for any future files in the cycle.
*
* We keep track of a reference count, so we can forget about a cached
* component context once every file referencing it has been removed. *)
type cached_ccx = {
leader: File_key.t;
ccx: Context.component_t;
mutable refcount: int;
}
type cached_file = {
file: Type_sig_merge.file;
cached_ccx: cached_ccx;
}
type t = {
files: cached_file Cache.t;
ccxs: (File_key.t, cached_ccx) Hashtbl.t;
mutable size: int;
capacity: int;
}
let create ~capacity =
let files = Cache.create () in
let ccxs = Hashtbl.create 0 in
{ files; ccxs; size = 0; capacity }
let release_ccx cache cached_ccx =
let refcount = cached_ccx.refcount in
if refcount = 1 then
Hashtbl.remove cache.ccxs cached_ccx.leader
else
cached_ccx.refcount <- pred refcount
let drop_least_recently_used cache =
match Cache.dequeue_back cache.files with
| None -> ()
| Some { cached_ccx; _ } ->
release_ccx cache cached_ccx;
cache.size <- pred cache.size
let find_or_create_ccx cache ~master_cx leader =
match Hashtbl.find_opt cache.ccxs leader with
| Some cached_ccx ->
cached_ccx.refcount <- succ cached_ccx.refcount;
cached_ccx
| None ->
let ccx = Context.make_ccx master_cx in
let cached_ccx = { leader; ccx; refcount = 1 } in
Hashtbl.add cache.ccxs leader cached_ccx;
cached_ccx
let find_or_create cache ~leader ~master_cx ~create_file file_key =
match Cache.lookup_and_move_to_front cache.files file_key with
| Some { file; _ } -> file
| None ->
let cached_ccx = find_or_create_ccx cache ~master_cx (Lazy.force leader) in
let file = create_file cached_ccx.ccx in
if cache.size = cache.capacity then drop_least_recently_used cache;
Cache.enqueue_front_exn cache.files file_key { file; cached_ccx };
cache.size <- succ cache.size;
file
Clearing the cache does not need to worry about the reference counts for
* cached component contexts , since all cached files are also cleared .
* cached component contexts, since all cached files are also cleared. *)
let clear cache =
Cache.clear cache.files;
Hashtbl.clear cache.ccxs;
cache.size <- 0
|
ecee143806810f0064048a3292674da77cee9ddfafbf830ca4ad8d9e65a42b79 | nomeata/haskell-candid | Types.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveTraversable #-}
module Codec.Candid.Types where
import qualified Data.ByteString.Lazy as BS
import qualified Data.Text as T
import qualified Data.Vector as V
import Data.Word
import Data.Int
import Numeric.Natural
import Control.Monad
import Data.Bifunctor
import Data.Void
import Data.Scientific
import Data.Char
import Numeric
import Prettyprinter
import Codec.Candid.Data
import Codec.Candid.FieldName
data Type a
-- prim types
= NatT | Nat8T | Nat16T | Nat32T | Nat64T
| IntT | Int8T | Int16T | Int32T | Int64T
| Float32T | Float64T
| BoolT
| TextT
| NullT
| ReservedT
| EmptyT
-- constructors
| OptT (Type a)
| VecT (Type a)
| RecT (Fields a)
| VariantT (Fields a)
-- reference
| FuncT (MethodType a)
| ServiceT [(T.Text, MethodType a)]
| PrincipalT
-- short-hands
| BlobT
-- ^ a short-hand for 'VecT' 'Nat8T'
-- future types
| FutureT
-- for recursive types
| RefT a -- ^ A reference to a named type
deriving (Show, Eq, Ord, Functor, Foldable, Traversable)
tupT :: [Type a] -> Type a
tupT = RecT . zipWith (\n t -> (hashedField n, t)) [0..]
instance Applicative Type where
pure = RefT
(<*>) = ap
instance Monad Type where
return = pure
NatT >>= _ = NatT
Nat8T >>= _ = Nat8T
Nat16T >>= _ = Nat16T
Nat32T >>= _ = Nat32T
Nat64T >>= _ = Nat64T
IntT >>= _ = IntT
Int8T >>= _ = Int8T
Int16T >>= _ = Int16T
Int32T >>= _ = Int32T
Int64T >>= _ = Int64T
Float32T >>= _ = Float32T
Float64T >>= _ = Float64T
BoolT >>= _ = BoolT
TextT >>= _ = TextT
NullT >>= _ = NullT
ReservedT >>= _ = ReservedT
EmptyT >>= _ = EmptyT
BlobT >>= _ = BlobT
FutureT >>= _ = FutureT
PrincipalT >>= _ = PrincipalT
OptT t >>= f = OptT (t >>= f)
VecT t >>= f = VecT (t >>= f)
RecT fs >>= f = RecT (map (second (>>= f)) fs)
VariantT fs >>= f = VariantT (map (second (>>= f)) fs)
FuncT mt >>= f = FuncT (bindMethodType f mt)
ServiceT ms >>= f = ServiceT (map (second (bindMethodType f)) ms)
RefT x >>= f = f x
bindMethodType :: (a -> Type b) -> MethodType a -> MethodType b
bindMethodType f (MethodType as bs q ow) =
MethodType (map (>>= f) as) (map (>>= f) bs) q ow
type Fields a = [(FieldName, Type a)]
type Args a = [Type a]
instance Pretty a => Pretty (Type a) where
pretty NatT = "nat"
pretty Nat8T = "nat8"
pretty Nat16T = "nat16"
pretty Nat32T = "nat32"
pretty Nat64T = "nat64"
pretty IntT = "int"
pretty Int8T = "int8"
pretty Int16T = "int16"
pretty Int32T = "int32"
pretty Int64T = "int64"
pretty Float32T = "float32"
pretty Float64T = "float64"
pretty BoolT = "bool"
pretty TextT = "text"
pretty NullT = "null"
pretty ReservedT = "reserved"
pretty EmptyT = "empty"
pretty (OptT t) = "opt" <+> pretty t
pretty (VecT t) = "vec" <+> pretty t
pretty (RecT fs) = "record" <+> prettyFields False fs
pretty (VariantT fs) = "variant" <+> prettyFields True fs
pretty (RefT a) = pretty a
pretty BlobT = "blob"
pretty (FuncT mt) = "func" <+> pretty mt
pretty (ServiceT s) =
"service" <+> ":" <+> braces (group (align (vsep $ prettyMeth <$> s)))
pretty PrincipalT = "principal"
pretty FutureT = "future"
prettyList = encloseSep lparen rparen (comma <> space) . map pretty
prettyFields :: Pretty a => Bool -> Fields a -> Doc ann
prettyFields in_variant fs = prettyBraceSemi $ map (prettyField in_variant) fs
prettyBraceSemi :: [Doc ann] -> Doc ann
prettyBraceSemi = braces . hsep . punctuate semi
prettyField :: Pretty a => Bool -> (FieldName, Type a) -> Doc ann
prettyField True (f, NullT) = pretty f
prettyField _ (f, t) = pretty f <+> colon <+> pretty t -- TODO: encode field names
data Value
= NumV Scientific -- used when parsing at an unknown numeric type
| NatV Natural
| Nat8V Word8
| Nat16V Word16
| Nat32V Word32
| Nat64V Word64
| IntV Integer
| Int8V Int8
| Int16V Int16
| Int32V Int32
| Int64V Int64
| Float32V Float
| Float64V Double
| BoolV Bool
| TextV T.Text
| NullV
| ReservedV
| OptV (Maybe Value)
| VecV (V.Vector Value)
| RecV [(FieldName, Value)]
| TupV [Value]
| VariantV FieldName Value
| FuncV Principal T.Text
| ServiceV Principal
| PrincipalV Principal
| BlobV BS.ByteString
| AnnV Value (Type Void)
| FutureV -- ^ An opaque value of a future type
deriving (Eq, Ord, Show)
instance Pretty Value where
pretty (NumV v) = pretty (show v)
pretty (NatV v) = pretty v
pretty (IntV v) | v >= 0 = "+" <> pretty v
| otherwise = pretty v
pretty (Nat8V v) = prettyAnn v Nat8T
pretty (Nat16V v) = prettyAnn v Nat16T
pretty (Nat32V v) = prettyAnn v Nat32T
pretty (Nat64V v) = prettyAnn v Nat64T
pretty (Int8V v) = prettyAnn v Int8T
pretty (Int16V v) = prettyAnn v Int16T
pretty (Int32V v) = prettyAnn v Int32T
pretty (Int64V v) = prettyAnn v Int64T
pretty (Float32V v) = prettyAnn v Float32T
pretty (Float64V v) = prettyAnn v Float64T
pretty (BoolV True) = "true"
pretty (BoolV False) = "false"
pretty (TextV v) = prettyText v
pretty NullV = "null"
pretty ReservedV = prettyAnn ("null"::T.Text) ReservedT
pretty (FuncV b m) = "func" <+> prettyText (prettyPrincipal b) <> "." <> prettyText m
pretty (ServiceV b) = "service" <+> prettyText (prettyPrincipal b)
pretty (PrincipalV b) = "principal" <+> prettyText (prettyPrincipal b)
pretty (BlobV b) = "blob" <+> prettyBlob b
pretty (OptV Nothing) = pretty NullV
pretty (OptV (Just v)) = "opt" <+> pretty v
pretty (VecV vs) = "vec" <+> prettyBraceSemi (map pretty (V.toList vs))
pretty (TupV vs) = "record" <+> prettyBraceSemi (map pretty vs)
pretty (RecV vs) = "record" <+> prettyBraceSemi (map go vs)
where go (fn, v) = pretty fn <+> "=" <+> pretty v
pretty (VariantV f NullV) = "variant" <+> braces (pretty f)
pretty (VariantV f v) = "variant" <+> braces (pretty f <+> "=" <+> pretty v)
pretty (AnnV v t) = prettyAnn v t
pretty FutureV = "future"
prettyList = encloseSep lparen rparen (comma <> space) . map pretty
prettyAnn :: Pretty a => a -> Type Void -> Doc ann
prettyAnn v t = parens $ pretty v <+> ":" <+> pretty t
prettyBlob :: BS.ByteString -> Doc ann
prettyBlob = dquotes . pretty . T.concat . map go . BS.unpack
where
go b | fromIntegral b == ord '\t' = "\\t"
go b | fromIntegral b == ord '\n' = "\\n"
go b | fromIntegral b == ord '\r' = "\\r"
go b | fromIntegral b == ord '"' = "\\\""
go b | fromIntegral b == ord '\'' = "\\\'"
go b | fromIntegral b == ord '\\' = "\\\\"
go b | b >= 0x20 && b < 0x7f = T.singleton (chr (fromIntegral b))
go b | b < 0x10 = "\\0" <> T.pack (showHex b "")
go b = "\\" <> T.pack (showHex b "")
prettyText :: T.Text -> Doc ann
prettyText = dquotes . pretty . T.concatMap go
where
go '\t' = "\\t"
go '\n' = "\\n"
go '\r' = "\\r"
go '"' = "\\\""
go '\'' = "\\\'"
go '\\' = "\\\\"
go c | isControl c = "\\u{" <> T.pack (showHex (ord c) "") <> "}"
go c = T.singleton c
tupV :: [Value] -> Value
tupV = RecV . zipWith (\n t -> (hashedField n, t)) [0..]
-- Put here because used for both decoding and encoding
primTyp :: Integer -> Maybe (Type a)
primTyp (-1) = Just NullT
primTyp (-2) = Just BoolT
primTyp (-3) = Just NatT
primTyp (-4) = Just IntT
primTyp (-5) = Just Nat8T
primTyp (-6) = Just Nat16T
primTyp (-7) = Just Nat32T
primTyp (-8) = Just Nat64T
primTyp (-9) = Just Int8T
primTyp (-10) = Just Int16T
primTyp (-11) = Just Int32T
primTyp (-12) = Just Int64T
primTyp (-13) = Just Float32T
primTyp (-14) = Just Float64T
primTyp (-15) = Just TextT
primTyp (-16) = Just ReservedT
primTyp (-17) = Just EmptyT
primTyp (-24) = Just PrincipalT
primTyp _ = Nothing
-- | The type of a candid method
data MethodType a = MethodType
{ methParams :: [Type a]
, methResults :: [Type a]
, methQuery :: Bool
, methOneway :: Bool
}
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
type TypeName = T.Text
type DidService a = [(T.Text, MethodType a)]
type DidDef a = (a, Type a)
data DidFile = DidFile
{ defs :: [ DidDef TypeName ]
, service :: DidService TypeName
}
deriving (Eq, Show)
instance Pretty a => Pretty (MethodType a) where
pretty (MethodType params results q o) = sep $
[ pretty params
, "->"
, pretty results
] <>
[ "query" | q ] <>
[ "oneway" | o ]
prettyDef :: Pretty a => DidDef a -> Doc ann
prettyDef (tn, t) = "type" <+> pretty tn <+> "=" <+> pretty t <> semi
prettyMeth :: Pretty a => (T.Text, MethodType a) -> Doc ann
prettyMeth (n, t) = pretty n <+> colon <+> pretty t <> semi
instance Pretty DidFile where
pretty (DidFile defs s) = vsep $
(prettyDef <$> defs) ++
[ "service" <+> ":" <+> braces (group (align (vsep $ prettyMeth <$> s))) ]
| null | https://raw.githubusercontent.com/nomeata/haskell-candid/87a4f01eb9cb93c827a0a7f5f29af0ee19135308/src/Codec/Candid/Types.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DeriveTraversable #
prim types
constructors
reference
short-hands
^ a short-hand for 'VecT' 'Nat8T'
future types
for recursive types
^ A reference to a named type
TODO: encode field names
used when parsing at an unknown numeric type
^ An opaque value of a future type
Put here because used for both decoding and encoding
| The type of a candid method | module Codec.Candid.Types where
import qualified Data.ByteString.Lazy as BS
import qualified Data.Text as T
import qualified Data.Vector as V
import Data.Word
import Data.Int
import Numeric.Natural
import Control.Monad
import Data.Bifunctor
import Data.Void
import Data.Scientific
import Data.Char
import Numeric
import Prettyprinter
import Codec.Candid.Data
import Codec.Candid.FieldName
data Type a
= NatT | Nat8T | Nat16T | Nat32T | Nat64T
| IntT | Int8T | Int16T | Int32T | Int64T
| Float32T | Float64T
| BoolT
| TextT
| NullT
| ReservedT
| EmptyT
| OptT (Type a)
| VecT (Type a)
| RecT (Fields a)
| VariantT (Fields a)
| FuncT (MethodType a)
| ServiceT [(T.Text, MethodType a)]
| PrincipalT
| BlobT
| FutureT
deriving (Show, Eq, Ord, Functor, Foldable, Traversable)
tupT :: [Type a] -> Type a
tupT = RecT . zipWith (\n t -> (hashedField n, t)) [0..]
instance Applicative Type where
pure = RefT
(<*>) = ap
instance Monad Type where
return = pure
NatT >>= _ = NatT
Nat8T >>= _ = Nat8T
Nat16T >>= _ = Nat16T
Nat32T >>= _ = Nat32T
Nat64T >>= _ = Nat64T
IntT >>= _ = IntT
Int8T >>= _ = Int8T
Int16T >>= _ = Int16T
Int32T >>= _ = Int32T
Int64T >>= _ = Int64T
Float32T >>= _ = Float32T
Float64T >>= _ = Float64T
BoolT >>= _ = BoolT
TextT >>= _ = TextT
NullT >>= _ = NullT
ReservedT >>= _ = ReservedT
EmptyT >>= _ = EmptyT
BlobT >>= _ = BlobT
FutureT >>= _ = FutureT
PrincipalT >>= _ = PrincipalT
OptT t >>= f = OptT (t >>= f)
VecT t >>= f = VecT (t >>= f)
RecT fs >>= f = RecT (map (second (>>= f)) fs)
VariantT fs >>= f = VariantT (map (second (>>= f)) fs)
FuncT mt >>= f = FuncT (bindMethodType f mt)
ServiceT ms >>= f = ServiceT (map (second (bindMethodType f)) ms)
RefT x >>= f = f x
bindMethodType :: (a -> Type b) -> MethodType a -> MethodType b
bindMethodType f (MethodType as bs q ow) =
MethodType (map (>>= f) as) (map (>>= f) bs) q ow
type Fields a = [(FieldName, Type a)]
type Args a = [Type a]
instance Pretty a => Pretty (Type a) where
pretty NatT = "nat"
pretty Nat8T = "nat8"
pretty Nat16T = "nat16"
pretty Nat32T = "nat32"
pretty Nat64T = "nat64"
pretty IntT = "int"
pretty Int8T = "int8"
pretty Int16T = "int16"
pretty Int32T = "int32"
pretty Int64T = "int64"
pretty Float32T = "float32"
pretty Float64T = "float64"
pretty BoolT = "bool"
pretty TextT = "text"
pretty NullT = "null"
pretty ReservedT = "reserved"
pretty EmptyT = "empty"
pretty (OptT t) = "opt" <+> pretty t
pretty (VecT t) = "vec" <+> pretty t
pretty (RecT fs) = "record" <+> prettyFields False fs
pretty (VariantT fs) = "variant" <+> prettyFields True fs
pretty (RefT a) = pretty a
pretty BlobT = "blob"
pretty (FuncT mt) = "func" <+> pretty mt
pretty (ServiceT s) =
"service" <+> ":" <+> braces (group (align (vsep $ prettyMeth <$> s)))
pretty PrincipalT = "principal"
pretty FutureT = "future"
prettyList = encloseSep lparen rparen (comma <> space) . map pretty
prettyFields :: Pretty a => Bool -> Fields a -> Doc ann
prettyFields in_variant fs = prettyBraceSemi $ map (prettyField in_variant) fs
prettyBraceSemi :: [Doc ann] -> Doc ann
prettyBraceSemi = braces . hsep . punctuate semi
prettyField :: Pretty a => Bool -> (FieldName, Type a) -> Doc ann
prettyField True (f, NullT) = pretty f
data Value
| NatV Natural
| Nat8V Word8
| Nat16V Word16
| Nat32V Word32
| Nat64V Word64
| IntV Integer
| Int8V Int8
| Int16V Int16
| Int32V Int32
| Int64V Int64
| Float32V Float
| Float64V Double
| BoolV Bool
| TextV T.Text
| NullV
| ReservedV
| OptV (Maybe Value)
| VecV (V.Vector Value)
| RecV [(FieldName, Value)]
| TupV [Value]
| VariantV FieldName Value
| FuncV Principal T.Text
| ServiceV Principal
| PrincipalV Principal
| BlobV BS.ByteString
| AnnV Value (Type Void)
deriving (Eq, Ord, Show)
instance Pretty Value where
pretty (NumV v) = pretty (show v)
pretty (NatV v) = pretty v
pretty (IntV v) | v >= 0 = "+" <> pretty v
| otherwise = pretty v
pretty (Nat8V v) = prettyAnn v Nat8T
pretty (Nat16V v) = prettyAnn v Nat16T
pretty (Nat32V v) = prettyAnn v Nat32T
pretty (Nat64V v) = prettyAnn v Nat64T
pretty (Int8V v) = prettyAnn v Int8T
pretty (Int16V v) = prettyAnn v Int16T
pretty (Int32V v) = prettyAnn v Int32T
pretty (Int64V v) = prettyAnn v Int64T
pretty (Float32V v) = prettyAnn v Float32T
pretty (Float64V v) = prettyAnn v Float64T
pretty (BoolV True) = "true"
pretty (BoolV False) = "false"
pretty (TextV v) = prettyText v
pretty NullV = "null"
pretty ReservedV = prettyAnn ("null"::T.Text) ReservedT
pretty (FuncV b m) = "func" <+> prettyText (prettyPrincipal b) <> "." <> prettyText m
pretty (ServiceV b) = "service" <+> prettyText (prettyPrincipal b)
pretty (PrincipalV b) = "principal" <+> prettyText (prettyPrincipal b)
pretty (BlobV b) = "blob" <+> prettyBlob b
pretty (OptV Nothing) = pretty NullV
pretty (OptV (Just v)) = "opt" <+> pretty v
pretty (VecV vs) = "vec" <+> prettyBraceSemi (map pretty (V.toList vs))
pretty (TupV vs) = "record" <+> prettyBraceSemi (map pretty vs)
pretty (RecV vs) = "record" <+> prettyBraceSemi (map go vs)
where go (fn, v) = pretty fn <+> "=" <+> pretty v
pretty (VariantV f NullV) = "variant" <+> braces (pretty f)
pretty (VariantV f v) = "variant" <+> braces (pretty f <+> "=" <+> pretty v)
pretty (AnnV v t) = prettyAnn v t
pretty FutureV = "future"
prettyList = encloseSep lparen rparen (comma <> space) . map pretty
prettyAnn :: Pretty a => a -> Type Void -> Doc ann
prettyAnn v t = parens $ pretty v <+> ":" <+> pretty t
prettyBlob :: BS.ByteString -> Doc ann
prettyBlob = dquotes . pretty . T.concat . map go . BS.unpack
where
go b | fromIntegral b == ord '\t' = "\\t"
go b | fromIntegral b == ord '\n' = "\\n"
go b | fromIntegral b == ord '\r' = "\\r"
go b | fromIntegral b == ord '"' = "\\\""
go b | fromIntegral b == ord '\'' = "\\\'"
go b | fromIntegral b == ord '\\' = "\\\\"
go b | b >= 0x20 && b < 0x7f = T.singleton (chr (fromIntegral b))
go b | b < 0x10 = "\\0" <> T.pack (showHex b "")
go b = "\\" <> T.pack (showHex b "")
prettyText :: T.Text -> Doc ann
prettyText = dquotes . pretty . T.concatMap go
where
go '\t' = "\\t"
go '\n' = "\\n"
go '\r' = "\\r"
go '"' = "\\\""
go '\'' = "\\\'"
go '\\' = "\\\\"
go c | isControl c = "\\u{" <> T.pack (showHex (ord c) "") <> "}"
go c = T.singleton c
tupV :: [Value] -> Value
tupV = RecV . zipWith (\n t -> (hashedField n, t)) [0..]
primTyp :: Integer -> Maybe (Type a)
primTyp (-1) = Just NullT
primTyp (-2) = Just BoolT
primTyp (-3) = Just NatT
primTyp (-4) = Just IntT
primTyp (-5) = Just Nat8T
primTyp (-6) = Just Nat16T
primTyp (-7) = Just Nat32T
primTyp (-8) = Just Nat64T
primTyp (-9) = Just Int8T
primTyp (-10) = Just Int16T
primTyp (-11) = Just Int32T
primTyp (-12) = Just Int64T
primTyp (-13) = Just Float32T
primTyp (-14) = Just Float64T
primTyp (-15) = Just TextT
primTyp (-16) = Just ReservedT
primTyp (-17) = Just EmptyT
primTyp (-24) = Just PrincipalT
primTyp _ = Nothing
data MethodType a = MethodType
{ methParams :: [Type a]
, methResults :: [Type a]
, methQuery :: Bool
, methOneway :: Bool
}
deriving (Eq, Ord, Show, Functor, Foldable, Traversable)
type TypeName = T.Text
type DidService a = [(T.Text, MethodType a)]
type DidDef a = (a, Type a)
data DidFile = DidFile
{ defs :: [ DidDef TypeName ]
, service :: DidService TypeName
}
deriving (Eq, Show)
instance Pretty a => Pretty (MethodType a) where
pretty (MethodType params results q o) = sep $
[ pretty params
, "->"
, pretty results
] <>
[ "query" | q ] <>
[ "oneway" | o ]
prettyDef :: Pretty a => DidDef a -> Doc ann
prettyDef (tn, t) = "type" <+> pretty tn <+> "=" <+> pretty t <> semi
prettyMeth :: Pretty a => (T.Text, MethodType a) -> Doc ann
prettyMeth (n, t) = pretty n <+> colon <+> pretty t <> semi
instance Pretty DidFile where
pretty (DidFile defs s) = vsep $
(prettyDef <$> defs) ++
[ "service" <+> ":" <+> braces (group (align (vsep $ prettyMeth <$> s))) ]
|
134e8ed50fd75a91b7aa16fbc86345d2520c739535e4b174a4b41ae7e3106f9b | enaeher/local-time-duration | timestamp.lisp | (in-package :ltd-tests)
(eval-when (:compile-toplevel :load-toplevel :execute)
(local-time:enable-read-macros))
(5am:test timestamp-difference
(5am:is (duration= (timestamp-difference @2014-01-01T09:00:00
@2014-01-01T04:30:00)
(duration :hour 4 :minute 30))))
(5am:test timestamp-add-duration
(5am:is (local-time:timestamp= (timestamp-duration+ @2014-01-01T09:00:00
(duration :hour 3))
@2014-01-01T12:00:00)))
(5am:test timestamp-subtract-duration
(5am:is (local-time:timestamp= (timestamp-duration- @2014-01-01T09:00:00
(duration :hour 3))
@2014-01-01T06:00:00)))
| null | https://raw.githubusercontent.com/enaeher/local-time-duration/fa20a4a03a1ee076eada649796e2f2345c930c21/tests/timestamp.lisp | lisp | (in-package :ltd-tests)
(eval-when (:compile-toplevel :load-toplevel :execute)
(local-time:enable-read-macros))
(5am:test timestamp-difference
(5am:is (duration= (timestamp-difference @2014-01-01T09:00:00
@2014-01-01T04:30:00)
(duration :hour 4 :minute 30))))
(5am:test timestamp-add-duration
(5am:is (local-time:timestamp= (timestamp-duration+ @2014-01-01T09:00:00
(duration :hour 3))
@2014-01-01T12:00:00)))
(5am:test timestamp-subtract-duration
(5am:is (local-time:timestamp= (timestamp-duration- @2014-01-01T09:00:00
(duration :hour 3))
@2014-01-01T06:00:00)))
| |
baba850fcba129075b497f1a17f119dfa290fdcd1c77d4660403b4b13daf9413 | caribou/caribou-core | util.clj | (ns caribou.util
(:require [clojure.string :as string]
[clojure.java.jdbc.deprecated :as old-sql]
[clojure.java.io :as io]
[clojure.data.codec.base64 :as b64]))
(import java.util.regex.Matcher)
(import java.sql.SQLException)
(import java.io.File)
(import java.util.UUID)
(defn random-uuid
[]
(String/valueOf (java.util.UUID/randomUUID)))
(defn b64-decode
[code]
(let [bytes (byte-array (map byte code))
uncode (b64/decode bytes)]
(string/join (map char uncode))))
(defn convert-int
[something]
(try
(condp = (type something)
nil nil
java.math.BigInteger (.longValue something)
java.math.BigDecimal (.longValue something)
(Integer. something))
(catch java.lang.NumberFormatException e nil)))
(defn find-methods
"Return all java methods available on a given object!"
[x]
(map
#(.getName %)
(.getDeclaredMethods (class x))))
(defn dups [seq]
(for [[id freq] (frequencies seq)
:when (> freq 1)]
id))
(defn seq-to-map
[f q]
(reduce #(assoc %1 (f %2) %2) {} q))
(defn slugify
[s]
(let [pared (string/replace (name s) #"'|\"" "")
islands (re-seq #"[a-zA-Z0-9]+" pared)
archipelago (string/join "-" islands)
shielded (string/replace archipelago #"^[0-9]" "-")]
(string/lower-case shielded)))
(defn url-slugify
[s]
(string/lower-case
(string/join
"-"
(re-seq
#"[a-zA-Z0-9]+"
(string/replace
(name s)
#"'|\""
"")))))
(defn transform-string
"accepts a string and a map of transformations, where the key is a pattern to match and the value
is the replacement for each found instance of the pattern. If an ordered set of replacements is
desired, swap out the map with a vector of pairs."
[s transform]
(loop [trans (seq transform)
clean s]
(if (seq trans)
(let [[pattern replacement] (first trans)
wash (string/replace clean pattern replacement)]
(recur (rest trans) wash))
clean)))
(defn slug-transform
[transform]
(fn [s]
(string/lower-case
(transform-string
(name s)
transform))))
(def dbslug-transform-map
[[#"['\"]+" ""]
[#"[_ \\/?%:#^\[\]<>@!|$&*+;,.()]+" "-"]
[#"^-+|-+$" ""]
[#"^[0-9]+" ""]])
(defn underscore
[s]
(.replace s \- \_))
(defn titleize
[s]
(string/join " " (map string/capitalize (string/split (name s) #"[^a-zA-Z]+"))))
(def file-separator
"/")
(defn pathify
[paths]
(string/join file-separator paths))
(defn file-exists?
[path]
(.exists (io/file path)))
(defn pull-resource
[path]
(io/resource path))
(defn map-keys
[f m]
(into {} (for [[k v] m] [(f k) v])))
(defn map-vals
[f m]
(into {} (for [[k v] m] [k (f v)])))
(defn map-map
[f m]
(into {} (for [[k v] m] (f k v))))
(defn re-replace
[r s f]
(let [between (string/split s r)
inside (re-seq r s)
transformed (concat (map f inside) [""])]
(apply str (interleave between transformed))))
(defn re-replace-first
[r s f]
(let [between (string/split s r)
inside (re-seq r s)
transformed (concat [(f (first inside))] (rest inside) [""])]
(apply str (interleave between transformed))))
(defn re-replace-beginning
[r s]
(let [[_ after] (re-find r s)]
after))
(defn get-file-extension [file]
(let [filename (.getName file)]
(.toLowerCase (.substring filename (.lastIndexOf filename ".")))))
(defn load-props
[props-name]
(try
(let [raw (io/reader (io/resource props-name))
props (java.util.Properties.)]
(.load props raw)
(into {} (for [[k v] props] [(keyword k) (read-string v)])))
;; this is not actually an error
(catch Exception e nil)))
(defn load-resource
[resource-name]
(let [thr (Thread/currentThread)
ldr (.getContextClassLoader thr)]
(.getResourceAsStream ldr resource-name)))
(defn load-path [path visit]
(doseq [file (file-seq (io/file path))]
(let [filename (.toString file)
subname (string/replace filename (str path "/") "")]
(if (.isFile file)
(visit file subname)))))
(defn walk
"A version of clojure.walk/walk that doesn't think Records are Maps"
[inner outer form]
(cond
(list? form) (outer (apply list (map inner form)))
(seq? form) (outer (doall (map inner form)))
(vector? form) (outer (vec (map inner form)))
(and (map? form) (not (instance? clojure.lang.IRecord form))) (outer (into (if (sorted? form) (sorted-map) {})
(map inner form)))
(set? form) (outer (into (if (sorted? form) (sorted-set) #{})
(map inner form)))
:else (outer form)))
(defn postwalk
"clojure.walk/postwalk that uses our walk function"
[f form]
(walk (partial postwalk f) f form))
(defn stringify-keys
"A version of clojure.walk/stringify-keys that is record-aware"
[m]
(let [f (fn [[k v]] (if (keyword? k) [(name k) v] [k v]))]
;; only apply to maps (not records)
(postwalk (fn [x] (if (and (map? x) (not (instance? clojure.lang.IRecord x))) (into {} (map f x)) x)) m)))
;; db support -------------------------------
(def naming-strategy
{:entity
(fn [k]
(string/replace (name k) "-" "_"))
:keyword
(fn [e]
(keyword (string/lower-case (string/replace e "_" "-"))))})
(defn zap
"quickly sanitize a potentially dirty string in preparation for a sql query"
[s]
(cond
# % ] " ( .replaceAll ( str s ) " ' " " '' " ) ) " " )
(keyword? s) (zap (name s))
:else s))
(defn dbize
[s]
(if (or (keyword? s) (string? s))
(old-sql/as-named-identifier naming-strategy (keyword (zap s)))
s))
(defn clause
"substitute values into a string template based on numbered % parameters"
[pred args]
(letfn [(rep [s i] (.replaceAll s (str "%" (inc i))
(let [item (nth args i)]
(Matcher/quoteReplacement
(cond
(keyword? item) (dbize (name item))
:else
(str item))))))]
(if (empty? args)
pred
(loop [i 0 retr pred]
(if (= i (-> args count dec))
(rep retr i)
(recur (inc i) (rep retr i)))))))
(defn query
"make an arbitrary query, substituting in extra args as % parameters"
[q & args]
(old-sql/with-query-results res
[(clause q args)]
(doall res)))
by Chouser :
(defn deep-merge-with
"Like merge-with, but merges maps recursively, applying the given fn
only when there's a non-map at a particular level.
(deepmerge + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4}
{:a {:b {:c 2 :d {:z 9} :z 3} :e 100}})
-> {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}"
[f & maps]
(apply
(fn m [& maps]
(if (every? map? maps)
(apply merge-with m maps)
(apply f maps)))
maps))
(defn prefix-key
[prefix slug]
(keyword (str (name prefix) "$" (name slug))))
(def pool "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
? /}]{[~ ` 0123456789 " )
(defn rand-str
([n] (rand-str n pool))
([n pool]
(string/join
(map
(fn [_]
(rand-nth pool))
(repeat n nil)))))
(defn purge-key
"remove all instances of the given key from every nested sequence in item"
[item key]
(let [non (dissoc item key)
seq-keys (map
first
(filter
(fn [[k v]]
(sequential? v))
non))]
(reduce
(fn [i k]
(update-in i [k] #(map (fn [item] purge-key item key) %)))
non seq-keys)))
(defn maybe-require
"require the given ns, ignore file not found errors, but let others
do their thing"
[ns]
(try
(require ns :reload)
(catch java.io.FileNotFoundException e nil)))
(defn run-namespace
[namespace action-symbol]
(let [namespace-symbol (symbol namespace)]
(maybe-require namespace-symbol)
(if-let [running (find-ns namespace-symbol)]
(if-let [action (ns-resolve running (symbol action-symbol))]
(action)))))
(defn dechunk
[coll]
(lazy-seq
(when-let [[x] (seq coll)]
(cons x
(dechunk (rest coll))))))
| null | https://raw.githubusercontent.com/caribou/caribou-core/6ebd9db4e14cddb1d6b4e152e771e016fa9c55f6/src/caribou/util.clj | clojure | this is not actually an error
only apply to maps (not records)
db support ------------------------------- | (ns caribou.util
(:require [clojure.string :as string]
[clojure.java.jdbc.deprecated :as old-sql]
[clojure.java.io :as io]
[clojure.data.codec.base64 :as b64]))
(import java.util.regex.Matcher)
(import java.sql.SQLException)
(import java.io.File)
(import java.util.UUID)
(defn random-uuid
[]
(String/valueOf (java.util.UUID/randomUUID)))
(defn b64-decode
[code]
(let [bytes (byte-array (map byte code))
uncode (b64/decode bytes)]
(string/join (map char uncode))))
(defn convert-int
[something]
(try
(condp = (type something)
nil nil
java.math.BigInteger (.longValue something)
java.math.BigDecimal (.longValue something)
(Integer. something))
(catch java.lang.NumberFormatException e nil)))
(defn find-methods
"Return all java methods available on a given object!"
[x]
(map
#(.getName %)
(.getDeclaredMethods (class x))))
(defn dups [seq]
(for [[id freq] (frequencies seq)
:when (> freq 1)]
id))
(defn seq-to-map
[f q]
(reduce #(assoc %1 (f %2) %2) {} q))
(defn slugify
[s]
(let [pared (string/replace (name s) #"'|\"" "")
islands (re-seq #"[a-zA-Z0-9]+" pared)
archipelago (string/join "-" islands)
shielded (string/replace archipelago #"^[0-9]" "-")]
(string/lower-case shielded)))
(defn url-slugify
[s]
(string/lower-case
(string/join
"-"
(re-seq
#"[a-zA-Z0-9]+"
(string/replace
(name s)
#"'|\""
"")))))
(defn transform-string
"accepts a string and a map of transformations, where the key is a pattern to match and the value
is the replacement for each found instance of the pattern. If an ordered set of replacements is
desired, swap out the map with a vector of pairs."
[s transform]
(loop [trans (seq transform)
clean s]
(if (seq trans)
(let [[pattern replacement] (first trans)
wash (string/replace clean pattern replacement)]
(recur (rest trans) wash))
clean)))
(defn slug-transform
[transform]
(fn [s]
(string/lower-case
(transform-string
(name s)
transform))))
(def dbslug-transform-map
[[#"['\"]+" ""]
[#"[_ \\/?%:#^\[\]<>@!|$&*+;,.()]+" "-"]
[#"^-+|-+$" ""]
[#"^[0-9]+" ""]])
(defn underscore
[s]
(.replace s \- \_))
(defn titleize
[s]
(string/join " " (map string/capitalize (string/split (name s) #"[^a-zA-Z]+"))))
(def file-separator
"/")
(defn pathify
[paths]
(string/join file-separator paths))
(defn file-exists?
[path]
(.exists (io/file path)))
(defn pull-resource
[path]
(io/resource path))
(defn map-keys
[f m]
(into {} (for [[k v] m] [(f k) v])))
(defn map-vals
[f m]
(into {} (for [[k v] m] [k (f v)])))
(defn map-map
[f m]
(into {} (for [[k v] m] (f k v))))
(defn re-replace
[r s f]
(let [between (string/split s r)
inside (re-seq r s)
transformed (concat (map f inside) [""])]
(apply str (interleave between transformed))))
(defn re-replace-first
[r s f]
(let [between (string/split s r)
inside (re-seq r s)
transformed (concat [(f (first inside))] (rest inside) [""])]
(apply str (interleave between transformed))))
(defn re-replace-beginning
[r s]
(let [[_ after] (re-find r s)]
after))
(defn get-file-extension [file]
(let [filename (.getName file)]
(.toLowerCase (.substring filename (.lastIndexOf filename ".")))))
(defn load-props
[props-name]
(try
(let [raw (io/reader (io/resource props-name))
props (java.util.Properties.)]
(.load props raw)
(into {} (for [[k v] props] [(keyword k) (read-string v)])))
(catch Exception e nil)))
(defn load-resource
[resource-name]
(let [thr (Thread/currentThread)
ldr (.getContextClassLoader thr)]
(.getResourceAsStream ldr resource-name)))
(defn load-path [path visit]
(doseq [file (file-seq (io/file path))]
(let [filename (.toString file)
subname (string/replace filename (str path "/") "")]
(if (.isFile file)
(visit file subname)))))
(defn walk
"A version of clojure.walk/walk that doesn't think Records are Maps"
[inner outer form]
(cond
(list? form) (outer (apply list (map inner form)))
(seq? form) (outer (doall (map inner form)))
(vector? form) (outer (vec (map inner form)))
(and (map? form) (not (instance? clojure.lang.IRecord form))) (outer (into (if (sorted? form) (sorted-map) {})
(map inner form)))
(set? form) (outer (into (if (sorted? form) (sorted-set) #{})
(map inner form)))
:else (outer form)))
(defn postwalk
"clojure.walk/postwalk that uses our walk function"
[f form]
(walk (partial postwalk f) f form))
(defn stringify-keys
"A version of clojure.walk/stringify-keys that is record-aware"
[m]
(let [f (fn [[k v]] (if (keyword? k) [(name k) v] [k v]))]
(postwalk (fn [x] (if (and (map? x) (not (instance? clojure.lang.IRecord x))) (into {} (map f x)) x)) m)))
(def naming-strategy
{:entity
(fn [k]
(string/replace (name k) "-" "_"))
:keyword
(fn [e]
(keyword (string/lower-case (string/replace e "_" "-"))))})
(defn zap
"quickly sanitize a potentially dirty string in preparation for a sql query"
[s]
(cond
# % ] " ( .replaceAll ( str s ) " ' " " '' " ) ) " " )
(keyword? s) (zap (name s))
:else s))
(defn dbize
[s]
(if (or (keyword? s) (string? s))
(old-sql/as-named-identifier naming-strategy (keyword (zap s)))
s))
(defn clause
"substitute values into a string template based on numbered % parameters"
[pred args]
(letfn [(rep [s i] (.replaceAll s (str "%" (inc i))
(let [item (nth args i)]
(Matcher/quoteReplacement
(cond
(keyword? item) (dbize (name item))
:else
(str item))))))]
(if (empty? args)
pred
(loop [i 0 retr pred]
(if (= i (-> args count dec))
(rep retr i)
(recur (inc i) (rep retr i)))))))
(defn query
"make an arbitrary query, substituting in extra args as % parameters"
[q & args]
(old-sql/with-query-results res
[(clause q args)]
(doall res)))
by Chouser :
(defn deep-merge-with
"Like merge-with, but merges maps recursively, applying the given fn
only when there's a non-map at a particular level.
(deepmerge + {:a {:b {:c 1 :d {:x 1 :y 2}} :e 3} :f 4}
{:a {:b {:c 2 :d {:z 9} :z 3} :e 100}})
-> {:a {:b {:z 3, :c 3, :d {:z 9, :x 1, :y 2}}, :e 103}, :f 4}"
[f & maps]
(apply
(fn m [& maps]
(if (every? map? maps)
(apply merge-with m maps)
(apply f maps)))
maps))
(defn prefix-key
[prefix slug]
(keyword (str (name prefix) "$" (name slug))))
(def pool "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
? /}]{[~ ` 0123456789 " )
(defn rand-str
([n] (rand-str n pool))
([n pool]
(string/join
(map
(fn [_]
(rand-nth pool))
(repeat n nil)))))
(defn purge-key
"remove all instances of the given key from every nested sequence in item"
[item key]
(let [non (dissoc item key)
seq-keys (map
first
(filter
(fn [[k v]]
(sequential? v))
non))]
(reduce
(fn [i k]
(update-in i [k] #(map (fn [item] purge-key item key) %)))
non seq-keys)))
(defn maybe-require
"require the given ns, ignore file not found errors, but let others
do their thing"
[ns]
(try
(require ns :reload)
(catch java.io.FileNotFoundException e nil)))
(defn run-namespace
[namespace action-symbol]
(let [namespace-symbol (symbol namespace)]
(maybe-require namespace-symbol)
(if-let [running (find-ns namespace-symbol)]
(if-let [action (ns-resolve running (symbol action-symbol))]
(action)))))
(defn dechunk
[coll]
(lazy-seq
(when-let [[x] (seq coll)]
(cons x
(dechunk (rest coll))))))
|
29dac0f8c7e72e36a9b521cedf9042e43844f0112ec6cd233b266926e8f7867c | unnohideyuki/bunny | sample218.hs | f '0' = "'0'"
f _ = "non-zero"
main = do putStrLn $ f '1'
putStrLn $ f '0'
| null | https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample218.hs | haskell | f '0' = "'0'"
f _ = "non-zero"
main = do putStrLn $ f '1'
putStrLn $ f '0'
| |
2a0765d1eb935e6aa9ef914453aa5ee0cea46ac5119753f75008e9c813a7df41 | contivero/hasmin | Color.hs | {-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Hasmin.Types.Color
Copyright : ( c ) 2017
-- License : BSD3
-- Stability : experimental
-- Portability : unknown
--
-----------------------------------------------------------------------------
module Hasmin.Types.Color
( Color(Named)
, mkHex3
, mkHex4
, mkHex6
, mkHex8
, mkNamed
, mkHSL
, mkHSLA
, mkRGBInt
, mkRGBPer
, mkRGBAInt
, mkRGBAPer
, keywordColors
, minifyColor
) where
import Control.Arrow (first)
import Control.Monad.Reader (asks)
import Data.Monoid ((<>))
import Data.Char (isHexDigit, digitToInt, intToDigit, toLower)
import Data.Maybe (fromMaybe)
import Data.Ratio ((%))
import Data.Text (Text)
import Data.Text.Lazy.Builder (Builder, singleton)
import qualified Data.Text.Lazy.Builder as B
import Data.Word (Word8)
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import Hasmin.Class
import Hasmin.Config
import Hasmin.Types.Numeric
import Hasmin.Utils
-- | CSS <-color/#colorunits \<color\>>
-- data type.
data Color = Hex3 Char Char Char
| Hex4 Char Char Char Char
| Hex6 String String String
| Hex8 String String String String
| Named Text
| RGBInt Word8 Word8 Word8
| RGBPer Percentage Percentage Percentage
| RGBAInt Word8 Word8 Word8 Alphavalue
| RGBAPer Percentage Percentage Percentage Alphavalue
| HSL Int Percentage Percentage
| HSLA Int Percentage Percentage Alphavalue
deriving (Show)
-- | Equality is slightly relaxed, since percentages and real numbers are mapped
to the [ 0,255 ] integer range , and then compared
instance Eq Color where
(Hex6 r1 g1 b1) == (Hex6 r2 g2 b2) =
r1 == r2 && g1 == g2 && b1 == b2
(Hex8 r1 g1 b1 a1) == (Hex8 r2 g2 b2 a2) =
r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2
(Hex8 r1 g1 b1 a) == (Hex6 r2 g2 b2)
| a == "ff" = r1 == r2 && g1 == g2 && b1 == b2
| otherwise = False
(Hex6 r1 g1 b1) == (Hex8 r2 g2 b2 a)
| a == "ff" = r1 == r2 && g1 == g2 && b1 == b2
| otherwise = False
c1 == (Named s) = Map.lookup (T.toLower s) colorMap == Just c1
(Named s) == c2 = c2 == Named s
a == b = toLongHex a == toLongHex b
instance Ord Color where
(Hex6 r1 g1 b1) <= (Hex6 r2 g2 b2) =
r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && b1 <= b2))
(Hex8 r1 g1 b1 a1) <= (Hex8 r2 g2 b2 a2) =
r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && (b1 < b2 || (b1 == b2 && a1 <= a2))))
(Hex8 r1 g1 b1 a) <= (Hex6 r2 g2 b2)
| a == "ff" = r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && b1 <= b2))
| otherwise = True
(Hex6 r1 g1 b1) <= (Hex8 r2 g2 b2 a)
| a == "ff" = r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && b1 <= b2))
| otherwise = False
c1 <= c2 = toLongHex c1 <= toLongHex c2
instance Minifiable Color where
minify c = do
colSettings <- asks colorSettings
pure $ case colSettings of
ColorMinOn -> minifyColor c
ColorMinOff -> c
minifyColor :: Color -> Color
minifyColor c@Hex6{} = fromMaybe (toHexShorthand c) (Map.lookup c minimalColorMap)
minifyColor c@(Hex8 r g b a)
| a == "ff" = minifyColor (Hex6 r g b)
| otherwise = toHexShorthand c
minifyColor c@(RGBAPer r g b a)
| a >= 1 = minifyColor (RGBPer r g b)
| otherwise = minifyColor $ toLongHex c
minifyColor c@(RGBAInt r g b a)
| a >= 1 = minifyColor (RGBInt r g b)
| otherwise = minifyColor $ toLongHex c
minifyColor c@(HSLA h s l a)
| a >= 1 = minifyColor (HSL h s l)
| otherwise = minifyColor $ toLongHex c
minifyColor c = case toLongHex c of
n@(Named _) -> n
other -> minifyColor other
instance ToText Color where
toBuilder (RGBInt r g b) = "rgb(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b]
toBuilder (RGBAInt r g b a) = "rgba(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b, toText a]
toBuilder (RGBPer r g b) = "rgb(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b]
toBuilder (RGBAPer r g b a) = "rgba(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b, toText a]
toBuilder (HSL h s l) = "hsl(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText h, toText s, toText l]
toBuilder (HSLA h s l a) = "hsla(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText h, toText s, toText l, toText a]
toBuilder (Named a) = B.fromText a
toBuilder (Hex3 r g b) = singleton '#' <> singleton r <> singleton g <> singleton b
toBuilder (Hex4 r g b a) = singleton '#' <> singleton r <> singleton g <> singleton b <> singleton a
toBuilder (Hex6 r g b) = B.fromString $ mconcat ["#", r, g, b]
toBuilder (Hex8 r g b a) = B.fromString $ mconcat ["#", r, g, b, a]
toBuilderWithCommas :: [Text] -> Builder
toBuilderWithCommas = mconcatIntersperse B.fromText (singleton ',')
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- Smart constructors
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
mkHex3 :: Char -> Char -> Char -> Color
mkHex3 r g b
| isHexDigit r && isHexDigit g && isHexDigit b = Hex3 (toLower r) (toLower g) (toLower b)
| otherwise = error "passing non hexadecimal arguments to mkHex3"
mkHex6 :: String -> String -> String -> Color
mkHex6 r g b
| allHex r && allHex g && allHex b = Hex6 (strToLower r) (strToLower g) (strToLower b)
| otherwise = error "passing non hexadecimal arguments to mkHex6"
mkHex4 :: Char -> Char -> Char -> Char -> Color
mkHex4 r g b a
| isHexDigit r && isHexDigit g && isHexDigit b && isHexDigit a = Hex4 (toLower r) (toLower g) (toLower b) (toLower a)
| otherwise = error "passing non hexadecimal arguments to mkHex4"
mkHex8 :: String -> String -> String -> String -> Color
mkHex8 r g b a
| allHex r && allHex g && allHex b = Hex8 (strToLower r) (strToLower g) (strToLower b) (strToLower a)
| otherwise = error "passing non hexadecimal arguments to mkHex6"
mkNamed :: Text -> Maybe Color
mkNamed colorName
| Map.member name colorMap = Just (Named name)
| otherwise = Nothing
where name = T.toLower colorName
mkHSL :: Int -> Percentage -> Percentage -> Color
mkHSL h s l = HSL (h `mod` 360) (bound s) (bound l)
where bound = restrict 0 100
mkHSLA :: Int -> Percentage -> Percentage -> Alphavalue -> Color
mkHSLA h s l = HSLA (h `mod` 360) (bound s) (bound l)
where bound = restrict 0 100
mkRGBInt :: Word8 -> Word8 -> Word8 -> Color
mkRGBInt r g b = RGBInt (bound r) (bound g) (bound b)
where bound = restrict 0 255
mkRGBPer :: Percentage -> Percentage -> Percentage -> Color
mkRGBPer r g b = RGBPer (bound r) (bound g) (bound b)
where bound = restrict 0 100
mkRGBAInt :: Word8 -> Word8 -> Word8 -> Alphavalue -> Color
mkRGBAInt r g b = RGBAInt (bound r) (bound g) (bound b)
where bound = restrict 0 255
mkRGBAPer :: Percentage -> Percentage -> Percentage -> Alphavalue -> Color
mkRGBAPer r g b = RGBAPer (bound r) (bound g) (bound b)
where bound = restrict 0 100
allHex :: String -> Bool
allHex = all isHexDigit
strToLower :: String -> String
strToLower = map toLower
-------------------------------------------------------------------------------
toHexShorthand :: Color -> Color
toHexShorthand c@(Hex6 [r1,r2] [g1,g2] [b1,b2])
| r1 == r2 && g1 == g2 && b1 == b2 = Hex3 r1 g1 b1
| otherwise = c
toHexShorthand c@(Hex8 [r1,r2] [g1,g2] [b1,b2] [a1,a2])
| r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2 = Hex4 r1 g1 b1 a1
| otherwise = c
toHexShorthand h = h
Returns hexadecimal equivalent as a string of two characters
( i.e. for values in the range [ 0,15 ] , a leading zero is added ) .
word8ToHex :: Word8 -> String
word8ToHex n | 0 <= n && n < 16 = '0':[intToDigit num]
| otherwise = intToDigit sndRemainder : [intToDigit fstRemainder]
where num = fromIntegral n
fstRemainder = num `mod` 16
sndRemainder = (num `quot` 16) `mod` 16
Takes a color to a Hex6 or representation unless it 's an invalid
-- keyword, in which case it remains the same
toLongHex :: Color -> Color
toLongHex c@(Named s) = fromMaybe c (Map.lookup (T.toLower s) colorMap)
toLongHex (RGBAInt r g b a) = Hex8 (word8ToHex r) (word8ToHex g) (word8ToHex b) (ratToHex a)
where ratToHex :: Alphavalue -> String
ratToHex n = word8ToHex . round $ toRational n * 255
toLongHex (RGBInt r g b) = Hex6 (word8ToHex r) (word8ToHex g) (word8ToHex b)
toLongHex c@RGBPer{} = toLongHex $ toRGBAInt c
toLongHex c@RGBAPer{} = toLongHex $ toRGBAInt c
toLongHex c@HSL{} = toLongHex $ toRGBAInt c
toLongHex c@HSLA{} = toLongHex $ toRGBAInt c
toLongHex (Hex3 r g b) = Hex6 [r,r] [g,g] [b,b]
toLongHex (Hex4 r g b a) = Hex8 [r,r] [g,g] [b,b] [a,a]
toLongHex a = a
This fold works in general to convert hexadecimals into Integers , but we
-- only need it for Word8
hexToWord8 :: String -> Word8
hexToWord8 = fromIntegral . foldl (\s c -> s*16 + digitToInt c) 0
toRGBAInt :: Color -> Color
toRGBAInt (Named s) = maybe (error e) toRGBAInt (Map.lookup t colorMap)
where e = T.unpack $ "Invalid color keyword (" <> s <> "). Can't convert to rgba"
t = T.toLower s
toRGBAInt (Hex3 r g b) = RGBAInt (f [r,r]) (f [g,g]) (f [b,b]) 1
where f = fromIntegral . hexToWord8
toRGBAInt (Hex6 r g b) = RGBAInt (hexToWord8 r) (hexToWord8 g) (hexToWord8 b) 1
toRGBAInt (Hex4 r g b a) = RGBAInt (f [r,r]) (f [g,g]) (f [b,b]) (h [a,a])
where f = fromIntegral . hexToWord8
h = toAlphavalue . hexToWord8
toRGBAInt (Hex8 r g b a) = RGBAInt (hexToWord8 r) (hexToWord8 g)
(hexToWord8 b) (toAlphavalue $ toRational (hexToWord8 a) / 255)
toRGBAInt (RGBInt r g b) = RGBAInt r g b 1
toRGBAInt (RGBPer r g b) = RGBAInt (f r) (f g) (f b) 1
where f = round . (2.55*)
toRGBAInt (RGBAPer r g b a) = RGBAInt (f r) (f g) (f b) a
where f = round . (2.55*)
toRGBAInt c@RGBAInt{} = c
toRGBAInt (HSL h s l) = withAlpha 1 $ hslToRgb (h, s, l)
toRGBAInt (HSLA h s l a) = withAlpha a $ hslToRgb (h, s, l)
withAlpha :: Alphavalue -> (Word8, Word8, Word8) -> Color
withAlpha a (r, g, b) = RGBAInt r g b a
hslToRgb :: (Int, Percentage, Percentage) -> (Word8, Word8, Word8)
hslToRgb (hue, sat, light) | s == 0 = (lumToRgb, lumToRgb, lumToRgb)
| l <= 0.5 = hslToRgb' h l (l * (s+1))
| otherwise = hslToRgb' h l (l + s - l*s)
where h = toPercentage hue / 360
s = sat / 100
l = light / 100
lumToRgb = round (l * 255)
hslToRgb' :: Percentage -> Percentage -> Percentage -> (Word8, Word8, Word8)
hslToRgb' h l t2 = (r, g, b)
where t1 = l*2 - t2
r = round $ 255 * hueToRgb t1 t2 (h + Percentage (1 % 3))
g = round $ 255 * hueToRgb t1 t2 h
b = round $ 255 * hueToRgb t1 t2 (h - Percentage (1 % 3))
hueToRgb :: Percentage -> Percentage -> Percentage -> Percentage
hueToRgb t1 t2 hue | hue < 0 = test t1 t2 (hue+1)
| hue > 1 = test t1 t2 (hue-1)
| otherwise = test t1 t2 hue
where test :: Percentage -> Percentage -> Percentage -> Percentage
test a b h | h * 6 < 1 = a + (b-a) * 6 * h
| h * 2 < 1 = b
| h * 3 < 2 = a + (b-a) * (Percentage (2 % 3) - h) * 6
| otherwise = a
-- | A map with hex values as keys, and their minimal colorname as value
minimalColorMap :: Map.Map Color Color
minimalColorMap = Map.fromList minimalColors
where minimalColors =
[(Hex6 "ff" "00" "00", Named "red")
,(Hex6 "d2" "b4" "8c", Named "tan")
,(Hex6 "00" "ff" "ff", Named "aqua")
,(Hex6 "00" "00" "ff", Named "blue")
,(Hex6 "00" "ff" "ff", Named "cyan")
,(Hex6 "ff" "d7" "00", Named "gold")
,(Hex6 "80" "80" "80", Named "gray")
,(Hex6 "80" "80" "80", Named "grey")
,(Hex6 "00" "ff" "00", Named "lime")
,(Hex6 "00" "00" "80", Named "navy")
,(Hex6 "cd" "85" "3f", Named "peru")
,(Hex6 "ff" "c0" "cb", Named "pink")
,(Hex6 "dd" "a0" "dd", Named "plum")
,(Hex6 "ff" "fa" "fa", Named "snow")
,(Hex6 "00" "80" "80", Named "teal")
,(Hex6 "f0" "ff" "ff", Named "azure")
,(Hex6 "f5" "f5" "dc", Named "beige")
,(Hex6 "a5" "2a" "2a", Named "brown")
,(Hex6 "ff" "7f" "50", Named "coral")
,(Hex6 "00" "80" "00", Named "green")
,(Hex6 "ff" "ff" "f0", Named "ivory")
,(Hex6 "f0" "e6" "8c", Named "khaki")
,(Hex6 "fa" "f0" "e6", Named "linen")
,(Hex6 "80" "80" "00", Named "olive")
,(Hex6 "f5" "de" "b3", Named "wheat")
,(Hex6 "ff" "e4" "c4", Named "bisque")
,(Hex6 "4b" "00" "82", Named "indigo")
,(Hex6 "80" "00" "00", Named "maroon")
,(Hex6 "ff" "a5" "00", Named "orange")
,(Hex6 "da" "70" "d6", Named "orchid")
,(Hex6 "80" "00" "80", Named "purple")
,(Hex6 "fa" "80" "72", Named "salmon")
,(Hex6 "a0" "52" "2d", Named "sienna")
,(Hex6 "c0" "c0" "c0", Named "silver")
,(Hex6 "ff" "63" "47", Named "tomato")
,(Hex6 "ee" "82" "ee", Named "violet")]
-- | Mapping between color names and hex values
colorMap :: Map.Map Text Color
colorMap = Map.fromList keywordColors
-- | Pairs of color keywords, and their equivalent hexadecimal value.
keywordColors :: [(Text, Color)]
keywordColors = map (first T.toLower)
[("aliceblue", Hex6 "f0" "f8" "ff")
,("antiquewhite", Hex6 "fa" "eb" "d7")
,("aqua", Hex6 "00" "ff" "ff")
,("aquamarine", Hex6 "7f" "ff" "d4")
,("azure", Hex6 "f0" "ff" "ff")
,("beige", Hex6 "f5" "f5" "dc")
,("bisque", Hex6 "ff" "e4" "c4")
,("black", Hex6 "00" "00" "00")
,("blanchedalmond", Hex6 "ff" "eb" "cd")
,("blue", Hex6 "00" "00" "ff")
,("blueviolet", Hex6 "8a" "2b" "e2")
,("brown", Hex6 "a5" "2a" "2a")
,("burlywood", Hex6 "de" "b8" "87")
,("cadetblue", Hex6 "5f" "9e" "a0")
,("chartreuse", Hex6 "7f" "ff" "00")
,("chocolate", Hex6 "d2" "69" "1e")
,("coral", Hex6 "ff" "7f" "50")
,("cornflowerblue", Hex6 "64" "95" "ed")
,("cornsilk", Hex6 "ff" "f8" "dc")
,("crimson", Hex6 "dc" "14" "3c")
,("cyan", Hex6 "00" "ff" "ff")
,("darkblue", Hex6 "00" "00" "8b")
,("darkcyan", Hex6 "00" "8b" "8b")
,("darkgoldenrod", Hex6 "b8" "86" "0b")
,("darkgray", Hex6 "a9" "a9" "a9")
,("darkgrey", Hex6 "a9" "a9" "a9")
,("darkgreen", Hex6 "00" "64" "00")
,("darkkhaki", Hex6 "bd" "b7" "6b")
,("darkmagenta", Hex6 "8b" "00" "8b")
,("darkolivegreen", Hex6 "55" "6b" "2f")
,("darkorange", Hex6 "ff" "8c" "00")
,("darkorchid", Hex6 "99" "32" "cc")
,("darkred", Hex6 "8b" "00" "00")
,("darksalmon", Hex6 "e9" "96" "7a")
,("darkseagreen", Hex6 "8f" "bc" "8f")
,("darkslateblue", Hex6 "48" "3d" "8b")
,("darkslategray", Hex6 "2f" "4f" "4f")
,("darkslategrey", Hex6 "2f" "4f" "4f")
,("darkturquoise", Hex6 "00" "ce" "d1")
,("darkviolet", Hex6 "94" "00" "d3")
,("deeppink", Hex6 "ff" "14" "93")
,("deepskyblue", Hex6 "00" "bf" "ff")
,("dimgray", Hex6 "69" "69" "69")
,("dimgrey", Hex6 "69" "69" "69")
,("dodgerblue", Hex6 "1e" "90" "ff")
,("firebrick", Hex6 "b2" "22" "22")
,("floralwhite", Hex6 "ff" "fa" "f0")
,("forestgreen", Hex6 "22" "8b" "22")
,("fuchsia", Hex6 "ff" "00" "ff")
,("gainsboro", Hex6 "dc" "dc" "dc")
,("ghostwhite", Hex6 "f8" "f8" "ff")
,("gold", Hex6 "ff" "d7" "00")
,("goldenrod", Hex6 "da" "a5" "20")
,("gray", Hex6 "80" "80" "80")
,("grey", Hex6 "80" "80" "80")
,("green", Hex6 "00" "80" "00")
,("greenyellow", Hex6 "ad" "ff" "2f")
,("honeydew", Hex6 "f0" "ff" "f0")
,("hotpink", Hex6 "ff" "69" "b4")
,("indianred", Hex6 "cd" "5c" "5c")
,("indigo", Hex6 "4b" "00" "82")
,("ivory", Hex6 "ff" "ff" "f0")
,("khaki", Hex6 "f0" "e6" "8c")
,("lavender", Hex6 "e6" "e6" "fa")
,("lavenderblush", Hex6 "ff" "f0" "f5")
,("lawngreen", Hex6 "7c" "fc" "00")
,("lemonchiffon", Hex6 "ff" "fa" "cd")
,("lightblue", Hex6 "ad" "d8" "e6")
,("lightcoral", Hex6 "f0" "80" "80")
,("lightcyan", Hex6 "e0" "ff" "ff")
,("lightgoldenrodyellow", Hex6 "fa" "fa" "d2")
,("lightgray", Hex6 "d3" "d3" "d3")
,("lightgrey", Hex6 "d3" "d3" "d3")
,("lightgreen", Hex6 "90" "ee" "90")
,("lightpink", Hex6 "ff" "b6" "c1")
,("lightsalmon", Hex6 "ff" "a0" "7a")
,("lightseagreen", Hex6 "20" "b2" "aa")
,("lightskyblue", Hex6 "87" "ce" "fa")
,("lightslategray", Hex6 "77" "88" "99")
,("lightslategrey", Hex6 "77" "88" "99")
,("lightsteelblue", Hex6 "b0" "c4" "de")
,("lightyellow", Hex6 "ff" "ff" "e0")
,("lime", Hex6 "00" "ff" "00")
,("limegreen", Hex6 "32" "cd" "32")
,("linen", Hex6 "fa" "f0" "e6")
,("magenta", Hex6 "ff" "00" "ff")
,("maroon", Hex6 "80" "00" "00")
,("mediumaquamarine", Hex6 "66" "cd" "aa")
,("mediumblue", Hex6 "00" "00" "cd")
,("mediumorchid", Hex6 "ba" "55" "d3")
,("mediumpurple", Hex6 "93" "70" "d8")
,("mediumseagreen", Hex6 "3c" "b3" "71")
,("mediumslateblue", Hex6 "7b" "68" "ee")
,("mediumspringgreen", Hex6 "00" "fa" "9a")
,("mediumturquoise", Hex6 "48" "d1" "cc")
,("mediumvioletred", Hex6 "c7" "15" "85")
,("midnightblue", Hex6 "19" "19" "70")
,("mintcream", Hex6 "f5" "ff" "fa")
,("mistyrose", Hex6 "ff" "e4" "e1")
,("moccasin", Hex6 "ff" "e4" "b5")
,("navajowhite", Hex6 "ff" "de" "ad")
,("navy", Hex6 "00" "00" "80")
,("oldlace", Hex6 "fd" "f5" "e6")
,("olive", Hex6 "80" "80" "00")
,("olivedrab", Hex6 "6b" "8e" "23")
,("orange", Hex6 "ff" "a5" "00")
,("orangered", Hex6 "ff" "45" "00")
,("orchid", Hex6 "da" "70" "d6")
,("palegoldenrod", Hex6 "ee" "e8" "aa")
,("palegreen", Hex6 "98" "fb" "98")
,("paleturquoise", Hex6 "af" "ee" "ee")
,("palevioletred", Hex6 "d8" "70" "93")
,("papayawhip", Hex6 "ff" "ef" "d5")
,("peachpuff", Hex6 "ff" "da" "b9")
,("peru", Hex6 "cd" "85" "3f")
,("pink", Hex6 "ff" "c0" "cb")
,("plum", Hex6 "dd" "a0" "dd")
,("powderblue", Hex6 "b0" "e0" "e6")
,("purple", Hex6 "80" "00" "80")
,("red", Hex6 "ff" "00" "00")
,("rosybrown", Hex6 "bc" "8f" "8f")
,("royalblue", Hex6 "41" "69" "e1")
,("saddlebrown", Hex6 "8b" "45" "13")
,("salmon", Hex6 "fa" "80" "72")
,("sandybrown", Hex6 "f4" "a4" "60")
,("seagreen", Hex6 "2e" "8b" "57")
,("seashell", Hex6 "ff" "f5" "ee")
,("sienna", Hex6 "a0" "52" "2d")
,("silver", Hex6 "c0" "c0" "c0")
,("skyblue", Hex6 "87" "ce" "eb")
,("slateblue", Hex6 "6a" "5a" "cd")
,("slategray", Hex6 "70" "80" "90")
,("slategrey", Hex6 "70" "80" "90")
,("snow", Hex6 "ff" "fa" "fa")
,("springgreen", Hex6 "00" "ff" "7f")
,("steelblue", Hex6 "46" "82" "b4")
,("tan", Hex6 "d2" "b4" "8c")
,("teal", Hex6 "00" "80" "80")
,("thistle", Hex6 "d8" "bf" "d8")
,("transparent", Hex8 "00" "00" "00" "00")
,("tomato", Hex6 "ff" "63" "47")
,("turquoise", Hex6 "40" "e0" "d0")
,("violet", Hex6 "ee" "82" "ee")
,("wheat", Hex6 "f5" "de" "b3")
,("white", Hex6 "ff" "ff" "ff")
,("whitesmoke", Hex6 "f5" "f5" "f5")
,("yellow", Hex6 "ff" "ff" "00")
,("yellowgreen", Hex6 "9a" "cd" "32")]
| null | https://raw.githubusercontent.com/contivero/hasmin/2a7604159b51e69c5e9c564dce53cb3ab09ae22b/src/Hasmin/Types/Color.hs | haskell | # LANGUAGE OverloadedStrings #
---------------------------------------------------------------------------
|
Module : Hasmin.Types.Color
License : BSD3
Stability : experimental
Portability : unknown
---------------------------------------------------------------------------
| CSS <-color/#colorunits \<color\>>
data type.
| Equality is slightly relaxed, since percentages and real numbers are mapped
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Smart constructors
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-----------------------------------------------------------------------------
keyword, in which case it remains the same
only need it for Word8
| A map with hex values as keys, and their minimal colorname as value
| Mapping between color names and hex values
| Pairs of color keywords, and their equivalent hexadecimal value. | Copyright : ( c ) 2017
module Hasmin.Types.Color
( Color(Named)
, mkHex3
, mkHex4
, mkHex6
, mkHex8
, mkNamed
, mkHSL
, mkHSLA
, mkRGBInt
, mkRGBPer
, mkRGBAInt
, mkRGBAPer
, keywordColors
, minifyColor
) where
import Control.Arrow (first)
import Control.Monad.Reader (asks)
import Data.Monoid ((<>))
import Data.Char (isHexDigit, digitToInt, intToDigit, toLower)
import Data.Maybe (fromMaybe)
import Data.Ratio ((%))
import Data.Text (Text)
import Data.Text.Lazy.Builder (Builder, singleton)
import qualified Data.Text.Lazy.Builder as B
import Data.Word (Word8)
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
import Hasmin.Class
import Hasmin.Config
import Hasmin.Types.Numeric
import Hasmin.Utils
data Color = Hex3 Char Char Char
| Hex4 Char Char Char Char
| Hex6 String String String
| Hex8 String String String String
| Named Text
| RGBInt Word8 Word8 Word8
| RGBPer Percentage Percentage Percentage
| RGBAInt Word8 Word8 Word8 Alphavalue
| RGBAPer Percentage Percentage Percentage Alphavalue
| HSL Int Percentage Percentage
| HSLA Int Percentage Percentage Alphavalue
deriving (Show)
to the [ 0,255 ] integer range , and then compared
instance Eq Color where
(Hex6 r1 g1 b1) == (Hex6 r2 g2 b2) =
r1 == r2 && g1 == g2 && b1 == b2
(Hex8 r1 g1 b1 a1) == (Hex8 r2 g2 b2 a2) =
r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2
(Hex8 r1 g1 b1 a) == (Hex6 r2 g2 b2)
| a == "ff" = r1 == r2 && g1 == g2 && b1 == b2
| otherwise = False
(Hex6 r1 g1 b1) == (Hex8 r2 g2 b2 a)
| a == "ff" = r1 == r2 && g1 == g2 && b1 == b2
| otherwise = False
c1 == (Named s) = Map.lookup (T.toLower s) colorMap == Just c1
(Named s) == c2 = c2 == Named s
a == b = toLongHex a == toLongHex b
instance Ord Color where
(Hex6 r1 g1 b1) <= (Hex6 r2 g2 b2) =
r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && b1 <= b2))
(Hex8 r1 g1 b1 a1) <= (Hex8 r2 g2 b2 a2) =
r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && (b1 < b2 || (b1 == b2 && a1 <= a2))))
(Hex8 r1 g1 b1 a) <= (Hex6 r2 g2 b2)
| a == "ff" = r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && b1 <= b2))
| otherwise = True
(Hex6 r1 g1 b1) <= (Hex8 r2 g2 b2 a)
| a == "ff" = r1 < r2 || r1 == r2 && (g1 < g2 || (g1 == g2 && b1 <= b2))
| otherwise = False
c1 <= c2 = toLongHex c1 <= toLongHex c2
instance Minifiable Color where
minify c = do
colSettings <- asks colorSettings
pure $ case colSettings of
ColorMinOn -> minifyColor c
ColorMinOff -> c
minifyColor :: Color -> Color
minifyColor c@Hex6{} = fromMaybe (toHexShorthand c) (Map.lookup c minimalColorMap)
minifyColor c@(Hex8 r g b a)
| a == "ff" = minifyColor (Hex6 r g b)
| otherwise = toHexShorthand c
minifyColor c@(RGBAPer r g b a)
| a >= 1 = minifyColor (RGBPer r g b)
| otherwise = minifyColor $ toLongHex c
minifyColor c@(RGBAInt r g b a)
| a >= 1 = minifyColor (RGBInt r g b)
| otherwise = minifyColor $ toLongHex c
minifyColor c@(HSLA h s l a)
| a >= 1 = minifyColor (HSL h s l)
| otherwise = minifyColor $ toLongHex c
minifyColor c = case toLongHex c of
n@(Named _) -> n
other -> minifyColor other
instance ToText Color where
toBuilder (RGBInt r g b) = "rgb(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b]
toBuilder (RGBAInt r g b a) = "rgba(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b, toText a]
toBuilder (RGBPer r g b) = "rgb(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b]
toBuilder (RGBAPer r g b a) = "rgba(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText r, toText g, toText b, toText a]
toBuilder (HSL h s l) = "hsl(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText h, toText s, toText l]
toBuilder (HSLA h s l a) = "hsla(" <> values <> singleton ')'
where values = toBuilderWithCommas [toText h, toText s, toText l, toText a]
toBuilder (Named a) = B.fromText a
toBuilder (Hex3 r g b) = singleton '#' <> singleton r <> singleton g <> singleton b
toBuilder (Hex4 r g b a) = singleton '#' <> singleton r <> singleton g <> singleton b <> singleton a
toBuilder (Hex6 r g b) = B.fromString $ mconcat ["#", r, g, b]
toBuilder (Hex8 r g b a) = B.fromString $ mconcat ["#", r, g, b, a]
toBuilderWithCommas :: [Text] -> Builder
toBuilderWithCommas = mconcatIntersperse B.fromText (singleton ',')
mkHex3 :: Char -> Char -> Char -> Color
mkHex3 r g b
| isHexDigit r && isHexDigit g && isHexDigit b = Hex3 (toLower r) (toLower g) (toLower b)
| otherwise = error "passing non hexadecimal arguments to mkHex3"
mkHex6 :: String -> String -> String -> Color
mkHex6 r g b
| allHex r && allHex g && allHex b = Hex6 (strToLower r) (strToLower g) (strToLower b)
| otherwise = error "passing non hexadecimal arguments to mkHex6"
mkHex4 :: Char -> Char -> Char -> Char -> Color
mkHex4 r g b a
| isHexDigit r && isHexDigit g && isHexDigit b && isHexDigit a = Hex4 (toLower r) (toLower g) (toLower b) (toLower a)
| otherwise = error "passing non hexadecimal arguments to mkHex4"
mkHex8 :: String -> String -> String -> String -> Color
mkHex8 r g b a
| allHex r && allHex g && allHex b = Hex8 (strToLower r) (strToLower g) (strToLower b) (strToLower a)
| otherwise = error "passing non hexadecimal arguments to mkHex6"
mkNamed :: Text -> Maybe Color
mkNamed colorName
| Map.member name colorMap = Just (Named name)
| otherwise = Nothing
where name = T.toLower colorName
mkHSL :: Int -> Percentage -> Percentage -> Color
mkHSL h s l = HSL (h `mod` 360) (bound s) (bound l)
where bound = restrict 0 100
mkHSLA :: Int -> Percentage -> Percentage -> Alphavalue -> Color
mkHSLA h s l = HSLA (h `mod` 360) (bound s) (bound l)
where bound = restrict 0 100
mkRGBInt :: Word8 -> Word8 -> Word8 -> Color
mkRGBInt r g b = RGBInt (bound r) (bound g) (bound b)
where bound = restrict 0 255
mkRGBPer :: Percentage -> Percentage -> Percentage -> Color
mkRGBPer r g b = RGBPer (bound r) (bound g) (bound b)
where bound = restrict 0 100
mkRGBAInt :: Word8 -> Word8 -> Word8 -> Alphavalue -> Color
mkRGBAInt r g b = RGBAInt (bound r) (bound g) (bound b)
where bound = restrict 0 255
mkRGBAPer :: Percentage -> Percentage -> Percentage -> Alphavalue -> Color
mkRGBAPer r g b = RGBAPer (bound r) (bound g) (bound b)
where bound = restrict 0 100
allHex :: String -> Bool
allHex = all isHexDigit
strToLower :: String -> String
strToLower = map toLower
toHexShorthand :: Color -> Color
toHexShorthand c@(Hex6 [r1,r2] [g1,g2] [b1,b2])
| r1 == r2 && g1 == g2 && b1 == b2 = Hex3 r1 g1 b1
| otherwise = c
toHexShorthand c@(Hex8 [r1,r2] [g1,g2] [b1,b2] [a1,a2])
| r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2 = Hex4 r1 g1 b1 a1
| otherwise = c
toHexShorthand h = h
Returns hexadecimal equivalent as a string of two characters
( i.e. for values in the range [ 0,15 ] , a leading zero is added ) .
word8ToHex :: Word8 -> String
word8ToHex n | 0 <= n && n < 16 = '0':[intToDigit num]
| otherwise = intToDigit sndRemainder : [intToDigit fstRemainder]
where num = fromIntegral n
fstRemainder = num `mod` 16
sndRemainder = (num `quot` 16) `mod` 16
Takes a color to a Hex6 or representation unless it 's an invalid
toLongHex :: Color -> Color
toLongHex c@(Named s) = fromMaybe c (Map.lookup (T.toLower s) colorMap)
toLongHex (RGBAInt r g b a) = Hex8 (word8ToHex r) (word8ToHex g) (word8ToHex b) (ratToHex a)
where ratToHex :: Alphavalue -> String
ratToHex n = word8ToHex . round $ toRational n * 255
toLongHex (RGBInt r g b) = Hex6 (word8ToHex r) (word8ToHex g) (word8ToHex b)
toLongHex c@RGBPer{} = toLongHex $ toRGBAInt c
toLongHex c@RGBAPer{} = toLongHex $ toRGBAInt c
toLongHex c@HSL{} = toLongHex $ toRGBAInt c
toLongHex c@HSLA{} = toLongHex $ toRGBAInt c
toLongHex (Hex3 r g b) = Hex6 [r,r] [g,g] [b,b]
toLongHex (Hex4 r g b a) = Hex8 [r,r] [g,g] [b,b] [a,a]
toLongHex a = a
This fold works in general to convert hexadecimals into Integers , but we
hexToWord8 :: String -> Word8
hexToWord8 = fromIntegral . foldl (\s c -> s*16 + digitToInt c) 0
toRGBAInt :: Color -> Color
toRGBAInt (Named s) = maybe (error e) toRGBAInt (Map.lookup t colorMap)
where e = T.unpack $ "Invalid color keyword (" <> s <> "). Can't convert to rgba"
t = T.toLower s
toRGBAInt (Hex3 r g b) = RGBAInt (f [r,r]) (f [g,g]) (f [b,b]) 1
where f = fromIntegral . hexToWord8
toRGBAInt (Hex6 r g b) = RGBAInt (hexToWord8 r) (hexToWord8 g) (hexToWord8 b) 1
toRGBAInt (Hex4 r g b a) = RGBAInt (f [r,r]) (f [g,g]) (f [b,b]) (h [a,a])
where f = fromIntegral . hexToWord8
h = toAlphavalue . hexToWord8
toRGBAInt (Hex8 r g b a) = RGBAInt (hexToWord8 r) (hexToWord8 g)
(hexToWord8 b) (toAlphavalue $ toRational (hexToWord8 a) / 255)
toRGBAInt (RGBInt r g b) = RGBAInt r g b 1
toRGBAInt (RGBPer r g b) = RGBAInt (f r) (f g) (f b) 1
where f = round . (2.55*)
toRGBAInt (RGBAPer r g b a) = RGBAInt (f r) (f g) (f b) a
where f = round . (2.55*)
toRGBAInt c@RGBAInt{} = c
toRGBAInt (HSL h s l) = withAlpha 1 $ hslToRgb (h, s, l)
toRGBAInt (HSLA h s l a) = withAlpha a $ hslToRgb (h, s, l)
withAlpha :: Alphavalue -> (Word8, Word8, Word8) -> Color
withAlpha a (r, g, b) = RGBAInt r g b a
hslToRgb :: (Int, Percentage, Percentage) -> (Word8, Word8, Word8)
hslToRgb (hue, sat, light) | s == 0 = (lumToRgb, lumToRgb, lumToRgb)
| l <= 0.5 = hslToRgb' h l (l * (s+1))
| otherwise = hslToRgb' h l (l + s - l*s)
where h = toPercentage hue / 360
s = sat / 100
l = light / 100
lumToRgb = round (l * 255)
hslToRgb' :: Percentage -> Percentage -> Percentage -> (Word8, Word8, Word8)
hslToRgb' h l t2 = (r, g, b)
where t1 = l*2 - t2
r = round $ 255 * hueToRgb t1 t2 (h + Percentage (1 % 3))
g = round $ 255 * hueToRgb t1 t2 h
b = round $ 255 * hueToRgb t1 t2 (h - Percentage (1 % 3))
hueToRgb :: Percentage -> Percentage -> Percentage -> Percentage
hueToRgb t1 t2 hue | hue < 0 = test t1 t2 (hue+1)
| hue > 1 = test t1 t2 (hue-1)
| otherwise = test t1 t2 hue
where test :: Percentage -> Percentage -> Percentage -> Percentage
test a b h | h * 6 < 1 = a + (b-a) * 6 * h
| h * 2 < 1 = b
| h * 3 < 2 = a + (b-a) * (Percentage (2 % 3) - h) * 6
| otherwise = a
minimalColorMap :: Map.Map Color Color
minimalColorMap = Map.fromList minimalColors
where minimalColors =
[(Hex6 "ff" "00" "00", Named "red")
,(Hex6 "d2" "b4" "8c", Named "tan")
,(Hex6 "00" "ff" "ff", Named "aqua")
,(Hex6 "00" "00" "ff", Named "blue")
,(Hex6 "00" "ff" "ff", Named "cyan")
,(Hex6 "ff" "d7" "00", Named "gold")
,(Hex6 "80" "80" "80", Named "gray")
,(Hex6 "80" "80" "80", Named "grey")
,(Hex6 "00" "ff" "00", Named "lime")
,(Hex6 "00" "00" "80", Named "navy")
,(Hex6 "cd" "85" "3f", Named "peru")
,(Hex6 "ff" "c0" "cb", Named "pink")
,(Hex6 "dd" "a0" "dd", Named "plum")
,(Hex6 "ff" "fa" "fa", Named "snow")
,(Hex6 "00" "80" "80", Named "teal")
,(Hex6 "f0" "ff" "ff", Named "azure")
,(Hex6 "f5" "f5" "dc", Named "beige")
,(Hex6 "a5" "2a" "2a", Named "brown")
,(Hex6 "ff" "7f" "50", Named "coral")
,(Hex6 "00" "80" "00", Named "green")
,(Hex6 "ff" "ff" "f0", Named "ivory")
,(Hex6 "f0" "e6" "8c", Named "khaki")
,(Hex6 "fa" "f0" "e6", Named "linen")
,(Hex6 "80" "80" "00", Named "olive")
,(Hex6 "f5" "de" "b3", Named "wheat")
,(Hex6 "ff" "e4" "c4", Named "bisque")
,(Hex6 "4b" "00" "82", Named "indigo")
,(Hex6 "80" "00" "00", Named "maroon")
,(Hex6 "ff" "a5" "00", Named "orange")
,(Hex6 "da" "70" "d6", Named "orchid")
,(Hex6 "80" "00" "80", Named "purple")
,(Hex6 "fa" "80" "72", Named "salmon")
,(Hex6 "a0" "52" "2d", Named "sienna")
,(Hex6 "c0" "c0" "c0", Named "silver")
,(Hex6 "ff" "63" "47", Named "tomato")
,(Hex6 "ee" "82" "ee", Named "violet")]
colorMap :: Map.Map Text Color
colorMap = Map.fromList keywordColors
keywordColors :: [(Text, Color)]
keywordColors = map (first T.toLower)
[("aliceblue", Hex6 "f0" "f8" "ff")
,("antiquewhite", Hex6 "fa" "eb" "d7")
,("aqua", Hex6 "00" "ff" "ff")
,("aquamarine", Hex6 "7f" "ff" "d4")
,("azure", Hex6 "f0" "ff" "ff")
,("beige", Hex6 "f5" "f5" "dc")
,("bisque", Hex6 "ff" "e4" "c4")
,("black", Hex6 "00" "00" "00")
,("blanchedalmond", Hex6 "ff" "eb" "cd")
,("blue", Hex6 "00" "00" "ff")
,("blueviolet", Hex6 "8a" "2b" "e2")
,("brown", Hex6 "a5" "2a" "2a")
,("burlywood", Hex6 "de" "b8" "87")
,("cadetblue", Hex6 "5f" "9e" "a0")
,("chartreuse", Hex6 "7f" "ff" "00")
,("chocolate", Hex6 "d2" "69" "1e")
,("coral", Hex6 "ff" "7f" "50")
,("cornflowerblue", Hex6 "64" "95" "ed")
,("cornsilk", Hex6 "ff" "f8" "dc")
,("crimson", Hex6 "dc" "14" "3c")
,("cyan", Hex6 "00" "ff" "ff")
,("darkblue", Hex6 "00" "00" "8b")
,("darkcyan", Hex6 "00" "8b" "8b")
,("darkgoldenrod", Hex6 "b8" "86" "0b")
,("darkgray", Hex6 "a9" "a9" "a9")
,("darkgrey", Hex6 "a9" "a9" "a9")
,("darkgreen", Hex6 "00" "64" "00")
,("darkkhaki", Hex6 "bd" "b7" "6b")
,("darkmagenta", Hex6 "8b" "00" "8b")
,("darkolivegreen", Hex6 "55" "6b" "2f")
,("darkorange", Hex6 "ff" "8c" "00")
,("darkorchid", Hex6 "99" "32" "cc")
,("darkred", Hex6 "8b" "00" "00")
,("darksalmon", Hex6 "e9" "96" "7a")
,("darkseagreen", Hex6 "8f" "bc" "8f")
,("darkslateblue", Hex6 "48" "3d" "8b")
,("darkslategray", Hex6 "2f" "4f" "4f")
,("darkslategrey", Hex6 "2f" "4f" "4f")
,("darkturquoise", Hex6 "00" "ce" "d1")
,("darkviolet", Hex6 "94" "00" "d3")
,("deeppink", Hex6 "ff" "14" "93")
,("deepskyblue", Hex6 "00" "bf" "ff")
,("dimgray", Hex6 "69" "69" "69")
,("dimgrey", Hex6 "69" "69" "69")
,("dodgerblue", Hex6 "1e" "90" "ff")
,("firebrick", Hex6 "b2" "22" "22")
,("floralwhite", Hex6 "ff" "fa" "f0")
,("forestgreen", Hex6 "22" "8b" "22")
,("fuchsia", Hex6 "ff" "00" "ff")
,("gainsboro", Hex6 "dc" "dc" "dc")
,("ghostwhite", Hex6 "f8" "f8" "ff")
,("gold", Hex6 "ff" "d7" "00")
,("goldenrod", Hex6 "da" "a5" "20")
,("gray", Hex6 "80" "80" "80")
,("grey", Hex6 "80" "80" "80")
,("green", Hex6 "00" "80" "00")
,("greenyellow", Hex6 "ad" "ff" "2f")
,("honeydew", Hex6 "f0" "ff" "f0")
,("hotpink", Hex6 "ff" "69" "b4")
,("indianred", Hex6 "cd" "5c" "5c")
,("indigo", Hex6 "4b" "00" "82")
,("ivory", Hex6 "ff" "ff" "f0")
,("khaki", Hex6 "f0" "e6" "8c")
,("lavender", Hex6 "e6" "e6" "fa")
,("lavenderblush", Hex6 "ff" "f0" "f5")
,("lawngreen", Hex6 "7c" "fc" "00")
,("lemonchiffon", Hex6 "ff" "fa" "cd")
,("lightblue", Hex6 "ad" "d8" "e6")
,("lightcoral", Hex6 "f0" "80" "80")
,("lightcyan", Hex6 "e0" "ff" "ff")
,("lightgoldenrodyellow", Hex6 "fa" "fa" "d2")
,("lightgray", Hex6 "d3" "d3" "d3")
,("lightgrey", Hex6 "d3" "d3" "d3")
,("lightgreen", Hex6 "90" "ee" "90")
,("lightpink", Hex6 "ff" "b6" "c1")
,("lightsalmon", Hex6 "ff" "a0" "7a")
,("lightseagreen", Hex6 "20" "b2" "aa")
,("lightskyblue", Hex6 "87" "ce" "fa")
,("lightslategray", Hex6 "77" "88" "99")
,("lightslategrey", Hex6 "77" "88" "99")
,("lightsteelblue", Hex6 "b0" "c4" "de")
,("lightyellow", Hex6 "ff" "ff" "e0")
,("lime", Hex6 "00" "ff" "00")
,("limegreen", Hex6 "32" "cd" "32")
,("linen", Hex6 "fa" "f0" "e6")
,("magenta", Hex6 "ff" "00" "ff")
,("maroon", Hex6 "80" "00" "00")
,("mediumaquamarine", Hex6 "66" "cd" "aa")
,("mediumblue", Hex6 "00" "00" "cd")
,("mediumorchid", Hex6 "ba" "55" "d3")
,("mediumpurple", Hex6 "93" "70" "d8")
,("mediumseagreen", Hex6 "3c" "b3" "71")
,("mediumslateblue", Hex6 "7b" "68" "ee")
,("mediumspringgreen", Hex6 "00" "fa" "9a")
,("mediumturquoise", Hex6 "48" "d1" "cc")
,("mediumvioletred", Hex6 "c7" "15" "85")
,("midnightblue", Hex6 "19" "19" "70")
,("mintcream", Hex6 "f5" "ff" "fa")
,("mistyrose", Hex6 "ff" "e4" "e1")
,("moccasin", Hex6 "ff" "e4" "b5")
,("navajowhite", Hex6 "ff" "de" "ad")
,("navy", Hex6 "00" "00" "80")
,("oldlace", Hex6 "fd" "f5" "e6")
,("olive", Hex6 "80" "80" "00")
,("olivedrab", Hex6 "6b" "8e" "23")
,("orange", Hex6 "ff" "a5" "00")
,("orangered", Hex6 "ff" "45" "00")
,("orchid", Hex6 "da" "70" "d6")
,("palegoldenrod", Hex6 "ee" "e8" "aa")
,("palegreen", Hex6 "98" "fb" "98")
,("paleturquoise", Hex6 "af" "ee" "ee")
,("palevioletred", Hex6 "d8" "70" "93")
,("papayawhip", Hex6 "ff" "ef" "d5")
,("peachpuff", Hex6 "ff" "da" "b9")
,("peru", Hex6 "cd" "85" "3f")
,("pink", Hex6 "ff" "c0" "cb")
,("plum", Hex6 "dd" "a0" "dd")
,("powderblue", Hex6 "b0" "e0" "e6")
,("purple", Hex6 "80" "00" "80")
,("red", Hex6 "ff" "00" "00")
,("rosybrown", Hex6 "bc" "8f" "8f")
,("royalblue", Hex6 "41" "69" "e1")
,("saddlebrown", Hex6 "8b" "45" "13")
,("salmon", Hex6 "fa" "80" "72")
,("sandybrown", Hex6 "f4" "a4" "60")
,("seagreen", Hex6 "2e" "8b" "57")
,("seashell", Hex6 "ff" "f5" "ee")
,("sienna", Hex6 "a0" "52" "2d")
,("silver", Hex6 "c0" "c0" "c0")
,("skyblue", Hex6 "87" "ce" "eb")
,("slateblue", Hex6 "6a" "5a" "cd")
,("slategray", Hex6 "70" "80" "90")
,("slategrey", Hex6 "70" "80" "90")
,("snow", Hex6 "ff" "fa" "fa")
,("springgreen", Hex6 "00" "ff" "7f")
,("steelblue", Hex6 "46" "82" "b4")
,("tan", Hex6 "d2" "b4" "8c")
,("teal", Hex6 "00" "80" "80")
,("thistle", Hex6 "d8" "bf" "d8")
,("transparent", Hex8 "00" "00" "00" "00")
,("tomato", Hex6 "ff" "63" "47")
,("turquoise", Hex6 "40" "e0" "d0")
,("violet", Hex6 "ee" "82" "ee")
,("wheat", Hex6 "f5" "de" "b3")
,("white", Hex6 "ff" "ff" "ff")
,("whitesmoke", Hex6 "f5" "f5" "f5")
,("yellow", Hex6 "ff" "ff" "00")
,("yellowgreen", Hex6 "9a" "cd" "32")]
|
b9da323f6d8efd0096d36a7bb0234efea890b71606c77a7df7c2102c7f7da125 | albertoruiz/easyVision | param1.hs | import EasyVision
smooth cam = do
o <- createParameters [("sigma",realParam 3 0 20)]
return $ do
x <- cam
sigma <- getParam o "sigma"
return (gaussS sigma x)
main = run $ camera ~> float . grayscale >>= smooth >>= observe "gauss" id
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/old/tutorial/param1.hs | haskell | import EasyVision
smooth cam = do
o <- createParameters [("sigma",realParam 3 0 20)]
return $ do
x <- cam
sigma <- getParam o "sigma"
return (gaussS sigma x)
main = run $ camera ~> float . grayscale >>= smooth >>= observe "gauss" id
| |
ada12ee038b36ab969e01779bdb39d8ebd25703c00daf8142f4ecc1a84005280 | realworldocaml/book | test_recursive_groups.ml | open Base
[@@@warning "-37"]
module _ = struct
type t = T of int [@@deriving_inline sexp_grammar]
let _ = fun (_ : t) -> ()
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped =
Lazy
(lazy
(Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag
{ name = "T"
; clause_kind =
List_clause { args = Cons (int_sexp_grammar.untyped, Empty) }
}
]
}))
}
;;
let _ = t_sexp_grammar
[@@@end]
end
module _ = struct
type t =
| T_int of int
| T_u of u
and u =
| U_int of int
| U_t of t
[@@deriving_inline sexp_grammar]
let _ = fun (_ : t) -> ()
let _ = fun (_ : u) -> ()
include struct
open struct
let (grammars__001_ : Sexplib0.Sexp_grammar.defn Stdlib.List.t Stdlib.Lazy.t) =
lazy
(let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped = Tycon ("t", []) }
and (u_sexp_grammar : u Sexplib0.Sexp_grammar.t) =
{ untyped = Tycon ("u", []) }
in
[ { tycon = "t"
; tyvars = []
; grammar =
Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag
{ name = "T_int"
; clause_kind =
List_clause
{ args = Cons (int_sexp_grammar.untyped, Empty) }
}
; No_tag
{ name = "T_u"
; clause_kind =
List_clause { args = Cons (u_sexp_grammar.untyped, Empty) }
}
]
}
}
; { tycon = "u"
; tyvars = []
; grammar =
Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag
{ name = "U_int"
; clause_kind =
List_clause
{ args = Cons (int_sexp_grammar.untyped, Empty) }
}
; No_tag
{ name = "U_t"
; clause_kind =
List_clause { args = Cons (t_sexp_grammar.untyped, Empty) }
}
]
}
}
])
;;
let _ = grammars__001_
end
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped =
Lazy (lazy (Recursive (Tycon ("t", []), Stdlib.Lazy.force grammars__001_)))
}
and (u_sexp_grammar : u Sexplib0.Sexp_grammar.t) =
{ untyped =
Lazy (lazy (Recursive (Tycon ("u", []), Stdlib.Lazy.force grammars__001_)))
}
;;
let _ = t_sexp_grammar
and _ = u_sexp_grammar
end
[@@@end]
end
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ppx_sexp_conv/test/sexp_grammar/test_recursive_groups.ml | ocaml | open Base
[@@@warning "-37"]
module _ = struct
type t = T of int [@@deriving_inline sexp_grammar]
let _ = fun (_ : t) -> ()
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped =
Lazy
(lazy
(Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag
{ name = "T"
; clause_kind =
List_clause { args = Cons (int_sexp_grammar.untyped, Empty) }
}
]
}))
}
;;
let _ = t_sexp_grammar
[@@@end]
end
module _ = struct
type t =
| T_int of int
| T_u of u
and u =
| U_int of int
| U_t of t
[@@deriving_inline sexp_grammar]
let _ = fun (_ : t) -> ()
let _ = fun (_ : u) -> ()
include struct
open struct
let (grammars__001_ : Sexplib0.Sexp_grammar.defn Stdlib.List.t Stdlib.Lazy.t) =
lazy
(let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped = Tycon ("t", []) }
and (u_sexp_grammar : u Sexplib0.Sexp_grammar.t) =
{ untyped = Tycon ("u", []) }
in
[ { tycon = "t"
; tyvars = []
; grammar =
Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag
{ name = "T_int"
; clause_kind =
List_clause
{ args = Cons (int_sexp_grammar.untyped, Empty) }
}
; No_tag
{ name = "T_u"
; clause_kind =
List_clause { args = Cons (u_sexp_grammar.untyped, Empty) }
}
]
}
}
; { tycon = "u"
; tyvars = []
; grammar =
Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag
{ name = "U_int"
; clause_kind =
List_clause
{ args = Cons (int_sexp_grammar.untyped, Empty) }
}
; No_tag
{ name = "U_t"
; clause_kind =
List_clause { args = Cons (t_sexp_grammar.untyped, Empty) }
}
]
}
}
])
;;
let _ = grammars__001_
end
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped =
Lazy (lazy (Recursive (Tycon ("t", []), Stdlib.Lazy.force grammars__001_)))
}
and (u_sexp_grammar : u Sexplib0.Sexp_grammar.t) =
{ untyped =
Lazy (lazy (Recursive (Tycon ("u", []), Stdlib.Lazy.force grammars__001_)))
}
;;
let _ = t_sexp_grammar
and _ = u_sexp_grammar
end
[@@@end]
end
| |
7c10e06a9c4b19a60a7978a9adb3693a6f2f2cb7d9ef3a3f95abb4db19c5c682 | mclumd/Meta-AQUA | understander.lisp | -*- Mode : LISP ; Syntax : Common - lisp ; Package : Meta - aqua ; Base : 10 -*-
(in-package :metaaqua)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; The Meta-AQUA Introspective Multistrategy Learning System
;;;; Version 6
;;;;
Copyright ( C ) 1996 ( )
;;;;
;;;;
;;;; File: understander.lisp
;;;;
;;;;
;;;; *******************************************************
;;;
;;; 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 1 , or ( at your option ) any later
;;; version.
;;;
;;; This program is distributed in the hope that it will be useful, but WITHOUT
;;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
;;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
;;; more details.
;;;
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. , 675
Mass Ave , Cambridge , , USA . In emacs type C - h C - w to view license .
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Some possibilities for addition to standard Aqua :
Creating tests to determine the best XP
;;; - this will allow detection of disinfo, lies, partial truths,
;;; or otherwise false explanations. Play what is wrong with this
;;; explanation. Integrate with detective domain.
;;;
;;; Adding recency and frequency control.
;;; Integrate with key domain.
;;;
Meta - XPs .
;;;
;;;
Can we find old Meta - XPs during processing to use as shortcuts by successive
refinement of the current Meta - XP in memory ? We then should run into other
;;; similar past traces.
;;;
;;;
;;; Mention how a vaiable points to its instantiation, then stress how
;;; the car of this instantiation points to the frame pattern with all
its bindings . Eg PTRANS.666 - > ( PTRANS ( actor ( value PERSON.23 ) ) ... )
( eval ( car PTRANS.666 ) ) - > ( PTRANS ( actor ( value = X ) ) ... ) .
;;;
||||| ( NOTE : 5 pipes mark comments that eventually must be addressed . )
;;; Need to uncomment the entity test eventually.
;;;
;;; Will we ever need the special handling test?
;;;
;;; Need to modify the search-by2 and other routines make to search for cases.
;;;
ISA hiearchy is still incomplete . Include other definitions from 's
;;; files.
;;;
;;; Need function to take a defined frame (w/out X.12 type form) and return
;;; its symbol-value. Could just modify *FRAME* to do it, but we should be
;;; careful of how to assure that frame variable was indeed passed. So modify
;;; frame-var-p also? No, I just modified *FRAME*. If a non frame-var-p atom is
;;; passed and the atom is bound, then the symbol value is returned. No other checking
is performed . 25 Oct 91
;;;
;;; Make sure that the lowest-common-ancestor function will work on isa
;;; hiearchies as in paper notes.
;;;
;;; ALL OF THE CANNED FORMAT STATEMENTS REALLY NEED TO BE GENERATED FROM A
META - XP REPRESENTING THE CHAIN OF REASONING ! ! ! But this is not central to the research !
;;;
HAVE TWO RUNS THAT CAN DEMONSTRATE THE SPEEDUP OR OTHER BENEFITS OF LEARNING
WITH AND WITHOUT META - XPS .
;;;
;;; Problem with AGENCY: The dog is not the authority, only the agent of the
;;; police.
;;;
;;; When f.put! is used on a facet which already has a filler there may be a
;;; problem with the backlinks and future processing. Will other nodes be
;;; updated so that they do not point any longer to the location? If it is not
;;; done right then when these other nodes are changed or unified with another,
;;; then the algorithm may update the new change made by f.put! The example
;;; which made me think of this possibility is having the program try to recover
;;; from overgeneralization. The program believes that the dog is the agent of
;;; the detection leads to the faulty conclusion the dog is the agent of the
;;; interdiction act. Later we want to learn that the dog was but an agent so
;;; the program must change the extant instantiations of dog outside detection
;;; to authority. f.put! may cause the problem discussed above.
;;;
The above discussion is a little off , but the first line is most important . The
;;; problem was really that if A is a filler to be replaced by B, then if f.put! did
;;; not change the backpointers of A, any process that subsequently did a unify with
;;; A will affect B, since the location is still referenced in A's list of
backpointers . -This is now fixed . 23 Apr 91 .
;;;
When reading the arrest scene , need to represent its larger context : The BUST .
;;; The interdiction-act can be a part of the bust. We instantiate the bust, then
;;; try to relate the sniff with review process. How is the reminding done so that
the PRECONDITON XP is properly found and applied ?
;;;
Make the program more similar to the reasoning model presented in the SAIC paper .
;;; We demand a separate decision process which select the reasoning strategy to use,
eg . CBR or explanation or analogy . How is this decision made if for example both
CRB and explanation have potential . In the XP sketched in the SAIC paper the
;;; reasons for performing explanation was that there existed an index to an XP.
;;; However there could also be an index to a case as well. Does the system use the
first strategy that " comes to mind " or does it arbitrate between all
;;; possibilities. Here is the serial vs. parallel issue among others.
;;;
;;; Interesting. Indexes can be variable. To index an explanation for why an agent does X
one uses X and the agent , but to index a case of arrest we do not refer to the agent .
;;; I suppose that this is because the agent is usually an authority. Instead we use what
;;; the crime is. This is the variable which varies to produce dependent cases? Should
;;; consider this more.
;;;
;;; NOTE that when the program instantiates the interdiction-act in the bust because it
;;; reads about the arrest, the system implicitly infers the existence of the confiscation
;;; even though it is not mentioned in the story. This will not be registered in the
Trace - Meta - XP , but that may not be wrong . Many inferences humans make surely are
subtle and unconscious whereas others will be deliberate . The META - XP registers the
;;; deliberate ones.
;;;
By making the processing explicit using Trace - Meta - XPs we produce side effect
;;; of making parameter passing and return values implicit from the view of
;;; a single function. Especially parameter passing. Function returns and
;;; function side effect is now a slot in a structure, so I guess it is more
;;; explicit. However instead of the programmer being able to point to the
;;; formal parameter list, we instead have to assume knowledge concerning where
in a Trace - Meta - XP the is . What are the implications of this trade - off ?
;;;
;;; After the program hypothesizes that sniffing can be viewed as a detection,
;;; it then reviews other detection methods that it knows about, to see if they
;;; can fit the description (is this a conscious review or a reminding; how are
;;; reminding and review related?). Then the program can post a specific
;;; hypothesis that it needs to have a new type of detection-method and thereby
;;; later modifying the isa-hierarchy. ???
;;;
NEED TO CONSIDER THE DIAGRAM AND COMMENTS FROM BLUE NOTEBOOK 22FEB91 ! ! !
These comments show many more representational features for a META - XP .
Where are the limits of an META - XP ? What is the functional role of these
;;; structures? Do we need to divide the functions, instead of having such a
;;; large and global structure?
;;;
;;; When f.unify fails it generates a failures list. This represents an anomaly!
;;; Generates additional questions. Both in sniff-detection anomaly and in
;;; dog-authority anomaly.
;;;
;;; Also need to generate a specific question asking how the dog physically
;;; accomplished the detection.
;;;
;;; The frame system DOES have to use the .list designator. Either that or
;;; require all facet fillers to be lists, even if they have only a single
;;; item. The problem lies in the ambiguity between the following:
( dummy.101 ( ptrans ( actor ( value = x ) ) ) )
;;; and
( ptrans ( actor ( value = x ) ) ) .
;;; For the time we use a hack. A list of frames is defined to be when
the first item is either a listr , a frame identifier ( ie . )
;;; or a variable identifier (ie. =X).
;;;
;;; Need function f.bound-put! in frame.lisp which destructively adds a filler
;;; to a frame. It differs from the normal f.put! though since if the facet is
;;; bound to other facets in the same frame, then it changes their value also.
;;; To do this we need to keep track of the bindings better in the frame
;;; definitions.
;;;
;;; Still seem to have a problem with backpointers.
;;;
When unifying two nodes there is a problem with system slots such as a ' slot slot .
;;; I was creating one in f.make-relation and subsequently using it (or planning to).
;;; However even though 'actor is a bound symbol, the program crashes when it hits
;;; (slot (value actor)) slot.
;;;
;;; Came up againt the problem again. I suppose this is related to the fact that actor is not
;;; a frame variable as actor.23 is. I now need system slots so I am starting to implement
;;; some of the suggestions below. The slot slot will be a property like isa. Will worry about
defining global system slots later . 21 Aug 91 . NOTE though that we must how to
;;; specify a slot slot when defining particular relations,
e.g. , ( define - relation X ( domain ... )(co - domain ... )(slot x ) ) . 26
;;; All system slots should be made properties of the variables instead of sublist as is now
;;; the case with the isa slot. This would make unification easier. How will the slots be
;;; defined? Since system slots should be common to all frames, we could have a special
;;; definition of the frame 'entity' which all frames share the slots of. Also realize that
the function f.unify may be affected . When two slots are unified and they are not of the
;;; same type, we need to make sure that the result has the correct slot property. But since
;;; the result of the unify is guaranteed to be the most specific frame, it will have the
;;; right slot property, a new one will not be created.
;;; Another problem with lists of frames: FACETS. If a slot is a list of frames, then the
;;; order must be significant since there could be an associated list of relation facets, etc.
The order of the list itself may NOT be significant if one views the associated lists as
having a corespondance , e.g. , ( ( value ( v1 v2 v3))(relation ( r1 r2 r3 ) ) ) . However if
one one is provided with a special facet , all others must at least be given a dummy . For
instance notice what happens if has values v1 .. v3 and v2 is given a relation facet .
;;; Without some kind of placeholder we do not know what value the relation coresponds to.
Dummies must be padded for the longest list . Consider a slot with three constraint facets .
One may have only one value known , but may later add a fourth . When adding the first
value the system needs to pad two dummies in the value facet list . However when adding
a fourth value the system must pad an extra dummy constraint . Notice also that there is
;;; no way the frame systems provides to modify the ith facet in a list. The user must read
;;; the value and insert a new value in the appropriate place. The frame system should then
;;; be responsible for updating (adding of deleting) the remaining facets when a change occurs
by a f.put ? 4 Sep 91
;;;
There is a choice to be made in the manner in which one indexes memory :
;;; When the program learns that there are distinctions to be made between
;;; dogs barking at animate objects (threaten explanation) and dogs barking
;;; at inanimate objects (detection explanation), and that dogs barking in
general is not specific enough , there are two possibilities for indexing .
AQUA would handle this by creating new categories of barking to index
the separate explanations . will for the time use indexes that
;;; have the additional features on barking, while barking is still the category.
What is the trade - off between the two methods ? 20 Oct 91
;;;
;;; How to represent questions and index answers such as
;;; Why did the dog bark?
;;; Why was there barking?
;;; Why did the dog bark at x?
;;; Why does the dog bark at red objects?
;;; 20 Oct 91
;;;
(defun tweak (failure-list)
; tweak-node will be a (node slot filler) triple returned by view-as.
; The facet is guaranteed to be *value-facet*.
(let ((tweak-node (apply #'view-as failure-list)))
(cond (tweak-node ; if view-as returned something
(format *aqua-window*
"~%~%~s can be viewed as ~s."
(second failure-list)
(first failure-list))
(format *aqua-window*
"~%because both ~s and ~s are ~s."
(second failure-list)
(third tweak-node)
(get-abstraction
(frame-type
(second failure-list))))
t)
((setf tweak-node ; else set it with the reverse of failure-list.
(apply #'view-as
(reverse failure-list)))
(format *aqua-window*
"~%~%~s can be viewed as ~s."
(first failure-list)
(second failure-list))
(format *aqua-window*
"~%because both ~s and ~s are ~s."
(first failure-list)
(third tweak-node)
(get-abstraction
(frame-type (first failure-list))))
t))
(cond (tweak-node
(format *aqua-window*
"~%~s is the value of the ~s slot of ~s.~%"
(third tweak-node)
(second tweak-node)
(first tweak-node))
(format *aqua-window*
"~%Tweak succeeds.")
t)))
)
;;;
;;; ||||| NOTE that it does not make sense to check for same main-result
;;; unless both nodes are MOPs or specializations of MOPs. Fix this.
;;;
(defun similar-p (failures)
(let ((lca-type nil)
(result-type nil)
(success nil))
(cond ((multiple-value-setq
(success result-type)
(apply #'same-results-p failures))
(format
*aqua-window*
"~%~%However they are somewhat similar.")
(format
*aqua-window*
"~%~s and ~s both have ~s as a main-result."
(first failures)
(second failures)
result-type)
(cond ((multiple-value-setq
(success lca-type)
(apply #'siblings-p failures))
(format
*aqua-window*
"~%Also they are siblings at the ~s level."
lca-type)
(values t result-type lca-type))
(t
(values nil result-type lca-type))))
(t
(format
*aqua-window*
(str-concat
"~%~%~s and ~s are not similar. "
"They have different main-results.")
(first failures)
(second failures))
(values nil result-type lca-type)))))
;;;
;;; Function outcome-template creates a representation to be placed on the
;;; outcome of the hypo-node. It says that knowing that there was no xp in the
;;; foreground knowledge initiates the knowledge of retrieval failure. That
;;; is, the reasoner is stumped.
;;;
(defun outcome-template (answer hypo-node)
`(mentally-initiates
(results- (,*value-facet*
,hypo-node))
(,*domain-slot*
(,*value-facet*
(truth =truth-relation
(,*domain-slot*
(,*value-facet* =xp))
(,*co-domain-slot*
(,*value-facet* ,*out*)))))
(,*co-domain-slot*
(,*value-facet*
(retrieval-failure
(initiates- (,*value-facet* =domain))
(expected-outcome
(,*value-facet*
(xp =xp
(truth (value ,*out*)
(relation =truth-relation))
(results- (,*value-facet* ,hypo-node))
)))
(actual-outcome
(,*value-facet* ,answer))))))
)
;;;
;;; Function exists-in-story is a predicate that returns t if the input
;;; assertion can unify with a concept in the world model or a concept
;;; reachable from some concept in the world model.
;;;
(defun exists-in-story (assertion)
(let ((found nil))
(or
(some
#'(lambda (each-world-concept)
(when
(can-unify-p
each-world-concept
assertion)
(if *Show-Bugs*
(format
*aqua-window*
"~%Asserted node ~s already known"
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%In first conditional test."
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%each-world-concept:~s."
each-world-concept))
(setf found t)
))
(get-model *World-Model*))
(some
#'(lambda (each-world-concept)
(f.traverse-frame
each-world-concept
#'(lambda (current-frame parent role facet-name level)
(when
(and
(not (visited-p current-frame))
(can-unify-p current-frame
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%Asserted node ~s already known"
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%In second conditional test."
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%Current frame:~s~%parent:~s~%role:~s~%facet-name:~s~%level:~s."
current-frame parent role facet-name level))
(setf found t)))))
(get-model *World-Model*)))
found)
)
;;;
;;; Want to view the source as the target concept. To do this we search for a
;;; value facet in the target which is the same type as the source. Returns the
;;; node (as slot filler pair) at which source was unified, or nil if no
;;; unifiaction is possible.
;;;
;;; ||||| This heuristic will not work very well if there are multiple
source - types within target . For example there could have been many mtrans
;;; inside of an interdiction-act.
;;;
(defun view-as (target source)
(some #'(lambda (each-slot)
;; Oh the HACKery!
(if (not (equal 'instrumental-scene-of
(slot->role each-slot)))
(some #'(lambda (each-facet)
(let ((filler (facet->filler each-facet)))
; ||||| Do I really want to check for filler being an instance?
; Ie. one with a period imbedded in it. We may allow abstractions.
(if (and (frame-var-p filler)
(equal (facet->facet-name each-facet)
*value-facet*))
(or (cond ((intersection (get-abstraction filler)
(get-abstraction (frame-type source)))
;Question this relation as only hypothesized to be true.
(mark-as-question
;; ||||| Since all input has relations explicitly added now,
;; is the call of f.mmake-relation necessary (harmful)?
(f.make-relation target (slot->role each-slot))
*hypothesized-in*)
;; ||||| Do we really need this here?
; (with-character-style (*Style*)
(format
*aqua-window*
(str-concat
"~%Trying to understand why actor "
"performs this act.~%"))
; )
(setf filler
(f.unify filler
source))
(setf source filler)
; ||||| Is filler and source now guaranteed to be same?
(list target (slot->role each-slot) filler)))
(view-as filler source)))))
(slot->facets each-slot))))
(f.slot-list target))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; THREE PHASES OF UNDERSTANDING
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; Question Identification Phase
;;;;
;;;
Currently two strategies exist to choose from in the Question
;;; Identification phase: Questioning (function pose-question) and
;;; skimming (function skim).
;;;
;;;
;;; Function pose-question actually poses the question "Why did the actor of
;;; the event passed as the concept parameter perform the action?" Modified so
that it will also ask why xps explain their explains node , and more
;;; generally, why values are domains of relations. [30oct94]
;;;
;;; How to mark this as a question explicitly. It is a knowledge goal so we
know this , but how did do it ? Consider that the * explanations - slot *
;;; is really supposed to be a facet on the actor slot. Now how do we say "Why
;;; did the actor choose to enter into this relation. Tag the XP with status =
;;; question!
;;;
;;; For example, the function parameters (and local var) might be as follows:
;;; action = DOG-BARKS.25745
;;; anomaly = ANOMALY.26311 -> (ANOMALY
( EXPECTED - OUTCOME ( VALUE ANIMATE - OBJECT.26303 ) )
;;; (ACTUAL-OUTCOME (VALUE LUGGAGE.25748))
;;; (ACTION (VALUE DOG-BARKS.25745))
;;; (PATHS (VALUE LITERAL.26312)))
LITERAL.26312 - > ( ( OBJECT ) ( TO DOMAIN ) )
supergoal = GOAL.26225 - > ( GOAL ( GOAL - OBJECT ( VALUE ID.26224 ) ) )
;;; ID.26224 -> (ID (CO-DOMAIN (VALUE DOG-BARKS.25745)))
;;; relation = ACTOR.25747 -> (ACTOR (DOMAIN (VALUE DOG-BARKS.25745))
;;; (CO-DOMAIN (VALUE DOG.25746)))
;;;
(defun pose-question (action anomaly supergoal)
(let* ((relation
(f.get-relation
action (map-2-slot action t))) ; NOTE THAT MAP-2-SLOT MAY SET ADD-BREAK
(tmxp (processing-trace supergoal))
(is-repeat-question?
(not (null (f.get relation *explanations-slot*))))
)
(do-break pose-question ; Add-break can be set by map-2-slot
(str-concat
"Action arg for pose-question "
"neither mop nor xp"))
(if (not is-repeat-question?)
(f.put!
(list
(mark-as-question
(f.instantiate-frame
`(xp
(,*explains-node*
(,*value-facet*
,relation
;; (entity)
))
(mxp
(,*value-facet* ,tmxp))))
*hypothesized*))
relation
*explanations-slot*))
(print-question-posed
relation
action
is-repeat-question?)
(when (not is-repeat-question?)
(index-question
relation
is-repeat-question?)
(index-anomaly2 relation
(symbol-value ; Paths are in a literal.
(f.get anomaly 'paths))))
;; Post goal to generate hypothesis.
(spawn-sub-goal
*current-character*
(make-goal-state 'generate
*current-character*
relation)
'knowledge-acquisition-goal
'seven.0
supergoal)
relation)
)
(defun print-question-posed (relation
action
&optional
is-repeat-question?
(stream *aqua-window*))
"Provide English feedback for the questions posed."
; (with-character-style (*Style*)
(format
stream
(str-concat
(if is-repeat-question?
"~%~%Repeating Old Question: ~s~% "
"~%~%Posing Question: ~s~% ")
(cond ((isa-p 'mop (list action))
"Why did the ~s ~s perform the ~s?~%")
((isa-p 'xp (list action))
"Why is the ~s ~s explained by this ~s explanation?~%")
(t
"Why is ~s ~s the domain of the ~s relation?~%" )))
relation
(frame-type
(f.get action
(map-2-slot action)))
(f.get action
(map-2-slot action))
(frame-type action))
; )
)
;;;
;;; [30oct94]
;;;
(defun map-2-slot (action &optional break)
"Map an action to a slot for question posing."
(cond ((isa-p 'mop (list action))
*actor-slot*)
((isa-p 'xp (list action))
*explains-node*)
(t
(if break
(add-break pose-question))
*domain-slot*))
)
;;;
;;; Function skim is a function which basically makes a minimal set of
;;; inferences such as those involved with story coherence. The function
;;; attempts to understand the input concept through simple script application.
;;; It also performs a print operation and deletes the current goal from the
;;; *Goal-Queue* (which is a small hack).
;;;
(defun skim (concept id-node k-goal)
; (assert (eq concept
( first
; (get-model
; *World-model*)))
; (*World-Model*)
; "Error in Skim")
; (with-character-style (*Style*)
(format
*aqua-window*
(str-concat
"~%~s is not a very interesting "
"concept.~% Skimming . . .~%")
concept )
; )
(remove-achieved-goal k-goal)
(scriptify *World-Model*)
)
(defun q.strategy-decision (decision-basis concept)
(let ((reason (interesting-p concept))
(k-state (f.instantiate-frame
knowledge-state)))
;; The following is the reason we will generate a question.
(f.put-all!
(or reason
(list 'noreason nil))
k-state
'believed-item
; (f.instantiate-frame
; (if reason
; (list concept reason)
; (list 'noreason nil)))
)
(f.put!
(list k-state)
(f.get
decision-basis
'knowledge)
'members)
(if reason
'questioning.0
'skimming.0)
))
(defun q.runstrategy (id-node choice concept k-goal)
(if (equal choice
'pose-question.0)
(do-break q.runstrategy))
(f.unify (f.get id-node 'main-result)
(f.instantiate-frame outcome))
(case choice
(questioning.0
(f.put! (list (pose-question
concept
(f.get
(first (return-decision-basis
id-node))
'believed-item)
k-goal))
(f.get id-node 'main-result)
'members)
'pose-question.0)
(skimming.0
(values 'skim.0
(skim concept id-node k-goal)))
( t (format
*aqua-window*
"ERROR: unknown q-strategy - ~s."
choice)))
)
;;;
;;; The function identify-question not only performs the primary role of
;;; determining whether there is a question that must be posed, but if there is
;;; not (and thus the program skims the input), then it also is the function
;;; that actually updates the script match number and passes it all the way
back to Meta - AQUA to be returned ( and if spinning automatic story
;;; generation then passing it back to spinqua).
;;;
(defun identify-question (k-goal id-node script-match-number)
(let ((new-input (goal-state k-goal))
(which-strategy nil) ; Note that which-strategy is really a dummy variable.
(new-script? nil))
(f.unify
(multiple-value-setq
(which-strategy
new-script?)
(q.runstrategy
id-node
(f.unify
(f.get id-node 'strategy-choice)
(q.strategy-decision
(return-decision-basis
id-node)
new-input))
new-input
k-goal))
(f.get id-node 'strategy-execution))
(if new-script?
(+ 1 script-match-number)
script-match-number))
)
;;;;
;;;; Hypothesis Generation Phase
;;;;
;;;
Currently four strategies exist to choose from in the Hypothesis
;;; Generation phase: Suspension (function suspend-task), explanation
;;; (function explain), analogy (function (analogize) and case-based
;;; reasoning (function episodize). Analogy is not actually implemented.
;;;
;;;
;;; Function resume-generation-phase is called by function answer-old-questions
;;; when opportunistically picking up on old processing that may now be
;;; completable. See resume-examination-phase.
;;;
;;; If answer is not an XP, then the function returns immediately with a value
of nil ( and no side - effect ) , otherwise it executes the body and returns t.
;;;
(defun resume-generation-phase
(answer questions old-goal current-goal question old-answer phase
&optional automatic?)
(do-break resume-generation-phase)
(when (not (isa-p 'xp (list answer)))
; (with-character-style (*Style*)
(format
*aqua-window*
"~%But input does not help answer question.~%")
; )
(return-from resume-generation-phase nil))
;; This is the case when the system was stumped (could not previously generate
;; an answer to the question) and now is presented a possible answer.
(format
*aqua-window*
"~%Found answer for previous baffling question.~%")
(let* ((hypo-node (f.get phase *co-domain-slot*))
(hypo-goal (return-phase-goal hypo-node)))
;; Must remove the suspend strategy-choice.
(f.put-all! *nil* hypo-node 'strategy-choice)
;; And the indication that suspension was done.
(f.put-all! *nil* hypo-node 'strategy-execution)
(resume-goal-hierarchy hypo-goal)
|||||| This hack is temporary in oder to get the data . [ cox 12jun95 ]
;; Come back to allow the system to reject an inappropriate IMXP.
(if (isa-p 'xp (list old-answer))
(let ((current-val
(get
(get
(get
'mentally-initiates
'truth)
'retrieval-failure)
'xp-type.0)))
(if (contains-previous-anomaly-p old-goal)
(if (not
(f.get
(first
current-val)
'anomaly))
(setf (get
(get
(get
'mentally-initiates
'truth)
'retrieval-failure)
'xp-type.0)
(reverse
current-val)))
(if (f.get
(first
current-val)
'anomaly)
(setf (get
(get
(get
'mentally-initiates
'truth)
'retrieval-failure)
'xp-type.0)
(reverse
current-val)))
)))
(cond ((dummy-explanation-p old-answer)
(explain question hypo-node old-goal answer automatic?)
(remove-indices-to-answered-question question)
;; Place the stumped representation on the outcome of the generation phase.
;;; (break "resume-generation-phase")
(f.unify
(assert-truth
*in*
(f.instantiate-frame
(outcome-template answer hypo-node))
)
(first (return-result hypo-node)))
;; Spawn a goal to learn.
(spawn-sub-goal
*current-character*
(make-goal-state
'review/learn
*current-character*
;; Review the reasoning which led to the faulty conclusions.
(processing-trace old-goal))
'knowledge-acquisition-goal
'three.0
old-goal))
(t
(format
*aqua-window*
"ERROR in resume-generation-phase.")))
t)
;; Then need to place the retrieval failure representation for stumped.
;; Place question on it to make sure that there exists no item in memory?
)
;;;
;;; Function contains-previous-anomaly-p acts as a predicate that returns
;;; non-nil whenever the reasoning trace that pursued the old goal detected an
;;; anomaly during the identification phase to initiate the reasoning, rather
;;; than some other reason such as the original input being interesting.
;;;
(defun contains-previous-anomaly-p (old-goal)
(isa-p
'anomaly
(list
(f.get
(first
(return-decision-basis
(f.get
(processing-trace old-goal)
'identification)))
'believed-item)))
)
;;;
;;; Function suspend-task is called by the hypothesis-generation and
;;; verification phases of both understanding and planning. Suspension occurs
;;; when the goal cannot be accomplished, so the task to achieve the goal is
;;; suspended until later opportunities arise.
;;;
(defun suspend-task (dummy goal)
; (with-character-style (*Style*)
(format
*aqua-window*
(str-concat
"~%Cannot achieve ~s at this time."
"~% Suspend ~s task . . .~%")
goal
(frame-type (goal-object goal))
)
; )
;; Remove the goal and all the superordinate goals above
;; it in the hierarchy from the goal queue.
(suspend-goal-hierarchy goal)
dummy)
;;; |||||
;;;
(defun analogize (question k-goal)
(format
*aqua-window*
"~%Should not have tried to run analogize.~%")
question)
;;;
;;; ||||| Eventually make more systematic, using all available info.
See SAIC paper .
;;;
;;; The basis for the decision is now the value pointed to by the index.
;;; The index currently has no name; it is an indirect reference so has
two indexes really . Fix eventualy . For now the strategy execution
;;; functions can just use the value placed in the processing trace
;;; associated with k-goal, not the index (sic).
;;;
;;; ||||| This function has become too long. Clean it up. Should we
;;; really be putting the case on the tmxp slot associated with the
;;; k-goal? This is supposed to be a decision phase not a strategy
;;; execution. I had to put the k-goal parameter on here just to do
this . Check what happens in other strategy decision routines . 3 May
93 .
;;;
(defun h.strategy-decision (decision-basis questions hypo-node k-goal)
(let ((xps (retrieve-xps questions))
(k-state (f.instantiate-frame
knowledge-state))
(return-val nil))
(do-break h.strategy-decision "Retrieved XPs: ~s" xps)
(cond (xps
;; The following is the reason we will generate a hypothesis.
(f.unify (make-index
questions xps)
(f.get
k-state
'believed-item))
(setf return-val 'explanation.0))
(t
(let ((case (retrieve-case questions)))
(cond (case
(f.unify (make-index
questions case)
(f.get
k-state
'believed-item))
(f.put! case
(processing-trace k-goal)
'cases)
(setf return-val 'CBR.0))
(t
;; ||||||Perhaps should place stumped (baffled?) representation on d-c-node at this point.
; (format *aqua-window*
; (str-concat
; "~%Suspension in h.strategy-decision."
; "~%Called with ~s and ~s.")
; hypo-node
; questions)
(setf return-val 'suspension.0))))
))
(f.put! (list k-state)
(f.get
decision-basis
'knowledge)
'members)
return-val)
)
;;;
;;; ||||| Instead of passing the choice perhaps runstrategy should find
;;; the choice in the current trace of the processing attached to
;;; k-goal.
;;;
(defun h.runstrategy (hypo-node choice question k-goal)
(f.unify (f.get hypo-node 'main-result)
(f.instantiate-frame outcome))
(if
(and
(not (eq choice 'suspension.0))
Then this is an original question ; i.e. , one without a previous explanation .
(dummy-explanation-p
(first
(f.get question *explanations-slot*))))
(set-self-gen-answers
*Current-Result-Record*))
(case choice
(explanation.0
; (f.put! (list (explain question hypo-node k-goal))
; (f.get hypo-node 'main-result)
; 'members)
(f.unify
(explain question hypo-node k-goal)
(first (return-result hypo-node)))
;;; (break "Check hypo node main result")
'explain.0)
(analogy.0
(f.unify
(analogize question k-goal)
(first (return-result hypo-node)))
'analogize.0)
(CBR.0
(f.unify
(episodize question k-goal)
(first (return-result hypo-node)))
'episodize.0)
(suspension.0
(suspend-task question k-goal)
'suspend-task.0)
( t (format
*aqua-window*
"ERROR: unknown h-strategy - ~s." choice))))
(defun generate-hypothesis (k-goal hypo-node)
(let ((questions (goal-state k-goal)))
;; ||||| The following code is currently dependent on the order of parameters.
(f.unify (h.runstrategy
hypo-node
(f.unify (f.get hypo-node 'strategy-choice)
(h.strategy-decision
(return-decision-basis
hypo-node)
questions
hypo-node
k-goal))
questions
k-goal)
(f.get hypo-node 'strategy-execution))
;; ||||| This is a case for use of f.bound-put! when finished.
;; Also, all strategy choices are guaranteed currently to return an XP.
;; This may not always be so.
(if (not
(equal 'suspension.0
(f.get hypo-node 'strategy-choice)))
(let ((resulting-xp
(first (return-result hypo-node))))
(cond (resulting-xp
(f.put-all!
resulting-xp
(processing-trace k-goal)
'main-xp))
(t
;; ||||||If I get to the following, shouldn't I be suspending the task?
(break "ERROR: No xp results"))))))
)
;;;;
;;;; Verification Phase
;;;;
;;;
Currently three strategies exist to choose from in the Verification
;;; phase: Suspension (function suspend-task), comparison (function
;;; compare), and devising a test (function devise-test). Devise-test is
;;; not actually implemented.
;;;
;;;
;;; Function resume-examination-phase is called by function
;;; answer-old-questions when opportunistically picking up on old processing
;;; that may now be completable. See resume-generation-phase.
;;;
;;; The function is not guaranteed to return t any longer. If the answer does
;;; not match to the question and the answer is not an alternative xp, then the
;;; function prints a message that the input does not help answer the old
;;; question and it returns nil. This forces function answer-old-questions to
;;; also return nil, which causes function do-understand to call reason-about.
;;;
(defun resume-examination-phase
(answer questions old-goal question old-answer phase)
(do-break resume-examination-phase)
(if (and (isa-p 'xp (list answer))
(equal (frame-type (f.get answer *explains-node*))
(frame-type question)))
||||| Probably should really do an apply - xp here . This would generate hvqs
;; (and if apply-xp is fixed) make sure that the pre-xp-nodes are in.
(let ((merged-node (f.unify (f.get answer *explains-node*)
question t nil t))
;; |||||| Cannot perform the following because there is already
;; a different explanation on the slot rather than a dummy.
;;; (merged-node (f.unify (f.get question *explanations-slot*) answer))
)
(f.put! (if old-answer ;||||||Possibly will always be an old answer, even if dummy.
(list answer old-answer)
(list answer))
merged-node
*explanations-slot*)))
||||| Eventually we should make sure first that there was no test of the
hypothesis being done first . We must look at the reason for the original suspension
;; to see that there was no reason yet to decide on a test method. Now we can do
;; the compare
(cond ((or (try-matching2 answer questions nil) ; Try matching strictly.
(try-matching2 answer questions t)) ; Now try lazy matching.
(if (and (isa-p 'xp (list old-answer))
(contains-previous-anomaly-p old-goal))
;; The current-phase is the test relation, thus the co-domain is the verify d-c-node.
(cond
((isa-p 'xp (list answer)) ; Added [cox 25def95]
(let* ((verify-node (f.get phase *co-domain-slot*))
(verify-goal (return-phase-goal verify-node)))
;; Must remove the suspend strategy-choice.
(f.put! *nil* verify-node 'strategy-choice)
;; And the indication that suspension was done.
(f.put! *nil* verify-node 'strategy-execution)
(resume-goal-hierarchy verify-goal)
(verify verify-goal
verify-node)
(remove-indices-to-answered-question question)
(spawn-sub-goal
*current-character*
(make-goal-state
'review/learn
*current-character*
;; Review the reasoning which led to the faulty conclusions.
(processing-trace old-goal))
'knowledge-acquisition-goal
'ten.0
old-goal)
t
))
(t
(format
*aqua-window*
"~%~%New input does not help answer old question.~%~%")
nil))))
(t
|||||| This hack is temporary in oder to get the data . [ cox 14jun95 ]
;; Come back to allow the system to reject an inappropriate IMXP.
(if (isa-p 'xp (list old-answer))
(let ((current-val ; Current value of the IMXPs stored at this location.
(get
(get
(get
'mentally-initiates
'not-equal-relation)
'expectation-failure)
'xp-type.0)))
(if (contains-previous-anomaly-p old-goal)
(if (not
(f.get
(first
current-val)
'anomaly))
(setf (get
(get
(get
'mentally-initiates
'not-equal-relation)
'expectation-failure)
'xp-type.0)
(reverse
current-val)))
(if (f.get
(first
current-val)
'anomaly)
(setf (get
(get
(get
'mentally-initiates
'not-equal-relation)
'expectation-failure)
'xp-type.0)
(reverse
current-val)))
)))
(cond
((isa-p 'xp (list answer)) ; Added [cox 25def95]
(let* ((verify-node (f.get phase *co-domain-slot*))
(verify-goal (return-phase-goal verify-node)))
;; Must remove the suspend strategy-choice.
(f.put! *nil* verify-node 'strategy-choice)
;; And the indication that suspension was done.
(f.put! *nil* verify-node 'strategy-execution)
(resume-goal-hierarchy verify-goal)
(verify verify-goal
verify-node)
(big-hack old-answer answer)
(remove-indices-to-answered-question question)
t
))
(t
( break " Odd that ~s is not an xp . " answer )
(format
*aqua-window*
"~%~%New input does not help answer old question.~%~%")
nil))))
)
;;;
;;; This routine is the one that (when implemented) will link understanding
;;; with problem-solving; that is, in order to verify a hypothetical
;;; interpretation of some input, a reasoner may have to devise a test and then
;;; plan the test.
;;;
(defun devise-test (hypothesis k-goal)
(format
*aqua-window*
"~%Execution of devise-test should not have occurred.~%")
)
;;;
;;; ||||| NOTE THAT BECAUSE THE FUNCTION COMPARE (or is it big-hack now?)
PERFORMS A F.UNIFY WITH THE HYPOTHESIS PARAMETER , IT MAY INADVERTENTLY
;;; CHANGE WHAT THE FRAME VARIABLE POINTED-TO BY IT CONTAINS. TO CHANGE THIS IS
NOT AS EASY AS THE CHANGES WE DID TO FUNCTION REVIEW . THE REASON IS THAT
;;; COMPARE IS ALREADY RETURNING A VALUE TO BE SET TO SOMETHING BY THE CALLING
FUNCTION . ALSO WE JUST USE MULTI - VALUE RETURN VALUES SINCE THE
;;; PARAMETER IS OBTAINED FROM THE PARAMETER OF THE CALLING FUNCTION. NEED TO
;;; FIX THIS ASAP.
;;;
;;; Since the learning does not really depend on this hack, I do not think that
;;; it is a real fudge about which to be worried. [30oct94]
;;;
(defun big-hack (alternative hypothesis)
;; Big HACKs. This is the unification of the sniff with the explanation of the bark.
;; Since the story does not explicitly say that the detection is the sniff, we need
;; infer it by backtracking. The system then needs to notice that the detection must
;; be the one in the bust scene.
(let ((d-method (f.instantiate-frame tip-off)))
; (format *aqua-window*
; "~%Unify goal-scene of tip-off with goal-scene of bark.")
; (f.unify (f.get d-method 'goal-scene)
; (f.chase-path alternative 'consequent 'goal-scene))
; (format *aqua-window*
; "~%Unify bark from because statement with previous bark.")
; (f.unify (f.get alternative 'consequent)
( fourth ( get - model * World - Model * ) ) )
; (format *aqua-window*
; "~%Add sniff as instrumental scene of detection-method.")
;; The following puts the sniff on the instrumental-scene slot of the detection method.
(f.put (return-last-element (get-model *World-Model*))
d-method
'instrumental-scene)
; (format
; *aqua-window*
; "~%F.unify tip-off with detection-method of detection scene of bust.")
(f.unify
d-method
(f.get
(get-scene 1
(second (get-model *World-Model*)) ; Returns a case.
)
'method))
; (f.unify (f.get alternative 'antecedent)
; (return-last-element (get-model *World-Model*)))
(let ((question (f.get hypothesis *explains-node*)))
; (with-character-style (*Style*)
(format *aqua-window*
"~%~%Found a better explanation for action of ~s.~%"
(f.get question *domain-slot*))
(format *aqua-window*
"~%The explanation links together more of the story.~%"
;;; (f.get question *domain-slot*)
)
; )
(f.put! (list alternative) question *explanations-slot*)))
)
;;;
;;; Function compare in this form is truer to the way in which it was presented
in the MSL-91 paper ( see page 224 ) . Think of the evidence as node A and the
;;; hypothesis as node E. The function returns either a successful prediction
;;; node or an expectation failure node.
;;;
;;; Return the conclusion: Successful-Prediction or Expectation-Failure.
;;; Side-effect: if expectation-failure, then spawn a goal that initiates
;;; learning.
;;;
(defun compare (evidence hypothesis k-goal verify-node)
(do-break compare)
(format
*aqua-window*
(str-concat
"~%Compare strategy applied to "
"evidence ~s for hypothesis ~s~%")
evidence
hypothesis)
(cond ((can-unify-p evidence hypothesis)
(remove-achieved-goal k-goal) ; Successful hypothesis, so remove knowledge goal.
(assert-truth
*in*
(f.instantiate-frame
`(mentally-initiates
(results- (,*value-facet*
,verify-node))
(,*domain-slot*
(,*value-facet*
(equal-relation
(,*domain-slot*
(,*value-facet* ,evidence))
(,*co-domain-slot*
(,*value-facet* ,hypothesis)))))
(,*co-domain-slot*
(,*value-facet*
(successful-prediction
(initiates- (,*value-facet* =domain))
(expected-outcome
(,*value-facet* ,hypothesis))
(actual-outcome
(,*value-facet* ,evidence)))))
))))
(t ; Post immediate goal to review process.
(spawn-sub-goal
*current-character*
(make-goal-state
'review/learn
*current-character*
;; Review the reasoning which led to the faulty conclusions.
(f.get hypothesis 'mxp))
'knowledge-acquisition-goal
'ten.0
k-goal)
(assert-truth
*in*
(f.instantiate-frame
`(mentally-initiates
(results- (,*value-facet*
,verify-node))
(,*domain-slot*
(,*value-facet*
(not-equal-relation
(,*domain-slot*
(,*value-facet* ,evidence))
(,*co-domain-slot*
(,*value-facet* ,hypothesis)))))
(,*co-domain-slot*
(,*value-facet*
(expectation-failure
(initiates- (,*value-facet* =domain))
(expected-outcome
(,*value-facet* ,hypothesis))
(actual-outcome
(,*value-facet* ,evidence)))))
)))))
)
;;;
;;; Function v.strategy-decision looks to see if there are any
;;; compatible concepts that could verify the hypothesis. If so it tries
;;; to compare these with the hypothesis. Otherwise it suspends the
;;; verification till a later time when more output may be available.
;;;
;;; ||||| Currently there is never a decision made to try to test a
;;; hypothesis. We usually suspend. Compares are then done when a later
;;; input can answer the question. The hypothesis is then checked for
;;; agreement.
;;;
(defun v.strategy-decision (decision-basis hypothesis verify-node k-goal)
(let ((relevant-input (find-relevant-input
hypothesis))
(k-state (f.instantiate-frame
knowledge-state))
(return-val nil))
(cond (relevant-input
(format
*aqua-window*
(str-concat
"~%Found relevant input "
"for verifying hypothesis: ~s~%")
relevant-input)
(format
*aqua-window*
"~%Comparison strategy selected ~%")
(do-break v.strategy-decision)
(f.unify
relevant-input
(f.get
k-state
'believed-item))
(setf return-val 'comparison.0))
((test-applicable-p hypothesis)
(setf return-val 'devise-test.0))
(t
(setf return-val 'suspension.0)))
(f.unify k-state
(or
(first
(f.chase-path
decision-basis
'knowledge
'members))
(first decision-basis)))
return-val)
)
;;;
;;; Function find-relevant-input takes as input a hypothetical explanation, and
returns as output the first item it finds in the world model that is of the
;;; same type as the object (explains node) of the hypothetical explanation
;;; input to the function. The explains node represents what the explanation is
;;; explaining.
;;;
;;; This function is called by function v.strategy-decision. The purpose is to
;;; retrieve a relevant piece of new input from the story that corroborates an
;;; old explanation.
;;;
(defun find-relevant-input (hypothesis)
(let* ((hypo-explains (f.get hypothesis
*explains-node*))
(hypo-type (frame-type
hypo-explains)))
(do-break find-relevant-input)
(if (not (null hypo-explains))
(some
#'(lambda (each-world-concept)
(if
(equal
hypo-type
(frame-type
(f.get each-world-concept
*explains-node*)))
each-world-concept))
;;; (get-model *World-Model*)
|||||| Temporary
)))
)
;;;
;;; Predicate test-applicable-p takes a hypothesis and returns whether or not a
;;; test can be devised (or is it worth for the system to try an devise a test)
;;; for the hypothesis.
;;;
;;; ||||| Currently NOT implemented.
;;;
(defun test-applicable-p (hypothesis)
nil)
(defun v.runstrategy (verify-node choice hypothesis k-goal)
(f.unify (f.get verify-node 'main-result)
(f.instantiate-frame outcome))
(case choice
(comparison.0
(f.put! (list (compare
(f.get
(first
(return-decision-basis
verify-node))
'believed-item)
hypothesis
k-goal
verify-node))
(f.get verify-node 'main-result)
'members)
'compare.0)
(devise-test.0
(f.put! (list (devise-test hypothesis k-goal))
(f.get verify-node 'main-result)
'members)
'devise-test.0)
(suspension.0
(suspend-task hypothesis k-goal)
'suspend-task.0)
( t (format
*aqua-window*
"ERROR: unknown v-strategy - ~s." choice))))
;;;
;;; ||||| See comment below for why the callers of f.put! is important.
;;;
(defun verify (k-goal verify-node)
;; The following calling sequence works because f.put will return the filler
;; passed to it. The filler is the value returned by v.strategy-decision.
;; ||||| NOTE that by using f.put! strategy decision will be assigned the value returned by
v.strategy - decision ( a string ) . However the slots in the d - c - node which are bound to the
strategy - choice slot ( the co - domain of link2 and the domain of link3 ) will not be changed .
;; This is why I need to finish f.bound-put!. Same event happens in function generate-hypothesis.
;;
;; I commented out the code the remarks above refer to and use f.unify until a more general
;; function like f.boutd-put! is finished.
; (v.runstrategy (f.put! verify-node
; 'strategy-choice
; *value-facet*
; (v.strategy-decision hypothesis))
; hypothesis)
(let ((hypothesis (goal-state k-goal)))
(do-break verify)
;; ||||| The following code is currently dependent on the order of parameters.
(f.unify
(v.runstrategy
verify-node
(f.unify
(f.get
verify-node
'strategy-choice)
(v.strategy-decision
(return-decision-basis verify-node)
hypothesis
verify-node
k-goal))
hypothesis
k-goal)
(f.get verify-node 'strategy-execution)))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; MAIN CONTROL FUNCTIONS
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Function boot-understanding is the routine to handle
;;; understanding goals in the dispatch call of function
;;; reason-about. It spawns a goal to identify any questions
;;; concerning the desired goal-state of the k-goal.
;;;
(defun boot-understanding (k-goal)
;; Post goal to identify the question.
(spawn-sub-goal
*current-character*
(make-goal-state
'id
*current-character*
(goal-state k-goal))
'knowledge-acquisition-goal
'seven.0
k-goal)
)
;;;
;;; Function dispatch-knowledge-goal calls particular reasoning
;;; functions depending on the type of goal-object in the knowledge
;;; goal. It returns a phase identifier that corresponds to the
;;; goal-object type. The counterpart function in the
;;; problem-solving process is dispatch-world-goal.
;;;
The function returns two values . The main ( first ) value is the phase
identifier ( goal type ? ) of the routine dispatched . The second value is the
;;; (possibly updated) script match number.
;;;
(defun dispatch-knowledge-goal (k-goal d-c-node script-match-number)
(values
(case (frame-type (goal-object k-goal))
(understands
(boot-understanding k-goal)
'understands)
(id
(setf script-match-number
(identify-question
k-goal
d-c-node
script-match-number))
'identification)
(generate
(generate-hypothesis k-goal d-c-node)
'generation)
(test
(verify k-goal d-c-node)
'examination)
(review/learn
(learn k-goal d-c-node)
'review)
(t
(format *aqua-window*
"ERROR: unknown goal type in function reason-about.")
nil))
script-match-number)
)
;;;
Function reason - about looks at the mxp slot of the knowledge goal
;;; (this is returned by function processing-trace)
;;; and determines where in the reasoning chain the sequence is. It then
;;; calls dispatches the proper routine to pick up the reasoning by
;;; calling dispatch-goal. It also passes the proper parameter info
stored in the mxp .
;;;
;;; Parameter k-goal is the knowledge-goal.
;;;
;;; NOTE that reason-about is the primary dispatching function for
calling the reasoning processes . It also manages the Trace - Meta - XP
;;; that records such reasoning. However the function
;;; answer-old-questions also performs this role when resuming suspended
;;; reasoning tasks.
;;;
;;; Returns script-match-number. It is (possibly) updated when passed
;;; through dispatch-knowledge-goal.
;;;
(defun reason-about (k-goal script-match-number)
(let ((d-c-node (gen-d-c-node k-goal))
(phase nil))
(do-break reason-about)
(multiple-value-setq
(phase script-match-number)
(dispatch-knowledge-goal
k-goal
d-c-node
script-match-number))
(if (and phase
(not (equal phase 'understands))
(not (equal phase 'wants)))
(let ((which-tmxp
(if (equal phase 'review)
(goal-state k-goal)
(processing-trace k-goal))))
;; NOTE that because D-C-Node is passed to dispatch-goal
;; and is possibly unified with other frames it might be
;; no longer point to the correct node.
(f.unify
d-c-node
(f.get which-tmxp phase))
(f.put! (f.make-relation
which-tmxp phase)
which-tmxp
'current-phase)))
script-match-number)
)
;;;
;;; Function do-understand processes a knowledge goal by checking to see if the
;;; current input (new input) possibly addresses a previously suspended
;;; question. If so it attempts to answer the question with the input, else it
;;; processes the input normally via the reason-about function.
;;;
;;; The function returns the script-match-number. It is (possibly) updated if
;;; passed through reason-about.
;;;
(defun do-understand (k-goal script-match-number &optional automatic?)
(let* ((new-input ; Note that this is not necessarily new input.
(goal-state k-goal))
(old-questions
(and
(is-goal-object-p ; Goal is to understand a new input.
'understands
k-goal)
(potential-answer-p new-input)
)))
(do-break do-understand)
(notice new-input ; Notice is currently used to unify a
k-goal ; posted goal with its equivalent.
(get-model *World-Model*))
(cond ((and
old-questions ; If old questions exist
(not ; and not a reassertion of the action being questioned.
(reasserts-act-being-questioned-p
new-input
(first old-questions)))
(print-remembers-old-question ; {this line guaranteed true}
old-questions) ; {in order to print }
(cond
((or ; and either
automatic? ; on automatic run or
(y-or-n-p "Answer this?")) ; user wants these questions answered
t)
(t
(if (y-or-n-p ; Prompt the user.
"Try to purge old question?")
(if (retrieve-memory
'question-type.0
new-input)
(do-index ; This will work for simply indexed questions.
nil
'question-type.0
new-input)))
nil))
(answer-old-questions ; then answer them
new-input old-questions
(get-old-goal old-questions)
k-goal automatic?))
script-match-number) ; Return script match number unchanged.
(t
(reason-about ; else pursue the reasoning goal, returning
k-goal ; the script-match-number which may be changed by
script-match-number)))) ; function reason-about.
)
(defun print-remembers-old-question (question)
"Simple feedback to user about reminding."
; (with-character-style (*Style*)
(format
*aqua-window*
"~%~%Input triggers reminding of old question:~% ~s~%"
question)
; )
t
) | null | https://raw.githubusercontent.com/mclumd/Meta-AQUA/e4d4f83330fd07d1354aec245a49bde9e246c618/understander.lisp | lisp | Syntax : Common - lisp ; Package : Meta - aqua ; Base : 10 -*-
The Meta-AQUA Introspective Multistrategy Learning System
Version 6
File: understander.lisp
*******************************************************
This program is free software; you can redistribute it and/or modify it
either version 1 , 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.
if not , write to the Free Software Foundation , Inc. , 675
- this will allow detection of disinfo, lies, partial truths,
or otherwise false explanations. Play what is wrong with this
explanation. Integrate with detective domain.
Adding recency and frequency control.
Integrate with key domain.
similar past traces.
Mention how a vaiable points to its instantiation, then stress how
the car of this instantiation points to the frame pattern with all
Need to uncomment the entity test eventually.
Will we ever need the special handling test?
Need to modify the search-by2 and other routines make to search for cases.
files.
Need function to take a defined frame (w/out X.12 type form) and return
its symbol-value. Could just modify *FRAME* to do it, but we should be
careful of how to assure that frame variable was indeed passed. So modify
frame-var-p also? No, I just modified *FRAME*. If a non frame-var-p atom is
passed and the atom is bound, then the symbol value is returned. No other checking
Make sure that the lowest-common-ancestor function will work on isa
hiearchies as in paper notes.
ALL OF THE CANNED FORMAT STATEMENTS REALLY NEED TO BE GENERATED FROM A
Problem with AGENCY: The dog is not the authority, only the agent of the
police.
When f.put! is used on a facet which already has a filler there may be a
problem with the backlinks and future processing. Will other nodes be
updated so that they do not point any longer to the location? If it is not
done right then when these other nodes are changed or unified with another,
then the algorithm may update the new change made by f.put! The example
which made me think of this possibility is having the program try to recover
from overgeneralization. The program believes that the dog is the agent of
the detection leads to the faulty conclusion the dog is the agent of the
interdiction act. Later we want to learn that the dog was but an agent so
the program must change the extant instantiations of dog outside detection
to authority. f.put! may cause the problem discussed above.
problem was really that if A is a filler to be replaced by B, then if f.put! did
not change the backpointers of A, any process that subsequently did a unify with
A will affect B, since the location is still referenced in A's list of
The interdiction-act can be a part of the bust. We instantiate the bust, then
try to relate the sniff with review process. How is the reminding done so that
We demand a separate decision process which select the reasoning strategy to use,
reasons for performing explanation was that there existed an index to an XP.
However there could also be an index to a case as well. Does the system use the
possibilities. Here is the serial vs. parallel issue among others.
Interesting. Indexes can be variable. To index an explanation for why an agent does X
I suppose that this is because the agent is usually an authority. Instead we use what
the crime is. This is the variable which varies to produce dependent cases? Should
consider this more.
NOTE that when the program instantiates the interdiction-act in the bust because it
reads about the arrest, the system implicitly infers the existence of the confiscation
even though it is not mentioned in the story. This will not be registered in the
deliberate ones.
of making parameter passing and return values implicit from the view of
a single function. Especially parameter passing. Function returns and
function side effect is now a slot in a structure, so I guess it is more
explicit. However instead of the programmer being able to point to the
formal parameter list, we instead have to assume knowledge concerning where
After the program hypothesizes that sniffing can be viewed as a detection,
it then reviews other detection methods that it knows about, to see if they
can fit the description (is this a conscious review or a reminding; how are
reminding and review related?). Then the program can post a specific
hypothesis that it needs to have a new type of detection-method and thereby
later modifying the isa-hierarchy. ???
structures? Do we need to divide the functions, instead of having such a
large and global structure?
When f.unify fails it generates a failures list. This represents an anomaly!
Generates additional questions. Both in sniff-detection anomaly and in
dog-authority anomaly.
Also need to generate a specific question asking how the dog physically
accomplished the detection.
The frame system DOES have to use the .list designator. Either that or
require all facet fillers to be lists, even if they have only a single
item. The problem lies in the ambiguity between the following:
and
For the time we use a hack. A list of frames is defined to be when
or a variable identifier (ie. =X).
Need function f.bound-put! in frame.lisp which destructively adds a filler
to a frame. It differs from the normal f.put! though since if the facet is
bound to other facets in the same frame, then it changes their value also.
To do this we need to keep track of the bindings better in the frame
definitions.
Still seem to have a problem with backpointers.
I was creating one in f.make-relation and subsequently using it (or planning to).
However even though 'actor is a bound symbol, the program crashes when it hits
(slot (value actor)) slot.
Came up againt the problem again. I suppose this is related to the fact that actor is not
a frame variable as actor.23 is. I now need system slots so I am starting to implement
some of the suggestions below. The slot slot will be a property like isa. Will worry about
specify a slot slot when defining particular relations,
All system slots should be made properties of the variables instead of sublist as is now
the case with the isa slot. This would make unification easier. How will the slots be
defined? Since system slots should be common to all frames, we could have a special
definition of the frame 'entity' which all frames share the slots of. Also realize that
same type, we need to make sure that the result has the correct slot property. But since
the result of the unify is guaranteed to be the most specific frame, it will have the
right slot property, a new one will not be created.
Another problem with lists of frames: FACETS. If a slot is a list of frames, then the
order must be significant since there could be an associated list of relation facets, etc.
Without some kind of placeholder we do not know what value the relation coresponds to.
no way the frame systems provides to modify the ith facet in a list. The user must read
the value and insert a new value in the appropriate place. The frame system should then
be responsible for updating (adding of deleting) the remaining facets when a change occurs
When the program learns that there are distinctions to be made between
dogs barking at animate objects (threaten explanation) and dogs barking
at inanimate objects (detection explanation), and that dogs barking in
have the additional features on barking, while barking is still the category.
How to represent questions and index answers such as
Why did the dog bark?
Why was there barking?
Why did the dog bark at x?
Why does the dog bark at red objects?
20 Oct 91
tweak-node will be a (node slot filler) triple returned by view-as.
The facet is guaranteed to be *value-facet*.
if view-as returned something
else set it with the reverse of failure-list.
||||| NOTE that it does not make sense to check for same main-result
unless both nodes are MOPs or specializations of MOPs. Fix this.
Function outcome-template creates a representation to be placed on the
outcome of the hypo-node. It says that knowing that there was no xp in the
foreground knowledge initiates the knowledge of retrieval failure. That
is, the reasoner is stumped.
Function exists-in-story is a predicate that returns t if the input
assertion can unify with a concept in the world model or a concept
reachable from some concept in the world model.
Want to view the source as the target concept. To do this we search for a
value facet in the target which is the same type as the source. Returns the
node (as slot filler pair) at which source was unified, or nil if no
unifiaction is possible.
||||| This heuristic will not work very well if there are multiple
inside of an interdiction-act.
Oh the HACKery!
||||| Do I really want to check for filler being an instance?
Ie. one with a period imbedded in it. We may allow abstractions.
Question this relation as only hypothesized to be true.
||||| Since all input has relations explicitly added now,
is the call of f.mmake-relation necessary (harmful)?
||||| Do we really need this here?
(with-character-style (*Style*)
)
||||| Is filler and source now guaranteed to be same?
THREE PHASES OF UNDERSTANDING
Question Identification Phase
Identification phase: Questioning (function pose-question) and
skimming (function skim).
Function pose-question actually poses the question "Why did the actor of
the event passed as the concept parameter perform the action?" Modified so
generally, why values are domains of relations. [30oct94]
How to mark this as a question explicitly. It is a knowledge goal so we
is really supposed to be a facet on the actor slot. Now how do we say "Why
did the actor choose to enter into this relation. Tag the XP with status =
question!
For example, the function parameters (and local var) might be as follows:
action = DOG-BARKS.25745
anomaly = ANOMALY.26311 -> (ANOMALY
(ACTUAL-OUTCOME (VALUE LUGGAGE.25748))
(ACTION (VALUE DOG-BARKS.25745))
(PATHS (VALUE LITERAL.26312)))
ID.26224 -> (ID (CO-DOMAIN (VALUE DOG-BARKS.25745)))
relation = ACTOR.25747 -> (ACTOR (DOMAIN (VALUE DOG-BARKS.25745))
(CO-DOMAIN (VALUE DOG.25746)))
NOTE THAT MAP-2-SLOT MAY SET ADD-BREAK
Add-break can be set by map-2-slot
(entity)
Paths are in a literal.
Post goal to generate hypothesis.
(with-character-style (*Style*)
)
[30oct94]
Function skim is a function which basically makes a minimal set of
inferences such as those involved with story coherence. The function
attempts to understand the input concept through simple script application.
It also performs a print operation and deletes the current goal from the
*Goal-Queue* (which is a small hack).
(assert (eq concept
(get-model
*World-model*)))
(*World-Model*)
"Error in Skim")
(with-character-style (*Style*)
)
The following is the reason we will generate a question.
(f.instantiate-frame
(if reason
(list concept reason)
(list 'noreason nil)))
The function identify-question not only performs the primary role of
determining whether there is a question that must be posed, but if there is
not (and thus the program skims the input), then it also is the function
that actually updates the script match number and passes it all the way
generation then passing it back to spinqua).
Note that which-strategy is really a dummy variable.
Hypothesis Generation Phase
Generation phase: Suspension (function suspend-task), explanation
(function explain), analogy (function (analogize) and case-based
reasoning (function episodize). Analogy is not actually implemented.
Function resume-generation-phase is called by function answer-old-questions
when opportunistically picking up on old processing that may now be
completable. See resume-examination-phase.
If answer is not an XP, then the function returns immediately with a value
(with-character-style (*Style*)
)
This is the case when the system was stumped (could not previously generate
an answer to the question) and now is presented a possible answer.
Must remove the suspend strategy-choice.
And the indication that suspension was done.
Come back to allow the system to reject an inappropriate IMXP.
Place the stumped representation on the outcome of the generation phase.
(break "resume-generation-phase")
Spawn a goal to learn.
Review the reasoning which led to the faulty conclusions.
Then need to place the retrieval failure representation for stumped.
Place question on it to make sure that there exists no item in memory?
Function contains-previous-anomaly-p acts as a predicate that returns
non-nil whenever the reasoning trace that pursued the old goal detected an
anomaly during the identification phase to initiate the reasoning, rather
than some other reason such as the original input being interesting.
Function suspend-task is called by the hypothesis-generation and
verification phases of both understanding and planning. Suspension occurs
when the goal cannot be accomplished, so the task to achieve the goal is
suspended until later opportunities arise.
(with-character-style (*Style*)
)
Remove the goal and all the superordinate goals above
it in the hierarchy from the goal queue.
|||||
||||| Eventually make more systematic, using all available info.
The basis for the decision is now the value pointed to by the index.
The index currently has no name; it is an indirect reference so has
functions can just use the value placed in the processing trace
associated with k-goal, not the index (sic).
||||| This function has become too long. Clean it up. Should we
really be putting the case on the tmxp slot associated with the
k-goal? This is supposed to be a decision phase not a strategy
execution. I had to put the k-goal parameter on here just to do
The following is the reason we will generate a hypothesis.
||||||Perhaps should place stumped (baffled?) representation on d-c-node at this point.
(format *aqua-window*
(str-concat
"~%Suspension in h.strategy-decision."
"~%Called with ~s and ~s.")
hypo-node
questions)
||||| Instead of passing the choice perhaps runstrategy should find
the choice in the current trace of the processing attached to
k-goal.
i.e. , one without a previous explanation .
(f.put! (list (explain question hypo-node k-goal))
(f.get hypo-node 'main-result)
'members)
(break "Check hypo node main result")
||||| The following code is currently dependent on the order of parameters.
||||| This is a case for use of f.bound-put! when finished.
Also, all strategy choices are guaranteed currently to return an XP.
This may not always be so.
||||||If I get to the following, shouldn't I be suspending the task?
Verification Phase
phase: Suspension (function suspend-task), comparison (function
compare), and devising a test (function devise-test). Devise-test is
not actually implemented.
Function resume-examination-phase is called by function
answer-old-questions when opportunistically picking up on old processing
that may now be completable. See resume-generation-phase.
The function is not guaranteed to return t any longer. If the answer does
not match to the question and the answer is not an alternative xp, then the
function prints a message that the input does not help answer the old
question and it returns nil. This forces function answer-old-questions to
also return nil, which causes function do-understand to call reason-about.
(and if apply-xp is fixed) make sure that the pre-xp-nodes are in.
|||||| Cannot perform the following because there is already
a different explanation on the slot rather than a dummy.
(merged-node (f.unify (f.get question *explanations-slot*) answer))
||||||Possibly will always be an old answer, even if dummy.
to see that there was no reason yet to decide on a test method. Now we can do
the compare
Try matching strictly.
Now try lazy matching.
The current-phase is the test relation, thus the co-domain is the verify d-c-node.
Added [cox 25def95]
Must remove the suspend strategy-choice.
And the indication that suspension was done.
Review the reasoning which led to the faulty conclusions.
Come back to allow the system to reject an inappropriate IMXP.
Current value of the IMXPs stored at this location.
Added [cox 25def95]
Must remove the suspend strategy-choice.
And the indication that suspension was done.
This routine is the one that (when implemented) will link understanding
with problem-solving; that is, in order to verify a hypothetical
interpretation of some input, a reasoner may have to devise a test and then
plan the test.
||||| NOTE THAT BECAUSE THE FUNCTION COMPARE (or is it big-hack now?)
CHANGE WHAT THE FRAME VARIABLE POINTED-TO BY IT CONTAINS. TO CHANGE THIS IS
COMPARE IS ALREADY RETURNING A VALUE TO BE SET TO SOMETHING BY THE CALLING
PARAMETER IS OBTAINED FROM THE PARAMETER OF THE CALLING FUNCTION. NEED TO
FIX THIS ASAP.
Since the learning does not really depend on this hack, I do not think that
it is a real fudge about which to be worried. [30oct94]
Big HACKs. This is the unification of the sniff with the explanation of the bark.
Since the story does not explicitly say that the detection is the sniff, we need
infer it by backtracking. The system then needs to notice that the detection must
be the one in the bust scene.
(format *aqua-window*
"~%Unify goal-scene of tip-off with goal-scene of bark.")
(f.unify (f.get d-method 'goal-scene)
(f.chase-path alternative 'consequent 'goal-scene))
(format *aqua-window*
"~%Unify bark from because statement with previous bark.")
(f.unify (f.get alternative 'consequent)
(format *aqua-window*
"~%Add sniff as instrumental scene of detection-method.")
The following puts the sniff on the instrumental-scene slot of the detection method.
(format
*aqua-window*
"~%F.unify tip-off with detection-method of detection scene of bust.")
Returns a case.
(f.unify (f.get alternative 'antecedent)
(return-last-element (get-model *World-Model*)))
(with-character-style (*Style*)
(f.get question *domain-slot*)
)
Function compare in this form is truer to the way in which it was presented
hypothesis as node E. The function returns either a successful prediction
node or an expectation failure node.
Return the conclusion: Successful-Prediction or Expectation-Failure.
Side-effect: if expectation-failure, then spawn a goal that initiates
learning.
Successful hypothesis, so remove knowledge goal.
Post immediate goal to review process.
Review the reasoning which led to the faulty conclusions.
Function v.strategy-decision looks to see if there are any
compatible concepts that could verify the hypothesis. If so it tries
to compare these with the hypothesis. Otherwise it suspends the
verification till a later time when more output may be available.
||||| Currently there is never a decision made to try to test a
hypothesis. We usually suspend. Compares are then done when a later
input can answer the question. The hypothesis is then checked for
agreement.
Function find-relevant-input takes as input a hypothetical explanation, and
same type as the object (explains node) of the hypothetical explanation
input to the function. The explains node represents what the explanation is
explaining.
This function is called by function v.strategy-decision. The purpose is to
retrieve a relevant piece of new input from the story that corroborates an
old explanation.
(get-model *World-Model*)
Predicate test-applicable-p takes a hypothesis and returns whether or not a
test can be devised (or is it worth for the system to try an devise a test)
for the hypothesis.
||||| Currently NOT implemented.
||||| See comment below for why the callers of f.put! is important.
The following calling sequence works because f.put will return the filler
passed to it. The filler is the value returned by v.strategy-decision.
||||| NOTE that by using f.put! strategy decision will be assigned the value returned by
This is why I need to finish f.bound-put!. Same event happens in function generate-hypothesis.
I commented out the code the remarks above refer to and use f.unify until a more general
function like f.boutd-put! is finished.
(v.runstrategy (f.put! verify-node
'strategy-choice
*value-facet*
(v.strategy-decision hypothesis))
hypothesis)
||||| The following code is currently dependent on the order of parameters.
MAIN CONTROL FUNCTIONS
Function boot-understanding is the routine to handle
understanding goals in the dispatch call of function
reason-about. It spawns a goal to identify any questions
concerning the desired goal-state of the k-goal.
Post goal to identify the question.
Function dispatch-knowledge-goal calls particular reasoning
functions depending on the type of goal-object in the knowledge
goal. It returns a phase identifier that corresponds to the
goal-object type. The counterpart function in the
problem-solving process is dispatch-world-goal.
(possibly updated) script match number.
(this is returned by function processing-trace)
and determines where in the reasoning chain the sequence is. It then
calls dispatches the proper routine to pick up the reasoning by
calling dispatch-goal. It also passes the proper parameter info
Parameter k-goal is the knowledge-goal.
NOTE that reason-about is the primary dispatching function for
that records such reasoning. However the function
answer-old-questions also performs this role when resuming suspended
reasoning tasks.
Returns script-match-number. It is (possibly) updated when passed
through dispatch-knowledge-goal.
NOTE that because D-C-Node is passed to dispatch-goal
and is possibly unified with other frames it might be
no longer point to the correct node.
Function do-understand processes a knowledge goal by checking to see if the
current input (new input) possibly addresses a previously suspended
question. If so it attempts to answer the question with the input, else it
processes the input normally via the reason-about function.
The function returns the script-match-number. It is (possibly) updated if
passed through reason-about.
Note that this is not necessarily new input.
Goal is to understand a new input.
Notice is currently used to unify a
posted goal with its equivalent.
If old questions exist
and not a reassertion of the action being questioned.
{this line guaranteed true}
{in order to print }
and either
on automatic run or
user wants these questions answered
Prompt the user.
This will work for simply indexed questions.
then answer them
Return script match number unchanged.
else pursue the reasoning goal, returning
the script-match-number which may be changed by
function reason-about.
(with-character-style (*Style*)
)
|
(in-package :metaaqua)
Copyright ( C ) 1996 ( )
under the terms of the GNU General Public License as published by the Free
You should have received a copy of the GNU General Public License along
Mass Ave , Cambridge , , USA . In emacs type C - h C - w to view license .
Some possibilities for addition to standard Aqua :
Creating tests to determine the best XP
Meta - XPs .
Can we find old Meta - XPs during processing to use as shortcuts by successive
refinement of the current Meta - XP in memory ? We then should run into other
its bindings . Eg PTRANS.666 - > ( PTRANS ( actor ( value PERSON.23 ) ) ... )
( eval ( car PTRANS.666 ) ) - > ( PTRANS ( actor ( value = X ) ) ... ) .
||||| ( NOTE : 5 pipes mark comments that eventually must be addressed . )
ISA hiearchy is still incomplete . Include other definitions from 's
is performed . 25 Oct 91
META - XP REPRESENTING THE CHAIN OF REASONING ! ! ! But this is not central to the research !
HAVE TWO RUNS THAT CAN DEMONSTRATE THE SPEEDUP OR OTHER BENEFITS OF LEARNING
WITH AND WITHOUT META - XPS .
The above discussion is a little off , but the first line is most important . The
backpointers . -This is now fixed . 23 Apr 91 .
When reading the arrest scene , need to represent its larger context : The BUST .
the PRECONDITON XP is properly found and applied ?
Make the program more similar to the reasoning model presented in the SAIC paper .
eg . CBR or explanation or analogy . How is this decision made if for example both
CRB and explanation have potential . In the XP sketched in the SAIC paper the
first strategy that " comes to mind " or does it arbitrate between all
one uses X and the agent , but to index a case of arrest we do not refer to the agent .
Trace - Meta - XP , but that may not be wrong . Many inferences humans make surely are
subtle and unconscious whereas others will be deliberate . The META - XP registers the
By making the processing explicit using Trace - Meta - XPs we produce side effect
in a Trace - Meta - XP the is . What are the implications of this trade - off ?
NEED TO CONSIDER THE DIAGRAM AND COMMENTS FROM BLUE NOTEBOOK 22FEB91 ! ! !
These comments show many more representational features for a META - XP .
Where are the limits of an META - XP ? What is the functional role of these
( dummy.101 ( ptrans ( actor ( value = x ) ) ) )
( ptrans ( actor ( value = x ) ) ) .
the first item is either a listr , a frame identifier ( ie . )
When unifying two nodes there is a problem with system slots such as a ' slot slot .
defining global system slots later . 21 Aug 91 . NOTE though that we must how to
e.g. , ( define - relation X ( domain ... )(co - domain ... )(slot x ) ) . 26
the function f.unify may be affected . When two slots are unified and they are not of the
The order of the list itself may NOT be significant if one views the associated lists as
having a corespondance , e.g. , ( ( value ( v1 v2 v3))(relation ( r1 r2 r3 ) ) ) . However if
one one is provided with a special facet , all others must at least be given a dummy . For
instance notice what happens if has values v1 .. v3 and v2 is given a relation facet .
Dummies must be padded for the longest list . Consider a slot with three constraint facets .
One may have only one value known , but may later add a fourth . When adding the first
value the system needs to pad two dummies in the value facet list . However when adding
a fourth value the system must pad an extra dummy constraint . Notice also that there is
by a f.put ? 4 Sep 91
There is a choice to be made in the manner in which one indexes memory :
general is not specific enough , there are two possibilities for indexing .
AQUA would handle this by creating new categories of barking to index
the separate explanations . will for the time use indexes that
What is the trade - off between the two methods ? 20 Oct 91
(defun tweak (failure-list)
(let ((tweak-node (apply #'view-as failure-list)))
(format *aqua-window*
"~%~%~s can be viewed as ~s."
(second failure-list)
(first failure-list))
(format *aqua-window*
"~%because both ~s and ~s are ~s."
(second failure-list)
(third tweak-node)
(get-abstraction
(frame-type
(second failure-list))))
t)
(apply #'view-as
(reverse failure-list)))
(format *aqua-window*
"~%~%~s can be viewed as ~s."
(first failure-list)
(second failure-list))
(format *aqua-window*
"~%because both ~s and ~s are ~s."
(first failure-list)
(third tweak-node)
(get-abstraction
(frame-type (first failure-list))))
t))
(cond (tweak-node
(format *aqua-window*
"~%~s is the value of the ~s slot of ~s.~%"
(third tweak-node)
(second tweak-node)
(first tweak-node))
(format *aqua-window*
"~%Tweak succeeds.")
t)))
)
(defun similar-p (failures)
(let ((lca-type nil)
(result-type nil)
(success nil))
(cond ((multiple-value-setq
(success result-type)
(apply #'same-results-p failures))
(format
*aqua-window*
"~%~%However they are somewhat similar.")
(format
*aqua-window*
"~%~s and ~s both have ~s as a main-result."
(first failures)
(second failures)
result-type)
(cond ((multiple-value-setq
(success lca-type)
(apply #'siblings-p failures))
(format
*aqua-window*
"~%Also they are siblings at the ~s level."
lca-type)
(values t result-type lca-type))
(t
(values nil result-type lca-type))))
(t
(format
*aqua-window*
(str-concat
"~%~%~s and ~s are not similar. "
"They have different main-results.")
(first failures)
(second failures))
(values nil result-type lca-type)))))
(defun outcome-template (answer hypo-node)
`(mentally-initiates
(results- (,*value-facet*
,hypo-node))
(,*domain-slot*
(,*value-facet*
(truth =truth-relation
(,*domain-slot*
(,*value-facet* =xp))
(,*co-domain-slot*
(,*value-facet* ,*out*)))))
(,*co-domain-slot*
(,*value-facet*
(retrieval-failure
(initiates- (,*value-facet* =domain))
(expected-outcome
(,*value-facet*
(xp =xp
(truth (value ,*out*)
(relation =truth-relation))
(results- (,*value-facet* ,hypo-node))
)))
(actual-outcome
(,*value-facet* ,answer))))))
)
(defun exists-in-story (assertion)
(let ((found nil))
(or
(some
#'(lambda (each-world-concept)
(when
(can-unify-p
each-world-concept
assertion)
(if *Show-Bugs*
(format
*aqua-window*
"~%Asserted node ~s already known"
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%In first conditional test."
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%each-world-concept:~s."
each-world-concept))
(setf found t)
))
(get-model *World-Model*))
(some
#'(lambda (each-world-concept)
(f.traverse-frame
each-world-concept
#'(lambda (current-frame parent role facet-name level)
(when
(and
(not (visited-p current-frame))
(can-unify-p current-frame
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%Asserted node ~s already known"
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%In second conditional test."
assertion))
(if *Show-Bugs*
(format
*aqua-window*
"~%Current frame:~s~%parent:~s~%role:~s~%facet-name:~s~%level:~s."
current-frame parent role facet-name level))
(setf found t)))))
(get-model *World-Model*)))
found)
)
source - types within target . For example there could have been many mtrans
(defun view-as (target source)
(some #'(lambda (each-slot)
(if (not (equal 'instrumental-scene-of
(slot->role each-slot)))
(some #'(lambda (each-facet)
(let ((filler (facet->filler each-facet)))
(if (and (frame-var-p filler)
(equal (facet->facet-name each-facet)
*value-facet*))
(or (cond ((intersection (get-abstraction filler)
(get-abstraction (frame-type source)))
(mark-as-question
(f.make-relation target (slot->role each-slot))
*hypothesized-in*)
(format
*aqua-window*
(str-concat
"~%Trying to understand why actor "
"performs this act.~%"))
(setf filler
(f.unify filler
source))
(setf source filler)
(list target (slot->role each-slot) filler)))
(view-as filler source)))))
(slot->facets each-slot))))
(f.slot-list target))
)
Currently two strategies exist to choose from in the Question
that it will also ask why xps explain their explains node , and more
know this , but how did do it ? Consider that the * explanations - slot *
( EXPECTED - OUTCOME ( VALUE ANIMATE - OBJECT.26303 ) )
LITERAL.26312 - > ( ( OBJECT ) ( TO DOMAIN ) )
supergoal = GOAL.26225 - > ( GOAL ( GOAL - OBJECT ( VALUE ID.26224 ) ) )
(defun pose-question (action anomaly supergoal)
(let* ((relation
(f.get-relation
(tmxp (processing-trace supergoal))
(is-repeat-question?
(not (null (f.get relation *explanations-slot*))))
)
(str-concat
"Action arg for pose-question "
"neither mop nor xp"))
(if (not is-repeat-question?)
(f.put!
(list
(mark-as-question
(f.instantiate-frame
`(xp
(,*explains-node*
(,*value-facet*
,relation
))
(mxp
(,*value-facet* ,tmxp))))
*hypothesized*))
relation
*explanations-slot*))
(print-question-posed
relation
action
is-repeat-question?)
(when (not is-repeat-question?)
(index-question
relation
is-repeat-question?)
(index-anomaly2 relation
(f.get anomaly 'paths))))
(spawn-sub-goal
*current-character*
(make-goal-state 'generate
*current-character*
relation)
'knowledge-acquisition-goal
'seven.0
supergoal)
relation)
)
(defun print-question-posed (relation
action
&optional
is-repeat-question?
(stream *aqua-window*))
"Provide English feedback for the questions posed."
(format
stream
(str-concat
(if is-repeat-question?
"~%~%Repeating Old Question: ~s~% "
"~%~%Posing Question: ~s~% ")
(cond ((isa-p 'mop (list action))
"Why did the ~s ~s perform the ~s?~%")
((isa-p 'xp (list action))
"Why is the ~s ~s explained by this ~s explanation?~%")
(t
"Why is ~s ~s the domain of the ~s relation?~%" )))
relation
(frame-type
(f.get action
(map-2-slot action)))
(f.get action
(map-2-slot action))
(frame-type action))
)
(defun map-2-slot (action &optional break)
"Map an action to a slot for question posing."
(cond ((isa-p 'mop (list action))
*actor-slot*)
((isa-p 'xp (list action))
*explains-node*)
(t
(if break
(add-break pose-question))
*domain-slot*))
)
(defun skim (concept id-node k-goal)
( first
(format
*aqua-window*
(str-concat
"~%~s is not a very interesting "
"concept.~% Skimming . . .~%")
concept )
(remove-achieved-goal k-goal)
(scriptify *World-Model*)
)
(defun q.strategy-decision (decision-basis concept)
(let ((reason (interesting-p concept))
(k-state (f.instantiate-frame
knowledge-state)))
(f.put-all!
(or reason
(list 'noreason nil))
k-state
'believed-item
)
(f.put!
(list k-state)
(f.get
decision-basis
'knowledge)
'members)
(if reason
'questioning.0
'skimming.0)
))
(defun q.runstrategy (id-node choice concept k-goal)
(if (equal choice
'pose-question.0)
(do-break q.runstrategy))
(f.unify (f.get id-node 'main-result)
(f.instantiate-frame outcome))
(case choice
(questioning.0
(f.put! (list (pose-question
concept
(f.get
(first (return-decision-basis
id-node))
'believed-item)
k-goal))
(f.get id-node 'main-result)
'members)
'pose-question.0)
(skimming.0
(values 'skim.0
(skim concept id-node k-goal)))
( t (format
*aqua-window*
"ERROR: unknown q-strategy - ~s."
choice)))
)
back to Meta - AQUA to be returned ( and if spinning automatic story
(defun identify-question (k-goal id-node script-match-number)
(let ((new-input (goal-state k-goal))
(new-script? nil))
(f.unify
(multiple-value-setq
(which-strategy
new-script?)
(q.runstrategy
id-node
(f.unify
(f.get id-node 'strategy-choice)
(q.strategy-decision
(return-decision-basis
id-node)
new-input))
new-input
k-goal))
(f.get id-node 'strategy-execution))
(if new-script?
(+ 1 script-match-number)
script-match-number))
)
Currently four strategies exist to choose from in the Hypothesis
of nil ( and no side - effect ) , otherwise it executes the body and returns t.
(defun resume-generation-phase
(answer questions old-goal current-goal question old-answer phase
&optional automatic?)
(do-break resume-generation-phase)
(when (not (isa-p 'xp (list answer)))
(format
*aqua-window*
"~%But input does not help answer question.~%")
(return-from resume-generation-phase nil))
(format
*aqua-window*
"~%Found answer for previous baffling question.~%")
(let* ((hypo-node (f.get phase *co-domain-slot*))
(hypo-goal (return-phase-goal hypo-node)))
(f.put-all! *nil* hypo-node 'strategy-choice)
(f.put-all! *nil* hypo-node 'strategy-execution)
(resume-goal-hierarchy hypo-goal)
|||||| This hack is temporary in oder to get the data . [ cox 12jun95 ]
(if (isa-p 'xp (list old-answer))
(let ((current-val
(get
(get
(get
'mentally-initiates
'truth)
'retrieval-failure)
'xp-type.0)))
(if (contains-previous-anomaly-p old-goal)
(if (not
(f.get
(first
current-val)
'anomaly))
(setf (get
(get
(get
'mentally-initiates
'truth)
'retrieval-failure)
'xp-type.0)
(reverse
current-val)))
(if (f.get
(first
current-val)
'anomaly)
(setf (get
(get
(get
'mentally-initiates
'truth)
'retrieval-failure)
'xp-type.0)
(reverse
current-val)))
)))
(cond ((dummy-explanation-p old-answer)
(explain question hypo-node old-goal answer automatic?)
(remove-indices-to-answered-question question)
(f.unify
(assert-truth
*in*
(f.instantiate-frame
(outcome-template answer hypo-node))
)
(first (return-result hypo-node)))
(spawn-sub-goal
*current-character*
(make-goal-state
'review/learn
*current-character*
(processing-trace old-goal))
'knowledge-acquisition-goal
'three.0
old-goal))
(t
(format
*aqua-window*
"ERROR in resume-generation-phase.")))
t)
)
(defun contains-previous-anomaly-p (old-goal)
(isa-p
'anomaly
(list
(f.get
(first
(return-decision-basis
(f.get
(processing-trace old-goal)
'identification)))
'believed-item)))
)
(defun suspend-task (dummy goal)
(format
*aqua-window*
(str-concat
"~%Cannot achieve ~s at this time."
"~% Suspend ~s task . . .~%")
goal
(frame-type (goal-object goal))
)
(suspend-goal-hierarchy goal)
dummy)
(defun analogize (question k-goal)
(format
*aqua-window*
"~%Should not have tried to run analogize.~%")
question)
See SAIC paper .
two indexes really . Fix eventualy . For now the strategy execution
this . Check what happens in other strategy decision routines . 3 May
93 .
(defun h.strategy-decision (decision-basis questions hypo-node k-goal)
(let ((xps (retrieve-xps questions))
(k-state (f.instantiate-frame
knowledge-state))
(return-val nil))
(do-break h.strategy-decision "Retrieved XPs: ~s" xps)
(cond (xps
(f.unify (make-index
questions xps)
(f.get
k-state
'believed-item))
(setf return-val 'explanation.0))
(t
(let ((case (retrieve-case questions)))
(cond (case
(f.unify (make-index
questions case)
(f.get
k-state
'believed-item))
(f.put! case
(processing-trace k-goal)
'cases)
(setf return-val 'CBR.0))
(t
(setf return-val 'suspension.0))))
))
(f.put! (list k-state)
(f.get
decision-basis
'knowledge)
'members)
return-val)
)
(defun h.runstrategy (hypo-node choice question k-goal)
(f.unify (f.get hypo-node 'main-result)
(f.instantiate-frame outcome))
(if
(and
(not (eq choice 'suspension.0))
(dummy-explanation-p
(first
(f.get question *explanations-slot*))))
(set-self-gen-answers
*Current-Result-Record*))
(case choice
(explanation.0
(f.unify
(explain question hypo-node k-goal)
(first (return-result hypo-node)))
'explain.0)
(analogy.0
(f.unify
(analogize question k-goal)
(first (return-result hypo-node)))
'analogize.0)
(CBR.0
(f.unify
(episodize question k-goal)
(first (return-result hypo-node)))
'episodize.0)
(suspension.0
(suspend-task question k-goal)
'suspend-task.0)
( t (format
*aqua-window*
"ERROR: unknown h-strategy - ~s." choice))))
(defun generate-hypothesis (k-goal hypo-node)
(let ((questions (goal-state k-goal)))
(f.unify (h.runstrategy
hypo-node
(f.unify (f.get hypo-node 'strategy-choice)
(h.strategy-decision
(return-decision-basis
hypo-node)
questions
hypo-node
k-goal))
questions
k-goal)
(f.get hypo-node 'strategy-execution))
(if (not
(equal 'suspension.0
(f.get hypo-node 'strategy-choice)))
(let ((resulting-xp
(first (return-result hypo-node))))
(cond (resulting-xp
(f.put-all!
resulting-xp
(processing-trace k-goal)
'main-xp))
(t
(break "ERROR: No xp results"))))))
)
Currently three strategies exist to choose from in the Verification
(defun resume-examination-phase
(answer questions old-goal question old-answer phase)
(do-break resume-examination-phase)
(if (and (isa-p 'xp (list answer))
(equal (frame-type (f.get answer *explains-node*))
(frame-type question)))
||||| Probably should really do an apply - xp here . This would generate hvqs
(let ((merged-node (f.unify (f.get answer *explains-node*)
question t nil t))
)
(list answer old-answer)
(list answer))
merged-node
*explanations-slot*)))
||||| Eventually we should make sure first that there was no test of the
hypothesis being done first . We must look at the reason for the original suspension
(if (and (isa-p 'xp (list old-answer))
(contains-previous-anomaly-p old-goal))
(cond
(let* ((verify-node (f.get phase *co-domain-slot*))
(verify-goal (return-phase-goal verify-node)))
(f.put! *nil* verify-node 'strategy-choice)
(f.put! *nil* verify-node 'strategy-execution)
(resume-goal-hierarchy verify-goal)
(verify verify-goal
verify-node)
(remove-indices-to-answered-question question)
(spawn-sub-goal
*current-character*
(make-goal-state
'review/learn
*current-character*
(processing-trace old-goal))
'knowledge-acquisition-goal
'ten.0
old-goal)
t
))
(t
(format
*aqua-window*
"~%~%New input does not help answer old question.~%~%")
nil))))
(t
|||||| This hack is temporary in oder to get the data . [ cox 14jun95 ]
(if (isa-p 'xp (list old-answer))
(get
(get
(get
'mentally-initiates
'not-equal-relation)
'expectation-failure)
'xp-type.0)))
(if (contains-previous-anomaly-p old-goal)
(if (not
(f.get
(first
current-val)
'anomaly))
(setf (get
(get
(get
'mentally-initiates
'not-equal-relation)
'expectation-failure)
'xp-type.0)
(reverse
current-val)))
(if (f.get
(first
current-val)
'anomaly)
(setf (get
(get
(get
'mentally-initiates
'not-equal-relation)
'expectation-failure)
'xp-type.0)
(reverse
current-val)))
)))
(cond
(let* ((verify-node (f.get phase *co-domain-slot*))
(verify-goal (return-phase-goal verify-node)))
(f.put! *nil* verify-node 'strategy-choice)
(f.put! *nil* verify-node 'strategy-execution)
(resume-goal-hierarchy verify-goal)
(verify verify-goal
verify-node)
(big-hack old-answer answer)
(remove-indices-to-answered-question question)
t
))
(t
( break " Odd that ~s is not an xp . " answer )
(format
*aqua-window*
"~%~%New input does not help answer old question.~%~%")
nil))))
)
(defun devise-test (hypothesis k-goal)
(format
*aqua-window*
"~%Execution of devise-test should not have occurred.~%")
)
PERFORMS A F.UNIFY WITH THE HYPOTHESIS PARAMETER , IT MAY INADVERTENTLY
NOT AS EASY AS THE CHANGES WE DID TO FUNCTION REVIEW . THE REASON IS THAT
FUNCTION . ALSO WE JUST USE MULTI - VALUE RETURN VALUES SINCE THE
(defun big-hack (alternative hypothesis)
(let ((d-method (f.instantiate-frame tip-off)))
( fourth ( get - model * World - Model * ) ) )
(f.put (return-last-element (get-model *World-Model*))
d-method
'instrumental-scene)
(f.unify
d-method
(f.get
(get-scene 1
)
'method))
(let ((question (f.get hypothesis *explains-node*)))
(format *aqua-window*
"~%~%Found a better explanation for action of ~s.~%"
(f.get question *domain-slot*))
(format *aqua-window*
"~%The explanation links together more of the story.~%"
)
(f.put! (list alternative) question *explanations-slot*)))
)
in the MSL-91 paper ( see page 224 ) . Think of the evidence as node A and the
(defun compare (evidence hypothesis k-goal verify-node)
(do-break compare)
(format
*aqua-window*
(str-concat
"~%Compare strategy applied to "
"evidence ~s for hypothesis ~s~%")
evidence
hypothesis)
(cond ((can-unify-p evidence hypothesis)
(assert-truth
*in*
(f.instantiate-frame
`(mentally-initiates
(results- (,*value-facet*
,verify-node))
(,*domain-slot*
(,*value-facet*
(equal-relation
(,*domain-slot*
(,*value-facet* ,evidence))
(,*co-domain-slot*
(,*value-facet* ,hypothesis)))))
(,*co-domain-slot*
(,*value-facet*
(successful-prediction
(initiates- (,*value-facet* =domain))
(expected-outcome
(,*value-facet* ,hypothesis))
(actual-outcome
(,*value-facet* ,evidence)))))
))))
(spawn-sub-goal
*current-character*
(make-goal-state
'review/learn
*current-character*
(f.get hypothesis 'mxp))
'knowledge-acquisition-goal
'ten.0
k-goal)
(assert-truth
*in*
(f.instantiate-frame
`(mentally-initiates
(results- (,*value-facet*
,verify-node))
(,*domain-slot*
(,*value-facet*
(not-equal-relation
(,*domain-slot*
(,*value-facet* ,evidence))
(,*co-domain-slot*
(,*value-facet* ,hypothesis)))))
(,*co-domain-slot*
(,*value-facet*
(expectation-failure
(initiates- (,*value-facet* =domain))
(expected-outcome
(,*value-facet* ,hypothesis))
(actual-outcome
(,*value-facet* ,evidence)))))
)))))
)
(defun v.strategy-decision (decision-basis hypothesis verify-node k-goal)
(let ((relevant-input (find-relevant-input
hypothesis))
(k-state (f.instantiate-frame
knowledge-state))
(return-val nil))
(cond (relevant-input
(format
*aqua-window*
(str-concat
"~%Found relevant input "
"for verifying hypothesis: ~s~%")
relevant-input)
(format
*aqua-window*
"~%Comparison strategy selected ~%")
(do-break v.strategy-decision)
(f.unify
relevant-input
(f.get
k-state
'believed-item))
(setf return-val 'comparison.0))
((test-applicable-p hypothesis)
(setf return-val 'devise-test.0))
(t
(setf return-val 'suspension.0)))
(f.unify k-state
(or
(first
(f.chase-path
decision-basis
'knowledge
'members))
(first decision-basis)))
return-val)
)
returns as output the first item it finds in the world model that is of the
(defun find-relevant-input (hypothesis)
(let* ((hypo-explains (f.get hypothesis
*explains-node*))
(hypo-type (frame-type
hypo-explains)))
(do-break find-relevant-input)
(if (not (null hypo-explains))
(some
#'(lambda (each-world-concept)
(if
(equal
hypo-type
(frame-type
(f.get each-world-concept
*explains-node*)))
each-world-concept))
|||||| Temporary
)))
)
(defun test-applicable-p (hypothesis)
nil)
(defun v.runstrategy (verify-node choice hypothesis k-goal)
(f.unify (f.get verify-node 'main-result)
(f.instantiate-frame outcome))
(case choice
(comparison.0
(f.put! (list (compare
(f.get
(first
(return-decision-basis
verify-node))
'believed-item)
hypothesis
k-goal
verify-node))
(f.get verify-node 'main-result)
'members)
'compare.0)
(devise-test.0
(f.put! (list (devise-test hypothesis k-goal))
(f.get verify-node 'main-result)
'members)
'devise-test.0)
(suspension.0
(suspend-task hypothesis k-goal)
'suspend-task.0)
( t (format
*aqua-window*
"ERROR: unknown v-strategy - ~s." choice))))
(defun verify (k-goal verify-node)
v.strategy - decision ( a string ) . However the slots in the d - c - node which are bound to the
strategy - choice slot ( the co - domain of link2 and the domain of link3 ) will not be changed .
(let ((hypothesis (goal-state k-goal)))
(do-break verify)
(f.unify
(v.runstrategy
verify-node
(f.unify
(f.get
verify-node
'strategy-choice)
(v.strategy-decision
(return-decision-basis verify-node)
hypothesis
verify-node
k-goal))
hypothesis
k-goal)
(f.get verify-node 'strategy-execution)))
)
(defun boot-understanding (k-goal)
(spawn-sub-goal
*current-character*
(make-goal-state
'id
*current-character*
(goal-state k-goal))
'knowledge-acquisition-goal
'seven.0
k-goal)
)
The function returns two values . The main ( first ) value is the phase
identifier ( goal type ? ) of the routine dispatched . The second value is the
(defun dispatch-knowledge-goal (k-goal d-c-node script-match-number)
(values
(case (frame-type (goal-object k-goal))
(understands
(boot-understanding k-goal)
'understands)
(id
(setf script-match-number
(identify-question
k-goal
d-c-node
script-match-number))
'identification)
(generate
(generate-hypothesis k-goal d-c-node)
'generation)
(test
(verify k-goal d-c-node)
'examination)
(review/learn
(learn k-goal d-c-node)
'review)
(t
(format *aqua-window*
"ERROR: unknown goal type in function reason-about.")
nil))
script-match-number)
)
Function reason - about looks at the mxp slot of the knowledge goal
stored in the mxp .
calling the reasoning processes . It also manages the Trace - Meta - XP
(defun reason-about (k-goal script-match-number)
(let ((d-c-node (gen-d-c-node k-goal))
(phase nil))
(do-break reason-about)
(multiple-value-setq
(phase script-match-number)
(dispatch-knowledge-goal
k-goal
d-c-node
script-match-number))
(if (and phase
(not (equal phase 'understands))
(not (equal phase 'wants)))
(let ((which-tmxp
(if (equal phase 'review)
(goal-state k-goal)
(processing-trace k-goal))))
(f.unify
d-c-node
(f.get which-tmxp phase))
(f.put! (f.make-relation
which-tmxp phase)
which-tmxp
'current-phase)))
script-match-number)
)
(defun do-understand (k-goal script-match-number &optional automatic?)
(goal-state k-goal))
(old-questions
(and
'understands
k-goal)
(potential-answer-p new-input)
)))
(do-break do-understand)
(get-model *World-Model*))
(cond ((and
(reasserts-act-being-questioned-p
new-input
(first old-questions)))
(cond
t)
(t
"Try to purge old question?")
(if (retrieve-memory
'question-type.0
new-input)
nil
'question-type.0
new-input)))
nil))
new-input old-questions
(get-old-goal old-questions)
k-goal automatic?))
(t
)
(defun print-remembers-old-question (question)
"Simple feedback to user about reminding."
(format
*aqua-window*
"~%~%Input triggers reminding of old question:~% ~s~%"
question)
t
) |
63292cf4ee30ee638988796b1c418015c9086ca216687636fa9d80f0008113cf | synduce/Synduce | largest_even_pos.ml | * @synduce -s 2 -NB --no - lifting
type 'a clist =
| Elt of 'a
| Cons of 'a * 'a clist
let rec is_sorted = function
| Elt x -> true
| Cons (hd, tl) -> aux hd tl
and aux prev = function
| Elt x -> prev >= x
| Cons (hd, tl) -> prev >= hd && aux hd tl
;;
let rec lpen = function
| Elt x -> if x mod 2 = 0 then x else 0
| Cons (hd, tl) ->
let r = lpen tl in
if hd mod 2 = 0 && hd > 0 then max hd r else r
;;
let rec amax = function
| Elt x -> [%synt base_case] x
| Cons (hd, tl) ->
if hd mod 2 = 0 && hd > 0 then [%synt f0] hd else [%synt f1] (lpen tl)
[@@requires is_sorted]
;;
assert (amax = lpen)
| null | https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/sortedlist/largest_even_pos.ml | ocaml | * @synduce -s 2 -NB --no - lifting
type 'a clist =
| Elt of 'a
| Cons of 'a * 'a clist
let rec is_sorted = function
| Elt x -> true
| Cons (hd, tl) -> aux hd tl
and aux prev = function
| Elt x -> prev >= x
| Cons (hd, tl) -> prev >= hd && aux hd tl
;;
let rec lpen = function
| Elt x -> if x mod 2 = 0 then x else 0
| Cons (hd, tl) ->
let r = lpen tl in
if hd mod 2 = 0 && hd > 0 then max hd r else r
;;
let rec amax = function
| Elt x -> [%synt base_case] x
| Cons (hd, tl) ->
if hd mod 2 = 0 && hd > 0 then [%synt f0] hd else [%synt f1] (lpen tl)
[@@requires is_sorted]
;;
assert (amax = lpen)
| |
d78aec27bc72edd7c519374f6f0f8e31e22814fac50176e0ecea8fc861a437f9 | life0fun/clojure-idiom | defspout.clj | (defn normalize-fns [body]
(for [[name args & impl] body
:let [args (-> "this"
gensym
(cons args)
vec)]]
(concat [name args] impl)
))
(defmacro defspout [name output-spec & [opts & impl :as all]]
(println opts " : impl= " impl " all= ", all)
(if-not (map? opts)
`(defspout ~name ~output-spec {} ~@all)
(let [worker-name (symbol (str name "__"))
conf-fn-name (symbol (str name "__conf__"))
params (:params opts)
conf-code (:conf opts)
prepare? (:prepare opts)
prepare? (if (nil? prepare?) true prepare?)
fn-body (if prepare?
(cons 'fn impl)
(let [[args & impl-body] impl
coll-sym (first args)
prepargs [(gensym "conf") (gensym "context") coll-sym]]
`(fn ~prepargs (spout (~'nextTuple [] ~@impl-body)))))
definer (if params
`(defn ~name [& args#]
(println ~output-spec ~worker-name ~conf-fn-name args#))
`(def ~name
(println ~output-spec ~worker-name ~conf-fn-name []))
)
]
(println "name=" name)
(println "params=" params)
(println "output-spec=" output-spec)
(println "impl=" impl)
(println "fn-body=" fn-body)
(println "conf-fn-name=" conf-fn-name)
(println "=------" )
;(println definer )
`(do
(defn ~conf-fn-name ~(if params params [])
~conf-code
)
(defn ~worker-name ~(if params params [])
~fn-body
)
~definer
))))
(defmacro spout [& body]
(let [[spout-fns other-fns] (split-with #(not (symbol? %)) body)
fns (normalize-fns spout-fns)]
`(reify ISpout
~@fns
~@other-fns)))
(defspout sentence-spout ["sentence"]
[conf context collector]
(let [sentences ["a little brown dog"
"the man petted the dog"
"four score and seven years ago"
"an apple a day keeps the doctor away"]]
(println sentences)
))
(defspout sentence-spout-parameterized ["word"] {:params [sentences] :prepare false}
[collector]
(Thread/sleep 500)
(println collector [(rand-nth sentences)]))
| null | https://raw.githubusercontent.com/life0fun/clojure-idiom/481b297eeabea917a68b492b1fb78b8151408507/defspout.clj | clojure | (println definer ) | (defn normalize-fns [body]
(for [[name args & impl] body
:let [args (-> "this"
gensym
(cons args)
vec)]]
(concat [name args] impl)
))
(defmacro defspout [name output-spec & [opts & impl :as all]]
(println opts " : impl= " impl " all= ", all)
(if-not (map? opts)
`(defspout ~name ~output-spec {} ~@all)
(let [worker-name (symbol (str name "__"))
conf-fn-name (symbol (str name "__conf__"))
params (:params opts)
conf-code (:conf opts)
prepare? (:prepare opts)
prepare? (if (nil? prepare?) true prepare?)
fn-body (if prepare?
(cons 'fn impl)
(let [[args & impl-body] impl
coll-sym (first args)
prepargs [(gensym "conf") (gensym "context") coll-sym]]
`(fn ~prepargs (spout (~'nextTuple [] ~@impl-body)))))
definer (if params
`(defn ~name [& args#]
(println ~output-spec ~worker-name ~conf-fn-name args#))
`(def ~name
(println ~output-spec ~worker-name ~conf-fn-name []))
)
]
(println "name=" name)
(println "params=" params)
(println "output-spec=" output-spec)
(println "impl=" impl)
(println "fn-body=" fn-body)
(println "conf-fn-name=" conf-fn-name)
(println "=------" )
`(do
(defn ~conf-fn-name ~(if params params [])
~conf-code
)
(defn ~worker-name ~(if params params [])
~fn-body
)
~definer
))))
(defmacro spout [& body]
(let [[spout-fns other-fns] (split-with #(not (symbol? %)) body)
fns (normalize-fns spout-fns)]
`(reify ISpout
~@fns
~@other-fns)))
(defspout sentence-spout ["sentence"]
[conf context collector]
(let [sentences ["a little brown dog"
"the man petted the dog"
"four score and seven years ago"
"an apple a day keeps the doctor away"]]
(println sentences)
))
(defspout sentence-spout-parameterized ["word"] {:params [sentences] :prepare false}
[collector]
(Thread/sleep 500)
(println collector [(rand-nth sentences)]))
|
6437094f460f629fd2062f664ff48f35b02c8fdee2db4711c971f17e67314413 | OpenC2-org/ocas | act_start.erl | @author
( C ) 2017 , sFractal Consulting LLC
-module(act_start).
%%%-------------------------------------------------------------------
%%%
%%% All rights reserved.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%%%
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions are
%%% met:
%%%
%%% * Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
%%%
%%% * Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in the
%%% documentation and/or other materials provided with the distribution.
%%%
%%% * The names of its contributors may not be used to endorse or promote
%%% products derived from this software without specific prior written
%%% permission.
%%%
%%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
%%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
%%% A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES . LOSS OF USE ,
%%% DATA, OR PROFITS. OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
%%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
%%% OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%%-------------------------------------------------------------------
-behaviour(gen_server).
-behaviour(oc_env). % for calling start modules
-author("Duncan Sparrell").
-license("Apache 2.0").
%% gen_server callbacks
-export([ init/1
, handle_call/3
, handle_cast/2
, handle_info/2
, terminate/2
, code_change/3
]).
%% interface calls
-export([ start/1
, stop/0
, keepalive/0
]).
-ignore_xref({start, 1}). % to keep xref happy
-ignore_xref({keepalive, 0}). % to keep xref happy
%% This routine API handles all the actions that can be taken
start(State) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [State], []).
stop() ->
gen_server:cast(?MODULE, shutdown).
keepalive() ->
gen_server:call(?MODULE, keepalive).
%% initialize server with state
init( [State] ) ->
lager:debug( "starting ~p with ~p", [?MODULE, State] ),
{ ok, State }.
%% synchronous calls
handle_call( keepalive, From, State ) ->
lager:debug( "~p got keepalive from ~p", [?MODULE, From] ),
reply to
Response = {keepalive_received, act_start},
{reply, Response, State};
%% handle unknown call messages
handle_call(Message, From, State) ->
lager:info( "~p got unknown ~p from ~p", [?MODULE, Message, From] ),
{reply, error, State}.
%% async calls
handle_cast(shutdown, State) ->
lager:info( "~p got shutdown", [?MODULE] ),
{stop, normal, State};
%% handle unknown cast messages
handle_cast(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
%% handle unknown info messages
handle_info(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
%% handle terminate
terminate(normal, _State) ->
ok.
%% don't really handle code change yet
code_change(_OldVsn, State, _Extra) ->
%% No change planned. The function is there for behaviour sanity,
%% but will not be used. Only a version on the next
{ok, State}.
| null | https://raw.githubusercontent.com/OpenC2-org/ocas/c15132d9f37b1e0e29884456a520557c25b22f38/apps/ocas/src/action_servers/act_start.erl | erlang | -------------------------------------------------------------------
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
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.
-------------------------------------------------------------------
for calling start modules
gen_server callbacks
interface calls
to keep xref happy
to keep xref happy
This routine API handles all the actions that can be taken
initialize server with state
synchronous calls
handle unknown call messages
async calls
handle unknown cast messages
handle unknown info messages
handle terminate
don't really handle code change yet
No change planned. The function is there for behaviour sanity,
but will not be used. Only a version on the next | @author
( C ) 2017 , sFractal Consulting LLC
-module(act_start).
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
" 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
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES . LOSS OF USE ,
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
-behaviour(gen_server).
-author("Duncan Sparrell").
-license("Apache 2.0").
-export([ init/1
, handle_call/3
, handle_cast/2
, handle_info/2
, terminate/2
, code_change/3
]).
-export([ start/1
, stop/0
, keepalive/0
]).
start(State) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [State], []).
stop() ->
gen_server:cast(?MODULE, shutdown).
keepalive() ->
gen_server:call(?MODULE, keepalive).
init( [State] ) ->
lager:debug( "starting ~p with ~p", [?MODULE, State] ),
{ ok, State }.
handle_call( keepalive, From, State ) ->
lager:debug( "~p got keepalive from ~p", [?MODULE, From] ),
reply to
Response = {keepalive_received, act_start},
{reply, Response, State};
handle_call(Message, From, State) ->
lager:info( "~p got unknown ~p from ~p", [?MODULE, Message, From] ),
{reply, error, State}.
handle_cast(shutdown, State) ->
lager:info( "~p got shutdown", [?MODULE] ),
{stop, normal, State};
handle_cast(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
handle_info(Message, State) ->
lager:info( "~p got unknown ~p", [?MODULE, Message] ),
{noreply, State}.
terminate(normal, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
|
ad5bc4fbc141d485c66f134238cabd6768d368c0bd8294c2de0b17238803d54b | tov/dssl2 | negative-huh.rkt | #lang dssl2
assert neg?(-5)
assert neg?(-5.5)
assert not neg?(0)
assert not neg?(1)
| null | https://raw.githubusercontent.com/tov/dssl2/105d18069465781bd9b87466f8336d5ce9e9a0f3/test/dssl2/negative-huh.rkt | racket | #lang dssl2
assert neg?(-5)
assert neg?(-5.5)
assert not neg?(0)
assert not neg?(1)
| |
d9e183818f4aa8c6aad04ec079f3713251213c94c14c21665605a341885e2e0b | project-oak/hafnium-verification | uninit.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 F = Format
module D = UninitDomain.Domain
(** Forward analysis to compute uninitialized variables at each program point *)
module MaybeUninitVars = UninitDomain.MaybeUninitVars
module AliasedVars = AbstractDomain.FiniteSet (UninitDomain.VarPair)
module RecordDomain = UninitDomain.Record (MaybeUninitVars) (AliasedVars) (D)
module Payload = SummaryPayload.Make (struct
type t = UninitDomain.Summary.t
let field = Payloads.Fields.uninit
end)
module Models = struct
let initializing_all_args = [BuiltinDecl.__set_array_length]
let is_initializing_all_args pname =
List.exists initializing_all_args ~f:(fun fname -> Procname.equal pname fname)
end
let should_report_on_type t =
match t.Typ.desc with
| Tptr (_, Pk_reference) ->
false
| Tint _ | Tfloat _ | Tvoid | Tptr _ ->
true
| _ ->
false
type extras = {formals: FormalMap.t; summary: Summary.t}
module TransferFunctions (CFG : ProcCfg.S) = struct
module CFG = CFG
module Domain = RecordDomain
type nonrec extras = extras
let report_intra access_expr loc summary =
let message =
F.asprintf "The value read from %a was never initialized" HilExp.AccessExpression.pp
access_expr
in
let ltr = [Errlog.make_trace_element 0 loc "" []] in
Reporting.log_error summary ~loc ~ltr IssueType.uninitialized_value message
let is_struct t = match t.Typ.desc with Typ.Tstruct _ -> true | _ -> false
let is_array t = match t.Typ.desc with Typ.Tarray _ -> true | _ -> false
let get_formals pname = Ondemand.get_proc_desc pname |> Option.map ~f:Procdesc.get_formals
let should_report_var pdesc tenv maybe_uninit_vars access_expr =
let base = HilExp.AccessExpression.get_base access_expr in
match (HilExp.AccessExpression.get_typ access_expr tenv, base) with
| Some typ, (Var.ProgramVar pv, _) ->
(not (Pvar.is_frontend_tmp pv))
&& (not (Procdesc.is_captured_pvar pdesc pv))
&& MaybeUninitVars.mem access_expr maybe_uninit_vars
&& should_report_on_type typ
| _, _ ->
false
let nth_formal_param callee_pname idx =
get_formals callee_pname |> Option.bind ~f:(fun formals -> List.nth formals idx)
let function_expects_a_pointer_as_nth_param callee_formals idx =
match List.nth callee_formals idx with Some (_, typ) -> Typ.is_pointer typ | _ -> false
let is_struct_field_passed_by_ref callee_formals t access_expr idx =
is_struct t
&& (not (HilExp.AccessExpression.is_base access_expr))
&& function_expects_a_pointer_as_nth_param callee_formals idx
let is_array_element_passed_by_ref callee_formals t access_expr idx =
is_array t
&& (not (HilExp.AccessExpression.is_base access_expr))
&& function_expects_a_pointer_as_nth_param callee_formals idx
let is_fld_or_array_elem_passed_by_ref t access_expr idx callee_formals =
is_struct_field_passed_by_ref callee_formals t access_expr idx
|| is_array_element_passed_by_ref callee_formals t access_expr idx
let report_on_function_params tenv maybe_uninit_vars actuals loc summary callee_formals_opt =
List.iteri actuals ~f:(fun idx e ->
match HilExp.ignore_cast e with
| HilExp.AccessExpression access_expr ->
let _, t = HilExp.AccessExpression.get_base access_expr in
if
should_report_var (Summary.get_proc_desc summary) tenv maybe_uninit_vars access_expr
&& (not (Typ.is_pointer t))
&& not
(Option.exists callee_formals_opt ~f:(fun callee_formals ->
is_struct_field_passed_by_ref callee_formals t access_expr idx ))
then report_intra access_expr loc summary
| _ ->
() )
let is_dummy_constructor_of_a_struct call =
let is_dummy_constructor_of_struct =
match get_formals call with
| Some [(_, {Typ.desc= Typ.Tptr ({Typ.desc= Tstruct _}, _)})] ->
true
| _ ->
false
in
Procname.is_constructor call && is_dummy_constructor_of_struct
let is_pointer_assignment tenv lhs rhs =
let _, base_typ = HilExp.AccessExpression.get_base lhs in
HilExp.is_null_literal rhs
the rhs has type int when assigning the lhs to null
|| Option.equal Typ.equal (HilExp.AccessExpression.get_typ lhs tenv) (HilExp.get_typ tenv rhs)
&& Typ.is_pointer base_typ
(* checks that the set of initialized formal parameters defined in the precondition of
the function (init_formal_params) contains the (base of) nth formal parameter of the function *)
let init_nth_actual_param callee_pname idx init_formal_params =
match nth_formal_param callee_pname idx with
| None ->
None
| Some (fparam, t) ->
let var_fparam = Var.of_pvar (Pvar.mk fparam callee_pname) in
if
D.exists
(fun access_expr ->
let base = HilExp.AccessExpression.get_base access_expr in
AccessPath.equal_base base (var_fparam, t) )
init_formal_params
then Some var_fparam
else None
let remove_initialized_params summary call maybe_uninit_vars idx access_expr remove_fields =
match Payload.read ~caller_summary:summary ~callee_pname:call with
| Some {pre= init_formals; post= _} -> (
match init_nth_actual_param call idx init_formals with
| Some var_formal ->
let maybe_uninit_vars = MaybeUninitVars.remove access_expr maybe_uninit_vars in
if remove_fields then
let base = HilExp.AccessExpression.get_base access_expr in
let init_formals' = MaybeUninitVars.of_list (D.elements init_formals) in
MaybeUninitVars.remove_init_fields base var_formal maybe_uninit_vars init_formals'
else maybe_uninit_vars
| _ ->
maybe_uninit_vars )
| _ ->
maybe_uninit_vars
(* true if a function initializes at least a param or a field of a struct param *)
let function_initializes_some_formal_params summary call =
match Payload.read ~caller_summary:summary ~callee_pname:call with
| Some {pre= initialized_formal_params; post= _} ->
not (D.is_empty initialized_formal_params)
| _ ->
false
let exec_instr (astate : Domain.t) {ProcData.summary; extras= {formals}; tenv} _
(instr : HilInstr.t) =
let pdesc = Summary.get_proc_desc summary in
let check_access_expr ~loc rhs_access_expr =
if should_report_var pdesc tenv astate.maybe_uninit_vars rhs_access_expr then
report_intra rhs_access_expr loc summary
in
let rec check_hil_expr ~loc = function
| HilExp.Cast (_, e) ->
check_hil_expr ~loc e
| HilExp.AccessExpression access_expr ->
check_access_expr ~loc access_expr
| hil_expr ->
HilExp.get_access_exprs hil_expr
|> List.iter ~f:(fun access_expr -> check_access_expr ~loc access_expr)
in
let update_prepost access_expr rhs =
let lhs_base = HilExp.AccessExpression.get_base access_expr in
if
FormalMap.is_formal lhs_base formals
&& Typ.is_pointer (snd lhs_base)
&& ( (not (is_pointer_assignment tenv access_expr rhs))
|| not (HilExp.AccessExpression.is_base access_expr) )
then
let pre = D.add access_expr astate.prepost.UninitDomain.pre in
{astate.prepost with pre}
else astate.prepost
in
match instr with
| Assign (lhs_access_expr, rhs_expr, loc) ->
(* check on lhs_typ to avoid false positive when assigning a pointer to another *)
( match HilExp.AccessExpression.get_typ lhs_access_expr tenv with
| Some lhs_typ when not (Typ.is_reference lhs_typ) ->
check_hil_expr ~loc rhs_expr
| _ ->
() ) ;
let maybe_uninit_vars = MaybeUninitVars.remove lhs_access_expr astate.maybe_uninit_vars in
let maybe_uninit_vars =
if HilExp.AccessExpression.is_base lhs_access_expr then
(* if we assign to the root of a struct then we need to remove all the fields *)
let lhs_base = HilExp.AccessExpression.get_base lhs_access_expr in
MaybeUninitVars.remove_all_fields tenv lhs_base maybe_uninit_vars
|> MaybeUninitVars.remove_dereference_access lhs_base
else maybe_uninit_vars
in
let prepost = update_prepost lhs_access_expr rhs_expr in
{astate with maybe_uninit_vars; prepost}
| Call (_, Direct callee_pname, _, _, _)
when Procname.equal callee_pname BuiltinDecl.objc_cpp_throw ->
{astate with maybe_uninit_vars= MaybeUninitVars.empty}
| Call (_, HilInstr.Direct call, [HilExp.AccessExpression (AddressOf (Base base))], _, _)
when is_dummy_constructor_of_a_struct call ->
if it 's a default constructor , we use the following heuristic : we assume that it initializes
correctly all fields when there is an implementation of the constructor that initilizes at least one
field . If there is no explicit implementation we can not assume fields are initialized
correctly all fields when there is an implementation of the constructor that initilizes at least one
field. If there is no explicit implementation we cannot assume fields are initialized *)
if function_initializes_some_formal_params summary call then
let maybe_uninit_vars =
in HIL / SIL the default constructor has only one param : the struct
MaybeUninitVars.remove_all_fields tenv base astate.maybe_uninit_vars
in
{astate with maybe_uninit_vars}
else astate
| Call (_, call, actuals, _, loc) ->
(* in case of intraprocedural only analysis we assume that parameters passed by reference
to a function will be initialized inside that function *)
let pname_opt = match call with Direct pname -> Some pname | Indirect _ -> None in
let callee_formals_opt = Option.bind pname_opt ~f:get_formals in
let is_initializing_all_args =
match call with
| Direct pname ->
Models.is_initializing_all_args pname
| Indirect _ ->
false
in
let maybe_uninit_vars =
List.foldi ~init:astate.maybe_uninit_vars actuals ~f:(fun idx acc actual_exp ->
match HilExp.ignore_cast actual_exp with
| HilExp.AccessExpression access_expr -> (
let access_expr_to_remove =
match access_expr with AddressOf ae -> ae | _ -> access_expr
in
match HilExp.AccessExpression.get_base access_expr with
| _, {Typ.desc= Tarray _} when is_initializing_all_args ->
MaybeUninitVars.remove access_expr acc
| _, t
(* Access to a field of a struct or an element of an array by reference *)
when Option.exists callee_formals_opt
~f:(is_fld_or_array_elem_passed_by_ref t access_expr idx) -> (
match pname_opt with
| Some pname when Config.uninit_interproc ->
remove_initialized_params summary pname acc idx access_expr_to_remove false
| _ ->
MaybeUninitVars.remove access_expr_to_remove acc )
| base when Option.exists pname_opt ~f:Procname.is_constructor ->
MaybeUninitVars.remove_all_fields tenv base
(MaybeUninitVars.remove access_expr_to_remove acc)
| _, {Typ.desc= Tptr _} -> (
match pname_opt with
| Some pname when Config.uninit_interproc ->
remove_initialized_params summary pname acc idx access_expr_to_remove true
| _ ->
MaybeUninitVars.remove_everything_under tenv access_expr_to_remove acc )
| _ ->
acc )
| HilExp.Closure (_, apl) ->
(* remove the captured variables of a block/lambda *)
List.fold apl ~init:acc ~f:(fun acc (base, _) ->
MaybeUninitVars.remove (HilExp.AccessExpression.base base) acc )
| _ ->
acc )
in
( match call with
| Direct _ ->
report_on_function_params tenv maybe_uninit_vars actuals loc summary callee_formals_opt
| Indirect _ ->
() ) ;
{astate with maybe_uninit_vars}
| Assume (expr, _, _, loc) ->
check_hil_expr expr ~loc ; astate
| Metadata _ ->
astate
let pp_session_name node fmt = F.fprintf fmt "uninit %a" CFG.Node.pp_id (CFG.Node.id node)
end
module CFG = ProcCfg.Normal
module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG))
module Initial = struct
let get_locals tenv pdesc =
List.fold (Procdesc.get_locals pdesc) ~init:[]
~f:(fun acc (var_data : ProcAttributes.var_data) ->
let pvar = Pvar.mk var_data.name (Procdesc.get_proc_name pdesc) in
let base_access_expr = HilExp.AccessExpression.base (Var.of_pvar pvar, var_data.typ) in
match var_data.typ.Typ.desc with
| Typ.Tstruct qual_name
(* T30105165 remove filtering after we improve union translation *)
when not (Typ.Name.is_union qual_name) -> (
match Tenv.lookup tenv qual_name with
| Some {fields} ->
let flist =
List.fold
~f:(fun acc' (fn, _, _) ->
HilExp.AccessExpression.field_offset base_access_expr fn :: acc' )
~init:acc fields
in
base_access_expr :: flist
for struct we take the struct address , and the access_path
to the fields one level down
to the fields one level down *)
| _ ->
acc )
| Typ.Tarray {elt} ->
HilExp.AccessExpression.array_offset base_access_expr elt None :: acc
| Typ.Tptr _ ->
base_access_expr :: HilExp.AccessExpression.dereference base_access_expr :: acc
| _ ->
base_access_expr :: acc )
end
let checker {Callbacks.exe_env; summary} : Summary.t =
let proc_desc = Summary.get_proc_desc summary in
let proc_name = Summary.get_proc_name summary in
let tenv = Exe_env.get_tenv exe_env proc_name in
start with empty set of uninit local vars and empty set of init formal params
let maybe_uninit_vars = Initial.get_locals tenv proc_desc in
let initial =
{ RecordDomain.maybe_uninit_vars= MaybeUninitVars.of_list maybe_uninit_vars
; aliased_vars= AliasedVars.empty
; prepost= {UninitDomain.pre= D.empty; post= D.empty} }
in
let proc_data =
let formals = FormalMap.make proc_desc in
ProcData.make summary tenv {formals; summary}
in
match Analyzer.compute_post proc_data ~initial with
| Some {RecordDomain.prepost} ->
Payload.update_summary prepost summary
| None ->
summary
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/checkers/uninit.ml | ocaml | * Forward analysis to compute uninitialized variables at each program point
checks that the set of initialized formal parameters defined in the precondition of
the function (init_formal_params) contains the (base of) nth formal parameter of the function
true if a function initializes at least a param or a field of a struct param
check on lhs_typ to avoid false positive when assigning a pointer to another
if we assign to the root of a struct then we need to remove all the fields
in case of intraprocedural only analysis we assume that parameters passed by reference
to a function will be initialized inside that function
Access to a field of a struct or an element of an array by reference
remove the captured variables of a block/lambda
T30105165 remove filtering after we improve union translation |
* 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 F = Format
module D = UninitDomain.Domain
module MaybeUninitVars = UninitDomain.MaybeUninitVars
module AliasedVars = AbstractDomain.FiniteSet (UninitDomain.VarPair)
module RecordDomain = UninitDomain.Record (MaybeUninitVars) (AliasedVars) (D)
module Payload = SummaryPayload.Make (struct
type t = UninitDomain.Summary.t
let field = Payloads.Fields.uninit
end)
module Models = struct
let initializing_all_args = [BuiltinDecl.__set_array_length]
let is_initializing_all_args pname =
List.exists initializing_all_args ~f:(fun fname -> Procname.equal pname fname)
end
let should_report_on_type t =
match t.Typ.desc with
| Tptr (_, Pk_reference) ->
false
| Tint _ | Tfloat _ | Tvoid | Tptr _ ->
true
| _ ->
false
type extras = {formals: FormalMap.t; summary: Summary.t}
module TransferFunctions (CFG : ProcCfg.S) = struct
module CFG = CFG
module Domain = RecordDomain
type nonrec extras = extras
let report_intra access_expr loc summary =
let message =
F.asprintf "The value read from %a was never initialized" HilExp.AccessExpression.pp
access_expr
in
let ltr = [Errlog.make_trace_element 0 loc "" []] in
Reporting.log_error summary ~loc ~ltr IssueType.uninitialized_value message
let is_struct t = match t.Typ.desc with Typ.Tstruct _ -> true | _ -> false
let is_array t = match t.Typ.desc with Typ.Tarray _ -> true | _ -> false
let get_formals pname = Ondemand.get_proc_desc pname |> Option.map ~f:Procdesc.get_formals
let should_report_var pdesc tenv maybe_uninit_vars access_expr =
let base = HilExp.AccessExpression.get_base access_expr in
match (HilExp.AccessExpression.get_typ access_expr tenv, base) with
| Some typ, (Var.ProgramVar pv, _) ->
(not (Pvar.is_frontend_tmp pv))
&& (not (Procdesc.is_captured_pvar pdesc pv))
&& MaybeUninitVars.mem access_expr maybe_uninit_vars
&& should_report_on_type typ
| _, _ ->
false
let nth_formal_param callee_pname idx =
get_formals callee_pname |> Option.bind ~f:(fun formals -> List.nth formals idx)
let function_expects_a_pointer_as_nth_param callee_formals idx =
match List.nth callee_formals idx with Some (_, typ) -> Typ.is_pointer typ | _ -> false
let is_struct_field_passed_by_ref callee_formals t access_expr idx =
is_struct t
&& (not (HilExp.AccessExpression.is_base access_expr))
&& function_expects_a_pointer_as_nth_param callee_formals idx
let is_array_element_passed_by_ref callee_formals t access_expr idx =
is_array t
&& (not (HilExp.AccessExpression.is_base access_expr))
&& function_expects_a_pointer_as_nth_param callee_formals idx
let is_fld_or_array_elem_passed_by_ref t access_expr idx callee_formals =
is_struct_field_passed_by_ref callee_formals t access_expr idx
|| is_array_element_passed_by_ref callee_formals t access_expr idx
let report_on_function_params tenv maybe_uninit_vars actuals loc summary callee_formals_opt =
List.iteri actuals ~f:(fun idx e ->
match HilExp.ignore_cast e with
| HilExp.AccessExpression access_expr ->
let _, t = HilExp.AccessExpression.get_base access_expr in
if
should_report_var (Summary.get_proc_desc summary) tenv maybe_uninit_vars access_expr
&& (not (Typ.is_pointer t))
&& not
(Option.exists callee_formals_opt ~f:(fun callee_formals ->
is_struct_field_passed_by_ref callee_formals t access_expr idx ))
then report_intra access_expr loc summary
| _ ->
() )
let is_dummy_constructor_of_a_struct call =
let is_dummy_constructor_of_struct =
match get_formals call with
| Some [(_, {Typ.desc= Typ.Tptr ({Typ.desc= Tstruct _}, _)})] ->
true
| _ ->
false
in
Procname.is_constructor call && is_dummy_constructor_of_struct
let is_pointer_assignment tenv lhs rhs =
let _, base_typ = HilExp.AccessExpression.get_base lhs in
HilExp.is_null_literal rhs
the rhs has type int when assigning the lhs to null
|| Option.equal Typ.equal (HilExp.AccessExpression.get_typ lhs tenv) (HilExp.get_typ tenv rhs)
&& Typ.is_pointer base_typ
let init_nth_actual_param callee_pname idx init_formal_params =
match nth_formal_param callee_pname idx with
| None ->
None
| Some (fparam, t) ->
let var_fparam = Var.of_pvar (Pvar.mk fparam callee_pname) in
if
D.exists
(fun access_expr ->
let base = HilExp.AccessExpression.get_base access_expr in
AccessPath.equal_base base (var_fparam, t) )
init_formal_params
then Some var_fparam
else None
let remove_initialized_params summary call maybe_uninit_vars idx access_expr remove_fields =
match Payload.read ~caller_summary:summary ~callee_pname:call with
| Some {pre= init_formals; post= _} -> (
match init_nth_actual_param call idx init_formals with
| Some var_formal ->
let maybe_uninit_vars = MaybeUninitVars.remove access_expr maybe_uninit_vars in
if remove_fields then
let base = HilExp.AccessExpression.get_base access_expr in
let init_formals' = MaybeUninitVars.of_list (D.elements init_formals) in
MaybeUninitVars.remove_init_fields base var_formal maybe_uninit_vars init_formals'
else maybe_uninit_vars
| _ ->
maybe_uninit_vars )
| _ ->
maybe_uninit_vars
let function_initializes_some_formal_params summary call =
match Payload.read ~caller_summary:summary ~callee_pname:call with
| Some {pre= initialized_formal_params; post= _} ->
not (D.is_empty initialized_formal_params)
| _ ->
false
let exec_instr (astate : Domain.t) {ProcData.summary; extras= {formals}; tenv} _
(instr : HilInstr.t) =
let pdesc = Summary.get_proc_desc summary in
let check_access_expr ~loc rhs_access_expr =
if should_report_var pdesc tenv astate.maybe_uninit_vars rhs_access_expr then
report_intra rhs_access_expr loc summary
in
let rec check_hil_expr ~loc = function
| HilExp.Cast (_, e) ->
check_hil_expr ~loc e
| HilExp.AccessExpression access_expr ->
check_access_expr ~loc access_expr
| hil_expr ->
HilExp.get_access_exprs hil_expr
|> List.iter ~f:(fun access_expr -> check_access_expr ~loc access_expr)
in
let update_prepost access_expr rhs =
let lhs_base = HilExp.AccessExpression.get_base access_expr in
if
FormalMap.is_formal lhs_base formals
&& Typ.is_pointer (snd lhs_base)
&& ( (not (is_pointer_assignment tenv access_expr rhs))
|| not (HilExp.AccessExpression.is_base access_expr) )
then
let pre = D.add access_expr astate.prepost.UninitDomain.pre in
{astate.prepost with pre}
else astate.prepost
in
match instr with
| Assign (lhs_access_expr, rhs_expr, loc) ->
( match HilExp.AccessExpression.get_typ lhs_access_expr tenv with
| Some lhs_typ when not (Typ.is_reference lhs_typ) ->
check_hil_expr ~loc rhs_expr
| _ ->
() ) ;
let maybe_uninit_vars = MaybeUninitVars.remove lhs_access_expr astate.maybe_uninit_vars in
let maybe_uninit_vars =
if HilExp.AccessExpression.is_base lhs_access_expr then
let lhs_base = HilExp.AccessExpression.get_base lhs_access_expr in
MaybeUninitVars.remove_all_fields tenv lhs_base maybe_uninit_vars
|> MaybeUninitVars.remove_dereference_access lhs_base
else maybe_uninit_vars
in
let prepost = update_prepost lhs_access_expr rhs_expr in
{astate with maybe_uninit_vars; prepost}
| Call (_, Direct callee_pname, _, _, _)
when Procname.equal callee_pname BuiltinDecl.objc_cpp_throw ->
{astate with maybe_uninit_vars= MaybeUninitVars.empty}
| Call (_, HilInstr.Direct call, [HilExp.AccessExpression (AddressOf (Base base))], _, _)
when is_dummy_constructor_of_a_struct call ->
if it 's a default constructor , we use the following heuristic : we assume that it initializes
correctly all fields when there is an implementation of the constructor that initilizes at least one
field . If there is no explicit implementation we can not assume fields are initialized
correctly all fields when there is an implementation of the constructor that initilizes at least one
field. If there is no explicit implementation we cannot assume fields are initialized *)
if function_initializes_some_formal_params summary call then
let maybe_uninit_vars =
in HIL / SIL the default constructor has only one param : the struct
MaybeUninitVars.remove_all_fields tenv base astate.maybe_uninit_vars
in
{astate with maybe_uninit_vars}
else astate
| Call (_, call, actuals, _, loc) ->
let pname_opt = match call with Direct pname -> Some pname | Indirect _ -> None in
let callee_formals_opt = Option.bind pname_opt ~f:get_formals in
let is_initializing_all_args =
match call with
| Direct pname ->
Models.is_initializing_all_args pname
| Indirect _ ->
false
in
let maybe_uninit_vars =
List.foldi ~init:astate.maybe_uninit_vars actuals ~f:(fun idx acc actual_exp ->
match HilExp.ignore_cast actual_exp with
| HilExp.AccessExpression access_expr -> (
let access_expr_to_remove =
match access_expr with AddressOf ae -> ae | _ -> access_expr
in
match HilExp.AccessExpression.get_base access_expr with
| _, {Typ.desc= Tarray _} when is_initializing_all_args ->
MaybeUninitVars.remove access_expr acc
| _, t
when Option.exists callee_formals_opt
~f:(is_fld_or_array_elem_passed_by_ref t access_expr idx) -> (
match pname_opt with
| Some pname when Config.uninit_interproc ->
remove_initialized_params summary pname acc idx access_expr_to_remove false
| _ ->
MaybeUninitVars.remove access_expr_to_remove acc )
| base when Option.exists pname_opt ~f:Procname.is_constructor ->
MaybeUninitVars.remove_all_fields tenv base
(MaybeUninitVars.remove access_expr_to_remove acc)
| _, {Typ.desc= Tptr _} -> (
match pname_opt with
| Some pname when Config.uninit_interproc ->
remove_initialized_params summary pname acc idx access_expr_to_remove true
| _ ->
MaybeUninitVars.remove_everything_under tenv access_expr_to_remove acc )
| _ ->
acc )
| HilExp.Closure (_, apl) ->
List.fold apl ~init:acc ~f:(fun acc (base, _) ->
MaybeUninitVars.remove (HilExp.AccessExpression.base base) acc )
| _ ->
acc )
in
( match call with
| Direct _ ->
report_on_function_params tenv maybe_uninit_vars actuals loc summary callee_formals_opt
| Indirect _ ->
() ) ;
{astate with maybe_uninit_vars}
| Assume (expr, _, _, loc) ->
check_hil_expr expr ~loc ; astate
| Metadata _ ->
astate
let pp_session_name node fmt = F.fprintf fmt "uninit %a" CFG.Node.pp_id (CFG.Node.id node)
end
module CFG = ProcCfg.Normal
module Analyzer = LowerHil.MakeAbstractInterpreter (TransferFunctions (CFG))
module Initial = struct
let get_locals tenv pdesc =
List.fold (Procdesc.get_locals pdesc) ~init:[]
~f:(fun acc (var_data : ProcAttributes.var_data) ->
let pvar = Pvar.mk var_data.name (Procdesc.get_proc_name pdesc) in
let base_access_expr = HilExp.AccessExpression.base (Var.of_pvar pvar, var_data.typ) in
match var_data.typ.Typ.desc with
| Typ.Tstruct qual_name
when not (Typ.Name.is_union qual_name) -> (
match Tenv.lookup tenv qual_name with
| Some {fields} ->
let flist =
List.fold
~f:(fun acc' (fn, _, _) ->
HilExp.AccessExpression.field_offset base_access_expr fn :: acc' )
~init:acc fields
in
base_access_expr :: flist
for struct we take the struct address , and the access_path
to the fields one level down
to the fields one level down *)
| _ ->
acc )
| Typ.Tarray {elt} ->
HilExp.AccessExpression.array_offset base_access_expr elt None :: acc
| Typ.Tptr _ ->
base_access_expr :: HilExp.AccessExpression.dereference base_access_expr :: acc
| _ ->
base_access_expr :: acc )
end
let checker {Callbacks.exe_env; summary} : Summary.t =
let proc_desc = Summary.get_proc_desc summary in
let proc_name = Summary.get_proc_name summary in
let tenv = Exe_env.get_tenv exe_env proc_name in
start with empty set of uninit local vars and empty set of init formal params
let maybe_uninit_vars = Initial.get_locals tenv proc_desc in
let initial =
{ RecordDomain.maybe_uninit_vars= MaybeUninitVars.of_list maybe_uninit_vars
; aliased_vars= AliasedVars.empty
; prepost= {UninitDomain.pre= D.empty; post= D.empty} }
in
let proc_data =
let formals = FormalMap.make proc_desc in
ProcData.make summary tenv {formals; summary}
in
match Analyzer.compute_post proc_data ~initial with
| Some {RecordDomain.prepost} ->
Payload.update_summary prepost summary
| None ->
summary
|
d67f4d8377cd3fee02ccf705646a52a384ec54da2f67a6318efb4b1b3f45eb20 | hiredman/raft | raft.clj | (ns com.manigfeald.raft
"runs the raft algorithm one step at a time."
(:require [com.manigfeald.raft.core :refer :all]
[com.manigfeald.raft.rules :refer [rules-of-raft]])
(:import (clojure.lang PersistentQueue)))
;; TODO: why do the tests still need with-pings with leaders sending noops?
;; TODO: document message formats
;; defrecords mainly just to document the expected fields
(defrecord RaftLeaderState [next-index match-index])
(defrecord RaftState [current-term voted-for log commit-index last-applied
node-type value votes leader-id node-set])
(defrecord IO [message out-queue])
(defrecord Timer [now next-timeout period])
(defrecord ImplementationState [io raft-state raft-leader-state id running-log
timer])
(alter-meta! #'map->RaftLeaderState assoc :no-doc true)
(alter-meta! #'map->RaftState assoc :no-doc true)
(alter-meta! #'map->IO assoc :no-doc true)
(alter-meta! #'map->Timer assoc :no-doc true)
(alter-meta! #'map->ImplementationState assoc :no-doc true)
(alter-meta! #'->RaftLeaderState assoc :no-doc true)
(alter-meta! #'->RaftState assoc :no-doc true)
(alter-meta! #'->IO assoc :no-doc true)
(alter-meta! #'->Timer assoc :no-doc true)
(alter-meta! #'->ImplementationState assoc :no-doc true)
(defn raft
"return an init state when given a node id and a node-set, id is the
id of the node this state represents, node-set is a set of the ids
of other nodes in the cluster"
[id node-set timer]
(->ImplementationState
(->IO nil PersistentQueue/EMPTY)
(->RaftState 0N
nil
(empty-log)
0N
0N
:follower
(->MapValue)
0N
nil
(set node-set))
(->RaftLeaderState {} {})
id
PersistentQueue/EMPTY
timer))
(defn run-one
"given a state, advance it to the next state"
[raft-state]
{:post [(not (seq (for [message (:out-queue (:io %))
:when (= (:type message) :request-vote-response)
:when (:success? message)
:when (not= (:voted-for (:raft-state %))
(:target message))]
message)))
(or (zero? (:last-applied (:raft-state %)))
(contains? (log-entry-of (:raft-state %)
(:last-applied (:raft-state %)))
:return))]}
(let [[applied? new-state] (rules-of-raft raft-state)
r (as-> new-state new-state
(cond-> new-state
(and (not (zero? (:last-applied
(:raft-state new-state))))
(not (contains? (log-entry-of
(:raft-state new-state)
(:last-applied
(:raft-state new-state)))
:return)))
((fn [x]
(locking #'*out*
(prn x))
x))
(not= (:node-type (:raft-state new-state))
(:node-type (:raft-state raft-state)))
(log-trace
(:node-type (:raft-state raft-state))
"=>"
(:node-type (:raft-state new-state))
(:run-count new-state))
( not= (: votes (: raft - state new - state ) )
;; (:votes (:raft-state raft-state)))
;; (log-trace "votes"
;; (:votes (:raft-state new-state))
;; (:run-count new-state))
(not= (:current-term (:raft-state new-state))
(:current-term (:raft-state raft-state)))
(log-trace "current-term"
(:current-term (:raft-state new-state))
(:run-count new-state))
(not= (:commit-index (:raft-state new-state))
(:commit-index (:raft-state raft-state)))
(log-trace "commit index"
(:commit-index (:raft-state new-state))
(:run-count new-state)))
(update-in new-state [:run-count] (fnil inc 0N)))]
(assert (not (seq (for [message (:out-queue (:io r))
:when (= (:type message) :request-vote-response)
:when (:success? message)
:when (not= (:voted-for (:raft-state r))
(:target message))]
message)))
(pr-str
(update-in r [:io :out-queue] seq)))
r))
| null | https://raw.githubusercontent.com/hiredman/raft/6e0575dd8a25b131281c6ebb212b86b0d984c416/src/com/manigfeald/raft.clj | clojure | TODO: why do the tests still need with-pings with leaders sending noops?
TODO: document message formats
defrecords mainly just to document the expected fields
(:votes (:raft-state raft-state)))
(log-trace "votes"
(:votes (:raft-state new-state))
(:run-count new-state)) | (ns com.manigfeald.raft
"runs the raft algorithm one step at a time."
(:require [com.manigfeald.raft.core :refer :all]
[com.manigfeald.raft.rules :refer [rules-of-raft]])
(:import (clojure.lang PersistentQueue)))
(defrecord RaftLeaderState [next-index match-index])
(defrecord RaftState [current-term voted-for log commit-index last-applied
node-type value votes leader-id node-set])
(defrecord IO [message out-queue])
(defrecord Timer [now next-timeout period])
(defrecord ImplementationState [io raft-state raft-leader-state id running-log
timer])
(alter-meta! #'map->RaftLeaderState assoc :no-doc true)
(alter-meta! #'map->RaftState assoc :no-doc true)
(alter-meta! #'map->IO assoc :no-doc true)
(alter-meta! #'map->Timer assoc :no-doc true)
(alter-meta! #'map->ImplementationState assoc :no-doc true)
(alter-meta! #'->RaftLeaderState assoc :no-doc true)
(alter-meta! #'->RaftState assoc :no-doc true)
(alter-meta! #'->IO assoc :no-doc true)
(alter-meta! #'->Timer assoc :no-doc true)
(alter-meta! #'->ImplementationState assoc :no-doc true)
(defn raft
"return an init state when given a node id and a node-set, id is the
id of the node this state represents, node-set is a set of the ids
of other nodes in the cluster"
[id node-set timer]
(->ImplementationState
(->IO nil PersistentQueue/EMPTY)
(->RaftState 0N
nil
(empty-log)
0N
0N
:follower
(->MapValue)
0N
nil
(set node-set))
(->RaftLeaderState {} {})
id
PersistentQueue/EMPTY
timer))
(defn run-one
"given a state, advance it to the next state"
[raft-state]
{:post [(not (seq (for [message (:out-queue (:io %))
:when (= (:type message) :request-vote-response)
:when (:success? message)
:when (not= (:voted-for (:raft-state %))
(:target message))]
message)))
(or (zero? (:last-applied (:raft-state %)))
(contains? (log-entry-of (:raft-state %)
(:last-applied (:raft-state %)))
:return))]}
(let [[applied? new-state] (rules-of-raft raft-state)
r (as-> new-state new-state
(cond-> new-state
(and (not (zero? (:last-applied
(:raft-state new-state))))
(not (contains? (log-entry-of
(:raft-state new-state)
(:last-applied
(:raft-state new-state)))
:return)))
((fn [x]
(locking #'*out*
(prn x))
x))
(not= (:node-type (:raft-state new-state))
(:node-type (:raft-state raft-state)))
(log-trace
(:node-type (:raft-state raft-state))
"=>"
(:node-type (:raft-state new-state))
(:run-count new-state))
( not= (: votes (: raft - state new - state ) )
(not= (:current-term (:raft-state new-state))
(:current-term (:raft-state raft-state)))
(log-trace "current-term"
(:current-term (:raft-state new-state))
(:run-count new-state))
(not= (:commit-index (:raft-state new-state))
(:commit-index (:raft-state raft-state)))
(log-trace "commit index"
(:commit-index (:raft-state new-state))
(:run-count new-state)))
(update-in new-state [:run-count] (fnil inc 0N)))]
(assert (not (seq (for [message (:out-queue (:io r))
:when (= (:type message) :request-vote-response)
:when (:success? message)
:when (not= (:voted-for (:raft-state r))
(:target message))]
message)))
(pr-str
(update-in r [:io :out-queue] seq)))
r))
|
6af4ed0dfaeed2faf09d98de148d61174f882f5b197f954bdbb3a5d4b5b450f6 | RunOrg/RunOrg | form.ml | (* © 2014 RunOrg *)
module I = FormLib.I
module FilledI = FormLib.FilledI
module Owner = FormLib.Owner
module Access = FormLib.FormAccess
module Stats = FormLib.Stats
include FormLib.Commands
include FormLib.Queries
| null | https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/form.ml | ocaml | © 2014 RunOrg |
module I = FormLib.I
module FilledI = FormLib.FilledI
module Owner = FormLib.Owner
module Access = FormLib.FormAccess
module Stats = FormLib.Stats
include FormLib.Commands
include FormLib.Queries
|
969dca0c0bea202983c5277c4dabcf43031ec9eb64373237ae94e1bd473b3a28 | nasa/Common-Metadata-Repository | root.clj | (ns ^:integration cmr.opendap.tests.integration.app.root
"Note: this namespace is exclusively for integration tests; all tests defined
here will use one or more integration test fixtures.
Warning: To run the integration tests, you will need to create CMR/ECHO
tokens and export these as shell environment variables. In particular, each
token gets its own ENV var:
* CMR_SIT_TOKEN
* CMR_UAT_TOKEN
* CMR_PROD_TOKEN
Definition used for integration tests:
* #Integration_testing"
(:require
[cheshire.core :as json]
[clojure.test :refer :all]
[cmr.opendap.testing.system :as test-system]
[org.httpkit.client :as httpc])
(:import
(clojure.lang ExceptionInfo)))
(use-fixtures :once test-system/with-system)
(deftest root-route
(testing "root route ..."
(let [response @(httpc/get (format ":%s/service-bridge"
(test-system/http-port)))]
(is (= 200 (:status response))))
(let [response @(httpc/head (format ":%s/service-bridge"
(test-system/http-port)))]
(is (= 200 (:status response)))))
(testing "root route with trailing slash ..."
(let [response @(httpc/get (format ":%s/service-bridge/"
(test-system/http-port)))]
(is (= 200 (:status response))))
(let [response @(httpc/head (format ":%s/service-bridge/"
(test-system/http-port)))]
(is (= 200 (:status response))))))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/service-bridge/test/cmr/opendap/tests/integration/app/root.clj | clojure | all tests defined | (ns ^:integration cmr.opendap.tests.integration.app.root
here will use one or more integration test fixtures.
Warning: To run the integration tests, you will need to create CMR/ECHO
tokens and export these as shell environment variables. In particular, each
token gets its own ENV var:
* CMR_SIT_TOKEN
* CMR_UAT_TOKEN
* CMR_PROD_TOKEN
Definition used for integration tests:
* #Integration_testing"
(:require
[cheshire.core :as json]
[clojure.test :refer :all]
[cmr.opendap.testing.system :as test-system]
[org.httpkit.client :as httpc])
(:import
(clojure.lang ExceptionInfo)))
(use-fixtures :once test-system/with-system)
(deftest root-route
(testing "root route ..."
(let [response @(httpc/get (format ":%s/service-bridge"
(test-system/http-port)))]
(is (= 200 (:status response))))
(let [response @(httpc/head (format ":%s/service-bridge"
(test-system/http-port)))]
(is (= 200 (:status response)))))
(testing "root route with trailing slash ..."
(let [response @(httpc/get (format ":%s/service-bridge/"
(test-system/http-port)))]
(is (= 200 (:status response))))
(let [response @(httpc/head (format ":%s/service-bridge/"
(test-system/http-port)))]
(is (= 200 (:status response))))))
|
fd1be468282d42589abfccdfd22832f056e7d4a7562cfaeb2b2058e6a2306863 | zachallaun/datomic-cljs | friends.cljs | (ns datomic-cljs.examples.friends
(:require [datomic-cljs.api :as d]
[cljs.core.async :as async :refer [<! >!]]
[cljs.nodejs :as nodejs])
(:require-macros [cljs.core.async.macros :refer [go]]
[datomic-cljs.macros :refer [<?]]))
(def js-fs (nodejs/require "fs"))
(def friend-schema (.readFileSync js-fs "resources/friend_schema.edn" "utf8"))
(def friend-data (.readFileSync js-fs "resources/friend_data.edn" "utf8"))
(defn -main [& args]
(go
Create and connect to a new Datomic database .
(let [conn (<? (d/create-database "localhost" 9898 "db" "friends"))]
;; Transact our schema and seed data.
(<? (d/transact conn friend-schema))
(<? (d/transact conn friend-data))
Find 's entity i d.
(let [caroll-eid (ffirst (<? (d/q '[:find ?e :where [?e :person/name "Caroll"]]
(d/db conn))))]
;; Using her entity id, get her entity map, and use that to
;; see all her friends.
(println (-> (<? (d/entity (d/db conn) caroll-eid))
:person/friends)))
wants to start going by .
(let [frank-eid (ffirst (<? (d/q '[:find ?e :where [?e :person/name "Frank"]]
(d/db conn))))
tx-data (<? (d/transact conn [[:db/add frank-eid :person/name "Franky"]]))
{{before-t :basis-t} :db-before} tx-data]
But we know he used to just be .
(println (<? (d/q '[:find ?n :in $ ?e :where [?e :person/name ?n]]
(d/as-of (d/db conn) before-t)
frank-eid)))))))
(set! *main-cli-fn* -main)
| null | https://raw.githubusercontent.com/zachallaun/datomic-cljs/a2accf1d999b7d6a554a9322f52b230eae1b58b3/examples/friends.cljs | clojure | Transact our schema and seed data.
Using her entity id, get her entity map, and use that to
see all her friends. | (ns datomic-cljs.examples.friends
(:require [datomic-cljs.api :as d]
[cljs.core.async :as async :refer [<! >!]]
[cljs.nodejs :as nodejs])
(:require-macros [cljs.core.async.macros :refer [go]]
[datomic-cljs.macros :refer [<?]]))
(def js-fs (nodejs/require "fs"))
(def friend-schema (.readFileSync js-fs "resources/friend_schema.edn" "utf8"))
(def friend-data (.readFileSync js-fs "resources/friend_data.edn" "utf8"))
(defn -main [& args]
(go
Create and connect to a new Datomic database .
(let [conn (<? (d/create-database "localhost" 9898 "db" "friends"))]
(<? (d/transact conn friend-schema))
(<? (d/transact conn friend-data))
Find 's entity i d.
(let [caroll-eid (ffirst (<? (d/q '[:find ?e :where [?e :person/name "Caroll"]]
(d/db conn))))]
(println (-> (<? (d/entity (d/db conn) caroll-eid))
:person/friends)))
wants to start going by .
(let [frank-eid (ffirst (<? (d/q '[:find ?e :where [?e :person/name "Frank"]]
(d/db conn))))
tx-data (<? (d/transact conn [[:db/add frank-eid :person/name "Franky"]]))
{{before-t :basis-t} :db-before} tx-data]
But we know he used to just be .
(println (<? (d/q '[:find ?n :in $ ?e :where [?e :person/name ?n]]
(d/as-of (d/db conn) before-t)
frank-eid)))))))
(set! *main-cli-fn* -main)
|
3315c4d794102ea4c6ca20ccdcf7b772438f3882cdbf9657040cdd7fae07c23f | RichiH/git-annex | QuickCheck.hs | QuickCheck with additional instances
-
- Copyright 2012 - 2014 < >
-
- License : BSD-2 - clause
-
- Copyright 2012-2014 Joey Hess <>
-
- License: BSD-2-clause
-}
# OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE TypeSynonymInstances , CPP #
module Utility.QuickCheck
( module X
, module Utility.QuickCheck
) where
import Test.QuickCheck as X
import Data.Time.Clock.POSIX
import System.Posix.Types
#if ! MIN_VERSION_QuickCheck(2,8,2)
import qualified Data.Map as M
import qualified Data.Set as S
#endif
import Control.Applicative
import Prelude
#if ! MIN_VERSION_QuickCheck(2,8,2)
instance (Arbitrary k, Arbitrary v, Ord k) => Arbitrary (M.Map k v) where
arbitrary = M.fromList <$> arbitrary
instance (Arbitrary v, Ord v) => Arbitrary (S.Set v) where
arbitrary = S.fromList <$> arbitrary
#endif
Times before the epoch are excluded .
instance Arbitrary POSIXTime where
arbitrary = fromInteger <$> nonNegative arbitrarySizedIntegral
{- Pids are never negative, or 0. -}
instance Arbitrary ProcessID where
arbitrary = arbitrarySizedBoundedIntegral `suchThat` (> 0)
Inodes are never negative .
instance Arbitrary FileID where
arbitrary = nonNegative arbitrarySizedIntegral
{- File sizes are never negative. -}
instance Arbitrary FileOffset where
arbitrary = nonNegative arbitrarySizedIntegral
nonNegative :: (Num a, Ord a) => Gen a -> Gen a
nonNegative g = g `suchThat` (>= 0)
positive :: (Num a, Ord a) => Gen a -> Gen a
positive g = g `suchThat` (> 0)
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Utility/QuickCheck.hs | haskell | Pids are never negative, or 0.
File sizes are never negative. | QuickCheck with additional instances
-
- Copyright 2012 - 2014 < >
-
- License : BSD-2 - clause
-
- Copyright 2012-2014 Joey Hess <>
-
- License: BSD-2-clause
-}
# OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE TypeSynonymInstances , CPP #
module Utility.QuickCheck
( module X
, module Utility.QuickCheck
) where
import Test.QuickCheck as X
import Data.Time.Clock.POSIX
import System.Posix.Types
#if ! MIN_VERSION_QuickCheck(2,8,2)
import qualified Data.Map as M
import qualified Data.Set as S
#endif
import Control.Applicative
import Prelude
#if ! MIN_VERSION_QuickCheck(2,8,2)
instance (Arbitrary k, Arbitrary v, Ord k) => Arbitrary (M.Map k v) where
arbitrary = M.fromList <$> arbitrary
instance (Arbitrary v, Ord v) => Arbitrary (S.Set v) where
arbitrary = S.fromList <$> arbitrary
#endif
Times before the epoch are excluded .
instance Arbitrary POSIXTime where
arbitrary = fromInteger <$> nonNegative arbitrarySizedIntegral
instance Arbitrary ProcessID where
arbitrary = arbitrarySizedBoundedIntegral `suchThat` (> 0)
Inodes are never negative .
instance Arbitrary FileID where
arbitrary = nonNegative arbitrarySizedIntegral
instance Arbitrary FileOffset where
arbitrary = nonNegative arbitrarySizedIntegral
nonNegative :: (Num a, Ord a) => Gen a -> Gen a
nonNegative g = g `suchThat` (>= 0)
positive :: (Num a, Ord a) => Gen a -> Gen a
positive g = g `suchThat` (> 0)
|
b2787f3422b56581c561191d6f060d1f85c65b166cace9d53bf444b4ebf48548 | re-ops/re-core | provider.clj | (ns re-core.test.provider
(:require
[re-core.provider :refer (mappings)])
(:use clojure.test))
(deftest mappings-sanity
(is (= (mappings {:os :ubuntu :domain "local"} {:os #{:template :flavor} :domain :search})
{:template :ubuntu :flavor :ubuntu :search "local"})))
| null | https://raw.githubusercontent.com/re-ops/re-core/93596efd4f3068d57e8140106da60011a6569310/test/re_core/test/provider.clj | clojure | (ns re-core.test.provider
(:require
[re-core.provider :refer (mappings)])
(:use clojure.test))
(deftest mappings-sanity
(is (= (mappings {:os :ubuntu :domain "local"} {:os #{:template :flavor} :domain :search})
{:template :ubuntu :flavor :ubuntu :search "local"})))
| |
4232c7c28ead4290cc24a42c0c169ade9da4552bfc59036e34c01d4ae3f42a4f | sgbj/MaximaSharp | zungqr.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :lapack)
(let* ((zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) zero) (ignorable zero))
(defun zungqr (m n k a lda tau work lwork info)
(declare (type (array f2cl-lib:complex16 (*)) work tau a)
(type (f2cl-lib:integer4) info lwork lda k n m))
(f2cl-lib:with-multi-array-data
((a f2cl-lib:complex16 a-%data% a-%offset%)
(tau f2cl-lib:complex16 tau-%data% tau-%offset%)
(work f2cl-lib:complex16 work-%data% work-%offset%))
(prog ((i 0) (ib 0) (iinfo 0) (iws 0) (j 0) (ki 0) (kk 0) (l 0)
(ldwork 0) (lwkopt 0) (nb 0) (nbmin 0) (nx 0) (lquery nil))
(declare (type (f2cl-lib:integer4) i ib iinfo iws j ki kk l ldwork
lwkopt nb nbmin nx)
(type f2cl-lib:logical lquery))
(setf info 0)
(setf nb (ilaenv 1 "ZUNGQR" " " m n k -1))
(setf lwkopt
(f2cl-lib:int-mul
(max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 n))
nb))
(setf (f2cl-lib:fref work-%data% (1) ((1 *)) work-%offset%)
(coerce lwkopt 'f2cl-lib:complex16))
(setf lquery (coerce (= lwork -1) 'f2cl-lib:logical))
(cond
((< m 0)
(setf info -1))
((or (< n 0) (> n m))
(setf info -2))
((or (< k 0) (> k n))
(setf info -3))
((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info -5))
((and
(< lwork (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 n)))
(not lquery))
(setf info -8)))
(cond
((/= info 0)
(xerbla "ZUNGQR" (f2cl-lib:int-sub info))
(go end_label))
(lquery
(go end_label)))
(cond
((<= n 0)
(setf (f2cl-lib:fref work-%data% (1) ((1 *)) work-%offset%)
(coerce 1 'f2cl-lib:complex16))
(go end_label)))
(setf nbmin 2)
(setf nx 0)
(setf iws n)
(cond
((and (> nb 1) (< nb k))
(setf nx
(max (the f2cl-lib:integer4 0)
(the f2cl-lib:integer4
(ilaenv 3 "ZUNGQR" " " m n k -1))))
(cond
((< nx k)
(setf ldwork n)
(setf iws (f2cl-lib:int-mul ldwork nb))
(cond
((< lwork iws)
(setf nb (the f2cl-lib:integer4 (truncate lwork ldwork)))
(setf nbmin
(max (the f2cl-lib:integer4 2)
(the f2cl-lib:integer4
(ilaenv 2 "ZUNGQR" " " m n k -1))))))))))
(cond
((and (>= nb nbmin) (< nb k) (< nx k))
(setf ki (* (the f2cl-lib:integer4 (truncate (- k nx 1) nb)) nb))
(setf kk
(min (the f2cl-lib:integer4 k)
(the f2cl-lib:integer4 (f2cl-lib:int-add ki nb))))
(f2cl-lib:fdo (j (f2cl-lib:int-add kk 1) (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i kk) nil)
(tagbody
(setf (f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%)
zero)
label10))
label20)))
(t
(setf kk 0)))
(if (< kk n)
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(zung2r (f2cl-lib:int-sub m kk) (f2cl-lib:int-sub n kk)
(f2cl-lib:int-sub k kk)
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
((+ kk 1) (f2cl-lib:int-add kk 1))
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice tau-%data%
f2cl-lib:complex16
((+ kk 1))
((1 *))
tau-%offset%)
work iinfo)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6))
(setf iinfo var-7)))
(cond
((> kk 0)
(f2cl-lib:fdo (i (f2cl-lib:int-add ki 1)
(f2cl-lib:int-add i (f2cl-lib:int-sub nb)))
((> i 1) nil)
(tagbody
(setf ib
(min (the f2cl-lib:integer4 nb)
(the f2cl-lib:integer4
(f2cl-lib:int-add (f2cl-lib:int-sub k i) 1))))
(cond
((<= (f2cl-lib:int-add i ib) n)
(zlarft "Forward" "Columnwise"
(f2cl-lib:int-add (f2cl-lib:int-sub m i) 1) ib
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i i)
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice tau-%data%
f2cl-lib:complex16
(i)
((1 *))
tau-%offset%)
work ldwork)
(zlarfb "Left" "No transpose" "Forward" "Columnwise"
(f2cl-lib:int-add (f2cl-lib:int-sub m i) 1)
(f2cl-lib:int-add (f2cl-lib:int-sub n i ib) 1) ib
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i i)
((1 lda) (1 *))
a-%offset%)
lda work ldwork
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i (f2cl-lib:int-add i ib))
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice work-%data%
f2cl-lib:complex16
((+ ib 1))
((1 *))
work-%offset%)
ldwork)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(zung2r (f2cl-lib:int-add (f2cl-lib:int-sub m i) 1) ib ib
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i i)
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice tau-%data%
f2cl-lib:complex16
(i)
((1 *))
tau-%offset%)
work iinfo)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6))
(setf iinfo var-7))
(f2cl-lib:fdo (j i (f2cl-lib:int-add j 1))
((> j
(f2cl-lib:int-add i ib (f2cl-lib:int-sub 1)))
nil)
(tagbody
(f2cl-lib:fdo (l 1 (f2cl-lib:int-add l 1))
((> l
(f2cl-lib:int-add i (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref a-%data%
(l j)
((1 lda) (1 *))
a-%offset%)
zero)
label30))
label40))
label50))))
(setf (f2cl-lib:fref work-%data% (1) ((1 *)) work-%offset%)
(coerce iws 'f2cl-lib:complex16))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil info))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zungqr
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil
fortran-to-lisp::info)
:calls '(fortran-to-lisp::zlarfb fortran-to-lisp::zlarft
fortran-to-lisp::zung2r fortran-to-lisp::xerbla
fortran-to-lisp::ilaenv))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/lapack/zungqr.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :lapack)
(let* ((zero (f2cl-lib:cmplx 0.0 0.0)))
(declare (type (f2cl-lib:complex16) zero) (ignorable zero))
(defun zungqr (m n k a lda tau work lwork info)
(declare (type (array f2cl-lib:complex16 (*)) work tau a)
(type (f2cl-lib:integer4) info lwork lda k n m))
(f2cl-lib:with-multi-array-data
((a f2cl-lib:complex16 a-%data% a-%offset%)
(tau f2cl-lib:complex16 tau-%data% tau-%offset%)
(work f2cl-lib:complex16 work-%data% work-%offset%))
(prog ((i 0) (ib 0) (iinfo 0) (iws 0) (j 0) (ki 0) (kk 0) (l 0)
(ldwork 0) (lwkopt 0) (nb 0) (nbmin 0) (nx 0) (lquery nil))
(declare (type (f2cl-lib:integer4) i ib iinfo iws j ki kk l ldwork
lwkopt nb nbmin nx)
(type f2cl-lib:logical lquery))
(setf info 0)
(setf nb (ilaenv 1 "ZUNGQR" " " m n k -1))
(setf lwkopt
(f2cl-lib:int-mul
(max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 n))
nb))
(setf (f2cl-lib:fref work-%data% (1) ((1 *)) work-%offset%)
(coerce lwkopt 'f2cl-lib:complex16))
(setf lquery (coerce (= lwork -1) 'f2cl-lib:logical))
(cond
((< m 0)
(setf info -1))
((or (< n 0) (> n m))
(setf info -2))
((or (< k 0) (> k n))
(setf info -3))
((< lda (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 m)))
(setf info -5))
((and
(< lwork (max (the f2cl-lib:integer4 1) (the f2cl-lib:integer4 n)))
(not lquery))
(setf info -8)))
(cond
((/= info 0)
(xerbla "ZUNGQR" (f2cl-lib:int-sub info))
(go end_label))
(lquery
(go end_label)))
(cond
((<= n 0)
(setf (f2cl-lib:fref work-%data% (1) ((1 *)) work-%offset%)
(coerce 1 'f2cl-lib:complex16))
(go end_label)))
(setf nbmin 2)
(setf nx 0)
(setf iws n)
(cond
((and (> nb 1) (< nb k))
(setf nx
(max (the f2cl-lib:integer4 0)
(the f2cl-lib:integer4
(ilaenv 3 "ZUNGQR" " " m n k -1))))
(cond
((< nx k)
(setf ldwork n)
(setf iws (f2cl-lib:int-mul ldwork nb))
(cond
((< lwork iws)
(setf nb (the f2cl-lib:integer4 (truncate lwork ldwork)))
(setf nbmin
(max (the f2cl-lib:integer4 2)
(the f2cl-lib:integer4
(ilaenv 2 "ZUNGQR" " " m n k -1))))))))))
(cond
((and (>= nb nbmin) (< nb k) (< nx k))
(setf ki (* (the f2cl-lib:integer4 (truncate (- k nx 1) nb)) nb))
(setf kk
(min (the f2cl-lib:integer4 k)
(the f2cl-lib:integer4 (f2cl-lib:int-add ki nb))))
(f2cl-lib:fdo (j (f2cl-lib:int-add kk 1) (f2cl-lib:int-add j 1))
((> j n) nil)
(tagbody
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1))
((> i kk) nil)
(tagbody
(setf (f2cl-lib:fref a-%data%
(i j)
((1 lda) (1 *))
a-%offset%)
zero)
label10))
label20)))
(t
(setf kk 0)))
(if (< kk n)
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(zung2r (f2cl-lib:int-sub m kk) (f2cl-lib:int-sub n kk)
(f2cl-lib:int-sub k kk)
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
((+ kk 1) (f2cl-lib:int-add kk 1))
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice tau-%data%
f2cl-lib:complex16
((+ kk 1))
((1 *))
tau-%offset%)
work iinfo)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6))
(setf iinfo var-7)))
(cond
((> kk 0)
(f2cl-lib:fdo (i (f2cl-lib:int-add ki 1)
(f2cl-lib:int-add i (f2cl-lib:int-sub nb)))
((> i 1) nil)
(tagbody
(setf ib
(min (the f2cl-lib:integer4 nb)
(the f2cl-lib:integer4
(f2cl-lib:int-add (f2cl-lib:int-sub k i) 1))))
(cond
((<= (f2cl-lib:int-add i ib) n)
(zlarft "Forward" "Columnwise"
(f2cl-lib:int-add (f2cl-lib:int-sub m i) 1) ib
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i i)
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice tau-%data%
f2cl-lib:complex16
(i)
((1 *))
tau-%offset%)
work ldwork)
(zlarfb "Left" "No transpose" "Forward" "Columnwise"
(f2cl-lib:int-add (f2cl-lib:int-sub m i) 1)
(f2cl-lib:int-add (f2cl-lib:int-sub n i ib) 1) ib
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i i)
((1 lda) (1 *))
a-%offset%)
lda work ldwork
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i (f2cl-lib:int-add i ib))
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice work-%data%
f2cl-lib:complex16
((+ ib 1))
((1 *))
work-%offset%)
ldwork)))
(multiple-value-bind
(var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7)
(zung2r (f2cl-lib:int-add (f2cl-lib:int-sub m i) 1) ib ib
(f2cl-lib:array-slice a-%data%
f2cl-lib:complex16
(i i)
((1 lda) (1 *))
a-%offset%)
lda
(f2cl-lib:array-slice tau-%data%
f2cl-lib:complex16
(i)
((1 *))
tau-%offset%)
work iinfo)
(declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6))
(setf iinfo var-7))
(f2cl-lib:fdo (j i (f2cl-lib:int-add j 1))
((> j
(f2cl-lib:int-add i ib (f2cl-lib:int-sub 1)))
nil)
(tagbody
(f2cl-lib:fdo (l 1 (f2cl-lib:int-add l 1))
((> l
(f2cl-lib:int-add i (f2cl-lib:int-sub 1)))
nil)
(tagbody
(setf (f2cl-lib:fref a-%data%
(l j)
((1 lda) (1 *))
a-%offset%)
zero)
label30))
label40))
label50))))
(setf (f2cl-lib:fref work-%data% (1) ((1 *)) work-%offset%)
(coerce iws 'f2cl-lib:complex16))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil info))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::zungqr
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(array fortran-to-lisp::complex16 (*))
(array fortran-to-lisp::complex16 (*))
(fortran-to-lisp::integer4)
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil
fortran-to-lisp::info)
:calls '(fortran-to-lisp::zlarfb fortran-to-lisp::zlarft
fortran-to-lisp::zung2r fortran-to-lisp::xerbla
fortran-to-lisp::ilaenv))))
|
3a0cc0237761c891440a3cd49280b058294429a408747d846cccddf2a5134112 | qfpl/reflex-workshop | Collections.hs | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
module Workshop.Collections (
collectionsSection
) where
import Reflex.Dom.Core
import qualified Data.Map as Map
import Types.RouteFragment
import Types.Section
import Workshop.Collections.Displaying
import Workshop.Collections.Adding
import Workshop.Collections.Removing
import Workshop.Collections.Model
import Workshop.Collections.EventWriter
collectionsSection :: MonadWidget t m => Section m
collectionsSection =
Section
"Collections"
(Page "collections")
"pages/collections.html"
[eventWriterSection]
mempty
(Map.fromList [ ("displaying", exDisplaying)
, ("adding", exAdding)
, ("removing", exRemoving)
, ("model", exModel)
])
| null | https://raw.githubusercontent.com/qfpl/reflex-workshop/244ef13fb4b2e884f455eccc50072e98d1668c9e/src/Workshop/Collections.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE GADTs # | |
Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Workshop.Collections (
collectionsSection
) where
import Reflex.Dom.Core
import qualified Data.Map as Map
import Types.RouteFragment
import Types.Section
import Workshop.Collections.Displaying
import Workshop.Collections.Adding
import Workshop.Collections.Removing
import Workshop.Collections.Model
import Workshop.Collections.EventWriter
collectionsSection :: MonadWidget t m => Section m
collectionsSection =
Section
"Collections"
(Page "collections")
"pages/collections.html"
[eventWriterSection]
mempty
(Map.fromList [ ("displaying", exDisplaying)
, ("adding", exAdding)
, ("removing", exRemoving)
, ("model", exModel)
])
|
07c7ab72b9701c82b9db4c42b18b37b3a5aa0c91e3995d99e889eb4e1b9ba0b3 | zcaudate/hara | dependency_test.clj | (ns hara.lib.aether.dependency-test
(:use hara.test)
(:require [hara.lib.aether.dependency :refer :all])
(:import (org.eclipse.aether.graph Exclusion)))
^{:refer hara.lib.aether.dependency/rep-exclusion :added "3.0"}
(fact "creates a rep from an exclusion"
(str (rep-exclusion (artifact-exclusion "hara:hara")))
=> "hara:hara:jar:")
^{:refer hara.lib.aether.dependency/artifact-exclusion :added "3.0"}
(fact "creates an artifact exclusion"
(artifact-exclusion "hara:hara:jar:2.8.4")
=> Exclusion)
| null | https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/test/hara/lib/aether/dependency_test.clj | clojure | (ns hara.lib.aether.dependency-test
(:use hara.test)
(:require [hara.lib.aether.dependency :refer :all])
(:import (org.eclipse.aether.graph Exclusion)))
^{:refer hara.lib.aether.dependency/rep-exclusion :added "3.0"}
(fact "creates a rep from an exclusion"
(str (rep-exclusion (artifact-exclusion "hara:hara")))
=> "hara:hara:jar:")
^{:refer hara.lib.aether.dependency/artifact-exclusion :added "3.0"}
(fact "creates an artifact exclusion"
(artifact-exclusion "hara:hara:jar:2.8.4")
=> Exclusion)
| |
ec09beffaccfa63f47c20a71d88438fdeb0bf1b732e0606925964f026e3eca9a | YoshikuniJujo/test_haskell | Taocp.hs | # LANGUAGE BlockArguments #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module HeapSort.Taocp where
import Control.Monad.ST
import Data.Array.ST
import Data.Bool
heapsort :: Ord a => [a] -> [a]
heapsort xs = runST
$ (>>) <$> hsort <*> getElems =<< newListArray (1, length xs) xs
hsort :: Ord a => STArray s Int a -> ST s ()
hsort ks = do
n <- rangeSize <$> getBounds ks
algorithm ks (n `div` 2 + 1) n
algorithm :: Ord a => STArray s Int a -> Int -> Int -> ST s ()
algorithm ks l r
| l > 1 = do
k <- readArray ks l'
shiftup ks k r l'
algorithm ks l' r
| otherwise = do
k <- readArray ks r
writeArray ks r =<< readArray ks 1
if r' == 1
then writeArray ks 1 k
else do shiftup ks k r' l
algorithm ks l r'
where
l' = l - 1
r' = r - 1
shiftupList :: Ord a => [a] -> a -> Int -> Int -> [a]
shiftupList xs x r j = runST do
a <- newListArray (1, length xs) xs
shiftup a x r j
getElems a
shiftup :: Ord a => STArray s Int a -> a -> Int -> Int -> ST s ()
shiftup ks k r j
| j' <= r = do
kj' <- readArray ks j'
j'' <- if j' < r
then do kj'1 <- readArray ks (j' + 1)
pure $ bool j' (j' + 1) (kj' < kj'1)
else pure j'
kj'' <- readArray ks j''
if k >= kj''
then writeArray ks i k
else do writeArray ks i kj''
shiftup ks k r j''
| otherwise = writeArray ks i k
where i = j; j' = 2 * j
| null | https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/00cf4f7e198ac3f6026a3ffd2558efe95466b6bf/tribial/mastodon/heapsort/src/HeapSort/Taocp.hs | haskell | # LANGUAGE BlockArguments #
# OPTIONS_GHC -Wall -fno - warn - tabs #
module HeapSort.Taocp where
import Control.Monad.ST
import Data.Array.ST
import Data.Bool
heapsort :: Ord a => [a] -> [a]
heapsort xs = runST
$ (>>) <$> hsort <*> getElems =<< newListArray (1, length xs) xs
hsort :: Ord a => STArray s Int a -> ST s ()
hsort ks = do
n <- rangeSize <$> getBounds ks
algorithm ks (n `div` 2 + 1) n
algorithm :: Ord a => STArray s Int a -> Int -> Int -> ST s ()
algorithm ks l r
| l > 1 = do
k <- readArray ks l'
shiftup ks k r l'
algorithm ks l' r
| otherwise = do
k <- readArray ks r
writeArray ks r =<< readArray ks 1
if r' == 1
then writeArray ks 1 k
else do shiftup ks k r' l
algorithm ks l r'
where
l' = l - 1
r' = r - 1
shiftupList :: Ord a => [a] -> a -> Int -> Int -> [a]
shiftupList xs x r j = runST do
a <- newListArray (1, length xs) xs
shiftup a x r j
getElems a
shiftup :: Ord a => STArray s Int a -> a -> Int -> Int -> ST s ()
shiftup ks k r j
| j' <= r = do
kj' <- readArray ks j'
j'' <- if j' < r
then do kj'1 <- readArray ks (j' + 1)
pure $ bool j' (j' + 1) (kj' < kj'1)
else pure j'
kj'' <- readArray ks j''
if k >= kj''
then writeArray ks i k
else do writeArray ks i kj''
shiftup ks k r j''
| otherwise = writeArray ks i k
where i = j; j' = 2 * j
| |
9163a78ad33c73bd218a315d4eba6c81898dd1c06249b756c302a83229f51555 | babashka/neil | changelog.clj | #!/usr/bin/env bb
(ns changelog
(:require [clojure.string :as str]))
(let [changelog (slurp "CHANGELOG.md")
replaced (str/replace changelog
#" #(\d+)"
(fn [[_ issue after]]
(format " [#%s]()%s"
issue issue (str after))))
replaced (str/replace replaced
#"@([a-zA-Z0-9-_]+)([, \.)])"
(fn [[_ name after]]
(format "[@%s]()%s"
name name after)))]
(spit "CHANGELOG.md" replaced))
| null | https://raw.githubusercontent.com/babashka/neil/832f3a9eee64f2ce72d787662bb3ea29b3d388c2/script/changelog.clj | clojure | #!/usr/bin/env bb
(ns changelog
(:require [clojure.string :as str]))
(let [changelog (slurp "CHANGELOG.md")
replaced (str/replace changelog
#" #(\d+)"
(fn [[_ issue after]]
(format " [#%s]()%s"
issue issue (str after))))
replaced (str/replace replaced
#"@([a-zA-Z0-9-_]+)([, \.)])"
(fn [[_ name after]]
(format "[@%s]()%s"
name name after)))]
(spit "CHANGELOG.md" replaced))
| |
1e4a9c4a3dc146813937a0c9427a4ca36203411465dd64af8aee0566bcd07cb4 | paurkedal/viz | graphalgo.mli | Copyright ( C ) 2011 - -2016 Petter A. Urkedal < >
*
* This file is part of the Viz Compiler < / > .
*
* The Viz Compiler 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 .
*
* The Viz Compiler 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 the Viz Compiler . If not , see < / > .
*
* This file is part of the Viz Compiler </>.
*
* The Viz Compiler 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.
*
* The Viz Compiler 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 the Viz Compiler. If not, see </>.
*)
(** Algorithms on Graph-Like Data *)
(** The signature of a "simply traversable" graph, without edges but with an
associated map structure for the vertices. *)
module type ST_GRAPH = sig
type graph
type vertex
module Vertex_map : sig
type 'a t
val empty : 'a t
val add : vertex -> 'a -> 'a t -> 'a t
val mem : vertex -> 'a t -> bool
val find : vertex -> 'a t -> 'a
end
val fold_adjacent : graph -> (vertex -> 'a -> 'a) -> vertex -> 'a -> 'a
end
* Functor to instantiate the algorithms on [ ST_GRAPH]s .
module ST_algo (G : ST_GRAPH) : sig
val fold_strongly_connected
: G.graph -> (G.vertex list -> 'a -> 'a) -> G.vertex list -> 'a -> 'a
* [ fold_strongly_connected g f vs ] is the composition of [ f us ] for each
[ us ] in the partition of strongly connected components of [ vs ] . The
components are passed to [ f ] in topological order , starting with the
deepest vertices as the rightmost factor . The implementation follows
algorithm .
[us] in the partition of strongly connected components of [vs]. The
components are passed to [f] in topological order, starting with the
deepest vertices as the rightmost factor. The implementation follows
the Cheriyan-Mehlhorn/Gabow algorithm. *)
end
| null | https://raw.githubusercontent.com/paurkedal/viz/ab1f1071fafdc51eae69185ec55d7a6e7bb94ea9/camlviz/graphalgo.mli | ocaml | * Algorithms on Graph-Like Data
* The signature of a "simply traversable" graph, without edges but with an
associated map structure for the vertices. | Copyright ( C ) 2011 - -2016 Petter A. Urkedal < >
*
* This file is part of the Viz Compiler < / > .
*
* The Viz Compiler 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 .
*
* The Viz Compiler 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 the Viz Compiler . If not , see < / > .
*
* This file is part of the Viz Compiler </>.
*
* The Viz Compiler 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.
*
* The Viz Compiler 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 the Viz Compiler. If not, see </>.
*)
module type ST_GRAPH = sig
type graph
type vertex
module Vertex_map : sig
type 'a t
val empty : 'a t
val add : vertex -> 'a -> 'a t -> 'a t
val mem : vertex -> 'a t -> bool
val find : vertex -> 'a t -> 'a
end
val fold_adjacent : graph -> (vertex -> 'a -> 'a) -> vertex -> 'a -> 'a
end
* Functor to instantiate the algorithms on [ ST_GRAPH]s .
module ST_algo (G : ST_GRAPH) : sig
val fold_strongly_connected
: G.graph -> (G.vertex list -> 'a -> 'a) -> G.vertex list -> 'a -> 'a
* [ fold_strongly_connected g f vs ] is the composition of [ f us ] for each
[ us ] in the partition of strongly connected components of [ vs ] . The
components are passed to [ f ] in topological order , starting with the
deepest vertices as the rightmost factor . The implementation follows
algorithm .
[us] in the partition of strongly connected components of [vs]. The
components are passed to [f] in topological order, starting with the
deepest vertices as the rightmost factor. The implementation follows
the Cheriyan-Mehlhorn/Gabow algorithm. *)
end
|
29339b5b92eaf8a300c5a8c9ef67fd541b14f8b6f7cd8683ac61b5a76ce4e911 | manuel-serrano/bigloo | evmeaning.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / runtime / Eval / evmeaning.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : We d Aug 4 10:48:41 1993 * /
* Last change : Sat Jul 20 10:44:40 2013 ( serrano ) * /
;* ------------------------------------------------------------- */
* The 's interpreter . * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* Le module */
;*---------------------------------------------------------------------*/
(module __evmeaning
(include "Eval/byte-code.sch")
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__bit
__param
__bexit
__object
__thread
__rgc
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_input_6_10_2
__r4_control_features_6_9
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__progn
__evenv
__evcompile
__everror
__evmodule)
(export (evmeaning ::obj ::pair-nil ::dynamic-env))
(extern (%funcall-0::obj (::procedure)
"eval_funcall_0")
(%funcall-1::obj (::procedure ::obj)
"eval_funcall_1")
(%funcall-2::obj (::procedure ::obj ::obj)
"eval_funcall_2")
(%funcall-3::obj (::procedure ::obj ::obj ::obj)
"eval_funcall_3")
(%funcall-4::obj (::procedure ::obj ::obj ::obj ::obj)
"eval_funcall_4")
(%eval-apply::obj (::procedure ::obj)
"eval_apply"))
(java (class foreign
(method static %funcall-0::obj (::procedure)
"eval_funcall_0")
(method static %funcall-1::obj (::procedure ::obj)
"eval_funcall_1")
(method static %funcall-2::obj (::procedure ::obj ::obj)
"eval_funcall_2")
(method static %funcall-3::obj (::procedure ::obj ::obj ::obj)
"eval_funcall_3")
(method static %funcall-4::obj (::procedure ::obj ::obj ::obj ::obj)
"eval_funcall_4")
(method static %eval-apply::obj (::procedure ::obj)
"eval_apply")))
;; Disabling user-inlining is strictly required in order
;; to avoid stack blow up in the evmeaning function.
inlining is required for the same reason .
(option (set! *user-inlining?* #f)
( set ! * inlining - kfactor * ( lambda ( x ) 1 ) )
(set! *saw-register-allocation?* #t)
(set! *saw-register-allocation-max-size* 8000)))
;*---------------------------------------------------------------------*/
;* case-bounce ... */
;*---------------------------------------------------------------------*/
(define-macro (case-bounce test . clauses)
(let* ((bounce '())
(r `(case ,test
,@(map (lambda (c)
(match-case c
(((bounce ?vars ((and (? integer?) ?n))) . ?body)
(let ((id (string->symbol
(string-append
"evmeaning-bounce-"
(integer->string n)))))
(set! bounce
(cons `(define (,id ,@vars) ,@body)
bounce))
`((,n) (,id ,@vars))))
(((bounce . ?-) . ?-)
(error 'case-bounce "Illegal clause" c))
(else
c)))
clauses))))
(putprop! 'case-bounce 'bouncing bounce)
r))
;*---------------------------------------------------------------------*/
;* emit-bounced! ... */
;*---------------------------------------------------------------------*/
(define-macro (emit-bounced!)
`(begin ,@(getprop 'case-bounce 'bouncing)))
;*---------------------------------------------------------------------*/
;* %inline-let ... */
;*---------------------------------------------------------------------*/
(define-macro (%with-inline body)
`(let ((type-check #t)
(a0 #unspecified))
,body))
;*---------------------------------------------------------------------*/
;* %inline1 ... */
;*---------------------------------------------------------------------*/
(define-macro (%inline1 fun code stack denv . type)
(if (null? type)
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv)))
`(,fun a0))
(let ((pred (symbol-append (car type) '?)))
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv)))
(if (,pred a0)
(,fun a0)
(evtype-error (evcode-loc code) "eval" ',(car type) a0))))))
;*---------------------------------------------------------------------*/
;* %inline2 ... */
;*---------------------------------------------------------------------*/
(define-macro (%inline2 fun code stack denv . type)
(if (null? type)
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv))
(a1 (evmeaning (evcode-ref ,code 3) ,stack ,denv)))
(,fun a0 a1))
(let ((pred (symbol-append (car type) '?)))
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv))
(a1 (evmeaning (evcode-ref ,code 3) ,stack ,denv)))
(if (,pred a0)
(if (,pred a1)
(,fun a0 a1)
(evtype-error (evcode-loc code) "eval" ',(car type) a1))
(evtype-error (evcode-loc code) "eval" ',(car type) a0))))))
;*---------------------------------------------------------------------*/
;* evmeaning-unbound ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-unbound loc name mod)
(everror loc
"eval"
(if (evmodule? mod)
(format "Unbound variable (from module `~a')"
(evmodule-name mod))
"Unbound variable (from top-level)")
name))
;*---------------------------------------------------------------------*/
;* evmeaning-uninitialized ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-uninitialized loc name)
(everror loc "eval" "Uninitialized variable" name))
;*---------------------------------------------------------------------*/
;* evmeaning ... */
;*---------------------------------------------------------------------*/
(define (evmeaning code stack denv)
(if (evcode? code)
(%with-inline
(case-bounce (evcode-op code)
((-2)
;; errors
(apply everror (evcode-loc code) (evcode-ref code 0)))
((-1)
La seule constante : les ` vecteurs '
(evcode-ref code 0))
((0)
first local variable
(car stack))
((1)
second local variable
(cadr stack))
((2)
third local variable
(caddr stack))
((3)
fourth local variable
(cadddr stack))
((4)
;; deep local variables
(let ((offset (evcode-ref code 0)))
(do ((i 4 (+fx i 1))
(env (cddddr stack) (cdr env)))
((=fx i offset) (car env)))))
((5)
;; mutable global variable
(__evmeaning_address-ref
(eval-global-value (evcode-ref code 0))))
((6)
;; global variable
(let* ((g (evcode-ref code 0))
(val (eval-global-value g)))
(if (eq? val #unspecified)
(let ((tag (eval-global-tag g)))
(if (or (=fx tag 3) (=fx tag 4))
(evmeaning-uninitialized
(evcode-loc code) (eval-global-name g))
val))
val)))
((bounce (code stack denv) (7))
;; dynamic global variable
(let* ((name (evcode-ref code 0))
(mod (evcode-ref code 1))
(global (evmodule-find-global mod name)))
(if (eval-global? global)
(begin
;; we change the value of the byte-code
;; because, now, the variable is bound
(evcode-op-set! code 6)
(evcode-set! code 0 global)
(eval-global-value global))
(evmeaning-unbound (evcode-loc code) name mod))))
((8)
;; (set! <global> <value>)
(let ((var (evcode-ref code 0))
(val (evmeaning (evcode-ref code 1) stack denv)))
(update-eval-global! code var val)
(unspecified)))
((bounce (code stack denv) (9))
;; (set! <dynamic-global> <value>)
(let* ((name (evcode-ref code 0))
(value (evcode-ref code 1))
(mod (evcode-ref code 2))
(global (evmodule-find-global mod name)))
(if (eval-global? global)
(begin
(evcode-op-set! code 8)
(evcode-set! code 0 global)
(evcode-set! code 1 value)
(evmeaning code stack denv))
(evmeaning-unbound (evcode-loc code) name mod))))
((10)
la mutation de la premiere variable locale
(set-car! stack (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((11)
la mutation de la deuxieme variable locale
(set-car! (cdr stack) (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((12)
;; la mutation de la troisieme variable locale
(set-car! (cddr stack) (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((13)
;; la mutation de la quatrieme variable locale
(set-car! (cdddr stack) (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((bounce (code stack denv) (14))
;; la mutation des variables locales profondes
(let ((offset (evcode-ref code 0))
(value (evmeaning (evcode-ref code 1) stack denv)))
(do ((i 4 (+fx i 1))
(env (cddddr stack) (cdr env)))
((=fx i offset) (set-car! env value)))
(unspecified)))
((15)
;; conditional
(if (evmeaning (evcode-ref code 0) stack denv)
(evmeaning (evcode-ref code 1) stack denv)
(evmeaning (evcode-ref code 2) stack denv)))
((16)
sequence ( by construction , the length is at least 1 )
(let ((len (-fx (evcode-length code) 1)))
(let loop ((i 0))
(if (=fx i len)
(evmeaning (evcode-ref code i) stack denv)
(begin
(evmeaning (evcode-ref code i) stack denv)
(loop (+fx i 1)))))))
((bounce (code stack denv) (17))
;; (define <global> <var>)
(let ((var (evcode-ref code 0))
(val (evcode-ref code 1))
(mod (evcode-ref code 2)))
(let ((v (evmodule-find-global mod var)))
(if (eval-global? v)
(case (eval-global-tag v)
((0)
(everror (evcode-loc code) "eval"
"Compiled read-only variable cannot be redefined"
var))
((1)
(evwarning (evcode-loc code) "eval"
"\nRedefinition of compiled variable -- "
var)
(update-eval-global! code v (evmeaning val '() denv)))
((2)
(update-eval-global! code v (evmeaning val '() denv)))
((3)
(update-eval-global! code v (evmeaning val '() denv))
(eval-global-tag-set! v 2))
((4)
(update-eval-global! code v (evmeaning val '() denv))
(eval-global-tag-set! v 5))
(else
(everror (evcode-loc code) "eval"
"Read-only variable cannot be redefined"
var)))
(let* ((loc (evcode-loc code))
(g (make-eval-global var (eval-module) loc)))
;; first we bind the variable
(evmodule-bind-global! mod var g loc)
;; second we evaluate it's body
(let ((value (evmeaning val '() denv)))
(set-eval-global-value! g value))))
var)))
((bounce (code stack denv) (18))
;; bind-exit
(bind-exit (__dummy__)
((evmeaning (evcode-ref code 0) stack denv) __dummy__)))
((bounce (code) (25))
l'appel de fonction de compilee anonyme d'arite 0
((evcode-ref code 0)))
((bounce (code stack denv) (26))
l'appel de fonction de compilee anonyme d'arite 1
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv)))
(fun a0)))
((bounce (code stack denv) (27))
l'appel de fonction de compilee anonyme d'arite 2
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv))
(a1 (evmeaning (evcode-ref code 2) stack denv)))
(fun a0 a1)))
((bounce (code stack denv) (28))
l'appel de fonction de compilee anonyme d'arite 3
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv))
(a1 (evmeaning (evcode-ref code 2) stack denv))
(a2 (evmeaning (evcode-ref code 3) stack denv)))
(fun a0 a1 a2)))
((bounce (code stack denv) (29))
l'appel de fonction de compilee anonyme d'arite 4
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv))
(a1 (evmeaning (evcode-ref code 2) stack denv))
(a2 (evmeaning (evcode-ref code 3) stack denv))
(a3 (evmeaning (evcode-ref code 4) stack denv)))
(fun a0 a1 a2 a3)))
((bounce (code stack denv) (30))
l'appel de fonction de compilee anonyme d'arite plus que 4
(let ((eargs (map (lambda (x)
(evmeaning x stack denv))
(evcode-ref code 1))))
(apply (evcode-ref code 0) eargs)))
((31)
;; funcall 0
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-0 code stack denv fun)))
((32)
funcall 1
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-1 code stack denv fun)))
((33)
funcall 2
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-2 code stack denv fun)))
((34)
funcall 3
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-3 code stack denv fun)))
((35)
funcall 4
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-4 code stack denv fun)))
((bounce (code stack denv) (36))
funcall > 4
(let* ((name (evcode-ref code 0))
(fun (evmeaning (evcode-ref code 1) stack denv)))
(let loop ((args (evcode-ref code 2))
(new '())
(len 0))
(if (null? args)
(begin
($env-set-trace-location denv (evcode-loc code))
(eval-apply code name fun len (reverse! new)))
(loop (cdr args)
(cons (evmeaning (car args) stack denv) new)
(+fx 1 len))))))
((bounce (code stack denv) (37))
;; This code is very sensitive to the compiler order. Because
;; of tail recursion, it is extremely important that the capture
variable are order 0 for the body ( the variable ! b ) , and 1
;; for the stack (the variable !s). To enforce this order, we
explicitly use a cascade of " if"s
;; procedure arity 0, traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda ()
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b !s !denv)))
($env-pop-trace !denv)
res))))
0
body
stack)))
((bounce (code stack denv) (42))
;; ...untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda ()
(let ((!b body))
(evmeaning !b stack denv)))
0
body
stack)))
((bounce (code stack denv) (38))
procedure arity 1 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b (cons x !s) !denv)))
($env-pop-trace !denv)
res))))
1
body
stack)))
((bounce (code stack denv) (43))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x)
(let ((!b body))
(evmeaning !b (cons x stack) denv)))
1
body
stack)))
((bounce (code stack denv) (39))
procedure arity 2 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((r (evmeaning !b (cons x (cons y !s)) !denv)))
($env-pop-trace !denv)
r))))
2
body
stack)))
((bounce (code stack denv) (44))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y)
(let ((!b body))
(evmeaning !b (cons x (cons y stack)) denv)))
2
body
stack)))
((bounce (code stack denv) (40))
procedure arity 3 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y z)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b
(cons x
(cons y
(cons z !s)))
!denv)))
($env-pop-trace !denv)
res))))
3
body
stack)))
((bounce (code stack denv) (45))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y z)
(let ((!b body))
(evmeaning !b (cons x (cons y (cons z stack))) denv)))
3
body
stack)))
((bounce (code stack denv) (41))
procedure arity 4 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y z t)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning
!b
(cons x
(cons y
(cons z
(cons t !s))))
!denv)))
($env-pop-trace !denv)
res))))
4
body
stack)))
((bounce (code stack denv) (46))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y z t)
(let ((!b body))
(evmeaning !b
(cons x (cons y (cons z (cons t stack))))
denv)))
4
body
stack)))
((bounce (code stack denv) (47))
;; procedure arity -1, traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b (cons x !s) !denv)))
($env-pop-trace !denv)
res))))
-1
body
stack)))
((bounce (code stack denv) (51))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda x
(let ((!b body))
(evmeaning !b (cons x stack) denv)))
-1
body
stack)))
((bounce (code stack denv) (48))
;; procedure arity -2, traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x . y)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((r (evmeaning !b (cons x (cons y !s)) !denv)))
($env-pop-trace !denv)
r))))
-2
body
stack)))
((bounce (code stack denv) (52))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x . y)
(let ((!b body))
(evmeaning !b (cons x (cons y stack)) denv)))
-2
body
stack)))
((bounce (code stack denv) (49))
;; procedure arity -3, traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y . z)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b
(cons x
(cons y
(cons z !s)))
!denv)))
($env-pop-trace !denv)
res))))
-3
body
stack)))
((bounce (code stack denv) (53))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y . z)
(let ((!b body))
(evmeaning !b
(cons x (cons y (cons z stack)))
denv)))
-3
body
stack)))
((bounce (code stack denv) (50))
;; procedure arity -4, traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y z . t)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning
!b
(cons x
(cons y
(cons z
(cons t
!s))))
!denv)))
($env-pop-trace !denv)
res))))
-4
body
stack)))
((bounce (code stack denv) (54))
;; untraced
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y z . t)
(let ((!b body))
(evmeaning
!b
(cons x (cons y (cons z (cons t stack))))
denv)))
-4
body
stack)))
((55)
procedure arity > 4 arguments , traced
(evmeaning-make-traced-4procedure code stack denv))
;; untraced
((56)
(evmeaning-make-4procedure code stack denv))
((bounce (code stack denv) (64))
;; unwind-protect
(let ((body (evcode-ref code 0))
(protect (evcode-ref code 1)))
(unwind-protect (evmeaning body stack denv)
(evmeaning protect stack denv))))
((65)
;; let (bindings are stored reversed!)
(let loop ((vals (evcode-ref code 1))
(env stack))
(if (null? vals)
(evmeaning (evcode-ref code 0) env denv)
(let ((v (evmeaning (car vals) stack denv)))
(loop (cdr vals) (cons v env))))))
((66)
;; let*
(let loop ((vals (evcode-ref code 1))
(stack stack))
(if (null? vals)
(evmeaning (evcode-ref code 0) stack denv)
(loop (cdr vals)
(cons (evmeaning (car vals) stack denv) stack)))))
((bounce (code stack denv) (67))
;; or
(let ((len (evcode-length code)))
(let loop ((i 0))
(if (<fx i len)
(or (evmeaning (evcode-ref code i) stack denv)
(loop (+fx i 1)))
#f))))
((bounce (code stack denv) (68))
;; and
(let ((len (evcode-length code)))
(let loop ((i 0)
(l #t))
(if (<fx i len)
(let ((l (evmeaning (evcode-ref code i) stack denv)))
(and l (loop (+fx i 1) l)))
l))))
((bounce (code stack denv) (70))
;; letrec
(let* ((vals (evcode-ref code 1))
(stack2 (append (make-list (length vals)) stack)))
(let loop ((vals vals)
(stack3 stack2))
(if (null? vals)
(evmeaning (evcode-ref code 0) stack2 denv)
(begin
(set-car! stack3 (evmeaning (car vals) stack2 denv))
(loop (cdr vals) (cdr stack3)))))))
((bounce (code stack denv) (71))
;; with-handler
(let* ((handler (evcode-ref code 0))
(body (evcode-ref code 1))
(ehandler (evmeaning handler stack denv))
(loc (evcode-loc code)))
(cond
((not (procedure? ehandler))
(evtype-error loc "eval" "procedure" ehandler))
((correct-arity? ehandler 1)
(with-handler ehandler (evmeaning body stack denv)))
(else
(evarity-error loc "with-handler" 1 ($procedure-arity ehandler))))))
((bounce (code stack denv) (175))
;; synchronize
(let* ((mutex (evcode-ref code 0))
(body (evcode-ref code 1))
(m (evmeaning mutex stack denv)))
(if (mutex? m)
(synchronize m
(evmeaning body stack denv))
(evtype-error (evcode-loc code) "synchronize" "mutex" m))))
((bounce (code stack denv) (176))
;; synchronize/prelock
(let* ((mutex (evcode-ref code 0))
(prelock (evcode-ref code 1))
(body (evcode-ref code 2))
(m (evmeaning mutex stack denv)))
(if (mutex? m)
(synchronize m
:prelock (evmeaning prelock stack denv)
(evmeaning body stack denv))
(evtype-error (evcode-loc code) "synchronize" "mutex" m))))
((131)
;; tailcall 0
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-0-stack code stack denv fun)
denv)
(evmeaning-funcall-0 code stack denv fun))))
((132)
;; tailcall 1
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-1-stack code stack denv fun)
denv)
(evmeaning-funcall-1 code stack denv fun))))
((133)
tailcall 2
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-2-stack code stack denv fun)
denv)
(evmeaning-funcall-2 code stack denv fun))))
((134)
tailcall 3
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-3-stack code stack denv fun)
denv)
(evmeaning-funcall-3 code stack denv fun))))
((135)
;; tailcall 4
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-4-stack code stack denv fun)
denv)
(evmeaning-funcall-4 code stack denv fun))))
((136)
tailcall > 4
(let* ((name (evcode-ref code 0))
(fun (evmeaning (evcode-ref code 1) stack denv))
(loc (evcode-loc code)))
(let loop ((args (evcode-ref code 2))
(new '())
(len 0))
(if (null? args)
(if (evmeaning-procedure? fun)
(let* ((fmls (evmeaning-procedure-args fun))
(stack (evmeaning-procedure-stack fun))
(wen (reverse! new))
(e2 (if (>=fx fmls 0)
(evmeaning-push-fxargs name
loc
wen
fmls
stack)
(evmeaning-push-vaargs name
loc
wen
fmls
stack))))
(evmeaning (evmeaning-procedure-bcode fun)
e2
denv))
(eval-apply code name fun len (reverse! new)))
(loop (cdr args)
(cons (evmeaning (car args) stack denv) new)
(+fx 1 len))))))
((145 146)
;; unlinked global variable
(evcode-op-set! code (-fx (evcode-op code) 140))
(evcode-set! code 0 (evmodule-find-global
(evcode-ref code 1)
(evcode-ref code 0)))
(evmeaning code stack denv))
;; inline code-op
((147)
(%inline2 + code stack denv number))
((148)
(%inline2 - code stack denv number))
((149)
(%inline2 * code stack denv number))
((150)
(%inline2 / code stack denv number))
((151)
(%inline2 < code stack denv number))
((152)
(%inline2 > code stack denv number))
((153)
(%inline2 <= code stack denv number))
((154)
(%inline2 >= code stack denv number))
((155)
(%inline2 = code stack denv number))
((166)
(%inline2 +fx code stack denv fixnum))
((167)
(%inline2 -fx code stack denv fixnum))
((168)
(%inline2 *fx code stack denv fixnum))
((169)
(%inline2 /fx code stack denv fixnum))
((170)
(%inline2 <fx code stack denv fixnum))
((171)
(%inline2 >fx code stack denv fixnum))
((172)
(%inline2 <=fx code stack denv fixnum))
((173)
(%inline2 >=fx code stack denv fixnum))
((174)
(%inline2 =fx code stack denv fixnum))
((156)
(%inline2 eq? code stack denv))
((157)
(%inline2 cons code stack denv))
((158)
(%inline1 car code stack denv pair))
((159)
(%inline1 cdr code stack denv pair))
((160)
(let ((a0 (evmeaning (evcode-ref code 2) stack denv)))
(cond
((and (pair? a0) (pair? (cdr a0)))
(cadr a0))
((pair? a0)
(evtype-error (evcode-loc code)
(evcode-ref code 0)
"pair" (cdr a0)))
(else
(evtype-error (evcode-loc code)
(evcode-ref code 0)
"pair" a0)))))
(else
;; unknown byte code
(everror (evcode-loc code) "eval" "unknown byte-code" code))))
code))
(emit-bounced!)
;*---------------------------------------------------------------------*/
;* evprocedure ... */
;*---------------------------------------------------------------------*/
(define-struct evprocedure args bcode stack)
;*---------------------------------------------------------------------*/
;* evmeaning-procedure? ... */
;*---------------------------------------------------------------------*/
(define-inline (evmeaning-procedure? proc)
(and (procedure? proc) (evprocedure? (procedure-attr proc))))
;*---------------------------------------------------------------------*/
;* evmeaning-procedure! ... */
;*---------------------------------------------------------------------*/
(define-inline (evmeaning-procedure! proc args bcode stack)
(procedure-attr-set! proc (evprocedure args bcode stack))
proc)
;*---------------------------------------------------------------------*/
;* evmeaning-procedure-bcode ... */
;*---------------------------------------------------------------------*/
(define-inline (evmeaning-procedure-bcode proc)
(evprocedure-bcode (procedure-attr proc)))
;*---------------------------------------------------------------------*/
;* evmeaning-procedure-stack ... */
;*---------------------------------------------------------------------*/
(define-inline (evmeaning-procedure-stack proc)
(evprocedure-stack (procedure-attr proc)))
;*---------------------------------------------------------------------*/
;* evmeaning-procedure-args ... */
;*---------------------------------------------------------------------*/
(define-inline (evmeaning-procedure-args proc)
(evprocedure-args (procedure-attr proc)))
;*---------------------------------------------------------------------*/
;* update-eval-global! ... */
;*---------------------------------------------------------------------*/
(define (update-eval-global! code var val)
(case (eval-global-tag var)
((0)
(everror (evcode-loc code) "set!" "read-only variable" (eval-global-name var)))
((1)
(__evmeaning_address-set! (eval-global-value var) val))
((2)
(set-eval-global-value! var val))
((3)
(set-eval-global-value! var val))
((4)
(set-eval-global-value! var val))
((5)
(everror (evcode-loc code) "set!" "read-only variable" (eval-global-name var)))))
;*---------------------------------------------------------------------*/
;* evmeaning-funcall-0 ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-funcall-0 code stack denv fun)
(let ((name (evcode-ref code 0))
(loc (evcode-loc code)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" name "Not a procedure"))
((not (correct-arity? fun 0))
(evarity-error loc name 0 ($procedure-arity fun)))
(else
(%funcall-0 fun)))))
;*---------------------------------------------------------------------*/
;* evmeaning-funcall-1 ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-funcall-1 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 1))
(evarity-error loc name 1 ($procedure-arity fun)))
(else
(%funcall-1 fun a0)))))
;*---------------------------------------------------------------------*/
;* evmeaning-funcall-2 ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-funcall-2 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 2))
(evarity-error loc name 2 ($procedure-arity fun)))
(else
(%funcall-2 fun a0 a1)))))
;*---------------------------------------------------------------------*/
;* evmeaning-funcall-3 ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-funcall-3 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 3))
(evarity-error loc name 3 ($procedure-arity fun)))
(else
(%funcall-3 fun a0 a1 a2)))))
;*---------------------------------------------------------------------*/
;* evmeaning-funcall-4 ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-funcall-4 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv))
(a3 (evmeaning (evcode-ref code 5) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 4))
(evarity-error loc name 4 ($procedure-arity fun)))
(else
(%funcall-4 fun a0 a1 a2 a3)))))
;*---------------------------------------------------------------------*/
;* evmeaning-tailcall-0-stack ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-tailcall-0-stack code stack denv fun)
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((0)
envd)
((-1)
(cons '() envd))
(else
(evarity-error loc (evcode-ref code 0) 0 arity)))))
;*---------------------------------------------------------------------*/
;* evmeaning-tailcall-1-stack ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-tailcall-1-stack code stack denv fun)
(let ((a0 (evmeaning (evcode-ref code 2) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((1)
(cons a0 envd))
((-1)
(cons (list a0) envd))
((-2)
(cons a0 (cons '() envd)))
(else
(evarity-error loc (evcode-ref code 0) 1 arity))))))
;*---------------------------------------------------------------------*/
;* evmeaning-tailcall-2-stack ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-tailcall-2-stack code stack denv fun)
(let* ((a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((2)
(cons a0 (cons a1 envd)))
((-1)
(cons (list a0 a1) envd))
((-2)
(cons a0 (cons (list a1) envd)))
((-3)
(cons a0 (cons a1 (cons '() envd))))
(else
(evarity-error loc (evcode-ref code 0) 2 arity))))))
;*---------------------------------------------------------------------*/
;* evmeaning-tailcall-3-stack ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-tailcall-3-stack code stack denv fun)
(let* ((a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((3)
(cons a0 (cons a1 (cons a2 envd))))
((-1)
(cons (list a0 a1 a2) envd))
((-2)
(cons a0 (cons (list a1 a2) envd)))
((-3)
(cons a0 (cons a1 (cons (list a2) envd))))
((-4)
(cons a0 (cons a1 (cons a2 (cons '() envd)))))
(else
(evarity-error loc (evcode-ref code 0) 3 arity))))))
;*---------------------------------------------------------------------*/
;* evmeaning-tailcall-4-stack ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-tailcall-4-stack code stack denv fun)
(let* ((a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv))
(a3 (evmeaning (evcode-ref code 5) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((4)
(cons a0 (cons a1 (cons a2 (cons a3 envd)))))
((-1)
(cons (list a0 a1 a2 a3) envd))
((-2)
(cons a0 (cons (list a1 a2 a3) envd)))
((-3)
(cons a0 (cons a1 (cons (list a2 a3) envd))))
((-4)
(cons a0 (cons a1 (cons a2 (cons (list a3) envd)))))
((-5)
(cons a0 (cons a1 (cons a2 (cons a3 (cons '() envd))))))
(else
(evarity-error loc (evcode-ref code 0) 4 arity))))))
;*---------------------------------------------------------------------*/
;* eval-apply ... */
;*---------------------------------------------------------------------*/
(define-inline (eval-apply code name fun len args)
(cond
((not (procedure? fun))
(everror (evcode-loc code) "apply" "Not a procedure" name))
((not (correct-arity? fun len))
(evarity-error (evcode-loc code) name len ($procedure-arity fun)))
(else
(%eval-apply fun args))))
;*---------------------------------------------------------------------*/
;* evmeaning-make-traced-4procedure ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-make-traced-4procedure code stack denv)
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(formals (evcode-ref code 2))
(loc (evcode-loc code)))
(if (list? formals)
(let ((lf (length formals)))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((e2 (evmeaning-push-fxargs where code x lf !s)))
(let ((res (evmeaning !b e2 !denv)))
($env-pop-trace !denv)
res)))))
lf
body
stack))
(let ((lf (let loop ((formals formals)
(num -1))
(if (pair? formals)
(loop (cdr formals) (-fx num 1))
num))))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((e2 (evmeaning-push-vaargs where code x lf !s)))
(let ((res (evmeaning !b e2 !denv)))
($env-pop-trace !denv)
res)))))
lf
body
stack)))))
;*---------------------------------------------------------------------*/
;* evmeaning-make-4procedure ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-make-4procedure code stack denv)
(let ((body (evcode-ref code 0))
(formals (evcode-ref code 1)))
(if (list? formals)
(let ((lf (length formals)))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack))
(let ((e2 (evmeaning-push-fxargs x code x lf !s)))
(evmeaning !b e2 denv))))
lf
body
stack))
(let ((lf (let loop ((formals formals)
(num -1))
(if (pair? formals)
(loop (cdr formals) (-fx num 1))
num))))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack))
(let ((e2 (evmeaning-push-vaargs x code x lf !s)))
(evmeaning !b e2 denv))))
lf
body
stack)))))
;*---------------------------------------------------------------------*/
;* evmeaning-push-fxargs ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-push-fxargs name loc actuals num stack)
(let _loop_ ((a actuals)
(n num))
(cond
((=fx n 0)
(if (not (null? a))
(evarity-error loc name (length actuals) num)
stack))
((null? a)
(evarity-error loc name (length actuals) num))
(else
(cons (car a) (_loop_ (cdr a) (-fx n 1)))))))
;*---------------------------------------------------------------------*/
;* evmeaning-push-vaargs ... */
;*---------------------------------------------------------------------*/
(define (evmeaning-push-vaargs name loc actuals num stack)
(let _loop_ ((a actuals)
(n num))
(cond
((=fx n -1)
(cons a stack))
((null? a)
(evarity-error loc name (length actuals) num))
(else
(cons (car a) (_loop_ (cdr a) (+fx n 1)))))))
;*---------------------------------------------------------------------*/
;* Les environments ... */
;*---------------------------------------------------------------------*/
(init-the-global-environment!)
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/runtime/Eval/evmeaning.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* Le module */
*---------------------------------------------------------------------*/
Disabling user-inlining is strictly required in order
to avoid stack blow up in the evmeaning function.
*---------------------------------------------------------------------*/
* case-bounce ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* emit-bounced! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %inline-let ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %inline1 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* %inline2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-unbound ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-uninitialized ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning ... */
*---------------------------------------------------------------------*/
errors
deep local variables
mutable global variable
global variable
dynamic global variable
we change the value of the byte-code
because, now, the variable is bound
(set! <global> <value>)
(set! <dynamic-global> <value>)
la mutation de la troisieme variable locale
la mutation de la quatrieme variable locale
la mutation des variables locales profondes
conditional
(define <global> <var>)
first we bind the variable
second we evaluate it's body
bind-exit
funcall 0
This code is very sensitive to the compiler order. Because
of tail recursion, it is extremely important that the capture
for the stack (the variable !s). To enforce this order, we
procedure arity 0, traced
...untraced
untraced
untraced
untraced
untraced
procedure arity -1, traced
untraced
procedure arity -2, traced
untraced
procedure arity -3, traced
untraced
procedure arity -4, traced
untraced
untraced
unwind-protect
let (bindings are stored reversed!)
let*
or
and
letrec
with-handler
synchronize
synchronize/prelock
tailcall 0
tailcall 1
tailcall 4
unlinked global variable
inline code-op
unknown byte code
*---------------------------------------------------------------------*/
* evprocedure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-procedure? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-procedure! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-procedure-bcode ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-procedure-stack ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-procedure-args ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* update-eval-global! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-funcall-0 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-funcall-1 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-funcall-2 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-funcall-3 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-funcall-4 ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-tailcall-0-stack ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-tailcall-1-stack ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-tailcall-2-stack ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-tailcall-3-stack ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-tailcall-4-stack ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* eval-apply ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-make-traced-4procedure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-make-4procedure ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-push-fxargs ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* evmeaning-push-vaargs ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* Les environments ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / runtime / Eval / evmeaning.scm * /
* Author : * /
* Creation : We d Aug 4 10:48:41 1993 * /
* Last change : Sat Jul 20 10:44:40 2013 ( serrano ) * /
* The 's interpreter . * /
(module __evmeaning
(include "Eval/byte-code.sch")
(import __type
__error
__bigloo
__tvector
__structure
__tvector
__bexit
__bignum
__os
__bit
__param
__bexit
__object
__thread
__rgc
__r4_numbers_6_5
__r4_numbers_6_5_fixnum
__r4_numbers_6_5_flonum
__r4_numbers_6_5_flonum_dtoa
__r4_characters_6_6
__r4_equivalence_6_2
__r4_booleans_6_1
__r4_symbols_6_4
__r4_strings_6_7
__r4_pairs_and_lists_6_3
__r4_input_6_10_2
__r4_control_features_6_9
__r4_vectors_6_8
__r4_ports_6_10_1
__r4_output_6_10_3
__progn
__evenv
__evcompile
__everror
__evmodule)
(export (evmeaning ::obj ::pair-nil ::dynamic-env))
(extern (%funcall-0::obj (::procedure)
"eval_funcall_0")
(%funcall-1::obj (::procedure ::obj)
"eval_funcall_1")
(%funcall-2::obj (::procedure ::obj ::obj)
"eval_funcall_2")
(%funcall-3::obj (::procedure ::obj ::obj ::obj)
"eval_funcall_3")
(%funcall-4::obj (::procedure ::obj ::obj ::obj ::obj)
"eval_funcall_4")
(%eval-apply::obj (::procedure ::obj)
"eval_apply"))
(java (class foreign
(method static %funcall-0::obj (::procedure)
"eval_funcall_0")
(method static %funcall-1::obj (::procedure ::obj)
"eval_funcall_1")
(method static %funcall-2::obj (::procedure ::obj ::obj)
"eval_funcall_2")
(method static %funcall-3::obj (::procedure ::obj ::obj ::obj)
"eval_funcall_3")
(method static %funcall-4::obj (::procedure ::obj ::obj ::obj ::obj)
"eval_funcall_4")
(method static %eval-apply::obj (::procedure ::obj)
"eval_apply")))
inlining is required for the same reason .
(option (set! *user-inlining?* #f)
( set ! * inlining - kfactor * ( lambda ( x ) 1 ) )
(set! *saw-register-allocation?* #t)
(set! *saw-register-allocation-max-size* 8000)))
(define-macro (case-bounce test . clauses)
(let* ((bounce '())
(r `(case ,test
,@(map (lambda (c)
(match-case c
(((bounce ?vars ((and (? integer?) ?n))) . ?body)
(let ((id (string->symbol
(string-append
"evmeaning-bounce-"
(integer->string n)))))
(set! bounce
(cons `(define (,id ,@vars) ,@body)
bounce))
`((,n) (,id ,@vars))))
(((bounce . ?-) . ?-)
(error 'case-bounce "Illegal clause" c))
(else
c)))
clauses))))
(putprop! 'case-bounce 'bouncing bounce)
r))
(define-macro (emit-bounced!)
`(begin ,@(getprop 'case-bounce 'bouncing)))
(define-macro (%with-inline body)
`(let ((type-check #t)
(a0 #unspecified))
,body))
(define-macro (%inline1 fun code stack denv . type)
(if (null? type)
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv)))
`(,fun a0))
(let ((pred (symbol-append (car type) '?)))
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv)))
(if (,pred a0)
(,fun a0)
(evtype-error (evcode-loc code) "eval" ',(car type) a0))))))
(define-macro (%inline2 fun code stack denv . type)
(if (null? type)
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv))
(a1 (evmeaning (evcode-ref ,code 3) ,stack ,denv)))
(,fun a0 a1))
(let ((pred (symbol-append (car type) '?)))
`(let ((a0 (evmeaning (evcode-ref ,code 2) ,stack ,denv))
(a1 (evmeaning (evcode-ref ,code 3) ,stack ,denv)))
(if (,pred a0)
(if (,pred a1)
(,fun a0 a1)
(evtype-error (evcode-loc code) "eval" ',(car type) a1))
(evtype-error (evcode-loc code) "eval" ',(car type) a0))))))
(define (evmeaning-unbound loc name mod)
(everror loc
"eval"
(if (evmodule? mod)
(format "Unbound variable (from module `~a')"
(evmodule-name mod))
"Unbound variable (from top-level)")
name))
(define (evmeaning-uninitialized loc name)
(everror loc "eval" "Uninitialized variable" name))
(define (evmeaning code stack denv)
(if (evcode? code)
(%with-inline
(case-bounce (evcode-op code)
((-2)
(apply everror (evcode-loc code) (evcode-ref code 0)))
((-1)
La seule constante : les ` vecteurs '
(evcode-ref code 0))
((0)
first local variable
(car stack))
((1)
second local variable
(cadr stack))
((2)
third local variable
(caddr stack))
((3)
fourth local variable
(cadddr stack))
((4)
(let ((offset (evcode-ref code 0)))
(do ((i 4 (+fx i 1))
(env (cddddr stack) (cdr env)))
((=fx i offset) (car env)))))
((5)
(__evmeaning_address-ref
(eval-global-value (evcode-ref code 0))))
((6)
(let* ((g (evcode-ref code 0))
(val (eval-global-value g)))
(if (eq? val #unspecified)
(let ((tag (eval-global-tag g)))
(if (or (=fx tag 3) (=fx tag 4))
(evmeaning-uninitialized
(evcode-loc code) (eval-global-name g))
val))
val)))
((bounce (code stack denv) (7))
(let* ((name (evcode-ref code 0))
(mod (evcode-ref code 1))
(global (evmodule-find-global mod name)))
(if (eval-global? global)
(begin
(evcode-op-set! code 6)
(evcode-set! code 0 global)
(eval-global-value global))
(evmeaning-unbound (evcode-loc code) name mod))))
((8)
(let ((var (evcode-ref code 0))
(val (evmeaning (evcode-ref code 1) stack denv)))
(update-eval-global! code var val)
(unspecified)))
((bounce (code stack denv) (9))
(let* ((name (evcode-ref code 0))
(value (evcode-ref code 1))
(mod (evcode-ref code 2))
(global (evmodule-find-global mod name)))
(if (eval-global? global)
(begin
(evcode-op-set! code 8)
(evcode-set! code 0 global)
(evcode-set! code 1 value)
(evmeaning code stack denv))
(evmeaning-unbound (evcode-loc code) name mod))))
((10)
la mutation de la premiere variable locale
(set-car! stack (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((11)
la mutation de la deuxieme variable locale
(set-car! (cdr stack) (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((12)
(set-car! (cddr stack) (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((13)
(set-car! (cdddr stack) (evmeaning (evcode-ref code 0) stack denv))
(unspecified))
((bounce (code stack denv) (14))
(let ((offset (evcode-ref code 0))
(value (evmeaning (evcode-ref code 1) stack denv)))
(do ((i 4 (+fx i 1))
(env (cddddr stack) (cdr env)))
((=fx i offset) (set-car! env value)))
(unspecified)))
((15)
(if (evmeaning (evcode-ref code 0) stack denv)
(evmeaning (evcode-ref code 1) stack denv)
(evmeaning (evcode-ref code 2) stack denv)))
((16)
sequence ( by construction , the length is at least 1 )
(let ((len (-fx (evcode-length code) 1)))
(let loop ((i 0))
(if (=fx i len)
(evmeaning (evcode-ref code i) stack denv)
(begin
(evmeaning (evcode-ref code i) stack denv)
(loop (+fx i 1)))))))
((bounce (code stack denv) (17))
(let ((var (evcode-ref code 0))
(val (evcode-ref code 1))
(mod (evcode-ref code 2)))
(let ((v (evmodule-find-global mod var)))
(if (eval-global? v)
(case (eval-global-tag v)
((0)
(everror (evcode-loc code) "eval"
"Compiled read-only variable cannot be redefined"
var))
((1)
(evwarning (evcode-loc code) "eval"
"\nRedefinition of compiled variable -- "
var)
(update-eval-global! code v (evmeaning val '() denv)))
((2)
(update-eval-global! code v (evmeaning val '() denv)))
((3)
(update-eval-global! code v (evmeaning val '() denv))
(eval-global-tag-set! v 2))
((4)
(update-eval-global! code v (evmeaning val '() denv))
(eval-global-tag-set! v 5))
(else
(everror (evcode-loc code) "eval"
"Read-only variable cannot be redefined"
var)))
(let* ((loc (evcode-loc code))
(g (make-eval-global var (eval-module) loc)))
(evmodule-bind-global! mod var g loc)
(let ((value (evmeaning val '() denv)))
(set-eval-global-value! g value))))
var)))
((bounce (code stack denv) (18))
(bind-exit (__dummy__)
((evmeaning (evcode-ref code 0) stack denv) __dummy__)))
((bounce (code) (25))
l'appel de fonction de compilee anonyme d'arite 0
((evcode-ref code 0)))
((bounce (code stack denv) (26))
l'appel de fonction de compilee anonyme d'arite 1
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv)))
(fun a0)))
((bounce (code stack denv) (27))
l'appel de fonction de compilee anonyme d'arite 2
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv))
(a1 (evmeaning (evcode-ref code 2) stack denv)))
(fun a0 a1)))
((bounce (code stack denv) (28))
l'appel de fonction de compilee anonyme d'arite 3
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv))
(a1 (evmeaning (evcode-ref code 2) stack denv))
(a2 (evmeaning (evcode-ref code 3) stack denv)))
(fun a0 a1 a2)))
((bounce (code stack denv) (29))
l'appel de fonction de compilee anonyme d'arite 4
(let* ((fun (evcode-ref code 0))
(a0 (evmeaning (evcode-ref code 1) stack denv))
(a1 (evmeaning (evcode-ref code 2) stack denv))
(a2 (evmeaning (evcode-ref code 3) stack denv))
(a3 (evmeaning (evcode-ref code 4) stack denv)))
(fun a0 a1 a2 a3)))
((bounce (code stack denv) (30))
l'appel de fonction de compilee anonyme d'arite plus que 4
(let ((eargs (map (lambda (x)
(evmeaning x stack denv))
(evcode-ref code 1))))
(apply (evcode-ref code 0) eargs)))
((31)
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-0 code stack denv fun)))
((32)
funcall 1
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-1 code stack denv fun)))
((33)
funcall 2
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-2 code stack denv fun)))
((34)
funcall 3
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-3 code stack denv fun)))
((35)
funcall 4
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(evmeaning-funcall-4 code stack denv fun)))
((bounce (code stack denv) (36))
funcall > 4
(let* ((name (evcode-ref code 0))
(fun (evmeaning (evcode-ref code 1) stack denv)))
(let loop ((args (evcode-ref code 2))
(new '())
(len 0))
(if (null? args)
(begin
($env-set-trace-location denv (evcode-loc code))
(eval-apply code name fun len (reverse! new)))
(loop (cdr args)
(cons (evmeaning (car args) stack denv) new)
(+fx 1 len))))))
((bounce (code stack denv) (37))
variable are order 0 for the body ( the variable ! b ) , and 1
explicitly use a cascade of " if"s
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda ()
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b !s !denv)))
($env-pop-trace !denv)
res))))
0
body
stack)))
((bounce (code stack denv) (42))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda ()
(let ((!b body))
(evmeaning !b stack denv)))
0
body
stack)))
((bounce (code stack denv) (38))
procedure arity 1 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b (cons x !s) !denv)))
($env-pop-trace !denv)
res))))
1
body
stack)))
((bounce (code stack denv) (43))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x)
(let ((!b body))
(evmeaning !b (cons x stack) denv)))
1
body
stack)))
((bounce (code stack denv) (39))
procedure arity 2 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((r (evmeaning !b (cons x (cons y !s)) !denv)))
($env-pop-trace !denv)
r))))
2
body
stack)))
((bounce (code stack denv) (44))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y)
(let ((!b body))
(evmeaning !b (cons x (cons y stack)) denv)))
2
body
stack)))
((bounce (code stack denv) (40))
procedure arity 3 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y z)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b
(cons x
(cons y
(cons z !s)))
!denv)))
($env-pop-trace !denv)
res))))
3
body
stack)))
((bounce (code stack denv) (45))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y z)
(let ((!b body))
(evmeaning !b (cons x (cons y (cons z stack))) denv)))
3
body
stack)))
((bounce (code stack denv) (41))
procedure arity 4 , traced
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y z t)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning
!b
(cons x
(cons y
(cons z
(cons t !s))))
!denv)))
($env-pop-trace !denv)
res))))
4
body
stack)))
((bounce (code stack denv) (46))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y z t)
(let ((!b body))
(evmeaning !b
(cons x (cons y (cons z (cons t stack))))
denv)))
4
body
stack)))
((bounce (code stack denv) (47))
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b (cons x !s) !denv)))
($env-pop-trace !denv)
res))))
-1
body
stack)))
((bounce (code stack denv) (51))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda x
(let ((!b body))
(evmeaning !b (cons x stack) denv)))
-1
body
stack)))
((bounce (code stack denv) (48))
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x . y)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((r (evmeaning !b (cons x (cons y !s)) !denv)))
($env-pop-trace !denv)
r))))
-2
body
stack)))
((bounce (code stack denv) (52))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x . y)
(let ((!b body))
(evmeaning !b (cons x (cons y stack)) denv)))
-2
body
stack)))
((bounce (code stack denv) (49))
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y . z)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning !b
(cons x
(cons y
(cons z !s)))
!denv)))
($env-pop-trace !denv)
res))))
-3
body
stack)))
((bounce (code stack denv) (53))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y . z)
(let ((!b body))
(evmeaning !b
(cons x (cons y (cons z stack)))
denv)))
-3
body
stack)))
((bounce (code stack denv) (50))
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(loc (evcode-loc code)))
(evmeaning-procedure!
(lambda (x y z . t)
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((res (evmeaning
!b
(cons x
(cons y
(cons z
(cons t
!s))))
!denv)))
($env-pop-trace !denv)
res))))
-4
body
stack)))
((bounce (code stack denv) (54))
(let ((body (evcode-ref code 0)))
(evmeaning-procedure!
(lambda (x y z . t)
(let ((!b body))
(evmeaning
!b
(cons x (cons y (cons z (cons t stack))))
denv)))
-4
body
stack)))
((55)
procedure arity > 4 arguments , traced
(evmeaning-make-traced-4procedure code stack denv))
((56)
(evmeaning-make-4procedure code stack denv))
((bounce (code stack denv) (64))
(let ((body (evcode-ref code 0))
(protect (evcode-ref code 1)))
(unwind-protect (evmeaning body stack denv)
(evmeaning protect stack denv))))
((65)
(let loop ((vals (evcode-ref code 1))
(env stack))
(if (null? vals)
(evmeaning (evcode-ref code 0) env denv)
(let ((v (evmeaning (car vals) stack denv)))
(loop (cdr vals) (cons v env))))))
((66)
(let loop ((vals (evcode-ref code 1))
(stack stack))
(if (null? vals)
(evmeaning (evcode-ref code 0) stack denv)
(loop (cdr vals)
(cons (evmeaning (car vals) stack denv) stack)))))
((bounce (code stack denv) (67))
(let ((len (evcode-length code)))
(let loop ((i 0))
(if (<fx i len)
(or (evmeaning (evcode-ref code i) stack denv)
(loop (+fx i 1)))
#f))))
((bounce (code stack denv) (68))
(let ((len (evcode-length code)))
(let loop ((i 0)
(l #t))
(if (<fx i len)
(let ((l (evmeaning (evcode-ref code i) stack denv)))
(and l (loop (+fx i 1) l)))
l))))
((bounce (code stack denv) (70))
(let* ((vals (evcode-ref code 1))
(stack2 (append (make-list (length vals)) stack)))
(let loop ((vals vals)
(stack3 stack2))
(if (null? vals)
(evmeaning (evcode-ref code 0) stack2 denv)
(begin
(set-car! stack3 (evmeaning (car vals) stack2 denv))
(loop (cdr vals) (cdr stack3)))))))
((bounce (code stack denv) (71))
(let* ((handler (evcode-ref code 0))
(body (evcode-ref code 1))
(ehandler (evmeaning handler stack denv))
(loc (evcode-loc code)))
(cond
((not (procedure? ehandler))
(evtype-error loc "eval" "procedure" ehandler))
((correct-arity? ehandler 1)
(with-handler ehandler (evmeaning body stack denv)))
(else
(evarity-error loc "with-handler" 1 ($procedure-arity ehandler))))))
((bounce (code stack denv) (175))
(let* ((mutex (evcode-ref code 0))
(body (evcode-ref code 1))
(m (evmeaning mutex stack denv)))
(if (mutex? m)
(synchronize m
(evmeaning body stack denv))
(evtype-error (evcode-loc code) "synchronize" "mutex" m))))
((bounce (code stack denv) (176))
(let* ((mutex (evcode-ref code 0))
(prelock (evcode-ref code 1))
(body (evcode-ref code 2))
(m (evmeaning mutex stack denv)))
(if (mutex? m)
(synchronize m
:prelock (evmeaning prelock stack denv)
(evmeaning body stack denv))
(evtype-error (evcode-loc code) "synchronize" "mutex" m))))
((131)
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-0-stack code stack denv fun)
denv)
(evmeaning-funcall-0 code stack denv fun))))
((132)
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-1-stack code stack denv fun)
denv)
(evmeaning-funcall-1 code stack denv fun))))
((133)
tailcall 2
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-2-stack code stack denv fun)
denv)
(evmeaning-funcall-2 code stack denv fun))))
((134)
tailcall 3
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-3-stack code stack denv fun)
denv)
(evmeaning-funcall-3 code stack denv fun))))
((135)
(let ((fun (evmeaning (evcode-ref code 1) stack denv)))
(if (evmeaning-procedure? fun)
(evmeaning (evmeaning-procedure-bcode fun)
(evmeaning-tailcall-4-stack code stack denv fun)
denv)
(evmeaning-funcall-4 code stack denv fun))))
((136)
tailcall > 4
(let* ((name (evcode-ref code 0))
(fun (evmeaning (evcode-ref code 1) stack denv))
(loc (evcode-loc code)))
(let loop ((args (evcode-ref code 2))
(new '())
(len 0))
(if (null? args)
(if (evmeaning-procedure? fun)
(let* ((fmls (evmeaning-procedure-args fun))
(stack (evmeaning-procedure-stack fun))
(wen (reverse! new))
(e2 (if (>=fx fmls 0)
(evmeaning-push-fxargs name
loc
wen
fmls
stack)
(evmeaning-push-vaargs name
loc
wen
fmls
stack))))
(evmeaning (evmeaning-procedure-bcode fun)
e2
denv))
(eval-apply code name fun len (reverse! new)))
(loop (cdr args)
(cons (evmeaning (car args) stack denv) new)
(+fx 1 len))))))
((145 146)
(evcode-op-set! code (-fx (evcode-op code) 140))
(evcode-set! code 0 (evmodule-find-global
(evcode-ref code 1)
(evcode-ref code 0)))
(evmeaning code stack denv))
((147)
(%inline2 + code stack denv number))
((148)
(%inline2 - code stack denv number))
((149)
(%inline2 * code stack denv number))
((150)
(%inline2 / code stack denv number))
((151)
(%inline2 < code stack denv number))
((152)
(%inline2 > code stack denv number))
((153)
(%inline2 <= code stack denv number))
((154)
(%inline2 >= code stack denv number))
((155)
(%inline2 = code stack denv number))
((166)
(%inline2 +fx code stack denv fixnum))
((167)
(%inline2 -fx code stack denv fixnum))
((168)
(%inline2 *fx code stack denv fixnum))
((169)
(%inline2 /fx code stack denv fixnum))
((170)
(%inline2 <fx code stack denv fixnum))
((171)
(%inline2 >fx code stack denv fixnum))
((172)
(%inline2 <=fx code stack denv fixnum))
((173)
(%inline2 >=fx code stack denv fixnum))
((174)
(%inline2 =fx code stack denv fixnum))
((156)
(%inline2 eq? code stack denv))
((157)
(%inline2 cons code stack denv))
((158)
(%inline1 car code stack denv pair))
((159)
(%inline1 cdr code stack denv pair))
((160)
(let ((a0 (evmeaning (evcode-ref code 2) stack denv)))
(cond
((and (pair? a0) (pair? (cdr a0)))
(cadr a0))
((pair? a0)
(evtype-error (evcode-loc code)
(evcode-ref code 0)
"pair" (cdr a0)))
(else
(evtype-error (evcode-loc code)
(evcode-ref code 0)
"pair" a0)))))
(else
(everror (evcode-loc code) "eval" "unknown byte-code" code))))
code))
(emit-bounced!)
(define-struct evprocedure args bcode stack)
(define-inline (evmeaning-procedure? proc)
(and (procedure? proc) (evprocedure? (procedure-attr proc))))
(define-inline (evmeaning-procedure! proc args bcode stack)
(procedure-attr-set! proc (evprocedure args bcode stack))
proc)
(define-inline (evmeaning-procedure-bcode proc)
(evprocedure-bcode (procedure-attr proc)))
(define-inline (evmeaning-procedure-stack proc)
(evprocedure-stack (procedure-attr proc)))
(define-inline (evmeaning-procedure-args proc)
(evprocedure-args (procedure-attr proc)))
(define (update-eval-global! code var val)
(case (eval-global-tag var)
((0)
(everror (evcode-loc code) "set!" "read-only variable" (eval-global-name var)))
((1)
(__evmeaning_address-set! (eval-global-value var) val))
((2)
(set-eval-global-value! var val))
((3)
(set-eval-global-value! var val))
((4)
(set-eval-global-value! var val))
((5)
(everror (evcode-loc code) "set!" "read-only variable" (eval-global-name var)))))
(define (evmeaning-funcall-0 code stack denv fun)
(let ((name (evcode-ref code 0))
(loc (evcode-loc code)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" name "Not a procedure"))
((not (correct-arity? fun 0))
(evarity-error loc name 0 ($procedure-arity fun)))
(else
(%funcall-0 fun)))))
(define (evmeaning-funcall-1 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 1))
(evarity-error loc name 1 ($procedure-arity fun)))
(else
(%funcall-1 fun a0)))))
(define (evmeaning-funcall-2 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 2))
(evarity-error loc name 2 ($procedure-arity fun)))
(else
(%funcall-2 fun a0 a1)))))
(define (evmeaning-funcall-3 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 3))
(evarity-error loc name 3 ($procedure-arity fun)))
(else
(%funcall-3 fun a0 a1 a2)))))
(define (evmeaning-funcall-4 code stack denv fun)
(let* ((name (evcode-ref code 0))
(loc (evcode-loc code))
(a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv))
(a3 (evmeaning (evcode-ref code 5) stack denv)))
($env-set-trace-location denv loc)
(cond
((not (procedure? fun))
(everror loc "eval" "Not a procedure" name))
((not (correct-arity? fun 4))
(evarity-error loc name 4 ($procedure-arity fun)))
(else
(%funcall-4 fun a0 a1 a2 a3)))))
(define (evmeaning-tailcall-0-stack code stack denv fun)
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((0)
envd)
((-1)
(cons '() envd))
(else
(evarity-error loc (evcode-ref code 0) 0 arity)))))
(define (evmeaning-tailcall-1-stack code stack denv fun)
(let ((a0 (evmeaning (evcode-ref code 2) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((1)
(cons a0 envd))
((-1)
(cons (list a0) envd))
((-2)
(cons a0 (cons '() envd)))
(else
(evarity-error loc (evcode-ref code 0) 1 arity))))))
(define (evmeaning-tailcall-2-stack code stack denv fun)
(let* ((a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((2)
(cons a0 (cons a1 envd)))
((-1)
(cons (list a0 a1) envd))
((-2)
(cons a0 (cons (list a1) envd)))
((-3)
(cons a0 (cons a1 (cons '() envd))))
(else
(evarity-error loc (evcode-ref code 0) 2 arity))))))
(define (evmeaning-tailcall-3-stack code stack denv fun)
(let* ((a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((3)
(cons a0 (cons a1 (cons a2 envd))))
((-1)
(cons (list a0 a1 a2) envd))
((-2)
(cons a0 (cons (list a1 a2) envd)))
((-3)
(cons a0 (cons a1 (cons (list a2) envd))))
((-4)
(cons a0 (cons a1 (cons a2 (cons '() envd)))))
(else
(evarity-error loc (evcode-ref code 0) 3 arity))))))
(define (evmeaning-tailcall-4-stack code stack denv fun)
(let* ((a0 (evmeaning (evcode-ref code 2) stack denv))
(a1 (evmeaning (evcode-ref code 3) stack denv))
(a2 (evmeaning (evcode-ref code 4) stack denv))
(a3 (evmeaning (evcode-ref code 5) stack denv)))
(let* ((envd (evmeaning-procedure-stack fun))
(arity (evmeaning-procedure-args fun))
(loc (evcode-loc code)))
(when (symbol? (evcode-ref code 0))
($env-set-trace-name denv (evcode-ref code 0))
($env-set-trace-location denv loc))
(case arity
((4)
(cons a0 (cons a1 (cons a2 (cons a3 envd)))))
((-1)
(cons (list a0 a1 a2 a3) envd))
((-2)
(cons a0 (cons (list a1 a2 a3) envd)))
((-3)
(cons a0 (cons a1 (cons (list a2 a3) envd))))
((-4)
(cons a0 (cons a1 (cons a2 (cons (list a3) envd)))))
((-5)
(cons a0 (cons a1 (cons a2 (cons a3 (cons '() envd))))))
(else
(evarity-error loc (evcode-ref code 0) 4 arity))))))
(define-inline (eval-apply code name fun len args)
(cond
((not (procedure? fun))
(everror (evcode-loc code) "apply" "Not a procedure" name))
((not (correct-arity? fun len))
(evarity-error (evcode-loc code) name len ($procedure-arity fun)))
(else
(%eval-apply fun args))))
(define (evmeaning-make-traced-4procedure code stack denv)
(let ((body (evcode-ref code 0))
(where (evcode-ref code 1))
(formals (evcode-ref code 2))
(loc (evcode-loc code)))
(if (list? formals)
(let ((lf (length formals)))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((e2 (evmeaning-push-fxargs where code x lf !s)))
(let ((res (evmeaning !b e2 !denv)))
($env-pop-trace !denv)
res)))))
lf
body
stack))
(let ((lf (let loop ((formals formals)
(num -1))
(if (pair? formals)
(loop (cdr formals) (-fx num 1))
num))))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack)
(!denv::dynamic-env (current-dynamic-env)))
(let ()
($env-push-trace !denv where loc)
(let ((e2 (evmeaning-push-vaargs where code x lf !s)))
(let ((res (evmeaning !b e2 !denv)))
($env-pop-trace !denv)
res)))))
lf
body
stack)))))
(define (evmeaning-make-4procedure code stack denv)
(let ((body (evcode-ref code 0))
(formals (evcode-ref code 1)))
(if (list? formals)
(let ((lf (length formals)))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack))
(let ((e2 (evmeaning-push-fxargs x code x lf !s)))
(evmeaning !b e2 denv))))
lf
body
stack))
(let ((lf (let loop ((formals formals)
(num -1))
(if (pair? formals)
(loop (cdr formals) (-fx num 1))
num))))
(evmeaning-procedure!
(lambda x
(let ((!b body)
(!s stack))
(let ((e2 (evmeaning-push-vaargs x code x lf !s)))
(evmeaning !b e2 denv))))
lf
body
stack)))))
(define (evmeaning-push-fxargs name loc actuals num stack)
(let _loop_ ((a actuals)
(n num))
(cond
((=fx n 0)
(if (not (null? a))
(evarity-error loc name (length actuals) num)
stack))
((null? a)
(evarity-error loc name (length actuals) num))
(else
(cons (car a) (_loop_ (cdr a) (-fx n 1)))))))
(define (evmeaning-push-vaargs name loc actuals num stack)
(let _loop_ ((a actuals)
(n num))
(cond
((=fx n -1)
(cons a stack))
((null? a)
(evarity-error loc name (length actuals) num))
(else
(cons (car a) (_loop_ (cdr a) (+fx n 1)))))))
(init-the-global-environment!)
|
72fd87b292b131a6d677a41ab9e942cd903fb1d50c9edf1db7714e8b398aeace | racket/plot | plot3d-untyped.rkt | #lang racket/base
(require "plot3d.rkt" ; must visit
racket/contract
racket/class
racket/draw
(only-in pict pict?)
(for-syntax racket/base "plot3d-evil-box.rkt")
"../../utils.rkt"
"../common/contract.rkt"
"../common/nonrenderer.rkt"
"../plot3d/renderer.rkt")
(provide
(contract-out
[untyped-plot3d/dc
(->* [(treeof (or/c renderer3d? nonrenderer?))
(is-a?/c dc<%>)
real?
real?
(>=/c 0)
(>=/c 0)]
[#:x-min (or/c real? #f)
#:x-max (or/c real? #f)
#:y-min (or/c real? #f)
#:y-max (or/c real? #f)
#:z-min (or/c real? #f)
#:z-max (or/c real? #f)
#:angle real?
#:altitude real?
#:title (or/c string? pict? #f)
#:x-label (or/c string? pict? #f)
#:y-label (or/c string? pict? #f)
#:z-label (or/c string? pict? #f)
#:aspect-ratio (or/c (and/c rational? positive?) #f)
#:legend-anchor legend-anchor/c]
plot-metrics-object/c)]))
(define-syntax untyped-plot3d/dc
(make-rename-transformer (unbox plot3d/dc-box)))
| null | https://raw.githubusercontent.com/racket/plot/c4126001f2c609e36c3aa12f300e9c673ab1a806/plot-lib/plot/private/no-gui/plot3d-untyped.rkt | racket | must visit | #lang racket/base
racket/contract
racket/class
racket/draw
(only-in pict pict?)
(for-syntax racket/base "plot3d-evil-box.rkt")
"../../utils.rkt"
"../common/contract.rkt"
"../common/nonrenderer.rkt"
"../plot3d/renderer.rkt")
(provide
(contract-out
[untyped-plot3d/dc
(->* [(treeof (or/c renderer3d? nonrenderer?))
(is-a?/c dc<%>)
real?
real?
(>=/c 0)
(>=/c 0)]
[#:x-min (or/c real? #f)
#:x-max (or/c real? #f)
#:y-min (or/c real? #f)
#:y-max (or/c real? #f)
#:z-min (or/c real? #f)
#:z-max (or/c real? #f)
#:angle real?
#:altitude real?
#:title (or/c string? pict? #f)
#:x-label (or/c string? pict? #f)
#:y-label (or/c string? pict? #f)
#:z-label (or/c string? pict? #f)
#:aspect-ratio (or/c (and/c rational? positive?) #f)
#:legend-anchor legend-anchor/c]
plot-metrics-object/c)]))
(define-syntax untyped-plot3d/dc
(make-rename-transformer (unbox plot3d/dc-box)))
|
63cbc4375654e9935aaa0bf7babda13a5e810317eb1e9364c4d54f6c70df8d03 | grzm/awyeah-api | http_client.clj | Copyright ( c )
Heavily inspired by congitect.http - client , Copyright ( c ) Cognitect , Inc.
;; All rights reserved.
(ns com.grzm.awyeah.http-client
(:require
[clojure.core.async :refer [put!] :as a]
[clojure.spec.alpha :as s]
[com.grzm.awyeah.http-client.client :as client]
[com.grzm.awyeah.http-client.specs])
(:import
(clojure.lang ExceptionInfo)
(java.net URI)
(java.net.http HttpClient
HttpClient$Redirect
HttpHeaders
HttpRequest
HttpRequest$Builder
HttpRequest$BodyPublishers
HttpResponse
HttpResponse$BodyHandlers)
(java.nio ByteBuffer)
(java.time Duration)
(java.util.function Function)))
(set! *warn-on-reflection* true)
(defn submit
"Submit an http request, channel will be filled with response. Returns ch.
Request map:
:server-name string
:server-port integer
:uri string
:query-string string, optional
:request-method :get/:post/:put/:head
:scheme :http or :https
:headers map from downcased string to string
:body ByteBuffer, optional
:com.grzm.awyeah.http-client/timeout-msec opt, total request send/receive timeout
:com.grzm.awyeah.http-client/meta opt, data to be added to the response map
content-type must be specified in the headers map
content-length is derived from the ByteBuffer passed to body
Response map:
:status integer HTTP status code
:body ByteBuffer, optional
:header map from downcased string to string
:com.grzm.awyeah.http-client/meta opt, data from the request
On error, response map is per cognitect.anomalies"
([client request]
(submit client request (a/chan 1)))
([client request ch]
(s/assert ::submit-request request)
(client/submit client request ch)))
(def method-string
{:get "GET"
:post "POST"
:put "PUT"
:head "HEAD"
:delete "DELETE"
:path "PATCH"})
(defn byte-buffer->byte-array
[^ByteBuffer bbuf]
(.rewind bbuf)
(let [arr (byte-array (.remaining bbuf))]
(.get bbuf arr)
arr))
(defn flatten-headers [headers]
(->> headers
(mapcat (fn [[nom val]]
(if (coll? val)
(map (fn [v] [(name nom) v]) val)
[[(name nom) val]])))))
;; "host" is a restricted header.
;; The host header is part of the AWS signed headers signature,
;; so it's included in the list of headers for request processing,
but we let the java.net.http HttpRequest assign the host header
from the URI rather than setting it directly .
(def restricted-headers #{"host"})
(defn add-headers
[^HttpRequest$Builder builder headers]
(doseq [[nom val] (->> (flatten-headers headers)
(remove (fn [[nom _]] (restricted-headers nom))))]
(.header builder nom val))
builder)
(defn map->http-request
[{:keys [scheme server-name server-port uri query-string
request-method headers body]
:or {scheme "https"}
:as m}]
(let [uri (URI. (str (name scheme)
"://"
server-name
(some->> server-port (str ":"))
uri
(some->> query-string (str "?"))))
method (method-string request-method)
bp (if body
(HttpRequest$BodyPublishers/ofByteArray (byte-buffer->byte-array body))
(HttpRequest$BodyPublishers/noBody))
builder (-> (HttpRequest/newBuilder uri)
(.method ^String method bp))]
(when (seq headers)
(add-headers builder headers))
(when (::timeout-msec m)
(.timeout builder (Duration/ofMillis (::timeout-msec m))))
(.build builder)))
(defn error->anomaly [^Throwable t]
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (.getMessage t)
::throwable t})
(defn header-map [^HttpHeaders headers]
(->> headers
(.map)
(map (fn [[k v]] [k (if (< 1 (count v))
(into [] v)
(first v))]))
(into {})))
(defn response-body?
[^HttpRequest http-request]
((complement #{"HEAD"}) (.method http-request)))
(defn response-map
[^HttpRequest http-request ^HttpResponse http-response]
(let [body (when (response-body? http-request)
(.body http-response))]
(cond-> {:status (.statusCode http-response)
:headers (header-map (.headers http-response))}
body (assoc :body (ByteBuffer/wrap body)))))
(defrecord Client
[^HttpClient http-client pending-ops pending-ops-limit]
client/Client
(-submit [_ request ch]
(if (< pending-ops-limit (swap! pending-ops inc))
(do
(put! ch (merge {:cognitect.anomalies/category :cognitect.anomalies/busy
:cognitect.anomalies/message (str "Ops limit reached: " pending-ops-limit)
:pending-ops-limit pending-ops-limit}
(select-keys request [::meta])))
(swap! pending-ops dec))
(try
(let [http-request (map->http-request request)]
(-> (.sendAsync http-client http-request (HttpResponse$BodyHandlers/ofByteArray))
(.thenApply
(reify Function
(apply [_ http-response]
(put! ch (merge (response-map http-request http-response)
(select-keys request [::meta]))))))
(.exceptionally
(reify Function
(apply [_ e]
(let [cause (.getCause ^Exception e)
t (if (instance? ExceptionInfo cause) cause e)]
(put! ch (merge (error->anomaly t) (select-keys request [::meta]))))))))
(swap! pending-ops dec))
(catch Throwable t
(put! ch (merge (error->anomaly t) (select-keys request [::meta])))
(swap! pending-ops dec))))
ch))
(defn create
[{:keys [connect-timeout-msecs
pending-ops-limit]
:or {connect-timeout-msecs 5000
pending-ops-limit 64}
:as _config}]
(let [http-client (.build (-> (HttpClient/newBuilder)
(.connectTimeout (Duration/ofMillis connect-timeout-msecs))
(.followRedirects HttpClient$Redirect/NORMAL)))]
(->Client http-client (atom 0) pending-ops-limit)))
(defn stop
"no-op. Implemented for compatibility"
[^Client _client])
| null | https://raw.githubusercontent.com/grzm/awyeah-api/1810bf624da2be58c77813106a1d51e32db11690/src/com/grzm/awyeah/http_client.clj | clojure | All rights reserved.
"host" is a restricted header.
The host header is part of the AWS signed headers signature,
so it's included in the list of headers for request processing, | Copyright ( c )
Heavily inspired by congitect.http - client , Copyright ( c ) Cognitect , Inc.
(ns com.grzm.awyeah.http-client
(:require
[clojure.core.async :refer [put!] :as a]
[clojure.spec.alpha :as s]
[com.grzm.awyeah.http-client.client :as client]
[com.grzm.awyeah.http-client.specs])
(:import
(clojure.lang ExceptionInfo)
(java.net URI)
(java.net.http HttpClient
HttpClient$Redirect
HttpHeaders
HttpRequest
HttpRequest$Builder
HttpRequest$BodyPublishers
HttpResponse
HttpResponse$BodyHandlers)
(java.nio ByteBuffer)
(java.time Duration)
(java.util.function Function)))
(set! *warn-on-reflection* true)
(defn submit
"Submit an http request, channel will be filled with response. Returns ch.
Request map:
:server-name string
:server-port integer
:uri string
:query-string string, optional
:request-method :get/:post/:put/:head
:scheme :http or :https
:headers map from downcased string to string
:body ByteBuffer, optional
:com.grzm.awyeah.http-client/timeout-msec opt, total request send/receive timeout
:com.grzm.awyeah.http-client/meta opt, data to be added to the response map
content-type must be specified in the headers map
content-length is derived from the ByteBuffer passed to body
Response map:
:status integer HTTP status code
:body ByteBuffer, optional
:header map from downcased string to string
:com.grzm.awyeah.http-client/meta opt, data from the request
On error, response map is per cognitect.anomalies"
([client request]
(submit client request (a/chan 1)))
([client request ch]
(s/assert ::submit-request request)
(client/submit client request ch)))
(def method-string
{:get "GET"
:post "POST"
:put "PUT"
:head "HEAD"
:delete "DELETE"
:path "PATCH"})
(defn byte-buffer->byte-array
[^ByteBuffer bbuf]
(.rewind bbuf)
(let [arr (byte-array (.remaining bbuf))]
(.get bbuf arr)
arr))
(defn flatten-headers [headers]
(->> headers
(mapcat (fn [[nom val]]
(if (coll? val)
(map (fn [v] [(name nom) v]) val)
[[(name nom) val]])))))
but we let the java.net.http HttpRequest assign the host header
from the URI rather than setting it directly .
(def restricted-headers #{"host"})
(defn add-headers
[^HttpRequest$Builder builder headers]
(doseq [[nom val] (->> (flatten-headers headers)
(remove (fn [[nom _]] (restricted-headers nom))))]
(.header builder nom val))
builder)
(defn map->http-request
[{:keys [scheme server-name server-port uri query-string
request-method headers body]
:or {scheme "https"}
:as m}]
(let [uri (URI. (str (name scheme)
"://"
server-name
(some->> server-port (str ":"))
uri
(some->> query-string (str "?"))))
method (method-string request-method)
bp (if body
(HttpRequest$BodyPublishers/ofByteArray (byte-buffer->byte-array body))
(HttpRequest$BodyPublishers/noBody))
builder (-> (HttpRequest/newBuilder uri)
(.method ^String method bp))]
(when (seq headers)
(add-headers builder headers))
(when (::timeout-msec m)
(.timeout builder (Duration/ofMillis (::timeout-msec m))))
(.build builder)))
(defn error->anomaly [^Throwable t]
{:cognitect.anomalies/category :cognitect.anomalies/fault
:cognitect.anomalies/message (.getMessage t)
::throwable t})
(defn header-map [^HttpHeaders headers]
(->> headers
(.map)
(map (fn [[k v]] [k (if (< 1 (count v))
(into [] v)
(first v))]))
(into {})))
(defn response-body?
[^HttpRequest http-request]
((complement #{"HEAD"}) (.method http-request)))
(defn response-map
[^HttpRequest http-request ^HttpResponse http-response]
(let [body (when (response-body? http-request)
(.body http-response))]
(cond-> {:status (.statusCode http-response)
:headers (header-map (.headers http-response))}
body (assoc :body (ByteBuffer/wrap body)))))
(defrecord Client
[^HttpClient http-client pending-ops pending-ops-limit]
client/Client
(-submit [_ request ch]
(if (< pending-ops-limit (swap! pending-ops inc))
(do
(put! ch (merge {:cognitect.anomalies/category :cognitect.anomalies/busy
:cognitect.anomalies/message (str "Ops limit reached: " pending-ops-limit)
:pending-ops-limit pending-ops-limit}
(select-keys request [::meta])))
(swap! pending-ops dec))
(try
(let [http-request (map->http-request request)]
(-> (.sendAsync http-client http-request (HttpResponse$BodyHandlers/ofByteArray))
(.thenApply
(reify Function
(apply [_ http-response]
(put! ch (merge (response-map http-request http-response)
(select-keys request [::meta]))))))
(.exceptionally
(reify Function
(apply [_ e]
(let [cause (.getCause ^Exception e)
t (if (instance? ExceptionInfo cause) cause e)]
(put! ch (merge (error->anomaly t) (select-keys request [::meta]))))))))
(swap! pending-ops dec))
(catch Throwable t
(put! ch (merge (error->anomaly t) (select-keys request [::meta])))
(swap! pending-ops dec))))
ch))
(defn create
[{:keys [connect-timeout-msecs
pending-ops-limit]
:or {connect-timeout-msecs 5000
pending-ops-limit 64}
:as _config}]
(let [http-client (.build (-> (HttpClient/newBuilder)
(.connectTimeout (Duration/ofMillis connect-timeout-msecs))
(.followRedirects HttpClient$Redirect/NORMAL)))]
(->Client http-client (atom 0) pending-ops-limit)))
(defn stop
"no-op. Implemented for compatibility"
[^Client _client])
|
015c9aa70591987691213d569b5981fc6f18eb6fc96f2eb76d8395ba3e799907 | weavery/sworn | WebAssembly.mli | (* This is free and unencumbered software released into the public domain. *)
val compile_program : SWIR.program -> Wasm.Ast.module_
| null | https://raw.githubusercontent.com/weavery/sworn/2a2f86223fafa6075122292a09c11dc15a75ff91/lib/WebAssembly/WebAssembly.mli | ocaml | This is free and unencumbered software released into the public domain. |
val compile_program : SWIR.program -> Wasm.Ast.module_
|
e2cced79f280bfe1f30c5cee3ca0fa15ce3f048d22e212e1365137bee3ac02a7 | silviucpp/erlkaf | erlkaf_utils.erl | -module(erlkaf_utils).
-export([
get_priv_path/1,
get_env/1,
get_env/2,
lookup/2,
lookup/3,
append_props/2,
to_binary/1,
safe_call/2,
safe_call/3,
call_stats_callback/3,
parralel_exec/2
]).
get_priv_path(File) ->
case code:priv_dir(erlkaf) of
{error, bad_name} ->
Ebin = filename:dirname(code:which(?MODULE)),
filename:join([filename:dirname(Ebin), "priv", File]);
Dir ->
filename:join(Dir, File)
end.
get_env(Key) ->
get_env(Key, undefined).
get_env(Key, Default) ->
case application:get_env(erlkaf, Key) of
undefined ->
Default;
{ok, Val} ->
Val
end.
lookup(Key, List) ->
lookup(Key, List, undefined).
lookup(Key, List, Default) ->
case lists:keyfind(Key, 1, List) of
{Key, Result}
-> Result;
false ->
Default
end.
append_props(L1, [{K, _} = H|T]) ->
case lookup(K, L1) of
undefined ->
append_props([H|L1], T);
_ ->
append_props(L1, T)
end;
append_props(L1, []) ->
L1.
to_binary(V) when is_binary(V) ->
V;
to_binary(V) when is_list(V) ->
list_to_binary(V);
to_binary(V) when is_atom(V) ->
atom_to_binary(V, utf8);
to_binary(V) when is_integer(V) ->
integer_to_binary(V);
to_binary(V) when is_float(V) ->
float_to_bin(V).
float_to_bin(Value) ->
float_to_binary(Value, [{decimals, 8}, compact]).
safe_call(Receiver, Message) ->
safe_call(Receiver, Message, 5000).
safe_call(Receiver, Message, Timeout) ->
try
gen_server:call(Receiver, Message, Timeout)
catch
exit:{noproc, _} ->
{error, not_started};
_: Exception ->
{error, Exception}
end.
call_stats_callback(undefined, _ClientId, _Stats) ->
ok;
call_stats_callback(C, ClientId, Stats) when is_function(C, 2) ->
C(ClientId, Stats);
call_stats_callback(C, ClientId, Stats) ->
C:stats_callback(ClientId, Stats).
parralel_exec(Fun, List) ->
Parent = self(),
Pids = [spawn_link(fun() -> Fun(E), Parent ! {self(), done} end) || E <- List],
[receive {Pid, done} -> ok end || Pid <- Pids],
ok.
| null | https://raw.githubusercontent.com/silviucpp/erlkaf/375fec8b3c9d0f96b1c5bd31a15b7e37ff2bff25/src/erlkaf_utils.erl | erlang | -module(erlkaf_utils).
-export([
get_priv_path/1,
get_env/1,
get_env/2,
lookup/2,
lookup/3,
append_props/2,
to_binary/1,
safe_call/2,
safe_call/3,
call_stats_callback/3,
parralel_exec/2
]).
get_priv_path(File) ->
case code:priv_dir(erlkaf) of
{error, bad_name} ->
Ebin = filename:dirname(code:which(?MODULE)),
filename:join([filename:dirname(Ebin), "priv", File]);
Dir ->
filename:join(Dir, File)
end.
get_env(Key) ->
get_env(Key, undefined).
get_env(Key, Default) ->
case application:get_env(erlkaf, Key) of
undefined ->
Default;
{ok, Val} ->
Val
end.
lookup(Key, List) ->
lookup(Key, List, undefined).
lookup(Key, List, Default) ->
case lists:keyfind(Key, 1, List) of
{Key, Result}
-> Result;
false ->
Default
end.
append_props(L1, [{K, _} = H|T]) ->
case lookup(K, L1) of
undefined ->
append_props([H|L1], T);
_ ->
append_props(L1, T)
end;
append_props(L1, []) ->
L1.
to_binary(V) when is_binary(V) ->
V;
to_binary(V) when is_list(V) ->
list_to_binary(V);
to_binary(V) when is_atom(V) ->
atom_to_binary(V, utf8);
to_binary(V) when is_integer(V) ->
integer_to_binary(V);
to_binary(V) when is_float(V) ->
float_to_bin(V).
float_to_bin(Value) ->
float_to_binary(Value, [{decimals, 8}, compact]).
safe_call(Receiver, Message) ->
safe_call(Receiver, Message, 5000).
safe_call(Receiver, Message, Timeout) ->
try
gen_server:call(Receiver, Message, Timeout)
catch
exit:{noproc, _} ->
{error, not_started};
_: Exception ->
{error, Exception}
end.
call_stats_callback(undefined, _ClientId, _Stats) ->
ok;
call_stats_callback(C, ClientId, Stats) when is_function(C, 2) ->
C(ClientId, Stats);
call_stats_callback(C, ClientId, Stats) ->
C:stats_callback(ClientId, Stats).
parralel_exec(Fun, List) ->
Parent = self(),
Pids = [spawn_link(fun() -> Fun(E), Parent ! {self(), done} end) || E <- List],
[receive {Pid, done} -> ok end || Pid <- Pids],
ok.
| |
cb6fef7780112f18e38294685baf1531e2f0981585d3a31be3ef2fd9c2b8ffa5 | mattjbray/ocaml-decoders | main.ml | open OUnit2
module M = Msgpck
let m_to_str m = M.StringBuf.to_string m |> Buffer.contents
let decoders_suite =
let open Decoders_msgpck.Decode in
let decoder_test ~decoder ~input ~expected _test_ctxt =
match decode_string decoder input with
| Ok value ->
assert_equal value expected
| Error error ->
assert_string (Format.asprintf "%a" pp_error error)
in
"decoders"
>::: [ "list string"
>:: decoder_test
~decoder:(list string)
~input:(m_to_str (M.List [ M.String "hello"; M.String "world" ]))
~expected:[ "hello"; "world" ]
; "field_opt present"
>:: decoder_test
~decoder:(field_opt "optional" string)
~input:
(m_to_str (M.Map [ (M.String "optional", M.String "hello") ]))
~expected:(Some "hello")
; "field_opt missing"
>:: decoder_test
~decoder:(field_opt "optional" string)
~input:
(m_to_str (M.Map [ (M.String "missing", M.String "hello") ]))
~expected:None
; ( "field_opt decode error"
>:: fun _ ->
match
decode_string
(field_opt "optional" string)
(m_to_str (M.Map [ (M.String "optional", M.Int 123) ]))
with
| Ok _ ->
assert_string "expected decode error"
| Error e ->
assert_equal
~printer:CCFun.id
{|in field "optional": Expected a string, but got 123|}
(Format.asprintf "%a" pp_error e) )
; "int32 conversion"
>:: decoder_test
~decoder:int
~input:(m_to_str (M.Int32 32l))
~expected:32
; "int64 conversion"
>:: decoder_test
~decoder:int
~input:(m_to_str (M.Int64 525252L))
~expected:525252
; "int64 helper"
>:: decoder_test
~decoder:int64
~input:(m_to_str (M.Int64 Int64.max_int))
~expected:Int64.max_int
; ( "int64 overflow"
>:: fun _ ->
match decode_string int (m_to_str (M.Int64 Int64.max_int)) with
| Ok v ->
assert_string (Printf.sprintf "expected decode error, got %d" v)
| Error _e ->
() )
; "pick1"
>:: decoder_test
~decoder:
(pick
[ ( "case_x"
, let* _x = field "x" null in
succeed
(let+ v = field "val" int in
`Int v ) )
; ( "case_y"
, let* _y = field "y" null in
succeed
(let+ v = field "val" float in
`Float v ) )
] )
~input:
(m_to_str
(M.Map [ (M.String "x", M.Nil); (M.String "val", M.Int 42) ]) )
~expected:(`Int 42)
; "pick2"
>:: decoder_test
~decoder:
(pick
[ ( "case_x"
, let* _x = field "x" null in
succeed
(let+ v = field "val" int in
`Int v ) )
; ( "case_y"
, let* _y = field "y" null in
succeed
(let+ v = field "val" float in
`Float v ) )
] )
~input:
(m_to_str
(M.Map
[ (M.String "y", M.Nil); (M.String "val", M.Float 1.1) ]
) )
~expected:(`Float 1.1)
]
let encoders_suite =
let open Decoders_msgpck.Encode in
"encoders"
>::: [ ( "list string"
>:: fun _ctxt ->
assert_equal
~printer:CCFun.id
(m_to_str (M.List [ M.String "hello"; M.String "world" ]))
(encode_string (list string) [ "hello"; "world" ]) )
; ( "string"
>:: fun _ctxt ->
assert_equal
~printer:CCFun.id
(m_to_str (M.String "hello"))
(encode_string string "hello") )
; ( "int64"
>:: fun _ctxt ->
assert_equal
~printer:CCFun.id
(m_to_str (M.Int64 Int64.max_int))
(encode_string int64 Int64.max_int) )
]
let () = "msgpck" >::: [ decoders_suite; encoders_suite ] |> run_test_tt_main
| null | https://raw.githubusercontent.com/mattjbray/ocaml-decoders/32aa29da3102f78f96f3202fbe035b520dec6e8e/test-msgpck/main.ml | ocaml | open OUnit2
module M = Msgpck
let m_to_str m = M.StringBuf.to_string m |> Buffer.contents
let decoders_suite =
let open Decoders_msgpck.Decode in
let decoder_test ~decoder ~input ~expected _test_ctxt =
match decode_string decoder input with
| Ok value ->
assert_equal value expected
| Error error ->
assert_string (Format.asprintf "%a" pp_error error)
in
"decoders"
>::: [ "list string"
>:: decoder_test
~decoder:(list string)
~input:(m_to_str (M.List [ M.String "hello"; M.String "world" ]))
~expected:[ "hello"; "world" ]
; "field_opt present"
>:: decoder_test
~decoder:(field_opt "optional" string)
~input:
(m_to_str (M.Map [ (M.String "optional", M.String "hello") ]))
~expected:(Some "hello")
; "field_opt missing"
>:: decoder_test
~decoder:(field_opt "optional" string)
~input:
(m_to_str (M.Map [ (M.String "missing", M.String "hello") ]))
~expected:None
; ( "field_opt decode error"
>:: fun _ ->
match
decode_string
(field_opt "optional" string)
(m_to_str (M.Map [ (M.String "optional", M.Int 123) ]))
with
| Ok _ ->
assert_string "expected decode error"
| Error e ->
assert_equal
~printer:CCFun.id
{|in field "optional": Expected a string, but got 123|}
(Format.asprintf "%a" pp_error e) )
; "int32 conversion"
>:: decoder_test
~decoder:int
~input:(m_to_str (M.Int32 32l))
~expected:32
; "int64 conversion"
>:: decoder_test
~decoder:int
~input:(m_to_str (M.Int64 525252L))
~expected:525252
; "int64 helper"
>:: decoder_test
~decoder:int64
~input:(m_to_str (M.Int64 Int64.max_int))
~expected:Int64.max_int
; ( "int64 overflow"
>:: fun _ ->
match decode_string int (m_to_str (M.Int64 Int64.max_int)) with
| Ok v ->
assert_string (Printf.sprintf "expected decode error, got %d" v)
| Error _e ->
() )
; "pick1"
>:: decoder_test
~decoder:
(pick
[ ( "case_x"
, let* _x = field "x" null in
succeed
(let+ v = field "val" int in
`Int v ) )
; ( "case_y"
, let* _y = field "y" null in
succeed
(let+ v = field "val" float in
`Float v ) )
] )
~input:
(m_to_str
(M.Map [ (M.String "x", M.Nil); (M.String "val", M.Int 42) ]) )
~expected:(`Int 42)
; "pick2"
>:: decoder_test
~decoder:
(pick
[ ( "case_x"
, let* _x = field "x" null in
succeed
(let+ v = field "val" int in
`Int v ) )
; ( "case_y"
, let* _y = field "y" null in
succeed
(let+ v = field "val" float in
`Float v ) )
] )
~input:
(m_to_str
(M.Map
[ (M.String "y", M.Nil); (M.String "val", M.Float 1.1) ]
) )
~expected:(`Float 1.1)
]
let encoders_suite =
let open Decoders_msgpck.Encode in
"encoders"
>::: [ ( "list string"
>:: fun _ctxt ->
assert_equal
~printer:CCFun.id
(m_to_str (M.List [ M.String "hello"; M.String "world" ]))
(encode_string (list string) [ "hello"; "world" ]) )
; ( "string"
>:: fun _ctxt ->
assert_equal
~printer:CCFun.id
(m_to_str (M.String "hello"))
(encode_string string "hello") )
; ( "int64"
>:: fun _ctxt ->
assert_equal
~printer:CCFun.id
(m_to_str (M.Int64 Int64.max_int))
(encode_string int64 Int64.max_int) )
]
let () = "msgpck" >::: [ decoders_suite; encoders_suite ] |> run_test_tt_main
| |
5085f05300b2e1fae3e12a1504d3ba740ae25e1a0d37a567f728b8f381649a58 | alexbs01/OCaml | e.ml | let e = exp(1.)
let _ = print_float e;
print_endline "";
| null | https://raw.githubusercontent.com/alexbs01/OCaml/92a28522a8467d8ed87ef380b6175f1c21616f85/p02/e.ml | ocaml | let e = exp(1.)
let _ = print_float e;
print_endline "";
| |
18c87fc2020663e8173fc238d418eb73d04497ace3b9314e239e2ea6cbadf809 | tolysz/ghcjs-stack | LabeledGraph.hs | -- | Wrapper around Data.Graph with support for edge labels
# LANGUAGE ScopedTypeVariables #
module Distribution.Client.Utils.LabeledGraph (
-- * Graphs
Graph
, Vertex
-- ** Building graphs
, graphFromEdges
, graphFromEdges'
, buildG
, transposeG
-- ** Graph properties
, vertices
, edges
-- ** Operations on the underlying unlabeled graph
, forgetLabels
, topSort
) where
import Data.Array
import Data.Graph (Vertex, Bounds)
import Data.List (sortBy)
import Data.Maybe (mapMaybe)
import qualified Data.Graph as G
{-------------------------------------------------------------------------------
Types
-------------------------------------------------------------------------------}
type Graph e = Array Vertex [(e, Vertex)]
type Edge e = (Vertex, e, Vertex)
{-------------------------------------------------------------------------------
Building graphs
-------------------------------------------------------------------------------}
-- | Construct an edge-labeled graph
--
-- This is a simple adaptation of the definition in Data.Graph
graphFromEdges :: forall key node edge. Ord key
=> [ (node, key, [(edge, key)]) ]
-> ( Graph edge
, Vertex -> (node, key, [(edge, key)])
, key -> Maybe Vertex
)
graphFromEdges edges0 =
(graph, \v -> vertex_map ! v, key_vertex)
where
max_v = length edges0 - 1
bounds0 = (0, max_v) :: (Vertex, Vertex)
sorted_edges = sortBy lt edges0
edges1 = zipWith (,) [0..] sorted_edges
graph = array bounds0 [(v, (mapMaybe mk_edge ks))
| (v, (_, _, ks)) <- edges1]
key_map = array bounds0 [(v, k )
| (v, (_, k, _ )) <- edges1]
vertex_map = array bounds0 edges1
(_,k1,_) `lt` (_,k2,_) = k1 `compare` k2
mk_edge :: (edge, key) -> Maybe (edge, Vertex)
mk_edge (edge, key) = do v <- key_vertex key ; return (edge, v)
-- returns Nothing for non-interesting vertices
key_vertex :: key -> Maybe Vertex
key_vertex k = findVertex 0 max_v
where
findVertex a b
| a > b = Nothing
| otherwise = case compare k (key_map ! mid) of
LT -> findVertex a (mid-1)
EQ -> Just mid
GT -> findVertex (mid+1) b
where
mid = a + (b - a) `div` 2
graphFromEdges' :: Ord key
=> [ (node, key, [(edge, key)]) ]
-> ( Graph edge
, Vertex -> (node, key, [(edge, key)])
)
graphFromEdges' x = (a,b)
where
(a,b,_) = graphFromEdges x
transposeG :: Graph e -> Graph e
transposeG g = buildG (bounds g) (reverseE g)
buildG :: Bounds -> [Edge e] -> Graph e
buildG bounds0 edges0 = accumArray (flip (:)) [] bounds0 (map reassoc edges0)
where
reassoc (v, e, w) = (v, (e, w))
reverseE :: Graph e -> [Edge e]
reverseE g = [ (w, e, v) | (v, e, w) <- edges g ]
{-------------------------------------------------------------------------------
Graph properties
-------------------------------------------------------------------------------}
vertices :: Graph e -> [Vertex]
vertices = indices
edges :: Graph e -> [Edge e]
edges g = [ (v, e, w) | v <- vertices g, (e, w) <- g!v ]
{-------------------------------------------------------------------------------
Operations on the underlying unlabelled graph
-------------------------------------------------------------------------------}
forgetLabels :: Graph e -> G.Graph
forgetLabels = fmap (map snd)
topSort :: Graph e -> [Vertex]
topSort = G.topSort . forgetLabels
| null | https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal-next/cabal-install/Distribution/Client/Utils/LabeledGraph.hs | haskell | | Wrapper around Data.Graph with support for edge labels
* Graphs
** Building graphs
** Graph properties
** Operations on the underlying unlabeled graph
------------------------------------------------------------------------------
Types
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Building graphs
------------------------------------------------------------------------------
| Construct an edge-labeled graph
This is a simple adaptation of the definition in Data.Graph
returns Nothing for non-interesting vertices
------------------------------------------------------------------------------
Graph properties
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Operations on the underlying unlabelled graph
------------------------------------------------------------------------------ | # LANGUAGE ScopedTypeVariables #
module Distribution.Client.Utils.LabeledGraph (
Graph
, Vertex
, graphFromEdges
, graphFromEdges'
, buildG
, transposeG
, vertices
, edges
, forgetLabels
, topSort
) where
import Data.Array
import Data.Graph (Vertex, Bounds)
import Data.List (sortBy)
import Data.Maybe (mapMaybe)
import qualified Data.Graph as G
type Graph e = Array Vertex [(e, Vertex)]
type Edge e = (Vertex, e, Vertex)
graphFromEdges :: forall key node edge. Ord key
=> [ (node, key, [(edge, key)]) ]
-> ( Graph edge
, Vertex -> (node, key, [(edge, key)])
, key -> Maybe Vertex
)
graphFromEdges edges0 =
(graph, \v -> vertex_map ! v, key_vertex)
where
max_v = length edges0 - 1
bounds0 = (0, max_v) :: (Vertex, Vertex)
sorted_edges = sortBy lt edges0
edges1 = zipWith (,) [0..] sorted_edges
graph = array bounds0 [(v, (mapMaybe mk_edge ks))
| (v, (_, _, ks)) <- edges1]
key_map = array bounds0 [(v, k )
| (v, (_, k, _ )) <- edges1]
vertex_map = array bounds0 edges1
(_,k1,_) `lt` (_,k2,_) = k1 `compare` k2
mk_edge :: (edge, key) -> Maybe (edge, Vertex)
mk_edge (edge, key) = do v <- key_vertex key ; return (edge, v)
key_vertex :: key -> Maybe Vertex
key_vertex k = findVertex 0 max_v
where
findVertex a b
| a > b = Nothing
| otherwise = case compare k (key_map ! mid) of
LT -> findVertex a (mid-1)
EQ -> Just mid
GT -> findVertex (mid+1) b
where
mid = a + (b - a) `div` 2
graphFromEdges' :: Ord key
=> [ (node, key, [(edge, key)]) ]
-> ( Graph edge
, Vertex -> (node, key, [(edge, key)])
)
graphFromEdges' x = (a,b)
where
(a,b,_) = graphFromEdges x
transposeG :: Graph e -> Graph e
transposeG g = buildG (bounds g) (reverseE g)
buildG :: Bounds -> [Edge e] -> Graph e
buildG bounds0 edges0 = accumArray (flip (:)) [] bounds0 (map reassoc edges0)
where
reassoc (v, e, w) = (v, (e, w))
reverseE :: Graph e -> [Edge e]
reverseE g = [ (w, e, v) | (v, e, w) <- edges g ]
vertices :: Graph e -> [Vertex]
vertices = indices
edges :: Graph e -> [Edge e]
edges g = [ (v, e, w) | v <- vertices g, (e, w) <- g!v ]
forgetLabels :: Graph e -> G.Graph
forgetLabels = fmap (map snd)
topSort :: Graph e -> [Vertex]
topSort = G.topSort . forgetLabels
|
d0e74e9e7fe7d259f736905788173e1a80f4e5cdae766dde1e18cb10b1a64879 | kelamg/HtDP2e-workthrough | ex236.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-intermediate-reader.ss" "lang")((modname ex236) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; N Lon -> Lon
;; adds n to each item in l
(define (addn n l)
(cond
[(empty? l) '()]
[else
(cons (+ n (first l))
(addn n (rest l)))]))
; Lon -> Lon
adds 1 to each item in l
(check-expect (add1* '()) '())
(check-expect
(add1* (list 4 10 27)) (list 5 11 28))
(define (add1* l)
(addn 1 l))
; Lon -> Lon
adds 5 to each item in l
(check-expect (plus5 '()) '())
(check-expect
(plus5 (list 2 11 55)) (list 7 16 60))
(define (plus5 l)
(addn 5 l))
;; Lon -> Lon
subtracts 2 from each item in l
(check-expect (subtract2 '()) '())
(check-expect
(subtract2 (list 2 10 25))
(list 0 8 23))
(define (subtract2 l)
(addn -2 l))
| null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Abstraction/ex236.rkt | racket | about the language level of this file in a form that our tools can easily process.
N Lon -> Lon
adds n to each item in l
Lon -> Lon
Lon -> Lon
Lon -> Lon | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-reader.ss" "lang")((modname ex236) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define (addn n l)
(cond
[(empty? l) '()]
[else
(cons (+ n (first l))
(addn n (rest l)))]))
adds 1 to each item in l
(check-expect (add1* '()) '())
(check-expect
(add1* (list 4 10 27)) (list 5 11 28))
(define (add1* l)
(addn 1 l))
adds 5 to each item in l
(check-expect (plus5 '()) '())
(check-expect
(plus5 (list 2 11 55)) (list 7 16 60))
(define (plus5 l)
(addn 5 l))
subtracts 2 from each item in l
(check-expect (subtract2 '()) '())
(check-expect
(subtract2 (list 2 10 25))
(list 0 8 23))
(define (subtract2 l)
(addn -2 l))
|
b221871f9cf42b4c04305c6ea9d531ea8a58ebcb67b87b3f305c8e2767f5b5c6 | alphagov/govuk-guix | utils.scm | (define-module (gds systems govuk utils)
#:use-module (srfi srfi-1)
#:use-module (ice-9 match)
#:use-module (guix gexp)
#:use-module (gnu services)
#:use-module (gnu system shadow)
#:use-module (gds services utils databases)
#:use-module (gds services utils databases elasticsearch)
#:use-module (gds services utils databases mongodb)
#:use-module (gds services utils databases mysql)
#:use-module (gds services utils databases postgresql)
#:export (govuk-skeletons-service-type))
(define (govuk-skeletons redis-connection-config
memcached-connection-config
postgresql-connection-config)
(define pair->alias
(match-lambda
((name . value)
(simple-format #f "alias ~A=\"~A\"\n" name value))))
`((".psqlrc" ,(local-file "skeletons/psqlrc"))
(".bashrc" ,(local-file "skeletons/bashrc"))
(".bash_aliases"
,(plain-file
"aliases"
(string-concatenate
(map pair->alias
`(("redis" .
,(string-append
"redis-cli -p "
(number->string
(redis-connection-config-port redis-connection-config))))
("memcached-telnet" .
,(string-append
"telnet "
(number->string
(memcached-connection-config-port memcached-connection-config)))))))))
(".environment"
,(plain-file
"environment"
(apply
string-append
(map (match-lambda
((name . value)
(simple-format #f "export ~A=~A\n" name value)))
`(("PGPORT" . ,(postgresql-connection-config-port
postgresql-connection-config))
("PGUSER" . "postgres")
("PAGER" . "less")
("LC_ALL" . "en_GB.UTF-8"))))))))
(define govuk-skeletons-service-type
(service-type
(name 'govuk-skeletons)
(extensions
(list
(service-extension account-service-type
(lambda (parameters)
(govuk-skeletons
(find redis-connection-config? parameters)
(find memcached-connection-config? parameters)
(find postgresql-connection-config? parameters))))))
(default-value
(list
(redis-connection-config)
(memcached-connection-config)
(postgresql-connection-config
(user #f) (database #f))))))
| null | https://raw.githubusercontent.com/alphagov/govuk-guix/dea8c26d2ae882d0278be5c745e23abb25d4a4e2/gds/systems/govuk/utils.scm | scheme | (define-module (gds systems govuk utils)
#:use-module (srfi srfi-1)
#:use-module (ice-9 match)
#:use-module (guix gexp)
#:use-module (gnu services)
#:use-module (gnu system shadow)
#:use-module (gds services utils databases)
#:use-module (gds services utils databases elasticsearch)
#:use-module (gds services utils databases mongodb)
#:use-module (gds services utils databases mysql)
#:use-module (gds services utils databases postgresql)
#:export (govuk-skeletons-service-type))
(define (govuk-skeletons redis-connection-config
memcached-connection-config
postgresql-connection-config)
(define pair->alias
(match-lambda
((name . value)
(simple-format #f "alias ~A=\"~A\"\n" name value))))
`((".psqlrc" ,(local-file "skeletons/psqlrc"))
(".bashrc" ,(local-file "skeletons/bashrc"))
(".bash_aliases"
,(plain-file
"aliases"
(string-concatenate
(map pair->alias
`(("redis" .
,(string-append
"redis-cli -p "
(number->string
(redis-connection-config-port redis-connection-config))))
("memcached-telnet" .
,(string-append
"telnet "
(number->string
(memcached-connection-config-port memcached-connection-config)))))))))
(".environment"
,(plain-file
"environment"
(apply
string-append
(map (match-lambda
((name . value)
(simple-format #f "export ~A=~A\n" name value)))
`(("PGPORT" . ,(postgresql-connection-config-port
postgresql-connection-config))
("PGUSER" . "postgres")
("PAGER" . "less")
("LC_ALL" . "en_GB.UTF-8"))))))))
(define govuk-skeletons-service-type
(service-type
(name 'govuk-skeletons)
(extensions
(list
(service-extension account-service-type
(lambda (parameters)
(govuk-skeletons
(find redis-connection-config? parameters)
(find memcached-connection-config? parameters)
(find postgresql-connection-config? parameters))))))
(default-value
(list
(redis-connection-config)
(memcached-connection-config)
(postgresql-connection-config
(user #f) (database #f))))))
| |
b192522413d9fc85632d9a1b8d3a90dd391ddb8d73021ff2ba703f639034a09f | kizzx2/haskell-qrcode | Placement.hs | {-# OPTIONS_HADDOCK hide #-}
# LANGUAGE FlexibleContexts , GeneralizedNewtypeDeriving , NoMonomorphismRestriction #
module Codec.Binary.QRCode.Placement where
import Codec.Binary.QRCode.Matrix
import Codec.Binary.QRCode.Spec
import Codec.Binary.QRCode.Utils
import Data.Tuple
import Data.List
import qualified Data.Set as S
import Control.Monad
import Control.Monad.Reader
import Data.Array.IArray
type Coords = [(Int,Int)]
type ReaderCoords = ReaderQR Coords
type MatrixPart = [((Int,Int),Module)]
intertwine :: [a] -> [a] -> [a]
intertwine (x:xs) (y:ys) = x:y:intertwine xs ys
intertwine (x:xs) [] = x:intertwine xs []
intertwine [] (y:ys) = y:intertwine [] ys
intertwine [] [] = []
-- mkCleanBoardMatrix :: Int -> Matrix
mkCleanBoardMatrix width = QRM $ array ( ( 0,0 ) , ( width-1,width-1 ) ) combined
-- where
finderTL =
mkMatrix :: Int -> [((Int, Int), Module)] -> Matrix
mkMatrix width = QRM . array ((0,0),(width-1,width-1))
mkSymbolWithFunctionPatterns :: Version -> Modules -> Matrix
mkSymbolWithFunctionPatterns ver mods = mkMatrix width combinedMods
where
width = qrNumModulesPerSide $ qrGetInfo ver
combinedMods = flip runReader ver $ do
let genAllLight = liftM $ flip zip $ repeat Light
formats <- formatInfoRegions
versions <- versionInfoRegions
finderTL <- genAllLight finderPatternTopLeft
finderBL <- genAllLight finderPatternBottomLeft
finderTR <- genAllLight finderPatternTopRight
timingH <- genAllLight timingPatternHorizontal
timingV <- genAllLight timingPatternVertical
hardcoded <- hardcodedDarkModule
path <- mkPath
let dat = zip path mods
finders = finderTL ++ finderBL ++ finderTR
timings = timingH ++ timingV
hc = zip hardcoded (repeat Light)
-- These will be applied to the symbol after masking
formats' = zip formats (repeat Light)
versions' = zip versions (repeat Light)
return $ dat ++ finders ++ timings ++ hc ++ formats' ++ versions'
mkSymbol :: Coords -> Version -> Modules -> Matrix
mkSymbol path ver mods = mkMatrix width combinedMods
where
width = qrNumModulesPerSide $ qrGetInfo ver
combinedMods = flip runReader ver $ do
formats <- formatInfoRegions
versions <- versionInfoRegions
finderTL <- genFinderPatternTopLeft finderPatternTopLeft
finderBL <- genFinderPatternBottomLeft finderPatternBottomLeft
finderTR <- genFinderPatternTopRight finderPatternTopRight
timingH <- genTimingPattern timingPatternHorizontal
timingV <- genTimingPattern timingPatternVertical
alignments <- liftM genAlignmentPatterns alignmentCoords
hardcoded <- hardcodedDarkModule
let dat = zip path mods
finders = finderTL ++ finderBL ++ finderTR
timings = timingH ++ timingV
hc = zip hardcoded [Dark]
formats' = zip formats $ repeat Light
versions' = zip versions $ repeat Light
return $ dat ++ finders ++ timings ++ hc ++ formats' ++ alignments ++ versions'
qrmApplyInfo :: ReaderQR Coords -> ReaderQR Coords -> Version -> Matrix-> BitStream -> Matrix
qrmApplyInfo region1 region2 ver mat bitstream = qrmOverlay mat overlays
where
mods = toModules bitstream
overlays = flip runReader ver $ do
path1 <- region1
path2 <- region2
return $ zip path1 mods ++ zip path2 mods
qrmApplyFormatInfo :: Version -> Matrix -> BitStream -> Matrix
qrmApplyFormatInfo = qrmApplyInfo formatInfoRegionHorizontal formatInfoRegionVertical
qrmApplyVersionInfo :: Version -> Matrix -> BitStream -> Matrix
qrmApplyVersionInfo = qrmApplyInfo versionInfoRegionBottomLeft versionInfoRegionTopRight
newtype MyChar = MC Char deriving (Eq, Ord, Enum)
instance Show MyChar where
show (MC '\n') = "\n"
show (MC c) = [c]
mkDebugPath :: Version -> Array (Int,Int) MyChar
mkDebugPath ver = base // trail
where
width = qrNumModulesPerSide $ qrGetInfo ver
ix = ((0,0),(width-1,width-1))
blanks = repeat (MC ' ')
trail = zip (runReader mkPath ver) $ cycle $ reverse [(MC '0')..(MC '7')]
base = listArray ix blanks
fred = putStrLn $ show2DArray $ mkDebugPath 21
bar = runReader mkRawPath 6 \\ mask
-- where
mask = [ ( x,2 ) | x < - [ 0 .. 5 ] ]
-- Create the coordinates, in order, where modules should
-- be placed in a matrix. The path excludes function
patterns so a bitstream can be zipped one to one to the
-- coordinates into a matrix. The path flows from the most
-- significant bit to the least
mkPath :: ReaderQR Coords
mkPath = mkRawPath `subtractPatterns` allFunctionPatterns
-- Return a "raw" path in coordinates. This is the path that
-- bits will follow according to the placement strategy in the spec.
--
-- The path is created by intervolving up-row pairs and down-row pairs
--
-- This creates a raw path. The real path can be obtained by simply
-- subtracting functional patterns' coordinates. Note that
-- the vertical timing pattern presents a special case because it will
-- reverse the orientation. This is kind of difficult to explain in
-- words but is apparent when you draw out the path on paper.
mkRawPath :: ReaderQR Coords
mkRawPath = do
ver <- ask
time <- natural 7
let width = qrGetWidth ver
upRowPair = concatMap (replicate 2) [0..(width-1)]
downRowPair = reverse upRowPair
mkCols = concat . concatMap (replicate width) . chunksOf 2
mkRows = concat . cycle
-- rows and cols "before" (to the right of) the vert timing pattern
cols1 = mkCols [0..(time-1)]
rows1 = mkRows [upRowPair, downRowPair]
-- "after"
cols2 = mkCols [(time+1)..(width-1)]
rows2 = mkRows [downRowPair, upRowPair]
return $ filter ((/=time) . fst) $ zip rows1 cols1 ++ zip rows2 cols2
genTimingPattern :: Monad m => m [a] -> m [(a, Module)]
genTimingPattern path = do
p <- path
return $ zip p (cycle [Dark, Light])
joinPatterns :: Applicative f => f [a] -> f [a] -> f [a]
joinPatterns = (<*>) . ((++) <$>)
fastDiff :: (Ord a) => [a] -> [a] -> [a]
xs `fastDiff` ys = filter (flip S.notMember ys') xs
where ys' = S.fromList ys
subtractPatterns :: (Applicative f, Ord a) => f [a] -> f [a] -> f [a]
subtractPatterns = (<*>) . (fastDiff <$>)
(/+/) :: Applicative f => f [a] -> f [a] -> f [a]
(/+/) = joinPatterns
allFunctionPatterns :: ReaderQR Coords
allFunctionPatterns = timingPatterns /+/ finderPatterns
/+/ formatInfoRegions
/+/ hardcodedDarkModule
/+/ alignmentCoords
/+/ versionInfoRegions
-- Convert a top-left-origin position to a bottom-right-origin
-- This is here so that we can input numbers according to the spec
--
When the spec says the " 6 - th column " , we can just say " natural 6 "
-- to get to the right position.
--
i.e. the top - left - origin here is ( 1,1 )
natural :: Int -> ReaderQR Int
natural n = do
ver <- ask
return $ qrGetWidth ver - n
timingPatterns :: ReaderQR Coords
timingPatterns = timingPatternHorizontal /+/ timingPatternVertical
timingPatternHorizontal :: ReaderQR Coords
timingPatternHorizontal = do
ver <- ask
row <- natural 7
let width = qrGetWidth ver
v = [(row,y) | y <- [0..(width-1)]]
finder <- finderPatterns
return $ v \\ finder
timingPatternVertical :: ReaderQR Coords
timingPatternVertical = map swap `fmap` timingPatternHorizontal
versionInfoRegion' :: (Num a, Enum a) => (a -> Int -> b) -> ReaderQR [b]
versionInfoRegion' f = do
ver@(Version v) <- ask
a <- natural 6
let width = qrGetWidth ver
rows = cycle [8..10]
cols = concatMap (replicate 3) [a..width-1]
return $ do
guard $ v >= 7
zipWith f rows cols
versionInfoRegionBottomLeft :: (Num a, Enum a) => ReaderQR [(a, Int)]
versionInfoRegionBottomLeft = versionInfoRegion' (,)
versionInfoRegionTopRight :: (Num a, Enum a) => ReaderQR [(Int, a)]
versionInfoRegionTopRight = versionInfoRegion' $ flip (,)
versionInfoRegions :: ReaderQR [(Int, Int)]
versionInfoRegions = versionInfoRegionBottomLeft /+/ versionInfoRegionTopRight
Figure 19 in spec
hardcodedDarkModule :: Num t => ReaderQR [(t, Int)]
hardcodedDarkModule = do
col <- natural 9
return [(7,col)]
formatInfoRegions :: ReaderQR [(Int, Int)]
formatInfoRegions = formatInfoRegionHorizontal /+/ formatInfoRegionVertical
formatInfoRegionHorizontal :: ReaderQR [(Int, Int)]
formatInfoRegionHorizontal = do
ver <- ask
row <- natural 9
c' <- natural 8
let width = qrGetWidth ver
return $ reverse [(row,col) | col <- [0..7] ++ [c'] ++ [c'+2..width-1]]
formatInfoRegionVertical :: ReaderQR [(Int, Int)]
formatInfoRegionVertical = do
col <- natural 9
let a = 0
b = 6
c <- natural 9
d <- natural 8
e <- natural 6
f <- natural 1
return [(row,col) | row <- [a..b] ++ [c..d] ++ [e..f]]
finderPatterns :: ReaderQR [(Int, Int)]
finderPatterns = finderPatternTopLeft /+/ finderPatternBottomLeft /+/ finderPatternTopRight
-- Includes separators
finderPatternTopLeft :: ReaderQR Coords
finderPatternTopLeft = do
ver <- ask
r' <- natural 8
let width = qrGetWidth ver
return [(row,col) | let vals = [r'..(width-1)], row <- vals, col <- vals]
finderPatternTopRight :: ReaderQR Coords
finderPatternTopRight = do
ver <- ask
r' <- natural 8
let width = qrGetWidth ver
return [(row,col) | row <- [r'..width-1], col <- [0..7]]
finderPatternBottomLeft :: ReaderQR Coords
finderPatternBottomLeft = do
ver <- ask
let width = qrGetWidth ver
c' <- natural 8
return [(row,col) | row <- [0..7], col <- [c'..width-1]]
-- This assumes a bottom-left origin, right to
-- left bottom to top path
genFinderPattern :: Monad m => Modules -> Modules -> Modules -> Modules -> m [a] -> m [(a, Module)]
genFinderPattern prepend append lpadCol rpadCol path = do
p <- path
-- Add the separator to the raw finder pattern so
-- that it matches exactly with the path given
let pat = prepend ++ rawFinderPattern ++ append
return $ zip p pat
where
rawFinderPattern = r1 ++ r2 ++ r3 ++ r3 ++ r3 ++ r2 ++ r1
r1 = rpadCol ++ replicate 7 Dark ++ lpadCol
r2 = rpadCol ++ [Dark, Light, Light, Light, Light, Light, Dark] ++ lpadCol
r3 = rpadCol ++ [Dark, Light, Dark, Dark, Dark, Light, Dark] ++ lpadCol
emptyFinderPatternRow :: Modules
emptyFinderPatternRow = replicate 8 Light
genFinderPatternTopLeft :: Monad m => m [a] -> m [(a, Module)]
genFinderPatternTopLeft = genFinderPattern emptyFinderPatternRow [] [] [Light]
genFinderPatternTopRight :: Monad m => m [a] -> m [(a, Module)]
genFinderPatternTopRight = genFinderPattern emptyFinderPatternRow [] [Light] []
genFinderPatternBottomLeft :: Monad m => m [a] -> m [(a, Module)]
genFinderPatternBottomLeft = genFinderPattern [] emptyFinderPatternRow [] [Light]
genAlignmentPatterns :: [a] -> [(a, Module)]
genAlignmentPatterns = flip zip (cycle patternMods)
where
patternMods = [ Dark, Dark, Dark, Dark, Dark
, Dark, Light, Light, Light, Dark
, Dark, Light, Dark, Light, Dark
, Dark, Light, Light, Light, Dark
, Dark, Dark, Dark, Dark, Dark
]
overlapsFinder :: (Int,Int) -> ReaderQR Bool
overlapsFinder (r,c) = do
a <- natural 8
return $ (r >= a && c >= a) || (r <= 8 && c >= a) || (r >= a && c <= 8)
alignmentCoords :: MonadReader Version m => m [(Int, Int)]
alignmentCoords = do
ver <- ask
let centers = qrAlignmentCenters ver
validCenters = [(x,y) | x <- centers, y <- centers, let inFinder = runReader (overlapsFinder (x,y)) ver, not inFinder]
mkPat (r,c) = [(r',c') | c' <- [c-2..c+2], r' <- [r-2..r+2]]
pats = concatMap mkPat validCenters
return pats
| null | https://raw.githubusercontent.com/kizzx2/haskell-qrcode/be06628d4cb77381c55a788c11c1695ebe432c28/Codec/Binary/QRCode/Placement.hs | haskell | # OPTIONS_HADDOCK hide #
mkCleanBoardMatrix :: Int -> Matrix
where
These will be applied to the symbol after masking
where
Create the coordinates, in order, where modules should
be placed in a matrix. The path excludes function
coordinates into a matrix. The path flows from the most
significant bit to the least
Return a "raw" path in coordinates. This is the path that
bits will follow according to the placement strategy in the spec.
The path is created by intervolving up-row pairs and down-row pairs
This creates a raw path. The real path can be obtained by simply
subtracting functional patterns' coordinates. Note that
the vertical timing pattern presents a special case because it will
reverse the orientation. This is kind of difficult to explain in
words but is apparent when you draw out the path on paper.
rows and cols "before" (to the right of) the vert timing pattern
"after"
Convert a top-left-origin position to a bottom-right-origin
This is here so that we can input numbers according to the spec
to get to the right position.
Includes separators
This assumes a bottom-left origin, right to
left bottom to top path
Add the separator to the raw finder pattern so
that it matches exactly with the path given | # LANGUAGE FlexibleContexts , GeneralizedNewtypeDeriving , NoMonomorphismRestriction #
module Codec.Binary.QRCode.Placement where
import Codec.Binary.QRCode.Matrix
import Codec.Binary.QRCode.Spec
import Codec.Binary.QRCode.Utils
import Data.Tuple
import Data.List
import qualified Data.Set as S
import Control.Monad
import Control.Monad.Reader
import Data.Array.IArray
type Coords = [(Int,Int)]
type ReaderCoords = ReaderQR Coords
type MatrixPart = [((Int,Int),Module)]
intertwine :: [a] -> [a] -> [a]
intertwine (x:xs) (y:ys) = x:y:intertwine xs ys
intertwine (x:xs) [] = x:intertwine xs []
intertwine [] (y:ys) = y:intertwine [] ys
intertwine [] [] = []
mkCleanBoardMatrix width = QRM $ array ( ( 0,0 ) , ( width-1,width-1 ) ) combined
finderTL =
mkMatrix :: Int -> [((Int, Int), Module)] -> Matrix
mkMatrix width = QRM . array ((0,0),(width-1,width-1))
mkSymbolWithFunctionPatterns :: Version -> Modules -> Matrix
mkSymbolWithFunctionPatterns ver mods = mkMatrix width combinedMods
where
width = qrNumModulesPerSide $ qrGetInfo ver
combinedMods = flip runReader ver $ do
let genAllLight = liftM $ flip zip $ repeat Light
formats <- formatInfoRegions
versions <- versionInfoRegions
finderTL <- genAllLight finderPatternTopLeft
finderBL <- genAllLight finderPatternBottomLeft
finderTR <- genAllLight finderPatternTopRight
timingH <- genAllLight timingPatternHorizontal
timingV <- genAllLight timingPatternVertical
hardcoded <- hardcodedDarkModule
path <- mkPath
let dat = zip path mods
finders = finderTL ++ finderBL ++ finderTR
timings = timingH ++ timingV
hc = zip hardcoded (repeat Light)
formats' = zip formats (repeat Light)
versions' = zip versions (repeat Light)
return $ dat ++ finders ++ timings ++ hc ++ formats' ++ versions'
mkSymbol :: Coords -> Version -> Modules -> Matrix
mkSymbol path ver mods = mkMatrix width combinedMods
where
width = qrNumModulesPerSide $ qrGetInfo ver
combinedMods = flip runReader ver $ do
formats <- formatInfoRegions
versions <- versionInfoRegions
finderTL <- genFinderPatternTopLeft finderPatternTopLeft
finderBL <- genFinderPatternBottomLeft finderPatternBottomLeft
finderTR <- genFinderPatternTopRight finderPatternTopRight
timingH <- genTimingPattern timingPatternHorizontal
timingV <- genTimingPattern timingPatternVertical
alignments <- liftM genAlignmentPatterns alignmentCoords
hardcoded <- hardcodedDarkModule
let dat = zip path mods
finders = finderTL ++ finderBL ++ finderTR
timings = timingH ++ timingV
hc = zip hardcoded [Dark]
formats' = zip formats $ repeat Light
versions' = zip versions $ repeat Light
return $ dat ++ finders ++ timings ++ hc ++ formats' ++ alignments ++ versions'
qrmApplyInfo :: ReaderQR Coords -> ReaderQR Coords -> Version -> Matrix-> BitStream -> Matrix
qrmApplyInfo region1 region2 ver mat bitstream = qrmOverlay mat overlays
where
mods = toModules bitstream
overlays = flip runReader ver $ do
path1 <- region1
path2 <- region2
return $ zip path1 mods ++ zip path2 mods
qrmApplyFormatInfo :: Version -> Matrix -> BitStream -> Matrix
qrmApplyFormatInfo = qrmApplyInfo formatInfoRegionHorizontal formatInfoRegionVertical
qrmApplyVersionInfo :: Version -> Matrix -> BitStream -> Matrix
qrmApplyVersionInfo = qrmApplyInfo versionInfoRegionBottomLeft versionInfoRegionTopRight
newtype MyChar = MC Char deriving (Eq, Ord, Enum)
instance Show MyChar where
show (MC '\n') = "\n"
show (MC c) = [c]
mkDebugPath :: Version -> Array (Int,Int) MyChar
mkDebugPath ver = base // trail
where
width = qrNumModulesPerSide $ qrGetInfo ver
ix = ((0,0),(width-1,width-1))
blanks = repeat (MC ' ')
trail = zip (runReader mkPath ver) $ cycle $ reverse [(MC '0')..(MC '7')]
base = listArray ix blanks
fred = putStrLn $ show2DArray $ mkDebugPath 21
bar = runReader mkRawPath 6 \\ mask
mask = [ ( x,2 ) | x < - [ 0 .. 5 ] ]
patterns so a bitstream can be zipped one to one to the
mkPath :: ReaderQR Coords
mkPath = mkRawPath `subtractPatterns` allFunctionPatterns
mkRawPath :: ReaderQR Coords
mkRawPath = do
ver <- ask
time <- natural 7
let width = qrGetWidth ver
upRowPair = concatMap (replicate 2) [0..(width-1)]
downRowPair = reverse upRowPair
mkCols = concat . concatMap (replicate width) . chunksOf 2
mkRows = concat . cycle
cols1 = mkCols [0..(time-1)]
rows1 = mkRows [upRowPair, downRowPair]
cols2 = mkCols [(time+1)..(width-1)]
rows2 = mkRows [downRowPair, upRowPair]
return $ filter ((/=time) . fst) $ zip rows1 cols1 ++ zip rows2 cols2
genTimingPattern :: Monad m => m [a] -> m [(a, Module)]
genTimingPattern path = do
p <- path
return $ zip p (cycle [Dark, Light])
joinPatterns :: Applicative f => f [a] -> f [a] -> f [a]
joinPatterns = (<*>) . ((++) <$>)
fastDiff :: (Ord a) => [a] -> [a] -> [a]
xs `fastDiff` ys = filter (flip S.notMember ys') xs
where ys' = S.fromList ys
subtractPatterns :: (Applicative f, Ord a) => f [a] -> f [a] -> f [a]
subtractPatterns = (<*>) . (fastDiff <$>)
(/+/) :: Applicative f => f [a] -> f [a] -> f [a]
(/+/) = joinPatterns
allFunctionPatterns :: ReaderQR Coords
allFunctionPatterns = timingPatterns /+/ finderPatterns
/+/ formatInfoRegions
/+/ hardcodedDarkModule
/+/ alignmentCoords
/+/ versionInfoRegions
When the spec says the " 6 - th column " , we can just say " natural 6 "
i.e. the top - left - origin here is ( 1,1 )
natural :: Int -> ReaderQR Int
natural n = do
ver <- ask
return $ qrGetWidth ver - n
timingPatterns :: ReaderQR Coords
timingPatterns = timingPatternHorizontal /+/ timingPatternVertical
timingPatternHorizontal :: ReaderQR Coords
timingPatternHorizontal = do
ver <- ask
row <- natural 7
let width = qrGetWidth ver
v = [(row,y) | y <- [0..(width-1)]]
finder <- finderPatterns
return $ v \\ finder
timingPatternVertical :: ReaderQR Coords
timingPatternVertical = map swap `fmap` timingPatternHorizontal
versionInfoRegion' :: (Num a, Enum a) => (a -> Int -> b) -> ReaderQR [b]
versionInfoRegion' f = do
ver@(Version v) <- ask
a <- natural 6
let width = qrGetWidth ver
rows = cycle [8..10]
cols = concatMap (replicate 3) [a..width-1]
return $ do
guard $ v >= 7
zipWith f rows cols
versionInfoRegionBottomLeft :: (Num a, Enum a) => ReaderQR [(a, Int)]
versionInfoRegionBottomLeft = versionInfoRegion' (,)
versionInfoRegionTopRight :: (Num a, Enum a) => ReaderQR [(Int, a)]
versionInfoRegionTopRight = versionInfoRegion' $ flip (,)
versionInfoRegions :: ReaderQR [(Int, Int)]
versionInfoRegions = versionInfoRegionBottomLeft /+/ versionInfoRegionTopRight
Figure 19 in spec
hardcodedDarkModule :: Num t => ReaderQR [(t, Int)]
hardcodedDarkModule = do
col <- natural 9
return [(7,col)]
formatInfoRegions :: ReaderQR [(Int, Int)]
formatInfoRegions = formatInfoRegionHorizontal /+/ formatInfoRegionVertical
formatInfoRegionHorizontal :: ReaderQR [(Int, Int)]
formatInfoRegionHorizontal = do
ver <- ask
row <- natural 9
c' <- natural 8
let width = qrGetWidth ver
return $ reverse [(row,col) | col <- [0..7] ++ [c'] ++ [c'+2..width-1]]
formatInfoRegionVertical :: ReaderQR [(Int, Int)]
formatInfoRegionVertical = do
col <- natural 9
let a = 0
b = 6
c <- natural 9
d <- natural 8
e <- natural 6
f <- natural 1
return [(row,col) | row <- [a..b] ++ [c..d] ++ [e..f]]
finderPatterns :: ReaderQR [(Int, Int)]
finderPatterns = finderPatternTopLeft /+/ finderPatternBottomLeft /+/ finderPatternTopRight
finderPatternTopLeft :: ReaderQR Coords
finderPatternTopLeft = do
ver <- ask
r' <- natural 8
let width = qrGetWidth ver
return [(row,col) | let vals = [r'..(width-1)], row <- vals, col <- vals]
finderPatternTopRight :: ReaderQR Coords
finderPatternTopRight = do
ver <- ask
r' <- natural 8
let width = qrGetWidth ver
return [(row,col) | row <- [r'..width-1], col <- [0..7]]
finderPatternBottomLeft :: ReaderQR Coords
finderPatternBottomLeft = do
ver <- ask
let width = qrGetWidth ver
c' <- natural 8
return [(row,col) | row <- [0..7], col <- [c'..width-1]]
genFinderPattern :: Monad m => Modules -> Modules -> Modules -> Modules -> m [a] -> m [(a, Module)]
genFinderPattern prepend append lpadCol rpadCol path = do
p <- path
let pat = prepend ++ rawFinderPattern ++ append
return $ zip p pat
where
rawFinderPattern = r1 ++ r2 ++ r3 ++ r3 ++ r3 ++ r2 ++ r1
r1 = rpadCol ++ replicate 7 Dark ++ lpadCol
r2 = rpadCol ++ [Dark, Light, Light, Light, Light, Light, Dark] ++ lpadCol
r3 = rpadCol ++ [Dark, Light, Dark, Dark, Dark, Light, Dark] ++ lpadCol
emptyFinderPatternRow :: Modules
emptyFinderPatternRow = replicate 8 Light
genFinderPatternTopLeft :: Monad m => m [a] -> m [(a, Module)]
genFinderPatternTopLeft = genFinderPattern emptyFinderPatternRow [] [] [Light]
genFinderPatternTopRight :: Monad m => m [a] -> m [(a, Module)]
genFinderPatternTopRight = genFinderPattern emptyFinderPatternRow [] [Light] []
genFinderPatternBottomLeft :: Monad m => m [a] -> m [(a, Module)]
genFinderPatternBottomLeft = genFinderPattern [] emptyFinderPatternRow [] [Light]
genAlignmentPatterns :: [a] -> [(a, Module)]
genAlignmentPatterns = flip zip (cycle patternMods)
where
patternMods = [ Dark, Dark, Dark, Dark, Dark
, Dark, Light, Light, Light, Dark
, Dark, Light, Dark, Light, Dark
, Dark, Light, Light, Light, Dark
, Dark, Dark, Dark, Dark, Dark
]
overlapsFinder :: (Int,Int) -> ReaderQR Bool
overlapsFinder (r,c) = do
a <- natural 8
return $ (r >= a && c >= a) || (r <= 8 && c >= a) || (r >= a && c <= 8)
alignmentCoords :: MonadReader Version m => m [(Int, Int)]
alignmentCoords = do
ver <- ask
let centers = qrAlignmentCenters ver
validCenters = [(x,y) | x <- centers, y <- centers, let inFinder = runReader (overlapsFinder (x,y)) ver, not inFinder]
mkPat (r,c) = [(r',c') | c' <- [c-2..c+2], r' <- [r-2..r+2]]
pats = concatMap mkPat validCenters
return pats
|
9782c47a2926f440de116bf23731c8e048e3dd3ed8eaece90eba0c2122502284 | objectionary/try-phi | Common.hs |
module Common(ppPhiToEO, ppWHNF, ppWHNFSteps, ppNF, ppTapSteps, ppStates, ppGraphs, getTermFromPhi, getTermFromEO, ppEOSource, ppPhi, Common.ppPhiSource, ppPhiToLatex) where
import Phi.Minimal as Phi
( nf,
whnf,
Term,
ppGraphStepsFor,
ppStepsFor,
ppTerm,
ppWhnfSteps,
ppPhiSource )
import Phi.Minimal.ConfigurationDot(renderList)
import qualified Data.Text.Lazy as T
import EOtoPhi(toMinimalTerm)
import EOParser as EOP(parseTermProgram)
import PhiToEO as EP (ppTermTop)
import Data.Text (pack)
import Phi.Minimal.Parser as PMP(parseTerm)
import Text.Megaparsec.Error(errorBundlePretty)
import Phi.Minimal.PPToLatex (Latex(..))
ppPhiSource :: Term -> String
ppPhiSource = show . Phi.ppPhiSource
ppEOSource :: Term -> String
ppEOSource t = (show . EP.ppTermTop) t <> "\n"
ppPhi :: Term -> String
ppPhi = show
ppPhiToEO :: Term -> String
ppPhiToEO = show . Phi.ppTerm
ppPhiToLatex :: Term -> String
ppPhiToLatex t = show (Latex t)
ppWHNF :: Term -> String
ppWHNF = show . Phi.whnf
ppNF :: Term -> String
ppNF = show . Phi.nf
ppWHNFSteps :: Term -> String
ppWHNFSteps = show . Phi.ppWhnfSteps
ppTapSteps :: Term -> String
ppTapSteps = show . Phi.ppStepsFor
-- | list of graph steps
FIXME send a list of steps , render current step on front
ppStates :: Int -> Term -> [String]
ppStates lim term = show <$> Phi.ppGraphStepsFor lim term
ppGraphs :: Int -> Term -> [String]
ppGraphs lim term = T.unpack <$> renderList lim term
getTermFromEO :: String -> Either String Term
getTermFromEO s = ret
where
t1 = toMinimalTerm <$> parseTermProgram (pack s)
ret =
case t1 of
Left l -> Left $ errorBundlePretty l
Right r -> Right r
getTermFromPhi :: String -> Either String Term
getTermFromPhi = PMP.parseTerm
| null | https://raw.githubusercontent.com/objectionary/try-phi/84b063427cb255dd2834df35840355b28e3f7098/back/language-utils/src/Common.hs | haskell | | list of graph steps |
module Common(ppPhiToEO, ppWHNF, ppWHNFSteps, ppNF, ppTapSteps, ppStates, ppGraphs, getTermFromPhi, getTermFromEO, ppEOSource, ppPhi, Common.ppPhiSource, ppPhiToLatex) where
import Phi.Minimal as Phi
( nf,
whnf,
Term,
ppGraphStepsFor,
ppStepsFor,
ppTerm,
ppWhnfSteps,
ppPhiSource )
import Phi.Minimal.ConfigurationDot(renderList)
import qualified Data.Text.Lazy as T
import EOtoPhi(toMinimalTerm)
import EOParser as EOP(parseTermProgram)
import PhiToEO as EP (ppTermTop)
import Data.Text (pack)
import Phi.Minimal.Parser as PMP(parseTerm)
import Text.Megaparsec.Error(errorBundlePretty)
import Phi.Minimal.PPToLatex (Latex(..))
ppPhiSource :: Term -> String
ppPhiSource = show . Phi.ppPhiSource
ppEOSource :: Term -> String
ppEOSource t = (show . EP.ppTermTop) t <> "\n"
ppPhi :: Term -> String
ppPhi = show
ppPhiToEO :: Term -> String
ppPhiToEO = show . Phi.ppTerm
ppPhiToLatex :: Term -> String
ppPhiToLatex t = show (Latex t)
ppWHNF :: Term -> String
ppWHNF = show . Phi.whnf
ppNF :: Term -> String
ppNF = show . Phi.nf
ppWHNFSteps :: Term -> String
ppWHNFSteps = show . Phi.ppWhnfSteps
ppTapSteps :: Term -> String
ppTapSteps = show . Phi.ppStepsFor
FIXME send a list of steps , render current step on front
ppStates :: Int -> Term -> [String]
ppStates lim term = show <$> Phi.ppGraphStepsFor lim term
ppGraphs :: Int -> Term -> [String]
ppGraphs lim term = T.unpack <$> renderList lim term
getTermFromEO :: String -> Either String Term
getTermFromEO s = ret
where
t1 = toMinimalTerm <$> parseTermProgram (pack s)
ret =
case t1 of
Left l -> Left $ errorBundlePretty l
Right r -> Right r
getTermFromPhi :: String -> Either String Term
getTermFromPhi = PMP.parseTerm
|
c84ae8e1c46b5d4364de25f2358f424efd8aeb14705ec4a3eeb624714203e0af | mitchellwrosen/hspolls | API.hs | module Hp.API
( API(..)
) where
import Hp.Entity.Poll (PollId)
import Hp.Entity.User (UserId)
import Hp.GitHub.Code (GitHubCode)
import Hp.RequestBody.AnswerPoll (AnswerPollRequestBody)
import Hp.RequestBody.CreatePoll (CreatePollRequestBody)
import Hp.RequestBody.Subscribe (SubscribeRequestBody)
import Hp.ResponseBody.GetPoll (GetPollResponseBody)
import Hp.UserProfile (UserProfile)
import Servant
import Servant.API.Generic
import Servant.Auth (Auth, Cookie)
import Servant.Auth.Server (SetCookie)
import Servant.HTML.Blaze
import qualified Text.Blaze.Html as Blaze
data API route
= API
{ -- | Answer a poll.
answerPollRoute
:: route
:- Auth '[Cookie] UserId
:> "poll"
:> Capture "PollId" PollId
:> ReqBody '[JSON] AnswerPollRequestBody
:> Post '[JSON] NoContent
-- | Create a poll.
, createPollRoute
:: route
:- Auth '[Cookie] UserId
:> "poll"
:> ReqBody '[JSON] CreatePollRequestBody
:> Post '[JSON] PollId
-- | Get Prometheus metrics.
, getMetricsRoute
:: route
:- "metrics"
:> Get '[PlainText] Text
, getPollRoute
:: route
:- "poll"
:> Capture "PollId" PollId
:> Get '[JSON] GetPollResponseBody
, getRootRoute
:: route
:- Auth '[Cookie] UserId
:> Get '[HTML] Blaze.Html
, getUserProfileRoute
:: route
:- Auth '[Cookie] UserId
:> "profile"
:> Get '[JSON] UserProfile
| Callback URL used for GitHub OAuth .
, gitHubOauthCallbackRoute
:: route
:- "oauth"
:> "github"
:> QueryParam' '[Required, Strict] "code" GitHubCode
TODO required " state " query param
TODO just returning html for now , but should redirect
:> Verb
'GET
302
'[HTML]
(Headers
'[ Header "Location" Text
, Header "Set-Cookie" SetCookie
, Header "Set-Cookie" SetCookie
]
NoContent)
-- | Adjust subscription settings.
, subscribeRoute
:: route
:- Auth '[Cookie] UserId
:> "subscribe"
:> ReqBody '[JSON] SubscribeRequestBody
:> Post '[JSON] NoContent
} deriving stock (Generic)
| null | https://raw.githubusercontent.com/mitchellwrosen/hspolls/22efea743194ade091f7daa112a2d9ce985a4500/src/Hp/API.hs | haskell | | Answer a poll.
| Create a poll.
| Get Prometheus metrics.
| Adjust subscription settings. | module Hp.API
( API(..)
) where
import Hp.Entity.Poll (PollId)
import Hp.Entity.User (UserId)
import Hp.GitHub.Code (GitHubCode)
import Hp.RequestBody.AnswerPoll (AnswerPollRequestBody)
import Hp.RequestBody.CreatePoll (CreatePollRequestBody)
import Hp.RequestBody.Subscribe (SubscribeRequestBody)
import Hp.ResponseBody.GetPoll (GetPollResponseBody)
import Hp.UserProfile (UserProfile)
import Servant
import Servant.API.Generic
import Servant.Auth (Auth, Cookie)
import Servant.Auth.Server (SetCookie)
import Servant.HTML.Blaze
import qualified Text.Blaze.Html as Blaze
data API route
= API
answerPollRoute
:: route
:- Auth '[Cookie] UserId
:> "poll"
:> Capture "PollId" PollId
:> ReqBody '[JSON] AnswerPollRequestBody
:> Post '[JSON] NoContent
, createPollRoute
:: route
:- Auth '[Cookie] UserId
:> "poll"
:> ReqBody '[JSON] CreatePollRequestBody
:> Post '[JSON] PollId
, getMetricsRoute
:: route
:- "metrics"
:> Get '[PlainText] Text
, getPollRoute
:: route
:- "poll"
:> Capture "PollId" PollId
:> Get '[JSON] GetPollResponseBody
, getRootRoute
:: route
:- Auth '[Cookie] UserId
:> Get '[HTML] Blaze.Html
, getUserProfileRoute
:: route
:- Auth '[Cookie] UserId
:> "profile"
:> Get '[JSON] UserProfile
| Callback URL used for GitHub OAuth .
, gitHubOauthCallbackRoute
:: route
:- "oauth"
:> "github"
:> QueryParam' '[Required, Strict] "code" GitHubCode
TODO required " state " query param
TODO just returning html for now , but should redirect
:> Verb
'GET
302
'[HTML]
(Headers
'[ Header "Location" Text
, Header "Set-Cookie" SetCookie
, Header "Set-Cookie" SetCookie
]
NoContent)
, subscribeRoute
:: route
:- Auth '[Cookie] UserId
:> "subscribe"
:> ReqBody '[JSON] SubscribeRequestBody
:> Post '[JSON] NoContent
} deriving stock (Generic)
|
1abe0d122d1f70e1a3d15441c161b8a4d7ee91c2b9fff6b4409a5c16afed2d95 | nada-attia/dama | move.mli | (** [Move] contains functions for moving pieces on the board*)
* the type representing the 4 possible directions a piece can move .
type direction =
| Up
| Down
| Left
| Right
(** Raised when a specified square is not found on the current board.*)
exception SquareNotFound
(** [get_square label board] is the square at position [label] on board
[board]. Raises an exception when a square is not found.*)
val get_square : char * int -> Board.t -> Board.square
(** [get_square_dir square board color direction] is the square in
direction [direction] from square [square] for a piece of color
[color] on board [board]. Raises an exception when a square is not
found .*)
val get_square_dir :
Board.square ->
Board.t ->
Board.color ->
direction ->
Board.square list
(** [where_move board square] are the squares a piece on square [square]
in board [board] it is allowed to move to. Raises an exception if
the provided square is empty. *)
val where_move : Board.t -> Board.square -> Board.square list
(** [where_move_all board color] is all of the squares that can be moved
to for the curently active pieces of color [color] on board [board]. *)
val where_move_all :
Board.t -> Board.color -> (Board.square * Board.square list) list
(** [can_move square board color] is true if a piece of color [color] on
square [square] in board [board] is currently able to move, and
false otherwise. *)
val can_move : Board.square -> Board.t -> Board.color -> bool
(** [get_movable_squares_reg square color board] is all of the squares a
regular piece of color [color] on square [square] in board [board]
can move to. *)
val get_movable_squares_reg :
Board.square -> Board.color -> Board.t -> Board.square list
* [ square board color ] is all of the ( jumped square ,
destination square ) 's that a regular piece of color [ color ] on
square [ square ] in board [ board ] is avalible to take and arrive at .
destination square)'s that a regular piece of color [color] on
square [square] in board [board] is avalible to take and arrive at. *)
val get_all_jumps :
Board.square ->
Board.t ->
Board.color ->
(Board.square * Board.square) list
* [ update_board color square board label1 label2 ] updates the board
for a player of color [ color ] after the player has captured a piece
on square [ square ] by moving from [ label1 ] to [ label2 ] in board
[ board ] .
for a player of color [color] after the player has captured a piece
on square [square] by moving from [label1] to [label2] in board
[board]. *)
val update_board :
Board.color ->
Board.square option ->
Board.t ->
char * int ->
char * int ->
unit
* [ square board color ] is all of the ( jumped
square , destination square ) 's that a lady piece of color [ color ] on
square [ square ] in board [ board ] is avalible to take and arrive at .
square, destination square)'s that a lady piece of color [color] on
square [square] in board [board] is avalible to take and arrive at. *)
val get_all_jumps_lady :
Board.square ->
Board.t ->
Board.color ->
(Board.square * Board.square) list
(** [can_move_all board color] is true if any piece of color [color] in
board [board] is currently able to move, and false otherwise. *)
val can_move_all : Board.t -> Board.color -> bool
(** [exists_jumps color board] is true if any valid jumps exist for a
piece of color [color] in board [board], and false otherwise. *)
val exists_jumps : Board.color -> Board.t -> Board.square list
(** [get_where_jump color board] is all of the destination squares for
all of jumps avalible for pieces of color [color] in board [board]. *)
val get_where_jump : Board.color -> Board.t -> Board.square list
| null | https://raw.githubusercontent.com/nada-attia/dama/df4a792dee2468b65192ff0d0852b579f48c583f/src/move.mli | ocaml | * [Move] contains functions for moving pieces on the board
* Raised when a specified square is not found on the current board.
* [get_square label board] is the square at position [label] on board
[board]. Raises an exception when a square is not found.
* [get_square_dir square board color direction] is the square in
direction [direction] from square [square] for a piece of color
[color] on board [board]. Raises an exception when a square is not
found .
* [where_move board square] are the squares a piece on square [square]
in board [board] it is allowed to move to. Raises an exception if
the provided square is empty.
* [where_move_all board color] is all of the squares that can be moved
to for the curently active pieces of color [color] on board [board].
* [can_move square board color] is true if a piece of color [color] on
square [square] in board [board] is currently able to move, and
false otherwise.
* [get_movable_squares_reg square color board] is all of the squares a
regular piece of color [color] on square [square] in board [board]
can move to.
* [can_move_all board color] is true if any piece of color [color] in
board [board] is currently able to move, and false otherwise.
* [exists_jumps color board] is true if any valid jumps exist for a
piece of color [color] in board [board], and false otherwise.
* [get_where_jump color board] is all of the destination squares for
all of jumps avalible for pieces of color [color] in board [board]. |
* the type representing the 4 possible directions a piece can move .
type direction =
| Up
| Down
| Left
| Right
exception SquareNotFound
val get_square : char * int -> Board.t -> Board.square
val get_square_dir :
Board.square ->
Board.t ->
Board.color ->
direction ->
Board.square list
val where_move : Board.t -> Board.square -> Board.square list
val where_move_all :
Board.t -> Board.color -> (Board.square * Board.square list) list
val can_move : Board.square -> Board.t -> Board.color -> bool
val get_movable_squares_reg :
Board.square -> Board.color -> Board.t -> Board.square list
* [ square board color ] is all of the ( jumped square ,
destination square ) 's that a regular piece of color [ color ] on
square [ square ] in board [ board ] is avalible to take and arrive at .
destination square)'s that a regular piece of color [color] on
square [square] in board [board] is avalible to take and arrive at. *)
val get_all_jumps :
Board.square ->
Board.t ->
Board.color ->
(Board.square * Board.square) list
* [ update_board color square board label1 label2 ] updates the board
for a player of color [ color ] after the player has captured a piece
on square [ square ] by moving from [ label1 ] to [ label2 ] in board
[ board ] .
for a player of color [color] after the player has captured a piece
on square [square] by moving from [label1] to [label2] in board
[board]. *)
val update_board :
Board.color ->
Board.square option ->
Board.t ->
char * int ->
char * int ->
unit
* [ square board color ] is all of the ( jumped
square , destination square ) 's that a lady piece of color [ color ] on
square [ square ] in board [ board ] is avalible to take and arrive at .
square, destination square)'s that a lady piece of color [color] on
square [square] in board [board] is avalible to take and arrive at. *)
val get_all_jumps_lady :
Board.square ->
Board.t ->
Board.color ->
(Board.square * Board.square) list
val can_move_all : Board.t -> Board.color -> bool
val exists_jumps : Board.color -> Board.t -> Board.square list
val get_where_jump : Board.color -> Board.t -> Board.square list
|
9301feac794ec6d7c56ae537db4acf45a7328ab267420ce5a7087af062864e80 | idris-lang/Idris-dev | System.hs | |
Module : IRTS.System
Description : Utilities for interacting with the System .
License : : The Idris Community .
Module : IRTS.System
Description : Utilities for interacting with the System.
License : BSD3
Maintainer : The Idris Community.
-}
# LANGUAGE CPP #
module IRTS.System( getIdrisDataFileByName
, getCC
, getLibFlags
, getIdrisDataDir
, getIdrisLibDir
, getIdrisDocDir
, getIdrisCRTSDir
, getIdrisJSRTSDir
, getIncFlags
, getEnvFlags
, version
) where
#ifdef FREESTANDING
import Paths_idris (version)
import Target_idris
#else
import Paths_idris
#endif
import BuildFlags_idris
import Control.Monad (Monad, liftM2)
import Control.Applicative ((<|>))
import Data.List.Split
import Data.Maybe (fromMaybe)
import System.Environment
import System.FilePath (addTrailingPathSeparator, dropTrailingPathSeparator,
(</>))
getIdrisDataDir :: IO String
getIdrisDataDir = do
envValue <- lookupEnv "TARGET"
case envValue of
Nothing -> do
ddir <- getDataDir
return ddir
Just ddir -> return ddir
getIdrisDataFileByName :: String -> IO FilePath
getIdrisDataFileByName fn = do
dir <- getIdrisDataDir
return $ dir </> fn
overrideIdrisSubDirWith :: String -- ^ Sub directory in `getDataDir` location.
-> String -- ^ Environment variable to get new location from.
-> IO FilePath
overrideIdrisSubDirWith fp envVar = do
envValue <- lookupEnv envVar
case envValue of
Nothing -> do
ddir <- getIdrisDataDir
return (ddir </> fp)
Just ddir -> return ddir
getCC :: IO String
getCC = fromMaybe cc <$> liftM2 (<|>) (lookupEnv "IDRIS_CC") (lookupEnv "CC")
where
#ifdef mingw32_HOST_OS
cc = "gcc"
#else
cc = "cc"
#endif
getEnvFlags :: IO [String]
getEnvFlags = maybe [] (splitOn " ") <$> liftM2 (<|>)
(lookupEnv "IDRIS_CFLAGS") (lookupEnv "CFLAGS")
#if defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS)\
|| defined(openbsd_HOST_OS) || defined(netbsd_HOST_OS)
extraLib = ["-L/usr/local/lib"]
extraInclude = ["-I/usr/local/include"]
#else
extraLib = []
extraInclude = []
#endif
#ifdef IDRIS_GMP
gmpLib = ["-lgmp", "-DIDRIS_GMP"]
#else
gmpLib = []
#endif
extraLibFlags = map ("-L" ++) extraLibDirs
getLibFlags = do dir <- getIdrisCRTSDir
return $ extraLibFlags
++ extraLib
++ ["-L" ++ dropTrailingPathSeparator dir, "-lidris_rts"]
++ gmpLib
++ ["-lpthread"]
getIdrisLibDir = addTrailingPathSeparator <$> overrideIdrisSubDirWith "libs" "IDRIS_LIBRARY_PATH"
getIdrisDocDir = addTrailingPathSeparator <$> overrideIdrisSubDirWith "docs" "IDRIS_DOC_PATH"
getIdrisJSRTSDir = do
ddir <- getIdrisDataDir
return $ addTrailingPathSeparator (ddir </> "jsrts")
getIdrisCRTSDir = do
ddir <- getIdrisDataDir
return $ addTrailingPathSeparator (ddir </> "rts")
getIncFlags = do dir <- getIdrisCRTSDir
return $ ("-I" ++ dropTrailingPathSeparator dir) : extraInclude
| null | https://raw.githubusercontent.com/idris-lang/Idris-dev/0d094e7619d9fed12b3deffd0b68f52c7ddeff21/src/IRTS/System.hs | haskell | ^ Sub directory in `getDataDir` location.
^ Environment variable to get new location from. | |
Module : IRTS.System
Description : Utilities for interacting with the System .
License : : The Idris Community .
Module : IRTS.System
Description : Utilities for interacting with the System.
License : BSD3
Maintainer : The Idris Community.
-}
# LANGUAGE CPP #
module IRTS.System( getIdrisDataFileByName
, getCC
, getLibFlags
, getIdrisDataDir
, getIdrisLibDir
, getIdrisDocDir
, getIdrisCRTSDir
, getIdrisJSRTSDir
, getIncFlags
, getEnvFlags
, version
) where
#ifdef FREESTANDING
import Paths_idris (version)
import Target_idris
#else
import Paths_idris
#endif
import BuildFlags_idris
import Control.Monad (Monad, liftM2)
import Control.Applicative ((<|>))
import Data.List.Split
import Data.Maybe (fromMaybe)
import System.Environment
import System.FilePath (addTrailingPathSeparator, dropTrailingPathSeparator,
(</>))
getIdrisDataDir :: IO String
getIdrisDataDir = do
envValue <- lookupEnv "TARGET"
case envValue of
Nothing -> do
ddir <- getDataDir
return ddir
Just ddir -> return ddir
getIdrisDataFileByName :: String -> IO FilePath
getIdrisDataFileByName fn = do
dir <- getIdrisDataDir
return $ dir </> fn
-> IO FilePath
overrideIdrisSubDirWith fp envVar = do
envValue <- lookupEnv envVar
case envValue of
Nothing -> do
ddir <- getIdrisDataDir
return (ddir </> fp)
Just ddir -> return ddir
getCC :: IO String
getCC = fromMaybe cc <$> liftM2 (<|>) (lookupEnv "IDRIS_CC") (lookupEnv "CC")
where
#ifdef mingw32_HOST_OS
cc = "gcc"
#else
cc = "cc"
#endif
getEnvFlags :: IO [String]
getEnvFlags = maybe [] (splitOn " ") <$> liftM2 (<|>)
(lookupEnv "IDRIS_CFLAGS") (lookupEnv "CFLAGS")
#if defined(freebsd_HOST_OS) || defined(dragonfly_HOST_OS)\
|| defined(openbsd_HOST_OS) || defined(netbsd_HOST_OS)
extraLib = ["-L/usr/local/lib"]
extraInclude = ["-I/usr/local/include"]
#else
extraLib = []
extraInclude = []
#endif
#ifdef IDRIS_GMP
gmpLib = ["-lgmp", "-DIDRIS_GMP"]
#else
gmpLib = []
#endif
extraLibFlags = map ("-L" ++) extraLibDirs
getLibFlags = do dir <- getIdrisCRTSDir
return $ extraLibFlags
++ extraLib
++ ["-L" ++ dropTrailingPathSeparator dir, "-lidris_rts"]
++ gmpLib
++ ["-lpthread"]
getIdrisLibDir = addTrailingPathSeparator <$> overrideIdrisSubDirWith "libs" "IDRIS_LIBRARY_PATH"
getIdrisDocDir = addTrailingPathSeparator <$> overrideIdrisSubDirWith "docs" "IDRIS_DOC_PATH"
getIdrisJSRTSDir = do
ddir <- getIdrisDataDir
return $ addTrailingPathSeparator (ddir </> "jsrts")
getIdrisCRTSDir = do
ddir <- getIdrisDataDir
return $ addTrailingPathSeparator (ddir </> "rts")
getIncFlags = do dir <- getIdrisCRTSDir
return $ ("-I" ++ dropTrailingPathSeparator dir) : extraInclude
|
5c012a2dae9e6ed799364a4e27a593ffef586a978f5cd1b9eff1c79b01452942 | mfoemmel/erlang-otp | orber_ifr_repository.erl | %%--------------------------------------------------------------------
%%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%
%%----------------------------------------------------------------------
%% File : orber_ifr_repository.erl
%% Purpose : Code for Repository
%%----------------------------------------------------------------------
-module(orber_ifr_repository).
-export(['_get_def_kind'/1,
destroy/1,
lookup/2,
contents/3,
lookup_name/5,
describe_contents/4,
create_module/4,
create_constant/6,
create_struct/5,
create_union/6,
create_enum/5,
create_alias/5,
create_interface/5,
create_exception/5,
lookup_id/2,
get_primitive/2,
create_string/2,
create_wstring/2,
create_fixed/3,
create_sequence/3,
create_array/3,
not in CORBA 2.0
not in CORBA 2.0
not in CORBA 2.0
]).
-include("orber_ifr.hrl").
-include("ifr_objects.hrl").
-include_lib("orber/include/corba.hrl").
%%%======================================================================
Repository ( Container ( IRObject ) )
%%%----------------------------------------------------------------------
Interfaces inherited from IRObject
'_get_def_kind'({ObjType, ObjID}) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_irobject:'_get_def_kind'({ObjType, ObjID}).
destroy({ObjType, ObjID}) ?tcheck(ir_Repository, ObjType) ->
orber:dbg("[~p] ~p:destroy(~p, ~p);~n"
"Destroying a repository is an error.~n",
[?LINE, ?MODULE, ObjType, ObjID], ?DEBUG_LEVEL),
corba:raise(#'INTF_REPOS'{completion_status=?COMPLETED_NO}).
%%%----------------------------------------------------------------------
Interfaces inherited from Container
lookup({ObjType,ObjID}, Search_name) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:lookup({ObjType, ObjID}, Search_name).
contents({ObjType,ObjID}, Limit_type, Exclude_inherited)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:contents({ObjType,ObjID},Limit_type,Exclude_inherited).
lookup_name({ObjType,ObjID}, Search_name, Levels_to_search, Limit_type,
Exclude_inherited) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:lookup_name({ObjType, ObjID}, Search_name,
Levels_to_search, Limit_type,
Exclude_inherited).
describe_contents({ObjType,ObjID}, Limit_type, Exclude_inherited,
Max_returned_objs) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:describe_contents({ObjType, ObjID}, Limit_type,
Exclude_inherited,Max_returned_objs).
create_module({ObjType,ObjID}, Id, Name, Version)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_module({ObjType,ObjID}, Id, Name, Version).
create_constant({ObjType,ObjID}, Id, Name, Version, Type, Value)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_constant({ObjType,ObjID}, Id, Name, Version,
Type, Value).
create_struct({ObjType,ObjID}, Id, Name, Version, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_struct({ObjType,ObjID}, Id, Name, Version,
Members).
create_union({ObjType,ObjID}, Id, Name, Version, Discriminator_type, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_union({ObjType,ObjID}, Id, Name, Version,
Discriminator_type, Members).
create_enum({ObjType,ObjID}, Id, Name, Version, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_enum({ObjType,ObjID},Id,Name,Version,Members).
create_alias({ObjType,ObjID}, Id, Name, Version, Original_type)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_alias({ObjType,ObjID}, Id, Name, Version,
Original_type).
create_interface({ObjType,ObjID}, Id, Name, Version, Base_interfaces)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_interface({ObjType,ObjID}, Id, Name, Version,
Base_interfaces).
create_exception({ObjType, ObjID}, Id, Name, Version, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_exception({ObjType, ObjID}, Id, Name, Version,
Members).
%%%----------------------------------------------------------------------
%%% Non-inherited interfaces
lookup_id({ObjType,ObjID}, Search_id) ?tcheck(ir_Repository, ObjType) ->
Contents = orber_ifr_container:contents({ObjType, ObjID}, dk_All, false),
case lists:filter(fun(X) -> orber_ifr_contained:'_get_id'(X) == Search_id
end, Contents) of
[] ->
[];
[ObjRef] ->
ObjRef;
[H|T] ->
%% This case is just a safety-guard; orber_ifr_container:contents
%% sometimes return duplicates due to inheritance.
case lists:any(fun(X) -> X =/= H end, T) of
false ->
H;
true ->
corba:raise(#'INTERNAL'{completion_status=?COMPLETED_NO})
end
end.
get_primitive({ObjType,ObjID}, Kind) ?tcheck(ir_Repository, ObjType) ->
Primitivedefs = orber_ifr_utils:get_field({ObjType,ObjID}, primitivedefs),
lists:filter(fun(X) -> orber_ifr_primitivedef:'_get_kind'(X) == Kind end,
Primitivedefs).
%% It is probably incorrect to add the anonymous typedefs (string,
%% sequence and array) to the field primitivdefs in the Repository.
%% It is probably also not correct to add them to the contents field.
%% Perhaps it is necessary to add another field in the ir_Repository
%% record for anonymous typedefs? Then again, perhaps it is not
%% necessary to keep the anonymous typedefs anywhere? According to
%% the specification it is the callers responsibility to destroy the
%% anonymous typedef if it is not successfully used.
create_string({ObjType,_ObjID}, Bound) ?tcheck(ir_Repository, ObjType) ->
New_string = #ir_StringDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_String,
type = {tk_string, Bound},
bound = Bound},
orber_ifr_utils:makeref(New_string).
create_wstring({ObjType,_ObjID}, Bound) ?tcheck(ir_Repository, ObjType) ->
NewWstring = #ir_WstringDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Wstring,
type = {tk_wstring, Bound},
bound = Bound},
orber_ifr_utils:makeref(NewWstring).
create_fixed({ObjType,_ObjID}, Digits, Scale) ?tcheck(ir_Repository, ObjType) ->
NewFixed = #ir_FixedDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Fixed,
type = {tk_fixed, Digits, Scale},
digits = Digits,
scale = Scale},
orber_ifr_utils:makeref(NewFixed).
create_sequence({ObjType,_ObjID}, Bound, Element_type)
?tcheck(ir_Repository, ObjType) ->
Element_typecode = orber_ifr_utils:get_field(Element_type, type),
New_sequence = #ir_SequenceDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Sequence,
type = {tk_sequence,Element_typecode,Bound},
bound = Bound,
element_type = Element_typecode,
element_type_def = Element_type},
orber_ifr_utils:makeref(New_sequence).
create_array({ObjType,_ObjID}, Length, Element_type)
?tcheck(ir_Repository, ObjType) ->
Element_typecode = orber_ifr_utils:get_field(Element_type, type),
New_array = #ir_ArrayDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Array,
type = {tk_array, Element_typecode, Length},
length = Length,
element_type = Element_typecode,
element_type_def = Element_type},
orber_ifr_utils:makeref(New_array).
%%%----------------------------------------------------------------------
Extra interfaces ( not in the IDL - spec for the IFR ) .
create_idltype(#orber_light_ifr_ref{} = LRef, _Typecode) ->
LRef;
create_idltype({ObjType,_ObjID}, Typecode) ?tcheck(ir_Repository, ObjType) ->
New_idltype = #ir_IDLType{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_none,
type=Typecode},
orber_ifr_utils:set_object(New_idltype),
orber_ifr_utils:makeref(New_idltype).
create_primitivedef(Pkind) ->
create_primitivedef(Pkind, true).
create_primitivedef(Pkind, Transaction) ->
Typecode = case Pkind of
pk_void ->
tk_void;
pk_short ->
tk_short;
pk_long ->
tk_long;
pk_longlong ->
tk_longlong;
pk_ushort ->
tk_ushort;
pk_ulong ->
tk_ulong;
pk_ulonglong ->
tk_ulonglong;
pk_float ->
tk_float;
pk_double ->
tk_double;
pk_boolean ->
tk_boolean;
pk_char ->
tk_char;
pk_wchar ->
tk_wchar;
pk_fixed ->
tk_fixed;
pk_octet ->
tk_octet;
pk_any ->
tk_any;
pk_TypeCode ->
tk_TypeCode;
pk_Principal ->
tk_Principal;
pk_string ->
orber_ifr_orb:create_string_tc(0);
pk_wstring ->
orber_ifr_orb:create_wstring_tc(0);
pk_objref ->
%%*** what should the Id and Name be here?
orber_ifr_orb:create_interface_tc("", "");
_ ->
orber:dbg("[~p] ~p:destroy(~p);~n"
"Illegal primitivekin.~n",
[?LINE, ?MODULE, Pkind], ?DEBUG_LEVEL),
corba:raise(#'INTF_REPOS'{completion_status=?COMPLETED_NO})
end,
New_primitivedef = #ir_PrimitiveDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Primitive,
type = Typecode,
kind = Pkind},
case Transaction of
true ->
orber_ifr_utils:set_object(New_primitivedef);
false ->
mnesia:write(New_primitivedef)
end,
orber_ifr_utils:makeref(New_primitivedef).
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/orber/src/orber_ifr_repository.erl | erlang | --------------------------------------------------------------------
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
----------------------------------------------------------------------
File : orber_ifr_repository.erl
Purpose : Code for Repository
----------------------------------------------------------------------
======================================================================
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Non-inherited interfaces
This case is just a safety-guard; orber_ifr_container:contents
sometimes return duplicates due to inheritance.
It is probably incorrect to add the anonymous typedefs (string,
sequence and array) to the field primitivdefs in the Repository.
It is probably also not correct to add them to the contents field.
Perhaps it is necessary to add another field in the ir_Repository
record for anonymous typedefs? Then again, perhaps it is not
necessary to keep the anonymous typedefs anywhere? According to
the specification it is the callers responsibility to destroy the
anonymous typedef if it is not successfully used.
----------------------------------------------------------------------
*** what should the Id and Name be here? | Copyright Ericsson AB 1997 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(orber_ifr_repository).
-export(['_get_def_kind'/1,
destroy/1,
lookup/2,
contents/3,
lookup_name/5,
describe_contents/4,
create_module/4,
create_constant/6,
create_struct/5,
create_union/6,
create_enum/5,
create_alias/5,
create_interface/5,
create_exception/5,
lookup_id/2,
get_primitive/2,
create_string/2,
create_wstring/2,
create_fixed/3,
create_sequence/3,
create_array/3,
not in CORBA 2.0
not in CORBA 2.0
not in CORBA 2.0
]).
-include("orber_ifr.hrl").
-include("ifr_objects.hrl").
-include_lib("orber/include/corba.hrl").
Repository ( Container ( IRObject ) )
Interfaces inherited from IRObject
'_get_def_kind'({ObjType, ObjID}) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_irobject:'_get_def_kind'({ObjType, ObjID}).
destroy({ObjType, ObjID}) ?tcheck(ir_Repository, ObjType) ->
orber:dbg("[~p] ~p:destroy(~p, ~p);~n"
"Destroying a repository is an error.~n",
[?LINE, ?MODULE, ObjType, ObjID], ?DEBUG_LEVEL),
corba:raise(#'INTF_REPOS'{completion_status=?COMPLETED_NO}).
Interfaces inherited from Container
lookup({ObjType,ObjID}, Search_name) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:lookup({ObjType, ObjID}, Search_name).
contents({ObjType,ObjID}, Limit_type, Exclude_inherited)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:contents({ObjType,ObjID},Limit_type,Exclude_inherited).
lookup_name({ObjType,ObjID}, Search_name, Levels_to_search, Limit_type,
Exclude_inherited) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:lookup_name({ObjType, ObjID}, Search_name,
Levels_to_search, Limit_type,
Exclude_inherited).
describe_contents({ObjType,ObjID}, Limit_type, Exclude_inherited,
Max_returned_objs) ?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:describe_contents({ObjType, ObjID}, Limit_type,
Exclude_inherited,Max_returned_objs).
create_module({ObjType,ObjID}, Id, Name, Version)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_module({ObjType,ObjID}, Id, Name, Version).
create_constant({ObjType,ObjID}, Id, Name, Version, Type, Value)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_constant({ObjType,ObjID}, Id, Name, Version,
Type, Value).
create_struct({ObjType,ObjID}, Id, Name, Version, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_struct({ObjType,ObjID}, Id, Name, Version,
Members).
create_union({ObjType,ObjID}, Id, Name, Version, Discriminator_type, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_union({ObjType,ObjID}, Id, Name, Version,
Discriminator_type, Members).
create_enum({ObjType,ObjID}, Id, Name, Version, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_enum({ObjType,ObjID},Id,Name,Version,Members).
create_alias({ObjType,ObjID}, Id, Name, Version, Original_type)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_alias({ObjType,ObjID}, Id, Name, Version,
Original_type).
create_interface({ObjType,ObjID}, Id, Name, Version, Base_interfaces)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_interface({ObjType,ObjID}, Id, Name, Version,
Base_interfaces).
create_exception({ObjType, ObjID}, Id, Name, Version, Members)
?tcheck(ir_Repository, ObjType) ->
orber_ifr_container:create_exception({ObjType, ObjID}, Id, Name, Version,
Members).
lookup_id({ObjType,ObjID}, Search_id) ?tcheck(ir_Repository, ObjType) ->
Contents = orber_ifr_container:contents({ObjType, ObjID}, dk_All, false),
case lists:filter(fun(X) -> orber_ifr_contained:'_get_id'(X) == Search_id
end, Contents) of
[] ->
[];
[ObjRef] ->
ObjRef;
[H|T] ->
case lists:any(fun(X) -> X =/= H end, T) of
false ->
H;
true ->
corba:raise(#'INTERNAL'{completion_status=?COMPLETED_NO})
end
end.
get_primitive({ObjType,ObjID}, Kind) ?tcheck(ir_Repository, ObjType) ->
Primitivedefs = orber_ifr_utils:get_field({ObjType,ObjID}, primitivedefs),
lists:filter(fun(X) -> orber_ifr_primitivedef:'_get_kind'(X) == Kind end,
Primitivedefs).
create_string({ObjType,_ObjID}, Bound) ?tcheck(ir_Repository, ObjType) ->
New_string = #ir_StringDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_String,
type = {tk_string, Bound},
bound = Bound},
orber_ifr_utils:makeref(New_string).
create_wstring({ObjType,_ObjID}, Bound) ?tcheck(ir_Repository, ObjType) ->
NewWstring = #ir_WstringDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Wstring,
type = {tk_wstring, Bound},
bound = Bound},
orber_ifr_utils:makeref(NewWstring).
create_fixed({ObjType,_ObjID}, Digits, Scale) ?tcheck(ir_Repository, ObjType) ->
NewFixed = #ir_FixedDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Fixed,
type = {tk_fixed, Digits, Scale},
digits = Digits,
scale = Scale},
orber_ifr_utils:makeref(NewFixed).
create_sequence({ObjType,_ObjID}, Bound, Element_type)
?tcheck(ir_Repository, ObjType) ->
Element_typecode = orber_ifr_utils:get_field(Element_type, type),
New_sequence = #ir_SequenceDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Sequence,
type = {tk_sequence,Element_typecode,Bound},
bound = Bound,
element_type = Element_typecode,
element_type_def = Element_type},
orber_ifr_utils:makeref(New_sequence).
create_array({ObjType,_ObjID}, Length, Element_type)
?tcheck(ir_Repository, ObjType) ->
Element_typecode = orber_ifr_utils:get_field(Element_type, type),
New_array = #ir_ArrayDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Array,
type = {tk_array, Element_typecode, Length},
length = Length,
element_type = Element_typecode,
element_type_def = Element_type},
orber_ifr_utils:makeref(New_array).
Extra interfaces ( not in the IDL - spec for the IFR ) .
create_idltype(#orber_light_ifr_ref{} = LRef, _Typecode) ->
LRef;
create_idltype({ObjType,_ObjID}, Typecode) ?tcheck(ir_Repository, ObjType) ->
New_idltype = #ir_IDLType{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_none,
type=Typecode},
orber_ifr_utils:set_object(New_idltype),
orber_ifr_utils:makeref(New_idltype).
create_primitivedef(Pkind) ->
create_primitivedef(Pkind, true).
create_primitivedef(Pkind, Transaction) ->
Typecode = case Pkind of
pk_void ->
tk_void;
pk_short ->
tk_short;
pk_long ->
tk_long;
pk_longlong ->
tk_longlong;
pk_ushort ->
tk_ushort;
pk_ulong ->
tk_ulong;
pk_ulonglong ->
tk_ulonglong;
pk_float ->
tk_float;
pk_double ->
tk_double;
pk_boolean ->
tk_boolean;
pk_char ->
tk_char;
pk_wchar ->
tk_wchar;
pk_fixed ->
tk_fixed;
pk_octet ->
tk_octet;
pk_any ->
tk_any;
pk_TypeCode ->
tk_TypeCode;
pk_Principal ->
tk_Principal;
pk_string ->
orber_ifr_orb:create_string_tc(0);
pk_wstring ->
orber_ifr_orb:create_wstring_tc(0);
pk_objref ->
orber_ifr_orb:create_interface_tc("", "");
_ ->
orber:dbg("[~p] ~p:destroy(~p);~n"
"Illegal primitivekin.~n",
[?LINE, ?MODULE, Pkind], ?DEBUG_LEVEL),
corba:raise(#'INTF_REPOS'{completion_status=?COMPLETED_NO})
end,
New_primitivedef = #ir_PrimitiveDef{ir_Internal_ID = orber_ifr_utils:unique(),
def_kind = dk_Primitive,
type = Typecode,
kind = Pkind},
case Transaction of
true ->
orber_ifr_utils:set_object(New_primitivedef);
false ->
mnesia:write(New_primitivedef)
end,
orber_ifr_utils:makeref(New_primitivedef).
|
d55a23afc4403628a929f36071bf1dcedc301ffcaa17cc6b45fc3c905216ebab | cpsc411/cpsc411-pub | info.rkt | #lang info
(define collection 'multi)
(define deps '(("base" #:version "7.3")))
(define build-deps
'("at-exp-lib"
"scribble-bettergrammar-lib"
("base" #:version "7.3")
"scribble-lib"
"racket-doc"
"rackunit-doc"
"rackunit-lib"
"sandbox-lib"
"cpsc411-lib"))
(define pkg-desc "Documentation for CPSC411 library.")
(define pkg-authors '(wilbowma))
| null | https://raw.githubusercontent.com/cpsc411/cpsc411-pub/757ececf84d54d86cfa0c2c6c84f1456c8765db9/cpsc411-doc/info.rkt | racket | #lang info
(define collection 'multi)
(define deps '(("base" #:version "7.3")))
(define build-deps
'("at-exp-lib"
"scribble-bettergrammar-lib"
("base" #:version "7.3")
"scribble-lib"
"racket-doc"
"rackunit-doc"
"rackunit-lib"
"sandbox-lib"
"cpsc411-lib"))
(define pkg-desc "Documentation for CPSC411 library.")
(define pkg-authors '(wilbowma))
| |
237a0e528409a9a90f2f556974d6c7c35f5d2ea0a1de0b73bac93fff87bd9493 | jwiegley/hours | Main.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE TupleSections #
module Main where
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Semigroup (Semigroup((<>)))
import Data.Time (UTCTime, getCurrentTime, getCurrentTimeZone)
import Hours.Budget (mapValues)
import Hours.Input (WorkDay(NotWorking), encodeIntervals)
import Hours.Time (parseIso)
import Options.Applicative
import System.IO.Unsafe
import Timelog (parseLogbook)
data Options = Options
{ now :: UTCTime
, timelog :: FilePath
}
deriving Show
instance MonadFail (Either String) where
fail = Left
options :: Parser Options
options = Options
<$> option parseT
(long "now" <>
help "Set the meaning of now" <>
value (unsafePerformIO getCurrentTime))
<*> strOption (long "file" <> help "File containing timelog data")
where
parseT :: ReadM UTCTime
parseT = eitherReader parseIso
main :: IO ()
main = do
opts <- execParser $ info (helper <*> options)
(fullDesc <> progDesc "Report work periods"
<> header "work-periods")
input <- case timelog opts of
"-" -> getContents
path -> readFile path
zone <- getCurrentTimeZone
let (logged, ints) = parseLogbook zone (now opts) input
BL.putStrLn (encodeIntervals (now opts) (not (null logged))
(mapValues (NotWorking,) ints))
| null | https://raw.githubusercontent.com/jwiegley/hours/3331fe105ed0820085e4bc26e348340568922b8b/timelog/Main.hs | haskell | # LANGUAGE FlexibleInstances #
# LANGUAGE TupleSections #
module Main where
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Semigroup (Semigroup((<>)))
import Data.Time (UTCTime, getCurrentTime, getCurrentTimeZone)
import Hours.Budget (mapValues)
import Hours.Input (WorkDay(NotWorking), encodeIntervals)
import Hours.Time (parseIso)
import Options.Applicative
import System.IO.Unsafe
import Timelog (parseLogbook)
data Options = Options
{ now :: UTCTime
, timelog :: FilePath
}
deriving Show
instance MonadFail (Either String) where
fail = Left
options :: Parser Options
options = Options
<$> option parseT
(long "now" <>
help "Set the meaning of now" <>
value (unsafePerformIO getCurrentTime))
<*> strOption (long "file" <> help "File containing timelog data")
where
parseT :: ReadM UTCTime
parseT = eitherReader parseIso
main :: IO ()
main = do
opts <- execParser $ info (helper <*> options)
(fullDesc <> progDesc "Report work periods"
<> header "work-periods")
input <- case timelog opts of
"-" -> getContents
path -> readFile path
zone <- getCurrentTimeZone
let (logged, ints) = parseLogbook zone (now opts) input
BL.putStrLn (encodeIntervals (now opts) (not (null logged))
(mapValues (NotWorking,) ints))
| |
008fec718ec8df82b7a68076695bbbf752cf4b7f055d950b26d851fc69de512d | dschrempf/elynx | Sequence.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
-- Module : ELynx.Sequence
-- Description : Hereditary sequences
Copyright : 2021
License : GPL-3.0 - or - later
--
-- Maintainer :
-- Stability : unstable
-- Portability : portable
--
Creation date : Thu Oct 4 18:54:51 2018 .
--
-- This module is to be imported qualified.
module ELynx.Sequence.Sequence
( -- * Types
Name,
Description,
Characters,
Sequence (..),
-- * Input
fromByteString,
-- * Output
toByteString,
header,
summarize,
summarizeSequences,
body,
-- * Analysis
length,
equalLength,
longest,
-- * Manipulation
trim,
concat,
concatSequences,
-- * Filtering
filterShorterThan,
filterLongerThan,
filterStandard,
)
where
import Control.Parallel.Strategies
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List (maximumBy)
import Data.Ord (comparing)
import qualified Data.Vector.Unboxed as V
import qualified ELynx.Alphabet.Alphabet as A
import ELynx.Alphabet.Character
import ELynx.Sequence.Defaults
import qualified Text.Printf as P
import Prelude hiding
( concat,
length,
)
import qualified Prelude as Pr
( length,
)
-- | 'Name's are just 'BL.ByteString's.
type Name = BL.ByteString
-- | The description of a sequence.
type Description = BL.ByteString
-- | The vector of characters of a sequence.
type Characters = V.Vector Character
-- | Convert byte string to sequence characters.
fromByteString :: BL.ByteString -> Characters
fromByteString = V.fromList . map fromChar . BL.unpack
-- | Convert sequence characters to byte string.
toByteString :: Characters -> BL.ByteString
toByteString = BL.pack . map toChar . V.toList
-- | Sequences have a name, a possibly empty description, a code and hopefully a
-- lot of data.
data Sequence = Sequence
{ name :: Name,
description :: Description,
alphabet :: A.Alphabet,
characters :: Characters
}
deriving (Show, Eq)
alignRight :: Int -> BL.ByteString -> BL.ByteString
alignRight n s =
BL.replicate (fromIntegral n - l) ' ' <> BL.take (fromIntegral n) s
where
l = BL.length s
alignLeft :: Int -> BL.ByteString -> BL.ByteString
alignLeft n s =
BL.take (fromIntegral n) s <> BL.replicate (fromIntegral n - l) ' '
where
l = BL.length s
getInfo :: Sequence -> BL.ByteString
getInfo s =
BL.unwords
[ alignLeft nameWidth (name s),
alignRight fieldWidth (BL.pack $ show $ alphabet s),
alignRight fieldWidth (BL.pack . show $ len),
alignRight fieldWidth (BL.pack $ P.printf "%2.2f" pGaps)
]
where
len = length s
nGaps = countGaps s
pGaps = 100 * fromIntegral nGaps / fromIntegral len :: Double
-- If a string is longer than a given value, trim it and add some dots.
summarizeByteString :: Int -> BL.ByteString -> BL.ByteString
summarizeByteString l s
| BL.length s >= fromIntegral l = BL.take (fromIntegral l) s <> BL.pack "..."
| otherwise = s
-- | Trim and show a 'Sequence'.
summarize :: Sequence -> BL.ByteString
summarize s =
BL.unwords
[getInfo s, summarizeByteString summaryLength $ toByteString (characters s)]
-- | Trim and show a list of 'Sequence's.
summarizeSequences :: [Sequence] -> BL.ByteString
summarizeSequences ss = header ss <> body (take summaryNSequences ss)
-- | Header printed before 'Sequence' list.
tableHeader :: BL.ByteString
tableHeader =
BL.unwords
[ alignLeft nameWidth "Name",
alignRight fieldWidth "Code",
alignRight fieldWidth "Length",
alignRight fieldWidth "Gaps [%]",
"Sequence"
]
-- | A short description of the sequence.
header :: [Sequence] -> BL.ByteString
header ss =
BL.unlines $
reportIfSubsetIsShown
++ [ BL.pack $
"For each sequence, the "
++ show summaryLength
++ " first bases are shown.",
BL.pack $ "List contains " ++ show (Pr.length ss) ++ " sequences.",
"",
tableHeader
]
where
l = Pr.length ss
s =
show summaryNSequences
++ " out of "
++ show (Pr.length ss)
++ " sequences are shown."
reportIfSubsetIsShown
| l > summaryNSequences = [BL.pack s]
| otherwise = []
-- | Trim and show a list of 'Sequence's.
body :: [Sequence] -> BL.ByteString
body ss = BL.unlines (map summarize ss `using` parListChunk 5 rdeepseq)
-- | Calculate length of 'Sequence'.
length :: Sequence -> Int
length = fromIntegral . V.length . characters
| Check if all ' Sequence 's have equal length .
equalLength :: [Sequence] -> Bool
equalLength = allEqual . map length
where
allEqual [] = True
allEqual xs = all (== head xs) $ tail xs
-- | Find the longest 'Sequence' in a list.
longest :: [Sequence] -> Sequence
longest = maximumBy (comparing length)
-- | Count number of gaps or unknown characters in sequence.
countGaps :: Sequence -> Int
countGaps s = V.length . V.filter (A.isGap $ alphabet s) $ characters s
-- | Trim to given length.
trim :: Int -> Sequence -> Sequence
trim n (Sequence nm d a cs) = Sequence nm d a (V.take (fromIntegral n) cs)
| Concatenate two sequences . ' Name 's have to match .
concat :: Sequence -> Sequence -> Sequence
concat (Sequence i d c cs) (Sequence j f k ks)
| i /= j =
error $
"concatenate: Sequences do not have equal names: "
++ BL.unpack i
++ ", "
++ BL.unpack j
++ "."
| d /= f =
error $
"concatenate: Sequences do not have equal descriptions: "
++ BL.unpack d
++ ", "
++ BL.unpack f
++ "."
| c /= k =
error $
"concatenate: Sequences do not have equal alphabets: "
++ show c
++ ", "
++ show k
++ "."
| otherwise =
Sequence i d c (cs <> ks)
-- | Concatenate a list of sequences, see 'concat'.
concatSequences :: [[Sequence]] -> [Sequence]
concatSequences [] = error "concatenateSequences: Nothing to concatenate."
concatSequences [ss] = ss
concatSequences sss = foldl1 (zipWith concat) sss
-- | Only take 'Sequence's that are shorter than a given number.
filterShorterThan :: Int -> [Sequence] -> [Sequence]
filterShorterThan n = filter (\x -> length x < n)
-- | Only take 'Sequence's that are longer than a given number.
filterLongerThan :: Int -> [Sequence] -> [Sequence]
filterLongerThan n = filter (\x -> length x > n)
-- | Only take 'Sequence's that contain at least on non-IUPAC character.
filterStandard :: [Sequence] -> [Sequence]
filterStandard = filter (\s -> anyStandard (alphabet s) s)
Are all characters IUPAC characters ?
anyStandard :: A.Alphabet -> Sequence -> Bool
anyStandard a s = V.any (A.isStd a) cs where cs = characters s
| null | https://raw.githubusercontent.com/dschrempf/elynx/69df2fcf5fd6351f062586352da3ce59a8786a36/elynx-seq/src/ELynx/Sequence/Sequence.hs | haskell | # LANGUAGE OverloadedStrings #
|
Module : ELynx.Sequence
Description : Hereditary sequences
Maintainer :
Stability : unstable
Portability : portable
This module is to be imported qualified.
* Types
* Input
* Output
* Analysis
* Manipulation
* Filtering
| 'Name's are just 'BL.ByteString's.
| The description of a sequence.
| The vector of characters of a sequence.
| Convert byte string to sequence characters.
| Convert sequence characters to byte string.
| Sequences have a name, a possibly empty description, a code and hopefully a
lot of data.
If a string is longer than a given value, trim it and add some dots.
| Trim and show a 'Sequence'.
| Trim and show a list of 'Sequence's.
| Header printed before 'Sequence' list.
| A short description of the sequence.
| Trim and show a list of 'Sequence's.
| Calculate length of 'Sequence'.
| Find the longest 'Sequence' in a list.
| Count number of gaps or unknown characters in sequence.
| Trim to given length.
| Concatenate a list of sequences, see 'concat'.
| Only take 'Sequence's that are shorter than a given number.
| Only take 'Sequence's that are longer than a given number.
| Only take 'Sequence's that contain at least on non-IUPAC character. |
Copyright : 2021
License : GPL-3.0 - or - later
Creation date : Thu Oct 4 18:54:51 2018 .
module ELynx.Sequence.Sequence
Name,
Description,
Characters,
Sequence (..),
fromByteString,
toByteString,
header,
summarize,
summarizeSequences,
body,
length,
equalLength,
longest,
trim,
concat,
concatSequences,
filterShorterThan,
filterLongerThan,
filterStandard,
)
where
import Control.Parallel.Strategies
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List (maximumBy)
import Data.Ord (comparing)
import qualified Data.Vector.Unboxed as V
import qualified ELynx.Alphabet.Alphabet as A
import ELynx.Alphabet.Character
import ELynx.Sequence.Defaults
import qualified Text.Printf as P
import Prelude hiding
( concat,
length,
)
import qualified Prelude as Pr
( length,
)
type Name = BL.ByteString
type Description = BL.ByteString
type Characters = V.Vector Character
fromByteString :: BL.ByteString -> Characters
fromByteString = V.fromList . map fromChar . BL.unpack
toByteString :: Characters -> BL.ByteString
toByteString = BL.pack . map toChar . V.toList
data Sequence = Sequence
{ name :: Name,
description :: Description,
alphabet :: A.Alphabet,
characters :: Characters
}
deriving (Show, Eq)
alignRight :: Int -> BL.ByteString -> BL.ByteString
alignRight n s =
BL.replicate (fromIntegral n - l) ' ' <> BL.take (fromIntegral n) s
where
l = BL.length s
alignLeft :: Int -> BL.ByteString -> BL.ByteString
alignLeft n s =
BL.take (fromIntegral n) s <> BL.replicate (fromIntegral n - l) ' '
where
l = BL.length s
getInfo :: Sequence -> BL.ByteString
getInfo s =
BL.unwords
[ alignLeft nameWidth (name s),
alignRight fieldWidth (BL.pack $ show $ alphabet s),
alignRight fieldWidth (BL.pack . show $ len),
alignRight fieldWidth (BL.pack $ P.printf "%2.2f" pGaps)
]
where
len = length s
nGaps = countGaps s
pGaps = 100 * fromIntegral nGaps / fromIntegral len :: Double
summarizeByteString :: Int -> BL.ByteString -> BL.ByteString
summarizeByteString l s
| BL.length s >= fromIntegral l = BL.take (fromIntegral l) s <> BL.pack "..."
| otherwise = s
summarize :: Sequence -> BL.ByteString
summarize s =
BL.unwords
[getInfo s, summarizeByteString summaryLength $ toByteString (characters s)]
summarizeSequences :: [Sequence] -> BL.ByteString
summarizeSequences ss = header ss <> body (take summaryNSequences ss)
tableHeader :: BL.ByteString
tableHeader =
BL.unwords
[ alignLeft nameWidth "Name",
alignRight fieldWidth "Code",
alignRight fieldWidth "Length",
alignRight fieldWidth "Gaps [%]",
"Sequence"
]
header :: [Sequence] -> BL.ByteString
header ss =
BL.unlines $
reportIfSubsetIsShown
++ [ BL.pack $
"For each sequence, the "
++ show summaryLength
++ " first bases are shown.",
BL.pack $ "List contains " ++ show (Pr.length ss) ++ " sequences.",
"",
tableHeader
]
where
l = Pr.length ss
s =
show summaryNSequences
++ " out of "
++ show (Pr.length ss)
++ " sequences are shown."
reportIfSubsetIsShown
| l > summaryNSequences = [BL.pack s]
| otherwise = []
body :: [Sequence] -> BL.ByteString
body ss = BL.unlines (map summarize ss `using` parListChunk 5 rdeepseq)
length :: Sequence -> Int
length = fromIntegral . V.length . characters
| Check if all ' Sequence 's have equal length .
equalLength :: [Sequence] -> Bool
equalLength = allEqual . map length
where
allEqual [] = True
allEqual xs = all (== head xs) $ tail xs
longest :: [Sequence] -> Sequence
longest = maximumBy (comparing length)
countGaps :: Sequence -> Int
countGaps s = V.length . V.filter (A.isGap $ alphabet s) $ characters s
trim :: Int -> Sequence -> Sequence
trim n (Sequence nm d a cs) = Sequence nm d a (V.take (fromIntegral n) cs)
| Concatenate two sequences . ' Name 's have to match .
concat :: Sequence -> Sequence -> Sequence
concat (Sequence i d c cs) (Sequence j f k ks)
| i /= j =
error $
"concatenate: Sequences do not have equal names: "
++ BL.unpack i
++ ", "
++ BL.unpack j
++ "."
| d /= f =
error $
"concatenate: Sequences do not have equal descriptions: "
++ BL.unpack d
++ ", "
++ BL.unpack f
++ "."
| c /= k =
error $
"concatenate: Sequences do not have equal alphabets: "
++ show c
++ ", "
++ show k
++ "."
| otherwise =
Sequence i d c (cs <> ks)
concatSequences :: [[Sequence]] -> [Sequence]
concatSequences [] = error "concatenateSequences: Nothing to concatenate."
concatSequences [ss] = ss
concatSequences sss = foldl1 (zipWith concat) sss
filterShorterThan :: Int -> [Sequence] -> [Sequence]
filterShorterThan n = filter (\x -> length x < n)
filterLongerThan :: Int -> [Sequence] -> [Sequence]
filterLongerThan n = filter (\x -> length x > n)
filterStandard :: [Sequence] -> [Sequence]
filterStandard = filter (\s -> anyStandard (alphabet s) s)
Are all characters IUPAC characters ?
anyStandard :: A.Alphabet -> Sequence -> Bool
anyStandard a s = V.any (A.isStd a) cs where cs = characters s
|
17e48f1b6fc2a0cd368e835800818ba517d0d3876adb93107743614d7b6fc0d2 | racket/algol60 | test.rkt | #lang at-exp racket/base
(require algol60/algol60
rackunit
racket/runtime-path
(for-syntax racket/base))
(define-syntax (capture-output stx)
(syntax-case stx ()
[(_ exp)
(parameterize ([error-print-source-location #f])
(with-handlers ((exn:fail?
(λ (exn)
#`(list 'expand
#,(exn-message exn)))))
(define expanded (local-expand #'exp 'expression #f))
#`(let ([op (open-output-string)]
[ep (open-output-string)])
(let/ec k
(parameterize ([current-output-port op]
[current-error-port ep]
[error-escape-handler (λ () (k (void)))])
#,expanded))
(list 'run
(get-output-string op)
(get-output-string ep)))))]))
(check-equal?
(capture-output
@literal-algol{
begin
printsln (`hello world')
end
})
'(run "hello world\n" ""))
(check-pred
(λ (x) (and (eq? (list-ref x 0) 'expand)
(regexp-match #rx"parse error near BEGIN"
(list-ref x 1))))
(capture-output
@literal-algol{
begin
}))
(check-pred
(λ (x) (and (eq? (list-ref x 0) 'expand)
(regexp-match #rx"parse error near PROCEDURE"
(list-ref x 1))))
(capture-output
@literal-algol{
procedure Absmax(a) Size:(n, m) Result:(y) Subscripts:(i, k);
value n, m; array a; integer n, m, i, k; real y;
begin integer p, q;
i : = k : = 1 ;
for p:=1 step 1 until n do
for q:=1 step 1 until m do
if abs(a[p, q]) > y then
begin y := abs(a[p, q]);
i := p; k := q
end
end Absmax
}))
(define-runtime-path export.rkt "export.rkt")
(check-equal? ((dynamic-require export.rkt 'f) 2) 1/2)
(check-equal? (object-name (dynamic-require export.rkt 'f)) 'f)
| null | https://raw.githubusercontent.com/racket/algol60/e4aebcaff66f121cf52a1f58f4f7bd285eded728/tests/test.rkt | racket |
array a; integer n, m, i, k; real y;
k := q | #lang at-exp racket/base
(require algol60/algol60
rackunit
racket/runtime-path
(for-syntax racket/base))
(define-syntax (capture-output stx)
(syntax-case stx ()
[(_ exp)
(parameterize ([error-print-source-location #f])
(with-handlers ((exn:fail?
(λ (exn)
#`(list 'expand
#,(exn-message exn)))))
(define expanded (local-expand #'exp 'expression #f))
#`(let ([op (open-output-string)]
[ep (open-output-string)])
(let/ec k
(parameterize ([current-output-port op]
[current-error-port ep]
[error-escape-handler (λ () (k (void)))])
#,expanded))
(list 'run
(get-output-string op)
(get-output-string ep)))))]))
(check-equal?
(capture-output
@literal-algol{
begin
printsln (`hello world')
end
})
'(run "hello world\n" ""))
(check-pred
(λ (x) (and (eq? (list-ref x 0) 'expand)
(regexp-match #rx"parse error near BEGIN"
(list-ref x 1))))
(capture-output
@literal-algol{
begin
}))
(check-pred
(λ (x) (and (eq? (list-ref x 0) 'expand)
(regexp-match #rx"parse error near PROCEDURE"
(list-ref x 1))))
(capture-output
@literal-algol{
for p:=1 step 1 until n do
for q:=1 step 1 until m do
if abs(a[p, q]) > y then
end
end Absmax
}))
(define-runtime-path export.rkt "export.rkt")
(check-equal? ((dynamic-require export.rkt 'f) 2) 1/2)
(check-equal? (object-name (dynamic-require export.rkt 'f)) 'f)
|
ad58f68ab7d5a2fc2842941081537a681883efb111829b06fcca1dc00ced216f | Eduap-com/WordMat | lb1.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :common-lisp-user)
(defun lb1 (iprint iter nfun gnorm n m x f g stp finish)
(declare (type f2cl-lib:logical finish)
(type (array double-float (*)) g x)
(type (double-float) stp f gnorm)
(type (f2cl-lib:integer4) m n nfun iter)
(type (array f2cl-lib:integer4 (*)) iprint))
(let ()
(symbol-macrolet ((mp (lb3-mp *lb3-common-block*)))
(f2cl-lib:with-multi-array-data
((iprint f2cl-lib:integer4 iprint-%data% iprint-%offset%)
(x double-float x-%data% x-%offset%)
(g double-float g-%data% g-%offset%))
(prog nil
(cond
((= iter 0)
(f2cl-lib:fformat mp
("*************************************************"
"~%"))
(f2cl-lib:fformat mp
(" N=" 1 (("~5D")) " NUMBER OF CORRECTIONS="
1 (("~2D")) "~%" " INITIAL VALUES" "~%")
n
m)
(f2cl-lib:fformat mp
(" F= " 1 (("~22,15,2,1,'*,,'DE")) " GNORM= "
1 (("~22,15,2,1,'*,,'DE")) "~%")
f
gnorm)
(cond
((>= (f2cl-lib:fref iprint (2) ((1 2))) 1)
(f2cl-lib:fformat mp (" VECTOR X= " "~%"))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE"))) "~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref x-%data%
(i)
((1 n))
x-%offset%)
%ret)))
(f2cl-lib:fformat mp (" GRADIENT VECTOR G= " "~%"))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE"))) "~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref g-%data%
(i)
((1 n))
g-%offset%)
%ret)))))
(f2cl-lib:fformat mp
("*************************************************"
"~%"))
(f2cl-lib:fformat mp
("~%" " I NFN" "~5@T" "FUNC" "~20@T" "GNORM"
"~19@T" "STEPLENGTH" "~%" "~%")))
(t
(if
(and
(= (f2cl-lib:fref iprint-%data% (1) ((1 2)) iprint-%offset%) 0)
(and (/= iter 1) (not finish)))
(go end_label))
(cond
((/= (f2cl-lib:fref iprint (1) ((1 2))) 0)
(cond
((or
(=
(mod (f2cl-lib:int-add iter (f2cl-lib:int-sub 1))
(f2cl-lib:fref iprint (1) ((1 2))))
0)
finish)
(if
(and
(>
(f2cl-lib:fref iprint-%data% (2) ((1 2)) iprint-%offset%)
1)
(> iter 1))
(f2cl-lib:fformat mp
("~%" " I NFN" "~5@T" "FUNC" "~20@T"
"GNORM" "~19@T" "STEPLENGTH" "~%" "~%")))
(f2cl-lib:fformat mp
(2 (1 (("~4D")) "~1@T") "~3@T" 3
(1 (("~22,15,2,1,'*,,'DE")) "~2@T") "~%")
iter
nfun
f
gnorm
stp))
(t
(go end_label))))
(t
(if
(and
(> (f2cl-lib:fref iprint-%data% (2) ((1 2)) iprint-%offset%)
1)
finish)
(f2cl-lib:fformat mp
("~%" " I NFN" "~5@T" "FUNC" "~20@T"
"GNORM" "~19@T" "STEPLENGTH" "~%" "~%")))
(f2cl-lib:fformat mp
(2 (1 (("~4D")) "~1@T") "~3@T" 3
(1 (("~22,15,2,1,'*,,'DE")) "~2@T") "~%")
iter
nfun
f
gnorm
stp)))
(cond
((or (= (f2cl-lib:fref iprint (2) ((1 2))) 2)
(= (f2cl-lib:fref iprint (2) ((1 2))) 3))
(cond
(finish
(f2cl-lib:fformat mp (" FINAL POINT X= " "~%")))
(t
(f2cl-lib:fformat mp (" VECTOR X= " "~%"))))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE"))) "~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref x-%data%
(i)
((1 n))
x-%offset%)
%ret)))
(cond
((= (f2cl-lib:fref iprint (2) ((1 2))) 3)
(f2cl-lib:fformat mp (" GRADIENT VECTOR G= " "~%"))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE")))
"~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref g-%data%
(i)
((1 n))
g-%offset%)
%ret)))))))
(if finish
(f2cl-lib:fformat mp
("~%"
" THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS."
"~%" " IFLAG = 0" "~%")))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil)))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::lb1 fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((array fortran-to-lisp::integer4 (2))
(fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(double-float) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(double-float) (array double-float (*)) (double-float)
fortran-to-lisp::logical)
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls 'nil)))
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/lbfgs/lb1.lisp | lisp | Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ "
" f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ "
" f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ "
" f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ "
" f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" macros.l , v 1.112 2009/01/08 12:57:19 " )
Using Lisp CMU Common Lisp 19f ( 19F )
(in-package :common-lisp-user)
(defun lb1 (iprint iter nfun gnorm n m x f g stp finish)
(declare (type f2cl-lib:logical finish)
(type (array double-float (*)) g x)
(type (double-float) stp f gnorm)
(type (f2cl-lib:integer4) m n nfun iter)
(type (array f2cl-lib:integer4 (*)) iprint))
(let ()
(symbol-macrolet ((mp (lb3-mp *lb3-common-block*)))
(f2cl-lib:with-multi-array-data
((iprint f2cl-lib:integer4 iprint-%data% iprint-%offset%)
(x double-float x-%data% x-%offset%)
(g double-float g-%data% g-%offset%))
(prog nil
(cond
((= iter 0)
(f2cl-lib:fformat mp
("*************************************************"
"~%"))
(f2cl-lib:fformat mp
(" N=" 1 (("~5D")) " NUMBER OF CORRECTIONS="
1 (("~2D")) "~%" " INITIAL VALUES" "~%")
n
m)
(f2cl-lib:fformat mp
(" F= " 1 (("~22,15,2,1,'*,,'DE")) " GNORM= "
1 (("~22,15,2,1,'*,,'DE")) "~%")
f
gnorm)
(cond
((>= (f2cl-lib:fref iprint (2) ((1 2))) 1)
(f2cl-lib:fformat mp (" VECTOR X= " "~%"))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE"))) "~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref x-%data%
(i)
((1 n))
x-%offset%)
%ret)))
(f2cl-lib:fformat mp (" GRADIENT VECTOR G= " "~%"))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE"))) "~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref g-%data%
(i)
((1 n))
g-%offset%)
%ret)))))
(f2cl-lib:fformat mp
("*************************************************"
"~%"))
(f2cl-lib:fformat mp
("~%" " I NFN" "~5@T" "FUNC" "~20@T" "GNORM"
"~19@T" "STEPLENGTH" "~%" "~%")))
(t
(if
(and
(= (f2cl-lib:fref iprint-%data% (1) ((1 2)) iprint-%offset%) 0)
(and (/= iter 1) (not finish)))
(go end_label))
(cond
((/= (f2cl-lib:fref iprint (1) ((1 2))) 0)
(cond
((or
(=
(mod (f2cl-lib:int-add iter (f2cl-lib:int-sub 1))
(f2cl-lib:fref iprint (1) ((1 2))))
0)
finish)
(if
(and
(>
(f2cl-lib:fref iprint-%data% (2) ((1 2)) iprint-%offset%)
1)
(> iter 1))
(f2cl-lib:fformat mp
("~%" " I NFN" "~5@T" "FUNC" "~20@T"
"GNORM" "~19@T" "STEPLENGTH" "~%" "~%")))
(f2cl-lib:fformat mp
(2 (1 (("~4D")) "~1@T") "~3@T" 3
(1 (("~22,15,2,1,'*,,'DE")) "~2@T") "~%")
iter
nfun
f
gnorm
stp))
(t
(go end_label))))
(t
(if
(and
(> (f2cl-lib:fref iprint-%data% (2) ((1 2)) iprint-%offset%)
1)
finish)
(f2cl-lib:fformat mp
("~%" " I NFN" "~5@T" "FUNC" "~20@T"
"GNORM" "~19@T" "STEPLENGTH" "~%" "~%")))
(f2cl-lib:fformat mp
(2 (1 (("~4D")) "~1@T") "~3@T" 3
(1 (("~22,15,2,1,'*,,'DE")) "~2@T") "~%")
iter
nfun
f
gnorm
stp)))
(cond
((or (= (f2cl-lib:fref iprint (2) ((1 2))) 2)
(= (f2cl-lib:fref iprint (2) ((1 2))) 3))
(cond
(finish
(f2cl-lib:fformat mp (" FINAL POINT X= " "~%")))
(t
(f2cl-lib:fformat mp (" VECTOR X= " "~%"))))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE"))) "~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref x-%data%
(i)
((1 n))
x-%offset%)
%ret)))
(cond
((= (f2cl-lib:fref iprint (2) ((1 2))) 3)
(f2cl-lib:fformat mp (" GRADIENT VECTOR G= " "~%"))
(f2cl-lib:fformat mp
(4 ("~2@T" 1 (("~22,15,2,1,'*,,'DE")))
"~%")
(do ((i 1 (f2cl-lib:int-add i 1))
(%ret nil))
((> i n) (nreverse %ret))
(declare (type f2cl-lib:integer4 i))
(push
(f2cl-lib:fref g-%data%
(i)
((1 n))
g-%offset%)
%ret)))))))
(if finish
(f2cl-lib:fformat mp
("~%"
" THE MINIMIZATION TERMINATED WITHOUT DETECTING ERRORS."
"~%" " IFLAG = 0" "~%")))))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil nil nil nil)))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::lb1 fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((array fortran-to-lisp::integer4 (2))
(fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(double-float) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(double-float) (array double-float (*)) (double-float)
fortran-to-lisp::logical)
:return-values '(nil nil nil nil nil nil nil nil nil nil nil)
:calls 'nil)))
|
acd0fbbf5304b9ca5242e780fdb84467ddfc4bcf843d19185650ef37806f1e0b | radian628/lispsmos | main.lisp | (include "../lispsmos-src/binary-decode.lisp")
(importOBJ "../assets/untitled.obj" cube)
(= y (* 2 (^ x 2)))
(= obj (getOBJData cube))
(= halfListLength ( floor ( / ( length l ) 2 ) ) )
;; (fn flatmap1 l
;; (piecewise
( ( > ( length l ) 1 ) ( execIf ( > ( length l ) 1 ) indexer
( join ( flatmap2 ( [ ] l 1 ... halfListLength ) ) ( flatmap2 ( [ ] l ( + halfListLength 1 ) ... ) ) )
;; ))
;; ((list ([] l 1) ([] l 1)))
;; )
;; )
;; (fn flatmap2 l
;; (piecewise
( ( > ( length l ) 1 ) ( execIf ( > ( length l ) 1 )
( join ( flatmap3 ( [ ] l 1 ... halfListLength ) ) ( flatmap3 ( [ ] l ( + halfListLength 1 ) ... ) ) )
;; ))
;; ((list ([] l 1) ([] l 1)))
;; )
;; )
;; (fn flatmap3 l
;; (piecewise
( ( > ( length l ) 1 ) ( execIf ( > ( length l ) 1 )
( join ( [ ] l 1 ... halfListLength ) ( [ ] l ( + halfListLength 1 ) ... ) )
;; ))
;; ((list ([] l 1) ([] l 1)))
;; )
;; )
( flatmap1 ( list 2 7 14 85 ) )
(= q 15)
( + q ( execIf ( > q 10 ) indexer ( sum n 1 400000000 ( + indexer ( * q n ) ) ) ) )
(folder ((title "Linear Algebra"))
(multilayerFn dotNormalized x1 y1 z1 x2 y2 z2
(
(mag1 (sqrt (+ (* x1 x1) (* y1 y1) (* z1 z1))))
(mag2 (sqrt (+ (* x2 x2) (* y2 y2) (* z2 z2))))
(result (+ (* (/ x1 mag1) (/ x2 mag2)) (* (/ y1 mag1) (/ y2 mag2)) (* (/ z1 mag1) (/ z2 mag2))))
)
)
(fn normalizeList L
(/ L (sqrt (+ (* ([] L 1) ([] L 1)) (* ([] L 2) ([] L 2)) (* ([] L 3) ([] L 3)))))
)
(= a 1)
(dotNormalized 2 2 2 -3 -3 -3)
(defineFindAndReplace xStaticCross ax ay az bx by bz
((- (* ay bz) (* az by)))
)
(defineFindAndReplace yStaticCross ax ay az bx by bz
((- (* az bx) (* ax bz)))
)
(defineFindAndReplace zStaticCross ax ay az bx by bz
((- (* ax by) (* ay bx)))
)
(defineFindAndReplace staticDot x1 y1 z1 x2 y2 z2
((+ (* x1 x2) (* y1 y2) (* z1 z2)))
)
(multilayerFn mullerTrumbore
xRay yRay zRay
xDir yDir zDir
xTri1 yTri1 zTri1
xTri2 yTri2 zTri2
xTri3 yTri3 zTri3
(
(xE1 (- xTri2 xTri1))
(yE1 (- yTri2 yTri1))
(zE1 (- zTri2 zTri1))
(xE2 (- xTri3 xTri1))
(yE2 (- yTri3 yTri1))
(zE2 (- zTri3 zTri1))
(xN (xStaticCross xE1 yE1 zE1 xE2 yE2 zE2))
(yN (yStaticCross xE1 yE1 zE1 xE2 yE2 zE2))
(zN (zStaticCross xE1 yE1 zE1 xE2 yE2 zE2))
(det (* -1 (staticDot xDir yDir zDir xN yN zN)))
(invdet (/ 1 det))
(xAO (- xRay xTri1))
(yAO (- yRay yTri1))
(zAO (- zRay zTri1))
(xDAO (xStaticCross xAO yAO zAO xDir yDir zDir))
(yDAO (yStaticCross xAO yAO zAO xDir yDir zDir))
(zDAO (zStaticCross xAO yAO zAO xDir yDir zDir))
(u (* (staticDot xE2 yE2 zE2 xDAO yDAO zDAO) invdet))
(v (* -1 (staticDot xE1 yE1 zE1 xDAO yDAO zDAO) invdet))
(t (* (staticDot xAO yAO zAO xN yN zN) invdet))
(return (piecewise
((< det 0.00001) -1)
((< t 0) -1)
((< u 0) -1)
((< v 0) -1)
((> (+ u v) 1) -1)
(t)
))
( return )
)
)
) | null | https://raw.githubusercontent.com/radian628/lispsmos/8e0531d2f0aacc15a523e9d0780b4c70e10c5ca4/lispsmos-experiments/ptgi/lispsmos-src/main.lisp | lisp | (fn flatmap1 l
(piecewise
))
((list ([] l 1) ([] l 1)))
)
)
(fn flatmap2 l
(piecewise
))
((list ([] l 1) ([] l 1)))
)
)
(fn flatmap3 l
(piecewise
))
((list ([] l 1) ([] l 1)))
)
) | (include "../lispsmos-src/binary-decode.lisp")
(importOBJ "../assets/untitled.obj" cube)
(= y (* 2 (^ x 2)))
(= obj (getOBJData cube))
(= halfListLength ( floor ( / ( length l ) 2 ) ) )
( ( > ( length l ) 1 ) ( execIf ( > ( length l ) 1 ) indexer
( join ( flatmap2 ( [ ] l 1 ... halfListLength ) ) ( flatmap2 ( [ ] l ( + halfListLength 1 ) ... ) ) )
( ( > ( length l ) 1 ) ( execIf ( > ( length l ) 1 )
( join ( flatmap3 ( [ ] l 1 ... halfListLength ) ) ( flatmap3 ( [ ] l ( + halfListLength 1 ) ... ) ) )
( ( > ( length l ) 1 ) ( execIf ( > ( length l ) 1 )
( join ( [ ] l 1 ... halfListLength ) ( [ ] l ( + halfListLength 1 ) ... ) )
( flatmap1 ( list 2 7 14 85 ) )
(= q 15)
( + q ( execIf ( > q 10 ) indexer ( sum n 1 400000000 ( + indexer ( * q n ) ) ) ) )
(folder ((title "Linear Algebra"))
(multilayerFn dotNormalized x1 y1 z1 x2 y2 z2
(
(mag1 (sqrt (+ (* x1 x1) (* y1 y1) (* z1 z1))))
(mag2 (sqrt (+ (* x2 x2) (* y2 y2) (* z2 z2))))
(result (+ (* (/ x1 mag1) (/ x2 mag2)) (* (/ y1 mag1) (/ y2 mag2)) (* (/ z1 mag1) (/ z2 mag2))))
)
)
(fn normalizeList L
(/ L (sqrt (+ (* ([] L 1) ([] L 1)) (* ([] L 2) ([] L 2)) (* ([] L 3) ([] L 3)))))
)
(= a 1)
(dotNormalized 2 2 2 -3 -3 -3)
(defineFindAndReplace xStaticCross ax ay az bx by bz
((- (* ay bz) (* az by)))
)
(defineFindAndReplace yStaticCross ax ay az bx by bz
((- (* az bx) (* ax bz)))
)
(defineFindAndReplace zStaticCross ax ay az bx by bz
((- (* ax by) (* ay bx)))
)
(defineFindAndReplace staticDot x1 y1 z1 x2 y2 z2
((+ (* x1 x2) (* y1 y2) (* z1 z2)))
)
(multilayerFn mullerTrumbore
xRay yRay zRay
xDir yDir zDir
xTri1 yTri1 zTri1
xTri2 yTri2 zTri2
xTri3 yTri3 zTri3
(
(xE1 (- xTri2 xTri1))
(yE1 (- yTri2 yTri1))
(zE1 (- zTri2 zTri1))
(xE2 (- xTri3 xTri1))
(yE2 (- yTri3 yTri1))
(zE2 (- zTri3 zTri1))
(xN (xStaticCross xE1 yE1 zE1 xE2 yE2 zE2))
(yN (yStaticCross xE1 yE1 zE1 xE2 yE2 zE2))
(zN (zStaticCross xE1 yE1 zE1 xE2 yE2 zE2))
(det (* -1 (staticDot xDir yDir zDir xN yN zN)))
(invdet (/ 1 det))
(xAO (- xRay xTri1))
(yAO (- yRay yTri1))
(zAO (- zRay zTri1))
(xDAO (xStaticCross xAO yAO zAO xDir yDir zDir))
(yDAO (yStaticCross xAO yAO zAO xDir yDir zDir))
(zDAO (zStaticCross xAO yAO zAO xDir yDir zDir))
(u (* (staticDot xE2 yE2 zE2 xDAO yDAO zDAO) invdet))
(v (* -1 (staticDot xE1 yE1 zE1 xDAO yDAO zDAO) invdet))
(t (* (staticDot xAO yAO zAO xN yN zN) invdet))
(return (piecewise
((< det 0.00001) -1)
((< t 0) -1)
((< u 0) -1)
((< v 0) -1)
((> (+ u v) 1) -1)
(t)
))
( return )
)
)
) |
c037d81d355db6775a804bb61a94d94bac132c4b3a3e55ed841ec8d2169c7618 | racket/eopl | store.rkt | #lang eopl
(provide initialize-store! reference? newref deref setref!
instrument-newref get-store-as-list)
(define instrument-newref (make-parameter #f))
;;;;;;;;;;;;;;;; references and the store ;;;;;;;;;;;;;;;;
;;; world's dumbest model of the store: the store is a list and a
;;; reference is number which denotes a position in the list.
;; the-store: a Scheme variable containing the current state of the
;; store. Initially set to a dummy variable.
(define the-store 'uninitialized)
;; empty-store : () -> Sto
Page : 111
(define empty-store
(lambda () '()))
;; initialize-store! : () -> Sto
;; usage: (initialize-store!) sets the-store to the empty-store
Page 111
(define initialize-store!
(lambda ()
(set! the-store (empty-store))))
;; get-store : () -> Sto
Page : 111
;; This is obsolete. Replaced by get-store-as-list below
(define get-store
(lambda () the-store))
;; reference? : SchemeVal -> Bool
Page : 111
(define reference?
(lambda (v)
(integer? v)))
;; newref : ExpVal -> Ref
Page : 111
(define newref
(lambda (val)
(let ((next-ref (length the-store)))
(set! the-store
(append the-store (list val)))
(when (instrument-newref)
(eopl:printf
"newref: allocating location ~s with initial contents ~s~%"
next-ref val))
next-ref)))
deref : Ref - > ExpVal
Page 111
(define deref
(lambda (ref)
(list-ref the-store ref)))
;; setref! : Ref * ExpVal -> Unspecified
Page : 112
(define setref!
(lambda (ref val)
(set! the-store
(letrec
((setref-inner
returns a list like store1 , except that position ref1
;; contains val.
(lambda (store1 ref1)
(cond
((null? store1)
(report-invalid-reference ref the-store))
((zero? ref1)
(cons val (cdr store1)))
(else
(cons
(car store1)
(setref-inner
(cdr store1) (- ref1 1))))))))
(setref-inner the-store ref)))))
(define report-invalid-reference
(lambda (ref the-store)
(eopl:error 'setref
"illegal reference ~s in store ~s"
ref the-store)))
get - store - as - list : ( ) - > , ) )
;; Exports the current state of the store as a scheme list.
( get - store - as - list ' ( foo bar baz ) ) = ( ( 0 foo)(1 bar ) ( 2 baz ) )
;; where foo, bar, and baz are expvals.
;; If the store were represented in a different way, this would be
;; replaced by something cleverer.
Replaces get - store ( p. 111 )
(define get-store-as-list
(lambda ()
(letrec
((inner-loop
;; convert sto to list as if its car was location n
(lambda (sto n)
(if (null? sto)
'()
(cons
(list n (car sto))
(inner-loop (cdr sto) (+ n 1)))))))
(inner-loop the-store 0))))
| null | https://raw.githubusercontent.com/racket/eopl/43575d6e95dc34ca6e49b305180f696565e16e0f/tests/chapter5/thread-lang/store.rkt | racket | references and the store ;;;;;;;;;;;;;;;;
world's dumbest model of the store: the store is a list and a
reference is number which denotes a position in the list.
the-store: a Scheme variable containing the current state of the
store. Initially set to a dummy variable.
empty-store : () -> Sto
initialize-store! : () -> Sto
usage: (initialize-store!) sets the-store to the empty-store
get-store : () -> Sto
This is obsolete. Replaced by get-store-as-list below
reference? : SchemeVal -> Bool
newref : ExpVal -> Ref
setref! : Ref * ExpVal -> Unspecified
contains val.
Exports the current state of the store as a scheme list.
where foo, bar, and baz are expvals.
If the store were represented in a different way, this would be
replaced by something cleverer.
convert sto to list as if its car was location n | #lang eopl
(provide initialize-store! reference? newref deref setref!
instrument-newref get-store-as-list)
(define instrument-newref (make-parameter #f))
(define the-store 'uninitialized)
Page : 111
(define empty-store
(lambda () '()))
Page 111
(define initialize-store!
(lambda ()
(set! the-store (empty-store))))
Page : 111
(define get-store
(lambda () the-store))
Page : 111
(define reference?
(lambda (v)
(integer? v)))
Page : 111
(define newref
(lambda (val)
(let ((next-ref (length the-store)))
(set! the-store
(append the-store (list val)))
(when (instrument-newref)
(eopl:printf
"newref: allocating location ~s with initial contents ~s~%"
next-ref val))
next-ref)))
deref : Ref - > ExpVal
Page 111
(define deref
(lambda (ref)
(list-ref the-store ref)))
Page : 112
(define setref!
(lambda (ref val)
(set! the-store
(letrec
((setref-inner
returns a list like store1 , except that position ref1
(lambda (store1 ref1)
(cond
((null? store1)
(report-invalid-reference ref the-store))
((zero? ref1)
(cons val (cdr store1)))
(else
(cons
(car store1)
(setref-inner
(cdr store1) (- ref1 1))))))))
(setref-inner the-store ref)))))
(define report-invalid-reference
(lambda (ref the-store)
(eopl:error 'setref
"illegal reference ~s in store ~s"
ref the-store)))
get - store - as - list : ( ) - > , ) )
( get - store - as - list ' ( foo bar baz ) ) = ( ( 0 foo)(1 bar ) ( 2 baz ) )
Replaces get - store ( p. 111 )
(define get-store-as-list
(lambda ()
(letrec
((inner-loop
(lambda (sto n)
(if (null? sto)
'()
(cons
(list n (car sto))
(inner-loop (cdr sto) (+ n 1)))))))
(inner-loop the-store 0))))
|
218070d3f172bf3787a9aa8b599f8b6a6a3eb532bba1270ba72ff0fe181ccacd | gedge-platform/gedge-platform | rabbit_mgmt_wm_health_check_node_is_mirror_sync_critical.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 .
%%
%% An HTTP API counterpart of 'rabbitmq-diagnostics check_if_node_is_quorum_critical'
-module(rabbit_mgmt_wm_health_check_node_is_mirror_sync_critical).
-export([init/2, to_json/2, content_types_provided/2, is_authorized/2]).
-export([resource_exists/2]).
-export([variances/2]).
-include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl").
%%--------------------------------------------------------------------
init(Req, _State) ->
{cowboy_rest, rabbit_mgmt_headers:set_common_permission_headers(Req, ?MODULE), #context{}}.
variances(Req, Context) ->
{[<<"accept-encoding">>, <<"origin">>], Req, Context}.
content_types_provided(ReqData, Context) ->
{rabbit_mgmt_util:responder_map(to_json), ReqData, Context}.
resource_exists(ReqData, Context) ->
{true, ReqData, Context}.
to_json(ReqData, Context) ->
case rabbit_nodes:is_single_node_cluster() of
true ->
rabbit_mgmt_util:reply([{status, ok},
{reason, <<"single node cluster">>}], ReqData, Context);
false ->
case rabbit_amqqueue:list_local_mirrored_classic_without_synchronised_mirrors_for_cli() of
[] ->
rabbit_mgmt_util:reply([{status, ok}], ReqData, Context);
Qs when length(Qs) > 0 ->
Msg = <<"There are classic mirrored queues without online synchronised mirrors">>,
failure(Msg, Qs, ReqData, Context)
end
end.
failure(Message, Qs, ReqData, Context) ->
{Response, ReqData1, Context1} = rabbit_mgmt_util:reply([{status, failed},
{reason, Message},
{queues, Qs}],
ReqData, Context),
{stop, cowboy_req:reply(503, #{}, Response, ReqData1), Context1}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized(ReqData, Context).
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_management/src/rabbit_mgmt_wm_health_check_node_is_mirror_sync_critical.erl | erlang |
An HTTP API counterpart of 'rabbitmq-diagnostics check_if_node_is_quorum_critical'
-------------------------------------------------------------------- | 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_mgmt_wm_health_check_node_is_mirror_sync_critical).
-export([init/2, to_json/2, content_types_provided/2, is_authorized/2]).
-export([resource_exists/2]).
-export([variances/2]).
-include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl").
init(Req, _State) ->
{cowboy_rest, rabbit_mgmt_headers:set_common_permission_headers(Req, ?MODULE), #context{}}.
variances(Req, Context) ->
{[<<"accept-encoding">>, <<"origin">>], Req, Context}.
content_types_provided(ReqData, Context) ->
{rabbit_mgmt_util:responder_map(to_json), ReqData, Context}.
resource_exists(ReqData, Context) ->
{true, ReqData, Context}.
to_json(ReqData, Context) ->
case rabbit_nodes:is_single_node_cluster() of
true ->
rabbit_mgmt_util:reply([{status, ok},
{reason, <<"single node cluster">>}], ReqData, Context);
false ->
case rabbit_amqqueue:list_local_mirrored_classic_without_synchronised_mirrors_for_cli() of
[] ->
rabbit_mgmt_util:reply([{status, ok}], ReqData, Context);
Qs when length(Qs) > 0 ->
Msg = <<"There are classic mirrored queues without online synchronised mirrors">>,
failure(Msg, Qs, ReqData, Context)
end
end.
failure(Message, Qs, ReqData, Context) ->
{Response, ReqData1, Context1} = rabbit_mgmt_util:reply([{status, failed},
{reason, Message},
{queues, Qs}],
ReqData, Context),
{stop, cowboy_req:reply(503, #{}, Response, ReqData1), Context1}.
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized(ReqData, Context).
|
5d3101afc6b72d20dd54e819dae128769a38ca357a65498b845066dd4d60a6bb | master/ejabberd | mod_proxy65_stream.erl | %%%----------------------------------------------------------------------
File : mod_proxy65_stream.erl
Author : < >
%%% Purpose : Bytestream process.
Created : 12 Oct 2006 by < >
%%%
ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
-module(mod_proxy65_stream).
-author('').
-behaviour(gen_fsm).
%% gen_fsm callbacks.
-export([
init/1,
handle_event/3,
handle_sync_event/4,
code_change/4,
handle_info/3,
terminate/3
]).
%% gen_fsm states.
-export([
wait_for_init/2,
wait_for_auth/2,
wait_for_request/2,
wait_for_activation/2,
stream_established/2
]).
%% API.
-export([
start/2,
stop/1,
start_link/3,
activate/2,
relay/3,
socket_type/0
]).
-include("mod_proxy65.hrl").
-include("ejabberd.hrl").
1 minute ( is it enough ? )
-record(state, {
socket, %% TCP socket
timer, %% timer reference
sha1, %% SHA1 key
host, %% virtual host
auth_type, %% authentication type: anonymous or plain
shaper %% Shaper name
}).
%% Unused callbacks
handle_event(_Event, StateName, StateData) ->
{next_state, StateName, StateData}.
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
%%-------------------------------
start({gen_tcp, Socket}, Opts1) ->
{[Host], Opts} = lists:partition(fun(O) -> is_list(O) end, Opts1),
Supervisor = gen_mod:get_module_proc(Host, ejabberd_mod_proxy65_sup),
supervisor:start_child(Supervisor, [Socket, Host, Opts]).
start_link(Socket, Host, Opts) ->
gen_fsm:start_link(?MODULE, [Socket, Host, Opts], []).
init([Socket, Host, Opts]) ->
process_flag(trap_exit, true),
AuthType = gen_mod:get_opt(auth_type, Opts, anonymous),
Shaper = gen_mod:get_opt(shaper, Opts, none),
RecvBuf = gen_mod:get_opt(recbuf, Opts, 8192),
SendBuf = gen_mod:get_opt(sndbuf, Opts, 8192),
TRef = erlang:send_after(?WAIT_TIMEOUT, self(), stop),
inet:setopts(Socket, [{active, true}, {recbuf, RecvBuf}, {sndbuf, SendBuf}]),
{ok, wait_for_init, #state{host = Host,
auth_type = AuthType,
socket = Socket,
shaper = Shaper,
timer = TRef}}.
terminate(_Reason, StateName, #state{sha1=SHA1}) ->
catch mod_proxy65_sm:unregister_stream(SHA1),
if StateName == stream_established ->
?INFO_MSG("Bytestream terminated", []);
true ->
ok
end.
%%%------------------------------
%%% API.
%%%------------------------------
socket_type() ->
raw.
stop(StreamPid) ->
StreamPid ! stop.
activate({P1, J1}, {P2, J2}) ->
case catch {gen_fsm:sync_send_all_state_event(P1, get_socket),
gen_fsm:sync_send_all_state_event(P2, get_socket)} of
{S1, S2} when is_port(S1), is_port(S2) ->
P1 ! {activate, P2, S2, J1, J2},
P2 ! {activate, P1, S1, J1, J2},
JID1 = jlib:jid_to_string(J1),
JID2 = jlib:jid_to_string(J2),
?INFO_MSG("(~w:~w) Activated bytestream for ~s -> ~s", [P1, P2, JID1, JID2]),
ok;
_ ->
error
end.
%%%-----------------------
States
%%%-----------------------
wait_for_init(Packet, #state{socket=Socket, auth_type=AuthType} = StateData) ->
case mod_proxy65_lib:unpack_init_message(Packet) of
{ok, AuthMethods} ->
Method = select_auth_method(AuthType, AuthMethods),
gen_tcp:send(Socket, mod_proxy65_lib:make_init_reply(Method)),
case Method of
?AUTH_ANONYMOUS ->
{next_state, wait_for_request, StateData};
?AUTH_PLAIN ->
{next_state, wait_for_auth, StateData};
?AUTH_NO_METHODS ->
{stop, normal, StateData}
end;
error ->
{stop, normal, StateData}
end.
wait_for_auth(Packet, #state{socket=Socket, host=Host} = StateData) ->
case mod_proxy65_lib:unpack_auth_request(Packet) of
{User, Pass} ->
Result = ejabberd_auth:check_password(User, Host, Pass),
gen_tcp:send(Socket, mod_proxy65_lib:make_auth_reply(Result)),
case Result of
true ->
{next_state, wait_for_request, StateData};
false ->
{stop, normal, StateData}
end;
_ ->
{stop, normal, StateData}
end.
wait_for_request(Packet, #state{socket=Socket} = StateData) ->
Request = mod_proxy65_lib:unpack_request(Packet),
case Request of
#s5_request{sha1=SHA1, cmd=connect} ->
case catch mod_proxy65_sm:register_stream(SHA1) of
{atomic, ok} ->
inet:setopts(Socket, [{active, false}]),
gen_tcp:send(Socket, mod_proxy65_lib:make_reply(Request)),
{next_state, wait_for_activation, StateData#state{sha1=SHA1}};
_ ->
Err = mod_proxy65_lib:make_error_reply(Request),
gen_tcp:send(Socket, Err),
{stop, normal, StateData}
end;
#s5_request{cmd=udp} ->
Err = mod_proxy65_lib:make_error_reply(Request, ?ERR_COMMAND_NOT_SUPPORTED),
gen_tcp:send(Socket, Err),
{stop, normal, StateData};
_ ->
{stop, normal, StateData}
end.
wait_for_activation(_Data, StateData) ->
{next_state, wait_for_activation, StateData}.
stream_established(_Data, StateData) ->
{next_state, stream_established, StateData}.
%%%-----------------------
%%% Callbacks processing
%%%-----------------------
SOCKS5 packets .
handle_info({tcp, _S, Data}, StateName, StateData)
when StateName /= wait_for_activation ->
erlang:cancel_timer(StateData#state.timer),
TRef = erlang:send_after(?WAIT_TIMEOUT, self(), stop),
gen_fsm:send_event(self(), Data),
{next_state, StateName, StateData#state{timer=TRef}};
%% Activation message.
handle_info({activate, PeerPid, PeerSocket, IJid, TJid},
wait_for_activation, StateData) ->
erlang:monitor(process, PeerPid),
erlang:cancel_timer(StateData#state.timer),
MySocket = StateData#state.socket,
Shaper = StateData#state.shaper,
Host = StateData#state.host,
MaxRate = find_maxrate(Shaper, IJid, TJid, Host),
spawn_link(?MODULE, relay, [MySocket, PeerSocket, MaxRate]),
{next_state, stream_established, StateData};
%% Socket closed
handle_info({tcp_closed, _Socket}, _StateName, StateData) ->
{stop, normal, StateData};
handle_info({tcp_error, _Socket, _Reason}, _StateName, StateData) ->
{stop, normal, StateData};
%% Got stop message.
handle_info(stop, _StateName, StateData) ->
{stop, normal, StateData};
%% Either linked process or peer process died.
handle_info({'EXIT',_,_}, _StateName, StateData) ->
{stop, normal, StateData};
handle_info({'DOWN',_,_,_,_}, _StateName, StateData) ->
{stop, normal, StateData};
%% Packets of no interest
handle_info(_Info, StateName, StateData) ->
{next_state, StateName, StateData}.
%% Socket request.
handle_sync_event(get_socket, _From, wait_for_activation, StateData) ->
Socket = StateData#state.socket,
{reply, Socket, wait_for_activation, StateData};
handle_sync_event(_Event, _From, StateName, StateData) ->
{reply, error, StateName, StateData}.
%%%-------------------------------------------------
Relay Process .
%%%-------------------------------------------------
relay(MySocket, PeerSocket, Shaper) ->
case gen_tcp:recv(MySocket, 0) of
{ok, Data} ->
gen_tcp:send(PeerSocket, Data),
{NewShaper, Pause} = shaper:update(Shaper, size(Data)),
if
Pause > 0 -> timer:sleep(Pause);
true -> pass
end,
relay(MySocket, PeerSocket, NewShaper);
_ ->
stopped
end.
%%%------------------------
%%% Auxiliary functions
%%%------------------------
select_auth_method(plain, AuthMethods) ->
case lists:member(?AUTH_PLAIN, AuthMethods) of
true -> ?AUTH_PLAIN;
false -> ?AUTH_NO_METHODS
end;
select_auth_method(anonymous, AuthMethods) ->
case lists:member(?AUTH_ANONYMOUS, AuthMethods) of
true -> ?AUTH_ANONYMOUS;
false -> ?AUTH_NO_METHODS
end.
%% Obviously, we must use shaper with maximum rate.
find_maxrate(Shaper, JID1, JID2, Host) ->
MaxRate1 = shaper:new(acl:match_rule(Host, Shaper, JID1)),
MaxRate2 = shaper:new(acl:match_rule(Host, Shaper, JID2)),
if
MaxRate1 == none; MaxRate2 == none ->
none;
true ->
lists:max([MaxRate1, MaxRate2])
end.
| null | https://raw.githubusercontent.com/master/ejabberd/9c31874d5a9d1852ece1b8ae70dd4b7e5eef7cf7/src/mod_proxy65/mod_proxy65_stream.erl | erlang | ----------------------------------------------------------------------
Purpose : Bytestream process.
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
gen_fsm callbacks.
gen_fsm states.
API.
TCP socket
timer reference
SHA1 key
virtual host
authentication type: anonymous or plain
Shaper name
Unused callbacks
-------------------------------
------------------------------
API.
------------------------------
-----------------------
-----------------------
-----------------------
Callbacks processing
-----------------------
Activation message.
Socket closed
Got stop message.
Either linked process or peer process died.
Packets of no interest
Socket request.
-------------------------------------------------
-------------------------------------------------
------------------------
Auxiliary functions
------------------------
Obviously, we must use shaper with maximum rate. | File : mod_proxy65_stream.erl
Author : < >
Created : 12 Oct 2006 by < >
ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(mod_proxy65_stream).
-author('').
-behaviour(gen_fsm).
-export([
init/1,
handle_event/3,
handle_sync_event/4,
code_change/4,
handle_info/3,
terminate/3
]).
-export([
wait_for_init/2,
wait_for_auth/2,
wait_for_request/2,
wait_for_activation/2,
stream_established/2
]).
-export([
start/2,
stop/1,
start_link/3,
activate/2,
relay/3,
socket_type/0
]).
-include("mod_proxy65.hrl").
-include("ejabberd.hrl").
1 minute ( is it enough ? )
-record(state, {
}).
handle_event(_Event, StateName, StateData) ->
{next_state, StateName, StateData}.
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
start({gen_tcp, Socket}, Opts1) ->
{[Host], Opts} = lists:partition(fun(O) -> is_list(O) end, Opts1),
Supervisor = gen_mod:get_module_proc(Host, ejabberd_mod_proxy65_sup),
supervisor:start_child(Supervisor, [Socket, Host, Opts]).
start_link(Socket, Host, Opts) ->
gen_fsm:start_link(?MODULE, [Socket, Host, Opts], []).
init([Socket, Host, Opts]) ->
process_flag(trap_exit, true),
AuthType = gen_mod:get_opt(auth_type, Opts, anonymous),
Shaper = gen_mod:get_opt(shaper, Opts, none),
RecvBuf = gen_mod:get_opt(recbuf, Opts, 8192),
SendBuf = gen_mod:get_opt(sndbuf, Opts, 8192),
TRef = erlang:send_after(?WAIT_TIMEOUT, self(), stop),
inet:setopts(Socket, [{active, true}, {recbuf, RecvBuf}, {sndbuf, SendBuf}]),
{ok, wait_for_init, #state{host = Host,
auth_type = AuthType,
socket = Socket,
shaper = Shaper,
timer = TRef}}.
terminate(_Reason, StateName, #state{sha1=SHA1}) ->
catch mod_proxy65_sm:unregister_stream(SHA1),
if StateName == stream_established ->
?INFO_MSG("Bytestream terminated", []);
true ->
ok
end.
socket_type() ->
raw.
stop(StreamPid) ->
StreamPid ! stop.
activate({P1, J1}, {P2, J2}) ->
case catch {gen_fsm:sync_send_all_state_event(P1, get_socket),
gen_fsm:sync_send_all_state_event(P2, get_socket)} of
{S1, S2} when is_port(S1), is_port(S2) ->
P1 ! {activate, P2, S2, J1, J2},
P2 ! {activate, P1, S1, J1, J2},
JID1 = jlib:jid_to_string(J1),
JID2 = jlib:jid_to_string(J2),
?INFO_MSG("(~w:~w) Activated bytestream for ~s -> ~s", [P1, P2, JID1, JID2]),
ok;
_ ->
error
end.
States
wait_for_init(Packet, #state{socket=Socket, auth_type=AuthType} = StateData) ->
case mod_proxy65_lib:unpack_init_message(Packet) of
{ok, AuthMethods} ->
Method = select_auth_method(AuthType, AuthMethods),
gen_tcp:send(Socket, mod_proxy65_lib:make_init_reply(Method)),
case Method of
?AUTH_ANONYMOUS ->
{next_state, wait_for_request, StateData};
?AUTH_PLAIN ->
{next_state, wait_for_auth, StateData};
?AUTH_NO_METHODS ->
{stop, normal, StateData}
end;
error ->
{stop, normal, StateData}
end.
wait_for_auth(Packet, #state{socket=Socket, host=Host} = StateData) ->
case mod_proxy65_lib:unpack_auth_request(Packet) of
{User, Pass} ->
Result = ejabberd_auth:check_password(User, Host, Pass),
gen_tcp:send(Socket, mod_proxy65_lib:make_auth_reply(Result)),
case Result of
true ->
{next_state, wait_for_request, StateData};
false ->
{stop, normal, StateData}
end;
_ ->
{stop, normal, StateData}
end.
wait_for_request(Packet, #state{socket=Socket} = StateData) ->
Request = mod_proxy65_lib:unpack_request(Packet),
case Request of
#s5_request{sha1=SHA1, cmd=connect} ->
case catch mod_proxy65_sm:register_stream(SHA1) of
{atomic, ok} ->
inet:setopts(Socket, [{active, false}]),
gen_tcp:send(Socket, mod_proxy65_lib:make_reply(Request)),
{next_state, wait_for_activation, StateData#state{sha1=SHA1}};
_ ->
Err = mod_proxy65_lib:make_error_reply(Request),
gen_tcp:send(Socket, Err),
{stop, normal, StateData}
end;
#s5_request{cmd=udp} ->
Err = mod_proxy65_lib:make_error_reply(Request, ?ERR_COMMAND_NOT_SUPPORTED),
gen_tcp:send(Socket, Err),
{stop, normal, StateData};
_ ->
{stop, normal, StateData}
end.
wait_for_activation(_Data, StateData) ->
{next_state, wait_for_activation, StateData}.
stream_established(_Data, StateData) ->
{next_state, stream_established, StateData}.
SOCKS5 packets .
handle_info({tcp, _S, Data}, StateName, StateData)
when StateName /= wait_for_activation ->
erlang:cancel_timer(StateData#state.timer),
TRef = erlang:send_after(?WAIT_TIMEOUT, self(), stop),
gen_fsm:send_event(self(), Data),
{next_state, StateName, StateData#state{timer=TRef}};
handle_info({activate, PeerPid, PeerSocket, IJid, TJid},
wait_for_activation, StateData) ->
erlang:monitor(process, PeerPid),
erlang:cancel_timer(StateData#state.timer),
MySocket = StateData#state.socket,
Shaper = StateData#state.shaper,
Host = StateData#state.host,
MaxRate = find_maxrate(Shaper, IJid, TJid, Host),
spawn_link(?MODULE, relay, [MySocket, PeerSocket, MaxRate]),
{next_state, stream_established, StateData};
handle_info({tcp_closed, _Socket}, _StateName, StateData) ->
{stop, normal, StateData};
handle_info({tcp_error, _Socket, _Reason}, _StateName, StateData) ->
{stop, normal, StateData};
handle_info(stop, _StateName, StateData) ->
{stop, normal, StateData};
handle_info({'EXIT',_,_}, _StateName, StateData) ->
{stop, normal, StateData};
handle_info({'DOWN',_,_,_,_}, _StateName, StateData) ->
{stop, normal, StateData};
handle_info(_Info, StateName, StateData) ->
{next_state, StateName, StateData}.
handle_sync_event(get_socket, _From, wait_for_activation, StateData) ->
Socket = StateData#state.socket,
{reply, Socket, wait_for_activation, StateData};
handle_sync_event(_Event, _From, StateName, StateData) ->
{reply, error, StateName, StateData}.
Relay Process .
relay(MySocket, PeerSocket, Shaper) ->
case gen_tcp:recv(MySocket, 0) of
{ok, Data} ->
gen_tcp:send(PeerSocket, Data),
{NewShaper, Pause} = shaper:update(Shaper, size(Data)),
if
Pause > 0 -> timer:sleep(Pause);
true -> pass
end,
relay(MySocket, PeerSocket, NewShaper);
_ ->
stopped
end.
select_auth_method(plain, AuthMethods) ->
case lists:member(?AUTH_PLAIN, AuthMethods) of
true -> ?AUTH_PLAIN;
false -> ?AUTH_NO_METHODS
end;
select_auth_method(anonymous, AuthMethods) ->
case lists:member(?AUTH_ANONYMOUS, AuthMethods) of
true -> ?AUTH_ANONYMOUS;
false -> ?AUTH_NO_METHODS
end.
find_maxrate(Shaper, JID1, JID2, Host) ->
MaxRate1 = shaper:new(acl:match_rule(Host, Shaper, JID1)),
MaxRate2 = shaper:new(acl:match_rule(Host, Shaper, JID2)),
if
MaxRate1 == none; MaxRate2 == none ->
none;
true ->
lists:max([MaxRate1, MaxRate2])
end.
|
7acbca2613e5e22528c4bce568e701f790bb43de52d25560b558983627926952 | active-group/sqlosure | sql_put_test.clj | (ns sqlosure.sql-put-test
(:require [active.clojure.lens :as lens]
[active.clojure.monad :as monad]
[clojure.test :as t :refer [deftest is testing]]
[clojure.string :as string]
[sqlosure.core :as c]
[sqlosure.optimization :as o]
[sqlosure.query-comprehension :as qc]
[sqlosure.relational-algebra-sql :as rel-alg-sql]
[sqlosure.relational-algebra :as rel]
[sqlosure.sql :as sql]
[sqlosure.sql-put :as put]
[sqlosure.type :as sql-t :refer [string% integer% double% boolean%]]))
(def tbl1 (sql/base-relation "tbl1"
[["one" string%]
["two" double%]]
:universe sql/sql-universe
:handle "tbl1"))
(def test-put-parameterization
(put/make-sql-put-parameterization
(fn [alias]
(if alias
(put/write! "TESTAS" alias)
(active.clojure.monad/return nil)))
put/default-put-combine))
(def test-run (partial put/run test-put-parameterization))
(deftest put-padding-if-non-null-test
(is (= ["" []] (test-run (put/put-padding-if-non-null nil put/write!))))
(is (= ["foo bar baz" []]
(test-run (put/put-padding-if-non-null ["foo" "bar" "baz"]
#(put/write! (string/join " " %)))))))
(deftest put-alias-test
(is (= ["TESTAS foo" []] (test-run (put/put-alias "foo"))))
(is (= ["" []] (test-run (put/put-alias nil)))))
(deftest put-literal-test
(is (= ["?" [[integer% 42]]] (test-run (put/put-literal integer% 42))))
(is (= ["?" [[string% "foobar"]]] (test-run (put/put-literal string% "foobar"))))
(is (= ["?" [[string% nil]]] (test-run (put/put-literal string% nil))))
(is (= ["?" [[boolean% true]]] (test-run (put/put-literal boolean% true))))
(is (= ["?" [[boolean% false]]] (test-run (put/put-literal boolean% false)))))
(deftest put-sql-select-test
(is (= ["" []] (test-run (put/put-sql-select (sql/new-sql-select)))))
(is (= ["SELECT * FROM CUSTOMERS" []]
(test-run (put/put-sql-select (sql/make-sql-select-table nil "CUSTOMERS")))))
(t/testing "table-spaces are printed correctly"
(t/is (= ["SELECT * FROM prefix.table" []]
(-> (sql/base-relation "table" [])
(rel/base-relation-table-space "prefix")
rel-alg-sql/query->sql
put/put-sql-select
test-run))))
(let [o (rel/make-order
{(rel/make-attribute-ref "one") :ascending}
tbl1)
q (rel-alg-sql/query->sql o)]
(is (= ["SELECT * FROM tbl1 ORDER BY one ASC" []]
(test-run (put/put-sql-select q)))))
(let [q1 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-tables
[["S" (sql/make-sql-select-table nil "SUPPLIERS")]
[nil (sql/make-sql-select-table nil "CUSTOMERS")]])
(lens/shove sql/sql-select-attributes
{"UID" (sql/make-sql-expr-column "UID")})
(lens/shove sql/sql-select-order-by
[[(sql/make-sql-expr-column "uid") :ascending]])
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "foo")
(sql/make-sql-expr-const integer% 10))
(sql/make-sql-expr-app sql/op-=
(sql/make-sql-expr-column "uid")
(sql/make-sql-expr-const integer% 5))]))
q2 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-attributes
{"cost" (sql/make-sql-expr-column "cost")})
(rel-alg-sql/add-table (sql/make-sql-select-table nil "PARTS"))
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "cost")
(sql/make-sql-expr-const integer% 100))]))]
(is (= ["SELECT UID FROM SUPPLIERS TESTAS S , CUSTOMERS WHERE ( foo < ? ) AND ( uid = ? ) ORDER BY uid ASC"
[[integer% 10] [integer% 5]]]
(test-run (put/put-sql-select q1))))
(is (= [(str "( SELECT UID "
"FROM SUPPLIERS TESTAS S , CUSTOMERS "
"WHERE ( foo < ? ) AND ( uid = ? ) "
"ORDER BY uid ASC ) "
"UNION "
"( SELECT cost "
"FROM PARTS "
"WHERE ( cost < ? ) )")
[[integer% 10] [integer% 5] [integer% 100]]]
(test-run (put/put-sql-select
(sql/make-sql-select-combine :union q1 q2)))))))
(deftest put-sql-outer-join-test
(testing "simple case"
(let [t1 (sql/base-relation "t1"
(rel/alist->rel-scheme [["C" string%]]))
t2 (sql/base-relation "t2"
(rel/alist->rel-scheme [["D" integer%]]))
r (rel/make-restrict-outer (sql/=$ (rel/make-attribute-ref "C")
(rel/make-attribute-ref "D"))
(rel/make-left-outer-product t1 t2))
sql (rel-alg-sql/query->sql r)]
(is (= ["SELECT * FROM t1 LEFT JOIN t2 ON ( C = D )" []]
(test-run (put/put-sql-select sql))))))
(testing "multiple tables on the left"
(let [t1 (sql/base-relation "t1"
(rel/alist->rel-scheme [["C" string%]]))
t2 (sql/base-relation "t2"
(rel/alist->rel-scheme [["D" integer%]]))
t3 (sql/base-relation "t3"
(rel/alist->rel-scheme [["E" integer%]]))
r (rel/make-restrict-outer (sql/=$ (rel/make-attribute-ref "C")
(rel/make-attribute-ref "E"))
(rel/make-left-outer-product (rel/make-product t1 t2) t3))
sql (rel-alg-sql/query->sql r)]
(is (= ["SELECT * FROM ( SELECT * FROM t1 , t2 ) LEFT JOIN t3 ON ( C = E )" []]
(test-run (put/put-sql-select sql)))))))
(deftest put-joining-infix-test
(is (= ["foo bar baz" []]
(test-run (put/put-joining-infix ["foo" "bar" "baz"] "" put/write!))))
(is (= ["foo - bar - baz" []]
(test-run (put/put-joining-infix ["foo" "bar" "baz"] "-" put/write!)))))
(deftest put-tables-test
(is (= ["foo" []]
(test-run (put/put-tables [[nil (sql/make-sql-select-table nil "foo")]] ", "))))
(is (= ["foo , bar TESTAS b" []]
(test-run (put/put-tables [[nil (sql/make-sql-select-table nil "foo")]
["b" (sql/make-sql-select-table nil "bar")]]
", ")))))
(deftest default-put-combine-test
(let [q1 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-tables
[["S" (sql/make-sql-select-table nil "SUPPLIERS")]
[nil (sql/make-sql-select-table nil "CUSTOMERS")]])
(lens/shove sql/sql-select-attributes
{"UID" (sql/make-sql-expr-column "UID")})
(lens/shove sql/sql-select-order-by
[[(sql/make-sql-expr-column "uid") :ascending]])
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "foo")
(sql/make-sql-expr-const integer% 10))
(sql/make-sql-expr-app sql/op-=
(sql/make-sql-expr-column "uid")
(sql/make-sql-expr-const integer% 5))]))
q2 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-attributes
{"cost" (sql/make-sql-expr-column "cost")})
(rel-alg-sql/add-table (sql/make-sql-select-table nil "PARTS"))
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "cost")
(sql/make-sql-expr-const integer% 100))]))]
(is (= [ (str "( SELECT UID FROM SUPPLIERS TESTAS S , CUSTOMERS WHERE ( foo < ? ) AND ( uid = ? ) ORDER BY uid ASC ) "
"UNION "
"( SELECT cost FROM PARTS WHERE ( cost < ? ) )")
[[integer% 10] [integer% 5] [integer% 100]]]
(test-run (put/default-put-combine :union q1 q2))))))
(deftest put-when-test
(is (= ["WHEN ? THEN ?" [[string% "foo"] [string% "bar"]]]
(test-run (put/put-when [(sql/make-sql-expr-const string% "foo")
(sql/make-sql-expr-const string% "bar")])))))
(deftest put-group-by-test
(is (= ["GROUP BY cost" []] (test-run (put/put-group-by #{"cost"}))))
(is (= ["GROUP BY cost , supplier" []] (test-run (put/put-group-by #{"cost" "supplier"})))))
(deftest put-order-by-test
(is (= ["ORDER BY one ASC" []]
(test-run (put/put-order-by [[(sql/make-sql-expr-column "one") :ascending]]))))
(is (= ["ORDER BY one ASC , two DESC" []]
(test-run (put/put-order-by [[(sql/make-sql-expr-column "one") :ascending]
[(sql/make-sql-expr-column "two") :descending]])))))
(deftest put-attributes-test
(is (= ["*" []] (test-run (put/put-attributes nil))))
(is (= ["foo , bar TESTAS something-else , same" []]
(test-run (put/put-attributes [[nil (sql/make-sql-expr-column "foo")]
["something-else" (sql/make-sql-expr-column "bar")]
["same" (sql/make-sql-expr-column "same")]])))))
(deftest local-table-space-test
(let [t (sql/base-relation "rel"
(rel/alist->rel-scheme [["id" sql-t/integer%]]))]
(t/testing "with a table-space, it is reflected in the final query"
(t/is (= ["SELECT id FROM prefix.rel" []]
(test-run
(put/put-sql-select
(-> (qc/with-table-space "prefix"
(monad/monadic [e (qc/embed t)]
(qc/project [["id" (e "id")]])))
qc/get-query
o/optimize-query
rel-alg-sql/query->sql))))))))
| null | https://raw.githubusercontent.com/active-group/sqlosure/0201b0ddb054a9216b94808b2026460084411216/test/sqlosure/sql_put_test.clj | clojure | (ns sqlosure.sql-put-test
(:require [active.clojure.lens :as lens]
[active.clojure.monad :as monad]
[clojure.test :as t :refer [deftest is testing]]
[clojure.string :as string]
[sqlosure.core :as c]
[sqlosure.optimization :as o]
[sqlosure.query-comprehension :as qc]
[sqlosure.relational-algebra-sql :as rel-alg-sql]
[sqlosure.relational-algebra :as rel]
[sqlosure.sql :as sql]
[sqlosure.sql-put :as put]
[sqlosure.type :as sql-t :refer [string% integer% double% boolean%]]))
(def tbl1 (sql/base-relation "tbl1"
[["one" string%]
["two" double%]]
:universe sql/sql-universe
:handle "tbl1"))
(def test-put-parameterization
(put/make-sql-put-parameterization
(fn [alias]
(if alias
(put/write! "TESTAS" alias)
(active.clojure.monad/return nil)))
put/default-put-combine))
(def test-run (partial put/run test-put-parameterization))
(deftest put-padding-if-non-null-test
(is (= ["" []] (test-run (put/put-padding-if-non-null nil put/write!))))
(is (= ["foo bar baz" []]
(test-run (put/put-padding-if-non-null ["foo" "bar" "baz"]
#(put/write! (string/join " " %)))))))
(deftest put-alias-test
(is (= ["TESTAS foo" []] (test-run (put/put-alias "foo"))))
(is (= ["" []] (test-run (put/put-alias nil)))))
(deftest put-literal-test
(is (= ["?" [[integer% 42]]] (test-run (put/put-literal integer% 42))))
(is (= ["?" [[string% "foobar"]]] (test-run (put/put-literal string% "foobar"))))
(is (= ["?" [[string% nil]]] (test-run (put/put-literal string% nil))))
(is (= ["?" [[boolean% true]]] (test-run (put/put-literal boolean% true))))
(is (= ["?" [[boolean% false]]] (test-run (put/put-literal boolean% false)))))
(deftest put-sql-select-test
(is (= ["" []] (test-run (put/put-sql-select (sql/new-sql-select)))))
(is (= ["SELECT * FROM CUSTOMERS" []]
(test-run (put/put-sql-select (sql/make-sql-select-table nil "CUSTOMERS")))))
(t/testing "table-spaces are printed correctly"
(t/is (= ["SELECT * FROM prefix.table" []]
(-> (sql/base-relation "table" [])
(rel/base-relation-table-space "prefix")
rel-alg-sql/query->sql
put/put-sql-select
test-run))))
(let [o (rel/make-order
{(rel/make-attribute-ref "one") :ascending}
tbl1)
q (rel-alg-sql/query->sql o)]
(is (= ["SELECT * FROM tbl1 ORDER BY one ASC" []]
(test-run (put/put-sql-select q)))))
(let [q1 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-tables
[["S" (sql/make-sql-select-table nil "SUPPLIERS")]
[nil (sql/make-sql-select-table nil "CUSTOMERS")]])
(lens/shove sql/sql-select-attributes
{"UID" (sql/make-sql-expr-column "UID")})
(lens/shove sql/sql-select-order-by
[[(sql/make-sql-expr-column "uid") :ascending]])
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "foo")
(sql/make-sql-expr-const integer% 10))
(sql/make-sql-expr-app sql/op-=
(sql/make-sql-expr-column "uid")
(sql/make-sql-expr-const integer% 5))]))
q2 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-attributes
{"cost" (sql/make-sql-expr-column "cost")})
(rel-alg-sql/add-table (sql/make-sql-select-table nil "PARTS"))
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "cost")
(sql/make-sql-expr-const integer% 100))]))]
(is (= ["SELECT UID FROM SUPPLIERS TESTAS S , CUSTOMERS WHERE ( foo < ? ) AND ( uid = ? ) ORDER BY uid ASC"
[[integer% 10] [integer% 5]]]
(test-run (put/put-sql-select q1))))
(is (= [(str "( SELECT UID "
"FROM SUPPLIERS TESTAS S , CUSTOMERS "
"WHERE ( foo < ? ) AND ( uid = ? ) "
"ORDER BY uid ASC ) "
"UNION "
"( SELECT cost "
"FROM PARTS "
"WHERE ( cost < ? ) )")
[[integer% 10] [integer% 5] [integer% 100]]]
(test-run (put/put-sql-select
(sql/make-sql-select-combine :union q1 q2)))))))
(deftest put-sql-outer-join-test
(testing "simple case"
(let [t1 (sql/base-relation "t1"
(rel/alist->rel-scheme [["C" string%]]))
t2 (sql/base-relation "t2"
(rel/alist->rel-scheme [["D" integer%]]))
r (rel/make-restrict-outer (sql/=$ (rel/make-attribute-ref "C")
(rel/make-attribute-ref "D"))
(rel/make-left-outer-product t1 t2))
sql (rel-alg-sql/query->sql r)]
(is (= ["SELECT * FROM t1 LEFT JOIN t2 ON ( C = D )" []]
(test-run (put/put-sql-select sql))))))
(testing "multiple tables on the left"
(let [t1 (sql/base-relation "t1"
(rel/alist->rel-scheme [["C" string%]]))
t2 (sql/base-relation "t2"
(rel/alist->rel-scheme [["D" integer%]]))
t3 (sql/base-relation "t3"
(rel/alist->rel-scheme [["E" integer%]]))
r (rel/make-restrict-outer (sql/=$ (rel/make-attribute-ref "C")
(rel/make-attribute-ref "E"))
(rel/make-left-outer-product (rel/make-product t1 t2) t3))
sql (rel-alg-sql/query->sql r)]
(is (= ["SELECT * FROM ( SELECT * FROM t1 , t2 ) LEFT JOIN t3 ON ( C = E )" []]
(test-run (put/put-sql-select sql)))))))
(deftest put-joining-infix-test
(is (= ["foo bar baz" []]
(test-run (put/put-joining-infix ["foo" "bar" "baz"] "" put/write!))))
(is (= ["foo - bar - baz" []]
(test-run (put/put-joining-infix ["foo" "bar" "baz"] "-" put/write!)))))
(deftest put-tables-test
(is (= ["foo" []]
(test-run (put/put-tables [[nil (sql/make-sql-select-table nil "foo")]] ", "))))
(is (= ["foo , bar TESTAS b" []]
(test-run (put/put-tables [[nil (sql/make-sql-select-table nil "foo")]
["b" (sql/make-sql-select-table nil "bar")]]
", ")))))
(deftest default-put-combine-test
(let [q1 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-tables
[["S" (sql/make-sql-select-table nil "SUPPLIERS")]
[nil (sql/make-sql-select-table nil "CUSTOMERS")]])
(lens/shove sql/sql-select-attributes
{"UID" (sql/make-sql-expr-column "UID")})
(lens/shove sql/sql-select-order-by
[[(sql/make-sql-expr-column "uid") :ascending]])
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "foo")
(sql/make-sql-expr-const integer% 10))
(sql/make-sql-expr-app sql/op-=
(sql/make-sql-expr-column "uid")
(sql/make-sql-expr-const integer% 5))]))
q2 (-> (sql/new-sql-select)
(lens/shove sql/sql-select-attributes
{"cost" (sql/make-sql-expr-column "cost")})
(rel-alg-sql/add-table (sql/make-sql-select-table nil "PARTS"))
(lens/shove sql/sql-select-criteria
[(sql/make-sql-expr-app sql/op-<
(sql/make-sql-expr-column "cost")
(sql/make-sql-expr-const integer% 100))]))]
(is (= [ (str "( SELECT UID FROM SUPPLIERS TESTAS S , CUSTOMERS WHERE ( foo < ? ) AND ( uid = ? ) ORDER BY uid ASC ) "
"UNION "
"( SELECT cost FROM PARTS WHERE ( cost < ? ) )")
[[integer% 10] [integer% 5] [integer% 100]]]
(test-run (put/default-put-combine :union q1 q2))))))
(deftest put-when-test
(is (= ["WHEN ? THEN ?" [[string% "foo"] [string% "bar"]]]
(test-run (put/put-when [(sql/make-sql-expr-const string% "foo")
(sql/make-sql-expr-const string% "bar")])))))
(deftest put-group-by-test
(is (= ["GROUP BY cost" []] (test-run (put/put-group-by #{"cost"}))))
(is (= ["GROUP BY cost , supplier" []] (test-run (put/put-group-by #{"cost" "supplier"})))))
(deftest put-order-by-test
(is (= ["ORDER BY one ASC" []]
(test-run (put/put-order-by [[(sql/make-sql-expr-column "one") :ascending]]))))
(is (= ["ORDER BY one ASC , two DESC" []]
(test-run (put/put-order-by [[(sql/make-sql-expr-column "one") :ascending]
[(sql/make-sql-expr-column "two") :descending]])))))
(deftest put-attributes-test
(is (= ["*" []] (test-run (put/put-attributes nil))))
(is (= ["foo , bar TESTAS something-else , same" []]
(test-run (put/put-attributes [[nil (sql/make-sql-expr-column "foo")]
["something-else" (sql/make-sql-expr-column "bar")]
["same" (sql/make-sql-expr-column "same")]])))))
(deftest local-table-space-test
(let [t (sql/base-relation "rel"
(rel/alist->rel-scheme [["id" sql-t/integer%]]))]
(t/testing "with a table-space, it is reflected in the final query"
(t/is (= ["SELECT id FROM prefix.rel" []]
(test-run
(put/put-sql-select
(-> (qc/with-table-space "prefix"
(monad/monadic [e (qc/embed t)]
(qc/project [["id" (e "id")]])))
qc/get-query
o/optimize-query
rel-alg-sql/query->sql))))))))
| |
1c4df13695a631b7fd3295cc0564741f070edbca335ac4285948010fdb288108 | mput/sicp-solutions | 1_32.rkt | #lang racket
Solution for exercise 1_32 .
(require rackunit "../solutions/utils.rkt")
(provide accumulation accumulation-iter)
(define (accumulation null-value combiner term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulation null-value combiner term (next a) next b))))
(define (accumulation-iter null-value combiner term a next b)
(define (iter next-a acc)
(if (> next-a b)
acc
(iter (next next-a) (combiner (term next-a) acc))))
(iter a null-value))
| null | https://raw.githubusercontent.com/mput/sicp-solutions/fe12ad2b6f17c99978c8fe04b2495005986b8496/solutions/1_32.rkt | racket | #lang racket
Solution for exercise 1_32 .
(require rackunit "../solutions/utils.rkt")
(provide accumulation accumulation-iter)
(define (accumulation null-value combiner term a next b)
(if (> a b)
null-value
(combiner (term a) (accumulation null-value combiner term (next a) next b))))
(define (accumulation-iter null-value combiner term a next b)
(define (iter next-a acc)
(if (> next-a b)
acc
(iter (next next-a) (combiner (term next-a) acc))))
(iter a null-value))
| |
d73f59c683546e5b87fd9f8d4b4fa9e664a1443f11c509d86308c4f27386e0a1 | avsm/mirage-duniverse | routing.ml | RFC 1112 : 01 - 00 - 5E-00 - 00 - 00 ORed with lower 23 bits of the ip address
let mac_of_multicast ip =
let ipb = Ipaddr.V4.to_bytes ip in
let macb = Bytes.create 6 in
Bytes.set macb 0 (Char.chr 0x01);
Bytes.set macb 1 (Char.chr 0x00);
Bytes.set macb 2 (Char.chr 0x5E);
Bytes.set macb 3 (Char.chr ((Char.code ipb.[1]) land 0x7F));
Bytes.set macb 4 (String.get ipb 2);
Bytes.set macb 5 (String.get ipb 3);
Macaddr.of_bytes_exn (Bytes.to_string macb)
type routing_error = [ `Local | `Gateway ]
module Make(Log : Logs.LOG) (A : Mirage_protocols_lwt.ARP) = struct
open Lwt.Infix
let destination_mac network gateway arp = function
Broadcast
Lwt.return @@ Ok Macaddr.broadcast
|ip when Ipaddr.V4.is_multicast ip ->
Lwt.return @@ Ok (mac_of_multicast ip)
|ip when Ipaddr.V4.Prefix.mem ip network -> (* Local *)
A.query arp ip >|= begin function
| Ok mac -> Ok mac
| Error `Timeout ->
Log.info (fun f ->
f "IP.output: could not determine link-layer address for local \
network (%a) ip %a" Ipaddr.V4.Prefix.pp network
Ipaddr.V4.pp ip);
Error `Local
| Error e ->
Log.info (fun f -> f "IP.output: %a" A.pp_error e);
Error `Local
end
Gateway
match gateway with
| None ->
Log.info (fun f ->
f "IP.output: no route to %a (no default gateway is configured)"
Ipaddr.V4.pp ip);
Lwt.return (Error `Gateway)
| Some gateway ->
A.query arp gateway >|= function
| Ok mac -> Ok mac
| Error `Timeout ->
Log.info (fun f ->
f "IP.output: could not send to %a: failed to contact gateway %a"
Ipaddr.V4.pp ip Ipaddr.V4.pp gateway);
Error `Gateway
| Error e ->
Log.info (fun f -> f "IP.output: %a" A.pp_error e);
Error `Gateway
end
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tcpip/src/ipv4/routing.ml | ocaml | Local | RFC 1112 : 01 - 00 - 5E-00 - 00 - 00 ORed with lower 23 bits of the ip address
let mac_of_multicast ip =
let ipb = Ipaddr.V4.to_bytes ip in
let macb = Bytes.create 6 in
Bytes.set macb 0 (Char.chr 0x01);
Bytes.set macb 1 (Char.chr 0x00);
Bytes.set macb 2 (Char.chr 0x5E);
Bytes.set macb 3 (Char.chr ((Char.code ipb.[1]) land 0x7F));
Bytes.set macb 4 (String.get ipb 2);
Bytes.set macb 5 (String.get ipb 3);
Macaddr.of_bytes_exn (Bytes.to_string macb)
type routing_error = [ `Local | `Gateway ]
module Make(Log : Logs.LOG) (A : Mirage_protocols_lwt.ARP) = struct
open Lwt.Infix
let destination_mac network gateway arp = function
Broadcast
Lwt.return @@ Ok Macaddr.broadcast
|ip when Ipaddr.V4.is_multicast ip ->
Lwt.return @@ Ok (mac_of_multicast ip)
A.query arp ip >|= begin function
| Ok mac -> Ok mac
| Error `Timeout ->
Log.info (fun f ->
f "IP.output: could not determine link-layer address for local \
network (%a) ip %a" Ipaddr.V4.Prefix.pp network
Ipaddr.V4.pp ip);
Error `Local
| Error e ->
Log.info (fun f -> f "IP.output: %a" A.pp_error e);
Error `Local
end
Gateway
match gateway with
| None ->
Log.info (fun f ->
f "IP.output: no route to %a (no default gateway is configured)"
Ipaddr.V4.pp ip);
Lwt.return (Error `Gateway)
| Some gateway ->
A.query arp gateway >|= function
| Ok mac -> Ok mac
| Error `Timeout ->
Log.info (fun f ->
f "IP.output: could not send to %a: failed to contact gateway %a"
Ipaddr.V4.pp ip Ipaddr.V4.pp gateway);
Error `Gateway
| Error e ->
Log.info (fun f -> f "IP.output: %a" A.pp_error e);
Error `Gateway
end
|
639452f7af314f4af6a85fe4c363144833143eda3dbd04bed152cb3838ae891d | 6502/JSLisp | cplot.lisp | (import * from gui)
(defvar *data*
'((53.9751 51.5681 50.7119 51.1049 51.5339 51.4977 51.2387 50.761 50.1732 49.8218 49.5442 48.936 47.4498 46.6484 45.8542 45.136 44.5268 44.071 43.7665 43.5928 43.5269 43.5385 43.6053 45.565 47.0071 46.8664 47.372 47.8324 48.295 48.731 49.0522 49.4001 49.7111 49.9919 50.2527 50.4928 50.7135 50.8831 51.0806 51.2683)
(55.6671 52.53 50.7764 50.5632 51.2095 51.5659 51.521 51.2143 50.653 50.2371 49.989 49.8089 49.6058 47.8355 47.3124 46.7346 46.1616 45.6498 45.2462 44.967 44.8005 44.7284 44.7295 44.7869 46.959 45.0194 46.73 48.0766 48.9395 49.5325 49.8498 50.1887 50.4798 50.7406 50.9808 51.2003 51.4074 51.555 51.7429 51.9218)
(56.6513 53.5919 51.2774 50.3133 50.7705 51.533 51.8287 51.7083 51.2816 50.7933 50.4806 50.2671 50.1009 50.0096 49.9052 49.4698 47.4655 47.0717 46.6849 46.3583 46.1122 45.952 45.8678 45.8485 45.8811 45.956 46.0634 47.2225 49.4363 50.2482 50.527 50.8558 51.1358 51.3809 51.607 51.8179 52.0161 52.1454 52.3263 52.497)
(57.078 54.3224 52.0759 50.4679 50.4677 51.297 52.0284 52.1594 51.9395 51.5518 51.1419 50.8765 50.6686 50.5101 50.4078 50.3473 50.3592 50.3813 49.7504 47.55 47.324 47.1365 46.9978 46.9119 46.8743 46.8811 46.9257 47.0013 50.0148 50.9106 51.1133 51.4282 51.7064 51.943 52.1587 52.3597 52.4789 52.6631 52.8359 52.9966)
(57.3835 54.9025 52.8571 50.9842 50.5197 51.1494 52.0599 52.4732 52.4716 52.2656 51.9535 51.6068 51.3466 51.1513 50.9708 50.8321 50.7639 50.7944 50.8817 49.8122 48.2038 48.086 47.9704 47.8735 47.8035 47.7644 47.7574 47.7803 50.8194 51.5486 51.6645 51.9745 52.2349 52.4508 52.6481 52.8317 52.9412 53.1097 53.2699 53.4171)
(57.9157 55.6092 53.6306 51.8011 50.9372 51.2615 52.1406 52.7436 52.8528 52.7829 52.6322 52.403 52.1149 51.866 51.6624 51.4773 51.317 51.2183 51.2153 51.1367 48.5913 48.6216 48.6218 48.5951 48.5589 48.527 48.5081 50.5185 51.6998 51.905 52.2258 52.4891 52.7062 52.8926 53.0655 53.2251 53.3262 53.4755 53.6169 53.7471)
(58.6093 56.432 54.307 52.6277 51.584 51.6482 52.3762 53.0685 53.2545 53.217 53.1356 53.0351 52.8481 52.6154 52.39 52.177 51.9977 51.843 51.7172 51.4587 48.7481 48.7984 48.864 48.9291 48.9843 49.0228 50.496 51.8667 52.3404 52.4759 52.6889 52.8851 53.0525 53.2072 53.354 53.4576 53.5925 53.7217 53.8432 53.956)
(58.9719 56.9885 54.8768 53.3526 52.3025 52.2089 52.7762 53.4444 53.6768 53.6706 53.5692 53.5162 53.4373 53.2886 53.1113 52.9065 52.6988 52.5193 52.3544 52.0384 48.9624 48.9653 49.0005 49.0574 49.1258 50.692 51.9726 52.4309 52.699 52.8194 52.9845 53.1336 53.2669 53.393 53.5118 53.6086 53.7213 53.8293 53.9308 54.026)
(58.5754 56.945 55.068 53.7798 52.9469 52.854 53.3136 53.8929 54.1205 54.1178 54.0128 53.9289 53.8906 53.8239 53.717 53.5724 53.3818 53.1892 53.009 49.3078 49.2524 49.2165 49.2032 49.2187 50.463 51.9497 52.4487 52.7041 52.8358 52.9776 53.1101 53.2293 53.3419 53.4487 53.5401 53.6365 53.7301 53.8205 53.9062 53.9869)
(57.623 56.547 55.0117 54.0512 53.5372 53.5246 53.927 54.3868 54.5828 54.5811 54.4501 54.3235 54.2626 54.2334 54.1802 54.1137 53.9897 53.8202 49.796 49.6864 49.5946 49.5216 49.4703 49.4432 51.8479 52.5574 52.8359 52.9722 53.0827 53.1826 53.2747 53.3597 53.4405 53.5138 53.5944 53.6751 53.7536 53.829 53.9019 53.9721)
(56.902 56.0005 54.9159 54.3352 54.123 54.2014 54.5659 54.8917 55.0307 55.0139 54.8838 54.7044 54.5863 54.5548 54.5258 54.4957 54.4633 51.4821 50.1897 50.0758 49.9683 49.8704 49.7842 51.5064 52.7625 53.0724 53.1926 53.2682 53.3404 53.4119 53.4831 53.5517 53.6169 53.6763 53.7383 53.8009 53.8644 53.9281 53.9905 54.0517)
(56.3455 55.5524 54.9336 54.6836 54.703 54.8657 55.1749 55.3844 55.4521 55.4019 55.2622 55.0281 54.8981 54.6591 54.7866 54.7678 54.7654 54.0436 54.2302 52.2533 50.3305 50.2276 50.1268 52.9617 53.4395 53.5504 53.5481 53.5524 53.5699 53.6014 53.644 53.6931 53.7445 53.7996 53.8548 53.9097 53.9655 54.0229 54.0813 54.1393)
(55.7493 55.3019 55.1012 55.0906 55.234 55.4751 55.7134 55.8462 55.8461 55.7425 55.5725 55.3535 55.1612 54.958 55.0193 54.9584 54.9531 54.8886 54.8256 54.2211 50.6477 50.5564 53.0546 53.8592 54.08 54.0288 53.9509 53.8796 53.8307 53.8073 53.8034 53.8142 53.8383 53.8725 53.9128 53.9558 54.0013 54.0497 54.103 54.1597)
(55.2575 55.1664 55.3165 55.5004 55.7345 55.9901 56.1852 56.2599 56.2027 56.0454 55.818 55.5754 55.302 55.2083 55.0224 55.1415 55.0656 55.0446 55.0263 54.7728 50.8924 53.4671 54.2587 54.5146 54.6171 54.519 54.3857 54.2497 54.1355 54.0509 53.9932 53.9584 53.941 53.939 53.9527 53.9798 54.0111 54.0465 54.0868 54.1339)
(54.8665 55.1533 55.5095 55.8512 56.1541 56.3995 56.5593 56.6009 56.5079 56.3001 56.0178 55.7187 55.448 55.063 55.2016 55.2116 55.1817 55.112 55.1099 55.0299 54.3358 54.6966 54.9199 55.0156 55.0728 54.975 54.8299 54.6609 54.493 54.3475 54.2349 54.1517 54.0928 54.0516 54.0245 54.013 54.0206 54.0404 54.0667 54.0989)
(54.2676 55.1132 55.6112 56.09 56.428 56.6661 56.8056 56.8374 56.7339 56.4923 56.1474 55.7977 55.4805 55.2341 54.8999 55.2662 55.2927 55.185 55.1237 55.1268 54.9772 55.1418 55.2612 55.3333 55.379 55.3244 55.2153 55.0629 54.881 54.6926 54.523 54.3866 54.2855 54.2118 54.1583 54.1191 54.0935 54.0834 54.0885 54.1057)
(54.1771 55.0795 55.7075 56.1772 56.5183 56.7522 56.8898 56.9315 56.8427 56.6056 56.2317 55.8095 55.4436 55.183 55.0284 54.9504 55.2833 55.2563 55.1498 55.1342 55.1331 55.259 55.3705 55.4452 55.4955 55.5087 55.4697 55.3766 55.2324 55.049 54.8485 54.6578 54.4995 54.3822 54.3002 54.2427 54.2022 54.1749 54.1598 54.1561)
(53.9112 54.85 55.6641 56.0844 56.4062 56.6232 56.757 56.8149 56.7669 56.5754 56.2311 55.785 55.366 55.0104 54.812 54.8845 55.1273 55.2339 55.1976 55.1049 55.0913 55.1843 55.3048 55.4076 55.4709 55.518 55.5455 55.5329 55.4636 55.3349 55.1595 54.9529 54.7462 54.5681 54.4342 54.3439 54.2848 54.2446 54.2222 54.2135)
(53.9368 54.9196 55.4408 55.7999 56.0652 56.2423 56.348 56.4106 56.4114 56.3028 56.0519 55.6779 55.2493 54.8836 54.6592 54.6347 54.8341 55.0606 55.1396 55.0967 55.0325 55.0501 55.1451 55.2627 55.3559 55.4216 55.4789 55.5183 55.5245 55.4779 55.3701 55.2072 55.0029 54.7876 54.5915 54.4378 54.3368 54.2787 54.2415 54.2271)
(53.9325 54.6506 55.0421 55.2926 55.4603 55.5679 55.6285 55.6792 55.7234 55.731 55.639 55.3923 55.043 54.6845 54.4188 54.3242 54.4606 54.7449 54.9548 55.0171 55.0047 54.9454 54.9666 55.0651 55.1828 55.2677 55.3308 55.3914 55.438 55.4544 55.4277 55.3385 55.1907 54.9981 54.7786 54.5691 54.4013 54.2898 54.233 54.1994)))
(defun refine (data)
(let ((result (list (first data)
(* 0.5 (+ (first data) (second data))))))
(dolist (i (range 1 (1- (length data))))
(push (/ (+ (aref data (1- i))
(aref data (1+ i))
(* 4 (aref data i)))
6)
result)
(push (* 0.5 (+ (aref data i) (aref data (1+ i)))) result))
(push (last data) result)
result))
(defun smooth2d (data)
(let** ((rows (length data))
(cols (length (first data)))
(nrows (1- (* 2 rows)))
(ncols (1- (* 2 cols)))
(result (repeat-collect nrows (list))))
(dotimes (j cols)
(enumerate (i v (refine (map (lambda (i) (aref data i j)) (range rows))))
(push v (aref result i))))
(map #'refine result)))
(setf *data* (smooth2d *data*))
(setf *data* (smooth2d *data*))
(defvar *maxv* (apply #'max (map (lambda (row) (apply #'max row)) *data*)))
(defvar *minv* (apply #'min (map (lambda (row) (apply #'min row)) *data*)))
(defun sample (i j)
(let** ((rows (length *data*))
(cols (length (first *data*)))
(i0 (min (- rows 2) (max 0 (floor i))))
(j0 (min (- cols 2) (max 0 (floor j))))
(i1 (1+ i0))
(j1 (1+ j0))
(v00 (aref *data* i0 j0))
(v01 (aref *data* i0 j1))
(v10 (aref *data* i1 j0))
(v11 (aref *data* i1 j1))
(z_0 (+ v00 (* (- i i0) (- v10 v00))))
(z_1 (+ v01 (* (- i i0) (- v11 v01))))
(z (+ z_0 (* (- j j0) (- z_1 z_0)))))
(/ (- z *minv*) (- *maxv* *minv*))))
(defun cplot (w h f x0 y0 x1 y1 scale)
(let** ((canvas (create-element "canvas"))
(ctx (canvas.getContext "2d"))
(mn null)
(mx null)
(N 80)
(L 30))
(setf canvas.width w)
(setf canvas.height h)
(let** ((idata (ctx.getImageData 0 0 w h))
(data idata.data)
(wp 0))
(dotimes (i h)
(let ((y (+ y0 (/ (* (+ 0.5 i) (- y1 y0)) h))))
(dotimes (j w)
(let ((x (+ x0 (/ (* (+ 0.5 j) (- x1 x0)) w))))
(let** ((val (funcall f x y))
(color (funcall scale val)))
(setf (aref data wp) (third color))
(setf (aref data (+ wp 1)) (second color))
(setf (aref data (+ wp 2)) (first color))
(setf (aref data (+ wp 3)) 255)
(incf wp 4)
(when (or (null? mn) (> mn val)) (setf mn val))
(when (or (null? mx) (< mx val)) (setf mx val)))))))
(ctx.putImageData idata 0 0))
(setf ctx.strokeStyle "#000")
(setf ctx.lineWidth 1)
(ctx.beginPath)
(dotimes (i N)
(let ((ya (+ y0 (/ (* i (- y1 y0)) N)))
(yb (+ y0 (/ (* (1+ i) (- y1 y0)) N))))
(dotimes (j N)
(let** ((xa (+ x0 (/ (* j (- x1 x0)) N)))
(xb (+ x0 (/ (* (1+ j) (- x1 x0)) N)))
(aa (funcall f xa ya))
(ab (funcall f xa yb))
(ba (funcall f xb ya))
(bb (funcall f xb yb)))
(dotimes (k L)
(let ((zz (+ mn (/ (* (+ 0.5 k) (- mx mn)) L)))
(even true))
(dolist ((xx0 yy0 z0 xx1 yy1 z1)
(list (list xa ya aa xa yb ab)
(list xa yb ab xb yb bb)
(list xb yb bb xb ya ba)
(list xb ya ba xa ya aa)))
(when (or (and (>= zz z0) (< zz z1))
(and (>= zz z1) (< zz z0)))
(let** ((t (/ (- zz z0) (- z1 z0)))
(xx (+ xx0 (* t (- xx1 xx0))))
(yy (+ yy0 (* t (- yy1 yy0))))
(x (* w (/ (- xx x0) (- x1 x0))))
(y (* h (/ (- yy y0) (- y1 y0)))))
(if even
(progn
(ctx.moveTo x y)
(setf even false))
(progn
(ctx.lineTo x y)
(setf even true))))))))))))
(ctx.stroke)
canvas))
(defun scale (x)
; black->blue->cyan->green->yellow->red scale
(let** ((k (* 256 5))
(i (max 0 (min (* x k))))
(zone (ash i -8))
(step (logand i 255)))
(cond
((= zone 0) (list 255 (- 255 step) (- 255 step)))
((= zone 1) (list 255 step 0))
((= zone 2) (list (- 255 step) 255 0))
((= zone 3) (list 0 255 step))
(true (list 0 (- 255 step) 255)))))
(defun main ()
(let ((canvas (cplot 512 512
#'sample
0 0 (length *data*) (length (first *data*))
#'scale)))
(append-child document.body
(set-style canvas
position "absolute"
px/top 0
px/right 0))))
(main)
| null | https://raw.githubusercontent.com/6502/JSLisp/9a4aa1a9116f0cfc598ec9f3f30b59d99810a728/examples/cplot.lisp | lisp | black->blue->cyan->green->yellow->red scale | (import * from gui)
(defvar *data*
'((53.9751 51.5681 50.7119 51.1049 51.5339 51.4977 51.2387 50.761 50.1732 49.8218 49.5442 48.936 47.4498 46.6484 45.8542 45.136 44.5268 44.071 43.7665 43.5928 43.5269 43.5385 43.6053 45.565 47.0071 46.8664 47.372 47.8324 48.295 48.731 49.0522 49.4001 49.7111 49.9919 50.2527 50.4928 50.7135 50.8831 51.0806 51.2683)
(55.6671 52.53 50.7764 50.5632 51.2095 51.5659 51.521 51.2143 50.653 50.2371 49.989 49.8089 49.6058 47.8355 47.3124 46.7346 46.1616 45.6498 45.2462 44.967 44.8005 44.7284 44.7295 44.7869 46.959 45.0194 46.73 48.0766 48.9395 49.5325 49.8498 50.1887 50.4798 50.7406 50.9808 51.2003 51.4074 51.555 51.7429 51.9218)
(56.6513 53.5919 51.2774 50.3133 50.7705 51.533 51.8287 51.7083 51.2816 50.7933 50.4806 50.2671 50.1009 50.0096 49.9052 49.4698 47.4655 47.0717 46.6849 46.3583 46.1122 45.952 45.8678 45.8485 45.8811 45.956 46.0634 47.2225 49.4363 50.2482 50.527 50.8558 51.1358 51.3809 51.607 51.8179 52.0161 52.1454 52.3263 52.497)
(57.078 54.3224 52.0759 50.4679 50.4677 51.297 52.0284 52.1594 51.9395 51.5518 51.1419 50.8765 50.6686 50.5101 50.4078 50.3473 50.3592 50.3813 49.7504 47.55 47.324 47.1365 46.9978 46.9119 46.8743 46.8811 46.9257 47.0013 50.0148 50.9106 51.1133 51.4282 51.7064 51.943 52.1587 52.3597 52.4789 52.6631 52.8359 52.9966)
(57.3835 54.9025 52.8571 50.9842 50.5197 51.1494 52.0599 52.4732 52.4716 52.2656 51.9535 51.6068 51.3466 51.1513 50.9708 50.8321 50.7639 50.7944 50.8817 49.8122 48.2038 48.086 47.9704 47.8735 47.8035 47.7644 47.7574 47.7803 50.8194 51.5486 51.6645 51.9745 52.2349 52.4508 52.6481 52.8317 52.9412 53.1097 53.2699 53.4171)
(57.9157 55.6092 53.6306 51.8011 50.9372 51.2615 52.1406 52.7436 52.8528 52.7829 52.6322 52.403 52.1149 51.866 51.6624 51.4773 51.317 51.2183 51.2153 51.1367 48.5913 48.6216 48.6218 48.5951 48.5589 48.527 48.5081 50.5185 51.6998 51.905 52.2258 52.4891 52.7062 52.8926 53.0655 53.2251 53.3262 53.4755 53.6169 53.7471)
(58.6093 56.432 54.307 52.6277 51.584 51.6482 52.3762 53.0685 53.2545 53.217 53.1356 53.0351 52.8481 52.6154 52.39 52.177 51.9977 51.843 51.7172 51.4587 48.7481 48.7984 48.864 48.9291 48.9843 49.0228 50.496 51.8667 52.3404 52.4759 52.6889 52.8851 53.0525 53.2072 53.354 53.4576 53.5925 53.7217 53.8432 53.956)
(58.9719 56.9885 54.8768 53.3526 52.3025 52.2089 52.7762 53.4444 53.6768 53.6706 53.5692 53.5162 53.4373 53.2886 53.1113 52.9065 52.6988 52.5193 52.3544 52.0384 48.9624 48.9653 49.0005 49.0574 49.1258 50.692 51.9726 52.4309 52.699 52.8194 52.9845 53.1336 53.2669 53.393 53.5118 53.6086 53.7213 53.8293 53.9308 54.026)
(58.5754 56.945 55.068 53.7798 52.9469 52.854 53.3136 53.8929 54.1205 54.1178 54.0128 53.9289 53.8906 53.8239 53.717 53.5724 53.3818 53.1892 53.009 49.3078 49.2524 49.2165 49.2032 49.2187 50.463 51.9497 52.4487 52.7041 52.8358 52.9776 53.1101 53.2293 53.3419 53.4487 53.5401 53.6365 53.7301 53.8205 53.9062 53.9869)
(57.623 56.547 55.0117 54.0512 53.5372 53.5246 53.927 54.3868 54.5828 54.5811 54.4501 54.3235 54.2626 54.2334 54.1802 54.1137 53.9897 53.8202 49.796 49.6864 49.5946 49.5216 49.4703 49.4432 51.8479 52.5574 52.8359 52.9722 53.0827 53.1826 53.2747 53.3597 53.4405 53.5138 53.5944 53.6751 53.7536 53.829 53.9019 53.9721)
(56.902 56.0005 54.9159 54.3352 54.123 54.2014 54.5659 54.8917 55.0307 55.0139 54.8838 54.7044 54.5863 54.5548 54.5258 54.4957 54.4633 51.4821 50.1897 50.0758 49.9683 49.8704 49.7842 51.5064 52.7625 53.0724 53.1926 53.2682 53.3404 53.4119 53.4831 53.5517 53.6169 53.6763 53.7383 53.8009 53.8644 53.9281 53.9905 54.0517)
(56.3455 55.5524 54.9336 54.6836 54.703 54.8657 55.1749 55.3844 55.4521 55.4019 55.2622 55.0281 54.8981 54.6591 54.7866 54.7678 54.7654 54.0436 54.2302 52.2533 50.3305 50.2276 50.1268 52.9617 53.4395 53.5504 53.5481 53.5524 53.5699 53.6014 53.644 53.6931 53.7445 53.7996 53.8548 53.9097 53.9655 54.0229 54.0813 54.1393)
(55.7493 55.3019 55.1012 55.0906 55.234 55.4751 55.7134 55.8462 55.8461 55.7425 55.5725 55.3535 55.1612 54.958 55.0193 54.9584 54.9531 54.8886 54.8256 54.2211 50.6477 50.5564 53.0546 53.8592 54.08 54.0288 53.9509 53.8796 53.8307 53.8073 53.8034 53.8142 53.8383 53.8725 53.9128 53.9558 54.0013 54.0497 54.103 54.1597)
(55.2575 55.1664 55.3165 55.5004 55.7345 55.9901 56.1852 56.2599 56.2027 56.0454 55.818 55.5754 55.302 55.2083 55.0224 55.1415 55.0656 55.0446 55.0263 54.7728 50.8924 53.4671 54.2587 54.5146 54.6171 54.519 54.3857 54.2497 54.1355 54.0509 53.9932 53.9584 53.941 53.939 53.9527 53.9798 54.0111 54.0465 54.0868 54.1339)
(54.8665 55.1533 55.5095 55.8512 56.1541 56.3995 56.5593 56.6009 56.5079 56.3001 56.0178 55.7187 55.448 55.063 55.2016 55.2116 55.1817 55.112 55.1099 55.0299 54.3358 54.6966 54.9199 55.0156 55.0728 54.975 54.8299 54.6609 54.493 54.3475 54.2349 54.1517 54.0928 54.0516 54.0245 54.013 54.0206 54.0404 54.0667 54.0989)
(54.2676 55.1132 55.6112 56.09 56.428 56.6661 56.8056 56.8374 56.7339 56.4923 56.1474 55.7977 55.4805 55.2341 54.8999 55.2662 55.2927 55.185 55.1237 55.1268 54.9772 55.1418 55.2612 55.3333 55.379 55.3244 55.2153 55.0629 54.881 54.6926 54.523 54.3866 54.2855 54.2118 54.1583 54.1191 54.0935 54.0834 54.0885 54.1057)
(54.1771 55.0795 55.7075 56.1772 56.5183 56.7522 56.8898 56.9315 56.8427 56.6056 56.2317 55.8095 55.4436 55.183 55.0284 54.9504 55.2833 55.2563 55.1498 55.1342 55.1331 55.259 55.3705 55.4452 55.4955 55.5087 55.4697 55.3766 55.2324 55.049 54.8485 54.6578 54.4995 54.3822 54.3002 54.2427 54.2022 54.1749 54.1598 54.1561)
(53.9112 54.85 55.6641 56.0844 56.4062 56.6232 56.757 56.8149 56.7669 56.5754 56.2311 55.785 55.366 55.0104 54.812 54.8845 55.1273 55.2339 55.1976 55.1049 55.0913 55.1843 55.3048 55.4076 55.4709 55.518 55.5455 55.5329 55.4636 55.3349 55.1595 54.9529 54.7462 54.5681 54.4342 54.3439 54.2848 54.2446 54.2222 54.2135)
(53.9368 54.9196 55.4408 55.7999 56.0652 56.2423 56.348 56.4106 56.4114 56.3028 56.0519 55.6779 55.2493 54.8836 54.6592 54.6347 54.8341 55.0606 55.1396 55.0967 55.0325 55.0501 55.1451 55.2627 55.3559 55.4216 55.4789 55.5183 55.5245 55.4779 55.3701 55.2072 55.0029 54.7876 54.5915 54.4378 54.3368 54.2787 54.2415 54.2271)
(53.9325 54.6506 55.0421 55.2926 55.4603 55.5679 55.6285 55.6792 55.7234 55.731 55.639 55.3923 55.043 54.6845 54.4188 54.3242 54.4606 54.7449 54.9548 55.0171 55.0047 54.9454 54.9666 55.0651 55.1828 55.2677 55.3308 55.3914 55.438 55.4544 55.4277 55.3385 55.1907 54.9981 54.7786 54.5691 54.4013 54.2898 54.233 54.1994)))
(defun refine (data)
(let ((result (list (first data)
(* 0.5 (+ (first data) (second data))))))
(dolist (i (range 1 (1- (length data))))
(push (/ (+ (aref data (1- i))
(aref data (1+ i))
(* 4 (aref data i)))
6)
result)
(push (* 0.5 (+ (aref data i) (aref data (1+ i)))) result))
(push (last data) result)
result))
(defun smooth2d (data)
(let** ((rows (length data))
(cols (length (first data)))
(nrows (1- (* 2 rows)))
(ncols (1- (* 2 cols)))
(result (repeat-collect nrows (list))))
(dotimes (j cols)
(enumerate (i v (refine (map (lambda (i) (aref data i j)) (range rows))))
(push v (aref result i))))
(map #'refine result)))
(setf *data* (smooth2d *data*))
(setf *data* (smooth2d *data*))
(defvar *maxv* (apply #'max (map (lambda (row) (apply #'max row)) *data*)))
(defvar *minv* (apply #'min (map (lambda (row) (apply #'min row)) *data*)))
(defun sample (i j)
(let** ((rows (length *data*))
(cols (length (first *data*)))
(i0 (min (- rows 2) (max 0 (floor i))))
(j0 (min (- cols 2) (max 0 (floor j))))
(i1 (1+ i0))
(j1 (1+ j0))
(v00 (aref *data* i0 j0))
(v01 (aref *data* i0 j1))
(v10 (aref *data* i1 j0))
(v11 (aref *data* i1 j1))
(z_0 (+ v00 (* (- i i0) (- v10 v00))))
(z_1 (+ v01 (* (- i i0) (- v11 v01))))
(z (+ z_0 (* (- j j0) (- z_1 z_0)))))
(/ (- z *minv*) (- *maxv* *minv*))))
(defun cplot (w h f x0 y0 x1 y1 scale)
(let** ((canvas (create-element "canvas"))
(ctx (canvas.getContext "2d"))
(mn null)
(mx null)
(N 80)
(L 30))
(setf canvas.width w)
(setf canvas.height h)
(let** ((idata (ctx.getImageData 0 0 w h))
(data idata.data)
(wp 0))
(dotimes (i h)
(let ((y (+ y0 (/ (* (+ 0.5 i) (- y1 y0)) h))))
(dotimes (j w)
(let ((x (+ x0 (/ (* (+ 0.5 j) (- x1 x0)) w))))
(let** ((val (funcall f x y))
(color (funcall scale val)))
(setf (aref data wp) (third color))
(setf (aref data (+ wp 1)) (second color))
(setf (aref data (+ wp 2)) (first color))
(setf (aref data (+ wp 3)) 255)
(incf wp 4)
(when (or (null? mn) (> mn val)) (setf mn val))
(when (or (null? mx) (< mx val)) (setf mx val)))))))
(ctx.putImageData idata 0 0))
(setf ctx.strokeStyle "#000")
(setf ctx.lineWidth 1)
(ctx.beginPath)
(dotimes (i N)
(let ((ya (+ y0 (/ (* i (- y1 y0)) N)))
(yb (+ y0 (/ (* (1+ i) (- y1 y0)) N))))
(dotimes (j N)
(let** ((xa (+ x0 (/ (* j (- x1 x0)) N)))
(xb (+ x0 (/ (* (1+ j) (- x1 x0)) N)))
(aa (funcall f xa ya))
(ab (funcall f xa yb))
(ba (funcall f xb ya))
(bb (funcall f xb yb)))
(dotimes (k L)
(let ((zz (+ mn (/ (* (+ 0.5 k) (- mx mn)) L)))
(even true))
(dolist ((xx0 yy0 z0 xx1 yy1 z1)
(list (list xa ya aa xa yb ab)
(list xa yb ab xb yb bb)
(list xb yb bb xb ya ba)
(list xb ya ba xa ya aa)))
(when (or (and (>= zz z0) (< zz z1))
(and (>= zz z1) (< zz z0)))
(let** ((t (/ (- zz z0) (- z1 z0)))
(xx (+ xx0 (* t (- xx1 xx0))))
(yy (+ yy0 (* t (- yy1 yy0))))
(x (* w (/ (- xx x0) (- x1 x0))))
(y (* h (/ (- yy y0) (- y1 y0)))))
(if even
(progn
(ctx.moveTo x y)
(setf even false))
(progn
(ctx.lineTo x y)
(setf even true))))))))))))
(ctx.stroke)
canvas))
(defun scale (x)
(let** ((k (* 256 5))
(i (max 0 (min (* x k))))
(zone (ash i -8))
(step (logand i 255)))
(cond
((= zone 0) (list 255 (- 255 step) (- 255 step)))
((= zone 1) (list 255 step 0))
((= zone 2) (list (- 255 step) 255 0))
((= zone 3) (list 0 255 step))
(true (list 0 (- 255 step) 255)))))
(defun main ()
(let ((canvas (cplot 512 512
#'sample
0 0 (length *data*) (length (first *data*))
#'scale)))
(append-child document.body
(set-style canvas
position "absolute"
px/top 0
px/right 0))))
(main)
|
e91819dfa450e2f99efd6754cac05d962fb5dec93d2ba5a03344f54c97b70ed4 | input-output-hk/marlowe-cardano | SkippingBlocks.hs | module SkippingBlocks
where
import Control.Concurrent (threadDelay)
import Data.Functor (($>))
import Data.Void (absurd)
import Language.Marlowe.Runtime.ChainSync.Api
import Network.Protocol.ChainSeek.Client
This client advances 1000 blocks at a time until it reaches the tip .
client :: RuntimeChainSeekClient IO ()
client = ChainSeekClient stInit
where
stInit = pure $ SendMsgRequestHandshake moveSchema stHandshake
stHandshake = ClientStHandshake
{ recvMsgHandshakeRejected = \supportedVersions -> do
putStr "Schema version not supported by server. Supported versions: "
print supportedVersions
, recvMsgHandshakeConfirmed = stIdle 1000
}
stIdle stepSize = do
putStrLn $ "Advancing " <> show stepSize <> " block(s)"
pure $ SendMsgQueryNext (AdvanceBlocks stepSize) stNext
stNext = ClientStNext
{ recvMsgQueryRejected = absurd
, recvMsgRollForward = const handleNewPoint
, recvMsgRollBackward = handleNewPoint
, recvMsgWait = threadDelay 1_000_000 $> SendMsgPoll stNext
}
handleNewPoint point tip = do
putStrLn $ "New local tip: " <> show point
let
pointBlock = \case
Genesis -> -1
At BlockHeader{..} -> blockNo
let stepSize = max 1 $ min 1000 $ pointBlock tip - pointBlock point
stIdle $ fromIntegral stepSize
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/3d7d6381baca1b827ffaa519f130c5ad17a5f318/marlowe-chain-sync/example-client/SkippingBlocks.hs | haskell | module SkippingBlocks
where
import Control.Concurrent (threadDelay)
import Data.Functor (($>))
import Data.Void (absurd)
import Language.Marlowe.Runtime.ChainSync.Api
import Network.Protocol.ChainSeek.Client
This client advances 1000 blocks at a time until it reaches the tip .
client :: RuntimeChainSeekClient IO ()
client = ChainSeekClient stInit
where
stInit = pure $ SendMsgRequestHandshake moveSchema stHandshake
stHandshake = ClientStHandshake
{ recvMsgHandshakeRejected = \supportedVersions -> do
putStr "Schema version not supported by server. Supported versions: "
print supportedVersions
, recvMsgHandshakeConfirmed = stIdle 1000
}
stIdle stepSize = do
putStrLn $ "Advancing " <> show stepSize <> " block(s)"
pure $ SendMsgQueryNext (AdvanceBlocks stepSize) stNext
stNext = ClientStNext
{ recvMsgQueryRejected = absurd
, recvMsgRollForward = const handleNewPoint
, recvMsgRollBackward = handleNewPoint
, recvMsgWait = threadDelay 1_000_000 $> SendMsgPoll stNext
}
handleNewPoint point tip = do
putStrLn $ "New local tip: " <> show point
let
pointBlock = \case
Genesis -> -1
At BlockHeader{..} -> blockNo
let stepSize = max 1 $ min 1000 $ pointBlock tip - pointBlock point
stIdle $ fromIntegral stepSize
| |
5a4636e27299b94319d20fa7d2a375dc4e916005ebce116a166bd1b502e5a611 | caadxyz/caad4lisp | bubble.lisp | (in-package :caad4lisp)
;***************************************************************
BUBBLE.LSP
;***************************************************************
; Draws a bubble at the end of axes
;***************************************************************
; Let's define the variables.
; store the old env, after this command we can restore the env.
(setq
get cmdecho state
oldLayer (getvar "clayer") ; get current layer
)
;Let's define the command
(defun c:bubble()
(setq cap (getdist "\nEnter bubble diameter:"))
(setvar "cmdecho" 1)
;Change the LAYEr and close command echo
(command "_.layer" "_new" "TAL_BUBBLE" "_set" "TAL_BUBBLE" "")
(draw_bubble)
(setvar "cmdecho" oldCmdecho)
(setvar "clayer" oldLayer)
(princ "\n one bubble added")
(princ)
)
Bublle draw function
(defun draw_bubble (/ aks pp aks_hand acd_en bh aks_pt1 aks_pt2 aks_ang dist1 dist2 circlecenter)
;Let's select the end of the axis where we will place the bubble
;and the selection point.
(setq
aks (entsel "\nSelect the axis line:")
Selection point ( PICKPOINT )
aks_hand (entget (car aks)) ; List of axis member
acd_en (cdr (assoc 0 aks_hand)) ; Name of the selected entity
)
;If the selected entity is not LINE, then exit the program
(if (/= acd_en "LINE")
(progn
(princ "\nSelected entity is not LINE!")
(quit)
)
(princ)
)
;Now, let's ask the other questions
(setq bh (getstring "\nEnter bubble label:"))
;Let's make the calculations
;Calculate the start and end points of axis
(setq
aks_pt1 (cdr (assoc 10 aks_hand))
aks_pt2 (cdr (assoc 11 aks_hand))
)
;Let's calculate the angle of axis
( by using deg2rad function )
(setq aks_ang (angle aks_pt1 aks_pt2))
;Let's find which end of axis the selection
;point is more close to
(setq
dist1 (distance pp aks_pt1)
dist2 (distance pp aks_pt2)
)
;Now make the drawing calculations
;If the selection point is close to starting point
(if (< dist1 dist2)
(setq circlecenter (polar aks_pt1 (+ pi aks_ang) (/ cap 2.0)))
(setq circlecenter (polar aks_pt2 aks_ang (/ cap 2.0)))
)
;Draw bubble
(command "_.circle" circlecenter (/ cap 2.0))
(princ "\ndraw a circle")
;Write its text
(command "._text" "_j" "_middle" circlecenter (* cap 0.6) 0 bh )
(princ "\nwrite its text")
)
;finished drawing
(princ "\n BUBBLE loaded.")
(princ)
| null | https://raw.githubusercontent.com/caadxyz/caad4lisp/393eaa7893bdbf307a3615573fe22a8c1e2b9412/src/bubble.lisp | lisp | ***************************************************************
***************************************************************
Draws a bubble at the end of axes
***************************************************************
Let's define the variables.
store the old env, after this command we can restore the env.
get current layer
Let's define the command
Change the LAYEr and close command echo
Let's select the end of the axis where we will place the bubble
and the selection point.
List of axis member
Name of the selected entity
If the selected entity is not LINE, then exit the program
Now, let's ask the other questions
Let's make the calculations
Calculate the start and end points of axis
Let's calculate the angle of axis
Let's find which end of axis the selection
point is more close to
Now make the drawing calculations
If the selection point is close to starting point
Draw bubble
Write its text
finished drawing
| (in-package :caad4lisp)
BUBBLE.LSP
(setq
get cmdecho state
)
(defun c:bubble()
(setq cap (getdist "\nEnter bubble diameter:"))
(setvar "cmdecho" 1)
(command "_.layer" "_new" "TAL_BUBBLE" "_set" "TAL_BUBBLE" "")
(draw_bubble)
(setvar "cmdecho" oldCmdecho)
(setvar "clayer" oldLayer)
(princ "\n one bubble added")
(princ)
)
Bublle draw function
(defun draw_bubble (/ aks pp aks_hand acd_en bh aks_pt1 aks_pt2 aks_ang dist1 dist2 circlecenter)
(setq
aks (entsel "\nSelect the axis line:")
Selection point ( PICKPOINT )
)
(if (/= acd_en "LINE")
(progn
(princ "\nSelected entity is not LINE!")
(quit)
)
(princ)
)
(setq bh (getstring "\nEnter bubble label:"))
(setq
aks_pt1 (cdr (assoc 10 aks_hand))
aks_pt2 (cdr (assoc 11 aks_hand))
)
( by using deg2rad function )
(setq aks_ang (angle aks_pt1 aks_pt2))
(setq
dist1 (distance pp aks_pt1)
dist2 (distance pp aks_pt2)
)
(if (< dist1 dist2)
(setq circlecenter (polar aks_pt1 (+ pi aks_ang) (/ cap 2.0)))
(setq circlecenter (polar aks_pt2 aks_ang (/ cap 2.0)))
)
(command "_.circle" circlecenter (/ cap 2.0))
(princ "\ndraw a circle")
(command "._text" "_j" "_middle" circlecenter (* cap 0.6) 0 bh )
(princ "\nwrite its text")
)
(princ "\n BUBBLE loaded.")
(princ)
|
d043690ce81a95ca35af8be0a441fe3c65e6a0a85435e2f606a66a987b3e2a48 | bos/llvm | Target.hs | module LLVM.Wrapper.Target
( module LLVM.FFI.Target
, TargetData
, ByteOrdering(..)
, byteOrder
, copyStringRepOfTargetData
, createTargetData
, withTargetData
) where
import LLVM.FFI.Target
( addTargetData
, disposeTargetData
, intPtrType
, callFrameAlignmentOfType
, aBIAlignmentOfType
, aBISizeOfType
, pointerSize
, preferredAlignmentOfGlobal
, preferredAlignmentOfType
, sizeOfTypeInBits
, storeSizeOfType
, elementAtOffset
, offsetOfElement
)
import qualified LLVM.FFI.Target as FFI.T
import Foreign.C.String (peekCString, withCString)
import Control.Exception (finally)
type TargetData = FFI.T.TargetDataRef
data ByteOrdering = BigEndian | LittleEndian deriving Eq
byteOrder :: TargetData -> ByteOrdering
byteOrder td = if FFI.T.byteOrder td == 0 then BigEndian else LittleEndian
copyStringRepOfTargetData :: TargetData -> IO String
copyStringRepOfTargetData td = do s <- FFI.T.copyStringRepOfTargetData td
peekCString s
createTargetData :: String -> IO TargetData
createTargetData str = withCString str $ \p -> FFI.T.createTargetData p
withTargetData :: String -> (TargetData -> IO a) -> IO a
withTargetData str f = do t <- createTargetData str
finally (f t) (FFI.T.disposeTargetData t)
| null | https://raw.githubusercontent.com/bos/llvm/819b94d048c9d7787ce41cd7c71b84424e894f64/base/LLVM/Wrapper/Target.hs | haskell | module LLVM.Wrapper.Target
( module LLVM.FFI.Target
, TargetData
, ByteOrdering(..)
, byteOrder
, copyStringRepOfTargetData
, createTargetData
, withTargetData
) where
import LLVM.FFI.Target
( addTargetData
, disposeTargetData
, intPtrType
, callFrameAlignmentOfType
, aBIAlignmentOfType
, aBISizeOfType
, pointerSize
, preferredAlignmentOfGlobal
, preferredAlignmentOfType
, sizeOfTypeInBits
, storeSizeOfType
, elementAtOffset
, offsetOfElement
)
import qualified LLVM.FFI.Target as FFI.T
import Foreign.C.String (peekCString, withCString)
import Control.Exception (finally)
type TargetData = FFI.T.TargetDataRef
data ByteOrdering = BigEndian | LittleEndian deriving Eq
byteOrder :: TargetData -> ByteOrdering
byteOrder td = if FFI.T.byteOrder td == 0 then BigEndian else LittleEndian
copyStringRepOfTargetData :: TargetData -> IO String
copyStringRepOfTargetData td = do s <- FFI.T.copyStringRepOfTargetData td
peekCString s
createTargetData :: String -> IO TargetData
createTargetData str = withCString str $ \p -> FFI.T.createTargetData p
withTargetData :: String -> (TargetData -> IO a) -> IO a
withTargetData str f = do t <- createTargetData str
finally (f t) (FFI.T.disposeTargetData t)
| |
cc2b4cd938f37ad057aeb7a95bf3e1c89fef464dd61867d8457495c9ced1c38e | dsheets/ocaml-unix-dirent | myocamlbuild.ml | open Ocamlbuild_plugin;;
open Ocamlbuild_pack;;
let ctypes_libdir = Sys.getenv "CTYPES_LIB_DIR" in
let ocaml_libdir = Sys.getenv "OCAML_LIB_DIR" in
let lwt_libdir = try Sys.getenv "LWT_LIB_DIR" with Not_found -> "" in
dispatch begin
function
| After_rules ->
rule "cstubs: lib_gen/x_types_detect.c -> x_types_detect"
~prods:["lib_gen/%_types_detect"]
~deps:["lib_gen/%_types_detect.c"]
(fun env build ->
Cmd (S[A"cc";
A("-I"); A ctypes_libdir;
A("-I"); A ocaml_libdir;
A"-o";
A(env "lib_gen/%_types_detect");
A(env "lib_gen/%_types_detect.c");
]));
rule "cstubs: lib_gen/x_types_detect -> unix/x_types_detected.ml"
~prods:["unix/%_types_detected.ml"]
~deps:["lib_gen/%_types_detect"]
(fun env build ->
Cmd (S[A(env "lib_gen/%_types_detect");
Sh">";
A(env "unix/%_types_detected.ml");
]));
rule "cstubs: lib_gen/x_types.ml -> x_types_detect.c"
~prods:["lib_gen/%_types_detect.c"]
~deps: ["lib_gen/%_typegen.byte"]
(fun env build ->
Cmd (A(env "lib_gen/%_typegen.byte")));
copy_rule "cstubs: lib_gen/x_types.ml -> unix/x_types.ml"
"lib_gen/%_types.ml" "unix/%_types.ml";
rule "cstubs: unix/x_bindings.ml -> x_stubs.c, x_generated.ml"
~prods:["unix/%_stubs.c"; "unix/%_generated.ml"]
~deps: ["lib_gen/%_bindgen.byte"]
(fun env build ->
Cmd (S[A(env "lib_gen/%_bindgen.byte");
A"--c-file";
A(env "unix/%_stubs.c");
A"--ml-file";
A(env "unix/%_generated.ml")]));
rule "cstubs: lwt/x_bindings.ml -> lwt/x_stubs.c, lwt/x_generated.ml"
~prods:["lwt/%_lwt_stubs.c"; "lwt/%_lwt_generated.ml"]
~deps: ["lib_gen/%_bindgen.byte"]
(fun env build ->
Cmd (S[A(env "lib_gen/%_bindgen.byte");
A"--lwt-bindings";
A"--c-file";
A(env "lwt/%_lwt_stubs.c");
A"--ml-file";
A(env "lwt/%_lwt_generated.ml")]));
copy_rule "cstubs: lib_gen/x_bindings.ml -> unix/x_bindings.ml"
"lib_gen/%_bindings.ml" "unix/%_bindings.ml";
flag ["c"; "compile"] & S[A"-ccopt"; A"-I/usr/local/include"];
flag ["c"; "ocamlmklib"] & A"-L/usr/local/lib";
flag ["ocaml"; "link"; "native"; "program"] &
S[A"-cclib"; A"-L/usr/local/lib"];
(* Linking cstubs *)
dep ["c"; "compile"; "use_dirent_util"]
["unix/unix_dirent_util.o"; "unix/unix_dirent_util.h"];
flag ["c"; "compile"; "use_ctypes"] & S[A"-I"; A ctypes_libdir];
flag ["c"; "compile"; "use_lwt"] & S[A"-I"; A lwt_libdir];
flag ["c"; "compile"; "debug"] & A"-g";
(* Linking generated stubs *)
flag ["ocaml"; "link"; "byte"; "library"; "use_dirent_stubs"] &
S[A"-dllib"; A"-lunix_dirent_stubs"];
flag ["ocaml"; "link"; "native"; "library"; "use_dirent_stubs"] &
S[A"-cclib"; A"-lunix_dirent_stubs"];
flag ["ocaml"; "link"; "byte"; "library"; "use_dirent_lwt_stubs"] &
S[A"-dllib"; A"-lunix_dirent_lwt_stubs"];
flag ["ocaml"; "link"; "native"; "library"; "use_dirent_lwt_stubs"] &
S[A"-cclib"; A"-lunix_dirent_lwt_stubs"];
(* Linking tests *)
flag ["ocaml"; "link"; "byte"; "program"; "use_dirent_stubs"] &
S[A"-dllib"; A"-lunix_dirent_stubs"];
dep ["ocaml"; "link"; "native"; "program"; "use_dirent_stubs"]
["unix/libunix_dirent_stubs"-.-(!Options.ext_lib)];
flag ["ocaml"; "link"; "byte"; "program"; "use_dirent_lwt_stubs"] &
S[A"-dllib"; A"-lunix_lwt_dirent_stubs"];
dep ["ocaml"; "link"; "native"; "program"; "use_dirent_lwt_stubs"]
["lwt/libunix_dirent_lwt_stubs"-.-(!Options.ext_lib)];
| _ -> ()
end;;
| null | https://raw.githubusercontent.com/dsheets/ocaml-unix-dirent/b3749486aa44642b911b7740193cd8133c6e144a/myocamlbuild.ml | ocaml | Linking cstubs
Linking generated stubs
Linking tests | open Ocamlbuild_plugin;;
open Ocamlbuild_pack;;
let ctypes_libdir = Sys.getenv "CTYPES_LIB_DIR" in
let ocaml_libdir = Sys.getenv "OCAML_LIB_DIR" in
let lwt_libdir = try Sys.getenv "LWT_LIB_DIR" with Not_found -> "" in
dispatch begin
function
| After_rules ->
rule "cstubs: lib_gen/x_types_detect.c -> x_types_detect"
~prods:["lib_gen/%_types_detect"]
~deps:["lib_gen/%_types_detect.c"]
(fun env build ->
Cmd (S[A"cc";
A("-I"); A ctypes_libdir;
A("-I"); A ocaml_libdir;
A"-o";
A(env "lib_gen/%_types_detect");
A(env "lib_gen/%_types_detect.c");
]));
rule "cstubs: lib_gen/x_types_detect -> unix/x_types_detected.ml"
~prods:["unix/%_types_detected.ml"]
~deps:["lib_gen/%_types_detect"]
(fun env build ->
Cmd (S[A(env "lib_gen/%_types_detect");
Sh">";
A(env "unix/%_types_detected.ml");
]));
rule "cstubs: lib_gen/x_types.ml -> x_types_detect.c"
~prods:["lib_gen/%_types_detect.c"]
~deps: ["lib_gen/%_typegen.byte"]
(fun env build ->
Cmd (A(env "lib_gen/%_typegen.byte")));
copy_rule "cstubs: lib_gen/x_types.ml -> unix/x_types.ml"
"lib_gen/%_types.ml" "unix/%_types.ml";
rule "cstubs: unix/x_bindings.ml -> x_stubs.c, x_generated.ml"
~prods:["unix/%_stubs.c"; "unix/%_generated.ml"]
~deps: ["lib_gen/%_bindgen.byte"]
(fun env build ->
Cmd (S[A(env "lib_gen/%_bindgen.byte");
A"--c-file";
A(env "unix/%_stubs.c");
A"--ml-file";
A(env "unix/%_generated.ml")]));
rule "cstubs: lwt/x_bindings.ml -> lwt/x_stubs.c, lwt/x_generated.ml"
~prods:["lwt/%_lwt_stubs.c"; "lwt/%_lwt_generated.ml"]
~deps: ["lib_gen/%_bindgen.byte"]
(fun env build ->
Cmd (S[A(env "lib_gen/%_bindgen.byte");
A"--lwt-bindings";
A"--c-file";
A(env "lwt/%_lwt_stubs.c");
A"--ml-file";
A(env "lwt/%_lwt_generated.ml")]));
copy_rule "cstubs: lib_gen/x_bindings.ml -> unix/x_bindings.ml"
"lib_gen/%_bindings.ml" "unix/%_bindings.ml";
flag ["c"; "compile"] & S[A"-ccopt"; A"-I/usr/local/include"];
flag ["c"; "ocamlmklib"] & A"-L/usr/local/lib";
flag ["ocaml"; "link"; "native"; "program"] &
S[A"-cclib"; A"-L/usr/local/lib"];
dep ["c"; "compile"; "use_dirent_util"]
["unix/unix_dirent_util.o"; "unix/unix_dirent_util.h"];
flag ["c"; "compile"; "use_ctypes"] & S[A"-I"; A ctypes_libdir];
flag ["c"; "compile"; "use_lwt"] & S[A"-I"; A lwt_libdir];
flag ["c"; "compile"; "debug"] & A"-g";
flag ["ocaml"; "link"; "byte"; "library"; "use_dirent_stubs"] &
S[A"-dllib"; A"-lunix_dirent_stubs"];
flag ["ocaml"; "link"; "native"; "library"; "use_dirent_stubs"] &
S[A"-cclib"; A"-lunix_dirent_stubs"];
flag ["ocaml"; "link"; "byte"; "library"; "use_dirent_lwt_stubs"] &
S[A"-dllib"; A"-lunix_dirent_lwt_stubs"];
flag ["ocaml"; "link"; "native"; "library"; "use_dirent_lwt_stubs"] &
S[A"-cclib"; A"-lunix_dirent_lwt_stubs"];
flag ["ocaml"; "link"; "byte"; "program"; "use_dirent_stubs"] &
S[A"-dllib"; A"-lunix_dirent_stubs"];
dep ["ocaml"; "link"; "native"; "program"; "use_dirent_stubs"]
["unix/libunix_dirent_stubs"-.-(!Options.ext_lib)];
flag ["ocaml"; "link"; "byte"; "program"; "use_dirent_lwt_stubs"] &
S[A"-dllib"; A"-lunix_lwt_dirent_stubs"];
dep ["ocaml"; "link"; "native"; "program"; "use_dirent_lwt_stubs"]
["lwt/libunix_dirent_lwt_stubs"-.-(!Options.ext_lib)];
| _ -> ()
end;;
|
294e92fd191af36de58d4b542395988419901730d577c27e2d57967134a6023c | tcsprojects/pgsolver | recursiveladder.ml | open Paritygame;;
let generator_game_func arguments =
let show_help _ =
print_string (Info.get_title "Recursive Ladder Game Generator");
print_string ("Usage: recursiveladder n\n\n" ^
" where n = n-th recursive ladder game\n\n")
in
if (Array.length arguments != 1) then (show_help (); exit 1);
let height = 1 + int_of_string arguments.(0) in
let w = 5 in
let game = pg_create (5 * height - 5) in
for i = 0 to height-1 do
let start_idx = i * w - 2 in
let p = (i + 1) * 3 + 2 in
let start_pl = i mod 2 in
let o = 1 - start_pl in
let mx = i = height - 1 in
let mfx = i = height - 2 in
let mn = i = 0 in
let prnt j pr pl succs =
let j' = start_idx + j in
pg_set_priority game j' pr;
pg_set_owner game j' (plr_benefits (start_pl + pl));
pg_set_desc game j' (Some (nd_show (start_idx + j)));
List.iter (fun w -> pg_add_edge game j' (w+start_idx)) succs
in
if not mn then (
prnt 0 o 1 [3-w;1];
prnt 1 o 0 (if mx then [0] else [0;2]);
);
if not mx then (
prnt 2 p 1 [w+1;3];
prnt 3 (p - 1) 0 ((if mn then [] else [3-w])@(if mfx then [] else [w+3])@[4]);
prnt 4 (p - 2) 1 (if mx then [3] else [3;w+1])
)
done;
game;;
let register _ = Generatorregistry.register_generator generator_game_func "recursiveladder" "Recursive Ladder Game";;
| null | https://raw.githubusercontent.com/tcsprojects/pgsolver/b0c31a8b367c405baed961385ad645d52f648325/src/generators/recursiveladder.ml | ocaml | open Paritygame;;
let generator_game_func arguments =
let show_help _ =
print_string (Info.get_title "Recursive Ladder Game Generator");
print_string ("Usage: recursiveladder n\n\n" ^
" where n = n-th recursive ladder game\n\n")
in
if (Array.length arguments != 1) then (show_help (); exit 1);
let height = 1 + int_of_string arguments.(0) in
let w = 5 in
let game = pg_create (5 * height - 5) in
for i = 0 to height-1 do
let start_idx = i * w - 2 in
let p = (i + 1) * 3 + 2 in
let start_pl = i mod 2 in
let o = 1 - start_pl in
let mx = i = height - 1 in
let mfx = i = height - 2 in
let mn = i = 0 in
let prnt j pr pl succs =
let j' = start_idx + j in
pg_set_priority game j' pr;
pg_set_owner game j' (plr_benefits (start_pl + pl));
pg_set_desc game j' (Some (nd_show (start_idx + j)));
List.iter (fun w -> pg_add_edge game j' (w+start_idx)) succs
in
if not mn then (
prnt 0 o 1 [3-w;1];
prnt 1 o 0 (if mx then [0] else [0;2]);
);
if not mx then (
prnt 2 p 1 [w+1;3];
prnt 3 (p - 1) 0 ((if mn then [] else [3-w])@(if mfx then [] else [w+3])@[4]);
prnt 4 (p - 2) 1 (if mx then [3] else [3;w+1])
)
done;
game;;
let register _ = Generatorregistry.register_generator generator_game_func "recursiveladder" "Recursive Ladder Game";;
| |
663566f68f2fcbb79de060f8802d2267f97b0bc2bbb6226b8e355d1cc13cab5b | atgreen/lisp-openshift | util.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : DOCUMENTATION - TEMPLATE ; Base : 10 -*-
$ Header : /usr / local / cvsrep / documentation - template / util.lisp , v 1.14 2010/08/05 19:24:27 edi Exp $
Copyright ( c ) 2006 - 2010 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :documentation-template)
For the purpose of this file , an " entry " is a list of four or five
;;; symbols - a name, a keyword for the kind of the entry, a lambda
;;; list (for functions and macros), a documentation string, and
optionally a list of specializers
#+(or :sbcl :allegro)
(defun function-lambda-list (function)
"Returns the lambda list of the function designator FUNCTION."
#+:sbcl
(sb-introspect:function-lambda-list function)
#+:allegro
(excl:arglist function))
(defun symbol-constant-p (symbol)
"Returns true if SYMBOL is a constant."
#+:lispworks (sys:symbol-constant-p symbol)
#-:lispworks (constantp symbol))
(defun declared-special-p (symbol)
"Returns true if SYMBOL is declared special."
#+:lispworks (sys:declared-special-p symbol)
#+:sbcl (eql :special (sb-int:info :variable :kind symbol))
#+:allegro (eq (sys:variable-information symbol) :special))
(defun constant-doc-entry (symbol)
"Returns a list with one entry for a constant if SYMBOL names a
constant."
(when (symbol-constant-p symbol)
(list (list symbol :constant nil (documentation symbol 'variable)))))
(defun special-var-doc-entry (symbol)
"Returns a list with one entry for a special variable if SYMBOL
names a special variable."
skip constants because SYS : DECLARED - SPECIAL - P is true for them as
;; well
(when (and (not (symbol-constant-p symbol))
(declared-special-p symbol))
(list (list symbol :special-var nil (documentation symbol 'variable)))))
(defun class-doc-entry (symbol)
"Returns a list with one entry for a class if SYMBOL names a
class."
(when (find-class symbol nil)
(list (list symbol :class nil (documentation symbol 'type)))))
(defun macro-doc-entry (symbol)
"Returns a list with one entry for a macro if SYMBOL names a
macro."
(when (and (fboundp symbol)
(macro-function symbol))
(list (list symbol :macro (function-lambda-list symbol)
(documentation symbol 'function)))))
#+:sbcl
(defgeneric %sbcl-simple-specializer (specializer)
(:documentation "Returns a simple representation of
SPECIALIZER.")
(:method (specializer)
(class-name specializer))
(:method ((specializer eql-specializer))
`(eql ,(eql-specializer-object specializer))))
(defun simplify-specializer (specializer)
"Converts specializers which are classes to their names, leaves
the rest alone."
(or (ignore-errors #+(or :lispworks :allegro) (class-name specializer)
#+:sbcl (%sbcl-simple-specializer specializer))
specializer))
(defun generic-function-doc-entry (name)
"Returns a list with one entry for a generic function and one
entry for each of its methods if NAME names a generic function."
(when (and (fboundp name)
(typep (fdefinition name) 'standard-generic-function))
(let* ((lambda-list (function-lambda-list name))
(generic-function-documentation (documentation name 'function))
(generic-function-entry
(list name :generic-function lambda-list
generic-function-documentation)))
(cond ((and generic-function-documentation *maybe-skip-methods-p*)
(list generic-function-entry))
(t (cons generic-function-entry
(loop for method in (generic-function-methods (fdefinition name))
collect (list name :method lambda-list
(documentation method t)
(mapcar #'simplify-specializer (method-specializers method))
(method-qualifiers method)))))))))
(defun function-doc-entry (name)
"Returns a list with one entry for a function if NAME names a
plain old function."
(when (and (fboundp name)
;; no macros
(or (listp name)
(not (macro-function name)))
;; no generic functions
(not (typep (fdefinition name) 'standard-generic-function)))
(list (list name :function (function-lambda-list name)
(documentation name 'function)))))
(defun doc-entries (symbol)
"Returns a list of all possible entries for the symbol SYMBOL
and for the corresponding SETF function name."
(let ((setf-name `(setf ,symbol)))
`(,@(constant-doc-entry symbol)
,@(special-var-doc-entry symbol)
,@(class-doc-entry symbol)
,@(macro-doc-entry symbol)
,@(generic-function-doc-entry symbol)
,@(function-doc-entry symbol)
,@(generic-function-doc-entry setf-name)
,@(function-doc-entry setf-name))))
(defun doc-type-ordinal (type)
"Assigns ordinals to the different kinds of entries for sorting
purposes."
(ecase type
(:constant 0)
(:special-var 1)
(:class 2)
(:macro 3)
(:function 4)
(:generic-function 5)
(:method 6)))
(defun name= (name1 name2)
"Two function names are equal if they are EQUAL - this covers
symbols as well as general function names."
(equal name1 name2))
(defun name< (name1 name2)
"Comparison function used for sorting - symbols are \"smaller\"
then SETF names, otherwise sort alphabetically."
(or (and (consp name2)
(atom name1))
(and (consp name1)
(consp name2)
(string< (second name1) (second name2)))
(and (atom name1)
(atom name2)
(string< name1 name2))))
(defun doc-entry< (entry1 entry2)
"Comparions function used for sorting - sort by name and, if
the names are the same, by DOC-TYPE-ORDINAL."
(or (name< (first entry1) (first entry2))
(and (name= (first entry1) (first entry2))
(< (doc-type-ordinal (second entry1))
(doc-type-ordinal (second entry2))))))
(defun collect-all-doc-entries (package)
"Returns a sorted list of entries for all exported symbols of
PACKAGE."
(let (result)
(do-external-symbols (symbol package (sort result #'doc-entry<))
(setq result (nconc (doc-entries symbol) result)))))
| null | https://raw.githubusercontent.com/atgreen/lisp-openshift/40235286bd3c6a61cab9f5af883d9ed9befba849/quicklisp/dists/quicklisp/software/documentation-template-0.4.2/util.lisp | lisp | Syntax : COMMON - LISP ; Package : DOCUMENTATION - TEMPLATE ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
symbols - a name, a keyword for the kind of the entry, a lambda
list (for functions and macros), a documentation string, and
well
no macros
no generic functions | $ Header : /usr / local / cvsrep / documentation - template / util.lisp , v 1.14 2010/08/05 19:24:27 edi Exp $
Copyright ( c ) 2006 - 2010 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package :documentation-template)
For the purpose of this file , an " entry " is a list of four or five
optionally a list of specializers
#+(or :sbcl :allegro)
(defun function-lambda-list (function)
"Returns the lambda list of the function designator FUNCTION."
#+:sbcl
(sb-introspect:function-lambda-list function)
#+:allegro
(excl:arglist function))
(defun symbol-constant-p (symbol)
"Returns true if SYMBOL is a constant."
#+:lispworks (sys:symbol-constant-p symbol)
#-:lispworks (constantp symbol))
(defun declared-special-p (symbol)
"Returns true if SYMBOL is declared special."
#+:lispworks (sys:declared-special-p symbol)
#+:sbcl (eql :special (sb-int:info :variable :kind symbol))
#+:allegro (eq (sys:variable-information symbol) :special))
(defun constant-doc-entry (symbol)
"Returns a list with one entry for a constant if SYMBOL names a
constant."
(when (symbol-constant-p symbol)
(list (list symbol :constant nil (documentation symbol 'variable)))))
(defun special-var-doc-entry (symbol)
"Returns a list with one entry for a special variable if SYMBOL
names a special variable."
skip constants because SYS : DECLARED - SPECIAL - P is true for them as
(when (and (not (symbol-constant-p symbol))
(declared-special-p symbol))
(list (list symbol :special-var nil (documentation symbol 'variable)))))
(defun class-doc-entry (symbol)
"Returns a list with one entry for a class if SYMBOL names a
class."
(when (find-class symbol nil)
(list (list symbol :class nil (documentation symbol 'type)))))
(defun macro-doc-entry (symbol)
"Returns a list with one entry for a macro if SYMBOL names a
macro."
(when (and (fboundp symbol)
(macro-function symbol))
(list (list symbol :macro (function-lambda-list symbol)
(documentation symbol 'function)))))
#+:sbcl
(defgeneric %sbcl-simple-specializer (specializer)
(:documentation "Returns a simple representation of
SPECIALIZER.")
(:method (specializer)
(class-name specializer))
(:method ((specializer eql-specializer))
`(eql ,(eql-specializer-object specializer))))
(defun simplify-specializer (specializer)
"Converts specializers which are classes to their names, leaves
the rest alone."
(or (ignore-errors #+(or :lispworks :allegro) (class-name specializer)
#+:sbcl (%sbcl-simple-specializer specializer))
specializer))
(defun generic-function-doc-entry (name)
"Returns a list with one entry for a generic function and one
entry for each of its methods if NAME names a generic function."
(when (and (fboundp name)
(typep (fdefinition name) 'standard-generic-function))
(let* ((lambda-list (function-lambda-list name))
(generic-function-documentation (documentation name 'function))
(generic-function-entry
(list name :generic-function lambda-list
generic-function-documentation)))
(cond ((and generic-function-documentation *maybe-skip-methods-p*)
(list generic-function-entry))
(t (cons generic-function-entry
(loop for method in (generic-function-methods (fdefinition name))
collect (list name :method lambda-list
(documentation method t)
(mapcar #'simplify-specializer (method-specializers method))
(method-qualifiers method)))))))))
(defun function-doc-entry (name)
"Returns a list with one entry for a function if NAME names a
plain old function."
(when (and (fboundp name)
(or (listp name)
(not (macro-function name)))
(not (typep (fdefinition name) 'standard-generic-function)))
(list (list name :function (function-lambda-list name)
(documentation name 'function)))))
(defun doc-entries (symbol)
"Returns a list of all possible entries for the symbol SYMBOL
and for the corresponding SETF function name."
(let ((setf-name `(setf ,symbol)))
`(,@(constant-doc-entry symbol)
,@(special-var-doc-entry symbol)
,@(class-doc-entry symbol)
,@(macro-doc-entry symbol)
,@(generic-function-doc-entry symbol)
,@(function-doc-entry symbol)
,@(generic-function-doc-entry setf-name)
,@(function-doc-entry setf-name))))
(defun doc-type-ordinal (type)
"Assigns ordinals to the different kinds of entries for sorting
purposes."
(ecase type
(:constant 0)
(:special-var 1)
(:class 2)
(:macro 3)
(:function 4)
(:generic-function 5)
(:method 6)))
(defun name= (name1 name2)
"Two function names are equal if they are EQUAL - this covers
symbols as well as general function names."
(equal name1 name2))
(defun name< (name1 name2)
"Comparison function used for sorting - symbols are \"smaller\"
then SETF names, otherwise sort alphabetically."
(or (and (consp name2)
(atom name1))
(and (consp name1)
(consp name2)
(string< (second name1) (second name2)))
(and (atom name1)
(atom name2)
(string< name1 name2))))
(defun doc-entry< (entry1 entry2)
"Comparions function used for sorting - sort by name and, if
the names are the same, by DOC-TYPE-ORDINAL."
(or (name< (first entry1) (first entry2))
(and (name= (first entry1) (first entry2))
(< (doc-type-ordinal (second entry1))
(doc-type-ordinal (second entry2))))))
(defun collect-all-doc-entries (package)
"Returns a sorted list of entries for all exported symbols of
PACKAGE."
(let (result)
(do-external-symbols (symbol package (sort result #'doc-entry<))
(setq result (nconc (doc-entries symbol) result)))))
|
3c02420c0ee8aa6c9db754ce1dc8327472953dd3f87d7273ae815953194d9706 | snapframework/cufp2011 | Util.hs | module Snap.Chat.Internal.Util
( seconds
) where
------------------------------------------------------------------------------
seconds :: Int -> Int
seconds n = n * ((10::Int)^(6::Int))
| null | https://raw.githubusercontent.com/snapframework/cufp2011/6519513ef80d561efc9846847860b50a19c7b9f6/src/Snap/Chat/Internal/Util.hs | haskell | ---------------------------------------------------------------------------- | module Snap.Chat.Internal.Util
( seconds
) where
seconds :: Int -> Int
seconds n = n * ((10::Int)^(6::Int))
|
d8d0a70edfcc22cf42cbaa338c3af95dcac72c0211c7266b5f2ea733ac8d93a3 | c4-project/c4f | function_rewriter.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
module type S = sig
val rewrite_all :
unit Fir.Function.t Common.C_named.t list
-> context:Context.t
-> unit Fir.Function.t Common.C_named.t list Or_error.t
end
type 'a local_rw_fun = 'a -> tid:int -> context:Context.t -> 'a Or_error.t
type 'a rw_fun = 'a -> 'a Or_error.t
module Make (Basic : sig
val rewrite_local_address : Fir.Address.t rw_fun
val rewrite_local_lvalue : Fir.Lvalue.t rw_fun
val rewrite_local_cid : Common.C_id.t local_rw_fun
val rewrite_global_address : Fir.Address.t rw_fun
val rewrite_global_lvalue : Fir.Lvalue.t rw_fun
end) =
struct
module Rewriter_with_thread (Ctx : sig
val thread : Thread.t
val context : Context.t
end) =
struct
let rewrite_lvalue_if_global : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Thread.when_global Ctx.thread ~over:Fir.Lvalue.variable_of
~f:Basic.rewrite_global_lvalue
let rewrite_address_if_global : Fir.Address.t -> Fir.Address.t Or_error.t
=
Thread.when_global Ctx.thread ~over:Fir.Address.variable_of
~f:Basic.rewrite_global_address
let rewrite_lvalue_if_local : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Thread.when_local Ctx.thread ~over:Fir.Lvalue.variable_of
~f:Basic.rewrite_local_lvalue
let rewrite_address_if_local : Fir.Address.t -> Fir.Address.t Or_error.t
=
Thread.when_local Ctx.thread ~over:Fir.Address.variable_of
~f:Basic.rewrite_local_address
let rewrite_id_if_local : Common.C_id.t -> Common.C_id.t Or_error.t =
Thread.when_local Ctx.thread ~over:Accessor.id
~f:(Basic.rewrite_local_cid ~context:Ctx.context ~tid:Ctx.thread.tid)
module C_stm_meta = Fir.Statement_traverse.With_meta (Unit)
let rewrite_ids : unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t
=
C_stm_meta.On_lvalues.With_errors.map_m
~f:
(Utils.Accessor.On_error.map Fir.Lvalue.variable_of
~f:rewrite_id_if_local )
(* When rewriting global lvalues (as part of a var-as-global run), we do
it _after_ address rewriting, as the address rewriting will
temporarily _increase_ the amount of indirection.
When rewriting local lvalues (as part of a var-as-parameter run), we
do it _before_ address rewriting, as the address rewriting will
temporarily _decrease_ the amount of indirection. *)
let rewrite_global_lvalues :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
C_stm_meta.On_lvalues.With_errors.map_m ~f:rewrite_lvalue_if_global
let rewrite_local_lvalues :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
C_stm_meta.On_lvalues.With_errors.map_m ~f:rewrite_lvalue_if_local
let rewrite_addresses :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
C_stm_meta.On_addresses.With_errors.map_m
~f:
Tx.Or_error.(
rewrite_address_if_local >=> rewrite_address_if_global)
let rewrite_statement :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
Tx.Or_error.(
rewrite_local_lvalues >=> rewrite_addresses
>=> rewrite_global_lvalues >=> rewrite_ids)
let rewrite_statements :
unit Fir.Statement.t list -> unit Fir.Statement.t list Or_error.t =
Tx.Or_error.combine_map ~f:rewrite_statement
let filter_by_scope :
(Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t
-> (Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t =
List.filter ~f:(fun (k, _) ->
Common.Litmus_id.is_in_local_scope k ~from:Ctx.thread.tid )
let expand_parameter ({c_id; c_type; _} : Var_map.Record.t) :
(Common.C_id.t * Fir.Type.t) Or_error.t =
Or_error.Let_syntax.(
let%map pty = Fir.Type.ref c_type in
(c_id, pty))
let expand_parameters :
(Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t
-> (Common.C_id.t, Fir.Type.t) List.Assoc.t Or_error.t =
Tx.Or_error.combine_map ~f:(fun (_, r) -> expand_parameter r)
let populate_parameters () :
(Common.C_id.t, Fir.Type.t) List.Assoc.t Or_error.t =
Ctx.context |> Context.var_map |> Var_map.param_mapped_vars
|> filter_by_scope |> expand_parameters
module F = Fir.Function.On (Or_error)
let rewrite : unit Fir.Function.t -> unit Fir.Function.t Or_error.t =
F.map_m
~parameters:(fun _ -> populate_parameters ())
~body_decls:(fun _ -> Ok [])
~body_stms:rewrite_statements
end
let rewrite (tid : int) (func : unit Fir.Function.t) ~(context : Context.t)
: unit Fir.Function.t Or_error.t =
let locals =
func |> Fir.Function.body_decls |> List.map ~f:fst
|> Set.of_list (module Common.C_id)
in
let module M = Rewriter_with_thread (struct
let thread = {Thread.tid; locals}
let context = context
end) in
M.rewrite func
let lookup_function (name : Common.C_id.t) ~(context : Context.t) :
Function_map.Record.t Or_error.t =
let fn =
(Context.aux context).@(Aux.function_map @> Accessor.Map.at name)
in
Result.of_option fn
~error:
(Error.create_s
[%message
"Could not find function in function map."
~(name : Common.C_id.t)] )
let rewrite_function_name (name : Common.C_id.t) ~(context : Context.t) :
Common.C_id.t Or_error.t =
Or_error.map
(lookup_function name ~context)
~f:(Accessor.get Function_map.Record.c_id)
let rewrite_named (tid : int) (fn : unit Fir.Function.t Common.C_named.t)
~(context : Context.t) :
unit Fir.Function.t Common.C_named.t Or_error.t =
Common.C_named.With_errors.bi_map_m fn
~left:(rewrite_function_name ~context)
~right:(rewrite tid ~context)
let rewrite_all (fs : unit Fir.Function.t Common.C_named.t list)
~(context : Context.t) :
unit Fir.Function.t Common.C_named.t list Or_error.t =
fs |> List.mapi ~f:(rewrite_named ~context) |> Or_error.combine_errors
end
module Vars_as_globals = Make (struct
let rewrite_global_address (addr : Fir.Address.t) :
Fir.Address.t Or_error.t =
let is_deref =
Accessor.exists Fir.Address.lvalue_of addr ~f:Fir.Lvalue.is_deref
in
let addr' =
if is_deref then addr
else
(* The added deref here will be removed in lvalue rewriting. *)
Ref
(Accessor.map Fir.Address.lvalue_of
~f:(Accessor.construct Fir.Lvalue.deref)
addr )
in
Ok addr'
let rewrite_global_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Fir.Lvalue.un_deref
let rewrite_local_address : Fir.Address.t -> Fir.Address.t Or_error.t =
Or_error.return
let rewrite_local_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Or_error.return
let rewrite_local_cid (cid : Common.C_id.t) ~(tid : int)
~(context : Context.t) : Common.C_id.t Or_error.t =
let vm = Context.var_map context in
Var_map.lookup_and_require_global vm ~id:(Common.Litmus_id.local tid cid)
end)
module Vars_as_parameters = Make (struct
let rewrite_global_address : Fir.Address.t -> Fir.Address.t Or_error.t =
Or_error.return
let rewrite_global_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Or_error.return
let rewrite_local_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
(* The added deref here will be removed in address rewriting if not
needed. *)
Fn.compose Or_error.return (Accessor.construct Fir.Lvalue.deref)
let rewrite_local_address : Fir.Address.t -> Fir.Address.t Or_error.t =
Fn.compose Or_error.return Fir.Address.normalise
let rewrite_local_cid (cid : Common.C_id.t) ~(tid : int)
~(context : Context.t) : Common.C_id.t Or_error.t =
let vm = Context.var_map context in
Var_map.lookup_and_require_param vm ~id:(Common.Litmus_id.local tid cid)
end)
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/delitmus/src/function_rewriter.ml | ocaml | When rewriting global lvalues (as part of a var-as-global run), we do
it _after_ address rewriting, as the address rewriting will
temporarily _increase_ the amount of indirection.
When rewriting local lvalues (as part of a var-as-parameter run), we
do it _before_ address rewriting, as the address rewriting will
temporarily _decrease_ the amount of indirection.
The added deref here will be removed in lvalue rewriting.
The added deref here will be removed in address rewriting if not
needed. | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
module type S = sig
val rewrite_all :
unit Fir.Function.t Common.C_named.t list
-> context:Context.t
-> unit Fir.Function.t Common.C_named.t list Or_error.t
end
type 'a local_rw_fun = 'a -> tid:int -> context:Context.t -> 'a Or_error.t
type 'a rw_fun = 'a -> 'a Or_error.t
module Make (Basic : sig
val rewrite_local_address : Fir.Address.t rw_fun
val rewrite_local_lvalue : Fir.Lvalue.t rw_fun
val rewrite_local_cid : Common.C_id.t local_rw_fun
val rewrite_global_address : Fir.Address.t rw_fun
val rewrite_global_lvalue : Fir.Lvalue.t rw_fun
end) =
struct
module Rewriter_with_thread (Ctx : sig
val thread : Thread.t
val context : Context.t
end) =
struct
let rewrite_lvalue_if_global : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Thread.when_global Ctx.thread ~over:Fir.Lvalue.variable_of
~f:Basic.rewrite_global_lvalue
let rewrite_address_if_global : Fir.Address.t -> Fir.Address.t Or_error.t
=
Thread.when_global Ctx.thread ~over:Fir.Address.variable_of
~f:Basic.rewrite_global_address
let rewrite_lvalue_if_local : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Thread.when_local Ctx.thread ~over:Fir.Lvalue.variable_of
~f:Basic.rewrite_local_lvalue
let rewrite_address_if_local : Fir.Address.t -> Fir.Address.t Or_error.t
=
Thread.when_local Ctx.thread ~over:Fir.Address.variable_of
~f:Basic.rewrite_local_address
let rewrite_id_if_local : Common.C_id.t -> Common.C_id.t Or_error.t =
Thread.when_local Ctx.thread ~over:Accessor.id
~f:(Basic.rewrite_local_cid ~context:Ctx.context ~tid:Ctx.thread.tid)
module C_stm_meta = Fir.Statement_traverse.With_meta (Unit)
let rewrite_ids : unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t
=
C_stm_meta.On_lvalues.With_errors.map_m
~f:
(Utils.Accessor.On_error.map Fir.Lvalue.variable_of
~f:rewrite_id_if_local )
let rewrite_global_lvalues :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
C_stm_meta.On_lvalues.With_errors.map_m ~f:rewrite_lvalue_if_global
let rewrite_local_lvalues :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
C_stm_meta.On_lvalues.With_errors.map_m ~f:rewrite_lvalue_if_local
let rewrite_addresses :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
C_stm_meta.On_addresses.With_errors.map_m
~f:
Tx.Or_error.(
rewrite_address_if_local >=> rewrite_address_if_global)
let rewrite_statement :
unit Fir.Statement.t -> unit Fir.Statement.t Or_error.t =
Tx.Or_error.(
rewrite_local_lvalues >=> rewrite_addresses
>=> rewrite_global_lvalues >=> rewrite_ids)
let rewrite_statements :
unit Fir.Statement.t list -> unit Fir.Statement.t list Or_error.t =
Tx.Or_error.combine_map ~f:rewrite_statement
let filter_by_scope :
(Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t
-> (Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t =
List.filter ~f:(fun (k, _) ->
Common.Litmus_id.is_in_local_scope k ~from:Ctx.thread.tid )
let expand_parameter ({c_id; c_type; _} : Var_map.Record.t) :
(Common.C_id.t * Fir.Type.t) Or_error.t =
Or_error.Let_syntax.(
let%map pty = Fir.Type.ref c_type in
(c_id, pty))
let expand_parameters :
(Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t
-> (Common.C_id.t, Fir.Type.t) List.Assoc.t Or_error.t =
Tx.Or_error.combine_map ~f:(fun (_, r) -> expand_parameter r)
let populate_parameters () :
(Common.C_id.t, Fir.Type.t) List.Assoc.t Or_error.t =
Ctx.context |> Context.var_map |> Var_map.param_mapped_vars
|> filter_by_scope |> expand_parameters
module F = Fir.Function.On (Or_error)
let rewrite : unit Fir.Function.t -> unit Fir.Function.t Or_error.t =
F.map_m
~parameters:(fun _ -> populate_parameters ())
~body_decls:(fun _ -> Ok [])
~body_stms:rewrite_statements
end
let rewrite (tid : int) (func : unit Fir.Function.t) ~(context : Context.t)
: unit Fir.Function.t Or_error.t =
let locals =
func |> Fir.Function.body_decls |> List.map ~f:fst
|> Set.of_list (module Common.C_id)
in
let module M = Rewriter_with_thread (struct
let thread = {Thread.tid; locals}
let context = context
end) in
M.rewrite func
let lookup_function (name : Common.C_id.t) ~(context : Context.t) :
Function_map.Record.t Or_error.t =
let fn =
(Context.aux context).@(Aux.function_map @> Accessor.Map.at name)
in
Result.of_option fn
~error:
(Error.create_s
[%message
"Could not find function in function map."
~(name : Common.C_id.t)] )
let rewrite_function_name (name : Common.C_id.t) ~(context : Context.t) :
Common.C_id.t Or_error.t =
Or_error.map
(lookup_function name ~context)
~f:(Accessor.get Function_map.Record.c_id)
let rewrite_named (tid : int) (fn : unit Fir.Function.t Common.C_named.t)
~(context : Context.t) :
unit Fir.Function.t Common.C_named.t Or_error.t =
Common.C_named.With_errors.bi_map_m fn
~left:(rewrite_function_name ~context)
~right:(rewrite tid ~context)
let rewrite_all (fs : unit Fir.Function.t Common.C_named.t list)
~(context : Context.t) :
unit Fir.Function.t Common.C_named.t list Or_error.t =
fs |> List.mapi ~f:(rewrite_named ~context) |> Or_error.combine_errors
end
module Vars_as_globals = Make (struct
let rewrite_global_address (addr : Fir.Address.t) :
Fir.Address.t Or_error.t =
let is_deref =
Accessor.exists Fir.Address.lvalue_of addr ~f:Fir.Lvalue.is_deref
in
let addr' =
if is_deref then addr
else
Ref
(Accessor.map Fir.Address.lvalue_of
~f:(Accessor.construct Fir.Lvalue.deref)
addr )
in
Ok addr'
let rewrite_global_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Fir.Lvalue.un_deref
let rewrite_local_address : Fir.Address.t -> Fir.Address.t Or_error.t =
Or_error.return
let rewrite_local_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Or_error.return
let rewrite_local_cid (cid : Common.C_id.t) ~(tid : int)
~(context : Context.t) : Common.C_id.t Or_error.t =
let vm = Context.var_map context in
Var_map.lookup_and_require_global vm ~id:(Common.Litmus_id.local tid cid)
end)
module Vars_as_parameters = Make (struct
let rewrite_global_address : Fir.Address.t -> Fir.Address.t Or_error.t =
Or_error.return
let rewrite_global_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Or_error.return
let rewrite_local_lvalue : Fir.Lvalue.t -> Fir.Lvalue.t Or_error.t =
Fn.compose Or_error.return (Accessor.construct Fir.Lvalue.deref)
let rewrite_local_address : Fir.Address.t -> Fir.Address.t Or_error.t =
Fn.compose Or_error.return Fir.Address.normalise
let rewrite_local_cid (cid : Common.C_id.t) ~(tid : int)
~(context : Context.t) : Common.C_id.t Or_error.t =
let vm = Context.var_map context in
Var_map.lookup_and_require_param vm ~id:(Common.Litmus_id.local tid cid)
end)
|
f35559cacbbc37bba5097b91fbdf6f5e8dc2be47d6d5ddd5d26f548c3a16e9d3 | janestreet/memtrace_viewer_with_deps | cst.mli | (** Concrete syntax tree of expectations and actual outputs *)
(** These types represent the contents of an [%expect] node or of the actual output. We
keep information about the original layout so that we can give an corrected
expectation that follows the original formatting.
In the following names, blank means ' ' or '\t', while space means blank or newline.
*)
open! Base
open Import
module Line : sig
type 'a not_blank =
{ trailing_blanks : string (** regexp: "[ \t]*" *)
; orig : string
(** Original contents of the line without the trailing blanks or indentation.
regexp: "[^\n]*[^ \t\n]" *)
; data : 'a
(** Data associated to the line. *)
}
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_not_blank :
('a -> Ppx_sexp_conv_lib.Sexp.t) ->
'a not_blank -> Ppx_sexp_conv_lib.Sexp.t
val compare_not_blank :
('a -> 'a -> int) -> 'a not_blank -> 'a not_blank -> int
val equal_not_blank :
('a -> 'a -> bool) -> 'a not_blank -> 'a not_blank -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
type 'a t =
| Blank of string (** regexp: "[ \t]*" *)
| Not_blank of 'a not_blank
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_t :
('a -> Ppx_sexp_conv_lib.Sexp.t) -> 'a t -> Ppx_sexp_conv_lib.Sexp.t
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
val invariant : ('a -> unit) -> 'a t -> unit
(** The callback receive the [orig] and [data] fields *)
val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t
(** Delete trailing blanks (everything for blank lines) *)
val strip : 'a t -> 'a t
val data : 'a t -> blank:'a -> 'a
end
* Single line represent [ % expect ] nodes with data on the first line but not on the
subsequent ones .
For instance :
{ [
[ % expect " blah " ] ;
[ % expect { | blah
| } ]
] }
subsequent ones.
For instance:
{[
[%expect " blah "];
[%expect {| blah
|}]
]}
*)
type 'a single_line =
{ leading_blanks : string (** regexp: "[ \t]*" *)
; trailing_spaces : string (** regexp: "[ \t\n]*" *)
; orig : string (** regexp: "[^ \t\n]([^\n]*[^ \t\n])?" *)
; data : 'a
}
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_single_line :
('a -> Ppx_sexp_conv_lib.Sexp.t) ->
'a single_line -> Ppx_sexp_conv_lib.Sexp.t
val compare_single_line :
('a -> 'a -> int) -> 'a single_line -> 'a single_line -> int
val equal_single_line :
('a -> 'a -> bool) -> 'a single_line -> 'a single_line -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
* Any [ % expect ] node with one or more newlines and at least one non - blank line .
This also include the case with exactly one non - blank line such as :
{ [
[ % expect { |
blah
| } ]
] }
This is to preserve this formatting in case the correction is multi - line .
[ leading_spaces ] contains everything until the first non - blank line , while
[ trailing_spaces ] is either :
- trailing blanks on the last line if of the form :
{ [
[ % expect { |
abc
def | } ]
] }
- all trailing spaces from the newline character ( inclusive ) on the last non - blank
line to the end if of the form :
{ [
[ % expect { |
abc
def
| } ]
] }
This also include the case with exactly one non-blank line such as:
{[
[%expect {|
blah
|}]
]}
This is to preserve this formatting in case the correction is multi-line.
[leading_spaces] contains everything until the first non-blank line, while
[trailing_spaces] is either:
- trailing blanks on the last line if of the form:
{[
[%expect {|
abc
def |}]
]}
- all trailing spaces from the newline character (inclusive) on the last non-blank
line to the end if of the form:
{[
[%expect {|
abc
def
|}]
]}
*)
type 'a multi_lines =
{ leading_spaces : string (** regexp: "\([ \t]*\n\)*" *)
* regexp : " [ \t ] * " or " \(\n [ \t]*\ ) * "
; indentation : string (** regexp: "[ \t]*" *)
; lines : 'a Line.t list (** regexp: not_blank (.* not_blank)? *)
}
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_multi_lines :
('a -> Ppx_sexp_conv_lib.Sexp.t) ->
'a multi_lines -> Ppx_sexp_conv_lib.Sexp.t
val compare_multi_lines :
('a -> 'a -> int) -> 'a multi_lines -> 'a multi_lines -> int
val equal_multi_lines :
('a -> 'a -> bool) -> 'a multi_lines -> 'a multi_lines -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
type 'a t =
| Empty of string (** regexp: "[ \t\n]*" *)
| Single_line of 'a single_line
| Multi_lines of 'a multi_lines
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_t :
('a -> Ppx_sexp_conv_lib.Sexp.t) -> 'a t -> Ppx_sexp_conv_lib.Sexp.t
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
val invariant : ('a -> unit) -> 'a t -> unit
val empty : 'a t
val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t
val data : 'a t -> blank:'a -> 'a list
val strip : 'a t -> 'a t
val to_string : _ t -> string
(** For single line expectation, leading blanks and trailing spaces are dropped. *)
val to_lines : 'a t -> 'a Line.t list
(** Remove blank lines at the beginning and end of the list. *)
val trim_lines : 'a Line.t list -> 'a Line.t list
(** Given a contents [t] and a list of [lines], try to produce a new contents containing
[lines] but with the same formating as [t].
[default_indentation] is the indentation to use in case we ignore [t]'s indentation
(for instance if [t] is [Single_line] or [Empty]). *)
val reconcile
: 'a t
-> lines : 'a Line.t list
-> default_indentation : int
-> pad_single_line : bool
-> 'a t
(** Compuute the longest indentation of a list of lines and trim it from every line. It
returns the found indentation and the list of trimmed lines. *)
val extract_indentation : 'a Line.t list -> string * 'a Line.t list
(** All the [.orig] fields of [Line.t] or [single_line] values, using [""] for blank
lines. *)
val stripped_original_lines : _ t -> string list
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/ppx_expect/matcher/cst.mli | ocaml | * Concrete syntax tree of expectations and actual outputs
* These types represent the contents of an [%expect] node or of the actual output. We
keep information about the original layout so that we can give an corrected
expectation that follows the original formatting.
In the following names, blank means ' ' or '\t', while space means blank or newline.
* regexp: "[ \t]*"
* Original contents of the line without the trailing blanks or indentation.
regexp: "[^\n]*[^ \t\n]"
* Data associated to the line.
* regexp: "[ \t]*"
* The callback receive the [orig] and [data] fields
* Delete trailing blanks (everything for blank lines)
* regexp: "[ \t]*"
* regexp: "[ \t\n]*"
* regexp: "[^ \t\n]([^\n]*[^ \t\n])?"
* regexp: "\([ \t]*\n\)*"
* regexp: "[ \t]*"
* regexp: not_blank (.* not_blank)?
* regexp: "[ \t\n]*"
* For single line expectation, leading blanks and trailing spaces are dropped.
* Remove blank lines at the beginning and end of the list.
* Given a contents [t] and a list of [lines], try to produce a new contents containing
[lines] but with the same formating as [t].
[default_indentation] is the indentation to use in case we ignore [t]'s indentation
(for instance if [t] is [Single_line] or [Empty]).
* Compuute the longest indentation of a list of lines and trim it from every line. It
returns the found indentation and the list of trimmed lines.
* All the [.orig] fields of [Line.t] or [single_line] values, using [""] for blank
lines. |
open! Base
open Import
module Line : sig
type 'a not_blank =
; orig : string
; data : 'a
}
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_not_blank :
('a -> Ppx_sexp_conv_lib.Sexp.t) ->
'a not_blank -> Ppx_sexp_conv_lib.Sexp.t
val compare_not_blank :
('a -> 'a -> int) -> 'a not_blank -> 'a not_blank -> int
val equal_not_blank :
('a -> 'a -> bool) -> 'a not_blank -> 'a not_blank -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
type 'a t =
| Not_blank of 'a not_blank
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_t :
('a -> Ppx_sexp_conv_lib.Sexp.t) -> 'a t -> Ppx_sexp_conv_lib.Sexp.t
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
val invariant : ('a -> unit) -> 'a t -> unit
val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t
val strip : 'a t -> 'a t
val data : 'a t -> blank:'a -> 'a
end
* Single line represent [ % expect ] nodes with data on the first line but not on the
subsequent ones .
For instance :
{ [
[ % expect " blah " ] ;
[ % expect { | blah
| } ]
] }
subsequent ones.
For instance:
{[
[%expect " blah "];
[%expect {| blah
|}]
]}
*)
type 'a single_line =
; data : 'a
}
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_single_line :
('a -> Ppx_sexp_conv_lib.Sexp.t) ->
'a single_line -> Ppx_sexp_conv_lib.Sexp.t
val compare_single_line :
('a -> 'a -> int) -> 'a single_line -> 'a single_line -> int
val equal_single_line :
('a -> 'a -> bool) -> 'a single_line -> 'a single_line -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
* Any [ % expect ] node with one or more newlines and at least one non - blank line .
This also include the case with exactly one non - blank line such as :
{ [
[ % expect { |
blah
| } ]
] }
This is to preserve this formatting in case the correction is multi - line .
[ leading_spaces ] contains everything until the first non - blank line , while
[ trailing_spaces ] is either :
- trailing blanks on the last line if of the form :
{ [
[ % expect { |
abc
def | } ]
] }
- all trailing spaces from the newline character ( inclusive ) on the last non - blank
line to the end if of the form :
{ [
[ % expect { |
abc
def
| } ]
] }
This also include the case with exactly one non-blank line such as:
{[
[%expect {|
blah
|}]
]}
This is to preserve this formatting in case the correction is multi-line.
[leading_spaces] contains everything until the first non-blank line, while
[trailing_spaces] is either:
- trailing blanks on the last line if of the form:
{[
[%expect {|
abc
def |}]
]}
- all trailing spaces from the newline character (inclusive) on the last non-blank
line to the end if of the form:
{[
[%expect {|
abc
def
|}]
]}
*)
type 'a multi_lines =
* regexp : " [ \t ] * " or " \(\n [ \t]*\ ) * "
}
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_multi_lines :
('a -> Ppx_sexp_conv_lib.Sexp.t) ->
'a multi_lines -> Ppx_sexp_conv_lib.Sexp.t
val compare_multi_lines :
('a -> 'a -> int) -> 'a multi_lines -> 'a multi_lines -> int
val equal_multi_lines :
('a -> 'a -> bool) -> 'a multi_lines -> 'a multi_lines -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
type 'a t =
| Single_line of 'a single_line
| Multi_lines of 'a multi_lines
[@@deriving_inline sexp_of, compare, equal]
include
sig
[@@@ocaml.warning "-32"]
val sexp_of_t :
('a -> Ppx_sexp_conv_lib.Sexp.t) -> 'a t -> Ppx_sexp_conv_lib.Sexp.t
val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int
val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool
end[@@ocaml.doc "@inline"]
[@@@end]
val invariant : ('a -> unit) -> 'a t -> unit
val empty : 'a t
val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t
val data : 'a t -> blank:'a -> 'a list
val strip : 'a t -> 'a t
val to_string : _ t -> string
val to_lines : 'a t -> 'a Line.t list
val trim_lines : 'a Line.t list -> 'a Line.t list
val reconcile
: 'a t
-> lines : 'a Line.t list
-> default_indentation : int
-> pad_single_line : bool
-> 'a t
val extract_indentation : 'a Line.t list -> string * 'a Line.t list
val stripped_original_lines : _ t -> string list
|
8cfd2d6fa169de2f2ce41b9686f8c8bf1a5dd99b6e4085e007ed236b680f491d | dvcrn/proton | core.cljs | (ns proton.layers.lang.sass.core
(:require [proton.lib.mode :as mode]
[proton.lib.helpers :refer [console!]]
[proton.layers.core.actions :as actions])
(:use [proton.layers.base :only [init-layer! get-packages init-package register-layer-dependencies]]))
(def sass-modes
{:sass-major-mode {:atom-scope "source.sass" :atom-grammars "Sass"}
:scss-major-mode {:atom-scope "source.css.scss" :atom-grammars "SCSS"}})
(defmethod get-packages :lang/sass []
[:language-sass
:atom-css-comb
:css-snippets
:pigments
:autocomplete-sass])
(defmethod init-layer! :lang/sass []
(console! "init" :lang/sass)
(register-layer-dependencies :tools/linter
[:linter-sass-lint])
(doall (map #(mode/define-mode (key %) (val %)) sass-modes)))
(defmethod init-package [:lang/sass :atom-css-comb] []
(mode/define-package-mode :atom-css-comb
{:mode-keybindings
{:f {:category "format"
:c {:action "css-comb:comb" :target actions/get-active-editor :title "css comb"}}}})
(mode/link-modes :scss-major-mode (mode/package-mode-name :atom-css-comb))
(mode/link-modes :sass-major-mode (mode/package-mode-name :atom-css-comb)))
| null | https://raw.githubusercontent.com/dvcrn/proton/427d83ffdb61d84a04e3d30032b792a9cfbfc53f/src/cljs/proton/layers/lang/sass/core.cljs | clojure | (ns proton.layers.lang.sass.core
(:require [proton.lib.mode :as mode]
[proton.lib.helpers :refer [console!]]
[proton.layers.core.actions :as actions])
(:use [proton.layers.base :only [init-layer! get-packages init-package register-layer-dependencies]]))
(def sass-modes
{:sass-major-mode {:atom-scope "source.sass" :atom-grammars "Sass"}
:scss-major-mode {:atom-scope "source.css.scss" :atom-grammars "SCSS"}})
(defmethod get-packages :lang/sass []
[:language-sass
:atom-css-comb
:css-snippets
:pigments
:autocomplete-sass])
(defmethod init-layer! :lang/sass []
(console! "init" :lang/sass)
(register-layer-dependencies :tools/linter
[:linter-sass-lint])
(doall (map #(mode/define-mode (key %) (val %)) sass-modes)))
(defmethod init-package [:lang/sass :atom-css-comb] []
(mode/define-package-mode :atom-css-comb
{:mode-keybindings
{:f {:category "format"
:c {:action "css-comb:comb" :target actions/get-active-editor :title "css comb"}}}})
(mode/link-modes :scss-major-mode (mode/package-mode-name :atom-css-comb))
(mode/link-modes :sass-major-mode (mode/package-mode-name :atom-css-comb)))
| |
726f92e90645bbdb1632c707d854fdd2bea0def946bd2d14723bac169cf39ab0 | headwinds/reagent-reframe-material-ui | loggers.cljc | (ns re-frame.loggers
(:require
[clojure.set :refer [difference]]
#?@(:clj [[clojure.string :as str]
[clojure.tools.logging :as log]])))
#?(:clj (defn log [level & args]
(log/log level (if (= 1 (count args))
(first args)
(str/join " " args)))))
;; XXX should loggers be put in the registrar ??
(def ^:private loggers
"Holds the current set of logging functions.
By default, re-frame uses the functions provided by js/console.
Use `set-loggers!` to change these defaults
"
(atom #?(:cljs {:log (js/console.log.bind js/console)
:warn (js/console.warn.bind js/console)
:error (js/console.error.bind js/console)
console.group does not exist < IE 11
(js/console.group.bind js/console)
(js/console.log.bind js/console))
console.groupEnd does not exist < IE 11
(js/console.groupEnd.bind js/console)
#())})
;; clojure versions
#?(:clj {:log (partial log :info)
:warn (partial log :warn)
:error (partial log :error)
:group (partial log :info)
:groupEnd #()})))
(defn console
[level & args]
(assert (contains? @loggers level) (str "re-frame: log called with unknown level: " level))
(apply (level @loggers) args))
(defn set-loggers!
"Change the set (or a subset) of logging functions used by re-frame.
`new-loggers` should be a map with the same keys as `loggers` (above)"
[new-loggers]
(assert (empty? (difference (set (keys new-loggers)) (-> @loggers keys set))) "Unknown keys in new-loggers")
(swap! loggers merge new-loggers))
(defn get-loggers
"Get the current logging functions used by re-frame."
[]
@loggers)
| null | https://raw.githubusercontent.com/headwinds/reagent-reframe-material-ui/8a6fba82a026cfedca38491becac85751be9a9d4/resources/public/js/out/re_frame/loggers.cljc | clojure | XXX should loggers be put in the registrar ??
clojure versions | (ns re-frame.loggers
(:require
[clojure.set :refer [difference]]
#?@(:clj [[clojure.string :as str]
[clojure.tools.logging :as log]])))
#?(:clj (defn log [level & args]
(log/log level (if (= 1 (count args))
(first args)
(str/join " " args)))))
(def ^:private loggers
"Holds the current set of logging functions.
By default, re-frame uses the functions provided by js/console.
Use `set-loggers!` to change these defaults
"
(atom #?(:cljs {:log (js/console.log.bind js/console)
:warn (js/console.warn.bind js/console)
:error (js/console.error.bind js/console)
console.group does not exist < IE 11
(js/console.group.bind js/console)
(js/console.log.bind js/console))
console.groupEnd does not exist < IE 11
(js/console.groupEnd.bind js/console)
#())})
#?(:clj {:log (partial log :info)
:warn (partial log :warn)
:error (partial log :error)
:group (partial log :info)
:groupEnd #()})))
(defn console
[level & args]
(assert (contains? @loggers level) (str "re-frame: log called with unknown level: " level))
(apply (level @loggers) args))
(defn set-loggers!
"Change the set (or a subset) of logging functions used by re-frame.
`new-loggers` should be a map with the same keys as `loggers` (above)"
[new-loggers]
(assert (empty? (difference (set (keys new-loggers)) (-> @loggers keys set))) "Unknown keys in new-loggers")
(swap! loggers merge new-loggers))
(defn get-loggers
"Get the current logging functions used by re-frame."
[]
@loggers)
|
0f9d029faa0f6c799593619b9de4e44c6249a5c7f4aff6f6f5ba7fce0185dad7 | cedlemo/OCaml-GI-ctypes-bindings-generator | Event_box.ml | open Ctypes
open Foreign
type t = unit ptr
let t_typ : t typ = ptr void
let create =
foreign "gtk_event_box_new" (void @-> returning (ptr Widget.t_typ))
let get_above_child =
foreign "gtk_event_box_get_above_child" (t_typ @-> returning (bool))
let get_visible_window =
foreign "gtk_event_box_get_visible_window" (t_typ @-> returning (bool))
let set_above_child =
foreign "gtk_event_box_set_above_child" (t_typ @-> bool @-> returning (void))
let set_visible_window =
foreign "gtk_event_box_set_visible_window" (t_typ @-> bool @-> returning (void))
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Event_box.ml | ocaml | open Ctypes
open Foreign
type t = unit ptr
let t_typ : t typ = ptr void
let create =
foreign "gtk_event_box_new" (void @-> returning (ptr Widget.t_typ))
let get_above_child =
foreign "gtk_event_box_get_above_child" (t_typ @-> returning (bool))
let get_visible_window =
foreign "gtk_event_box_get_visible_window" (t_typ @-> returning (bool))
let set_above_child =
foreign "gtk_event_box_set_above_child" (t_typ @-> bool @-> returning (void))
let set_visible_window =
foreign "gtk_event_box_set_visible_window" (t_typ @-> bool @-> returning (void))
| |
b44c4018895349361de4aa8fd766403dde5f6b850f7ae88f9588b0aaa2685cfa | goncalotomas/FMKe | gen_fmke_kv_driver.erl | This module documents the callbacks that an FMKE driver for a Key - Value Store must implement .
%%
%% A brief explanation about FMKe adapters and drivers:
%%
An adapter is an Erlang module that implements the complete FMKe callback set , but that is able to make assumptions
%% about the data model, connection pool or any other configurable parameter. Adapters don't communicate directly with
%% client libraries for databases, but instead do it through drivers.
%%
%% A driver is a simple wrapper over a database's client library that exposes a common interface to all databases.
%% When implementing a driver it is necessary to implement additional logic required to maintain correct application
%% state, such as keeping track of previously read values within a transaction. Failure to implement the additional
%% logic may result in anomalies which will should be documented. The performance to correctness trade-off is common
%% in these types of storage systems, and the documentation of the presented anomalies along with performance values
%% is paramount.
%%
%% Since adapters do not make assumptions about the capabilities of the database, the drivers will need to export
callbacks related to transactions ( e.g. start_transaction/1 , commit_transaction/1 ) . These functions are expected to
%% return opaque state that is passed in to further operations, meaning that you can add contextual information by
%% returning {ok, term()}, or just {ok, []} if there is no need for context in order to perform the operations.
%%
%% Drivers might also need to set up additional components and state for themselves, which is why the start/0
%% hooks exist. In these functions you may open a pool of connections to the database (but for that purpose you can
%% already use the fmke_db_conn_manager module), create an ETS table for caching results, etc.
%% Conversely, the stop/0 function will allow you to terminate gracefully and perform any teardown you feel necessary.
%%
%% The get and put functions that drivers need to implement contain extra parameters in order to give operation context
%% to the drivers. This is to avoid all possible overhead from using a generic approach (for instance, having to derive
%% which entity is being obtained from the key passed in get/3, if you used separate buckets in the database for each
%% one) as well as trying to provide optimal compatibility with other storage systems that may require extra context to
%% perform operations.
-module(gen_fmke_kv_driver).
-include("fmke.hrl").
-type value() :: term().
-type context() :: term().
-type options() :: list({atom(), term()}).
-type txn_result() :: ok | {error, term()}.
% -type data_model() :: nested | non_nested.
%% ---------------------------------------------------------------------------------------------------------------------
%% Setup and teardown callbacks
%% ---------------------------------------------------------------------------------------------------------------------
%% Startup hook that provides information about whether the current benchmark execution is using a normalized or nested
%% data layout. It is the driver's responsability to implement the logic for both data layouts, although the code should
%% not change significantly between them. (See example below)
A typical way of storing objects in CRDT databases would be to nest every field inside a top level record , which has
so far proved to have worse performance , since each CRDT state size will increase over multiple operations .
%% Furthermore, application records such as patients will need to store their associated prescriptions, which are
separate entities / records , further increasing CRDT state size . One way to bypass this is to store a reference to the
%% prescription key inside the patient, and we consider this to be a "normalized" (non-nested) data layout.
%% Implementing a driver may be done for a single data layout, ignoring the other completely. When test executions are
%% run, only valid data model implementations are considered for performance results.
% -callback start(DataModel::data_model()) -> {error, term()} | {ok, pid()}.
Teardown hook , called when the application is stopped .
% -callback stop() -> ok.
%% ---------------------------------------------------------------------------------------------------------------------
Transactional support callbacks
%% ---------------------------------------------------------------------------------------------------------------------
%% Starts a transaction while providing some context of the type of operations that are going to be performed.
%% A proplist of options (Options) is passed in, with the following values considered valid options:
%% {entity, Entity :: entity()} ->
The following operations that are going to be performed in this transaction only concern one entity , Entity .
%%
Returns any erlang term containing the state that is required by the driver to execute each operation related with a
transaction . It is common for the returned state to include a Pid that contains a connection to the database and
possibly identifier(s ) for the transaction . Any erlang term is considered valid and will be passed in to subsequent
%% operations related to the same transaction.
-callback start_transaction(Options::options()) -> {ok, OperationContext::context()}.
%% Signals the end of a transaction, passing in the current operation context as well as a list of options that
%% currently serves no purpose. A typical implementation of commit_transaction includes calling commit_transaction on
client library ( if supported ) and returning the Pid to the connection pool .
%%
%% See some implementations in the fmke_db_adapter_driver_antidote.erl and fmke_db_adapter_driver_riak.erl modules.
-callback commit_transaction(OperationContext::context(), Options::options()) -> Result::txn_result().
%% ---------------------------------------------------------------------------------------------------------------------
%% Key value callbacks
%% ---------------------------------------------------------------------------------------------------------------------
get/2 - Fetches a list of keys from the database .
%% To provide context, some information about the entity being retrieved is included, and additionally the operation
context is also passed in from a previous get/3 , put/4 , or start_transaction/1 .
%%
Returns a triple with { ok , GetResult , NextOperationContext } if the operation was executed successfully or
{ error , , NextOperationContext } otherwise .
-callback get(list({Key::key(), Type::entity()}), OperationContext::context()) ->
{list(app_record() | {error, term()}), context()}.
%% put/3 - Adds a list of key-value entries to the database.
%% To provide context, some information about the each entry being added is included, and additionally the operation
context is also passed in from a previous get/3 , put/4 , or start_transaction/1 .
%%
Returns a pair with { list(put_results ( ) ) , NextOperationContext } if the operation was executed successfully or
{ error , , NextOperationContext } otherwise .
%%
%% The Key to be written is passed in binary string format, as that is currently universally supported by all libraries.
%% The Value to be written is a value that the driver is able to recognize, which means that the adapters need to pass
%% valid values that the drivers are able to recognize and convert to a proper internal representation.
%%
%% A more in-depth explanation of what key() and value() should be:
1 . key ( ) is a binary string representation of the key that is going to be written .
2 . value ( ) is either an application record ( in which case it is considered that every field is supposed to stay under
%% the same key, )
-callback put(list({Key::key(), Type::entity(), Value::value()}), OperationContext::context()) ->
{list(ok | {error, term()}), context()}.
| null | https://raw.githubusercontent.com/goncalotomas/FMKe/654d3211ef57d841540e58033a397ce0f3dee0f7/src/gen_fmke_kv_driver.erl | erlang |
A brief explanation about FMKe adapters and drivers:
about the data model, connection pool or any other configurable parameter. Adapters don't communicate directly with
client libraries for databases, but instead do it through drivers.
A driver is a simple wrapper over a database's client library that exposes a common interface to all databases.
When implementing a driver it is necessary to implement additional logic required to maintain correct application
state, such as keeping track of previously read values within a transaction. Failure to implement the additional
logic may result in anomalies which will should be documented. The performance to correctness trade-off is common
in these types of storage systems, and the documentation of the presented anomalies along with performance values
is paramount.
Since adapters do not make assumptions about the capabilities of the database, the drivers will need to export
return opaque state that is passed in to further operations, meaning that you can add contextual information by
returning {ok, term()}, or just {ok, []} if there is no need for context in order to perform the operations.
Drivers might also need to set up additional components and state for themselves, which is why the start/0
hooks exist. In these functions you may open a pool of connections to the database (but for that purpose you can
already use the fmke_db_conn_manager module), create an ETS table for caching results, etc.
Conversely, the stop/0 function will allow you to terminate gracefully and perform any teardown you feel necessary.
The get and put functions that drivers need to implement contain extra parameters in order to give operation context
to the drivers. This is to avoid all possible overhead from using a generic approach (for instance, having to derive
which entity is being obtained from the key passed in get/3, if you used separate buckets in the database for each
one) as well as trying to provide optimal compatibility with other storage systems that may require extra context to
perform operations.
-type data_model() :: nested | non_nested.
---------------------------------------------------------------------------------------------------------------------
Setup and teardown callbacks
---------------------------------------------------------------------------------------------------------------------
Startup hook that provides information about whether the current benchmark execution is using a normalized or nested
data layout. It is the driver's responsability to implement the logic for both data layouts, although the code should
not change significantly between them. (See example below)
Furthermore, application records such as patients will need to store their associated prescriptions, which are
prescription key inside the patient, and we consider this to be a "normalized" (non-nested) data layout.
Implementing a driver may be done for a single data layout, ignoring the other completely. When test executions are
run, only valid data model implementations are considered for performance results.
-callback start(DataModel::data_model()) -> {error, term()} | {ok, pid()}.
-callback stop() -> ok.
---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------
Starts a transaction while providing some context of the type of operations that are going to be performed.
A proplist of options (Options) is passed in, with the following values considered valid options:
{entity, Entity :: entity()} ->
operations related to the same transaction.
Signals the end of a transaction, passing in the current operation context as well as a list of options that
currently serves no purpose. A typical implementation of commit_transaction includes calling commit_transaction on
See some implementations in the fmke_db_adapter_driver_antidote.erl and fmke_db_adapter_driver_riak.erl modules.
---------------------------------------------------------------------------------------------------------------------
Key value callbacks
---------------------------------------------------------------------------------------------------------------------
To provide context, some information about the entity being retrieved is included, and additionally the operation
put/3 - Adds a list of key-value entries to the database.
To provide context, some information about the each entry being added is included, and additionally the operation
The Key to be written is passed in binary string format, as that is currently universally supported by all libraries.
The Value to be written is a value that the driver is able to recognize, which means that the adapters need to pass
valid values that the drivers are able to recognize and convert to a proper internal representation.
A more in-depth explanation of what key() and value() should be:
the same key, ) | This module documents the callbacks that an FMKE driver for a Key - Value Store must implement .
An adapter is an Erlang module that implements the complete FMKe callback set , but that is able to make assumptions
callbacks related to transactions ( e.g. start_transaction/1 , commit_transaction/1 ) . These functions are expected to
-module(gen_fmke_kv_driver).
-include("fmke.hrl").
-type value() :: term().
-type context() :: term().
-type options() :: list({atom(), term()}).
-type txn_result() :: ok | {error, term()}.
A typical way of storing objects in CRDT databases would be to nest every field inside a top level record , which has
so far proved to have worse performance , since each CRDT state size will increase over multiple operations .
separate entities / records , further increasing CRDT state size . One way to bypass this is to store a reference to the
Teardown hook , called when the application is stopped .
Transactional support callbacks
The following operations that are going to be performed in this transaction only concern one entity , Entity .
Returns any erlang term containing the state that is required by the driver to execute each operation related with a
transaction . It is common for the returned state to include a Pid that contains a connection to the database and
possibly identifier(s ) for the transaction . Any erlang term is considered valid and will be passed in to subsequent
-callback start_transaction(Options::options()) -> {ok, OperationContext::context()}.
client library ( if supported ) and returning the Pid to the connection pool .
-callback commit_transaction(OperationContext::context(), Options::options()) -> Result::txn_result().
get/2 - Fetches a list of keys from the database .
context is also passed in from a previous get/3 , put/4 , or start_transaction/1 .
Returns a triple with { ok , GetResult , NextOperationContext } if the operation was executed successfully or
{ error , , NextOperationContext } otherwise .
-callback get(list({Key::key(), Type::entity()}), OperationContext::context()) ->
{list(app_record() | {error, term()}), context()}.
context is also passed in from a previous get/3 , put/4 , or start_transaction/1 .
Returns a pair with { list(put_results ( ) ) , NextOperationContext } if the operation was executed successfully or
{ error , , NextOperationContext } otherwise .
1 . key ( ) is a binary string representation of the key that is going to be written .
2 . value ( ) is either an application record ( in which case it is considered that every field is supposed to stay under
-callback put(list({Key::key(), Type::entity(), Value::value()}), OperationContext::context()) ->
{list(ok | {error, term()}), context()}.
|
c035c9c9fce5a6951099f565276b8f048d8dfa03daa42ab2e05d2f64b42d4b20 | charlieg/Sparser | doc-streams.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
;;;
;;; copyright and other intellectual interests in this file and
;;; the information it contains are governed by the contract signed
March 28 , 1994 between of 14 Brantwood Road ,
Arlington Massachusetts , and Apple Computer , Inc.
;;;
;;; File: "doc streams"
;;; Module: "interface;Apple:"
Version : 1.1 September 5 , 1994
;;Changelog
;; 1.1 Set up the filelists as concatenations with parameterized components
;; of the hard pathnames to make it simpler to customize them to a given
;; site.
(in-package :sparser)
;;;------------------------------------
;;; parameters for the hard file names
;;;------------------------------------
(unless (boundp '*Apple-documents-directory*)
(defparameter *Apple-documents-directory*
" HitchHiker 120 : Apple documents : "
"Macintosh HD:Apple documents:"
))
;; This is a pathname from the root -- note the final colon
;;;----------------------------------------------
Document streams for Powertalk and Reference
;;;----------------------------------------------
(define-document-stream '|Documentation|
:superstream t )
(define-document-stream '|PowerTalk|
:substream-of '|Documentation|
:style-name 'Apple
:file-list
(mapcar #'(lambda (number-string)
(concatenate 'string
*Apple-documents-directory*
"new PowerTalk:Chap"
number-string
":body"
number-string
".gml"))
'( "1" "2" "3" "4" "5" "6" "7" "8" "A" "B" )))
(define-document-stream '|Reference|
:substream-of '|Documentation|
:style-name 'Apple
:file-list
(mapcar #'(lambda (number-string)
(concatenate 'string
*Apple-documents-directory*
"new Reference:Chap"
number-string
":body"
number-string
".gml"))
'( "1" "2" "3" "4" "5" "6" "B" "C")))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/interface/Apple/doc-streams.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:SPARSER -*-
copyright and other intellectual interests in this file and
the information it contains are governed by the contract signed
File: "doc streams"
Module: "interface;Apple:"
Changelog
1.1 Set up the filelists as concatenations with parameterized components
of the hard pathnames to make it simpler to customize them to a given
site.
------------------------------------
parameters for the hard file names
------------------------------------
This is a pathname from the root -- note the final colon
----------------------------------------------
---------------------------------------------- | March 28 , 1994 between of 14 Brantwood Road ,
Arlington Massachusetts , and Apple Computer , Inc.
Version : 1.1 September 5 , 1994
(in-package :sparser)
(unless (boundp '*Apple-documents-directory*)
(defparameter *Apple-documents-directory*
" HitchHiker 120 : Apple documents : "
"Macintosh HD:Apple documents:"
))
Document streams for Powertalk and Reference
(define-document-stream '|Documentation|
:superstream t )
(define-document-stream '|PowerTalk|
:substream-of '|Documentation|
:style-name 'Apple
:file-list
(mapcar #'(lambda (number-string)
(concatenate 'string
*Apple-documents-directory*
"new PowerTalk:Chap"
number-string
":body"
number-string
".gml"))
'( "1" "2" "3" "4" "5" "6" "7" "8" "A" "B" )))
(define-document-stream '|Reference|
:substream-of '|Documentation|
:style-name 'Apple
:file-list
(mapcar #'(lambda (number-string)
(concatenate 'string
*Apple-documents-directory*
"new Reference:Chap"
number-string
":body"
number-string
".gml"))
'( "1" "2" "3" "4" "5" "6" "B" "C")))
|
346ff0041b4af07a9093043e778cf64bdc69bc8e03cbdfd6cd4f90c10f2829f9 | panterarocks49/datascript-firebase | reactive.cljs | (ns datascript-firebase.reactive
(:require
[reagent.core :as r]
[reagent.ratom :as r-ratom]
[datascript.core :as d]))
(defn listen!
"registers a listener for the connection transactions. Returns
the conn object itself with the added listener and state holder
Subsequent usages of conn in q! and pull! will return reactive
atoms that will update their value whenever the Datascript value
changes"
[conn]
(when (nil? (::ratom @conn))
(let [ratom (r/atom @conn)] ;; initial state
(d/listen! conn
::tx
(fn [{:as tx-report :keys [tx-data db-after]}]
(reset! ratom db-after)))
keep a reference to the to avoid GC
;; could add this as meta data
(swap! conn assoc ::ratom ratom)))
;; return the conn again to allow standard datascript usage
conn)
(defn unlisten!
"unregisters the transaction listener previously attached with
listen!"
[conn]
(d/unlisten! conn ::tx)
(swap! conn dissoc ::ratom))
(defn pull
"same as datascript/pull but returns a ratom which will be updated
every time that the value of conn changes"
[conn selector eid]
(r-ratom/make-reaction
#(try
(d/pull @(::ratom @conn) (conj selector :db/id) eid)
(catch js/Error e
{:db/id nil}))))
(defn q
"Returns a reagent/atom with the result of the query.
The value of the ratom will be automatically updated whenever
a change is detected"
[query conn & inputs]
(r-ratom/make-reaction
#(try
(apply d/q query @(::ratom @conn) inputs)
(catch js/Error e
nil))))
(defn datoms
[conn index & args]
(r-ratom/make-reaction
#(try
(mapv vec
(apply d/datoms @(::ratom @conn) index args))
(catch js/Error e
nil))
))
(defn f-entity
"f gets the f-entity"
[conn f eid & args]
(r-ratom/make-reaction
#(try
(apply f (d/entity @(::ratom @conn) eid) args)
(catch js/Error e
nil))))
| null | https://raw.githubusercontent.com/panterarocks49/datascript-firebase/fcfb3d61532923457e9e5e971ceb673a5503099e/src/cljs/datascript_firebase/reactive.cljs | clojure | initial state
could add this as meta data
return the conn again to allow standard datascript usage | (ns datascript-firebase.reactive
(:require
[reagent.core :as r]
[reagent.ratom :as r-ratom]
[datascript.core :as d]))
(defn listen!
"registers a listener for the connection transactions. Returns
the conn object itself with the added listener and state holder
Subsequent usages of conn in q! and pull! will return reactive
atoms that will update their value whenever the Datascript value
changes"
[conn]
(when (nil? (::ratom @conn))
(d/listen! conn
::tx
(fn [{:as tx-report :keys [tx-data db-after]}]
(reset! ratom db-after)))
keep a reference to the to avoid GC
(swap! conn assoc ::ratom ratom)))
conn)
(defn unlisten!
"unregisters the transaction listener previously attached with
listen!"
[conn]
(d/unlisten! conn ::tx)
(swap! conn dissoc ::ratom))
(defn pull
"same as datascript/pull but returns a ratom which will be updated
every time that the value of conn changes"
[conn selector eid]
(r-ratom/make-reaction
#(try
(d/pull @(::ratom @conn) (conj selector :db/id) eid)
(catch js/Error e
{:db/id nil}))))
(defn q
"Returns a reagent/atom with the result of the query.
The value of the ratom will be automatically updated whenever
a change is detected"
[query conn & inputs]
(r-ratom/make-reaction
#(try
(apply d/q query @(::ratom @conn) inputs)
(catch js/Error e
nil))))
(defn datoms
[conn index & args]
(r-ratom/make-reaction
#(try
(mapv vec
(apply d/datoms @(::ratom @conn) index args))
(catch js/Error e
nil))
))
(defn f-entity
"f gets the f-entity"
[conn f eid & args]
(r-ratom/make-reaction
#(try
(apply f (d/entity @(::ratom @conn) eid) args)
(catch js/Error e
nil))))
|
66265547350aef6a6415c10d9b9fe5cc97b1e1b36642cc3113a5de17981b16cd | dschrempf/elynx | AminoAcid.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
-- |
-- Module : ELynx.AminoAcid
-- Description : Amino acid related types and functions
Copyright : 2021
License : GPL-3.0 - or - later
--
-- Maintainer :
-- Stability : unstable
-- Portability : portable
--
Creation date : Thu Oct 4 18:26:35 2018 .
--
See header of ' ELynx . Alphabet . Alphabet ' .
--
Amino acids in alphabetical order .
--
-- @
Amino Acid Code : Three letter Code : Amino Acid :
-- ---------------- ------------------ -----------
-- A Ala Alanine
C Cysteine
-- D Asp Aspartic Acid
E Glu Glutamic Acid
-- F Phe Phenylalanine
-- G Gly Glycine
H His
-- I Ile Isoleucine
K Lys Lysine
-- L Leu Leucine
-- M Met Methionine
N Asn Asparagine
P Pro Proline
-- Q Gln Glutamine
-- R Arg Arginine
-- S Ser Serine
T Threonine
V
-- W Trp Tryptophan
-- Y Tyr Tyrosine
-- @
module ELynx.Character.AminoAcid
( AminoAcid (..),
)
where
import Data.ByteString.Internal (c2w, w2c)
import Data.Vector.Unboxed.Deriving
import Data.Word8
import qualified ELynx.Character.Character as C
-- | Amino acids.
data AminoAcid = A | C | D | E | F | G | H | I | K | L | M | N | P | Q | R | S | T | V | W | Y
deriving (Show, Read, Eq, Ord, Enum, Bounded)
toWord :: AminoAcid -> Word8
toWord A = c2w 'A'
toWord C = c2w 'C'
toWord D = c2w 'D'
toWord E = c2w 'E'
toWord F = c2w 'F'
toWord G = c2w 'G'
toWord H = c2w 'H'
toWord I = c2w 'I'
toWord K = c2w 'K'
toWord L = c2w 'L'
toWord M = c2w 'M'
toWord N = c2w 'N'
toWord P = c2w 'P'
toWord Q = c2w 'Q'
toWord R = c2w 'R'
toWord S = c2w 'S'
toWord T = c2w 'T'
toWord V = c2w 'V'
toWord W = c2w 'W'
toWord Y = c2w 'Y'
fromWord :: Word8 -> AminoAcid
fromWord w = case w2c w of
'A' -> A
'C' -> C
'D' -> D
'E' -> E
'F' -> F
'G' -> G
'H' -> H
'I' -> I
'K' -> K
'L' -> L
'M' -> M
'N' -> N
'P' -> P
'Q' -> Q
'R' -> R
'S' -> S
'T' -> T
'V' -> V
'W' -> W
'Y' -> Y
_ -> error "fromWord: Cannot convert to AminoAcid."
derivingUnbox
"AminoAcid"
[t|AminoAcid -> Word8|]
[|toWord|]
[|fromWord|]
instance C.Character AminoAcid where
toWord = toWord
fromWord = fromWord
| null | https://raw.githubusercontent.com/dschrempf/elynx/f73f4474c61c22c6a9e54c56bdc34b37eff09687/elynx-seq/src/ELynx/Character/AminoAcid.hs | haskell | |
Module : ELynx.AminoAcid
Description : Amino acid related types and functions
Maintainer :
Stability : unstable
Portability : portable
@
---------------- ------------------ -----------
A Ala Alanine
D Asp Aspartic Acid
F Phe Phenylalanine
G Gly Glycine
I Ile Isoleucine
L Leu Leucine
M Met Methionine
Q Gln Glutamine
R Arg Arginine
S Ser Serine
W Trp Tryptophan
Y Tyr Tyrosine
@
| Amino acids. | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
Copyright : 2021
License : GPL-3.0 - or - later
Creation date : Thu Oct 4 18:26:35 2018 .
See header of ' ELynx . Alphabet . Alphabet ' .
Amino acids in alphabetical order .
Amino Acid Code : Three letter Code : Amino Acid :
C Cysteine
E Glu Glutamic Acid
H His
K Lys Lysine
N Asn Asparagine
P Pro Proline
T Threonine
V
module ELynx.Character.AminoAcid
( AminoAcid (..),
)
where
import Data.ByteString.Internal (c2w, w2c)
import Data.Vector.Unboxed.Deriving
import Data.Word8
import qualified ELynx.Character.Character as C
data AminoAcid = A | C | D | E | F | G | H | I | K | L | M | N | P | Q | R | S | T | V | W | Y
deriving (Show, Read, Eq, Ord, Enum, Bounded)
toWord :: AminoAcid -> Word8
toWord A = c2w 'A'
toWord C = c2w 'C'
toWord D = c2w 'D'
toWord E = c2w 'E'
toWord F = c2w 'F'
toWord G = c2w 'G'
toWord H = c2w 'H'
toWord I = c2w 'I'
toWord K = c2w 'K'
toWord L = c2w 'L'
toWord M = c2w 'M'
toWord N = c2w 'N'
toWord P = c2w 'P'
toWord Q = c2w 'Q'
toWord R = c2w 'R'
toWord S = c2w 'S'
toWord T = c2w 'T'
toWord V = c2w 'V'
toWord W = c2w 'W'
toWord Y = c2w 'Y'
fromWord :: Word8 -> AminoAcid
fromWord w = case w2c w of
'A' -> A
'C' -> C
'D' -> D
'E' -> E
'F' -> F
'G' -> G
'H' -> H
'I' -> I
'K' -> K
'L' -> L
'M' -> M
'N' -> N
'P' -> P
'Q' -> Q
'R' -> R
'S' -> S
'T' -> T
'V' -> V
'W' -> W
'Y' -> Y
_ -> error "fromWord: Cannot convert to AminoAcid."
derivingUnbox
"AminoAcid"
[t|AminoAcid -> Word8|]
[|toWord|]
[|fromWord|]
instance C.Character AminoAcid where
toWord = toWord
fromWord = fromWord
|
b6c20ef8b39ec9bfe587cf6116c86692de829d3b915b7cf961aaf03c390888f6 | jeapostrophe/exp | bf-1.rkt | #lang racket
(define pipe-tag (make-continuation-prompt-tag 'pipe))
(define (pipe* f)
(let/ec esc
(call-with-continuation-prompt f pipe-tag esc)
(error 'pipe "did not pipe-out")))
(define-syntax-rule (pipe e ...)
(pipe* (λ () e ...)))
(define (pipe-out v)
(call-with-composable-continuation
(λ (come-back)
(abort-current-continuation pipe-tag v come-back))
pipe-tag))
;; In response to:
(define parse
(match-lambda
[(list* 'lbr more)
(define-values (more-p pipe-in) (pipe (parse more)))
(list* (pipe-in (list)) (parse more-p))]
[(list* 'rbr more)
(pipe-out more)]
[(list)
(list)]
[(list* i more)
(list* i (parse more))]))
(require rackunit)
(check-equal? (parse '()) '())
(check-equal? (parse '(>)) '(>))
(check-equal? (parse '(> >)) '(> >))
(check-equal? (parse '(lbr > > rbr)) '((> >)))
(check-exn exn:fail? (λ () (parse '(lbr > >))))
(check-equal? (parse '(> lbr > > rbr >)) '(> (> >) >))
;; Plus, a puzzle...
(define (A i)
(cond
[(zero? i)
empty]
[else
(define-values (j pipe-in) (pipe (list* i (A (pipe-out (sub1 i))))))
(list* j (pipe-in (sub1 j)))]))
;; Can you predict what this expression evaluates to?
(A 10)
| null | https://raw.githubusercontent.com/jeapostrophe/exp/43615110fd0439d2ef940c42629fcdc054c370f9/bf-1.rkt | racket | In response to:
Plus, a puzzle...
Can you predict what this expression evaluates to? | #lang racket
(define pipe-tag (make-continuation-prompt-tag 'pipe))
(define (pipe* f)
(let/ec esc
(call-with-continuation-prompt f pipe-tag esc)
(error 'pipe "did not pipe-out")))
(define-syntax-rule (pipe e ...)
(pipe* (λ () e ...)))
(define (pipe-out v)
(call-with-composable-continuation
(λ (come-back)
(abort-current-continuation pipe-tag v come-back))
pipe-tag))
(define parse
(match-lambda
[(list* 'lbr more)
(define-values (more-p pipe-in) (pipe (parse more)))
(list* (pipe-in (list)) (parse more-p))]
[(list* 'rbr more)
(pipe-out more)]
[(list)
(list)]
[(list* i more)
(list* i (parse more))]))
(require rackunit)
(check-equal? (parse '()) '())
(check-equal? (parse '(>)) '(>))
(check-equal? (parse '(> >)) '(> >))
(check-equal? (parse '(lbr > > rbr)) '((> >)))
(check-exn exn:fail? (λ () (parse '(lbr > >))))
(check-equal? (parse '(> lbr > > rbr >)) '(> (> >) >))
(define (A i)
(cond
[(zero? i)
empty]
[else
(define-values (j pipe-in) (pipe (list* i (A (pipe-out (sub1 i))))))
(list* j (pipe-in (sub1 j)))]))
(A 10)
|
299791918040d811ad0dfe282cc61e4db192787b0d52f74cad1eaf466e6a68bc | johnwhitington/ocamli | tinyocamlutil.ml | open Tinyocaml
open
let calc = function
Add -> (+) | Sub -> (-) | Mul -> ( * ) | Div -> (/)
let comp = function
LT -> (<) | EQ -> (=) | GT -> (>) | EQLT -> (<=) | EQGT -> (>=) | NEQ -> (<>)
(* Predicate on value-ness of expressions. *)
let rec is_value e =
(*Printf.printf "isvalue on %s\n" (to_string e);*)
match e with
Unit | Int _ | Bool _ | Fun _ | Function _
| Int32 _ | Int64 _ | NativeInt _
| OutChannel _ | InChannel _ | Char _ | String _ | Float _ | Nil -> true
| Record items when
List.for_all is_value (List.map (fun (_, {contents = e}) -> e) items) -> true
| Struct (_, items) when
List.for_all is_value items -> true
| Tuple items when
List.for_all is_value items -> true
| Array items when
Array.for_all is_value items -> true
| Constr (_, _, None) -> true
| Constr (_, _, Some t) -> is_value t
| Cons (e, e') when
is_value e && is_value e' -> true
| LetDef (_, bindings) when
List.for_all (fun (_, e) -> is_value e) bindings -> true
| Let (_, bindings, e) when
List.for_all (fun (_, e) -> is_value e) bindings && is_value e -> true
| ModuleBinding (_, x) -> is_value x
| ExceptionDef _ | TypeDef _ | ModuleConstraint _ | ModuleIdentifier _ -> true
| Open _ -> true
| LocalOpen (_, t) -> is_value t
| Lazy t -> true
| Functor _ -> true
| ModuleApply (_, x) -> is_value x
| Include _ -> true
| Control (_, x) -> is_value x
Printf.printf " IS_VALUE FALSE : % s\n " ( Tinyocaml.to_string x ) ;
let bold, ul, code_end = ("\x1b[1m", "\x1b[4m", "\x1b[0m")
(* If not a value, underline it as the next redex *)
let underline x =
Control (Underline, x)
exception UnderlineValueUnderLets
exception UnderlineValueUnderLets2
let fastcurry = ref false
let rec underline_redex e =
try
match e with
Control (c, x) -> Control (c, underline_redex x)
| Op (_, (Int _ | Var _), (Int _ | Var _)) -> underline e
| Op (op, ((Int _ | Var _) as a), b) -> Op (op, a, underline_redex b)
| Op (op, a, b) -> Op (op, underline_redex a, b)
| And (Bool false, _) -> underline e
| And (Bool true, Bool _) -> underline e
| And (Bool true, b) -> And (Bool true, underline_redex b)
| And (a, b) -> And (underline_redex a, b)
| Or (Bool true, _) -> underline e
| Or (Bool false, Bool b) -> underline e
| Or (Bool false, b) -> Or (Bool false, underline_redex b)
| Cmp (_, (Int _ | Var _), (Int _ | Var _)) -> underline e
| Cmp (op, a, ((Int _ | Var _) as b)) -> Cmp (op, underline_redex a, b)
| Cmp (op, a, b) -> Cmp (op, a, underline_redex b)
| If (Bool _, _, _) -> underline e
| If (cond, a, b) -> If (underline_redex cond, a, b)
| Let (recflag, bindings, e') ->
if List.for_all (fun (_, v) -> is_value v) bindings then
Let (recflag, bindings, underline_redex e')
else
Let (recflag, underline_first_non_value_binding bindings, e')
| LetDef (recflag, bindings) ->
if List.for_all (fun (_, v) -> is_value v) bindings then
failwith "letdef already a value"
else
LetDef (recflag, underline_first_non_value_binding bindings)
| App (Fun f, x) ->
if is_value x then underline e else App (Fun f, underline_redex x)
| App (Function f, x) ->
if is_value x then underline e else App (Function f, underline_redex x)
| App (Var v, x) ->
App (underline (Var v), x)
| App (App _, _) when !fastcurry ->
underline_curry e
| App (f, x) -> App (underline_redex f, x)
| Seq (a, b) ->
if is_value a then underline e else Seq (underline_redex a, b)
| While (we, we', copy_we, copy_we') ->
if not (is_value we) then While (underline_redex we, we', copy_we, copy_we') else
if not (is_value we') then While (we, underline_redex we', copy_we, copy_we') else
underline e
| For (n, fe, updown, fe', fe'', copy_fe'') ->
if not (is_value fe) then
For (n, underline_redex fe, updown, fe', fe'', copy_fe'')
else if not (is_value fe') then
For (n, fe, updown, underline_redex fe', fe'', copy_fe'')
else if not (is_value fe'') then
For (n, fe, updown, fe', underline_redex fe'', copy_fe'')
else
underline e
| Var _ -> underline e
| Record items ->
underline_first_non_value_ref items;
Record items
| Field (a, n) ->
if is_value a then underline e else Field (underline a, n)
| SetField (a, n, b) ->
if is_value a then
if is_value b then underline e else SetField (a, n, underline b)
else
SetField (underline a, n, b)
| Raise _ -> underline e
| TryWith (a, cases) ->
if is_value a then underline e else TryWith (underline_redex a, cases)
| CallBuiltIn (typ, name, args, fn) ->
if List.for_all is_value args
then underline e
else CallBuiltIn (typ, name, underline_first_non_value args, fn)
| Struct (b, ls) ->
if List.for_all is_value ls
then failwith "module already a value"
else Struct (b, underline_first_non_value ls)
| Tuple ls ->
if List.for_all is_value ls
then failwith "tuple already a value"
else Tuple (underline_first_non_value ls)
| Array items ->
if Array.for_all is_value items
then failwith "tuple already a value"
else
begin
underline_first_non_value_array items;
Array items
end
| Constr (tag, n, Some t) ->
if is_value t
then failwith "constr already a value"
else Constr (tag, n, Some (underline_redex t))
| Cons (x, y) ->
if is_value x then Cons (x, underline_redex y) else Cons (underline x, y)
| Match (x, patmatch) ->
if is_value x then underline e else Match (underline_redex x, patmatch)
| LocalOpen (n, e) ->
LocalOpen (n, underline_redex e)
| _ ->
raise UnderlineValueUnderLets
with
UnderlineValueUnderLets -> raise UnderlineValueUnderLets2
| UnderlineValueUnderLets2 -> underline e
1 ) Underline the first function which is not a value , if there is one , or else
2 ) Underline the last argument which is not a value , if there is one , or else
3 ) We are ready to apply , return None .
and underline_curry_inner e =
match e with
| App (f, x) when not (is_value x) -> Some (App (f, underline_redex x))
| App (App _ as f', x') ->
begin match underline_curry_inner f' with
None -> None
| Some f'' -> Some (App (f'', x'))
end
| App (f, x) when not (is_value f) -> Some (App (underline_redex f, x))
| _ -> None
and underline_curry e =
match underline_curry_inner e with
None -> underline e
| Some x -> x
and underline_first_non_value = function
[] -> []
| h::t ->
if is_value h
then h::underline_first_non_value t
else underline_redex h::t
and underline_first_non_value_array x =
let rec loop p =
if p >= Array.length x then ()
else if is_value x.(p) then loop (p + 1)
else x.(p) <- underline_redex x.(p)
in
loop 0
and underline_first_non_value_binding = function
[] -> []
| (k, v)::t ->
if is_value v
then (k, v)::underline_first_non_value_binding t
else (k, underline_redex v)::t
and underline_first_non_value_ref items =
try
List.iter
(fun (_, v) -> if not (is_value !v) then begin v := underline_redex !v; raise Exit end)
items
with
Exit -> ()
let underline_redex e =
if is_value e then e else underline_redex e
let rec strip_control = function
Control (_, e) -> strip_control e
| x -> Tinyocaml.recurse strip_control x
let rec remove_named_recursive_functions all fns = function
Let (true, [(PatVar n, v)], e) ->
let r = Tinyocaml.recurse (remove_named_recursive_functions all fns) e in
if all || List.mem n fns then r else Let (true, [(PatVar n, v)], r)
| x -> Tinyocaml.recurse (remove_named_recursive_functions all fns) x
| null | https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/tinyocamlutil.ml | ocaml | Predicate on value-ness of expressions.
Printf.printf "isvalue on %s\n" (to_string e);
If not a value, underline it as the next redex | open Tinyocaml
open
let calc = function
Add -> (+) | Sub -> (-) | Mul -> ( * ) | Div -> (/)
let comp = function
LT -> (<) | EQ -> (=) | GT -> (>) | EQLT -> (<=) | EQGT -> (>=) | NEQ -> (<>)
let rec is_value e =
match e with
Unit | Int _ | Bool _ | Fun _ | Function _
| Int32 _ | Int64 _ | NativeInt _
| OutChannel _ | InChannel _ | Char _ | String _ | Float _ | Nil -> true
| Record items when
List.for_all is_value (List.map (fun (_, {contents = e}) -> e) items) -> true
| Struct (_, items) when
List.for_all is_value items -> true
| Tuple items when
List.for_all is_value items -> true
| Array items when
Array.for_all is_value items -> true
| Constr (_, _, None) -> true
| Constr (_, _, Some t) -> is_value t
| Cons (e, e') when
is_value e && is_value e' -> true
| LetDef (_, bindings) when
List.for_all (fun (_, e) -> is_value e) bindings -> true
| Let (_, bindings, e) when
List.for_all (fun (_, e) -> is_value e) bindings && is_value e -> true
| ModuleBinding (_, x) -> is_value x
| ExceptionDef _ | TypeDef _ | ModuleConstraint _ | ModuleIdentifier _ -> true
| Open _ -> true
| LocalOpen (_, t) -> is_value t
| Lazy t -> true
| Functor _ -> true
| ModuleApply (_, x) -> is_value x
| Include _ -> true
| Control (_, x) -> is_value x
Printf.printf " IS_VALUE FALSE : % s\n " ( Tinyocaml.to_string x ) ;
let bold, ul, code_end = ("\x1b[1m", "\x1b[4m", "\x1b[0m")
let underline x =
Control (Underline, x)
exception UnderlineValueUnderLets
exception UnderlineValueUnderLets2
let fastcurry = ref false
let rec underline_redex e =
try
match e with
Control (c, x) -> Control (c, underline_redex x)
| Op (_, (Int _ | Var _), (Int _ | Var _)) -> underline e
| Op (op, ((Int _ | Var _) as a), b) -> Op (op, a, underline_redex b)
| Op (op, a, b) -> Op (op, underline_redex a, b)
| And (Bool false, _) -> underline e
| And (Bool true, Bool _) -> underline e
| And (Bool true, b) -> And (Bool true, underline_redex b)
| And (a, b) -> And (underline_redex a, b)
| Or (Bool true, _) -> underline e
| Or (Bool false, Bool b) -> underline e
| Or (Bool false, b) -> Or (Bool false, underline_redex b)
| Cmp (_, (Int _ | Var _), (Int _ | Var _)) -> underline e
| Cmp (op, a, ((Int _ | Var _) as b)) -> Cmp (op, underline_redex a, b)
| Cmp (op, a, b) -> Cmp (op, a, underline_redex b)
| If (Bool _, _, _) -> underline e
| If (cond, a, b) -> If (underline_redex cond, a, b)
| Let (recflag, bindings, e') ->
if List.for_all (fun (_, v) -> is_value v) bindings then
Let (recflag, bindings, underline_redex e')
else
Let (recflag, underline_first_non_value_binding bindings, e')
| LetDef (recflag, bindings) ->
if List.for_all (fun (_, v) -> is_value v) bindings then
failwith "letdef already a value"
else
LetDef (recflag, underline_first_non_value_binding bindings)
| App (Fun f, x) ->
if is_value x then underline e else App (Fun f, underline_redex x)
| App (Function f, x) ->
if is_value x then underline e else App (Function f, underline_redex x)
| App (Var v, x) ->
App (underline (Var v), x)
| App (App _, _) when !fastcurry ->
underline_curry e
| App (f, x) -> App (underline_redex f, x)
| Seq (a, b) ->
if is_value a then underline e else Seq (underline_redex a, b)
| While (we, we', copy_we, copy_we') ->
if not (is_value we) then While (underline_redex we, we', copy_we, copy_we') else
if not (is_value we') then While (we, underline_redex we', copy_we, copy_we') else
underline e
| For (n, fe, updown, fe', fe'', copy_fe'') ->
if not (is_value fe) then
For (n, underline_redex fe, updown, fe', fe'', copy_fe'')
else if not (is_value fe') then
For (n, fe, updown, underline_redex fe', fe'', copy_fe'')
else if not (is_value fe'') then
For (n, fe, updown, fe', underline_redex fe'', copy_fe'')
else
underline e
| Var _ -> underline e
| Record items ->
underline_first_non_value_ref items;
Record items
| Field (a, n) ->
if is_value a then underline e else Field (underline a, n)
| SetField (a, n, b) ->
if is_value a then
if is_value b then underline e else SetField (a, n, underline b)
else
SetField (underline a, n, b)
| Raise _ -> underline e
| TryWith (a, cases) ->
if is_value a then underline e else TryWith (underline_redex a, cases)
| CallBuiltIn (typ, name, args, fn) ->
if List.for_all is_value args
then underline e
else CallBuiltIn (typ, name, underline_first_non_value args, fn)
| Struct (b, ls) ->
if List.for_all is_value ls
then failwith "module already a value"
else Struct (b, underline_first_non_value ls)
| Tuple ls ->
if List.for_all is_value ls
then failwith "tuple already a value"
else Tuple (underline_first_non_value ls)
| Array items ->
if Array.for_all is_value items
then failwith "tuple already a value"
else
begin
underline_first_non_value_array items;
Array items
end
| Constr (tag, n, Some t) ->
if is_value t
then failwith "constr already a value"
else Constr (tag, n, Some (underline_redex t))
| Cons (x, y) ->
if is_value x then Cons (x, underline_redex y) else Cons (underline x, y)
| Match (x, patmatch) ->
if is_value x then underline e else Match (underline_redex x, patmatch)
| LocalOpen (n, e) ->
LocalOpen (n, underline_redex e)
| _ ->
raise UnderlineValueUnderLets
with
UnderlineValueUnderLets -> raise UnderlineValueUnderLets2
| UnderlineValueUnderLets2 -> underline e
1 ) Underline the first function which is not a value , if there is one , or else
2 ) Underline the last argument which is not a value , if there is one , or else
3 ) We are ready to apply , return None .
and underline_curry_inner e =
match e with
| App (f, x) when not (is_value x) -> Some (App (f, underline_redex x))
| App (App _ as f', x') ->
begin match underline_curry_inner f' with
None -> None
| Some f'' -> Some (App (f'', x'))
end
| App (f, x) when not (is_value f) -> Some (App (underline_redex f, x))
| _ -> None
and underline_curry e =
match underline_curry_inner e with
None -> underline e
| Some x -> x
and underline_first_non_value = function
[] -> []
| h::t ->
if is_value h
then h::underline_first_non_value t
else underline_redex h::t
and underline_first_non_value_array x =
let rec loop p =
if p >= Array.length x then ()
else if is_value x.(p) then loop (p + 1)
else x.(p) <- underline_redex x.(p)
in
loop 0
and underline_first_non_value_binding = function
[] -> []
| (k, v)::t ->
if is_value v
then (k, v)::underline_first_non_value_binding t
else (k, underline_redex v)::t
and underline_first_non_value_ref items =
try
List.iter
(fun (_, v) -> if not (is_value !v) then begin v := underline_redex !v; raise Exit end)
items
with
Exit -> ()
let underline_redex e =
if is_value e then e else underline_redex e
let rec strip_control = function
Control (_, e) -> strip_control e
| x -> Tinyocaml.recurse strip_control x
let rec remove_named_recursive_functions all fns = function
Let (true, [(PatVar n, v)], e) ->
let r = Tinyocaml.recurse (remove_named_recursive_functions all fns) e in
if all || List.mem n fns then r else Let (true, [(PatVar n, v)], r)
| x -> Tinyocaml.recurse (remove_named_recursive_functions all fns) x
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.