_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
|
---|---|---|---|---|---|---|---|---|
7f05102ecc8d5298095017e5f5d16155e5bd6ab3f119c5c9392895d1c35460e1 | murtaza52/almonds | core.clj | (ns almonds.core
(:require [almonds.api :as api]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; reset state ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(api/clear-all)
;;;;;;;;;;;;;;;; execute the handler calls ;;;;;;;;;;;;;;;
(require 'almonds.handler)
;;;;;;;;;;;;;;;; reset resources ;;;;;;;;;;;;;;;;;;;;;;
(require 'almonds.resources :reload)
;;;;;;;;;;;;;;; compile other resources ;;;;;;;;;;;;;;;;;;
(require 'almonds.resources.security-group
'almonds.resources.eip-assoc
'almonds.resources.elastic-ip
'almonds.resources.instance
'almonds.resources.security-rule)
| null | https://raw.githubusercontent.com/murtaza52/almonds/f7c5879833316ce395788bcf304eedab8315f0e5/src/almonds/core.clj | clojure | reset state ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
execute the handler calls ;;;;;;;;;;;;;;;
reset resources ;;;;;;;;;;;;;;;;;;;;;;
compile other resources ;;;;;;;;;;;;;;;;;; | (ns almonds.core
(:require [almonds.api :as api]))
(api/clear-all)
(require 'almonds.handler)
(require 'almonds.resources :reload)
(require 'almonds.resources.security-group
'almonds.resources.eip-assoc
'almonds.resources.elastic-ip
'almonds.resources.instance
'almonds.resources.security-rule)
|
70d96c017efe773bf84271970a5041316c9f27ca747c8ebb536689d1969e3316 | brendanhay/gogol | Patch.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . DialogFlow . Projects . Locations . Agents . EntityTypes . Patch
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Updates the specified entity type. Note: You should always train a flow prior to sending it queries. See the < training documentation>.
--
/See:/ < / Dialogflow API Reference > for @dialogflow.projects.locations.agents.entityTypes.patch@.
module Gogol.DialogFlow.Projects.Locations.Agents.EntityTypes.Patch
( -- * Resource
DialogFlowProjectsLocationsAgentsEntityTypesPatchResource,
-- ** Constructing a Request
DialogFlowProjectsLocationsAgentsEntityTypesPatch (..),
newDialogFlowProjectsLocationsAgentsEntityTypesPatch,
)
where
import Gogol.DialogFlow.Types
import qualified Gogol.Prelude as Core
| A resource alias for @dialogflow.projects.locations.agents.entityTypes.patch@ method which the
-- 'DialogFlowProjectsLocationsAgentsEntityTypesPatch' request conforms to.
type DialogFlowProjectsLocationsAgentsEntityTypesPatchResource =
"v3"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "languageCode" Core.Text
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody
'[Core.JSON]
GoogleCloudDialogflowCxV3EntityType
Core.:> Core.Patch
'[Core.JSON]
GoogleCloudDialogflowCxV3EntityType
-- | Updates the specified entity type. Note: You should always train a flow prior to sending it queries. See the < training documentation>.
--
-- /See:/ 'newDialogFlowProjectsLocationsAgentsEntityTypesPatch' smart constructor.
data DialogFlowProjectsLocationsAgentsEntityTypesPatch = DialogFlowProjectsLocationsAgentsEntityTypesPatch
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
| The language of the following fields in : * @EntityType.entities.value@ * @EntityType.entities.synonyms@ * @EntityType.excluded_phrases.value@ If not specified , the agent\ 's default language is used . < Many languages > are supported . Note : languages must be enabled in the agent before they can be used .
languageCode :: (Core.Maybe Core.Text),
| The unique identifier of the entity type . Required for EntityTypes . UpdateEntityType . Format : @projects\/\/locations\/\/agents\/\/entityTypes\/@.
name :: Core.Text,
-- | Multipart request metadata.
payload :: GoogleCloudDialogflowCxV3EntityType,
-- | The mask to control which fields get updated.
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'DialogFlowProjectsLocationsAgentsEntityTypesPatch' with the minimum fields required to make a request.
newDialogFlowProjectsLocationsAgentsEntityTypesPatch ::
| The unique identifier of the entity type . Required for EntityTypes . UpdateEntityType . Format : @projects\/\/locations\/\/agents\/\/entityTypes\/@. See ' name ' .
Core.Text ->
-- | Multipart request metadata. See 'payload'.
GoogleCloudDialogflowCxV3EntityType ->
DialogFlowProjectsLocationsAgentsEntityTypesPatch
newDialogFlowProjectsLocationsAgentsEntityTypesPatch name payload =
DialogFlowProjectsLocationsAgentsEntityTypesPatch
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
languageCode = Core.Nothing,
name = name,
payload = payload,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
DialogFlowProjectsLocationsAgentsEntityTypesPatch
where
type
Rs
DialogFlowProjectsLocationsAgentsEntityTypesPatch =
GoogleCloudDialogflowCxV3EntityType
type
Scopes
DialogFlowProjectsLocationsAgentsEntityTypesPatch =
'[CloudPlatform'FullControl, Dialogflow'FullControl]
requestClient
DialogFlowProjectsLocationsAgentsEntityTypesPatch {..} =
go
name
xgafv
accessToken
callback
languageCode
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
dialogFlowService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
DialogFlowProjectsLocationsAgentsEntityTypesPatchResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-dialogflow/gen/Gogol/DialogFlow/Projects/Locations/Agents/EntityTypes/Patch.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Updates the specified entity type. Note: You should always train a flow prior to sending it queries. See the < training documentation>.
* Resource
** Constructing a Request
'DialogFlowProjectsLocationsAgentsEntityTypesPatch' request conforms to.
| Updates the specified entity type. Note: You should always train a flow prior to sending it queries. See the < training documentation>.
/See:/ 'newDialogFlowProjectsLocationsAgentsEntityTypesPatch' smart constructor.
| V1 error format.
| OAuth access token.
| Multipart request metadata.
| The mask to control which fields get updated.
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'DialogFlowProjectsLocationsAgentsEntityTypesPatch' with the minimum fields required to make a request.
| Multipart request metadata. See 'payload'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . DialogFlow . Projects . Locations . Agents . EntityTypes . Patch
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
/See:/ < / Dialogflow API Reference > for @dialogflow.projects.locations.agents.entityTypes.patch@.
module Gogol.DialogFlow.Projects.Locations.Agents.EntityTypes.Patch
DialogFlowProjectsLocationsAgentsEntityTypesPatchResource,
DialogFlowProjectsLocationsAgentsEntityTypesPatch (..),
newDialogFlowProjectsLocationsAgentsEntityTypesPatch,
)
where
import Gogol.DialogFlow.Types
import qualified Gogol.Prelude as Core
| A resource alias for @dialogflow.projects.locations.agents.entityTypes.patch@ method which the
type DialogFlowProjectsLocationsAgentsEntityTypesPatchResource =
"v3"
Core.:> Core.Capture "name" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "languageCode" Core.Text
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody
'[Core.JSON]
GoogleCloudDialogflowCxV3EntityType
Core.:> Core.Patch
'[Core.JSON]
GoogleCloudDialogflowCxV3EntityType
data DialogFlowProjectsLocationsAgentsEntityTypesPatch = DialogFlowProjectsLocationsAgentsEntityTypesPatch
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
| The language of the following fields in : * @EntityType.entities.value@ * @EntityType.entities.synonyms@ * @EntityType.excluded_phrases.value@ If not specified , the agent\ 's default language is used . < Many languages > are supported . Note : languages must be enabled in the agent before they can be used .
languageCode :: (Core.Maybe Core.Text),
| The unique identifier of the entity type . Required for EntityTypes . UpdateEntityType . Format : @projects\/\/locations\/\/agents\/\/entityTypes\/@.
name :: Core.Text,
payload :: GoogleCloudDialogflowCxV3EntityType,
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newDialogFlowProjectsLocationsAgentsEntityTypesPatch ::
| The unique identifier of the entity type . Required for EntityTypes . UpdateEntityType . Format : @projects\/\/locations\/\/agents\/\/entityTypes\/@. See ' name ' .
Core.Text ->
GoogleCloudDialogflowCxV3EntityType ->
DialogFlowProjectsLocationsAgentsEntityTypesPatch
newDialogFlowProjectsLocationsAgentsEntityTypesPatch name payload =
DialogFlowProjectsLocationsAgentsEntityTypesPatch
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
languageCode = Core.Nothing,
name = name,
payload = payload,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
DialogFlowProjectsLocationsAgentsEntityTypesPatch
where
type
Rs
DialogFlowProjectsLocationsAgentsEntityTypesPatch =
GoogleCloudDialogflowCxV3EntityType
type
Scopes
DialogFlowProjectsLocationsAgentsEntityTypesPatch =
'[CloudPlatform'FullControl, Dialogflow'FullControl]
requestClient
DialogFlowProjectsLocationsAgentsEntityTypesPatch {..} =
go
name
xgafv
accessToken
callback
languageCode
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
dialogFlowService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy
DialogFlowProjectsLocationsAgentsEntityTypesPatchResource
)
Core.mempty
|
35887fb54ef208a8e2257a07d0945ecfbc0593ed37b86c0688cdcce8ed9cfd13 | basho/riak_kv | riak_kv_schema_tests.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2013 - 2016 Basho Technologies , Inc.
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(riak_kv_schema_tests).
-include_lib("eunit/include/eunit.hrl").
-compile([export_all, nowarn_export_all]).
-define(DEFAULT_ENABLED_JOB_CLASSES, [
{riak_kv, list_buckets},
{riak_kv, list_keys},
{riak_kv, map_reduce_js},
{riak_kv, map_reduce},
{riak_kv, secondary_index},
{riak_kv, stream_list_buckets},
{riak_kv, stream_list_keys},
{riak_kv, stream_secondary_index}
]).
%% basic schema test will check to make sure that all defaults from the schema
%% make it into the generated app.config
basic_schema_test() ->
The defaults are defined in priv / riak_kv.schema and multi_backend.schema .
%% they are the files under test.
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], [], context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy", {on, []}),
cuttlefish_unit:assert_config(Config, "riak_kv.storage_backend", riak_kv_bitcask_backend),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_build_limit", {1, 3600000}),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_expire", 604800000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_concurrency", 2),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_tick", 15000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_data_dir", "./data/anti_entropy"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.write_buffer_size", 4194304),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.max_open_files", 20),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_enabled", true),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.aae_throttle_limits"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.use_bloomfilter", true),
cuttlefish_unit:assert_config(Config, "riak_kv.fsm_limit", 50000),
cuttlefish_unit:assert_config(Config, "riak_kv.retry_put_coordinator_failure", true),
cuttlefish_unit:assert_config(Config, "riak_kv.object_format", v1),
cuttlefish_unit:assert_config(Config, "riak_kv.vnode_md_cache_size", 0),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.max_memory"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.ttl"),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_rejected_max", 6),
make sure multi backend is not on by shell_default
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend_default"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend"),
cuttlefish_unit:assert_config(Config, "riak_kv.secure_referer_check", true),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_object_size", 5242880),
cuttlefish_unit:assert_config(Config, "riak_kv.max_object_size", 52428800),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_siblings", 25),
cuttlefish_unit:assert_config(Config, "riak_kv.max_siblings", 100),
cuttlefish_unit:assert_config(Config, "riak_kv.ttaaefs_allcheck_window", always),
%% Default Bucket Properties
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pr", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.r", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.w", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pw", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.rw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.notfound_ok", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.basic_quorum", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.allow_mult", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.last_write_wins", false),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.precommit"),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.postcommit"),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dvv_enabled", false),
cuttlefish_unit:assert_config(Config, "riak_dt.binary_compression", 1),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_use_background_manager", false),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_use_background_manager", false),
ok.
override_non_multi_backend_schema_test() ->
%% Conf represents the riak.conf file that would be read in by cuttlefish.
%% this proplists is what would be output by the conf_parse module
Conf = [
{["anti_entropy"], 'active-debug'},
{["storage_backend"], leveldb},
{["anti_entropy", "tree", "build_limit", "number"], 2},
{["anti_entropy", "tree", "build_limit", "per_timespan"], "1m"},
{["anti_entropy", "tree", "expiry"], never},
{["anti_entropy", "concurrency_limit"], 1},
{["anti_entropy", "trigger_interval"], "1s"},
{["anti_entropy", "data_dir"], "/absolute/data/anti_entropy"},
{["anti_entropy", "write_buffer_size"], "8MB"},
{["anti_entropy", "max_open_files"], 30},
{["anti_entropy", "throttle"], off},
{["anti_entropy", "throttle", "tier1", "mailbox_size"], 0},
{["anti_entropy", "throttle", "tier1", "delay"], "1d"},
{["anti_entropy", "throttle", "tier2", "mailbox_size"], 11},
{["anti_entropy", "throttle", "tier2", "delay"], "10d"},
{["anti_entropy", "bloomfilter"], off},
{["max_concurrent_requests"], 100000},
{["retry_put_coordinator_failure"], off},
{["object", "format"], 0},
{["metadata_cache_size"], "512KB"},
{["memory_backend", "max_memory_per_vnode"], "8GB"},
{["memory_backend", "ttl"], "1d"},
{["secure_referer_check"], off},
{["object", "size", "warning_threshold"], "10MB"},
{["object", "size", "maximum"], "100MB"},
{["object", "siblings", "warning_threshold"], 250},
{["object", "siblings", "maximum"], 1000},
{["buckets", "default", "merge_strategy"], '2'},
%% Default Bucket Properties
{["buckets", "default", "pr"], quorum},
{["buckets", "default", "r"], 2},
{["buckets", "default", "w"], 4},
{["buckets", "default", "pw"], all},
{["buckets", "default", "dw"], all},
{["buckets", "default", "rw"], 1},
{["buckets", "default", "notfound_ok"], false},
{["buckets", "default", "basic_quorum"], true},
{["buckets", "default", "allow_mult"], true},
{["buckets", "default", "last_write_wins"], true},
{["buckets", "default", "precommit"], "module:function javascriptFunction"},
{["buckets", "default", "postcommit"], "module2:function2"},
{["datatypes", "compression_level"], "off"},
{["handoff", "use_background_manager"], on},
{["handoff", "max_rejects"], 10},
{["anti_entropy", "use_background_manager"], on}
],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy", {on, [debug]}),
cuttlefish_unit:assert_config(Config, "riak_kv.storage_backend", riak_kv_eleveldb_backend),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_build_limit", {2, 60000}),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_expire", never),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_concurrency", 1),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_tick", 1000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_data_dir", "/absolute/data/anti_entropy"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.write_buffer_size", 8388608),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.max_open_files", 30),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_enabled", false),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_limits", [{-1, 86400000}, {10, 864000000}]),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.use_bloomfilter", false),
cuttlefish_unit:assert_config(Config, "riak_kv.fsm_limit", 100000),
cuttlefish_unit:assert_config(Config, "riak_kv.retry_put_coordinator_failure", false),
cuttlefish_unit:assert_config(Config, "riak_kv.object_format", v0),
cuttlefish_unit:assert_config(Config, "riak_kv.memory_backend.max_memory", 8192),
cuttlefish_unit:assert_config(Config, "riak_kv.memory_backend.ttl", 86400),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_rejected_max", 10),
make sure multi backend is not on by shell_default
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend_default"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend"),
cuttlefish_unit:assert_config(Config, "riak_kv.secure_referer_check", false),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_object_size", 10485760),
cuttlefish_unit:assert_config(Config, "riak_kv.max_object_size", 104857600),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_siblings", 250),
cuttlefish_unit:assert_config(Config, "riak_kv.max_siblings", 1000),
%% Default Bucket Properties
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pr", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.r", 2),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.w", 4),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pw", all),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dw", all),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.rw", 1),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.notfound_ok", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.basic_quorum", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.allow_mult", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.last_write_wins", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dvv_enabled", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.precommit", [
{struct, [
{<<"mod">>, <<"module">>},
{<<"fun">>, <<"function">>}
]},
{struct, [
{<<"name">>, <<"javascriptFunction">>}
]}]),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.postcommit", [
{struct, [
{<<"mod">>, <<"module2">>},
{<<"fun">>, <<"function2">>}
]}
]),
cuttlefish_unit:assert_config(Config, "riak_dt.binary_compression", false),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_use_background_manager", true),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_use_background_manager", true),
ok.
multi_backend_test() ->
Conf = [
{["storage_backend"], multi},
{["multi_backend", "default"], "backend_one"},
{["multi_backend", "backend_one", "storage_backend"], "memory"},
{["multi_backend", "backend_one", "memory_backend", "max_memory_per_vnode"], "8GB"},
{["multi_backend", "backend_one", "memory_backend", "ttl"], "1d"},
{["multi_backend", "backend_two", "storage_backend"], "memory"}
],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy", {on, []}),
cuttlefish_unit:assert_config(Config, "riak_kv.storage_backend", riak_kv_multi_backend),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_build_limit", {1, 3600000}),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_expire", 604800000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_concurrency", 2),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_tick", 15000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_data_dir", "./data/anti_entropy"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.write_buffer_size", 4194304),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.max_open_files", 20),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_enabled", true),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.aae_throttle_limits"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.use_bloomfilter", true),
cuttlefish_unit:assert_config(Config, "riak_kv.fsm_limit", 50000),
cuttlefish_unit:assert_config(Config, "riak_kv.retry_put_coordinator_failure", true),
cuttlefish_unit:assert_config(Config, "riak_kv.object_format", v1),
cuttlefish_unit:assert_config(Config, "riak_kv.vnode_md_cache_size", 0),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.max_memory"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.ttl"),
cuttlefish_unit:assert_config(Config, "riak_kv.secure_referer_check", true),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_object_size", 5242880),
cuttlefish_unit:assert_config(Config, "riak_kv.max_object_size", 52428800),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_siblings", 25),
cuttlefish_unit:assert_config(Config, "riak_kv.max_siblings", 100),
%% Default Bucket Properties
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pr", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.r", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.w", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pw", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.rw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.notfound_ok", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.basic_quorum", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.allow_mult", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.last_write_wins", false),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.precommit"),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.postcommit"),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dvv_enabled", false),
cuttlefish_unit:assert_config(Config, "riak_dt.binary_compression", 1),
cuttlefish_unit:assert_config(Config, "riak_kv.multi_backend_default", <<"backend_one">>),
ExpectedMutliConfig = [
{<<"backend_one">>, riak_kv_memory_backend, [{ttl, 86400}, {max_memory, 8192}]},
{<<"backend_two">>, riak_kv_memory_backend, []}
],
cuttlefish_unit:assert_config(Config, "riak_kv.multi_backend", ExpectedMutliConfig),
ok.
all_check_window_test() ->
Conf =
[
{["ttaaefs_allcheck", "policy"], window},
{["ttaaefs_allcheck", "window", "start"], 18},
{["ttaaefs_allcheck", "window", "end"], 5}],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.ttaaefs_allcheck_window", {18, 5}).
commit_hooks_test() ->
Conf = [
{["buckets", "default", "precommit"], "bad:mod:fun"},
{["buckets", "default", "postcommit"], "jsLOL"}
],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
?assertEqual({error, apply_translations,
{errorlist, [
{error,
{translation_invalid_configuration,
{"riak_core.default_bucket_props.postcommit",
"incorrect hook format 'jsLOL'"}}},
{error,
{translation_invalid_configuration,
{"riak_core.default_bucket_props.precommit",
"incorrect hook format 'bad:mod:fun'"}}}
]}}, Config).
datatype_compression_validator_test() ->
Conf = [{["datatypes", "compression_level"], 10}],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_error_in_phase(Config, validation),
ok.
correct_error_handling_by_multibackend_test() ->
Conf = [
{["multi_backend", "default", "storage_backend"], bitcask},
{["multi_backend", "default", "bitcask", "data_root"], "/data/default_bitcask"}
],
SchemaPaths = schema_paths() ++ [ "test/bad_bitcask_multi.schema" ],
Config = cuttlefish_unit:generate_templated_config(SchemaPaths,
Conf,
context(),
predefined_schema()),
?assertMatch({error, apply_translations, {errorlist, _}}, Config),
{error, apply_translations, {errorlist, [Error]}} = Config,
?assertMatch({error, {translation_invalid_configuration, _}},
Error),
ok.
all_backend_multi_test() ->
Conf = [
{["storage_backend"], multi},
{["multi_backend", "default"], "bitcask1"},
{["multi_backend", "bitcask1", "storage_backend"], bitcask},
{["multi_backend", "bitcask1", "bitcask", "data_root"], "/data/bitcask1"},
{["multi_backend", "bitcask2", "storage_backend"], bitcask},
{["multi_backend", "bitcask2", "bitcask", "data_root"], "/data/bitcask2"},
{["multi_backend", "level3", "storage_backend"], leveldb},
{["multi_backend", "level3", "leveldb", "data_root"], "/data/level3"},
{["multi_backend", "level4", "storage_backend"], leveldb},
{["multi_backend", "level4", "leveldb", "data_root"], "/data/level4"},
{["multi_backend", "memory5", "storage_backend"], "memory"},
{["multi_backend", "memory5", "memory_backend", "max_memory_per_vnode"], "8GB"},
{["multi_backend", "memory6", "memory_backend", "ttl"], "1d"},
{["multi_backend", "memory6", "storage_backend"], "memory"}
],
SchemaPaths = schema_paths(),
Config = cuttlefish_unit:generate_templated_config(SchemaPaths,
Conf, context(), predefined_schema()),
MultiBackendConfig = proplists:get_value(multi_backend, proplists:get_value(riak_kv, Config)),
{<<"bitcask1">>, riak_kv_bitcask_backend, B1} = lists:keyfind(<<"bitcask1">>, 1, MultiBackendConfig),
{<<"bitcask2">>, riak_kv_bitcask_backend, B2} = lists:keyfind(<<"bitcask2">>, 1, MultiBackendConfig),
{<<"level3">>, riak_kv_eleveldb_backend, L3} = lists:keyfind(<<"level3">>, 1, MultiBackendConfig),
{<<"level4">>, riak_kv_eleveldb_backend, L4} = lists:keyfind(<<"level4">>, 1, MultiBackendConfig),
{<<"memory5">>, riak_kv_memory_backend, M5} = lists:keyfind(<<"memory5">>, 1, MultiBackendConfig),
{<<"memory6">>, riak_kv_memory_backend, M6} = lists:keyfind(<<"memory6">>, 1, MultiBackendConfig),
%% Check B1
cuttlefish_unit:assert_config(B1, "data_root", "/data/bitcask1"),
%% Check B2
cuttlefish_unit:assert_config(B2, "data_root", "/data/bitcask2"),
%% Check L3
cuttlefish_unit:assert_config(L3, "data_root", "/data/level3"),
%% Check L4
cuttlefish_unit:assert_config(L4, "data_root", "/data/level4"),
Check M5
cuttlefish_unit:assert_not_configured(M5, "ttl"),
cuttlefish_unit:assert_config(M5, "max_memory", 8192),
Check M6
cuttlefish_unit:assert_config(M6, "ttl", 86400),
cuttlefish_unit:assert_not_configured(M6, "max_memory"),
ok.
job_class_enabled_test() ->
test_job_class_enabled(riak_core_schema()).
test_job_class_enabled({true, RCSchema}) when erlang:is_list(RCSchema) ->
Config = cuttlefish_unit:generate_templated_config(
[RCSchema, "priv/riak_kv.schema"], [],
riak_core_schema_tests:context() ++ context()),
cuttlefish_unit:assert_config(
Config, "riak_core.job_accept_class",
lists:sort(?DEFAULT_ENABLED_JOB_CLASSES)),
ok;
test_job_class_enabled({error, enoent}) ->
% If riak_core is not present, or eunit hasn't been run there, the
% necessary schema and/or beam file won't be found. If we fail the test
% buildbot won't pass because the riak_core .eunit files haven't been built.
?debugMsg("Supporting riak_core components not present,"
" skipping job_class_enabled test").
%% this context() represents the substitution variables that rebar
%% will use during the build process. riak_core's schema file is
%% written with some {{mustache_vars}} for substitution during
%% packaging cuttlefish doesn't have a great time parsing those, so we
perform the substitutions first , because that 's how it would work
%% in real life.
context() ->
[
{storage_backend, "bitcask"}
].
%% This predefined schema covers riak_kv's dependency on
%% platform_data_dir
predefined_schema() ->
Mapping = cuttlefish_mapping:parse({mapping,
"platform_data_dir",
"riak_core.platform_data_dir", [
{default, "./data"},
{datatype, directory}
]}),
{[], [Mapping], []}.
%% Ensure that the riak_core_schema_tests module is loaded and return the
%% path of the riak_core.schema file.
riak_core_schema() ->
riak_core_schema(riak_core_dir()).
riak_core_schema({RCDir, Schema}) when erlang:is_list(RCDir) ->
case code:ensure_loaded(riak_core_schema_tests) of
{module, _} ->
{true, Schema};
_ ->
Search = filename:join([RCDir, "**", "riak_core_schema_tests.beam"]),
% ?debugFmt("Checking ~s", [Search]),
case filelib:wildcard(Search) of
[Beam | _] ->
% ?debugFmt("Loading ~s", [Beam]),
case code:load_abs(filename:rootname(Beam)) of
{module, _} ->
{true, Schema};
Error ->
Error
end;
[] ->
{error, enoent}
end
end;
riak_core_schema(Error) ->
Error.
riak_core_dir() ->
Dir = get_deps_dir(riak_core),
Schema = filename:join([Dir, "priv", "riak_core.schema"]),
{Dir, Schema}.
get_deps_dir(App) ->
case code:lib_dir(App) of
{error, _} ->
error({not_found, App});
Path ->
filename:dirname(Path)
end.
schema_paths() ->
[
filename:join(code:priv_dir(riak_kv), "riak_kv.schema"),
filename:join(code:priv_dir(riak_kv), "multi_backend.schema"),
filename:join(code:priv_dir(bitcask), "bitcask.schema"),
filename:join(code:priv_dir(bitcask), "bitcask_multi.schema"),
filename:join(code:priv_dir(eleveldb), "eleveldb.schema"),
filename:join(code:priv_dir(eleveldb), "eleveldb_multi.schema")
].
| null | https://raw.githubusercontent.com/basho/riak_kv/0a5f60faeb11a59ce15acf249c9464f58853c609/test/riak_kv_schema_tests.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
basic schema test will check to make sure that all defaults from the schema
make it into the generated app.config
they are the files under test.
Default Bucket Properties
Conf represents the riak.conf file that would be read in by cuttlefish.
this proplists is what would be output by the conf_parse module
Default Bucket Properties
Default Bucket Properties
Default Bucket Properties
Check B1
Check B2
Check L3
Check L4
If riak_core is not present, or eunit hasn't been run there, the
necessary schema and/or beam file won't be found. If we fail the test
buildbot won't pass because the riak_core .eunit files haven't been built.
this context() represents the substitution variables that rebar
will use during the build process. riak_core's schema file is
written with some {{mustache_vars}} for substitution during
packaging cuttlefish doesn't have a great time parsing those, so we
in real life.
This predefined schema covers riak_kv's dependency on
platform_data_dir
Ensure that the riak_core_schema_tests module is loaded and return the
path of the riak_core.schema file.
?debugFmt("Checking ~s", [Search]),
?debugFmt("Loading ~s", [Beam]), | Copyright ( c ) 2013 - 2016 Basho Technologies , Inc.
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(riak_kv_schema_tests).
-include_lib("eunit/include/eunit.hrl").
-compile([export_all, nowarn_export_all]).
-define(DEFAULT_ENABLED_JOB_CLASSES, [
{riak_kv, list_buckets},
{riak_kv, list_keys},
{riak_kv, map_reduce_js},
{riak_kv, map_reduce},
{riak_kv, secondary_index},
{riak_kv, stream_list_buckets},
{riak_kv, stream_list_keys},
{riak_kv, stream_secondary_index}
]).
basic_schema_test() ->
The defaults are defined in priv / riak_kv.schema and multi_backend.schema .
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], [], context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy", {on, []}),
cuttlefish_unit:assert_config(Config, "riak_kv.storage_backend", riak_kv_bitcask_backend),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_build_limit", {1, 3600000}),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_expire", 604800000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_concurrency", 2),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_tick", 15000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_data_dir", "./data/anti_entropy"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.write_buffer_size", 4194304),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.max_open_files", 20),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_enabled", true),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.aae_throttle_limits"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.use_bloomfilter", true),
cuttlefish_unit:assert_config(Config, "riak_kv.fsm_limit", 50000),
cuttlefish_unit:assert_config(Config, "riak_kv.retry_put_coordinator_failure", true),
cuttlefish_unit:assert_config(Config, "riak_kv.object_format", v1),
cuttlefish_unit:assert_config(Config, "riak_kv.vnode_md_cache_size", 0),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.max_memory"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.ttl"),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_rejected_max", 6),
make sure multi backend is not on by shell_default
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend_default"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend"),
cuttlefish_unit:assert_config(Config, "riak_kv.secure_referer_check", true),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_object_size", 5242880),
cuttlefish_unit:assert_config(Config, "riak_kv.max_object_size", 52428800),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_siblings", 25),
cuttlefish_unit:assert_config(Config, "riak_kv.max_siblings", 100),
cuttlefish_unit:assert_config(Config, "riak_kv.ttaaefs_allcheck_window", always),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pr", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.r", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.w", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pw", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.rw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.notfound_ok", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.basic_quorum", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.allow_mult", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.last_write_wins", false),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.precommit"),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.postcommit"),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dvv_enabled", false),
cuttlefish_unit:assert_config(Config, "riak_dt.binary_compression", 1),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_use_background_manager", false),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_use_background_manager", false),
ok.
override_non_multi_backend_schema_test() ->
Conf = [
{["anti_entropy"], 'active-debug'},
{["storage_backend"], leveldb},
{["anti_entropy", "tree", "build_limit", "number"], 2},
{["anti_entropy", "tree", "build_limit", "per_timespan"], "1m"},
{["anti_entropy", "tree", "expiry"], never},
{["anti_entropy", "concurrency_limit"], 1},
{["anti_entropy", "trigger_interval"], "1s"},
{["anti_entropy", "data_dir"], "/absolute/data/anti_entropy"},
{["anti_entropy", "write_buffer_size"], "8MB"},
{["anti_entropy", "max_open_files"], 30},
{["anti_entropy", "throttle"], off},
{["anti_entropy", "throttle", "tier1", "mailbox_size"], 0},
{["anti_entropy", "throttle", "tier1", "delay"], "1d"},
{["anti_entropy", "throttle", "tier2", "mailbox_size"], 11},
{["anti_entropy", "throttle", "tier2", "delay"], "10d"},
{["anti_entropy", "bloomfilter"], off},
{["max_concurrent_requests"], 100000},
{["retry_put_coordinator_failure"], off},
{["object", "format"], 0},
{["metadata_cache_size"], "512KB"},
{["memory_backend", "max_memory_per_vnode"], "8GB"},
{["memory_backend", "ttl"], "1d"},
{["secure_referer_check"], off},
{["object", "size", "warning_threshold"], "10MB"},
{["object", "size", "maximum"], "100MB"},
{["object", "siblings", "warning_threshold"], 250},
{["object", "siblings", "maximum"], 1000},
{["buckets", "default", "merge_strategy"], '2'},
{["buckets", "default", "pr"], quorum},
{["buckets", "default", "r"], 2},
{["buckets", "default", "w"], 4},
{["buckets", "default", "pw"], all},
{["buckets", "default", "dw"], all},
{["buckets", "default", "rw"], 1},
{["buckets", "default", "notfound_ok"], false},
{["buckets", "default", "basic_quorum"], true},
{["buckets", "default", "allow_mult"], true},
{["buckets", "default", "last_write_wins"], true},
{["buckets", "default", "precommit"], "module:function javascriptFunction"},
{["buckets", "default", "postcommit"], "module2:function2"},
{["datatypes", "compression_level"], "off"},
{["handoff", "use_background_manager"], on},
{["handoff", "max_rejects"], 10},
{["anti_entropy", "use_background_manager"], on}
],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy", {on, [debug]}),
cuttlefish_unit:assert_config(Config, "riak_kv.storage_backend", riak_kv_eleveldb_backend),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_build_limit", {2, 60000}),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_expire", never),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_concurrency", 1),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_tick", 1000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_data_dir", "/absolute/data/anti_entropy"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.write_buffer_size", 8388608),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.max_open_files", 30),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_enabled", false),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_limits", [{-1, 86400000}, {10, 864000000}]),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.use_bloomfilter", false),
cuttlefish_unit:assert_config(Config, "riak_kv.fsm_limit", 100000),
cuttlefish_unit:assert_config(Config, "riak_kv.retry_put_coordinator_failure", false),
cuttlefish_unit:assert_config(Config, "riak_kv.object_format", v0),
cuttlefish_unit:assert_config(Config, "riak_kv.memory_backend.max_memory", 8192),
cuttlefish_unit:assert_config(Config, "riak_kv.memory_backend.ttl", 86400),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_rejected_max", 10),
make sure multi backend is not on by shell_default
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend_default"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.multi_backend"),
cuttlefish_unit:assert_config(Config, "riak_kv.secure_referer_check", false),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_object_size", 10485760),
cuttlefish_unit:assert_config(Config, "riak_kv.max_object_size", 104857600),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_siblings", 250),
cuttlefish_unit:assert_config(Config, "riak_kv.max_siblings", 1000),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pr", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.r", 2),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.w", 4),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pw", all),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dw", all),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.rw", 1),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.notfound_ok", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.basic_quorum", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.allow_mult", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.last_write_wins", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dvv_enabled", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.precommit", [
{struct, [
{<<"mod">>, <<"module">>},
{<<"fun">>, <<"function">>}
]},
{struct, [
{<<"name">>, <<"javascriptFunction">>}
]}]),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.postcommit", [
{struct, [
{<<"mod">>, <<"module2">>},
{<<"fun">>, <<"function2">>}
]}
]),
cuttlefish_unit:assert_config(Config, "riak_dt.binary_compression", false),
cuttlefish_unit:assert_config(Config, "riak_kv.handoff_use_background_manager", true),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_use_background_manager", true),
ok.
multi_backend_test() ->
Conf = [
{["storage_backend"], multi},
{["multi_backend", "default"], "backend_one"},
{["multi_backend", "backend_one", "storage_backend"], "memory"},
{["multi_backend", "backend_one", "memory_backend", "max_memory_per_vnode"], "8GB"},
{["multi_backend", "backend_one", "memory_backend", "ttl"], "1d"},
{["multi_backend", "backend_two", "storage_backend"], "memory"}
],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy", {on, []}),
cuttlefish_unit:assert_config(Config, "riak_kv.storage_backend", riak_kv_multi_backend),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_build_limit", {1, 3600000}),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_expire", 604800000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_concurrency", 2),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_tick", 15000),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_data_dir", "./data/anti_entropy"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.write_buffer_size", 4194304),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.max_open_files", 20),
cuttlefish_unit:assert_config(Config, "riak_kv.aae_throttle_enabled", true),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.aae_throttle_limits"),
cuttlefish_unit:assert_config(Config, "riak_kv.anti_entropy_leveldb_opts.use_bloomfilter", true),
cuttlefish_unit:assert_config(Config, "riak_kv.fsm_limit", 50000),
cuttlefish_unit:assert_config(Config, "riak_kv.retry_put_coordinator_failure", true),
cuttlefish_unit:assert_config(Config, "riak_kv.object_format", v1),
cuttlefish_unit:assert_config(Config, "riak_kv.vnode_md_cache_size", 0),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.max_memory"),
cuttlefish_unit:assert_not_configured(Config, "riak_kv.memory_backend.ttl"),
cuttlefish_unit:assert_config(Config, "riak_kv.secure_referer_check", true),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_object_size", 5242880),
cuttlefish_unit:assert_config(Config, "riak_kv.max_object_size", 52428800),
cuttlefish_unit:assert_config(Config, "riak_kv.warn_siblings", 25),
cuttlefish_unit:assert_config(Config, "riak_kv.max_siblings", 100),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pr", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.r", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.w", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.pw", 0),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.rw", quorum),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.notfound_ok", true),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.basic_quorum", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.allow_mult", false),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.last_write_wins", false),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.precommit"),
cuttlefish_unit:assert_not_configured(Config, "riak_core.default_bucket_props.postcommit"),
cuttlefish_unit:assert_config(Config, "riak_core.default_bucket_props.dvv_enabled", false),
cuttlefish_unit:assert_config(Config, "riak_dt.binary_compression", 1),
cuttlefish_unit:assert_config(Config, "riak_kv.multi_backend_default", <<"backend_one">>),
ExpectedMutliConfig = [
{<<"backend_one">>, riak_kv_memory_backend, [{ttl, 86400}, {max_memory, 8192}]},
{<<"backend_two">>, riak_kv_memory_backend, []}
],
cuttlefish_unit:assert_config(Config, "riak_kv.multi_backend", ExpectedMutliConfig),
ok.
all_check_window_test() ->
Conf =
[
{["ttaaefs_allcheck", "policy"], window},
{["ttaaefs_allcheck", "window", "start"], 18},
{["ttaaefs_allcheck", "window", "end"], 5}],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_config(Config, "riak_kv.ttaaefs_allcheck_window", {18, 5}).
commit_hooks_test() ->
Conf = [
{["buckets", "default", "precommit"], "bad:mod:fun"},
{["buckets", "default", "postcommit"], "jsLOL"}
],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
?assertEqual({error, apply_translations,
{errorlist, [
{error,
{translation_invalid_configuration,
{"riak_core.default_bucket_props.postcommit",
"incorrect hook format 'jsLOL'"}}},
{error,
{translation_invalid_configuration,
{"riak_core.default_bucket_props.precommit",
"incorrect hook format 'bad:mod:fun'"}}}
]}}, Config).
datatype_compression_validator_test() ->
Conf = [{["datatypes", "compression_level"], 10}],
Config = cuttlefish_unit:generate_templated_config(
["priv/riak_kv.schema", "priv/multi_backend.schema"], Conf, context(), predefined_schema()),
cuttlefish_unit:assert_error_in_phase(Config, validation),
ok.
correct_error_handling_by_multibackend_test() ->
Conf = [
{["multi_backend", "default", "storage_backend"], bitcask},
{["multi_backend", "default", "bitcask", "data_root"], "/data/default_bitcask"}
],
SchemaPaths = schema_paths() ++ [ "test/bad_bitcask_multi.schema" ],
Config = cuttlefish_unit:generate_templated_config(SchemaPaths,
Conf,
context(),
predefined_schema()),
?assertMatch({error, apply_translations, {errorlist, _}}, Config),
{error, apply_translations, {errorlist, [Error]}} = Config,
?assertMatch({error, {translation_invalid_configuration, _}},
Error),
ok.
all_backend_multi_test() ->
Conf = [
{["storage_backend"], multi},
{["multi_backend", "default"], "bitcask1"},
{["multi_backend", "bitcask1", "storage_backend"], bitcask},
{["multi_backend", "bitcask1", "bitcask", "data_root"], "/data/bitcask1"},
{["multi_backend", "bitcask2", "storage_backend"], bitcask},
{["multi_backend", "bitcask2", "bitcask", "data_root"], "/data/bitcask2"},
{["multi_backend", "level3", "storage_backend"], leveldb},
{["multi_backend", "level3", "leveldb", "data_root"], "/data/level3"},
{["multi_backend", "level4", "storage_backend"], leveldb},
{["multi_backend", "level4", "leveldb", "data_root"], "/data/level4"},
{["multi_backend", "memory5", "storage_backend"], "memory"},
{["multi_backend", "memory5", "memory_backend", "max_memory_per_vnode"], "8GB"},
{["multi_backend", "memory6", "memory_backend", "ttl"], "1d"},
{["multi_backend", "memory6", "storage_backend"], "memory"}
],
SchemaPaths = schema_paths(),
Config = cuttlefish_unit:generate_templated_config(SchemaPaths,
Conf, context(), predefined_schema()),
MultiBackendConfig = proplists:get_value(multi_backend, proplists:get_value(riak_kv, Config)),
{<<"bitcask1">>, riak_kv_bitcask_backend, B1} = lists:keyfind(<<"bitcask1">>, 1, MultiBackendConfig),
{<<"bitcask2">>, riak_kv_bitcask_backend, B2} = lists:keyfind(<<"bitcask2">>, 1, MultiBackendConfig),
{<<"level3">>, riak_kv_eleveldb_backend, L3} = lists:keyfind(<<"level3">>, 1, MultiBackendConfig),
{<<"level4">>, riak_kv_eleveldb_backend, L4} = lists:keyfind(<<"level4">>, 1, MultiBackendConfig),
{<<"memory5">>, riak_kv_memory_backend, M5} = lists:keyfind(<<"memory5">>, 1, MultiBackendConfig),
{<<"memory6">>, riak_kv_memory_backend, M6} = lists:keyfind(<<"memory6">>, 1, MultiBackendConfig),
cuttlefish_unit:assert_config(B1, "data_root", "/data/bitcask1"),
cuttlefish_unit:assert_config(B2, "data_root", "/data/bitcask2"),
cuttlefish_unit:assert_config(L3, "data_root", "/data/level3"),
cuttlefish_unit:assert_config(L4, "data_root", "/data/level4"),
Check M5
cuttlefish_unit:assert_not_configured(M5, "ttl"),
cuttlefish_unit:assert_config(M5, "max_memory", 8192),
Check M6
cuttlefish_unit:assert_config(M6, "ttl", 86400),
cuttlefish_unit:assert_not_configured(M6, "max_memory"),
ok.
job_class_enabled_test() ->
test_job_class_enabled(riak_core_schema()).
test_job_class_enabled({true, RCSchema}) when erlang:is_list(RCSchema) ->
Config = cuttlefish_unit:generate_templated_config(
[RCSchema, "priv/riak_kv.schema"], [],
riak_core_schema_tests:context() ++ context()),
cuttlefish_unit:assert_config(
Config, "riak_core.job_accept_class",
lists:sort(?DEFAULT_ENABLED_JOB_CLASSES)),
ok;
test_job_class_enabled({error, enoent}) ->
?debugMsg("Supporting riak_core components not present,"
" skipping job_class_enabled test").
perform the substitutions first , because that 's how it would work
context() ->
[
{storage_backend, "bitcask"}
].
predefined_schema() ->
Mapping = cuttlefish_mapping:parse({mapping,
"platform_data_dir",
"riak_core.platform_data_dir", [
{default, "./data"},
{datatype, directory}
]}),
{[], [Mapping], []}.
riak_core_schema() ->
riak_core_schema(riak_core_dir()).
riak_core_schema({RCDir, Schema}) when erlang:is_list(RCDir) ->
case code:ensure_loaded(riak_core_schema_tests) of
{module, _} ->
{true, Schema};
_ ->
Search = filename:join([RCDir, "**", "riak_core_schema_tests.beam"]),
case filelib:wildcard(Search) of
[Beam | _] ->
case code:load_abs(filename:rootname(Beam)) of
{module, _} ->
{true, Schema};
Error ->
Error
end;
[] ->
{error, enoent}
end
end;
riak_core_schema(Error) ->
Error.
riak_core_dir() ->
Dir = get_deps_dir(riak_core),
Schema = filename:join([Dir, "priv", "riak_core.schema"]),
{Dir, Schema}.
get_deps_dir(App) ->
case code:lib_dir(App) of
{error, _} ->
error({not_found, App});
Path ->
filename:dirname(Path)
end.
schema_paths() ->
[
filename:join(code:priv_dir(riak_kv), "riak_kv.schema"),
filename:join(code:priv_dir(riak_kv), "multi_backend.schema"),
filename:join(code:priv_dir(bitcask), "bitcask.schema"),
filename:join(code:priv_dir(bitcask), "bitcask_multi.schema"),
filename:join(code:priv_dir(eleveldb), "eleveldb.schema"),
filename:join(code:priv_dir(eleveldb), "eleveldb_multi.schema")
].
|
6f5afdd554c241fefcd06df517230d4c9a5f7d742aa452b29caf42b2a1ec8e0d | migamake/json-autotype | CommonCLI.hs | module CommonCLI(TypeOpts(..), unflag, tyOptParser) where
import Data.Monoid ((<>))
import Options.Applicative
import System.Process (system)
import qualified System.Environment (lookupEnv)
import System.Exit (ExitCode)
import Data.Aeson.AutoType.CodeGen (Lang(..))
data TypeOpts = TyOptions {
autounify :: Bool
, toplevel :: String
, debug :: Bool
, test :: Bool
, suggest :: Bool
, lang :: Lang
}
unflag :: Mod FlagFields Bool -> Parser Bool
unflag = flag True False
tyOptParser :: Parser TypeOpts
tyOptParser = TyOptions
<$> unflag (long "no-autounify" <> help "Do not automatically unify suggested candidates")
<*> strOption (short 't' <>
long "toplevel" <> value "TopLevel"
<> help "Name for toplevel data type")
<*> switch (long "debug" <> help "Set this flag to see more debugging info" )
<*> unflag (long "no-test" <> help "Do not run generated parser afterwards" )
<*> unflag (long "no-suggest" <> help "Do not suggest candidates for unification" )
<*> langOpts
langOpts :: Parser Lang
langOpts = flag Haskell Haskell (long "haskell")
<|> flag Haskell Elm (long "elm")
| null | https://raw.githubusercontent.com/migamake/json-autotype/6244e1f2c0352e9a18657051b65df62b9af157cd/json-autotype/common/CommonCLI.hs | haskell | module CommonCLI(TypeOpts(..), unflag, tyOptParser) where
import Data.Monoid ((<>))
import Options.Applicative
import System.Process (system)
import qualified System.Environment (lookupEnv)
import System.Exit (ExitCode)
import Data.Aeson.AutoType.CodeGen (Lang(..))
data TypeOpts = TyOptions {
autounify :: Bool
, toplevel :: String
, debug :: Bool
, test :: Bool
, suggest :: Bool
, lang :: Lang
}
unflag :: Mod FlagFields Bool -> Parser Bool
unflag = flag True False
tyOptParser :: Parser TypeOpts
tyOptParser = TyOptions
<$> unflag (long "no-autounify" <> help "Do not automatically unify suggested candidates")
<*> strOption (short 't' <>
long "toplevel" <> value "TopLevel"
<> help "Name for toplevel data type")
<*> switch (long "debug" <> help "Set this flag to see more debugging info" )
<*> unflag (long "no-test" <> help "Do not run generated parser afterwards" )
<*> unflag (long "no-suggest" <> help "Do not suggest candidates for unification" )
<*> langOpts
langOpts :: Parser Lang
langOpts = flag Haskell Haskell (long "haskell")
<|> flag Haskell Elm (long "elm")
|
|
2ee687724cb186f4d99f298c0cd7aa363148d5421b74fd22ee6acd6e43aa198b | waddlaw/TAPL | Utils.hs | module Utils (evalAllStrategy) where
import Language.Core.Types
import Language.UntypedLambda
import RIO
import Test.Tasty.HUnit
evalAllStrategy :: UntypedLambda -> UntypedLambda -> IO ()
evalAllStrategy term expected = do
eval NormalOrder term @?= expected
eval CallByName term @?= expected
eval CallByValue term @?= expected
| null | https://raw.githubusercontent.com/waddlaw/TAPL/94576e46821aaf7abce6d1d828fc3ce6d05a40b8/subs/lambda-untyped/test/Utils.hs | haskell | module Utils (evalAllStrategy) where
import Language.Core.Types
import Language.UntypedLambda
import RIO
import Test.Tasty.HUnit
evalAllStrategy :: UntypedLambda -> UntypedLambda -> IO ()
evalAllStrategy term expected = do
eval NormalOrder term @?= expected
eval CallByName term @?= expected
eval CallByValue term @?= expected
|
|
b87cfb49c326957f902f15de317726693ca51527fdd9fb27115233e8feb904d6 | manuel-serrano/bigloo | build.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / comptime / Ast / build.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Fri May 31 14:00:21 1996 * /
* Last change : Tue Apr 19 14:18:41 2016 ( serrano ) * /
;* ------------------------------------------------------------- */
* From the code definition , we build the Ast * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module ast_build
(include "Engine/pass.sch"
"Ast/node.sch")
(import ast_unit
ast_sexp
ast_env
ast_find-gdefs
ast_remove
ast_local
tools_args
tools_progn
tools_location
tools_error
tools_shape)
(export (append-ast::pair-nil ::pair-nil ::pair-nil)
(build-ast ::obj)
(build-ast-sans-remove ::obj)))
;*---------------------------------------------------------------------*/
;* append-ast ... */
;*---------------------------------------------------------------------*/
(define (append-ast a1 a2)
(append a1 a2))
;*---------------------------------------------------------------------*/
;* build-ast ... */
;* ------------------------------------------------------------- */
;* All global variables are now bound, we can now, build the ast. */
;*---------------------------------------------------------------------*/
(define (build-ast units)
(remove-var 'ast (build-ast-sans-remove units)))
;*---------------------------------------------------------------------*/
;* build-ast-sans-remove ... */
;* ------------------------------------------------------------- */
;* All global variables are now bound, we can now, build the ast. */
;*---------------------------------------------------------------------*/
(define (build-ast-sans-remove units)
(pass-prelude "Ast")
there are two separate ` map ' because we ca n't build
;; node of the ast _until_ all the units have been processed
;; (otherwise some global variables could be unbound).
(let* ((nberr *nb-error-on-pass*)
(defs (apply append (map unit->defs units))))
(if (=fx nberr *nb-error-on-pass*)
(begin
;; we can now check if all declared global variables are defined.
(check-to-be-define)
;; and build the regular ast
(let ((ast (map sfun-def->ast defs)))
;; and we return the constructed ast
(pass-postlude ast)))
(pass-postlude '()))))
;*---------------------------------------------------------------------*/
;* sfun-def->ast ... */
;*---------------------------------------------------------------------*/
(define (sfun-def->ast::global def::global)
(enter-function (global-id def))
(unwind-protect
(let* ((sfun (global-value def))
(sfun-args (sfun-args sfun))
(sfun-body-exp (sfun-body sfun))
(def-loc (find-location (global-src def)))
(loc (find-location/loc sfun-body-exp def-loc))
(body (sexp->node sfun-body-exp sfun-args loc 'value)))
(sfun-body-set! sfun body))
(leave-function))
def)
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/comptime/Ast/build.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* append-ast ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* build-ast ... */
* ------------------------------------------------------------- */
* All global variables are now bound, we can now, build the ast. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* build-ast-sans-remove ... */
* ------------------------------------------------------------- */
* All global variables are now bound, we can now, build the ast. */
*---------------------------------------------------------------------*/
node of the ast _until_ all the units have been processed
(otherwise some global variables could be unbound).
we can now check if all declared global variables are defined.
and build the regular ast
and we return the constructed ast
*---------------------------------------------------------------------*/
* sfun-def->ast ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / comptime / Ast / build.scm * /
* Author : * /
* Creation : Fri May 31 14:00:21 1996 * /
* Last change : Tue Apr 19 14:18:41 2016 ( serrano ) * /
* From the code definition , we build the Ast * /
(module ast_build
(include "Engine/pass.sch"
"Ast/node.sch")
(import ast_unit
ast_sexp
ast_env
ast_find-gdefs
ast_remove
ast_local
tools_args
tools_progn
tools_location
tools_error
tools_shape)
(export (append-ast::pair-nil ::pair-nil ::pair-nil)
(build-ast ::obj)
(build-ast-sans-remove ::obj)))
(define (append-ast a1 a2)
(append a1 a2))
(define (build-ast units)
(remove-var 'ast (build-ast-sans-remove units)))
(define (build-ast-sans-remove units)
(pass-prelude "Ast")
there are two separate ` map ' because we ca n't build
(let* ((nberr *nb-error-on-pass*)
(defs (apply append (map unit->defs units))))
(if (=fx nberr *nb-error-on-pass*)
(begin
(check-to-be-define)
(let ((ast (map sfun-def->ast defs)))
(pass-postlude ast)))
(pass-postlude '()))))
(define (sfun-def->ast::global def::global)
(enter-function (global-id def))
(unwind-protect
(let* ((sfun (global-value def))
(sfun-args (sfun-args sfun))
(sfun-body-exp (sfun-body sfun))
(def-loc (find-location (global-src def)))
(loc (find-location/loc sfun-body-exp def-loc))
(body (sexp->node sfun-body-exp sfun-args loc 'value)))
(sfun-body-set! sfun body))
(leave-function))
def)
|
74acbae19d84585c4621dd78b12cad994530608da734f4647998127b2e66afcd | nuprl/gradual-typing-performance | render-utils.rkt | #lang scheme/base
(require "../core.rkt")
(provide part-style?
select-suffix
extract-table-cell-styles
empty-content?)
(define (part-style? p s)
(memq s (style-properties (part-style p))))
(define (select-suffix path suggested-suffixes accepted-suffixes)
(or (ormap (lambda (suggested)
(and (member suggested accepted-suffixes)
(let ([p (bytes->path
(bytes-append (path->bytes (if (string? path)
(string->path path)
path))
(string->bytes/utf-8 suggested)))])
(and (file-exists? p)
p))))
suggested-suffixes)
path))
(define (extract-table-cell-styles t)
(let ([vars (style-properties (table-style t))])
(or (let ([l (ormap (lambda (v)
(and (table-cells? v)
(table-cells-styless v)))
vars)])
(and l
(unless (= (length l) (length (table-blockss t)))
(error 'table
"table-cells property list's length does not match row count: ~e vs. ~e"
l (length (table-blockss t))))
(for-each (lambda (l row)
(unless (= (length l) (length row))
(error 'table
"table-cells property list contains a row whose length does not match the content: ~e vs. ~e"
l (length row))))
l (table-blockss t))
l))
(let ([cols (ormap (lambda (v) (and (table-columns? v) v)) vars)])
(and cols
(let ([cols (table-columns-styles cols)])
(map (lambda (row)
(unless (= (length cols) (length row))
(error 'table
"table-columns property list's length does not match a row length: ~e vs. ~e"
cols (length row)))
cols)
(table-blockss t)))))
(map (lambda (row) (map (lambda (c) plain) row)) (table-blockss t)))))
(define (empty-content? c) (null? c))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/scribble-lib/scribble/private/render-utils.rkt | racket | #lang scheme/base
(require "../core.rkt")
(provide part-style?
select-suffix
extract-table-cell-styles
empty-content?)
(define (part-style? p s)
(memq s (style-properties (part-style p))))
(define (select-suffix path suggested-suffixes accepted-suffixes)
(or (ormap (lambda (suggested)
(and (member suggested accepted-suffixes)
(let ([p (bytes->path
(bytes-append (path->bytes (if (string? path)
(string->path path)
path))
(string->bytes/utf-8 suggested)))])
(and (file-exists? p)
p))))
suggested-suffixes)
path))
(define (extract-table-cell-styles t)
(let ([vars (style-properties (table-style t))])
(or (let ([l (ormap (lambda (v)
(and (table-cells? v)
(table-cells-styless v)))
vars)])
(and l
(unless (= (length l) (length (table-blockss t)))
(error 'table
"table-cells property list's length does not match row count: ~e vs. ~e"
l (length (table-blockss t))))
(for-each (lambda (l row)
(unless (= (length l) (length row))
(error 'table
"table-cells property list contains a row whose length does not match the content: ~e vs. ~e"
l (length row))))
l (table-blockss t))
l))
(let ([cols (ormap (lambda (v) (and (table-columns? v) v)) vars)])
(and cols
(let ([cols (table-columns-styles cols)])
(map (lambda (row)
(unless (= (length cols) (length row))
(error 'table
"table-columns property list's length does not match a row length: ~e vs. ~e"
cols (length row)))
cols)
(table-blockss t)))))
(map (lambda (row) (map (lambda (c) plain) row)) (table-blockss t)))))
(define (empty-content? c) (null? c))
|
|
4f1a78f024d2047164dd3a79cb6daa9c6e4c87e64e71f61e66f8f6f61ca506eb | SKA-ScienceDataProcessor/RC | Vector.hs | # LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE RankNTypes , ScopedTypeVariables #
# LANGUAGE CPP #
{-# LANGUAGE MultiWayIf #-}
module Flow.Vector
( Vector(..)
, vectorSize, vectorByteSize
, nullVector
, castVector
, offsetVector
, peekVector, pokeVector
, makeVector, unmakeVector
, copyVector
-- * Memory Management
, allocCVector
#ifdef USE_CUDA
, allocHostVector, allocDeviceVector
#endif
, freeVector
-- * Conversion
, toCVector, dupCVector
#ifdef USE_CUDA
, toHostVector, dupHostVector
, toDeviceVector, dupDeviceVector
#endif
, unsafeToByteString, unsafeToByteString'
, dumpVector, dumpVector'
, dumpCVectorList, readCVectorList
, readVector, readCVector
, putVector, getVector
) where
import Control.Monad (when, forM_)
import Data.Binary (Binary(..))
import Data.Binary.Put
import Data.Binary.Get
import Data.Int (Int8)
import Data.Typeable (Typeable)
import Data.ByteString (ByteString, hPut)
import Data.ByteString.Unsafe (unsafePackAddressLen, unsafeUseAsCString)
import Foreign.Ptr
import Foreign.C
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array (advancePtr)
import Foreign.Marshal.Utils
#ifdef USE_CUDA
import Foreign.CUDA.Ptr as C
import Foreign.CUDA.Runtime as CUDA hiding (get)
import qualified Data.ByteString.Internal as BSI
#endif
import Foreign.Storable
import GHC.Exts (Ptr(..))
import GHC.Generics (Generic)
import qualified GHC.IO.FD as FD
import qualified GHC.IO.Device as Dev
import System.IO
import System.IO.Unsafe
-- | The alignment that we are going to use for all vectors
vectorAlign :: CUInt
vectorAlign = 32
-- | Vector type. Depending on the requirements of the kernel that
-- uses it, it might have a different underlying pointer type.
data Vector a
= CVector !Int (Ptr a)
#ifdef USE_CUDA
| HostVector !Int (HostPtr a)
| DeviceVector !Int (DevicePtr a)
#endif
deriving (Show, Typeable, Generic)
-- FIXME: No sane binary instance but we need to pass this data type around
instance Binary (Vector a) where
get = error "getting vectors is undefined!"
put = error "putting vectors is undefined!"
-- | Returns the number of elements a vector has. Note that this will
return @0@ for the result of " offsetVector " .
vectorSize :: forall a. Storable a => Vector a -> Int
vectorSize v = (vectorByteSize v) `div` sizeOf (undefined :: a)
-- | Returns the size of the vector in bytes. Note that this will
return @0@ for the result of " offsetVector " .
vectorByteSize :: Vector a -> Int
vectorByteSize (CVector n _) = n
#ifdef USE_CUDA
vectorByteSize (HostVector n _) = n
vectorByteSize (DeviceVector n _) = n
#endif
-- | A vector carrying no data, pointing nowhere
nullVector :: Vector a
nullVector = CVector 0 nullPtr
-- | Cast a vector to a different element type. Moderately evil.
castVector :: Vector a -> Vector b
castVector (CVector n p) = CVector n $ castPtr p
#ifdef USE_CUDA
castVector (HostVector n p) = HostVector n $ HostPtr $ castPtr $ useHostPtr p
castVector (DeviceVector n p) = DeviceVector n $ DevicePtr $ castPtr $ useDevicePtr p
#endif
-- | Make an at-offset vector. Note that this vector will only remain
-- valid as long as the original vector data isn't free.
offsetVector :: Storable a => Vector a -> Int -> Vector a
offsetVector (CVector _ p) off = CVector 0 $ p `advancePtr` off
#ifdef USE_CUDA
offsetVector (HostVector _ p) off = HostVector 0 $ p `advanceHostPtr` off
offsetVector (DeviceVector _ p) off = DeviceVector 0 $ p `advanceDevPtr` off
#endif
-- | Read an element from the vector
peekVector :: Storable a => Vector a -> Int -> IO a
peekVector (CVector _ p) off = peekElemOff p off
#ifdef USE_CUDA
peekVector (HostVector _ p) off = peekElemOff (useHostPtr p) off
peekVector (DeviceVector _ _) _ = error "Attempted to peek device vector!"
#endif
-- | Write an element to a vector
pokeVector :: Storable a => Vector a -> Int -> a -> IO ()
pokeVector (CVector _ p) off = pokeElemOff p off
#ifdef USE_CUDA
pokeVector (HostVector _ p) off = pokeElemOff (useHostPtr p) off
pokeVector (DeviceVector _ _) _ = error "Attempted to poke device vector!"
#endif
-- | Make a vector populated with values from the given list
makeVector :: Storable a => (Int -> IO (Vector a)) -> [a] -> IO (Vector a)
makeVector alloc vs = do
let len = length vs
vec <- alloc len
forM_ (zip [0..len-1] vs) $ uncurry (pokeVector vec)
return vec
-- | Show vector contents
unmakeVector :: Storable a => Vector a -> Int -> Int -> IO [a]
#ifdef USE_CUDA
unmakeVector (DeviceVector _ p) off len = do
v' <- dupCVector (DeviceVector len (p `advanceDevPtr` off))
r <- unmakeVector v' 0 len
freeVector v'
return r
#endif
unmakeVector v off len = do
(CVector _ p) <- toCVector v
mapM (peekElemOff p) [off..off+len-1]
| Copies a portion of one vector into another vector
copyVector :: forall a. Storable a
=> Vector a -- ^ Output vector
-> Int -- ^ Output offset
-> Vector a -- ^ Input vector
-> Int -- ^ Input offset
-> Int -- ^ Input length
-> IO ()
copyVector (CVector _ outp) outoff (CVector _ inp) inoff inl
= copyBytes (outp `advancePtr` outoff) (inp `advancePtr` inoff) (inl * sizeOf (undefined :: a))
#ifdef USE_CUDA
copyVector _ _ _ _ _
= fail "copyVector only supported to C vectors so far - TODO!"
#endif
-- | Allocate a C vector using @malloc@ that is large enough for the
-- given number of elements. The returned vector will be aligned
-- according to "vectorAlign".
allocCVector :: forall a. Storable a => Int -> IO (Vector a)
#ifdef mingw32_HOST_OS
On Windows we can use _ aligned_malloc directly
allocCVector n = fmap (CVector vs) $ c_aligned_malloc (fromIntegral vs) vectorAlign
where vs = n * sizeOf (undefined :: a)
foreign import ccall unsafe "_aligned_malloc"
c_aligned_malloc :: CUInt -> CUInt -> IO (Ptr a)
#else
-- The POSIX version is slightly less nice because just "memalign" is
-- apparently obsolete.
allocCVector n = alloca $ \pp -> do
let vs = n * sizeOf (undefined :: a)
ret <- c_posix_memalign pp vectorAlign (fromIntegral vs)
when (ret /= 0) $
ioError $ errnoToIOError "allocCVector" (Errno ret) Nothing Nothing
p <- peek pp
return $ CVector vs p
foreign import ccall unsafe "posix_memalign"
c_posix_memalign :: Ptr (Ptr a) -> CUInt -> CUInt -> IO CInt
#endif
#ifdef USE_CUDA
-- | Allocate a CUDA host vector in pinned memory with the given
-- number of elements.
allocHostVector :: forall a. Storable a => Int -> IO (Vector a)
allocHostVector n = fmap (HostVector (n * sizeOf (undefined :: a))) $ mallocHostArray [] n
-- | Allocate a CUDA device array with the given number of elements
allocDeviceVector :: forall a. Storable a => Int -> IO (Vector a)
allocDeviceVector n = fmap (DeviceVector (n * sizeOf (undefined :: a))) $ CUDA.mallocArray n
#endif
-- | Free data associated with the vector. It is generally required to
-- call this manually, or the data will remain valid!
--
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "_aligned_free" c_aligned_free :: Ptr a -> IO ()
#endif
-- This function will do nothing for vectors obtained using
-- @nullVector@ or @offsetVector@.
freeVector :: Vector a -> IO ()
freeVector (CVector 0 _) = return ()
freeVector (CVector _ ptr) =
#ifndef mingw32_HOST_OS
Foreign.Marshal.Alloc.free ptr
#else
c_aligned_free ptr
#endif
#ifdef USE_CUDA
freeVector (HostVector 0 _) = return ()
freeVector (HostVector _ ptr) = freeHost ptr
freeVector (DeviceVector 0 _) = return ()
freeVector (DeviceVector _ ptr) = CUDA.free ptr
#endif
-- | Convert the given vector into a C vector. The passed vector is
-- consumed.
toCVector :: Storable a => Vector a -> IO (Vector a)
toCVector v@CVector{} = return v
#ifdef USE_CUDA
toCVector (HostVector n p) = return $ CVector n (useHostPtr p)
Can use a host ptr as C ptr
toCVector v = do v' <- dupCVector v; freeVector v; return v'
Slightly non - puristic signature ( second Int parameter )
foreign import ccall unsafe cudaHostRegister :: Ptr a -> Int -> CUInt -> IO CInt
-- | Convert the given vector into a host vector. The passed vector is
-- consumed.
toHostVector :: forall a. Storable a => Vector a -> IO (Vector a)
toHostVector v@HostVector{} = return v
toHostVector v@(CVector n p) = do _ <- cudaHostRegister p (vectorByteSize v) 0
return (HostVector n (HostPtr p))
toHostVector v = do v' <- dupHostVector v; freeVector v; return v'
-- | Convert the given vector into a device vector. The passed vector
-- is consumed.
toDeviceVector :: forall a. Storable a => Vector a -> IO (Vector a)
toDeviceVector v@DeviceVector{} = return v
toDeviceVector v = do v' <- dupDeviceVector v; freeVector v; return v'
#endif
-- | Create a copy of the given vector as a C vector. Leaves the
-- original vector intact.
dupCVector :: forall a. Storable a => Vector a -> IO (Vector a)
dupCVector v = do
v'@(CVector _ p') <- allocCVector (vectorSize v)
case v of
CVector _ p -> copyBytes p' p (vectorByteSize v)
#ifdef USE_CUDA
HostVector _ p -> copyBytes p' (useHostPtr p) (vectorByteSize v)
DeviceVector _ p -> peekArray (vectorSize v) p p'
#endif
return v'
#ifdef USE_CUDA
-- | Create a copy of the given vector as a host vector. Leaves the
-- original vector intact.
dupHostVector :: Storable a => Vector a -> IO (Vector a)
dupHostVector v@(CVector _ p) = do
v'@(HostVector _ p') <- allocHostVector (vectorSize v)
copyBytes (useHostPtr p') p (vectorByteSize v)
return v'
dupHostVector v@(HostVector _ p) = do
v'@(HostVector _ p') <- allocHostVector (vectorSize v)
copyBytes (useHostPtr p') (useHostPtr p) (vectorByteSize v)
return v'
dupHostVector v@(DeviceVector _ p) = do
v'@(HostVector _ p') <- allocHostVector (vectorSize v)
peekArray (vectorSize v) p (useHostPtr p')
return v'
-- | Create a copy of the given vector as a device vector. Leaves the
-- original vector intact.
dupDeviceVector :: Storable a => Vector a -> IO (Vector a)
dupDeviceVector v@(CVector _ p) = do
v'@(DeviceVector _ p') <- allocDeviceVector (vectorSize v)
pokeArray (vectorSize v) p p'
return v'
dupDeviceVector v@(HostVector _ p) = do
v'@(DeviceVector _ p') <- allocDeviceVector (vectorSize v)
pokeArray (vectorSize v) (useHostPtr p) p'
return v'
dupDeviceVector v@(DeviceVector _ p) = do
v'@(DeviceVector _ p') <- allocDeviceVector (vectorSize v)
copyArray (vectorSize v) p p'
return v'
#endif
-- | Turn a vector into a bytestring referencing the same data. This
-- is unsafe insofar that changes to the vector might change the
-- bytestring, and freeing it might cause crashes.
unsafeToByteString :: Storable a => Vector a -> IO ByteString
unsafeToByteString v = unsafeToByteString' v 0 (vectorSize v)
-- | As @unsafeByteString@, but allows specifying the vector's offset
-- and size.
unsafeToByteString' :: forall a. Storable a => Vector a -> Int -> Int -> IO ByteString
unsafeToByteString' (CVector _ p) off size =
case p `advancePtr` off of
Ptr addr -> unsafePackAddressLen (size * sizeOf (undefined :: a)) addr
#ifdef USE_CUDA
unsafeToByteString' (HostVector _ (HostPtr p)) off size =
case p `advancePtr` off of
Ptr addr -> unsafePackAddressLen (size * sizeOf (undefined :: a)) addr
unsafeToByteString' (DeviceVector _ p) off size =
BSI.create (size * sizeOf (undefined :: a)) $ \p' ->
CUDA.sync >> peekArray size (p `advanceDevPtr` off) (castPtr p')
#endif
-- | Write vector to a file (raw)
dumpVector :: Storable a => Vector a -> FilePath -> IO ()
dumpVector v file =
withBinaryFile file WriteMode $ \h ->
hPut h =<< unsafeToByteString v
dumpCVectorList :: [Vector a] -> FilePath -> IO ()
dumpCVectorList vs file = do
withBinaryFile file WriteMode $ \h -> alloca $ \sizebuf -> do
let dumpVec (CVector n p) = do
poke sizebuf n
hPutBuf h sizebuf (sizeOf (undefined :: Int))
hPutBuf h p n
dumpVec _ = fail "Not a C Vector!"
mapM_ dumpVec vs
readCVectorList :: FilePath -> IO [Vector a]
readCVectorList file = do
fmap reverse readAll
where
readAll = withBinaryFile file ReadMode $ \h -> alloca $ \sizebuf ->
let readVec vs = do
r <- hGetBuf h sizebuf sizeOfInt
if | r == 0 -> return vs
| r < sizeOfInt -> fail $ "Bad size: can't read CVector list from " ++ file
| otherwise -> do
n <- peek sizebuf
v@(CVector _ p) <- allocCVector n :: IO (Vector Int8)
nb <- hGetBuf h p n
if nb < n
then fail $ "Bad vector data: can't read CVector list from " ++ file
else readVec (castVector v:vs)
in readVec []
sizeOfInt = sizeOf (undefined :: Int)
-- | Write vector to a file (raw)
dumpVector' :: Storable a => Vector a -> Int -> Int -> FilePath -> IO ()
dumpVector' v off size file = do
withBinaryFile file WriteMode $ \h ->
hPut h =<< unsafeToByteString' v off size
-- | Read vector from a file (raw)
readVector :: Storable a => Vector a -> FilePath -> Int -> IO ()
readVector v@(CVector _ p) file n | n <= vectorSize v = do
(fd,_) <- FD.openFile file ReadMode False
bytes <- Dev.read fd (castPtr p) (vectorByteSize v)
when (bytes /= 0 && bytes /= vectorByteSize v) $
fail $ "readCVector: Expected to read " ++ show (vectorByteSize v) ++
" bytes, but only received " ++ show bytes ++ "!"
Dev.close fd
readVector _ _ _ = fail "readVector: Wrong vector type or too small!"
-- | Read new C vector from a file (raw)
readCVector :: Storable a => FilePath -> Int -> IO (Vector a)
readCVector file n = do
v <- allocCVector n
readVector v file n
return v
putVector :: Vector a -> Put
putVector vec = do
let vec' = castVector vec :: Vector Int8
bs = unsafePerformIO $ unsafeToByteString vec'
Apparently this already gets emitted by BS put ?
put ( vectorByteSize )
put bs
getVector :: Get (Vector a)
getVector = do
size <- get :: Get Int
bs <- getByteString size
return $ unsafePerformIO $ do
vec@(CVector _ vp) <- allocCVector size :: IO (Vector Int8)
unsafeUseAsCString bs $ \p -> copyBytes vp (castPtr p) size
return (castVector vec)
| null | https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS6/dna/flow/Flow/Vector.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE MultiWayIf #
* Memory Management
* Conversion
| The alignment that we are going to use for all vectors
| Vector type. Depending on the requirements of the kernel that
uses it, it might have a different underlying pointer type.
FIXME: No sane binary instance but we need to pass this data type around
| Returns the number of elements a vector has. Note that this will
| Returns the size of the vector in bytes. Note that this will
| A vector carrying no data, pointing nowhere
| Cast a vector to a different element type. Moderately evil.
| Make an at-offset vector. Note that this vector will only remain
valid as long as the original vector data isn't free.
| Read an element from the vector
| Write an element to a vector
| Make a vector populated with values from the given list
| Show vector contents
^ Output vector
^ Output offset
^ Input vector
^ Input offset
^ Input length
| Allocate a C vector using @malloc@ that is large enough for the
given number of elements. The returned vector will be aligned
according to "vectorAlign".
The POSIX version is slightly less nice because just "memalign" is
apparently obsolete.
| Allocate a CUDA host vector in pinned memory with the given
number of elements.
| Allocate a CUDA device array with the given number of elements
| Free data associated with the vector. It is generally required to
call this manually, or the data will remain valid!
This function will do nothing for vectors obtained using
@nullVector@ or @offsetVector@.
| Convert the given vector into a C vector. The passed vector is
consumed.
| Convert the given vector into a host vector. The passed vector is
consumed.
| Convert the given vector into a device vector. The passed vector
is consumed.
| Create a copy of the given vector as a C vector. Leaves the
original vector intact.
| Create a copy of the given vector as a host vector. Leaves the
original vector intact.
| Create a copy of the given vector as a device vector. Leaves the
original vector intact.
| Turn a vector into a bytestring referencing the same data. This
is unsafe insofar that changes to the vector might change the
bytestring, and freeing it might cause crashes.
| As @unsafeByteString@, but allows specifying the vector's offset
and size.
| Write vector to a file (raw)
| Write vector to a file (raw)
| Read vector from a file (raw)
| Read new C vector from a file (raw) | # LANGUAGE DeriveGeneric #
# LANGUAGE RankNTypes , ScopedTypeVariables #
# LANGUAGE CPP #
module Flow.Vector
( Vector(..)
, vectorSize, vectorByteSize
, nullVector
, castVector
, offsetVector
, peekVector, pokeVector
, makeVector, unmakeVector
, copyVector
, allocCVector
#ifdef USE_CUDA
, allocHostVector, allocDeviceVector
#endif
, freeVector
, toCVector, dupCVector
#ifdef USE_CUDA
, toHostVector, dupHostVector
, toDeviceVector, dupDeviceVector
#endif
, unsafeToByteString, unsafeToByteString'
, dumpVector, dumpVector'
, dumpCVectorList, readCVectorList
, readVector, readCVector
, putVector, getVector
) where
import Control.Monad (when, forM_)
import Data.Binary (Binary(..))
import Data.Binary.Put
import Data.Binary.Get
import Data.Int (Int8)
import Data.Typeable (Typeable)
import Data.ByteString (ByteString, hPut)
import Data.ByteString.Unsafe (unsafePackAddressLen, unsafeUseAsCString)
import Foreign.Ptr
import Foreign.C
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array (advancePtr)
import Foreign.Marshal.Utils
#ifdef USE_CUDA
import Foreign.CUDA.Ptr as C
import Foreign.CUDA.Runtime as CUDA hiding (get)
import qualified Data.ByteString.Internal as BSI
#endif
import Foreign.Storable
import GHC.Exts (Ptr(..))
import GHC.Generics (Generic)
import qualified GHC.IO.FD as FD
import qualified GHC.IO.Device as Dev
import System.IO
import System.IO.Unsafe
vectorAlign :: CUInt
vectorAlign = 32
data Vector a
= CVector !Int (Ptr a)
#ifdef USE_CUDA
| HostVector !Int (HostPtr a)
| DeviceVector !Int (DevicePtr a)
#endif
deriving (Show, Typeable, Generic)
instance Binary (Vector a) where
get = error "getting vectors is undefined!"
put = error "putting vectors is undefined!"
return @0@ for the result of " offsetVector " .
vectorSize :: forall a. Storable a => Vector a -> Int
vectorSize v = (vectorByteSize v) `div` sizeOf (undefined :: a)
return @0@ for the result of " offsetVector " .
vectorByteSize :: Vector a -> Int
vectorByteSize (CVector n _) = n
#ifdef USE_CUDA
vectorByteSize (HostVector n _) = n
vectorByteSize (DeviceVector n _) = n
#endif
nullVector :: Vector a
nullVector = CVector 0 nullPtr
castVector :: Vector a -> Vector b
castVector (CVector n p) = CVector n $ castPtr p
#ifdef USE_CUDA
castVector (HostVector n p) = HostVector n $ HostPtr $ castPtr $ useHostPtr p
castVector (DeviceVector n p) = DeviceVector n $ DevicePtr $ castPtr $ useDevicePtr p
#endif
offsetVector :: Storable a => Vector a -> Int -> Vector a
offsetVector (CVector _ p) off = CVector 0 $ p `advancePtr` off
#ifdef USE_CUDA
offsetVector (HostVector _ p) off = HostVector 0 $ p `advanceHostPtr` off
offsetVector (DeviceVector _ p) off = DeviceVector 0 $ p `advanceDevPtr` off
#endif
peekVector :: Storable a => Vector a -> Int -> IO a
peekVector (CVector _ p) off = peekElemOff p off
#ifdef USE_CUDA
peekVector (HostVector _ p) off = peekElemOff (useHostPtr p) off
peekVector (DeviceVector _ _) _ = error "Attempted to peek device vector!"
#endif
pokeVector :: Storable a => Vector a -> Int -> a -> IO ()
pokeVector (CVector _ p) off = pokeElemOff p off
#ifdef USE_CUDA
pokeVector (HostVector _ p) off = pokeElemOff (useHostPtr p) off
pokeVector (DeviceVector _ _) _ = error "Attempted to poke device vector!"
#endif
makeVector :: Storable a => (Int -> IO (Vector a)) -> [a] -> IO (Vector a)
makeVector alloc vs = do
let len = length vs
vec <- alloc len
forM_ (zip [0..len-1] vs) $ uncurry (pokeVector vec)
return vec
unmakeVector :: Storable a => Vector a -> Int -> Int -> IO [a]
#ifdef USE_CUDA
unmakeVector (DeviceVector _ p) off len = do
v' <- dupCVector (DeviceVector len (p `advanceDevPtr` off))
r <- unmakeVector v' 0 len
freeVector v'
return r
#endif
unmakeVector v off len = do
(CVector _ p) <- toCVector v
mapM (peekElemOff p) [off..off+len-1]
| Copies a portion of one vector into another vector
copyVector :: forall a. Storable a
-> IO ()
copyVector (CVector _ outp) outoff (CVector _ inp) inoff inl
= copyBytes (outp `advancePtr` outoff) (inp `advancePtr` inoff) (inl * sizeOf (undefined :: a))
#ifdef USE_CUDA
copyVector _ _ _ _ _
= fail "copyVector only supported to C vectors so far - TODO!"
#endif
allocCVector :: forall a. Storable a => Int -> IO (Vector a)
#ifdef mingw32_HOST_OS
On Windows we can use _ aligned_malloc directly
allocCVector n = fmap (CVector vs) $ c_aligned_malloc (fromIntegral vs) vectorAlign
where vs = n * sizeOf (undefined :: a)
foreign import ccall unsafe "_aligned_malloc"
c_aligned_malloc :: CUInt -> CUInt -> IO (Ptr a)
#else
allocCVector n = alloca $ \pp -> do
let vs = n * sizeOf (undefined :: a)
ret <- c_posix_memalign pp vectorAlign (fromIntegral vs)
when (ret /= 0) $
ioError $ errnoToIOError "allocCVector" (Errno ret) Nothing Nothing
p <- peek pp
return $ CVector vs p
foreign import ccall unsafe "posix_memalign"
c_posix_memalign :: Ptr (Ptr a) -> CUInt -> CUInt -> IO CInt
#endif
#ifdef USE_CUDA
allocHostVector :: forall a. Storable a => Int -> IO (Vector a)
allocHostVector n = fmap (HostVector (n * sizeOf (undefined :: a))) $ mallocHostArray [] n
allocDeviceVector :: forall a. Storable a => Int -> IO (Vector a)
allocDeviceVector n = fmap (DeviceVector (n * sizeOf (undefined :: a))) $ CUDA.mallocArray n
#endif
#ifdef mingw32_HOST_OS
foreign import ccall unsafe "_aligned_free" c_aligned_free :: Ptr a -> IO ()
#endif
freeVector :: Vector a -> IO ()
freeVector (CVector 0 _) = return ()
freeVector (CVector _ ptr) =
#ifndef mingw32_HOST_OS
Foreign.Marshal.Alloc.free ptr
#else
c_aligned_free ptr
#endif
#ifdef USE_CUDA
freeVector (HostVector 0 _) = return ()
freeVector (HostVector _ ptr) = freeHost ptr
freeVector (DeviceVector 0 _) = return ()
freeVector (DeviceVector _ ptr) = CUDA.free ptr
#endif
toCVector :: Storable a => Vector a -> IO (Vector a)
toCVector v@CVector{} = return v
#ifdef USE_CUDA
toCVector (HostVector n p) = return $ CVector n (useHostPtr p)
Can use a host ptr as C ptr
toCVector v = do v' <- dupCVector v; freeVector v; return v'
Slightly non - puristic signature ( second Int parameter )
foreign import ccall unsafe cudaHostRegister :: Ptr a -> Int -> CUInt -> IO CInt
toHostVector :: forall a. Storable a => Vector a -> IO (Vector a)
toHostVector v@HostVector{} = return v
toHostVector v@(CVector n p) = do _ <- cudaHostRegister p (vectorByteSize v) 0
return (HostVector n (HostPtr p))
toHostVector v = do v' <- dupHostVector v; freeVector v; return v'
toDeviceVector :: forall a. Storable a => Vector a -> IO (Vector a)
toDeviceVector v@DeviceVector{} = return v
toDeviceVector v = do v' <- dupDeviceVector v; freeVector v; return v'
#endif
dupCVector :: forall a. Storable a => Vector a -> IO (Vector a)
dupCVector v = do
v'@(CVector _ p') <- allocCVector (vectorSize v)
case v of
CVector _ p -> copyBytes p' p (vectorByteSize v)
#ifdef USE_CUDA
HostVector _ p -> copyBytes p' (useHostPtr p) (vectorByteSize v)
DeviceVector _ p -> peekArray (vectorSize v) p p'
#endif
return v'
#ifdef USE_CUDA
dupHostVector :: Storable a => Vector a -> IO (Vector a)
dupHostVector v@(CVector _ p) = do
v'@(HostVector _ p') <- allocHostVector (vectorSize v)
copyBytes (useHostPtr p') p (vectorByteSize v)
return v'
dupHostVector v@(HostVector _ p) = do
v'@(HostVector _ p') <- allocHostVector (vectorSize v)
copyBytes (useHostPtr p') (useHostPtr p) (vectorByteSize v)
return v'
dupHostVector v@(DeviceVector _ p) = do
v'@(HostVector _ p') <- allocHostVector (vectorSize v)
peekArray (vectorSize v) p (useHostPtr p')
return v'
dupDeviceVector :: Storable a => Vector a -> IO (Vector a)
dupDeviceVector v@(CVector _ p) = do
v'@(DeviceVector _ p') <- allocDeviceVector (vectorSize v)
pokeArray (vectorSize v) p p'
return v'
dupDeviceVector v@(HostVector _ p) = do
v'@(DeviceVector _ p') <- allocDeviceVector (vectorSize v)
pokeArray (vectorSize v) (useHostPtr p) p'
return v'
dupDeviceVector v@(DeviceVector _ p) = do
v'@(DeviceVector _ p') <- allocDeviceVector (vectorSize v)
copyArray (vectorSize v) p p'
return v'
#endif
unsafeToByteString :: Storable a => Vector a -> IO ByteString
unsafeToByteString v = unsafeToByteString' v 0 (vectorSize v)
unsafeToByteString' :: forall a. Storable a => Vector a -> Int -> Int -> IO ByteString
unsafeToByteString' (CVector _ p) off size =
case p `advancePtr` off of
Ptr addr -> unsafePackAddressLen (size * sizeOf (undefined :: a)) addr
#ifdef USE_CUDA
unsafeToByteString' (HostVector _ (HostPtr p)) off size =
case p `advancePtr` off of
Ptr addr -> unsafePackAddressLen (size * sizeOf (undefined :: a)) addr
unsafeToByteString' (DeviceVector _ p) off size =
BSI.create (size * sizeOf (undefined :: a)) $ \p' ->
CUDA.sync >> peekArray size (p `advanceDevPtr` off) (castPtr p')
#endif
dumpVector :: Storable a => Vector a -> FilePath -> IO ()
dumpVector v file =
withBinaryFile file WriteMode $ \h ->
hPut h =<< unsafeToByteString v
dumpCVectorList :: [Vector a] -> FilePath -> IO ()
dumpCVectorList vs file = do
withBinaryFile file WriteMode $ \h -> alloca $ \sizebuf -> do
let dumpVec (CVector n p) = do
poke sizebuf n
hPutBuf h sizebuf (sizeOf (undefined :: Int))
hPutBuf h p n
dumpVec _ = fail "Not a C Vector!"
mapM_ dumpVec vs
readCVectorList :: FilePath -> IO [Vector a]
readCVectorList file = do
fmap reverse readAll
where
readAll = withBinaryFile file ReadMode $ \h -> alloca $ \sizebuf ->
let readVec vs = do
r <- hGetBuf h sizebuf sizeOfInt
if | r == 0 -> return vs
| r < sizeOfInt -> fail $ "Bad size: can't read CVector list from " ++ file
| otherwise -> do
n <- peek sizebuf
v@(CVector _ p) <- allocCVector n :: IO (Vector Int8)
nb <- hGetBuf h p n
if nb < n
then fail $ "Bad vector data: can't read CVector list from " ++ file
else readVec (castVector v:vs)
in readVec []
sizeOfInt = sizeOf (undefined :: Int)
dumpVector' :: Storable a => Vector a -> Int -> Int -> FilePath -> IO ()
dumpVector' v off size file = do
withBinaryFile file WriteMode $ \h ->
hPut h =<< unsafeToByteString' v off size
readVector :: Storable a => Vector a -> FilePath -> Int -> IO ()
readVector v@(CVector _ p) file n | n <= vectorSize v = do
(fd,_) <- FD.openFile file ReadMode False
bytes <- Dev.read fd (castPtr p) (vectorByteSize v)
when (bytes /= 0 && bytes /= vectorByteSize v) $
fail $ "readCVector: Expected to read " ++ show (vectorByteSize v) ++
" bytes, but only received " ++ show bytes ++ "!"
Dev.close fd
readVector _ _ _ = fail "readVector: Wrong vector type or too small!"
readCVector :: Storable a => FilePath -> Int -> IO (Vector a)
readCVector file n = do
v <- allocCVector n
readVector v file n
return v
putVector :: Vector a -> Put
putVector vec = do
let vec' = castVector vec :: Vector Int8
bs = unsafePerformIO $ unsafeToByteString vec'
Apparently this already gets emitted by BS put ?
put ( vectorByteSize )
put bs
getVector :: Get (Vector a)
getVector = do
size <- get :: Get Int
bs <- getByteString size
return $ unsafePerformIO $ do
vec@(CVector _ vp) <- allocCVector size :: IO (Vector Int8)
unsafeUseAsCString bs $ \p -> copyBytes vp (castPtr p) size
return (castVector vec)
|
4a8a55f783f3887edbc5089a41a4dd5ed7ac0501a451916f0d2d277842fec104 | apache/couchdb-couch-mrview | couch_mrview_changes_since_tests.erl | 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(couch_mrview_changes_since_tests).
-include_lib("couch/include/couch_eunit.hrl").
-include_lib("couch/include/couch_db.hrl").
-define(TIMEOUT, 1000).
setup() ->
{ok, Db} = couch_mrview_test_util:init_db(?tempdb(), changes),
Db.
teardown(Db) ->
couch_db:close(Db),
couch_server:delete(Db#db.name, [?ADMIN_CTX]),
ok.
changes_since_test() ->
{
"changes_since tests",
{
setup,
fun test_util:start_couch/0, fun test_util:stop_couch/1,
{
foreach,
fun setup/0, fun teardown/1,
[
fun test_basic/1,
fun test_range/1,
fun test_basic_since/1,
fun test_range_since/1,
fun test_basic_count/1,
fun test_range_count/1,
fun test_basic_count_since/1,
fun test_range_count_since/1,
fun test_compact/1,
fun test_remove_key/1
]
}
}
}.
test_basic(Db) ->
Result = run_query(Db, 0, []),
Expect = {ok, [
{{2, 1, <<"1">>}, 1},
{{3, 10, <<"10">>}, 10},
{{4, 2, <<"2">>}, 2},
{{5, 3, <<"3">>}, 3},
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5},
{{8, 6, <<"6">>}, 6},
{{9, 7, <<"7">>}, 7},
{{10, 8, <<"8">>}, 8},
{{11, 9, <<"9">>}, 9}
]},
?_assertEqual(Result, Expect).
test_range(Db) ->
Result = run_query(Db, 0, [{start_key, 3}, {end_key, 5}]),
Expect = {ok, [
{{5, 3, <<"3">>}, 3},
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5}
]},
?_assertEqual(Result, Expect).
test_basic_since(Db) ->
Result = run_query(Db, 5, []),
Expect = {ok, [
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5},
{{8, 6, <<"6">>}, 6},
{{9, 7, <<"7">>}, 7},
{{10, 8, <<"8">>}, 8},
{{11, 9, <<"9">>}, 9}
]},
?_assertEqual(Result, Expect).
test_range_since(Db) ->
Result = run_query(Db, 5, [{start_key, 3}, {end_key, 5}]),
Expect = {ok, [
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5}
]},
?_assertEqual(Result, Expect).
test_basic_count(Db) ->
Result = run_count_query(Db, 0, []),
?_assertEqual(Result, 10).
test_range_count(Db) ->
Result = run_count_query(Db, 0, [{start_key, 3}, {end_key, 5}]),
?_assertEqual(Result, 3).
test_basic_count_since(Db) ->
Result = run_count_query(Db, 5, []),
?_assertEqual(Result, 6).
test_range_count_since(Db) ->
Result = run_count_query(Db, 5, [{start_key, 3}, {end_key, 5}]),
?_assertEqual(Result, 2).
test_compact(Db) ->
Result = couch_mrview:compact(Db, <<"_design/bar">>),
?_assertEqual(Result, ok),
Count = run_count_query(Db, 0, []),
?_assertEqual(Count, 10).
test_remove_key(Db) ->
%% add new doc
Doc = couch_mrview_test_util:doc(11),
{ok, Rev} = couch_db:update_doc(Db, Doc, []),
RevStr = couch_doc:rev_to_str(Rev),
{ok, _} = couch_db:ensure_full_commit(Db),
{ok, Db1} = couch_db:reopen(Db),
Result = run_count_query(Db1, 0, []),
?_assertEqual(Result, 11),
%% check new view key
Result1 = run_query(Db1, 0, [{start_key, 11}, {end_key, 11}]),
Expect = {ok, [
{{12, 11, <<"11">>}, 11}
]},
?_assertEqual(Result1, Expect),
%% delete doc
Doc2 = couch_doc:from_json_obj({[
{<<"_id">>, <<"11">>},
{<<"_rev">>, RevStr},
{<<"_deleted">>, true}
]}),
{ok, _} = couch_db:update_doc(Db1, Doc2, []),
{ok, Db2} = couch_db:reopen(Db1),
Result2 = run_count_query(Db2, 0, []),
?_assertEqual(Result2, 11),
%% check new view key
Result3 = run_query(Db2, 0, [{start_key, 11}, {end_key, 11}]),
Expect2 = {ok, [
{{13, 11, <<"11">>}, {[{<<"_removed">>, true}]}}
]},
?_assertEqual(Result3, Expect2).
run_query(Db, Since, Opts) ->
Fun = fun(KV, Acc) -> {ok, [KV | Acc]} end,
{ok, R} = couch_mrview:view_changes_since(Db, <<"_design/bar">>, <<"baz">>,
Since, Fun, Opts, []),
{ok, lists:reverse(R)}.
run_count_query(Db, Since, Opts) ->
couch_mrview:count_view_changes_since(Db, <<"_design/bar">>, <<"baz">>,
Since, Opts).
| null | https://raw.githubusercontent.com/apache/couchdb-couch-mrview/f08c26a098a46366cfaf0e14b940af1f11d84577/test/couch_mrview_changes_since_tests.erl | erlang | 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
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
add new doc
check new view key
delete doc
check new view key | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(couch_mrview_changes_since_tests).
-include_lib("couch/include/couch_eunit.hrl").
-include_lib("couch/include/couch_db.hrl").
-define(TIMEOUT, 1000).
setup() ->
{ok, Db} = couch_mrview_test_util:init_db(?tempdb(), changes),
Db.
teardown(Db) ->
couch_db:close(Db),
couch_server:delete(Db#db.name, [?ADMIN_CTX]),
ok.
changes_since_test() ->
{
"changes_since tests",
{
setup,
fun test_util:start_couch/0, fun test_util:stop_couch/1,
{
foreach,
fun setup/0, fun teardown/1,
[
fun test_basic/1,
fun test_range/1,
fun test_basic_since/1,
fun test_range_since/1,
fun test_basic_count/1,
fun test_range_count/1,
fun test_basic_count_since/1,
fun test_range_count_since/1,
fun test_compact/1,
fun test_remove_key/1
]
}
}
}.
test_basic(Db) ->
Result = run_query(Db, 0, []),
Expect = {ok, [
{{2, 1, <<"1">>}, 1},
{{3, 10, <<"10">>}, 10},
{{4, 2, <<"2">>}, 2},
{{5, 3, <<"3">>}, 3},
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5},
{{8, 6, <<"6">>}, 6},
{{9, 7, <<"7">>}, 7},
{{10, 8, <<"8">>}, 8},
{{11, 9, <<"9">>}, 9}
]},
?_assertEqual(Result, Expect).
test_range(Db) ->
Result = run_query(Db, 0, [{start_key, 3}, {end_key, 5}]),
Expect = {ok, [
{{5, 3, <<"3">>}, 3},
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5}
]},
?_assertEqual(Result, Expect).
test_basic_since(Db) ->
Result = run_query(Db, 5, []),
Expect = {ok, [
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5},
{{8, 6, <<"6">>}, 6},
{{9, 7, <<"7">>}, 7},
{{10, 8, <<"8">>}, 8},
{{11, 9, <<"9">>}, 9}
]},
?_assertEqual(Result, Expect).
test_range_since(Db) ->
Result = run_query(Db, 5, [{start_key, 3}, {end_key, 5}]),
Expect = {ok, [
{{6, 4, <<"4">>}, 4},
{{7, 5, <<"5">>}, 5}
]},
?_assertEqual(Result, Expect).
test_basic_count(Db) ->
Result = run_count_query(Db, 0, []),
?_assertEqual(Result, 10).
test_range_count(Db) ->
Result = run_count_query(Db, 0, [{start_key, 3}, {end_key, 5}]),
?_assertEqual(Result, 3).
test_basic_count_since(Db) ->
Result = run_count_query(Db, 5, []),
?_assertEqual(Result, 6).
test_range_count_since(Db) ->
Result = run_count_query(Db, 5, [{start_key, 3}, {end_key, 5}]),
?_assertEqual(Result, 2).
test_compact(Db) ->
Result = couch_mrview:compact(Db, <<"_design/bar">>),
?_assertEqual(Result, ok),
Count = run_count_query(Db, 0, []),
?_assertEqual(Count, 10).
test_remove_key(Db) ->
Doc = couch_mrview_test_util:doc(11),
{ok, Rev} = couch_db:update_doc(Db, Doc, []),
RevStr = couch_doc:rev_to_str(Rev),
{ok, _} = couch_db:ensure_full_commit(Db),
{ok, Db1} = couch_db:reopen(Db),
Result = run_count_query(Db1, 0, []),
?_assertEqual(Result, 11),
Result1 = run_query(Db1, 0, [{start_key, 11}, {end_key, 11}]),
Expect = {ok, [
{{12, 11, <<"11">>}, 11}
]},
?_assertEqual(Result1, Expect),
Doc2 = couch_doc:from_json_obj({[
{<<"_id">>, <<"11">>},
{<<"_rev">>, RevStr},
{<<"_deleted">>, true}
]}),
{ok, _} = couch_db:update_doc(Db1, Doc2, []),
{ok, Db2} = couch_db:reopen(Db1),
Result2 = run_count_query(Db2, 0, []),
?_assertEqual(Result2, 11),
Result3 = run_query(Db2, 0, [{start_key, 11}, {end_key, 11}]),
Expect2 = {ok, [
{{13, 11, <<"11">>}, {[{<<"_removed">>, true}]}}
]},
?_assertEqual(Result3, Expect2).
run_query(Db, Since, Opts) ->
Fun = fun(KV, Acc) -> {ok, [KV | Acc]} end,
{ok, R} = couch_mrview:view_changes_since(Db, <<"_design/bar">>, <<"baz">>,
Since, Fun, Opts, []),
{ok, lists:reverse(R)}.
run_count_query(Db, Since, Opts) ->
couch_mrview:count_view_changes_since(Db, <<"_design/bar">>, <<"baz">>,
Since, Opts).
|
f2c454f0c6c7789188b23fa4d1c5f7b1a6b4e737cba93d4752c262f5db39736d | tomjridge/imp_fs | v3_live_object_cache.ml | * Live object cache .
A cache of " live " objects . Expunging an object may take some
time . Resurrecting an object may take some time . We use reference
counting to prevent objects from being expunged while references
remain live .
We are maintaining a cache of objects by i d. We can maintain the
counter with the object . A kref is an abstract wrapper round the
object . Essentially it provides : : kref - > obj . It also
includes put : kref - > unit which destroys the kref and reduces the
underlying count .
Do n't open .
A cache of "live" objects. Expunging an object may take some
time. Resurrecting an object may take some time. We use reference
counting to prevent objects from being expunged while references
remain live.
We are maintaining a cache of objects by id. We can maintain the
counter with the object. A kref is an abstract wrapper round the
object. Essentially it provides: kref_to_obj: kref -> obj. It also
includes put: kref -> unit which destroys the kref and reduces the
underlying count.
Don't open. *)
let line s = Printf.printf "%s: Reached line %d\n%!" "V3_live_object_cache" s; true
* User view of krefs ; the user must call when finished with
the object .
the object. *)
type ('obj,'kref) kref_ops = {
kref_to_obj : 'kref -> 'obj;
krelease : 'kref -> unit;
}
module Private_kref_impl = struct
type 'a kref = {
obj: 'a;
* whether this kref is valid
counter: int ref; (** backing counter *)
}
let kref_to_obj: 'a kref -> 'a =
fun x ->
assert(x.valid);
x.obj
let create ~counter obj =
let kref = {obj; valid=true; counter} in
(* Add a finalizer to ensure that the obj is not GC'ed in valid state *)
assert(
kref |> Gc.finalise (fun x ->
if x.valid then Printf.printf "WARNING! kref object GC'ed but valid flag was set\n%!");
true);
kref
let krelease kref =
kref.valid <- false;
Stdlib.decr kref.counter
let kref_ops = { kref_to_obj; krelease }
end
type 'a kref = 'a Private_kref_impl.kref
let kref_ops = Private_kref_impl.kref_ops
module Kref = Private_kref_impl
* A cache of live objects is just an LRU of ref counted objects
type 'a counted = {
count: int ref;
obj: 'a
}
type ('a,'t) entry = [
| `Resurrecting of (unit,'t)m
| `Present of 'a counted
| `Finalising of (unit,'t)m
]
type config = {
cache_size: int;
trim_delta: int;
}
type ('lru,'t) cache = {
lru : 'lru;
config : config;
mutable gc_thread : (unit,'t)m;
}
type ('id,'a,'kref,'cache,'t) cache_ops = {
create : config:config -> 'cache;
get : 'id -> 'cache -> ('kref,'t)m;
put : 'kref -> unit;
kref_to_obj : 'kref -> 'a;
}
module type S = sig
type t = lwt
type id
type a
end
module type T = sig
type t = lwt
type id
type a
type kref
type cache
(** resurrect: slow operation to resurrect an object from a
persistent store; finalise:called when removing objects from the
cache; no outstanding references remain; as such, the object
should certainly not be locked *)
val make_cache_ops:
resurrect : (id -> (a,t)m) ->
finalise : ( (id*a) list -> (unit,t)m) ->
(id,a,kref,cache,t)cache_ops
end
module Make(S:S) : T with type id = S.id and type a = S.a = struct
let dont_log = !V3_intf.dont_log
include S
open Tjr_monad.With_lwt
module Tmp = struct
module S' = struct
type k = id
type v = (a,t)entry
end
module Lru = Tjr_lru.Mutable.Make_with_pervasives(S')
end
type lru = Tmp.Lru.t
let lru_ops : (id,(a,t)entry,lru) Tjr_lru.Mutable.lru_ops = Tmp.Lru.lru_ops
module Lru = (val lru_ops)
type nonrec kref = a Private_kref_impl.kref
type nonrec cache = (lru,lwt)cache
exception Exit_early
let make_cache_ops ~resurrect ~finalise =
let open (struct
(* FIXME we want this to run only when necessary, or at least, to
run often if there is a lot of pressure, but not often if less
pressure *)
(** A thread that scans the Lru to remove entries that are no longer
referenced *)
let rec gc_thread cache =
let overflow = Lru.size cache.lru - cache.config.cache_size in
match overflow > 0 with
| false -> from_lwt (sleep 1.) >>= fun () -> gc_thread cache
| true ->
let n_to_remove = overflow+cache.config.trim_delta in
let to_trim = ref [] in
let n_removed = ref 0 in (* number of removed entries *)
(* NOTE we modify the lru state as we iterate over it; this is
safe with the current mutable lru implementation I believe
*)
(* a promise to signal the end of finalising *)
let (p,signal_p) = Lwt.wait () in
begin try
cache.lru |> Lru.iter (fun k v ->
match !n_removed >= n_to_remove with
| true -> raise Exit_early
| false ->
match v with
| `Finalising _ -> ()
| `Resurrecting _ -> ()
| `Present counted -> (
match !(counted.count) with
| 0 -> (
(* can remove; so replace existing binding *)
Lru.add k (`Finalising (from_lwt p)) cache.lru;
to_trim := (k,counted.obj) :: !to_trim;
incr n_removed;
())
| _ -> ()))
with Exit_early -> () end;
begin
(* Some warnings *)
if !n_removed < n_to_remove then
Printf.printf
"WARNING! Trimmed %d entries, but this is less than %d \
(amount we aim to trim). Possibly too many live entries?\n%!"
!n_removed
n_to_remove;
if Lru.size cache.lru > cache.config.cache_size then
Printf.printf
"WARNING! The LRU size %d exceeds the capacity %d and we \
were unable to remove more entries\n%!"
(Lru.size cache.lru)
cache.config.cache_size
(* FIXME what is the reasonable thing to do in this
situation? maybe timeout??? or block and wait for
finds to complete? Or maybe mark cache as full, so that
no new entries get added... possibly this is simplest
*)
end;
finalise !to_trim >>= fun () ->
(* now remove the finalising entries from the map *)
(List.map fst !to_trim) |> List.iter (fun k -> Lru.remove k cache.lru);
Lwt.wakeup_later signal_p ();
gc_thread cache
let create ~config =
let lru = Lru.create config.cache_size in
let cache = {lru; config; gc_thread=(return ()) } in
let gc_thread = gc_thread cache in
cache.gc_thread <- gc_thread;
cache
(* FIXME a bit worried about thrashing eg a thread finds a
resurrecting entry, and whilst waiting the entry is resurrected
then removed from cache, so the thread has to wait again *)
let rec get id cache =
assert(dont_log || line __LINE__);
match Lru.find id cache.lru with
(* If resurrecting or finalising, wait and try again *)
| Some(`Resurrecting p) | Some (`Finalising p) ->
assert(dont_log || line __LINE__);
Lru.promote id cache.lru;
(With_lwt.yield () |> from_lwt) >>= fun () ->
p >>= fun _ -> get id cache
If in the cache , return a new kref
| Some(`Present x) ->
assert(dont_log || line __LINE__);
incr x.count;
Lru.promote id cache.lru;
return (Kref.create ~counter:x.count x.obj)
If not in the cache , resurrect ( and mark resurrecting ) , then
place in cache and return kref
place in cache and return kref *)
| None ->
assert(dont_log || line __LINE__);
NOTE nasty bug where p was unguarded , ran immediately ,
returned immediately , then had ` Present overridden by
` Resurrecting !
returned immediately, then had `Present overridden by
`Resurrecting! *)
let (p,r) = Lwt.wait () in
Lru.add id (`Resurrecting (p|>from_lwt)) cache.lru;
(* resurrect the object, and replace entry in the cache; then try again *)
resurrect id >>= fun obj ->
Lru.add id (`Present {count=ref 0;obj}) cache.lru;
assert(Lru.find id cache.lru |> function | Some (`Present _) -> true | _ -> false);
assert(dont_log || line __LINE__);
(Lwt.wakeup_later r ());
assert(dont_log || line __LINE__);
get id cache
let _ : i d - > ( lru , lwt ) cache - > ( kref , lwt ) m = get
let put kref = kref_ops.krelease kref
let kref_to_obj = kref_ops.kref_to_obj
let cache_ops : (id,a,kref,cache,t)cache_ops = {create;get;put;kref_to_obj}
end)
in
cache_ops
let _ = make_cache_ops
end
| null | https://raw.githubusercontent.com/tomjridge/imp_fs/dae69505130073747f37ecab845fe3b6c495e66a/src/_v3/v3_live_object_cache.ml | ocaml | * backing counter
Add a finalizer to ensure that the obj is not GC'ed in valid state
* resurrect: slow operation to resurrect an object from a
persistent store; finalise:called when removing objects from the
cache; no outstanding references remain; as such, the object
should certainly not be locked
FIXME we want this to run only when necessary, or at least, to
run often if there is a lot of pressure, but not often if less
pressure
* A thread that scans the Lru to remove entries that are no longer
referenced
number of removed entries
NOTE we modify the lru state as we iterate over it; this is
safe with the current mutable lru implementation I believe
a promise to signal the end of finalising
can remove; so replace existing binding
Some warnings
FIXME what is the reasonable thing to do in this
situation? maybe timeout??? or block and wait for
finds to complete? Or maybe mark cache as full, so that
no new entries get added... possibly this is simplest
now remove the finalising entries from the map
FIXME a bit worried about thrashing eg a thread finds a
resurrecting entry, and whilst waiting the entry is resurrected
then removed from cache, so the thread has to wait again
If resurrecting or finalising, wait and try again
resurrect the object, and replace entry in the cache; then try again | * Live object cache .
A cache of " live " objects . Expunging an object may take some
time . Resurrecting an object may take some time . We use reference
counting to prevent objects from being expunged while references
remain live .
We are maintaining a cache of objects by i d. We can maintain the
counter with the object . A kref is an abstract wrapper round the
object . Essentially it provides : : kref - > obj . It also
includes put : kref - > unit which destroys the kref and reduces the
underlying count .
Do n't open .
A cache of "live" objects. Expunging an object may take some
time. Resurrecting an object may take some time. We use reference
counting to prevent objects from being expunged while references
remain live.
We are maintaining a cache of objects by id. We can maintain the
counter with the object. A kref is an abstract wrapper round the
object. Essentially it provides: kref_to_obj: kref -> obj. It also
includes put: kref -> unit which destroys the kref and reduces the
underlying count.
Don't open. *)
let line s = Printf.printf "%s: Reached line %d\n%!" "V3_live_object_cache" s; true
* User view of krefs ; the user must call when finished with
the object .
the object. *)
type ('obj,'kref) kref_ops = {
kref_to_obj : 'kref -> 'obj;
krelease : 'kref -> unit;
}
module Private_kref_impl = struct
type 'a kref = {
obj: 'a;
* whether this kref is valid
}
let kref_to_obj: 'a kref -> 'a =
fun x ->
assert(x.valid);
x.obj
let create ~counter obj =
let kref = {obj; valid=true; counter} in
assert(
kref |> Gc.finalise (fun x ->
if x.valid then Printf.printf "WARNING! kref object GC'ed but valid flag was set\n%!");
true);
kref
let krelease kref =
kref.valid <- false;
Stdlib.decr kref.counter
let kref_ops = { kref_to_obj; krelease }
end
type 'a kref = 'a Private_kref_impl.kref
let kref_ops = Private_kref_impl.kref_ops
module Kref = Private_kref_impl
* A cache of live objects is just an LRU of ref counted objects
type 'a counted = {
count: int ref;
obj: 'a
}
type ('a,'t) entry = [
| `Resurrecting of (unit,'t)m
| `Present of 'a counted
| `Finalising of (unit,'t)m
]
type config = {
cache_size: int;
trim_delta: int;
}
type ('lru,'t) cache = {
lru : 'lru;
config : config;
mutable gc_thread : (unit,'t)m;
}
type ('id,'a,'kref,'cache,'t) cache_ops = {
create : config:config -> 'cache;
get : 'id -> 'cache -> ('kref,'t)m;
put : 'kref -> unit;
kref_to_obj : 'kref -> 'a;
}
module type S = sig
type t = lwt
type id
type a
end
module type T = sig
type t = lwt
type id
type a
type kref
type cache
val make_cache_ops:
resurrect : (id -> (a,t)m) ->
finalise : ( (id*a) list -> (unit,t)m) ->
(id,a,kref,cache,t)cache_ops
end
module Make(S:S) : T with type id = S.id and type a = S.a = struct
let dont_log = !V3_intf.dont_log
include S
open Tjr_monad.With_lwt
module Tmp = struct
module S' = struct
type k = id
type v = (a,t)entry
end
module Lru = Tjr_lru.Mutable.Make_with_pervasives(S')
end
type lru = Tmp.Lru.t
let lru_ops : (id,(a,t)entry,lru) Tjr_lru.Mutable.lru_ops = Tmp.Lru.lru_ops
module Lru = (val lru_ops)
type nonrec kref = a Private_kref_impl.kref
type nonrec cache = (lru,lwt)cache
exception Exit_early
let make_cache_ops ~resurrect ~finalise =
let open (struct
let rec gc_thread cache =
let overflow = Lru.size cache.lru - cache.config.cache_size in
match overflow > 0 with
| false -> from_lwt (sleep 1.) >>= fun () -> gc_thread cache
| true ->
let n_to_remove = overflow+cache.config.trim_delta in
let to_trim = ref [] in
let (p,signal_p) = Lwt.wait () in
begin try
cache.lru |> Lru.iter (fun k v ->
match !n_removed >= n_to_remove with
| true -> raise Exit_early
| false ->
match v with
| `Finalising _ -> ()
| `Resurrecting _ -> ()
| `Present counted -> (
match !(counted.count) with
| 0 -> (
Lru.add k (`Finalising (from_lwt p)) cache.lru;
to_trim := (k,counted.obj) :: !to_trim;
incr n_removed;
())
| _ -> ()))
with Exit_early -> () end;
begin
if !n_removed < n_to_remove then
Printf.printf
"WARNING! Trimmed %d entries, but this is less than %d \
(amount we aim to trim). Possibly too many live entries?\n%!"
!n_removed
n_to_remove;
if Lru.size cache.lru > cache.config.cache_size then
Printf.printf
"WARNING! The LRU size %d exceeds the capacity %d and we \
were unable to remove more entries\n%!"
(Lru.size cache.lru)
cache.config.cache_size
end;
finalise !to_trim >>= fun () ->
(List.map fst !to_trim) |> List.iter (fun k -> Lru.remove k cache.lru);
Lwt.wakeup_later signal_p ();
gc_thread cache
let create ~config =
let lru = Lru.create config.cache_size in
let cache = {lru; config; gc_thread=(return ()) } in
let gc_thread = gc_thread cache in
cache.gc_thread <- gc_thread;
cache
let rec get id cache =
assert(dont_log || line __LINE__);
match Lru.find id cache.lru with
| Some(`Resurrecting p) | Some (`Finalising p) ->
assert(dont_log || line __LINE__);
Lru.promote id cache.lru;
(With_lwt.yield () |> from_lwt) >>= fun () ->
p >>= fun _ -> get id cache
If in the cache , return a new kref
| Some(`Present x) ->
assert(dont_log || line __LINE__);
incr x.count;
Lru.promote id cache.lru;
return (Kref.create ~counter:x.count x.obj)
If not in the cache , resurrect ( and mark resurrecting ) , then
place in cache and return kref
place in cache and return kref *)
| None ->
assert(dont_log || line __LINE__);
NOTE nasty bug where p was unguarded , ran immediately ,
returned immediately , then had ` Present overridden by
` Resurrecting !
returned immediately, then had `Present overridden by
`Resurrecting! *)
let (p,r) = Lwt.wait () in
Lru.add id (`Resurrecting (p|>from_lwt)) cache.lru;
resurrect id >>= fun obj ->
Lru.add id (`Present {count=ref 0;obj}) cache.lru;
assert(Lru.find id cache.lru |> function | Some (`Present _) -> true | _ -> false);
assert(dont_log || line __LINE__);
(Lwt.wakeup_later r ());
assert(dont_log || line __LINE__);
get id cache
let _ : i d - > ( lru , lwt ) cache - > ( kref , lwt ) m = get
let put kref = kref_ops.krelease kref
let kref_to_obj = kref_ops.kref_to_obj
let cache_ops : (id,a,kref,cache,t)cache_ops = {create;get;put;kref_to_obj}
end)
in
cache_ops
let _ = make_cache_ops
end
|
078284ae8721c76d6b8e3892e85cca72cd3eac6a2c8c85ed156339023a97b54f | fugue/fregot | Order.hs | |
Copyright : ( c ) 2020 Fugue , Inc.
License : Apache License , version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
Copyright : (c) 2020 Fugue, Inc.
License : Apache License, version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE MultiWayIf #-}
# LANGUAGE ScopedTypeVariables #
module Fregot.Compile.Order
( OrderPredicate (..)
, reorder
, Safe (..)
, Unsafe (..)
, orderForClosures
, orderForSafety
, orderTermForSafety
, ovLiteral
, ovRuleBody
) where
import Control.Lens (traverseOf, view, (^.))
import Control.Monad.Extended (mapAccumM)
import Control.Monad.Identity (runIdentity)
import Control.Monad.Parachute (runParachuteT)
import Control.Monad.Writer (Writer, runWriter, writer)
import Data.Foldable (for_)
import Data.Functor (($>))
import qualified Data.HashMap.Strict as HMS
import qualified Data.HashSet.Extended as HS
import Data.List.NonEmpty.Extended (NonEmpty)
import qualified Data.List.NonEmpty.Extended as NonEmpty
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, listToMaybe)
import qualified Data.Unification as Unification
import Fregot.Names
import Fregot.Prepare.Ast
import Fregot.Prepare.Lens
import qualified Fregot.PrettyPrint as PP
import Fregot.Sources.SourceSpan (SourceSpan)
import qualified Fregot.Types.Infer as Types
import qualified Fregot.Types.Internal as Types
data OrderPredicate a e
= OrderOk a
| OrderError e
-- | General strategy for reordering.
reorder
^ May be added now ?
-> b -- ^ Initial accumulator.
-> [a] -- ^ Items to order.
-> (b, [a], [e]) -- ^ Reordered, errors.
reorder orderPredicate = \userAcc items ->
-- Associate a number with each item.
let itemMap = Map.fromList $ zip [0 :: Int ..] items in
loop userAcc [] Map.empty itemMap
where
loop userAcc0 ordered0 errorMap0 itemMap0 =
-- Perform a fold over the remaining items to add them all to the list.
let (userAcc1, ordered1, errorMap1) = Map.foldlWithKey'
(\(userAcc, acc, errors) k item ->
case orderPredicate userAcc acc item of
OrderOk ua -> (ua, acc ++ [item], Map.delete k errors)
OrderError e -> (userAcc, acc, Map.insert k e errors))
(userAcc0, ordered0, errorMap0)
itemMap0
-- Update the remaining items, these are only the ones that still
-- have errors.
itemMap1 = itemMap0 `Map.intersection` errorMap1 in
if | Map.null itemMap1 ->
-- No items remaining means that we are done. `errorMap1`
-- should be empty.
(userAcc1, ordered1, map snd $ Map.toList errorMap1)
| Map.size itemMap0 == Map.size itemMap1 ->
-- If the size of the remaining items did not change, we are
-- stuck with the errors we have now.
(userAcc1, ordered1, map snd $ Map.toList errorMap1)
| otherwise ->
-- Run again.
loop userAcc1 ordered1 errorMap1 itemMap1
newtype Safe v = Safe {unSafe :: HS.HashSet v}
deriving (Eq, Monoid, Semigroup, Show)
instance PP.Pretty PP.Sem v => PP.Pretty PP.Sem (Safe v) where
pretty = PP.set . HS.toList . unSafe
newtype Unsafe v a = Unsafe {unUnsafe :: HMS.HashMap v (NonEmpty a)}
deriving (Eq, Monoid, Semigroup, Show)
orderForClosures
:: Types.InferEnv -> Safe Var -> RuleBody SourceSpan
-> (RuleBody SourceSpan, Unsafe Var SourceSpan)
orderForClosures inferEnv safe body =
let (_, body', unsafes) = reorder step () body in
(body', mconcat unsafes)
where
-- Variables appearing in the body.
bodyVars = HS.toHashSetOf
(ruleBodyTerms . termCosmosNoClosures . termNames . traverse . _LocalName)
body
-- Order predicate.
step () reordered lit =
-- Variables appearing in closures in this statement.
let inClosureVars = HS.toHashSetOf
(literalTerms . termCosmosClosures . comprehensionTerms .
termCosmosNames . traverse . _LocalName)
lit
Variabels that are both in the body as well as in the closures
must be bound first .
needOutVars =
(bodyVars `HS.intersection` inClosureVars) `HS.difference`
unSafe safe
-- The current output variables.
currentOutVars = maybe HS.empty unSafe $
ovRuleBody inferEnv safe reordered
-- Missing output variables.
missing = needOutVars `HS.difference` currentOutVars
-- Compute unsafe variables. Should be empty in the best case.
unsafes =
const (NonEmpty.singleton (lit ^. literalAnn)) <$>
HS.toMap missing in
if HMS.null unsafes then OrderOk () else OrderError (Unsafe unsafes)
orderForSafety
:: Types.InferEnv -> Safe Var -> RuleBody SourceSpan
-> (RuleBody SourceSpan, Unsafe Var SourceSpan)
orderForSafety inferEnv safe0 body0
-- If ordering for closures fails, shortcut here.
| not (HMS.null (unUnsafe unsafes1)) = (body1, unsafes1)
-- Otherwise, do a proper ordering.
| otherwise =
let idxBody = zip [0 :: Int ..] body1
-- A list of unsafe variables per statement.
unsafes = Map.fromList $ do
(idx, lit) <- idxBody
let inLit = HS.toHashSetOf
(literalTerms . termCosmosNoClosures . termNames . traverse . _LocalName)
lit
return (idx, inLit `HS.difference` unSafe safe0)
-- Order statements in this body.
(_, body2, unsafes2) = reorder step (safe0, unsafes) idxBody
-- Final run to recursively call `orderForSafety` on closures within
-- terms in this body.
((_, body3), unsafes3) = runWriter $ mapAccumM
(\safe lit -> do
lit' <- recurse safe lit
return (safe <> fromMaybe mempty (ovLiteral inferEnv safe lit'), lit'))
safe0
(map snd body2) in
(body3, unsafes1 <> mconcat unsafes2 <> unsafes3)
where
(body1, unsafes1) = orderForClosures inferEnv safe0 body0
step
:: (Safe Var, Map.Map Int (HS.HashSet Var))
-> [(Int, Literal SourceSpan)]
-> (Int, Literal SourceSpan)
-> OrderPredicate
(Safe Var, Map.Map Int (HS.HashSet Var))
(Unsafe Var SourceSpan)
step (safe, unsafes) _ordered (idx, lit)
-- Find the unsafes we previously stored for this literal.
| HMS.null stillUnsafe = OrderOk (nowSafe, Map.delete idx unsafes)
| otherwise = OrderError (Unsafe stillUnsafe)
where
nowSafe = safe <> fromMaybe mempty (ovLiteral inferEnv safe lit)
prevUnsafes = fromMaybe mempty (Map.lookup idx unsafes)
stillUnsafe =
const (NonEmpty.singleton (lit ^. literalAnn)) <$>
HS.toMap (prevUnsafes `HS.difference` unSafe nowSafe)
-- Recursively rewrite all closures in a literal using the given safe list.
recurse
:: Safe Var -> Literal SourceSpan
-> Writer (Unsafe Var SourceSpan) (Literal SourceSpan)
recurse rsafe =
traverseOf literalTerms (writer . orderTermForSafety inferEnv rsafe)
orderTermForSafety
:: Types.InferEnv -> Safe Var -> Term SourceSpan
-> (Term SourceSpan, Unsafe Var SourceSpan)
orderTermForSafety inferEnv safe =
runWriter .
traverseOf termRuleBodies (writer . orderForSafety inferEnv safe)
inferOutVars
:: Types.InferEnv -> Safe Var -> Maybe SourceSpan -> Types.InferM a
-> Maybe (Safe Var)
inferOutVars inferEnv safe mbSource infer =
case maybeInferred of
Nothing -> Nothing
Just (_, env) -> Just . Safe $ Unification.keys env
where
maybeInferred =
snd $ runIdentity $ runParachuteT $
Types.runInfer inferEnv {Types.ieInferClosures = False} $ do
for_ mbSource $ \source -> Types.setInferContext source $
HS.toMap (unSafe safe) $> Types.unknown
infer
ovRuleBody
:: Types.InferEnv -> Safe Var -> RuleBody SourceSpan -> Maybe (Safe Var)
ovRuleBody inferEnv safe body =
inferOutVars inferEnv safe (view literalAnn <$> listToMaybe body) (Types.inferRuleBody body)
ovLiteral
:: Types.InferEnv -> Safe Var -> Literal SourceSpan -> Maybe (Safe Var)
ovLiteral inferEnv safe lit =
inferOutVars inferEnv safe
(Just $ lit ^. literalAnn) (Types.inferLiteral lit)
| null | https://raw.githubusercontent.com/fugue/fregot/c3d87f37c43558761d5f6ac758d2f1a4117adb3e/lib/Fregot/Compile/Order.hs | haskell | # LANGUAGE MultiWayIf #
| General strategy for reordering.
^ Initial accumulator.
^ Items to order.
^ Reordered, errors.
Associate a number with each item.
Perform a fold over the remaining items to add them all to the list.
Update the remaining items, these are only the ones that still
have errors.
No items remaining means that we are done. `errorMap1`
should be empty.
If the size of the remaining items did not change, we are
stuck with the errors we have now.
Run again.
Variables appearing in the body.
Order predicate.
Variables appearing in closures in this statement.
The current output variables.
Missing output variables.
Compute unsafe variables. Should be empty in the best case.
If ordering for closures fails, shortcut here.
Otherwise, do a proper ordering.
A list of unsafe variables per statement.
Order statements in this body.
Final run to recursively call `orderForSafety` on closures within
terms in this body.
Find the unsafes we previously stored for this literal.
Recursively rewrite all closures in a literal using the given safe list. | |
Copyright : ( c ) 2020 Fugue , Inc.
License : Apache License , version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
Copyright : (c) 2020 Fugue, Inc.
License : Apache License, version 2.0
Maintainer :
Stability : experimental
Portability : POSIX
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
module Fregot.Compile.Order
( OrderPredicate (..)
, reorder
, Safe (..)
, Unsafe (..)
, orderForClosures
, orderForSafety
, orderTermForSafety
, ovLiteral
, ovRuleBody
) where
import Control.Lens (traverseOf, view, (^.))
import Control.Monad.Extended (mapAccumM)
import Control.Monad.Identity (runIdentity)
import Control.Monad.Parachute (runParachuteT)
import Control.Monad.Writer (Writer, runWriter, writer)
import Data.Foldable (for_)
import Data.Functor (($>))
import qualified Data.HashMap.Strict as HMS
import qualified Data.HashSet.Extended as HS
import Data.List.NonEmpty.Extended (NonEmpty)
import qualified Data.List.NonEmpty.Extended as NonEmpty
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, listToMaybe)
import qualified Data.Unification as Unification
import Fregot.Names
import Fregot.Prepare.Ast
import Fregot.Prepare.Lens
import qualified Fregot.PrettyPrint as PP
import Fregot.Sources.SourceSpan (SourceSpan)
import qualified Fregot.Types.Infer as Types
import qualified Fregot.Types.Internal as Types
data OrderPredicate a e
= OrderOk a
| OrderError e
reorder
^ May be added now ?
reorder orderPredicate = \userAcc items ->
let itemMap = Map.fromList $ zip [0 :: Int ..] items in
loop userAcc [] Map.empty itemMap
where
loop userAcc0 ordered0 errorMap0 itemMap0 =
let (userAcc1, ordered1, errorMap1) = Map.foldlWithKey'
(\(userAcc, acc, errors) k item ->
case orderPredicate userAcc acc item of
OrderOk ua -> (ua, acc ++ [item], Map.delete k errors)
OrderError e -> (userAcc, acc, Map.insert k e errors))
(userAcc0, ordered0, errorMap0)
itemMap0
itemMap1 = itemMap0 `Map.intersection` errorMap1 in
if | Map.null itemMap1 ->
(userAcc1, ordered1, map snd $ Map.toList errorMap1)
| Map.size itemMap0 == Map.size itemMap1 ->
(userAcc1, ordered1, map snd $ Map.toList errorMap1)
| otherwise ->
loop userAcc1 ordered1 errorMap1 itemMap1
newtype Safe v = Safe {unSafe :: HS.HashSet v}
deriving (Eq, Monoid, Semigroup, Show)
instance PP.Pretty PP.Sem v => PP.Pretty PP.Sem (Safe v) where
pretty = PP.set . HS.toList . unSafe
newtype Unsafe v a = Unsafe {unUnsafe :: HMS.HashMap v (NonEmpty a)}
deriving (Eq, Monoid, Semigroup, Show)
orderForClosures
:: Types.InferEnv -> Safe Var -> RuleBody SourceSpan
-> (RuleBody SourceSpan, Unsafe Var SourceSpan)
orderForClosures inferEnv safe body =
let (_, body', unsafes) = reorder step () body in
(body', mconcat unsafes)
where
bodyVars = HS.toHashSetOf
(ruleBodyTerms . termCosmosNoClosures . termNames . traverse . _LocalName)
body
step () reordered lit =
let inClosureVars = HS.toHashSetOf
(literalTerms . termCosmosClosures . comprehensionTerms .
termCosmosNames . traverse . _LocalName)
lit
Variabels that are both in the body as well as in the closures
must be bound first .
needOutVars =
(bodyVars `HS.intersection` inClosureVars) `HS.difference`
unSafe safe
currentOutVars = maybe HS.empty unSafe $
ovRuleBody inferEnv safe reordered
missing = needOutVars `HS.difference` currentOutVars
unsafes =
const (NonEmpty.singleton (lit ^. literalAnn)) <$>
HS.toMap missing in
if HMS.null unsafes then OrderOk () else OrderError (Unsafe unsafes)
orderForSafety
:: Types.InferEnv -> Safe Var -> RuleBody SourceSpan
-> (RuleBody SourceSpan, Unsafe Var SourceSpan)
orderForSafety inferEnv safe0 body0
| not (HMS.null (unUnsafe unsafes1)) = (body1, unsafes1)
| otherwise =
let idxBody = zip [0 :: Int ..] body1
unsafes = Map.fromList $ do
(idx, lit) <- idxBody
let inLit = HS.toHashSetOf
(literalTerms . termCosmosNoClosures . termNames . traverse . _LocalName)
lit
return (idx, inLit `HS.difference` unSafe safe0)
(_, body2, unsafes2) = reorder step (safe0, unsafes) idxBody
((_, body3), unsafes3) = runWriter $ mapAccumM
(\safe lit -> do
lit' <- recurse safe lit
return (safe <> fromMaybe mempty (ovLiteral inferEnv safe lit'), lit'))
safe0
(map snd body2) in
(body3, unsafes1 <> mconcat unsafes2 <> unsafes3)
where
(body1, unsafes1) = orderForClosures inferEnv safe0 body0
step
:: (Safe Var, Map.Map Int (HS.HashSet Var))
-> [(Int, Literal SourceSpan)]
-> (Int, Literal SourceSpan)
-> OrderPredicate
(Safe Var, Map.Map Int (HS.HashSet Var))
(Unsafe Var SourceSpan)
step (safe, unsafes) _ordered (idx, lit)
| HMS.null stillUnsafe = OrderOk (nowSafe, Map.delete idx unsafes)
| otherwise = OrderError (Unsafe stillUnsafe)
where
nowSafe = safe <> fromMaybe mempty (ovLiteral inferEnv safe lit)
prevUnsafes = fromMaybe mempty (Map.lookup idx unsafes)
stillUnsafe =
const (NonEmpty.singleton (lit ^. literalAnn)) <$>
HS.toMap (prevUnsafes `HS.difference` unSafe nowSafe)
recurse
:: Safe Var -> Literal SourceSpan
-> Writer (Unsafe Var SourceSpan) (Literal SourceSpan)
recurse rsafe =
traverseOf literalTerms (writer . orderTermForSafety inferEnv rsafe)
orderTermForSafety
:: Types.InferEnv -> Safe Var -> Term SourceSpan
-> (Term SourceSpan, Unsafe Var SourceSpan)
orderTermForSafety inferEnv safe =
runWriter .
traverseOf termRuleBodies (writer . orderForSafety inferEnv safe)
inferOutVars
:: Types.InferEnv -> Safe Var -> Maybe SourceSpan -> Types.InferM a
-> Maybe (Safe Var)
inferOutVars inferEnv safe mbSource infer =
case maybeInferred of
Nothing -> Nothing
Just (_, env) -> Just . Safe $ Unification.keys env
where
maybeInferred =
snd $ runIdentity $ runParachuteT $
Types.runInfer inferEnv {Types.ieInferClosures = False} $ do
for_ mbSource $ \source -> Types.setInferContext source $
HS.toMap (unSafe safe) $> Types.unknown
infer
ovRuleBody
:: Types.InferEnv -> Safe Var -> RuleBody SourceSpan -> Maybe (Safe Var)
ovRuleBody inferEnv safe body =
inferOutVars inferEnv safe (view literalAnn <$> listToMaybe body) (Types.inferRuleBody body)
ovLiteral
:: Types.InferEnv -> Safe Var -> Literal SourceSpan -> Maybe (Safe Var)
ovLiteral inferEnv safe lit =
inferOutVars inferEnv safe
(Just $ lit ^. literalAnn) (Types.inferLiteral lit)
|
45ca6820af72d37cd3d79c9fd2872d3459d4035af30b23c5945d9b5365da406b | nathanmarz/cascalog | stats.clj | (ns cascalog.math.stats
(:use cascalog.api)
(:require [cascalog.logic.ops :as c]
[cascalog.logic.def :as d]
[cascalog.math.contrib [accumulators :as acc]]))
(defn initialize-mean-variance-parallel [& X]
(map (fn [x] (acc/mean-variance {:mean x :variance 0 :n 1})) X))
(d/defparallelagg mean-variance-parallel
:init-var #'initialize-mean-variance-parallel
:combine-var #'acc/combine)
(defn get-variance [mvp-struct]
(double (mvp-struct :variance)))
(def sample-variance-parallel
"Predicate macro that calculates the sample variance of the supplied input
var, in a parallel, numerically stable way."
(<- [!val :> !var]
(mean-variance-parallel :< !val :> !ret)
(get-variance :< !ret :> !var)))
(def variance
"Predicate macro that calculates the variance of the supplied input
var."
(<- [!val :> !var]
(* !val !val :> !squared)
(c/sum !squared :> !square-sum)
(c/count !count)
(c/avg !val :> !mean)
(* !mean !mean :> !mean-squared)
(div !square-sum !count :> !i)
(- !i !mean-squared :> !var)))
(def sample-variance
"Predicate macro that calculates the sample variance of the supplied input
var."
(<- [!val :> !var]
(* !val !val :> !squared)
(c/sum !squared :> !squared-sum)
(c/count !count)
(c/sum !val :> !sum)
(c/avg !val :> !mean)
(* !sum !mean :> !i)
(- !squared-sum !i :> !num)
(- !count 1 :> !denom)
(div !num !denom :> !var)))
| null | https://raw.githubusercontent.com/nathanmarz/cascalog/deaad977aa98985f68f3d1cc3e081d345184c0c8/cascalog-math/src/cascalog/math/stats.clj | clojure | (ns cascalog.math.stats
(:use cascalog.api)
(:require [cascalog.logic.ops :as c]
[cascalog.logic.def :as d]
[cascalog.math.contrib [accumulators :as acc]]))
(defn initialize-mean-variance-parallel [& X]
(map (fn [x] (acc/mean-variance {:mean x :variance 0 :n 1})) X))
(d/defparallelagg mean-variance-parallel
:init-var #'initialize-mean-variance-parallel
:combine-var #'acc/combine)
(defn get-variance [mvp-struct]
(double (mvp-struct :variance)))
(def sample-variance-parallel
"Predicate macro that calculates the sample variance of the supplied input
var, in a parallel, numerically stable way."
(<- [!val :> !var]
(mean-variance-parallel :< !val :> !ret)
(get-variance :< !ret :> !var)))
(def variance
"Predicate macro that calculates the variance of the supplied input
var."
(<- [!val :> !var]
(* !val !val :> !squared)
(c/sum !squared :> !square-sum)
(c/count !count)
(c/avg !val :> !mean)
(* !mean !mean :> !mean-squared)
(div !square-sum !count :> !i)
(- !i !mean-squared :> !var)))
(def sample-variance
"Predicate macro that calculates the sample variance of the supplied input
var."
(<- [!val :> !var]
(* !val !val :> !squared)
(c/sum !squared :> !squared-sum)
(c/count !count)
(c/sum !val :> !sum)
(c/avg !val :> !mean)
(* !sum !mean :> !i)
(- !squared-sum !i :> !num)
(- !count 1 :> !denom)
(div !num !denom :> !var)))
|
|
de6a5a85229ec2830739bb68c3afe6a4934f9eba66a5320611c42bd7d2d901d9 | FestCat/festival-ca | upclex_central.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Lexicon , LTS and Postlexical rules for upc_catalan
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Adapted for Catalan by the UPC team
;;;
( c )
Universitat Politècnica de Catalunya , Barcelona , Spain
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (upc_catalan_addenda_central)
"(upc_catalan_addenda_central)
Basic lexicon should (must ?) have basic letters, symbols and punctuation."
;;; Words to be added in future versions:
; Currently prediction is bad for these words:
; <Empty (for now)>
;;; Common words on the internet
; gmail, hotmail, facebook
(lex.add.entry '("hotmail" n ( ((o1 t) 1 ) ( ( m E1 i1 l ) 0 ) ) ) )
(lex.add.entry '("gmail" n ( ((Z E1) 1 ) ( ( m E1 i1 l ) 0 ) ) ) )
(lex.add.entry '("facebook" n ( ((f E1 i1 s) 1 ) ( ( b u k ) 0 ) ) ) )
(lex.add.entry '("copyright" n ( ((k O1) 1 ) ((p i) 0 ) ((rr a i t) 0) ) ))
(lex.add.entry '("wikipedia" n ( ( (g w i) 0 ) ((k i) 0 ) ( (p E1) 1 ) ( (d i) 0 ) ( (ax) 0) ) ))
(lex.add.entry '("twitter" n ( ( (t w i1) 1 ) ( (t e r) 0 ) ) ) )
(lex.add.entry '("debian" n ( ( (d e1) 1 ) ( (b i ) 0 ) ( ( ax n) 0) )))
(lex.add.entry '("linux" n ( ( (l i1) 1 ) ( (n u k s) 0 ) )))
(lex.add.entry '("google" n ( ( (g u) 1 ) ( (g ax l ) 0 ) )))
; ;;; Symbols ...
(lex.add.entry '("*" n (((ax s) 0) ((t e1) 0) ((r i1 s k) 1))))
(lex.add.entry '("%" n (((p ax r) 0) ((s e1 n ) 1))))
(lex.add.entry '("+" n (((m e1 s) 1 ))))
(lex.add.entry '("=" n (((i) 0) ((G w a1 l) 1))))
(lex.add.entry '("€" n (((e1 uw) 1) ((r u) 0))))
(lex.add.entry '("$" n (((d o1 ) 1) ((l ax r) 0))))
(lex.add.entry '("@" n (((ax ) 0) ((rr o1) 1) ((b ax) 0))))
(lex.add.entry '("/" n (((b a1 ) 1) ((rr ax ) 0))))
;; Basic punctuation must be in with nil pronunciation
)
(define (upclex_catalan_define_ruleset_syl_central )
"Define a ruleset to do syllabification"
(let (
(oldlex (lex.select "upc_catalan-central"))
)
(lts.ruleset
upc_catalan_syl
Sons vocàlics
(V a a1 E1 e1 e O1 o1 o u1 i1 i u ax)
Sons vocàlics àtons
(VA a e i o u )
Vocals , " i " i " u "
(VGQ ax a1 o1 O1 o u)
(VW i u ) ;; Sons i u àtons (vocals dèbils)
Sons i u tònics ( vocals dèbils en )
Sons vocàlics tònics
; (SC y w ) ;; Sons semi-consonàntics
( SV j uw ) ; ; Sons semi - vocàlics
(SC j w ) ;; Sons semi-consonàntics (allophone removed)
(SV j w ) ;; Sons semi-vocàlics (allophones removed)
(GQ k g )
(C p t b d k g f s z S Z m n J l L r rr)
(A a a1 E E1 e e1 O O1 o o1 u u1 i i1 ax p t k b d g f s z S Z m n J l L r rr w j )
)
;; Rules will add - at syllable boundary
(
;; Diftongs creixents
( [ GQ w VGQ ] = GQ w VQG ) ; ; Ex : quotidià : k w u - t i - d i - a1
( [ k w ax ] = - k w ax )
( [ k w a ] = - k w a )
( [ k w a1 ] = - k w a1 )
( [ k w o1 ] = - k w o1 )
( [ k w O1 ] = - k w O1 )
( [ k w o ] = - k w o )
( [ k w u ] = - k w u )
( [ g w ax ] = - g w ax )
( [ g w a ] = - g w a )
( [ g w a1 ] = - g w a1 )
( [ g w o1 ] = - g w o1 )
( [ g w O1 ] = - g w O1 )
( [ g w o ] = - g w o )
( [ g w u ] = - g w u )
Correccions LTS
( V [ s j ] = - s j )
( j [ t ] s V = t - )
;; Semi-consonants break
;; ( # SC V [ A ] = - A ) ;; Ex: iode: y o - d ax
( # SC V [ a ] = - a )
( # SC V [ a1 ] = - a1 )
( # SC V [ E1 ] = - E1 )
( # SC V [ e1 ] = - e1 )
( # SC V [ e ] = - e )
( # SC V [ O1 ] = - O1 )
( # SC V [ o1 ] = - o1 )
( # SC V [ o ] = - o )
( # SC V [ u1 ] = - u1 )
( # SC V [ i1 ] = - i1 )
( # SC V [ i ] = - i )
( # SC V [ u ] = - u )
( # SC V [ ax ] = - ax )
( [ u i1 ] = u - i1 )
( V [ SC ] V = - SC ) ; ; Ex : : d u - y ax
( V [ w ] V = - w )
( V [ j ] V = - j )
hiat break
( [ VWT VA ] = VWT - VA ) ; ; Ex : : i1 - ax t
( [ i1 a ] = i1 - a )
( [ i1 ax ] = i1 - ax )
( [ i1 e ] = i1 - e )
( [ i1 i ] = i1 - i )
( [ i1 o ] = i1 - o )
( [ i1 u ] = i1 - u )
( [ i1 a ] = i1 - a )
( [ i1 ax ] = i1 - ax )
( [ i1 e ] = i1 - e )
( [ i1 i ] = i1 - i )
( [ i1 o ] = i1 - o )
( [ i1 u ] = i1 - u )
( [ u1 a ] = u1 - a )
( [ u1 ax ] = u1 - ax )
( [ u1 e ] = u1 - e )
( [ u1 i ] = u1 - i )
( [ u1 o ] = u1 - o )
( [ u1 u ] = u1 - u )
( [ u1 a ] = u1 - a )
( [ u1 ax ] = u1 - ax )
( [ u1 e ] = u1 - e )
( [ u1 i ] = u1 - i )
( [ u1 o ] = u1 - o )
( [ u1 u ] = u1 - u )
( C u [ ax ] C = - ax )
( VT [ a1 ] = - a1 )
( VT [ E1 ] = - E1 )
( VT [ e1 ] = - e1 )
( VT [ O1 ] = - O1 )
( VT [ o1 ] = - o1 )
( VT [ u1 ] = - u1 )
( VT [ i1 ] = - i1 )
( ax [ i ] = - i )
( ax [ u ] = - u )
( i1 [ ax ] = - ax )
( u [ i1 ] = - i1 )
( u [ u1 ] = - u1 )
( [ i u ] = i - u )
( [ ax i1 ] = ax - i1 )
( C * [ i ax ] C * = i - ax )
( C * [ u ax ] C * = u - ax )
( C * [ i ax ] # = i - ax )
( C * [ u ax ] # = u - ax )
( VNIU [ ax ] = - ax )
( VNIU [ a ] = - a )
( VNIU [ a1 ] = - a1 )
( VNIU [ e1 ] = - e1 )
( VNIU [ E1 ] = - E1 )
( VNIU [ e ] = - e )
( VNIU [ O1 ] = - O1 )
( VNIU [ O ] = - O )
( VNIU [ o ] = - o )
( VNIU [ o1 ] = - o1 )
( [ e1 i ] = e1 - i )
( VA [ VWT ] = - VWT ) ; ; Ex : beneït : b ax - n ax - i1 t
( VA [ i1 ] = - i1 )
( VA [ u1 ] = - u1 )
( ax [ i1 ] = - i1 )
( ax [ u1 ] = - u1 )
( VW [ VT ] = - VT ) ; ; Ex : marià : m ax - r i - a1
( u [ i1 ] = - i1 )
( VW [ i1 ] = - i1 )
( VW [ u1 ] = - u1 )
( VW [ O1 ] = - O1 )
( VW [ o1 ] = - o1 )
( VW [ a1 ] = - a1 )
( VW [ e1 ] = - e1 )
( VW [ E1 ] = - E1 )
;; prova
; ( [ bb ] = b - b )
; ( [ gg ] = g - g )
( [ V SV ] = V SV ) ; ; Ex : : n O1 j
( [ a1 j ] C V = a1 j - )
( [ a1 j ] = a1 j )
( [ a j ] = a j )
( [ E1 j ] = E1 j )
( [ e1 j ] = e1 j )
( [ e j ] = e j )
( [ O1 j ] = O1 j )
( [ o1 j ] = o1 j )
( [ o j ] = o j )
( [ u1 j ] = u1 j )
( [ i1 j ] = i1 j )
( [ i j ] = i j )
( [ u j ] = u j )
( [ ax j ] = ax j )
( [ a1 w ] = a1 w )
( [ a w ] = a w )
( [ E1 w ] = E1 w )
( [ e1 w ] = e1 w )
( [ e w ] = e w )
( [ O1 w ] = O1 w )
( [ o1 w ] = o1 w )
( [ o w ] = o w )
( [ u1 w ] = u1 w )
( [ i1 w ] = i1 w )
( [ i w ] = i w )
( [ u w ] = u w )
( [ ax w ] = ax w )
( ax w [ s ] t r = s - )
( ax w [ s ] t V = s - )
( ax w [ k ] C V = k - )
;; Others hiat
;; ( V [ V ] = - V ) ;;
( V [ a1 ] = a1 )
( V [ a ] = a )
( V [ E1 ] = E1 )
( V [ e1 ] = e1 )
( V [ e ] = e )
( V [ O1 ] = O1 )
( V [ o1 ] = o1 )
( V [ o ] = o )
( V [ u1 ] = u1 )
( V [ i1 ] = i1 )
( V [ i ] = i )
( V [ u ] = u )
( V [ ax ] = ax )
( C [ u ] VW C = u - )
( C [ i ] VW C = i - )
( C [ u ] ax = u - )
( V [ s ] SC = - s )
( j [ o1 ] = - o1 )
( [ e1 u ] = e1 - u1 )
( [ e i1 ] = e - i1 )
- finals de paraula
( A [ g w ] = - g w )
( C [ k w ] = - k w )
( [ g m ] = g - m )
( VA [ i ] t = - i1 )
( VA [ u ] t = - u1 )
( V [ n t ] # = n )
( [ n t s ] = n s )
( [ d s ] # = s )
( [ d ] # = t )
( C [ t ] # = t )
( V [ l k ] # = l k )
( V [ rr p s ] # = rr p s )
( V [ rr p ] # = rr p )
( V [ s t s ] # = s t s )
( V [ m f s ] # = m f s )
( V [ m f ] # = m f )
( [ rr n ] # = rr n )
( j [ t ] # = t )
( [ rr n s ] # = rr n s )
( [ l m ] # = l m )
( [ l m s ] # = l m s )
( [ k s t ] # = k s t )
( j [ k ] = k )
( j [ k s ] = k s )
( [ j k ] # = j k )
( [ k s t s ] # = k s t s )
( # [ p s ] = p s )
( [ s k s ] = s k s )
( [ rr m ] # = rr m )
( [ rr m s ] # = rr m s )
( [ rr k ] # = rr k )
( [ rr k s ] # = rr k s )
( [ l k s ] # = l k s )
( [ l t s ] # = l t s )
( j [ t s ] # = t s )
( [ t r ] = - t r )
( [ t rr ] = - t rr )
;; Semi-vowels break
Ex : reis : rr E1 j s
( V SV [ C ] = - C ) ; ; Ex : : s ax j - t o1
( # ax u [ g ] = g )
( V SV [ p ] = - p )
( V SV [ b ] = - b )
( V SV [ t ] = - t )
( V SV [ d ] = - d )
( V SV [ k ] = - k )
( V SV [ g ] = - g )
( V SV [ f ] = - f )
( V SV [ s ] = - s )
( V SV [ z ] = - z )
( V SV [ S ] = - S )
( V SV [ Z ] = - Z )
( V SV [ m ] = - m )
( V SV [ n ] = - n )
( V SV [ J ] = - J )
( V SV [ l ] = - l )
( V SV [ L ] = - L )
( V SV [ r ] = - r )
( V SV [ rr ] = - rr )
( V SV [ w ] = - w )
( V SV [ j ] = - j )
( V SV [ w ] = - w )
valid CC groups
( V * [ s ] t = s )
( V C * [ b l ] V = - b l ) ;; Ex: blanca : b l a1 N - k ax
( V C * [ b r ] V = - b r ) ;; Ex: setembre : s ax - t e1 m - b r ax
( V C * [ k l ] V = - k l ) ;; Ex: inclús : i N - k l u1 s
( V C * [ k r ] V = - k r ) ;; Ex: concret : k u N - k r e1 t
Ex : : f O1 k s
( V C * [ d r ] V = - d r ) ;; Ex : drenar : d r ax - n a1
( V C * [ f l ] V = - f l ) ;; Ex: inflar : i m - f l a1
Ex : : f r ax - t i - s i1 - D ax
( V C * [ f rr ] V = - f rr )
Ex : aglà : ax - g l a1
( V C * [ g r ] V = - g r ) ;; Ex: grapa: g r a1 - p ax
( V C * [ p l ] V = - p l ) ;; Ex: platja: p l a1 d - Z ax
( V C * [ p r ] V = - p r ) ;; Ex: promoció: p r u - m u - s i - o1
( V C * [ p rr ] V = - p r )
( [ t rr ] = - t r ) ;; Ex: treball: t r ax - B a1 L
( [ t r ] = - t r )
( V C * [ n s ] C = n s )
( V C * [ n s ] V = n - s )
( V C * [ J s ] = J s )
( w [ t r ] V = - t r )
( V [ s k ] # = s k ) ;; Ex: francesc : f r ax n - s e1 s k
( j [ b r ] V = - b r )
( # [ b l ] V = b l ) ;; Ex: blanca : b l a1 N k ax
( # [ b r ] V = b r ) ;; Ex: setembre : s ax t e1 m b r ax
( # [ k l ] V = k l ) ;; Ex: inclús : i N k l u1 s
( # [ k r ] V = k r ) ;; Ex: concret : k u N k r e1 t
Ex : : f O1 k s
( # [ d r ] V = d r ) ;; Ex : drenar : d r ax n a1
( # [ f l ] V = f l ) ;; Ex: inflar : i m f l a1
Ex : : f r ax t i s i1 D ax
( # [ f rr ] V = f rr )
Ex : : ax g l a1
( # [ g r ] V = g r ) ;; Ex: grapa: g r a1 p ax
( # [ p l ] V = p l ) ;; Ex: platja: p l a1 d Z ax
( # [ p r ] V = p r ) ;; Ex: promoció: p r u m u s i o1
( # [ p rr ] V = p r )
( # [ t rr ] V = t r ) ;; Ex: treball: t r ax B a1 L
( # [ t r ] V = t r )
( V [ s k ] # = s k ) ;; Ex: francesc : f r ax n - s e1 s k
( V [ k s ] C V = k s - )
( V [ k s ] C C V = k s - )
( V [ k w ] = - k w )
( [ ax k w ] = ax - k w )
( V [ p s ] C = p s - )
( [ n z ] C V * = n z - )
( j [ t ] C V = t - )
( V [ L ] C = L - ) ; ; Ex : : B ax L - t e1 rr
;; If any consonant is followed by a vowel and there is a vowel
;; before it, its a syl break
;; the consonant cluster are dealt with above
( w [ k ] s = k )
( rr [ s ] C = s - )
( n [ g w ] = - g w )
( n [ g ] = - g )
( V C * [ b ] V = - b )
( V C * [ z ] V = - z )
( V C * [ d ] V = - d )
( V C * [ f ] V = - f )
( V C * [ g ] V = - g )
( V C * [ S ] V = - S )
( V C * [ k ] V = - k )
( V C * [ l ] V = - l )
( V C * [ Z ] V = - Z )
( V C * [ m ] V = - m )
( V C * [ n ] V = - n )
( V C * [ J ] V = - J )
( V C * [ p ] V = - p )
( V C * [ r ] V = - r )
( V C * [ rr ] V = - rr )
( V C * [ s ] V = - s )
( V C * [ t ] V = - t )
( V C * [ L ] V = - L )
;; ( V C * [ y ] V = - y )
( V C * [ w ] V = - w )
( V C * [ j ] V = - j )
( V C * [ w ] V = - w )
( C [ j ] C V = j - )
( [ n s ] C = n s - )
;; Catch all consonants on their own (at end of word)
;; and vowels not preceded by vowels are just written as it
( C [ s ] # = s )
( C [ b ] = - b )
( C [ z ] = - z )
( C [ d ] = - d )
( C [ f ] = - f )
( C [ g ] = - g )
( C [ S ] = - S )
( C [ k ] = - k )
( C [ l ] = - l )
( C [ Z ] = - Z )
( C [ m ] = - m )
( C [ n ] = - n )
( C [ J ] = - J )
( C [ p ] = - p )
( t [ r ] = r )
( C [ r ] = - r )
( C [ rr ] = - rr )
( C [ s ] = - s )
( C [ t ] = - t )
( C [ L ] = - L )
;( C [ y ] = - y )
( C [ w ] = - w )
( C [ j ] = - j )
( [ b ] = b )
( [ z ] = z )
( [ d ] = d )
( [ f ] = f )
( [ g ] = g )
( [ S ] = S )
( [ k ] = k )
( [ l ] = l )
( [ Z ] = Z )
( [ m ] = m )
( [ n ] = n )
( [ J ] = J )
( [ p ] = p )
( [ r ] = r )
( [ rr ] = rr )
( [ s ] = s )
( [ t ] = t )
( [ L ] = L )
( [ w ] = w )
( [ j ] = j )
( [ w ] = w )
( [ a1 ] = a1 )
( [ a ] = a )
( [ E1 ] = E1 )
( [ E ] = E )
( [ e1 ] = e1 )
( [ e ] = e )
( [ O1 ] = O1 )
( [ O ] = O )
( [ o1 ] = o1 )
( [ o ] = o )
( [ u1 ] = u1 )
( [ u ] = u )
( [ i1 ] = i1 )
( [ i ] = i )
( [ ax ] = ax )
)
)
(lex.select oldlex)
)
)
(provide 'upclex_central)
| null | https://raw.githubusercontent.com/FestCat/festival-ca/f6b2d9bf4fc4f77b80890ebb95770075ad36ccaf/src/data/festival/lib/dicts/upc/upclex_central.scm | scheme |
Words to be added in future versions:
Currently prediction is bad for these words:
<Empty (for now)>
Common words on the internet
gmail, hotmail, facebook
;;; Symbols ...
Basic punctuation must be in with nil pronunciation
Sons i u àtons (vocals dèbils)
(SC y w ) ;; Sons semi-consonàntics
; Sons semi - vocàlics
Sons semi-consonàntics (allophone removed)
Sons semi-vocàlics (allophones removed)
Rules will add - at syllable boundary
Diftongs creixents
; Ex : quotidià : k w u - t i - d i - a1
Semi-consonants break
( # SC V [ A ] = - A ) ;; Ex: iode: y o - d ax
; Ex : : d u - y ax
; Ex : : i1 - ax t
; Ex : beneït : b ax - n ax - i1 t
; Ex : marià : m ax - r i - a1
prova
( [ bb ] = b - b )
( [ gg ] = g - g )
; Ex : : n O1 j
Others hiat
( V [ V ] = - V ) ;;
Semi-vowels break
; Ex : : s ax j - t o1
Ex: blanca : b l a1 N - k ax
Ex: setembre : s ax - t e1 m - b r ax
Ex: inclús : i N - k l u1 s
Ex: concret : k u N - k r e1 t
Ex : drenar : d r ax - n a1
Ex: inflar : i m - f l a1
Ex: grapa: g r a1 - p ax
Ex: platja: p l a1 d - Z ax
Ex: promoció: p r u - m u - s i - o1
Ex: treball: t r ax - B a1 L
Ex: francesc : f r ax n - s e1 s k
Ex: blanca : b l a1 N k ax
Ex: setembre : s ax t e1 m b r ax
Ex: inclús : i N k l u1 s
Ex: concret : k u N k r e1 t
Ex : drenar : d r ax n a1
Ex: inflar : i m f l a1
Ex: grapa: g r a1 p ax
Ex: platja: p l a1 d Z ax
Ex: promoció: p r u m u s i o1
Ex: treball: t r ax B a1 L
Ex: francesc : f r ax n - s e1 s k
; Ex : : B ax L - t e1 rr
If any consonant is followed by a vowel and there is a vowel
before it, its a syl break
the consonant cluster are dealt with above
( V C * [ y ] V = - y )
Catch all consonants on their own (at end of word)
and vowels not preceded by vowels are just written as it
( C [ y ] = - y ) | Lexicon , LTS and Postlexical rules for upc_catalan
Adapted for Catalan by the UPC team
( c )
Universitat Politècnica de Catalunya , Barcelona , Spain
(define (upc_catalan_addenda_central)
"(upc_catalan_addenda_central)
Basic lexicon should (must ?) have basic letters, symbols and punctuation."
(lex.add.entry '("hotmail" n ( ((o1 t) 1 ) ( ( m E1 i1 l ) 0 ) ) ) )
(lex.add.entry '("gmail" n ( ((Z E1) 1 ) ( ( m E1 i1 l ) 0 ) ) ) )
(lex.add.entry '("facebook" n ( ((f E1 i1 s) 1 ) ( ( b u k ) 0 ) ) ) )
(lex.add.entry '("copyright" n ( ((k O1) 1 ) ((p i) 0 ) ((rr a i t) 0) ) ))
(lex.add.entry '("wikipedia" n ( ( (g w i) 0 ) ((k i) 0 ) ( (p E1) 1 ) ( (d i) 0 ) ( (ax) 0) ) ))
(lex.add.entry '("twitter" n ( ( (t w i1) 1 ) ( (t e r) 0 ) ) ) )
(lex.add.entry '("debian" n ( ( (d e1) 1 ) ( (b i ) 0 ) ( ( ax n) 0) )))
(lex.add.entry '("linux" n ( ( (l i1) 1 ) ( (n u k s) 0 ) )))
(lex.add.entry '("google" n ( ( (g u) 1 ) ( (g ax l ) 0 ) )))
(lex.add.entry '("*" n (((ax s) 0) ((t e1) 0) ((r i1 s k) 1))))
(lex.add.entry '("%" n (((p ax r) 0) ((s e1 n ) 1))))
(lex.add.entry '("+" n (((m e1 s) 1 ))))
(lex.add.entry '("=" n (((i) 0) ((G w a1 l) 1))))
(lex.add.entry '("€" n (((e1 uw) 1) ((r u) 0))))
(lex.add.entry '("$" n (((d o1 ) 1) ((l ax r) 0))))
(lex.add.entry '("@" n (((ax ) 0) ((rr o1) 1) ((b ax) 0))))
(lex.add.entry '("/" n (((b a1 ) 1) ((rr ax ) 0))))
)
(define (upclex_catalan_define_ruleset_syl_central )
"Define a ruleset to do syllabification"
(let (
(oldlex (lex.select "upc_catalan-central"))
)
(lts.ruleset
upc_catalan_syl
Sons vocàlics
(V a a1 E1 e1 e O1 o1 o u1 i1 i u ax)
Sons vocàlics àtons
(VA a e i o u )
Vocals , " i " i " u "
(VGQ ax a1 o1 O1 o u)
Sons i u tònics ( vocals dèbils en )
Sons vocàlics tònics
(GQ k g )
(C p t b d k g f s z S Z m n J l L r rr)
(A a a1 E E1 e e1 O O1 o o1 u u1 i i1 ax p t k b d g f s z S Z m n J l L r rr w j )
)
(
( [ k w ax ] = - k w ax )
( [ k w a ] = - k w a )
( [ k w a1 ] = - k w a1 )
( [ k w o1 ] = - k w o1 )
( [ k w O1 ] = - k w O1 )
( [ k w o ] = - k w o )
( [ k w u ] = - k w u )
( [ g w ax ] = - g w ax )
( [ g w a ] = - g w a )
( [ g w a1 ] = - g w a1 )
( [ g w o1 ] = - g w o1 )
( [ g w O1 ] = - g w O1 )
( [ g w o ] = - g w o )
( [ g w u ] = - g w u )
Correccions LTS
( V [ s j ] = - s j )
( j [ t ] s V = t - )
( # SC V [ a ] = - a )
( # SC V [ a1 ] = - a1 )
( # SC V [ E1 ] = - E1 )
( # SC V [ e1 ] = - e1 )
( # SC V [ e ] = - e )
( # SC V [ O1 ] = - O1 )
( # SC V [ o1 ] = - o1 )
( # SC V [ o ] = - o )
( # SC V [ u1 ] = - u1 )
( # SC V [ i1 ] = - i1 )
( # SC V [ i ] = - i )
( # SC V [ u ] = - u )
( # SC V [ ax ] = - ax )
( [ u i1 ] = u - i1 )
( V [ w ] V = - w )
( V [ j ] V = - j )
hiat break
( [ i1 a ] = i1 - a )
( [ i1 ax ] = i1 - ax )
( [ i1 e ] = i1 - e )
( [ i1 i ] = i1 - i )
( [ i1 o ] = i1 - o )
( [ i1 u ] = i1 - u )
( [ i1 a ] = i1 - a )
( [ i1 ax ] = i1 - ax )
( [ i1 e ] = i1 - e )
( [ i1 i ] = i1 - i )
( [ i1 o ] = i1 - o )
( [ i1 u ] = i1 - u )
( [ u1 a ] = u1 - a )
( [ u1 ax ] = u1 - ax )
( [ u1 e ] = u1 - e )
( [ u1 i ] = u1 - i )
( [ u1 o ] = u1 - o )
( [ u1 u ] = u1 - u )
( [ u1 a ] = u1 - a )
( [ u1 ax ] = u1 - ax )
( [ u1 e ] = u1 - e )
( [ u1 i ] = u1 - i )
( [ u1 o ] = u1 - o )
( [ u1 u ] = u1 - u )
( C u [ ax ] C = - ax )
( VT [ a1 ] = - a1 )
( VT [ E1 ] = - E1 )
( VT [ e1 ] = - e1 )
( VT [ O1 ] = - O1 )
( VT [ o1 ] = - o1 )
( VT [ u1 ] = - u1 )
( VT [ i1 ] = - i1 )
( ax [ i ] = - i )
( ax [ u ] = - u )
( i1 [ ax ] = - ax )
( u [ i1 ] = - i1 )
( u [ u1 ] = - u1 )
( [ i u ] = i - u )
( [ ax i1 ] = ax - i1 )
( C * [ i ax ] C * = i - ax )
( C * [ u ax ] C * = u - ax )
( C * [ i ax ] # = i - ax )
( C * [ u ax ] # = u - ax )
( VNIU [ ax ] = - ax )
( VNIU [ a ] = - a )
( VNIU [ a1 ] = - a1 )
( VNIU [ e1 ] = - e1 )
( VNIU [ E1 ] = - E1 )
( VNIU [ e ] = - e )
( VNIU [ O1 ] = - O1 )
( VNIU [ O ] = - O )
( VNIU [ o ] = - o )
( VNIU [ o1 ] = - o1 )
( [ e1 i ] = e1 - i )
( VA [ i1 ] = - i1 )
( VA [ u1 ] = - u1 )
( ax [ i1 ] = - i1 )
( ax [ u1 ] = - u1 )
( u [ i1 ] = - i1 )
( VW [ i1 ] = - i1 )
( VW [ u1 ] = - u1 )
( VW [ O1 ] = - O1 )
( VW [ o1 ] = - o1 )
( VW [ a1 ] = - a1 )
( VW [ e1 ] = - e1 )
( VW [ E1 ] = - E1 )
( [ a1 j ] C V = a1 j - )
( [ a1 j ] = a1 j )
( [ a j ] = a j )
( [ E1 j ] = E1 j )
( [ e1 j ] = e1 j )
( [ e j ] = e j )
( [ O1 j ] = O1 j )
( [ o1 j ] = o1 j )
( [ o j ] = o j )
( [ u1 j ] = u1 j )
( [ i1 j ] = i1 j )
( [ i j ] = i j )
( [ u j ] = u j )
( [ ax j ] = ax j )
( [ a1 w ] = a1 w )
( [ a w ] = a w )
( [ E1 w ] = E1 w )
( [ e1 w ] = e1 w )
( [ e w ] = e w )
( [ O1 w ] = O1 w )
( [ o1 w ] = o1 w )
( [ o w ] = o w )
( [ u1 w ] = u1 w )
( [ i1 w ] = i1 w )
( [ i w ] = i w )
( [ u w ] = u w )
( [ ax w ] = ax w )
( ax w [ s ] t r = s - )
( ax w [ s ] t V = s - )
( ax w [ k ] C V = k - )
( V [ a1 ] = a1 )
( V [ a ] = a )
( V [ E1 ] = E1 )
( V [ e1 ] = e1 )
( V [ e ] = e )
( V [ O1 ] = O1 )
( V [ o1 ] = o1 )
( V [ o ] = o )
( V [ u1 ] = u1 )
( V [ i1 ] = i1 )
( V [ i ] = i )
( V [ u ] = u )
( V [ ax ] = ax )
( C [ u ] VW C = u - )
( C [ i ] VW C = i - )
( C [ u ] ax = u - )
( V [ s ] SC = - s )
( j [ o1 ] = - o1 )
( [ e1 u ] = e1 - u1 )
( [ e i1 ] = e - i1 )
- finals de paraula
( A [ g w ] = - g w )
( C [ k w ] = - k w )
( [ g m ] = g - m )
( VA [ i ] t = - i1 )
( VA [ u ] t = - u1 )
( V [ n t ] # = n )
( [ n t s ] = n s )
( [ d s ] # = s )
( [ d ] # = t )
( C [ t ] # = t )
( V [ l k ] # = l k )
( V [ rr p s ] # = rr p s )
( V [ rr p ] # = rr p )
( V [ s t s ] # = s t s )
( V [ m f s ] # = m f s )
( V [ m f ] # = m f )
( [ rr n ] # = rr n )
( j [ t ] # = t )
( [ rr n s ] # = rr n s )
( [ l m ] # = l m )
( [ l m s ] # = l m s )
( [ k s t ] # = k s t )
( j [ k ] = k )
( j [ k s ] = k s )
( [ j k ] # = j k )
( [ k s t s ] # = k s t s )
( # [ p s ] = p s )
( [ s k s ] = s k s )
( [ rr m ] # = rr m )
( [ rr m s ] # = rr m s )
( [ rr k ] # = rr k )
( [ rr k s ] # = rr k s )
( [ l k s ] # = l k s )
( [ l t s ] # = l t s )
( j [ t s ] # = t s )
( [ t r ] = - t r )
( [ t rr ] = - t rr )
Ex : reis : rr E1 j s
( # ax u [ g ] = g )
( V SV [ p ] = - p )
( V SV [ b ] = - b )
( V SV [ t ] = - t )
( V SV [ d ] = - d )
( V SV [ k ] = - k )
( V SV [ g ] = - g )
( V SV [ f ] = - f )
( V SV [ s ] = - s )
( V SV [ z ] = - z )
( V SV [ S ] = - S )
( V SV [ Z ] = - Z )
( V SV [ m ] = - m )
( V SV [ n ] = - n )
( V SV [ J ] = - J )
( V SV [ l ] = - l )
( V SV [ L ] = - L )
( V SV [ r ] = - r )
( V SV [ rr ] = - rr )
( V SV [ w ] = - w )
( V SV [ j ] = - j )
( V SV [ w ] = - w )
valid CC groups
( V * [ s ] t = s )
Ex : : f O1 k s
Ex : : f r ax - t i - s i1 - D ax
( V C * [ f rr ] V = - f rr )
Ex : aglà : ax - g l a1
( V C * [ p rr ] V = - p r )
( [ t r ] = - t r )
( V C * [ n s ] C = n s )
( V C * [ n s ] V = n - s )
( V C * [ J s ] = J s )
( w [ t r ] V = - t r )
( j [ b r ] V = - b r )
Ex : : f O1 k s
Ex : : f r ax t i s i1 D ax
( # [ f rr ] V = f rr )
Ex : : ax g l a1
( # [ p rr ] V = p r )
( # [ t r ] V = t r )
( V [ k s ] C V = k s - )
( V [ k s ] C C V = k s - )
( V [ k w ] = - k w )
( [ ax k w ] = ax - k w )
( V [ p s ] C = p s - )
( [ n z ] C V * = n z - )
( j [ t ] C V = t - )
( w [ k ] s = k )
( rr [ s ] C = s - )
( n [ g w ] = - g w )
( n [ g ] = - g )
( V C * [ b ] V = - b )
( V C * [ z ] V = - z )
( V C * [ d ] V = - d )
( V C * [ f ] V = - f )
( V C * [ g ] V = - g )
( V C * [ S ] V = - S )
( V C * [ k ] V = - k )
( V C * [ l ] V = - l )
( V C * [ Z ] V = - Z )
( V C * [ m ] V = - m )
( V C * [ n ] V = - n )
( V C * [ J ] V = - J )
( V C * [ p ] V = - p )
( V C * [ r ] V = - r )
( V C * [ rr ] V = - rr )
( V C * [ s ] V = - s )
( V C * [ t ] V = - t )
( V C * [ L ] V = - L )
( V C * [ w ] V = - w )
( V C * [ j ] V = - j )
( V C * [ w ] V = - w )
( C [ j ] C V = j - )
( [ n s ] C = n s - )
( C [ s ] # = s )
( C [ b ] = - b )
( C [ z ] = - z )
( C [ d ] = - d )
( C [ f ] = - f )
( C [ g ] = - g )
( C [ S ] = - S )
( C [ k ] = - k )
( C [ l ] = - l )
( C [ Z ] = - Z )
( C [ m ] = - m )
( C [ n ] = - n )
( C [ J ] = - J )
( C [ p ] = - p )
( t [ r ] = r )
( C [ r ] = - r )
( C [ rr ] = - rr )
( C [ s ] = - s )
( C [ t ] = - t )
( C [ L ] = - L )
( C [ w ] = - w )
( C [ j ] = - j )
( [ b ] = b )
( [ z ] = z )
( [ d ] = d )
( [ f ] = f )
( [ g ] = g )
( [ S ] = S )
( [ k ] = k )
( [ l ] = l )
( [ Z ] = Z )
( [ m ] = m )
( [ n ] = n )
( [ J ] = J )
( [ p ] = p )
( [ r ] = r )
( [ rr ] = rr )
( [ s ] = s )
( [ t ] = t )
( [ L ] = L )
( [ w ] = w )
( [ j ] = j )
( [ w ] = w )
( [ a1 ] = a1 )
( [ a ] = a )
( [ E1 ] = E1 )
( [ E ] = E )
( [ e1 ] = e1 )
( [ e ] = e )
( [ O1 ] = O1 )
( [ O ] = O )
( [ o1 ] = o1 )
( [ o ] = o )
( [ u1 ] = u1 )
( [ u ] = u )
( [ i1 ] = i1 )
( [ i ] = i )
( [ ax ] = ax )
)
)
(lex.select oldlex)
)
)
(provide 'upclex_central)
|
ee03d5cc38d4e6e7b26d87b39a305588a76de03f12f8eb57c2d7a01d2ed85060 | semilin/layoup | Oneproduct.lisp |
(MAKE-LAYOUT :NAME "Oneproduct" :MATRIX
(APPLY #'KEY-MATRIX '("pldwgjxoyq" "nrstmuaeih" "zcfvb,.';k"))
:SHIFT-MATRIX NIL :KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/Oneproduct.lisp | lisp |
(MAKE-LAYOUT :NAME "Oneproduct" :MATRIX
(APPLY #'KEY-MATRIX '("pldwgjxoyq" "nrstmuaeih" "zcfvb,.';k"))
:SHIFT-MATRIX NIL :KEYBOARD NIL) |
|
e748050643c674eea9411843dbf24bd884ef69a5777dcaac3a0eadeb8dafdcde | metosin/tyylikas | project.clj | (defproject tyylikas "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[rewrite-clj "0.6.0"]])
| null | https://raw.githubusercontent.com/metosin/tyylikas/e2d57acf86df38fb0aafed2c14a64bdd1602a87e/project.clj | clojure | (defproject tyylikas "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[rewrite-clj "0.6.0"]])
|
|
4d99cdda42ceccab24f1c9ea20f3932b72d37938cd2bcecf7f0e12a466cbb585 | lingnand/VIMonad | GridVariants.hs | # LANGUAGE DeriveDataTypeable , FlexibleInstances , MultiParamTypeClasses #
----------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.GridVariants
Copyright : ( c )
-- License : BSD-style (see LICENSE)
--
-- Maintainer :
-- Stability : unstable
-- Portability : unportable
--
Two layouts : one is a variant of the Grid layout that allows the
-- desired aspect ratio of windows to be specified. The other is like
-- Tall but places a grid with fixed number of rows and columns in the
-- master area and uses an aspect-ratio-specified layout for the
-- slaves.
----------------------------------------------------------------------
module XMonad.Layout.GridVariants ( -- * Usage
-- $usage
ChangeMasterGridGeom(..)
, ChangeGridGeom(..)
, Grid(..)
, TallGrid(..)
, SplitGrid(..)
, Orientation(..)
) where
import Control.Monad
import XMonad
import qualified XMonad.StackSet as W
-- $usage
-- This module can be used as follows:
--
> import XMonad . Layout . GridVariants
--
-- Then add something like this to your layouts:
--
> Grid ( 16/10 )
--
for a 16:10 aspect ratio grid , or
--
> SplitGrid L 2 3 ( 2/3 ) ( 16/10 ) ( 5/100 )
--
for a layout with a 2x3 master grid that uses 2/3 of the screen ,
and a 16:10 aspect ratio slave grid to its right . The last
-- parameter is again the percentage by which the split between master
-- and slave area changes in response to Expand/Shrink messages.
--
-- To be able to change the geometry of the master grid, add something
-- like this to your keybindings:
--
> ( ( modm .| . shiftMask , xK_equal ) , sendMessage $ IncMasterCols 1 ) ,
-- > ((modm .|. shiftMask, xK_minus), sendMessage $ IncMasterCols (-1)),
> ( ( modm .| . controlMask , xK_equal ) , sendMessage $ IncMasterRows 1 ) ,
> ( ( modm .| . controlMask , xK_minus ) , sendMessage $ IncMasterRows ( -1 ) )
-- | Grid layout. The parameter is the desired x:y aspect ratio of windows
data Grid a = Grid !Rational
deriving (Read, Show)
instance LayoutClass Grid a where
pureLayout (Grid aspect) rect st = zip wins rects
where
wins = W.integrate st
nwins = length wins
rects = arrangeAspectGrid rect nwins aspect
pureMessage layout msg = fmap (changeGridAspect layout) (fromMessage msg)
description _ = "Grid"
changeGridAspect :: Grid a -> ChangeGridGeom -> Grid a
changeGridAspect (Grid _) (SetGridAspect aspect) = Grid aspect
changeGridAspect (Grid aspect) (ChangeGridAspect delta) =
Grid (max 0.00001 (aspect + delta))
|Geometry change messages understood by Grid and SplitGrid
data ChangeGridGeom
= SetGridAspect !Rational
| ChangeGridAspect !Rational
deriving Typeable
instance Message ChangeGridGeom
-- |SplitGrid layout. Parameters are
--
-- - side where the master is
-- - number of master rows
-- - number of master columns
-- - portion of screen used for master grid
-- - x:y aspect ratio of slave windows
-- - increment for resize messages
data SplitGrid a = SplitGrid Orientation !Int !Int !Rational !Rational !Rational
deriving (Read, Show)
-- |Type to specify the side of the screen that holds
the master area of a SplitGrid .
data Orientation = T | B | L | R
deriving (Eq, Read, Show)
instance LayoutClass SplitGrid a where
pureLayout (SplitGrid o mrows mcols mfrac saspect _) rect st = zip wins rects
where
wins = W.integrate st
nwins = length wins
rects = arrangeSplitGrid rect o nwins mrows mcols mfrac saspect
pureMessage layout msg =
msum [ fmap (resizeMaster layout) (fromMessage msg)
, fmap (changeMasterGrid layout) (fromMessage msg)
, fmap (changeSlaveGridAspect layout) (fromMessage msg)
]
description _ = "SplitGrid"
-- |The geometry change message understood by the master grid
data ChangeMasterGridGeom
= IncMasterRows !Int -- ^Change the number of master rows
| IncMasterCols !Int -- ^Change the number of master columns
| SetMasterRows !Int -- ^Set the number of master rows to absolute value
| SetMasterCols !Int -- ^Set the number of master columns to absolute value
| SetMasterFraction !Rational -- ^Set the fraction of the screen used by the master grid
deriving Typeable
instance Message ChangeMasterGridGeom
arrangeSplitGrid :: Rectangle -> Orientation -> Int -> Int -> Int -> Rational -> Rational -> [Rectangle]
arrangeSplitGrid rect@(Rectangle rx ry rw rh) o nwins mrows mcols mfrac saspect
| nwins <= mwins = arrangeMasterGrid rect nwins mcols
| mwins == 0 = arrangeAspectGrid rect nwins saspect
| otherwise = (arrangeMasterGrid mrect mwins mcols) ++
(arrangeAspectGrid srect swins saspect)
where
mwins = mrows * mcols
swins = nwins - mwins
mrect = Rectangle mx my mw mh
srect = Rectangle sx sy sw sh
(mh, sh, mw, sw) = if o `elem` [T, B] then
(ceiling (fromIntegral rh * mfrac), rh - mh, rw, rw)
else
(rh, rh, ceiling (fromIntegral rw * mfrac), rw - mw)
mx = fromIntegral rx + if o == R then fromIntegral sw else 0
my = fromIntegral ry + if o == B then fromIntegral sh else 0
sx = fromIntegral rx + if o == L then fromIntegral mw else 0
sy = fromIntegral ry + if o == T then fromIntegral mh else 0
arrangeMasterGrid :: Rectangle -> Int -> Int -> [Rectangle]
arrangeMasterGrid rect nwins mcols = arrangeGrid rect nwins (min nwins mcols)
arrangeAspectGrid :: Rectangle -> Int -> Rational -> [Rectangle]
arrangeAspectGrid rect@(Rectangle _ _ rw rh) nwins aspect =
arrangeGrid rect nwins (min nwins ncols)
where
scr_a = fromIntegral rw / fromIntegral rh
fcols = sqrt ( fromRational $ scr_a * fromIntegral nwins / aspect ) :: Double
cols1 = floor fcols :: Int
cols2 = ceiling fcols :: Int
rows1 = ceiling ( fromIntegral nwins / fromIntegral cols1 :: Rational ) :: Int
rows2 = floor ( fromIntegral nwins / fromIntegral cols2 :: Rational ) :: Int
a1 = scr_a * fromIntegral rows1 / fromIntegral cols1
a2 = scr_a * fromIntegral rows2 / fromIntegral cols2
ncols | cols1 == 0 = cols2
| rows2 == 0 = cols1
| a1 / aspect < aspect / a2 = cols1
| otherwise = cols2
arrangeGrid :: Rectangle -> Int -> Int -> [Rectangle]
arrangeGrid (Rectangle rx ry rw rh) nwins ncols =
[Rectangle (fromIntegral x + rx) (fromIntegral y + ry) (fromIntegral w) (fromIntegral h)
| (x, y, w, h) <- rects]
where
nrows_in_cols = listDifference $ splitEvenly nwins ncols
x_slabs = splitIntoSlabs (fromIntegral rw) ncols
y_slabs = [splitIntoSlabs (fromIntegral rh) nrows | nrows <- nrows_in_cols]
rects_in_cols = [[(x, y, w, h) | (y, h) <- lst]
| ((x, w), lst) <- zip x_slabs y_slabs]
rects = foldr (++) [] rects_in_cols
splitIntoSlabs :: Int -> Int -> [(Int, Int)]
splitIntoSlabs width nslabs = zip (0:xs) widths
where
xs = splitEvenly width nslabs
widths = listDifference xs
listDifference :: [Int] -> [Int]
listDifference lst = [cur-pre | (cur,pre) <- zip lst (0:lst)]
splitEvenly :: Int -> Int -> [Int]
splitEvenly n parts = [ sz-off | (sz,off) <- zip sizes offsets]
where
size = ceiling ( (fromIntegral n / fromIntegral parts) :: Double )
extra = size*parts - n
sizes = [i*size | i <- [1..parts]]
offsets = (take (fromIntegral extra) [1..]) ++ [extra,extra..]
resizeMaster :: SplitGrid a -> Resize -> SplitGrid a
resizeMaster (SplitGrid o mrows mcols mfrac saspect delta) Shrink =
SplitGrid o mrows mcols (max 0 (mfrac - delta)) saspect delta
resizeMaster (SplitGrid o mrows mcols mfrac saspect delta) Expand =
SplitGrid o mrows mcols (min 1 (mfrac + delta)) saspect delta
changeMasterGrid :: SplitGrid a -> ChangeMasterGridGeom -> SplitGrid a
changeMasterGrid (SplitGrid o mrows mcols mfrac saspect delta) (IncMasterRows d) =
SplitGrid o (max 0 (mrows + d)) mcols mfrac saspect delta
changeMasterGrid (SplitGrid o mrows mcols mfrac saspect delta) (IncMasterCols d) =
SplitGrid o mrows (max 0 (mcols + d)) mfrac saspect delta
changeMasterGrid (SplitGrid o _ mcols mfrac saspect delta) (SetMasterRows mrows) =
SplitGrid o (max 0 mrows) mcols mfrac saspect delta
changeMasterGrid (SplitGrid o mrows _ mfrac saspect delta) (SetMasterCols mcols) =
SplitGrid o mrows (max 0 mcols) mfrac saspect delta
changeMasterGrid (SplitGrid o mrows mcols _ saspect delta) (SetMasterFraction mfrac) =
SplitGrid o mrows mcols mfrac saspect delta
changeSlaveGridAspect :: SplitGrid a -> ChangeGridGeom -> SplitGrid a
changeSlaveGridAspect (SplitGrid o mrows mcols mfrac _ delta) (SetGridAspect saspect) =
SplitGrid o mrows mcols mfrac saspect delta
changeSlaveGridAspect (SplitGrid o mrows mcols mfrac saspect delta) (ChangeGridAspect sdelta) =
SplitGrid o mrows mcols mfrac (max 0.00001 (saspect + sdelta)) delta
| TallGrid layout . Parameters are
--
-- - number of master rows
-- - number of master columns
-- - portion of screen used for master grid
-- - x:y aspect ratio of slave windows
-- - increment for resize messages
--
-- This exists mostly because it was introduced in an earlier version.
-- It's a fairly thin wrapper around "SplitGrid L".
data TallGrid a = TallGrid !Int !Int !Rational !Rational !Rational
deriving (Read, Show)
instance LayoutClass TallGrid a where
pureLayout (TallGrid mrows mcols mfrac saspect _) rect st = zip wins rects
where
wins = W.integrate st
nwins = length wins
rects = arrangeSplitGrid rect L nwins mrows mcols mfrac saspect
pureMessage layout msg =
msum [ fmap ((tallGridAdapter resizeMaster) layout) (fromMessage msg)
, fmap ((tallGridAdapter changeMasterGrid) layout) (fromMessage msg) ]
description _ = "TallGrid"
tallGridAdapter :: (SplitGrid a -> b -> SplitGrid a) -> TallGrid a -> b -> TallGrid a
tallGridAdapter f (TallGrid mrows mcols mfrac saspect delta) msg =
TallGrid mrows' mcols' mfrac' saspect' delta'
where
SplitGrid _ mrows' mcols' mfrac' saspect' delta' =
f (SplitGrid L mrows mcols mfrac saspect delta) msg
| null | https://raw.githubusercontent.com/lingnand/VIMonad/048e419fc4ef57a5235dbaeef8890faf6956b574/XMonadContrib/XMonad/Layout/GridVariants.hs | haskell | --------------------------------------------------------------------
|
Module : XMonad.Layout.GridVariants
License : BSD-style (see LICENSE)
Maintainer :
Stability : unstable
Portability : unportable
desired aspect ratio of windows to be specified. The other is like
Tall but places a grid with fixed number of rows and columns in the
master area and uses an aspect-ratio-specified layout for the
slaves.
--------------------------------------------------------------------
* Usage
$usage
$usage
This module can be used as follows:
Then add something like this to your layouts:
parameter is again the percentage by which the split between master
and slave area changes in response to Expand/Shrink messages.
To be able to change the geometry of the master grid, add something
like this to your keybindings:
> ((modm .|. shiftMask, xK_minus), sendMessage $ IncMasterCols (-1)),
| Grid layout. The parameter is the desired x:y aspect ratio of windows
|SplitGrid layout. Parameters are
- side where the master is
- number of master rows
- number of master columns
- portion of screen used for master grid
- x:y aspect ratio of slave windows
- increment for resize messages
|Type to specify the side of the screen that holds
|The geometry change message understood by the master grid
^Change the number of master rows
^Change the number of master columns
^Set the number of master rows to absolute value
^Set the number of master columns to absolute value
^Set the fraction of the screen used by the master grid
- number of master rows
- number of master columns
- portion of screen used for master grid
- x:y aspect ratio of slave windows
- increment for resize messages
This exists mostly because it was introduced in an earlier version.
It's a fairly thin wrapper around "SplitGrid L". | # LANGUAGE DeriveDataTypeable , FlexibleInstances , MultiParamTypeClasses #
Copyright : ( c )
Two layouts : one is a variant of the Grid layout that allows the
ChangeMasterGridGeom(..)
, ChangeGridGeom(..)
, Grid(..)
, TallGrid(..)
, SplitGrid(..)
, Orientation(..)
) where
import Control.Monad
import XMonad
import qualified XMonad.StackSet as W
> import XMonad . Layout . GridVariants
> Grid ( 16/10 )
for a 16:10 aspect ratio grid , or
> SplitGrid L 2 3 ( 2/3 ) ( 16/10 ) ( 5/100 )
for a layout with a 2x3 master grid that uses 2/3 of the screen ,
and a 16:10 aspect ratio slave grid to its right . The last
> ( ( modm .| . shiftMask , xK_equal ) , sendMessage $ IncMasterCols 1 ) ,
> ( ( modm .| . controlMask , xK_equal ) , sendMessage $ IncMasterRows 1 ) ,
> ( ( modm .| . controlMask , xK_minus ) , sendMessage $ IncMasterRows ( -1 ) )
data Grid a = Grid !Rational
deriving (Read, Show)
instance LayoutClass Grid a where
pureLayout (Grid aspect) rect st = zip wins rects
where
wins = W.integrate st
nwins = length wins
rects = arrangeAspectGrid rect nwins aspect
pureMessage layout msg = fmap (changeGridAspect layout) (fromMessage msg)
description _ = "Grid"
changeGridAspect :: Grid a -> ChangeGridGeom -> Grid a
changeGridAspect (Grid _) (SetGridAspect aspect) = Grid aspect
changeGridAspect (Grid aspect) (ChangeGridAspect delta) =
Grid (max 0.00001 (aspect + delta))
|Geometry change messages understood by Grid and SplitGrid
data ChangeGridGeom
= SetGridAspect !Rational
| ChangeGridAspect !Rational
deriving Typeable
instance Message ChangeGridGeom
data SplitGrid a = SplitGrid Orientation !Int !Int !Rational !Rational !Rational
deriving (Read, Show)
the master area of a SplitGrid .
data Orientation = T | B | L | R
deriving (Eq, Read, Show)
instance LayoutClass SplitGrid a where
pureLayout (SplitGrid o mrows mcols mfrac saspect _) rect st = zip wins rects
where
wins = W.integrate st
nwins = length wins
rects = arrangeSplitGrid rect o nwins mrows mcols mfrac saspect
pureMessage layout msg =
msum [ fmap (resizeMaster layout) (fromMessage msg)
, fmap (changeMasterGrid layout) (fromMessage msg)
, fmap (changeSlaveGridAspect layout) (fromMessage msg)
]
description _ = "SplitGrid"
data ChangeMasterGridGeom
deriving Typeable
instance Message ChangeMasterGridGeom
arrangeSplitGrid :: Rectangle -> Orientation -> Int -> Int -> Int -> Rational -> Rational -> [Rectangle]
arrangeSplitGrid rect@(Rectangle rx ry rw rh) o nwins mrows mcols mfrac saspect
| nwins <= mwins = arrangeMasterGrid rect nwins mcols
| mwins == 0 = arrangeAspectGrid rect nwins saspect
| otherwise = (arrangeMasterGrid mrect mwins mcols) ++
(arrangeAspectGrid srect swins saspect)
where
mwins = mrows * mcols
swins = nwins - mwins
mrect = Rectangle mx my mw mh
srect = Rectangle sx sy sw sh
(mh, sh, mw, sw) = if o `elem` [T, B] then
(ceiling (fromIntegral rh * mfrac), rh - mh, rw, rw)
else
(rh, rh, ceiling (fromIntegral rw * mfrac), rw - mw)
mx = fromIntegral rx + if o == R then fromIntegral sw else 0
my = fromIntegral ry + if o == B then fromIntegral sh else 0
sx = fromIntegral rx + if o == L then fromIntegral mw else 0
sy = fromIntegral ry + if o == T then fromIntegral mh else 0
arrangeMasterGrid :: Rectangle -> Int -> Int -> [Rectangle]
arrangeMasterGrid rect nwins mcols = arrangeGrid rect nwins (min nwins mcols)
arrangeAspectGrid :: Rectangle -> Int -> Rational -> [Rectangle]
arrangeAspectGrid rect@(Rectangle _ _ rw rh) nwins aspect =
arrangeGrid rect nwins (min nwins ncols)
where
scr_a = fromIntegral rw / fromIntegral rh
fcols = sqrt ( fromRational $ scr_a * fromIntegral nwins / aspect ) :: Double
cols1 = floor fcols :: Int
cols2 = ceiling fcols :: Int
rows1 = ceiling ( fromIntegral nwins / fromIntegral cols1 :: Rational ) :: Int
rows2 = floor ( fromIntegral nwins / fromIntegral cols2 :: Rational ) :: Int
a1 = scr_a * fromIntegral rows1 / fromIntegral cols1
a2 = scr_a * fromIntegral rows2 / fromIntegral cols2
ncols | cols1 == 0 = cols2
| rows2 == 0 = cols1
| a1 / aspect < aspect / a2 = cols1
| otherwise = cols2
arrangeGrid :: Rectangle -> Int -> Int -> [Rectangle]
arrangeGrid (Rectangle rx ry rw rh) nwins ncols =
[Rectangle (fromIntegral x + rx) (fromIntegral y + ry) (fromIntegral w) (fromIntegral h)
| (x, y, w, h) <- rects]
where
nrows_in_cols = listDifference $ splitEvenly nwins ncols
x_slabs = splitIntoSlabs (fromIntegral rw) ncols
y_slabs = [splitIntoSlabs (fromIntegral rh) nrows | nrows <- nrows_in_cols]
rects_in_cols = [[(x, y, w, h) | (y, h) <- lst]
| ((x, w), lst) <- zip x_slabs y_slabs]
rects = foldr (++) [] rects_in_cols
splitIntoSlabs :: Int -> Int -> [(Int, Int)]
splitIntoSlabs width nslabs = zip (0:xs) widths
where
xs = splitEvenly width nslabs
widths = listDifference xs
listDifference :: [Int] -> [Int]
listDifference lst = [cur-pre | (cur,pre) <- zip lst (0:lst)]
splitEvenly :: Int -> Int -> [Int]
splitEvenly n parts = [ sz-off | (sz,off) <- zip sizes offsets]
where
size = ceiling ( (fromIntegral n / fromIntegral parts) :: Double )
extra = size*parts - n
sizes = [i*size | i <- [1..parts]]
offsets = (take (fromIntegral extra) [1..]) ++ [extra,extra..]
resizeMaster :: SplitGrid a -> Resize -> SplitGrid a
resizeMaster (SplitGrid o mrows mcols mfrac saspect delta) Shrink =
SplitGrid o mrows mcols (max 0 (mfrac - delta)) saspect delta
resizeMaster (SplitGrid o mrows mcols mfrac saspect delta) Expand =
SplitGrid o mrows mcols (min 1 (mfrac + delta)) saspect delta
changeMasterGrid :: SplitGrid a -> ChangeMasterGridGeom -> SplitGrid a
changeMasterGrid (SplitGrid o mrows mcols mfrac saspect delta) (IncMasterRows d) =
SplitGrid o (max 0 (mrows + d)) mcols mfrac saspect delta
changeMasterGrid (SplitGrid o mrows mcols mfrac saspect delta) (IncMasterCols d) =
SplitGrid o mrows (max 0 (mcols + d)) mfrac saspect delta
changeMasterGrid (SplitGrid o _ mcols mfrac saspect delta) (SetMasterRows mrows) =
SplitGrid o (max 0 mrows) mcols mfrac saspect delta
changeMasterGrid (SplitGrid o mrows _ mfrac saspect delta) (SetMasterCols mcols) =
SplitGrid o mrows (max 0 mcols) mfrac saspect delta
changeMasterGrid (SplitGrid o mrows mcols _ saspect delta) (SetMasterFraction mfrac) =
SplitGrid o mrows mcols mfrac saspect delta
changeSlaveGridAspect :: SplitGrid a -> ChangeGridGeom -> SplitGrid a
changeSlaveGridAspect (SplitGrid o mrows mcols mfrac _ delta) (SetGridAspect saspect) =
SplitGrid o mrows mcols mfrac saspect delta
changeSlaveGridAspect (SplitGrid o mrows mcols mfrac saspect delta) (ChangeGridAspect sdelta) =
SplitGrid o mrows mcols mfrac (max 0.00001 (saspect + sdelta)) delta
| TallGrid layout . Parameters are
data TallGrid a = TallGrid !Int !Int !Rational !Rational !Rational
deriving (Read, Show)
instance LayoutClass TallGrid a where
pureLayout (TallGrid mrows mcols mfrac saspect _) rect st = zip wins rects
where
wins = W.integrate st
nwins = length wins
rects = arrangeSplitGrid rect L nwins mrows mcols mfrac saspect
pureMessage layout msg =
msum [ fmap ((tallGridAdapter resizeMaster) layout) (fromMessage msg)
, fmap ((tallGridAdapter changeMasterGrid) layout) (fromMessage msg) ]
description _ = "TallGrid"
tallGridAdapter :: (SplitGrid a -> b -> SplitGrid a) -> TallGrid a -> b -> TallGrid a
tallGridAdapter f (TallGrid mrows mcols mfrac saspect delta) msg =
TallGrid mrows' mcols' mfrac' saspect' delta'
where
SplitGrid _ mrows' mcols' mfrac' saspect' delta' =
f (SplitGrid L mrows mcols mfrac saspect delta) msg
|
131f8ada5d2f0cf26bd74a454c2fae2277ea692b8fd3b0d9575de60d8309e585 | mlabs-haskell/plutus-simple-model | Oracle.hs | # OPTIONS_GHC -Wno - incomplete - uni - patterns #
| Oracle example to test reference inputs
with inlined and hashed datums .
The players bet on integer value and oracle should provide an aswer .
Answer is read by reference input . Oracle inlines the answer to datum .
The BetDatum keeps the track of answers so far . Every user can bet @betStep@ lovelaces
and append the answer to the list of answers .
The winner is player with the closest guess to the Oracle 's answer .
with inlined and hashed datums.
The players bet on integer value and oracle should provide an aswer.
Answer is read by reference input. Oracle inlines the answer to datum.
The BetDatum keeps the track of answers so far. Every user can bet @betStep@ lovelaces
and append the answer to the list of answers.
The winner is player with the closest guess to the Oracle's answer.
-}
module Suites.Plutus.Model.Script.V2.Onchain.Oracle (
AnswerDatum (..),
BetDatum (..),
BetAct (..),
BetParams (..),
betStep,
betContract,
) where
import Plutus.Model.V2
import PlutusLedgerApi.V1.Address (pubKeyHashAddress)
import PlutusLedgerApi.V2
import PlutusLedgerApi.V2.Contexts
import PlutusTx qualified
import PlutusTx.Prelude
-- | Answer of the oracle
newtype AnswerDatum = AnswerDatum Integer
newtype BetDatum = BetDatum [(PubKeyHash, Integer)]
PlutusTx.unstableMakeIsData ''BetDatum
# INLINEABLE betStep #
betStep :: Integer
betStep = 100
data BetAct
= -- | User mades a guess
Bet Integer
| -- | User answers
Answer
newtype BetParams = BetParams {betParams'oracle :: PubKeyHash}
# #
betContract :: (TxInfo -> TxOut -> Maybe AnswerDatum) -> BetParams -> BetDatum -> BetAct -> ScriptContext -> Bool
betContract readDatum (BetParams oraclePkh) (BetDatum answers) act ctx =
case act of
Bet n -> bet n
Answer -> answer
where
!info = scriptContextTxInfo ctx
bet guess =
traceIfFalse
"Answers update is right"
((pkh, guess) : answers == answersOut)
&& traceIfFalse
"Value is increased by bet step"
(txOutValue tout == txOutValue tin <> singleton adaSymbol adaToken betStep)
where
Just (BetDatum answersOut) = datumOf info tout
(tin, tout) = getThrough ctx
[pkh] = txInfoSignatories info
answer =
traceIfFalse
"Script is fully spent"
(null (getContinuingOutputs ctx))
&& traceIfFalse
"Oracle owner is right"
(txOutAddress oracleIn == pubKeyHashAddress oraclePkh)
&& traceIfFalse
"answer is closest of pkh"
(all (\x -> getAnswerDiff x >= answerDiff) answers)
where
[pkh] = txInfoSignatories info
Just guess = find ((== pkh) . fst) answers
[oracleInfo] = txInfoReferenceInputs info
oracleIn = txInInfoResolved oracleInfo
Just (AnswerDatum oracleAnswer) = readDatum info oracleIn
answerDiff = getAnswerDiff guess
getAnswerDiff (_key, n) = abs (oracleAnswer - n)
PlutusTx.unstableMakeIsData ''AnswerDatum
PlutusTx.unstableMakeIsData ''BetAct
PlutusTx.makeLift ''BetParams
| null | https://raw.githubusercontent.com/mlabs-haskell/plutus-simple-model/10000d64ede979bb1d7838b3ed20b785615910b9/psm/test/Suites/Plutus/Model/Script/V2/Onchain/Oracle.hs | haskell | | Answer of the oracle
| User mades a guess
| User answers | # OPTIONS_GHC -Wno - incomplete - uni - patterns #
| Oracle example to test reference inputs
with inlined and hashed datums .
The players bet on integer value and oracle should provide an aswer .
Answer is read by reference input . Oracle inlines the answer to datum .
The BetDatum keeps the track of answers so far . Every user can bet @betStep@ lovelaces
and append the answer to the list of answers .
The winner is player with the closest guess to the Oracle 's answer .
with inlined and hashed datums.
The players bet on integer value and oracle should provide an aswer.
Answer is read by reference input. Oracle inlines the answer to datum.
The BetDatum keeps the track of answers so far. Every user can bet @betStep@ lovelaces
and append the answer to the list of answers.
The winner is player with the closest guess to the Oracle's answer.
-}
module Suites.Plutus.Model.Script.V2.Onchain.Oracle (
AnswerDatum (..),
BetDatum (..),
BetAct (..),
BetParams (..),
betStep,
betContract,
) where
import Plutus.Model.V2
import PlutusLedgerApi.V1.Address (pubKeyHashAddress)
import PlutusLedgerApi.V2
import PlutusLedgerApi.V2.Contexts
import PlutusTx qualified
import PlutusTx.Prelude
newtype AnswerDatum = AnswerDatum Integer
newtype BetDatum = BetDatum [(PubKeyHash, Integer)]
PlutusTx.unstableMakeIsData ''BetDatum
# INLINEABLE betStep #
betStep :: Integer
betStep = 100
data BetAct
Bet Integer
Answer
newtype BetParams = BetParams {betParams'oracle :: PubKeyHash}
# #
betContract :: (TxInfo -> TxOut -> Maybe AnswerDatum) -> BetParams -> BetDatum -> BetAct -> ScriptContext -> Bool
betContract readDatum (BetParams oraclePkh) (BetDatum answers) act ctx =
case act of
Bet n -> bet n
Answer -> answer
where
!info = scriptContextTxInfo ctx
bet guess =
traceIfFalse
"Answers update is right"
((pkh, guess) : answers == answersOut)
&& traceIfFalse
"Value is increased by bet step"
(txOutValue tout == txOutValue tin <> singleton adaSymbol adaToken betStep)
where
Just (BetDatum answersOut) = datumOf info tout
(tin, tout) = getThrough ctx
[pkh] = txInfoSignatories info
answer =
traceIfFalse
"Script is fully spent"
(null (getContinuingOutputs ctx))
&& traceIfFalse
"Oracle owner is right"
(txOutAddress oracleIn == pubKeyHashAddress oraclePkh)
&& traceIfFalse
"answer is closest of pkh"
(all (\x -> getAnswerDiff x >= answerDiff) answers)
where
[pkh] = txInfoSignatories info
Just guess = find ((== pkh) . fst) answers
[oracleInfo] = txInfoReferenceInputs info
oracleIn = txInInfoResolved oracleInfo
Just (AnswerDatum oracleAnswer) = readDatum info oracleIn
answerDiff = getAnswerDiff guess
getAnswerDiff (_key, n) = abs (oracleAnswer - n)
PlutusTx.unstableMakeIsData ''AnswerDatum
PlutusTx.unstableMakeIsData ''BetAct
PlutusTx.makeLift ''BetParams
|
e4a1f1c35359c314057c263fed4a6ed4de726ee085f9dbb8fa5486b995bfde7a | juspay/atlas | OnSearch.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Core . ACL.OnSearch
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Core.ACL.OnSearch
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Core.ACL.OnSearch where
import Beckn.Prelude
import qualified Beckn.Types.Core.Taxi.OnSearch as OnSearch
import Beckn.Types.Id (ShortId)
import qualified Domain.Types.DriverQuote as DQuote
import qualified Domain.Types.Organization as DOrg
data DOnSearchReq = DOnSearchReq
{ transporterInfo :: TransporterInfo,
quotes :: [DQuote.DriverQuote]
}
data TransporterInfo = TransporterInfo
{ shortId :: ShortId DOrg.Organization,
name :: Text,
contacts :: Text,
ridesInProgress :: Int,
ridesCompleted :: Int,
ridesConfirmed :: Int
}
mkOnSearchMessage ::
DOnSearchReq ->
OnSearch.OnSearchMessage
mkOnSearchMessage DOnSearchReq {..} = do
let provider =
OnSearch.Provider
{ id = transporterInfo.shortId.getShortId,
name = transporterInfo.name,
category_id = "ONE_WAY",
items = map mkItem quotes,
contacts = transporterInfo.contacts,
rides_inprogress = transporterInfo.ridesInProgress,
rides_completed = transporterInfo.ridesCompleted,
rides_confirmed = transporterInfo.ridesConfirmed
}
OnSearch.OnSearchMessage $ OnSearch.Catalog [provider]
mkItem :: DQuote.DriverQuote -> OnSearch.Item
mkItem q =
OnSearch.Item
{ id = q.id.getId,
vehicle_variant = show q.vehicleVariant,
estimated_price = estimated_price_,
discount = Nothing,
discounted_price = estimated_price_,
nearest_driver_distance = Just $ OnSearch.DecimalValue $ toRational q.distanceToPickup.getMeters,
baseDistance = Nothing,
baseDurationHr = Nothing,
descriptions = Nothing
}
where
estimated_price_ = OnSearch.Price $ realToFrac $ q.baseFare + fromMaybe 0 q.extraFareSelected
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/driver-offer-bpp/src/Core/ACL/OnSearch.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Core . ACL.OnSearch
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Core.ACL.OnSearch
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Core.ACL.OnSearch where
import Beckn.Prelude
import qualified Beckn.Types.Core.Taxi.OnSearch as OnSearch
import Beckn.Types.Id (ShortId)
import qualified Domain.Types.DriverQuote as DQuote
import qualified Domain.Types.Organization as DOrg
data DOnSearchReq = DOnSearchReq
{ transporterInfo :: TransporterInfo,
quotes :: [DQuote.DriverQuote]
}
data TransporterInfo = TransporterInfo
{ shortId :: ShortId DOrg.Organization,
name :: Text,
contacts :: Text,
ridesInProgress :: Int,
ridesCompleted :: Int,
ridesConfirmed :: Int
}
mkOnSearchMessage ::
DOnSearchReq ->
OnSearch.OnSearchMessage
mkOnSearchMessage DOnSearchReq {..} = do
let provider =
OnSearch.Provider
{ id = transporterInfo.shortId.getShortId,
name = transporterInfo.name,
category_id = "ONE_WAY",
items = map mkItem quotes,
contacts = transporterInfo.contacts,
rides_inprogress = transporterInfo.ridesInProgress,
rides_completed = transporterInfo.ridesCompleted,
rides_confirmed = transporterInfo.ridesConfirmed
}
OnSearch.OnSearchMessage $ OnSearch.Catalog [provider]
mkItem :: DQuote.DriverQuote -> OnSearch.Item
mkItem q =
OnSearch.Item
{ id = q.id.getId,
vehicle_variant = show q.vehicleVariant,
estimated_price = estimated_price_,
discount = Nothing,
discounted_price = estimated_price_,
nearest_driver_distance = Just $ OnSearch.DecimalValue $ toRational q.distanceToPickup.getMeters,
baseDistance = Nothing,
baseDurationHr = Nothing,
descriptions = Nothing
}
where
estimated_price_ = OnSearch.Price $ realToFrac $ q.baseFare + fromMaybe 0 q.extraFareSelected
|
|
e0d1ec9d684a3485b6679b587a007080422861a7a043d63415d65323617b71ff | Ericson2314/lighthouse | MenuEvent.hs | -- #hide
-----------------------------------------------------------------------------
-- |
-- Module : OS.MenuEvent
Copyright : ( c ) 2002
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- OS.MenuEvent defines the DeviceEventFunction for the menu device.
-- This function is placed in a separate module because it is platform dependent.
--
-----------------------------------------------------------------------------
module Graphics.UI.ObjectIO.OS.MenuEvent(menuEvent, menuHandlesGetMenuStateHandles) where
import Graphics.UI.ObjectIO.CommonDef
import Graphics.UI.ObjectIO.Device.Events
import Graphics.UI.ObjectIO.Device.SystemState
import Graphics.UI.ObjectIO.Process.IOState
import Graphics.UI.ObjectIO.StdGUI
import Graphics.UI.ObjectIO.Menu.Handle
import Graphics.UI.ObjectIO.Menu.Access(menuStateHandleGetHandle, menuStateHandleGetMenuId)
import Graphics.UI.ObjectIO.StdProcessAttribute(getProcessToolbarAtt, isProcessToolbar)
import Graphics.UI.ObjectIO.OS.Event(SchedulerEvent(..), OSEvent)
import Graphics.UI.ObjectIO.OS.ToolBar(OSToolbar(..))
import Graphics.UI.ObjectIO.OS.Menu
import Graphics.UI.ObjectIO.OS.Types
import Graphics.UI.ObjectIO.OS.ClCrossCall_12
import Graphics.UI.ObjectIO.OS.ClCCall_12
import Graphics.UI.ObjectIO.OS.Cutil_12(addr2int)
import Graphics.UI.ObjectIO.Id(IdParent(..))
import Foreign.C.String
import Data.Bits -- Defines .&. for bitand;
Defines Int32 instance for Bits ;
import Data.IORef(readIORef)
import Data.Map as Map (lookup)
menuEventFatalError :: String -> String -> x
menuEventFatalError function error
= dumpFatalError function "OS.MenuEvent" error
{- menuEvent filters the scheduler events that can be handled by this menu device.
For the time being no timer menu elements are added, so these events are ignored.
menuEvent assumes that it is not applied to an empty IOSt and that its device is
present.
-}
menuEvent :: IOSt ps -> SchedulerEvent -> IO (Bool,Maybe DeviceEvent,SchedulerEvent)
menuEvent ioState schedulerEvent
| ioStHasDevice MenuDevice ioState = menuEvent schedulerEvent ioState
| otherwise = menuEventFatalError "menuEvent" "MenuDevice.dEvent applied while MenuDevice not present in IOSt"
where
menuEvent :: SchedulerEvent -> IOSt ps -> IO (Bool,Maybe DeviceEvent,SchedulerEvent)
menuEvent schedulerEvent@(ScheduleOSEvent osEvent@(CrossCallInfo {ccMsg=ccMsg}) _) ioState
| isToolbarOSEvent ccMsg = do
(myEvent,replyToOS,deviceEvent) <- filterToolbarEvent (ioStGetOSDInfo ioState) osEvent ioState
let schedulerEvent1 =
if isJust replyToOS then
(ScheduleOSEvent osEvent (fromJust replyToOS))
else schedulerEvent
return (myEvent,deviceEvent,schedulerEvent1)
| isMenuOSEvent ccMsg = do
let (found,mDevice) = ioStGetDevice MenuDevice ioState
let menus = menuSystemStateGetMenuHandles mDevice
(myEvent,replyToOS,deviceEvent) <- filterOSEvent osEvent (found {-&& systemId==ioId-}) menus
let schedulerEvent1 = if isJust replyToOS then (ScheduleOSEvent osEvent (fromJust replyToOS)) else schedulerEvent
return (myEvent,deviceEvent,schedulerEvent1)
| otherwise =
return (False,Nothing,schedulerEvent)
where
isMenuOSEvent :: Int -> Bool
isMenuOSEvent msg = msg == ccWmCOMMAND
isToolbarOSEvent :: Int -> Bool
isToolbarOSEvent msg = msg == ccWmBUTTONCLICKED || msg == ccWmGETTOOLBARTIPTEXT
menuEvent schedulerEvent@(ScheduleMsgEvent rId) ioState = do
iocontext <- readIORef (ioStGetContext ioState)
case Map.lookup rId (ioContextGetIdTable iocontext) of
Just idParent | idpIOId idParent == ioStGetIOId ioState && idpDevice idParent == MenuDevice ->
let (_,mDevice) = ioStGetDevice MenuDevice ioState
menus = menuSystemStateGetMenuHandles mDevice
found = hasMenuHandlesMenu (idpId idParent) menus
deviceEvent = if found then (Just (ReceiverEvent rId)) else Nothing
in return (found,deviceEvent,schedulerEvent)
_ -> return (False,Nothing,schedulerEvent)
where
hasMenuHandlesMenu :: Id -> MenuHandles ps -> Bool
hasMenuHandlesMenu menuId mHs@(MenuHandles {mMenus=mMenus}) =
any (eqMenuId menuId) mMenus
where
eqMenuId :: Id -> MenuStateHandle ps -> Bool
eqMenuId theId msH = theId == menuStateHandleGetMenuId msH
filterToolbarEvent filters the OSEvents that can be handled by this menu device .
filterToolbarEvent :: OSDInfo -> OSEvent -> IOSt ps -> IO (Bool,Maybe [Int],Maybe DeviceEvent)
filterToolbarEvent osdInfo cci@(CrossCallInfo{ccMsg=ccMsg}) ioState
{- ccWmBUTTONCLICKED is a menu event in case of a toolbar selection. -}
| ccMsg == ccWmBUTTONCLICKED =
if isToolbarEvent osdInfo (p2 cci) then
return (True,Nothing,Just (ToolbarSelection (p4 cci)))
else
return (False,Nothing,Nothing)
{- ccWmGETTOOLBARTIPTEXT does not continue platform independent event handling, but returns the
String associated with the requested toolbar item.
-}
| ccMsg == ccWmGETTOOLBARTIPTEXT =
if isToolbarEvent osdInfo (p1 cci) then
let atts = ioStGetProcessAttributes ioState
(found,att) = cselect isProcessToolbar undefined atts
maybe_tip = gettooltip (p2 cci) (getProcessToolbarAtt att)
gettooltip :: Int -> [ToolbarItem ps] -> Maybe String
gettooltip i (item:items)
| i==1 && isItem = tip
| otherwise = gettooltip i' items
where
(isItem,i',tip) = case item of
ToolbarItem _ tip _ -> (True,i-1,tip)
ToolbarSeparator -> (False,i,Nothing)
gettooltip _ _ = Nothing
in
if not found || isNothing maybe_tip then return (True,Nothing,Nothing)
else do
textptr <- newCString (fromJust maybe_tip)
return (True,Just [addr2int textptr],Nothing)
else
return (False,Nothing,Nothing)
| otherwise = menuEventFatalError "filterToolbarEvent" "unmatched OSEvent"
filterOSEvent filters the OSEvents that can be handled by this menu device .
The argument is True iff the parent process is visible and active .
The Bool argument is True iff the parent process is visible and active.
-}
filterOSEvent :: OSEvent -> Bool -> (MenuHandles ps) -> IO (Bool,Maybe [Int],Maybe DeviceEvent)
ccWmCOMMAND returns the selected menu item .
This item is identified by :
- the top level menu I d ,
- a possibly empty list of parent sub menus . This list is given by zero based indices starting from the top level menu .
- in the parent ( sub ) menu , the zero based index of the item .
Only MenuItemHandle and SubMenuHandle elements increase the index ; all other elements do n't .
This item is identified by:
- the top level menu Id,
- a possibly empty list of parent sub menus. This list is given by zero based indices starting from the top level menu.
- in the parent (sub) menu, the zero based index of the item.
Only MenuItemHandle and SubMenuHandle elements increase the index; all other elements don't.
-}
filterOSEvent CrossCallInfo{ccMsg=ccMsg,p1=item,p2=mods} _ menus@(MenuHandles {mEnabled=mEnabled,mMenus=mHs})
| ccMsg == ccWmCOMMAND =
if not mEnabled then return (False,Nothing,Nothing)
else do
(found,deviceEvent) <- getSelectedMenuStateHandlesItem item mods mHs
return (found,Nothing,deviceEvent)
| otherwise =
menuEventFatalError "filterOSEvent" "unmatched OSEvent"
where
getSelectedMenuStateHandlesItem :: Int -> Int -> [MenuStateHandle ps] -> IO (Bool,Maybe DeviceEvent)
getSelectedMenuStateHandlesItem item mods [] =
return (False,Nothing)
getSelectedMenuStateHandlesItem item mods (msH:msHs) = do
(found,menuEvent) <- getSelectedMenuStateHandleItem item mods msH
(if found then return (found,menuEvent)
else getSelectedMenuStateHandlesItem item mods msHs)
where
getSelectedMenuStateHandleItem :: Int -> Int -> MenuStateHandle ps -> IO (Bool,Maybe DeviceEvent)
getSelectedMenuStateHandleItem item mods msH@(MenuStateHandle mlsH@(MenuLSHandle {mlsHandle=mH@(MenuHandle {mSelect=mSelect,mMenuId=mMenuId,mItems=mItems})}))
| not mSelect =
return (False,Nothing)
| otherwise = do
(found,menuEvent,_,_) <- getSelectedMenuElementHandlesItem item mMenuId mods [] 0 mItems
return (found,menuEvent)
where
getSelectedMenuElementHandlesItem :: Int -> Id -> Int -> [Int] -> Int -> [MenuElementHandle ls ps] -> IO (Bool,Maybe DeviceEvent,[Int],Int)
getSelectedMenuElementHandlesItem item menuId mods parents zIndex [] =
return (False,Nothing,parents,zIndex)
getSelectedMenuElementHandlesItem item menuId mods parents zIndex (itemH:itemHs) = do
(found,menuEvent,parents,zIndex) <- getSelectedMenuElementHandle item menuId mods parents zIndex itemH
(if found then return (found,menuEvent,parents,zIndex)
else getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs)
where
getSelectedMenuElementHandle :: Int -> Id -> Int -> [Int] -> Int -> MenuElementHandle ls ps -> IO (Bool,Maybe DeviceEvent,[Int],Int)
getSelectedMenuElementHandle item menuId mods parents zIndex itemH@(MenuItemHandle {mOSMenuItem=mOSMenuItem,mItemId=mItemId})
| item==mOSMenuItem =
return (True,Just (MenuTraceEvent (MenuTraceInfo {mtId=menuId,mtParents=parents,mtItemNr=zIndex,mtModifiers=toModifiers mods})),parents,zIndex+1)
| otherwise =
return (False,Nothing,parents,zIndex+1)
getSelectedMenuElementHandle item menuId mods parents zIndex itemH@(SubMenuHandle {mSubSelect=mSubSelect,mSubHandle=mSubHandle,mSubItems=mSubItems})
| not mSubSelect =
return (False,Nothing,parents,zIndex+1)
| otherwise = do
(found,menuEvent,parents1,_) <- getSelectedMenuElementHandlesItem item menuId mods (parents++[zIndex]) 0 mSubItems
let parents2 = if found then parents1 else parents
return (found,menuEvent,parents2,zIndex+1)
getSelectedMenuElementHandle item menuId mods parents zIndex itemH@(RadioMenuHandle {mRadioSelect=mRadioSelect,mRadioItems=itemHs,mRadioIndex=mRadioIndex})
| not mRadioSelect =
return (False,Nothing,parents,zIndex+(length itemHs))
| otherwise =
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle item menuId mods parents zIndex (MenuListLSHandle itemHs) = do
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle item menuId mods parents zIndex (MenuExtendLSHandle exLS itemHs) = do
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle item menuId mods parents itemNr (MenuChangeLSHandle chLS itemHs) = do
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle _ _ _ parents zIndex itemH =
return (False,Nothing,parents,zIndex)
PA : this function is also defined identically in windowevent .
toModifiers :: Int -> Modifiers
toModifiers i
= Modifiers
{ shiftDown = shifton
, optionDown = alton
, commandDown = ctrlon
, controlDown = ctrlon
, altDown = alton
}
where
shifton = (i1 .&. (fromIntegral shiftBIT)) /= 0
alton = (i1 .&. (fromIntegral altBIT)) /= 0
ctrlon = (i1 .&. (fromIntegral ctrlBIT)) /= 0
i1 = fromIntegral i :: Int32
isToolbarEvent checks whether the toolbar equals the OSDInfo toolbar .
isToolbarEvent :: OSDInfo -> OSWindowPtr -> Bool
isToolbarEvent osdInfo tPtr =
case getOSDInfoOSToolbar osdInfo of
Nothing -> False
Just toolbar -> toolbarPtr toolbar == tPtr
menuHandlesGetMenuStateHandles :: MenuHandles ps -> ([MenuStateHandle ps],MenuHandles ps)
menuHandlesGetMenuStateHandles mHs@(MenuHandles {mMenus=mMenus})
= (mMenus,mHs{mMenus=[]})
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/ObjectIO/Graphics/UI/ObjectIO/OS/MenuEvent.hs | haskell | #hide
---------------------------------------------------------------------------
|
Module : OS.MenuEvent
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
OS.MenuEvent defines the DeviceEventFunction for the menu device.
This function is placed in a separate module because it is platform dependent.
---------------------------------------------------------------------------
Defines .&. for bitand;
menuEvent filters the scheduler events that can be handled by this menu device.
For the time being no timer menu elements are added, so these events are ignored.
menuEvent assumes that it is not applied to an empty IOSt and that its device is
present.
&& systemId==ioId
ccWmBUTTONCLICKED is a menu event in case of a toolbar selection.
ccWmGETTOOLBARTIPTEXT does not continue platform independent event handling, but returns the
String associated with the requested toolbar item.
| Copyright : ( c ) 2002
module Graphics.UI.ObjectIO.OS.MenuEvent(menuEvent, menuHandlesGetMenuStateHandles) where
import Graphics.UI.ObjectIO.CommonDef
import Graphics.UI.ObjectIO.Device.Events
import Graphics.UI.ObjectIO.Device.SystemState
import Graphics.UI.ObjectIO.Process.IOState
import Graphics.UI.ObjectIO.StdGUI
import Graphics.UI.ObjectIO.Menu.Handle
import Graphics.UI.ObjectIO.Menu.Access(menuStateHandleGetHandle, menuStateHandleGetMenuId)
import Graphics.UI.ObjectIO.StdProcessAttribute(getProcessToolbarAtt, isProcessToolbar)
import Graphics.UI.ObjectIO.OS.Event(SchedulerEvent(..), OSEvent)
import Graphics.UI.ObjectIO.OS.ToolBar(OSToolbar(..))
import Graphics.UI.ObjectIO.OS.Menu
import Graphics.UI.ObjectIO.OS.Types
import Graphics.UI.ObjectIO.OS.ClCrossCall_12
import Graphics.UI.ObjectIO.OS.ClCCall_12
import Graphics.UI.ObjectIO.OS.Cutil_12(addr2int)
import Graphics.UI.ObjectIO.Id(IdParent(..))
import Foreign.C.String
Defines Int32 instance for Bits ;
import Data.IORef(readIORef)
import Data.Map as Map (lookup)
menuEventFatalError :: String -> String -> x
menuEventFatalError function error
= dumpFatalError function "OS.MenuEvent" error
menuEvent :: IOSt ps -> SchedulerEvent -> IO (Bool,Maybe DeviceEvent,SchedulerEvent)
menuEvent ioState schedulerEvent
| ioStHasDevice MenuDevice ioState = menuEvent schedulerEvent ioState
| otherwise = menuEventFatalError "menuEvent" "MenuDevice.dEvent applied while MenuDevice not present in IOSt"
where
menuEvent :: SchedulerEvent -> IOSt ps -> IO (Bool,Maybe DeviceEvent,SchedulerEvent)
menuEvent schedulerEvent@(ScheduleOSEvent osEvent@(CrossCallInfo {ccMsg=ccMsg}) _) ioState
| isToolbarOSEvent ccMsg = do
(myEvent,replyToOS,deviceEvent) <- filterToolbarEvent (ioStGetOSDInfo ioState) osEvent ioState
let schedulerEvent1 =
if isJust replyToOS then
(ScheduleOSEvent osEvent (fromJust replyToOS))
else schedulerEvent
return (myEvent,deviceEvent,schedulerEvent1)
| isMenuOSEvent ccMsg = do
let (found,mDevice) = ioStGetDevice MenuDevice ioState
let menus = menuSystemStateGetMenuHandles mDevice
let schedulerEvent1 = if isJust replyToOS then (ScheduleOSEvent osEvent (fromJust replyToOS)) else schedulerEvent
return (myEvent,deviceEvent,schedulerEvent1)
| otherwise =
return (False,Nothing,schedulerEvent)
where
isMenuOSEvent :: Int -> Bool
isMenuOSEvent msg = msg == ccWmCOMMAND
isToolbarOSEvent :: Int -> Bool
isToolbarOSEvent msg = msg == ccWmBUTTONCLICKED || msg == ccWmGETTOOLBARTIPTEXT
menuEvent schedulerEvent@(ScheduleMsgEvent rId) ioState = do
iocontext <- readIORef (ioStGetContext ioState)
case Map.lookup rId (ioContextGetIdTable iocontext) of
Just idParent | idpIOId idParent == ioStGetIOId ioState && idpDevice idParent == MenuDevice ->
let (_,mDevice) = ioStGetDevice MenuDevice ioState
menus = menuSystemStateGetMenuHandles mDevice
found = hasMenuHandlesMenu (idpId idParent) menus
deviceEvent = if found then (Just (ReceiverEvent rId)) else Nothing
in return (found,deviceEvent,schedulerEvent)
_ -> return (False,Nothing,schedulerEvent)
where
hasMenuHandlesMenu :: Id -> MenuHandles ps -> Bool
hasMenuHandlesMenu menuId mHs@(MenuHandles {mMenus=mMenus}) =
any (eqMenuId menuId) mMenus
where
eqMenuId :: Id -> MenuStateHandle ps -> Bool
eqMenuId theId msH = theId == menuStateHandleGetMenuId msH
filterToolbarEvent filters the OSEvents that can be handled by this menu device .
filterToolbarEvent :: OSDInfo -> OSEvent -> IOSt ps -> IO (Bool,Maybe [Int],Maybe DeviceEvent)
filterToolbarEvent osdInfo cci@(CrossCallInfo{ccMsg=ccMsg}) ioState
| ccMsg == ccWmBUTTONCLICKED =
if isToolbarEvent osdInfo (p2 cci) then
return (True,Nothing,Just (ToolbarSelection (p4 cci)))
else
return (False,Nothing,Nothing)
| ccMsg == ccWmGETTOOLBARTIPTEXT =
if isToolbarEvent osdInfo (p1 cci) then
let atts = ioStGetProcessAttributes ioState
(found,att) = cselect isProcessToolbar undefined atts
maybe_tip = gettooltip (p2 cci) (getProcessToolbarAtt att)
gettooltip :: Int -> [ToolbarItem ps] -> Maybe String
gettooltip i (item:items)
| i==1 && isItem = tip
| otherwise = gettooltip i' items
where
(isItem,i',tip) = case item of
ToolbarItem _ tip _ -> (True,i-1,tip)
ToolbarSeparator -> (False,i,Nothing)
gettooltip _ _ = Nothing
in
if not found || isNothing maybe_tip then return (True,Nothing,Nothing)
else do
textptr <- newCString (fromJust maybe_tip)
return (True,Just [addr2int textptr],Nothing)
else
return (False,Nothing,Nothing)
| otherwise = menuEventFatalError "filterToolbarEvent" "unmatched OSEvent"
filterOSEvent filters the OSEvents that can be handled by this menu device .
The argument is True iff the parent process is visible and active .
The Bool argument is True iff the parent process is visible and active.
-}
filterOSEvent :: OSEvent -> Bool -> (MenuHandles ps) -> IO (Bool,Maybe [Int],Maybe DeviceEvent)
ccWmCOMMAND returns the selected menu item .
This item is identified by :
- the top level menu I d ,
- a possibly empty list of parent sub menus . This list is given by zero based indices starting from the top level menu .
- in the parent ( sub ) menu , the zero based index of the item .
Only MenuItemHandle and SubMenuHandle elements increase the index ; all other elements do n't .
This item is identified by:
- the top level menu Id,
- a possibly empty list of parent sub menus. This list is given by zero based indices starting from the top level menu.
- in the parent (sub) menu, the zero based index of the item.
Only MenuItemHandle and SubMenuHandle elements increase the index; all other elements don't.
-}
filterOSEvent CrossCallInfo{ccMsg=ccMsg,p1=item,p2=mods} _ menus@(MenuHandles {mEnabled=mEnabled,mMenus=mHs})
| ccMsg == ccWmCOMMAND =
if not mEnabled then return (False,Nothing,Nothing)
else do
(found,deviceEvent) <- getSelectedMenuStateHandlesItem item mods mHs
return (found,Nothing,deviceEvent)
| otherwise =
menuEventFatalError "filterOSEvent" "unmatched OSEvent"
where
getSelectedMenuStateHandlesItem :: Int -> Int -> [MenuStateHandle ps] -> IO (Bool,Maybe DeviceEvent)
getSelectedMenuStateHandlesItem item mods [] =
return (False,Nothing)
getSelectedMenuStateHandlesItem item mods (msH:msHs) = do
(found,menuEvent) <- getSelectedMenuStateHandleItem item mods msH
(if found then return (found,menuEvent)
else getSelectedMenuStateHandlesItem item mods msHs)
where
getSelectedMenuStateHandleItem :: Int -> Int -> MenuStateHandle ps -> IO (Bool,Maybe DeviceEvent)
getSelectedMenuStateHandleItem item mods msH@(MenuStateHandle mlsH@(MenuLSHandle {mlsHandle=mH@(MenuHandle {mSelect=mSelect,mMenuId=mMenuId,mItems=mItems})}))
| not mSelect =
return (False,Nothing)
| otherwise = do
(found,menuEvent,_,_) <- getSelectedMenuElementHandlesItem item mMenuId mods [] 0 mItems
return (found,menuEvent)
where
getSelectedMenuElementHandlesItem :: Int -> Id -> Int -> [Int] -> Int -> [MenuElementHandle ls ps] -> IO (Bool,Maybe DeviceEvent,[Int],Int)
getSelectedMenuElementHandlesItem item menuId mods parents zIndex [] =
return (False,Nothing,parents,zIndex)
getSelectedMenuElementHandlesItem item menuId mods parents zIndex (itemH:itemHs) = do
(found,menuEvent,parents,zIndex) <- getSelectedMenuElementHandle item menuId mods parents zIndex itemH
(if found then return (found,menuEvent,parents,zIndex)
else getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs)
where
getSelectedMenuElementHandle :: Int -> Id -> Int -> [Int] -> Int -> MenuElementHandle ls ps -> IO (Bool,Maybe DeviceEvent,[Int],Int)
getSelectedMenuElementHandle item menuId mods parents zIndex itemH@(MenuItemHandle {mOSMenuItem=mOSMenuItem,mItemId=mItemId})
| item==mOSMenuItem =
return (True,Just (MenuTraceEvent (MenuTraceInfo {mtId=menuId,mtParents=parents,mtItemNr=zIndex,mtModifiers=toModifiers mods})),parents,zIndex+1)
| otherwise =
return (False,Nothing,parents,zIndex+1)
getSelectedMenuElementHandle item menuId mods parents zIndex itemH@(SubMenuHandle {mSubSelect=mSubSelect,mSubHandle=mSubHandle,mSubItems=mSubItems})
| not mSubSelect =
return (False,Nothing,parents,zIndex+1)
| otherwise = do
(found,menuEvent,parents1,_) <- getSelectedMenuElementHandlesItem item menuId mods (parents++[zIndex]) 0 mSubItems
let parents2 = if found then parents1 else parents
return (found,menuEvent,parents2,zIndex+1)
getSelectedMenuElementHandle item menuId mods parents zIndex itemH@(RadioMenuHandle {mRadioSelect=mRadioSelect,mRadioItems=itemHs,mRadioIndex=mRadioIndex})
| not mRadioSelect =
return (False,Nothing,parents,zIndex+(length itemHs))
| otherwise =
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle item menuId mods parents zIndex (MenuListLSHandle itemHs) = do
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle item menuId mods parents zIndex (MenuExtendLSHandle exLS itemHs) = do
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle item menuId mods parents itemNr (MenuChangeLSHandle chLS itemHs) = do
getSelectedMenuElementHandlesItem item menuId mods parents zIndex itemHs
getSelectedMenuElementHandle _ _ _ parents zIndex itemH =
return (False,Nothing,parents,zIndex)
PA : this function is also defined identically in windowevent .
toModifiers :: Int -> Modifiers
toModifiers i
= Modifiers
{ shiftDown = shifton
, optionDown = alton
, commandDown = ctrlon
, controlDown = ctrlon
, altDown = alton
}
where
shifton = (i1 .&. (fromIntegral shiftBIT)) /= 0
alton = (i1 .&. (fromIntegral altBIT)) /= 0
ctrlon = (i1 .&. (fromIntegral ctrlBIT)) /= 0
i1 = fromIntegral i :: Int32
isToolbarEvent checks whether the toolbar equals the OSDInfo toolbar .
isToolbarEvent :: OSDInfo -> OSWindowPtr -> Bool
isToolbarEvent osdInfo tPtr =
case getOSDInfoOSToolbar osdInfo of
Nothing -> False
Just toolbar -> toolbarPtr toolbar == tPtr
menuHandlesGetMenuStateHandles :: MenuHandles ps -> ([MenuStateHandle ps],MenuHandles ps)
menuHandlesGetMenuStateHandles mHs@(MenuHandles {mMenus=mMenus})
= (mMenus,mHs{mMenus=[]})
|
5a3d1f5db799820b3461ac03ff21b100da63421eda49161a0c1ed0a9cb1aa8ab | gerritjvv/fun-utils | apply_get_create_tests.clj | (ns fun-utils.apply-get-create-tests
(:require [fun-utils.core :refer [apply-get-create]])
(:use midje.sweet))
(facts "Test apply-get-create"
(fact "test new value created"
(apply-get-create {} :a inc (fn [& args] 1)) => {:a 1}
;the inc is applied but the result is not assoced to the map
this method is used to creawte resources in a map if they do not exist
;e.g. agents, channels, files
(apply-get-create {:a 1} :a inc (fn [& args] 1)) => {:a 1}
)
;(fact "test with ref"
; (let [v (ref {})]
; (dosync
( alter v apply - get - create : a ( fn [ ] ( send agnt inc ) ) ( fn [ & args ] ( agent 1 ) ) )
( alter v apply - get - create : a ( fn [ ] ( send agnt inc ) ) ( fn [ & args ] ( agent 1 ) ) )
( alter v apply - get - create : a ( fn [ ] ( send agnt inc ) ) ( fn [ & args ] ( agent 1 ) ) ) )
;
; (prn @v)
( deref (: a @v ) ) = > 1
;
; ))
)
| null | https://raw.githubusercontent.com/gerritjvv/fun-utils/72152ce4ca901af9a89bb21ca5817dbead773151/test/fun_utils/apply_get_create_tests.clj | clojure | the inc is applied but the result is not assoced to the map
e.g. agents, channels, files
(fact "test with ref"
(let [v (ref {})]
(dosync
(prn @v)
)) | (ns fun-utils.apply-get-create-tests
(:require [fun-utils.core :refer [apply-get-create]])
(:use midje.sweet))
(facts "Test apply-get-create"
(fact "test new value created"
(apply-get-create {} :a inc (fn [& args] 1)) => {:a 1}
this method is used to creawte resources in a map if they do not exist
(apply-get-create {:a 1} :a inc (fn [& args] 1)) => {:a 1}
)
( alter v apply - get - create : a ( fn [ ] ( send agnt inc ) ) ( fn [ & args ] ( agent 1 ) ) )
( alter v apply - get - create : a ( fn [ ] ( send agnt inc ) ) ( fn [ & args ] ( agent 1 ) ) )
( alter v apply - get - create : a ( fn [ ] ( send agnt inc ) ) ( fn [ & args ] ( agent 1 ) ) ) )
( deref (: a @v ) ) = > 1
)
|
7afcdc233599767a1dc9572a5247e1fa0c760ccfd89f1240c9d2c22841423b10 | bintracker/bintracker | m6809.tests.scm | (import scheme (chicken base) test schemta)
(define (run-src src)
(map char->integer (assemble 'm6809 src)))
(test-group
"Addressing Modes"
(test "immediate" '(#x89 #xff) (run-src " adca #$ff"))
(test "direct" '(#x99 #xff) (run-src " adca <$ffff"))
(test "extended" '(#xb9 #xff #xfe) (run-src " adca $fffe"))
(test "extended-indirect" '(#xa9 #x9f #xff #xfe) (run-src " adca [$fffe]"))
(test "indexed-autoinc2" '(#xa9 #xa1) (run-src " adca ,y++"))
(test "indexed-autoinc1" '(#xa9 #xa0) (run-src " adca ,y+"))
(test "indexed-autodec2" '(#xa9 #xa3) (run-src " adca ,--y"))
(test "indexed-autodec1" '(#xa9 #xa2) (run-src " adca ,-y"))
(test "indexed-autoinc2-indirect" '(#xa9 #xb1) (run-src " adca [,y++]"))
(test "indexed-autodec2-indirect" '(#xa9 #xb3) (run-src " adca [,--y]"))
(test "indexed-constant-null-offset-from-r" '(#xa9 #xa4) (run-src " adca ,y"))
(test "indexed-constant-null-offset-from-r-indirect"
'(#xa9 #xb8)
(run-src " adca [,y]"))
(test "indexed-constant-5bit-offset-from-r"
'(#xa9 #x30)
(run-src " adca -16,y"))
(test "indexed-constant-8bit-offset-from-r"
'(#xa9 #xa8 #x80)
(run-src " adca -128,y"))
(test "indexed-constant-16bit-offset-from-r"
'(#xa9 #xa9 #x80 #x00)
(run-src " adca -32768,y"))
(test "indexed-constant-8bit-offset-from-pc"
'(#xa9 #x8c #xf0)
(run-src " adca -16,pcr"))
(test "indexed-constant-16bit-offset-from-pc"
'(#xa9 #x8d #x80 #x00)
(run-src " adca -32768,pcr"))
(test "indexed-accumulator-offset-from-r" '(#xa9 #xa6) (run-src " adca a,y"))
(test "indexed-accumulator-offset-from-r-indirect"
'(#xa9 #xb6)
(run-src " adca [a,y]"))
(test "indexed-constant-8bit-offset-from-r-indirect"
'(#xa9 #xb8 #xf0)
(run-src " adca [-16,y]"))
(test "indexed-constant-16bit-offset-from-r-indirect"
'(#xa9 #xb9 #x80 #x00)
(run-src " adca [-32768,y]"))
(test "indexed-constant-8bit-offset-from-pc-indirect"
'(#xa9 #xfc #xf0)
(run-src " adca [-16,pcr]"))
(test "indexed-constant-16bit-offset-from-pc-indirect"
'(#xa9 #xfd #x80 00)
(run-src " adca [-32768,pcr]")))
(test-group
"Instructions"
(test "abx" '(#x3a) (run-src " abx"))
(test "adca" '(#x89 #xff) (run-src " adca #$ff"))
(test "adcb" '(#xc9 #xff) (run-src " adcb #$ff"))
(test "adda" '(#x8b #xff) (run-src " adda #$ff"))
(test "addb" '(#xcb #xff) (run-src " addb #$ff"))
(test "addd" '(#xc3 #xff #xfe) (run-src " addd #$fffe"))
(test "anda" '(#x84 #xff) (run-src " anda #$ff"))
(test "andb" '(#xc4 #xff) (run-src " andb #$ff"))
(test "asl" '(#x68 #xa1) (run-src " asl ,y++"))
(test "asla" '(#x48) (run-src " asla"))
(test "aslb" '(#x58) (run-src " aslb"))
(test "bcc" '(#x24 #x02) (run-src " bcc 2"))
(test "bcs" '(#x25 #x02) (run-src " bcs 2"))
(test "beq" '(#x27 #x02) (run-src " beq 2"))
(test "bge" '(#x2c #x02) (run-src " bge 2"))
(test "bgt" '(#x2e #x02) (run-src " bgt 2"))
(test "bhi" '(#x22 #x02) (run-src " bhi 2"))
(test "bhs" '(#x24 #x02) (run-src " bhs 2"))
(test "bita" '(#x85 #xff) (run-src " bita #$ff"))
(test "bitb" '(#xc5 #xff) (run-src " bitb #$ff"))
(test "ble" '(#x2f #x02) (run-src " ble 2"))
(test "blo" '(#x25 #x02) (run-src " blo 2"))
(test "bls" '(#x23 #x02) (run-src " bls 2"))
(test "blt" '(#x2d #x02) (run-src " blt 2"))
(test "bmi" '(#x2b #x02) (run-src " bmi 2"))
(test "bne" '(#x26 #x02) (run-src " bne 2"))
(test "bpl" '(#x2a #x02) (run-src " bpl 2"))
(test "bra" '(#x20 #x02) (run-src " bra 2"))
(test "brn" '(#x21 #x02) (run-src " brn 2"))
(test "bsr" '(#x8d #x02) (run-src " bsr 2"))
(test "bvc" '(#x28 #x02) (run-src " bvc 2"))
(test "bvs" '(#x29 #x02) (run-src " bvs 2"))
(test "clr" '(#x6f #xa1) (run-src " clr ,y++"))
(test "clra" '(#x4f) (run-src " clra"))
(test "clrb" '(#x5f) (run-src " clrb"))
(test "cmpa" '(#x81 #xff) (run-src " cmpa #$ff"))
(test "cmpb" '(#xc1 #xff) (run-src " cmpb #$ff"))
(test "cmpd" '(#x10 #x83 #xff #xfe) (run-src " cmpd #$fffe"))
(test "cmps" '(#x11 #x8c #xff #xfe) (run-src " cmps #$fffe"))
(test "cmpu" '(#x11 #x83 #xff #xfe) (run-src " cmpu #$fffe"))
(test "cmpx" '(#x8c #xff #xfe) (run-src " cmpx #$fffe"))
(test "cmpy" '(#x10 #x8c #xff #xfe) (run-src " cmpy #$fffe"))
(test "com" '(#x63 #xa1) (run-src " com ,y++"))
(test "coma" '(#x43) (run-src " coma"))
(test "comb" '(#x53) (run-src " comb"))
(test "cwai" '(#x3c #xff) (run-src " cwai #$ff"))
(test "daa" '(#x19) (run-src " daa"))
(test "dec" '(#x6a #xa1) (run-src " dec ,y++"))
(test "deca" '(#x4a) (run-src " deca"))
(test "decb" '(#x5a) (run-src " decb"))
(test "eora" '(#x88 #xff) (run-src " eora #$ff"))
(test "eorb" '(#xc8 #xff) (run-src " eorb #$ff"))
(test "exg" '(#x1e #x8b) (run-src " exg a,dp"))
(test "inc" '(#x6c #xa1) (run-src " inc ,y++"))
(test "inca" '(#x4c) (run-src " inca"))
(test "incb" '(#x5c) (run-src " incb"))
(test "jmp" '(#x6e #xa1) (run-src " jmp ,y++"))
(test "jsr" '(#xad #xa1) (run-src " jsr ,y++"))
(test "lbcc" '(#x10 #x24 #x02 #x00) (run-src " lbcc $200"))
(test "lbcs" '(#x10 #x25 #x02 #x00) (run-src " lbcs $200"))
(test "lbeq" '(#x10 #x27 #x02 #x00) (run-src " lbeq $200"))
(test "lbge" '(#x10 #x2c #x02 #x00) (run-src " lbge $200"))
(test "lbgt" '(#x10 #x2e #x02 #x00) (run-src " lbgt $200"))
(test "lbhi" '(#x10 #x22 #x02 #x00) (run-src " lbhi $200"))
(test "lbhs" '(#x10 #x24 #x02 #x00) (run-src " lbhs $200"))
(test "lble" '(#x10 #x2f #x02 #x00) (run-src " lble $200"))
(test "lblo" '(#x10 #x25 #x02 #x00) (run-src " lblo $200"))
(test "lbls" '(#x10 #x23 #x02 #x00) (run-src " lbls $200"))
(test "lblt" '(#x10 #x2d #x02 #x00) (run-src " lblt $200"))
(test "lbmi" '(#x10 #x2b #x02 #x00) (run-src " lbmi $200"))
(test "lbne" '(#x10 #x26 #x02 #x00) (run-src " lbne $200"))
(test "lbpl" '(#x10 #x2a #x02 #x00) (run-src " lbpl $200"))
(test "lbra" '(#x16 #x02 #x00) (run-src " lbra $200"))
(test "lbrn" '(#x10 #x21 #x02 #x00) (run-src " lbrn $200"))
(test "lbsr" '(#x17 #x02 #x00) (run-src " lbsr $200"))
(test "lbvc" '(#x10 #x28 #x02 #x00) (run-src " lbvc $200"))
(test "lbvs" '(#x10 #x29 #x02 #x00) (run-src " lbvs $200"))
(test "lda" '(#x86 #xff) (run-src " lda #$ff"))
(test "ldb" '(#xc6 #xff) (run-src " ldb #$ff"))
(test "ldd" '(#xcc #xff #xfe) (run-src " ldd #$fffe"))
(test "lds" '(#x10 #xce #xff #xfe) (run-src " lds #$fffe"))
(test "ldu" '(#xce #xff #xfe) (run-src " ldu #$fffe"))
(test "ldx" '(#x8e #xff #xfe) (run-src " ldx #$fffe"))
(test "ldy" '(#x10 #x8e #xff #xfe) (run-src " ldy #$fffe"))
(test "leas" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leau" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leax" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leay" '(#x32 #xa1) (run-src " leas ,y++"))
(test "lsl" '(#x68 #xa1) (run-src " lsl ,y++"))
(test "lsla" '(#x48) (run-src " lsla"))
(test "lslb" '(#x49) (run-src " lslb"))
(test "lsr" '(#x64 #xa1) (run-src " lsr ,y++"))
(test "lsra" '(#x44) (run-src " lsra"))
(test "lsrb" '(#x45) (run-src " lsrb"))
(test "mul" '(#x3d) (run-src " mul"))
(test "ncc" '(#x62 #xa1) (run-src " ncc ,y++"))
(test "ncca" '(#x42) (run-src " ncca"))
(test "nccb" '(#x52) (run-src " nccb"))
(test "neg" '(#x60 #xa1) (run-src " neg ,y++"))
(test "nega" '(#x40) (run-src " nega"))
(test "negb" '(#x50) (run-src " negb"))
(test "nop" '(#x12) (run-src " nop"))
(test "ora" '(#x8a #xff) (run-src " ora #$ff"))
(test "ora" '(#xca #xff) (run-src " orb #$ff"))
(test "orcc" '(#x1a #xff) (run-src " orcc #$ff"))
(test "page" '(#x10) (run-src " page 2"))
(test "pshs" '(#x34 #xff) (run-src " pshs cc,a,b,dp,x,y,u,pc"))
(test "pshu" '(#x36 #xff) (run-src " pshu cc,a,b,dp,x,y,s,pc"))
(test "puls" '(#x35 #xff) (run-src " puls cc,a,b,dp,x,y,u,pc"))
(test "pulu" '(#x37 #xff) (run-src " pulu cc,a,b,dp,x,y,s,pc"))
(test "reset" '(#x3e) (run-src " reset"))
(test "rol" '(#x69 #xa1) (run-src " rol ,y++"))
(test "rola" '(#x49) (run-src " rola"))
(test "rolb" '(#x59) (run-src " rolb"))
(test "ror" '(#x66 #xa1) (run-src " ror ,y++"))
(test "rora" '(#x46) (run-src " rora"))
(test "rorb" '(#x56) (run-src " rorb"))
(test "rti" '(#x3b) (run-src " rti"))
(test "rts" '(#x39) (run-src " rts"))
(test "sbca" '(#x82 #xff) (run-src " sbca #$ff"))
(test "sbcb" '(#xc2 #xff) (run-src " sbcb #$ff"))
(test "sex" '(#x1d) (run-src " sex"))
(test "sta" '(#xa7 #xa1) (run-src " sta ,y++"))
(test "stb" '(#xe7 #xa1) (run-src " stb ,y++"))
(test "std" '(#xed #xa1) (run-src " std ,y++"))
(test "sts" '(#x10 #xef #xa1) (run-src " sts ,y++"))
(test "stu" '(#xef #xa1) (run-src " stu ,y++"))
(test "stx" '(#xaf #xa1) (run-src " stx ,y++"))
(test "sty" '(#x10 #xaf #xa1) (run-src " sty ,y++"))
(test "swi" '(#x3f) (run-src " swi"))
(test "swi2" '(#x10 #x3f) (run-src " swi2"))
(test "swi3" '(#x11 #x3f) (run-src " swi3"))
(test "sync" '(#x13) (run-src " sync"))
(test "tfr" '(#x1f #x8b) (run-src " tfr a,dp"))
(test "tst" '(#x6d #xa1) (run-src " tst ,y++"))
(test "tsta" '(#x4d) (run-src " tsta"))
(test "tstb" '(#x5d) (run-src " tstb")))
(test-exit)
| null | https://raw.githubusercontent.com/bintracker/bintracker/d09e0a9315b988b2aa2f8e4d1754182b17e10a54/libmdal/schemta-tests/m6809.tests.scm | scheme | (import scheme (chicken base) test schemta)
(define (run-src src)
(map char->integer (assemble 'm6809 src)))
(test-group
"Addressing Modes"
(test "immediate" '(#x89 #xff) (run-src " adca #$ff"))
(test "direct" '(#x99 #xff) (run-src " adca <$ffff"))
(test "extended" '(#xb9 #xff #xfe) (run-src " adca $fffe"))
(test "extended-indirect" '(#xa9 #x9f #xff #xfe) (run-src " adca [$fffe]"))
(test "indexed-autoinc2" '(#xa9 #xa1) (run-src " adca ,y++"))
(test "indexed-autoinc1" '(#xa9 #xa0) (run-src " adca ,y+"))
(test "indexed-autodec2" '(#xa9 #xa3) (run-src " adca ,--y"))
(test "indexed-autodec1" '(#xa9 #xa2) (run-src " adca ,-y"))
(test "indexed-autoinc2-indirect" '(#xa9 #xb1) (run-src " adca [,y++]"))
(test "indexed-autodec2-indirect" '(#xa9 #xb3) (run-src " adca [,--y]"))
(test "indexed-constant-null-offset-from-r" '(#xa9 #xa4) (run-src " adca ,y"))
(test "indexed-constant-null-offset-from-r-indirect"
'(#xa9 #xb8)
(run-src " adca [,y]"))
(test "indexed-constant-5bit-offset-from-r"
'(#xa9 #x30)
(run-src " adca -16,y"))
(test "indexed-constant-8bit-offset-from-r"
'(#xa9 #xa8 #x80)
(run-src " adca -128,y"))
(test "indexed-constant-16bit-offset-from-r"
'(#xa9 #xa9 #x80 #x00)
(run-src " adca -32768,y"))
(test "indexed-constant-8bit-offset-from-pc"
'(#xa9 #x8c #xf0)
(run-src " adca -16,pcr"))
(test "indexed-constant-16bit-offset-from-pc"
'(#xa9 #x8d #x80 #x00)
(run-src " adca -32768,pcr"))
(test "indexed-accumulator-offset-from-r" '(#xa9 #xa6) (run-src " adca a,y"))
(test "indexed-accumulator-offset-from-r-indirect"
'(#xa9 #xb6)
(run-src " adca [a,y]"))
(test "indexed-constant-8bit-offset-from-r-indirect"
'(#xa9 #xb8 #xf0)
(run-src " adca [-16,y]"))
(test "indexed-constant-16bit-offset-from-r-indirect"
'(#xa9 #xb9 #x80 #x00)
(run-src " adca [-32768,y]"))
(test "indexed-constant-8bit-offset-from-pc-indirect"
'(#xa9 #xfc #xf0)
(run-src " adca [-16,pcr]"))
(test "indexed-constant-16bit-offset-from-pc-indirect"
'(#xa9 #xfd #x80 00)
(run-src " adca [-32768,pcr]")))
(test-group
"Instructions"
(test "abx" '(#x3a) (run-src " abx"))
(test "adca" '(#x89 #xff) (run-src " adca #$ff"))
(test "adcb" '(#xc9 #xff) (run-src " adcb #$ff"))
(test "adda" '(#x8b #xff) (run-src " adda #$ff"))
(test "addb" '(#xcb #xff) (run-src " addb #$ff"))
(test "addd" '(#xc3 #xff #xfe) (run-src " addd #$fffe"))
(test "anda" '(#x84 #xff) (run-src " anda #$ff"))
(test "andb" '(#xc4 #xff) (run-src " andb #$ff"))
(test "asl" '(#x68 #xa1) (run-src " asl ,y++"))
(test "asla" '(#x48) (run-src " asla"))
(test "aslb" '(#x58) (run-src " aslb"))
(test "bcc" '(#x24 #x02) (run-src " bcc 2"))
(test "bcs" '(#x25 #x02) (run-src " bcs 2"))
(test "beq" '(#x27 #x02) (run-src " beq 2"))
(test "bge" '(#x2c #x02) (run-src " bge 2"))
(test "bgt" '(#x2e #x02) (run-src " bgt 2"))
(test "bhi" '(#x22 #x02) (run-src " bhi 2"))
(test "bhs" '(#x24 #x02) (run-src " bhs 2"))
(test "bita" '(#x85 #xff) (run-src " bita #$ff"))
(test "bitb" '(#xc5 #xff) (run-src " bitb #$ff"))
(test "ble" '(#x2f #x02) (run-src " ble 2"))
(test "blo" '(#x25 #x02) (run-src " blo 2"))
(test "bls" '(#x23 #x02) (run-src " bls 2"))
(test "blt" '(#x2d #x02) (run-src " blt 2"))
(test "bmi" '(#x2b #x02) (run-src " bmi 2"))
(test "bne" '(#x26 #x02) (run-src " bne 2"))
(test "bpl" '(#x2a #x02) (run-src " bpl 2"))
(test "bra" '(#x20 #x02) (run-src " bra 2"))
(test "brn" '(#x21 #x02) (run-src " brn 2"))
(test "bsr" '(#x8d #x02) (run-src " bsr 2"))
(test "bvc" '(#x28 #x02) (run-src " bvc 2"))
(test "bvs" '(#x29 #x02) (run-src " bvs 2"))
(test "clr" '(#x6f #xa1) (run-src " clr ,y++"))
(test "clra" '(#x4f) (run-src " clra"))
(test "clrb" '(#x5f) (run-src " clrb"))
(test "cmpa" '(#x81 #xff) (run-src " cmpa #$ff"))
(test "cmpb" '(#xc1 #xff) (run-src " cmpb #$ff"))
(test "cmpd" '(#x10 #x83 #xff #xfe) (run-src " cmpd #$fffe"))
(test "cmps" '(#x11 #x8c #xff #xfe) (run-src " cmps #$fffe"))
(test "cmpu" '(#x11 #x83 #xff #xfe) (run-src " cmpu #$fffe"))
(test "cmpx" '(#x8c #xff #xfe) (run-src " cmpx #$fffe"))
(test "cmpy" '(#x10 #x8c #xff #xfe) (run-src " cmpy #$fffe"))
(test "com" '(#x63 #xa1) (run-src " com ,y++"))
(test "coma" '(#x43) (run-src " coma"))
(test "comb" '(#x53) (run-src " comb"))
(test "cwai" '(#x3c #xff) (run-src " cwai #$ff"))
(test "daa" '(#x19) (run-src " daa"))
(test "dec" '(#x6a #xa1) (run-src " dec ,y++"))
(test "deca" '(#x4a) (run-src " deca"))
(test "decb" '(#x5a) (run-src " decb"))
(test "eora" '(#x88 #xff) (run-src " eora #$ff"))
(test "eorb" '(#xc8 #xff) (run-src " eorb #$ff"))
(test "exg" '(#x1e #x8b) (run-src " exg a,dp"))
(test "inc" '(#x6c #xa1) (run-src " inc ,y++"))
(test "inca" '(#x4c) (run-src " inca"))
(test "incb" '(#x5c) (run-src " incb"))
(test "jmp" '(#x6e #xa1) (run-src " jmp ,y++"))
(test "jsr" '(#xad #xa1) (run-src " jsr ,y++"))
(test "lbcc" '(#x10 #x24 #x02 #x00) (run-src " lbcc $200"))
(test "lbcs" '(#x10 #x25 #x02 #x00) (run-src " lbcs $200"))
(test "lbeq" '(#x10 #x27 #x02 #x00) (run-src " lbeq $200"))
(test "lbge" '(#x10 #x2c #x02 #x00) (run-src " lbge $200"))
(test "lbgt" '(#x10 #x2e #x02 #x00) (run-src " lbgt $200"))
(test "lbhi" '(#x10 #x22 #x02 #x00) (run-src " lbhi $200"))
(test "lbhs" '(#x10 #x24 #x02 #x00) (run-src " lbhs $200"))
(test "lble" '(#x10 #x2f #x02 #x00) (run-src " lble $200"))
(test "lblo" '(#x10 #x25 #x02 #x00) (run-src " lblo $200"))
(test "lbls" '(#x10 #x23 #x02 #x00) (run-src " lbls $200"))
(test "lblt" '(#x10 #x2d #x02 #x00) (run-src " lblt $200"))
(test "lbmi" '(#x10 #x2b #x02 #x00) (run-src " lbmi $200"))
(test "lbne" '(#x10 #x26 #x02 #x00) (run-src " lbne $200"))
(test "lbpl" '(#x10 #x2a #x02 #x00) (run-src " lbpl $200"))
(test "lbra" '(#x16 #x02 #x00) (run-src " lbra $200"))
(test "lbrn" '(#x10 #x21 #x02 #x00) (run-src " lbrn $200"))
(test "lbsr" '(#x17 #x02 #x00) (run-src " lbsr $200"))
(test "lbvc" '(#x10 #x28 #x02 #x00) (run-src " lbvc $200"))
(test "lbvs" '(#x10 #x29 #x02 #x00) (run-src " lbvs $200"))
(test "lda" '(#x86 #xff) (run-src " lda #$ff"))
(test "ldb" '(#xc6 #xff) (run-src " ldb #$ff"))
(test "ldd" '(#xcc #xff #xfe) (run-src " ldd #$fffe"))
(test "lds" '(#x10 #xce #xff #xfe) (run-src " lds #$fffe"))
(test "ldu" '(#xce #xff #xfe) (run-src " ldu #$fffe"))
(test "ldx" '(#x8e #xff #xfe) (run-src " ldx #$fffe"))
(test "ldy" '(#x10 #x8e #xff #xfe) (run-src " ldy #$fffe"))
(test "leas" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leau" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leax" '(#x32 #xa1) (run-src " leas ,y++"))
(test "leay" '(#x32 #xa1) (run-src " leas ,y++"))
(test "lsl" '(#x68 #xa1) (run-src " lsl ,y++"))
(test "lsla" '(#x48) (run-src " lsla"))
(test "lslb" '(#x49) (run-src " lslb"))
(test "lsr" '(#x64 #xa1) (run-src " lsr ,y++"))
(test "lsra" '(#x44) (run-src " lsra"))
(test "lsrb" '(#x45) (run-src " lsrb"))
(test "mul" '(#x3d) (run-src " mul"))
(test "ncc" '(#x62 #xa1) (run-src " ncc ,y++"))
(test "ncca" '(#x42) (run-src " ncca"))
(test "nccb" '(#x52) (run-src " nccb"))
(test "neg" '(#x60 #xa1) (run-src " neg ,y++"))
(test "nega" '(#x40) (run-src " nega"))
(test "negb" '(#x50) (run-src " negb"))
(test "nop" '(#x12) (run-src " nop"))
(test "ora" '(#x8a #xff) (run-src " ora #$ff"))
(test "ora" '(#xca #xff) (run-src " orb #$ff"))
(test "orcc" '(#x1a #xff) (run-src " orcc #$ff"))
(test "page" '(#x10) (run-src " page 2"))
(test "pshs" '(#x34 #xff) (run-src " pshs cc,a,b,dp,x,y,u,pc"))
(test "pshu" '(#x36 #xff) (run-src " pshu cc,a,b,dp,x,y,s,pc"))
(test "puls" '(#x35 #xff) (run-src " puls cc,a,b,dp,x,y,u,pc"))
(test "pulu" '(#x37 #xff) (run-src " pulu cc,a,b,dp,x,y,s,pc"))
(test "reset" '(#x3e) (run-src " reset"))
(test "rol" '(#x69 #xa1) (run-src " rol ,y++"))
(test "rola" '(#x49) (run-src " rola"))
(test "rolb" '(#x59) (run-src " rolb"))
(test "ror" '(#x66 #xa1) (run-src " ror ,y++"))
(test "rora" '(#x46) (run-src " rora"))
(test "rorb" '(#x56) (run-src " rorb"))
(test "rti" '(#x3b) (run-src " rti"))
(test "rts" '(#x39) (run-src " rts"))
(test "sbca" '(#x82 #xff) (run-src " sbca #$ff"))
(test "sbcb" '(#xc2 #xff) (run-src " sbcb #$ff"))
(test "sex" '(#x1d) (run-src " sex"))
(test "sta" '(#xa7 #xa1) (run-src " sta ,y++"))
(test "stb" '(#xe7 #xa1) (run-src " stb ,y++"))
(test "std" '(#xed #xa1) (run-src " std ,y++"))
(test "sts" '(#x10 #xef #xa1) (run-src " sts ,y++"))
(test "stu" '(#xef #xa1) (run-src " stu ,y++"))
(test "stx" '(#xaf #xa1) (run-src " stx ,y++"))
(test "sty" '(#x10 #xaf #xa1) (run-src " sty ,y++"))
(test "swi" '(#x3f) (run-src " swi"))
(test "swi2" '(#x10 #x3f) (run-src " swi2"))
(test "swi3" '(#x11 #x3f) (run-src " swi3"))
(test "sync" '(#x13) (run-src " sync"))
(test "tfr" '(#x1f #x8b) (run-src " tfr a,dp"))
(test "tst" '(#x6d #xa1) (run-src " tst ,y++"))
(test "tsta" '(#x4d) (run-src " tsta"))
(test "tstb" '(#x5d) (run-src " tstb")))
(test-exit)
|
|
0cc9f9d0837911fb0af2414047b8eef5d02e23d7b229bcd66e10ea6825fa6afa | camoy/contract-etc | no-env.rkt | #lang racket/base
(require chk
racket/contract
"../annotate.rkt")
;; outside `test` submodule
(: foo-fo integer?)
(define foo-fo 42)
(: foo-ho (-> integer?))
(define (foo-ho) "hi")
(chk
foo-fo 42
#:t (procedure? foo-ho)
(foo-ho) "hi"
#:x
(let ()
(: bar-fo integer?)
(define (bar-fo) 42)
(void))
"bar-fo: broke its own contract"
(let ()
(: bar-ho (-> integer?))
(define (bar-ho) "hi")
(bar-ho))
"hi")
;; make sure we don't break submodule order
(module+ examples
(provide (all-defined-out))
(define forty-two 42))
;; inside `test` submodule
(module+ test
(require (submod ".." examples))
(: baz-fo integer?)
(define baz-fo forty-two)
(: baz-ho (-> integer?))
(define (baz-ho) "hi")
(chk
baz-fo 42
#:t (procedure? baz-ho)
(baz-ho) "hi"
(foo-ho) "hi"
#:x
(let ()
(: qux-fo integer?)
(define (qux-fo) 42)
(void))
"qux-fo: broke its own contract"
(let ()
(: qux-ho (-> integer?))
(define (qux-ho) "hi")
(qux-ho))
"hi"))
| null | https://raw.githubusercontent.com/camoy/contract-etc/3758ad23c407f72b160df4969623576d661301b8/tests/no-env.rkt | racket | outside `test` submodule
make sure we don't break submodule order
inside `test` submodule | #lang racket/base
(require chk
racket/contract
"../annotate.rkt")
(: foo-fo integer?)
(define foo-fo 42)
(: foo-ho (-> integer?))
(define (foo-ho) "hi")
(chk
foo-fo 42
#:t (procedure? foo-ho)
(foo-ho) "hi"
#:x
(let ()
(: bar-fo integer?)
(define (bar-fo) 42)
(void))
"bar-fo: broke its own contract"
(let ()
(: bar-ho (-> integer?))
(define (bar-ho) "hi")
(bar-ho))
"hi")
(module+ examples
(provide (all-defined-out))
(define forty-two 42))
(module+ test
(require (submod ".." examples))
(: baz-fo integer?)
(define baz-fo forty-two)
(: baz-ho (-> integer?))
(define (baz-ho) "hi")
(chk
baz-fo 42
#:t (procedure? baz-ho)
(baz-ho) "hi"
(foo-ho) "hi"
#:x
(let ()
(: qux-fo integer?)
(define (qux-fo) 42)
(void))
"qux-fo: broke its own contract"
(let ()
(: qux-ho (-> integer?))
(define (qux-ho) "hi")
(qux-ho))
"hi"))
|
9de628b58461373107737dcf2f5ad1cfa20a7a54f2aa7c898a4e5f988603673b | xively/clj-mqtt | pubrec_test.clj | (ns mqtt.packets.pubrec-test
(:use clojure.test
mqtt.test-helpers
mqtt.decoder
mqtt.encoder
mqtt.packets.common
mqtt.packets.pubrec)
(:import [io.netty.buffer Unpooled]
[io.netty.handler.codec EncoderException]))
(deftest pubrec-validate-message-test
(testing "nil when valid"
(is (= nil (validate-message {:type :pubrec
:message-id 1}))))
(testing "it throws if no message-id"
(is (thrown? EncoderException (validate-message {:type :pubrec}))))
(testing "it throws if message-id is 0"
(is (thrown? EncoderException (validate-message {:type :pubrec
:message-id 0})))))
(deftest pubrec-encoding-test
(testing "when encoding a simple pubrec packet"
(let [encoder (make-encoder)
packet {:type :pubrec :message-id 5}
out (Unpooled/buffer 4)]
(.encode encoder nil packet out)
(is (= (byte-buffer-to-bytes out)
[;; fixed header
2r01010000
;; remaining length
2
;; message id
0 5])))))
(deftest decoding-pubrec-packet-test
(testing "when parsing a simple pubrec packet"
(let [decoder (make-decoder)
packet (bytes-to-byte-buffer
;; fixed header
2r01010000
;; remaining length
2
;; message id
0 5)
out (new java.util.ArrayList)
_ (.decode decoder nil packet out)
decoded (first out)]
(testing "parses a packet"
(is (not (nil? decoded)))
(is (= :pubrec (:type decoded))))
(testing "should not be a duplicate"
(is (= false (:duplicate decoded))))
(testing "parses the qos"
(is (= 0 (:qos decoded))))
(testing "should not be retained"
(is (= false (:retain decoded))))
(testing "it parses the message id"
(is (= 5 (:message-id decoded)))))))
| null | https://raw.githubusercontent.com/xively/clj-mqtt/74964112505da717ea88279b62f239146450528c/test/mqtt/packets/pubrec_test.clj | clojure | fixed header
remaining length
message id
fixed header
remaining length
message id | (ns mqtt.packets.pubrec-test
(:use clojure.test
mqtt.test-helpers
mqtt.decoder
mqtt.encoder
mqtt.packets.common
mqtt.packets.pubrec)
(:import [io.netty.buffer Unpooled]
[io.netty.handler.codec EncoderException]))
(deftest pubrec-validate-message-test
(testing "nil when valid"
(is (= nil (validate-message {:type :pubrec
:message-id 1}))))
(testing "it throws if no message-id"
(is (thrown? EncoderException (validate-message {:type :pubrec}))))
(testing "it throws if message-id is 0"
(is (thrown? EncoderException (validate-message {:type :pubrec
:message-id 0})))))
(deftest pubrec-encoding-test
(testing "when encoding a simple pubrec packet"
(let [encoder (make-encoder)
packet {:type :pubrec :message-id 5}
out (Unpooled/buffer 4)]
(.encode encoder nil packet out)
(is (= (byte-buffer-to-bytes out)
2r01010000
2
0 5])))))
(deftest decoding-pubrec-packet-test
(testing "when parsing a simple pubrec packet"
(let [decoder (make-decoder)
packet (bytes-to-byte-buffer
2r01010000
2
0 5)
out (new java.util.ArrayList)
_ (.decode decoder nil packet out)
decoded (first out)]
(testing "parses a packet"
(is (not (nil? decoded)))
(is (= :pubrec (:type decoded))))
(testing "should not be a duplicate"
(is (= false (:duplicate decoded))))
(testing "parses the qos"
(is (= 0 (:qos decoded))))
(testing "should not be retained"
(is (= false (:retain decoded))))
(testing "it parses the message id"
(is (= 5 (:message-id decoded)))))))
|
db6ddc79434b40bc213c4cfa14ede151477b65ba14c43eb56b13c35e07e98122 | rescript-lang/syntax | res_driver_reason_binary.ml | module IO = Res_io
let isReasonDocComment (comment : Res_comment.t) =
let content = Res_comment.txt comment in
let len = String.length content in
if len = 0 then true
else if
len >= 2
&& String.unsafe_get content 0 = '*'
&& String.unsafe_get content 1 = '*'
then false
else if len >= 1 && String.unsafe_get content 0 = '*' then true
else false
let extractConcreteSyntax filename =
let commentData = ref [] in
let stringData = ref [] in
let src = IO.readFile ~filename in
let scanner = Res_scanner.make src ~filename in
let rec next prevEndPos scanner =
let startPos, endPos, token = Res_scanner.scan scanner in
match token with
| Eof -> ()
| Comment c ->
Res_comment.setPrevTokEndPos c prevEndPos;
commentData := c :: !commentData;
next endPos scanner
| String _ ->
let loc =
{Location.loc_start = startPos; loc_end = endPos; loc_ghost = false}
in
let len = endPos.pos_cnum - startPos.pos_cnum in
let txt = (String.sub [@doesNotRaise]) src startPos.pos_cnum len in
stringData := (txt, loc) :: !stringData;
next endPos scanner
| Lbrace ->
(* handle {| |} or {sql||sql} quoted strings. We don't care about its contents.
Why? // abcdef inside the quoted string would otherwise be picked up as an extra comment *)
Res_scanner.tryAdvanceQuotedString scanner;
next endPos scanner
| _ -> next endPos scanner
in
next Lexing.dummy_pos scanner;
let comments =
!commentData
|> List.filter (fun c -> not (isReasonDocComment c))
|> List.rev
in
(comments, !stringData)
let parsingEngine =
{
Res_driver.parseImplementation =
(fun ~forPrinter:_ ~filename ->
let chan, close =
if String.length filename == 0 then (stdin, fun _ -> ())
else
let file_chan = open_in_bin filename in
let () = seek_in file_chan 0 in
(file_chan, close_in_noerr)
in
let magic = Config.ast_impl_magic_number in
ignore
((really_input_string [@doesNotRaise]) chan (String.length magic));
let filename = input_value chan in
let comments, stringData =
if filename <> "" then extractConcreteSyntax filename else ([], [])
in
let ast = input_value chan in
close chan;
let structure =
ast
|> Res_ast_conversion.replaceStringLiteralStructure stringData
|> Res_ast_conversion.normalizeReasonArityStructure ~forPrinter:true
|> Res_ast_conversion.structure
in
{
Res_driver.filename;
source = "";
parsetree = structure;
diagnostics = ();
invalid = false;
comments;
});
parseInterface =
(fun ~forPrinter:_ ~filename ->
let chan, close =
if String.length filename == 0 then (stdin, fun _ -> ())
else
let file_chan = open_in_bin filename in
let () = seek_in file_chan 0 in
(file_chan, close_in_noerr)
in
let magic = Config.ast_intf_magic_number in
ignore
((really_input_string [@doesNotRaise]) chan (String.length magic));
let filename = input_value chan in
let comments, stringData =
if filename <> "" then extractConcreteSyntax filename else ([], [])
in
let ast = input_value chan in
close chan;
let signature =
ast
|> Res_ast_conversion.replaceStringLiteralSignature stringData
|> Res_ast_conversion.normalizeReasonAritySignature ~forPrinter:true
|> Res_ast_conversion.signature
in
{
Res_driver.filename;
source = "";
parsetree = signature;
diagnostics = ();
invalid = false;
comments;
});
stringOfDiagnostics = (fun ~source:_ ~filename:_ _diagnostics -> ());
}
| null | https://raw.githubusercontent.com/rescript-lang/syntax/67fec537284579e58bee8e70120bff8e03688fa8/src/res_driver_reason_binary.ml | ocaml | handle {| |} or {sql||sql} quoted strings. We don't care about its contents.
Why? // abcdef inside the quoted string would otherwise be picked up as an extra comment | module IO = Res_io
let isReasonDocComment (comment : Res_comment.t) =
let content = Res_comment.txt comment in
let len = String.length content in
if len = 0 then true
else if
len >= 2
&& String.unsafe_get content 0 = '*'
&& String.unsafe_get content 1 = '*'
then false
else if len >= 1 && String.unsafe_get content 0 = '*' then true
else false
let extractConcreteSyntax filename =
let commentData = ref [] in
let stringData = ref [] in
let src = IO.readFile ~filename in
let scanner = Res_scanner.make src ~filename in
let rec next prevEndPos scanner =
let startPos, endPos, token = Res_scanner.scan scanner in
match token with
| Eof -> ()
| Comment c ->
Res_comment.setPrevTokEndPos c prevEndPos;
commentData := c :: !commentData;
next endPos scanner
| String _ ->
let loc =
{Location.loc_start = startPos; loc_end = endPos; loc_ghost = false}
in
let len = endPos.pos_cnum - startPos.pos_cnum in
let txt = (String.sub [@doesNotRaise]) src startPos.pos_cnum len in
stringData := (txt, loc) :: !stringData;
next endPos scanner
| Lbrace ->
Res_scanner.tryAdvanceQuotedString scanner;
next endPos scanner
| _ -> next endPos scanner
in
next Lexing.dummy_pos scanner;
let comments =
!commentData
|> List.filter (fun c -> not (isReasonDocComment c))
|> List.rev
in
(comments, !stringData)
let parsingEngine =
{
Res_driver.parseImplementation =
(fun ~forPrinter:_ ~filename ->
let chan, close =
if String.length filename == 0 then (stdin, fun _ -> ())
else
let file_chan = open_in_bin filename in
let () = seek_in file_chan 0 in
(file_chan, close_in_noerr)
in
let magic = Config.ast_impl_magic_number in
ignore
((really_input_string [@doesNotRaise]) chan (String.length magic));
let filename = input_value chan in
let comments, stringData =
if filename <> "" then extractConcreteSyntax filename else ([], [])
in
let ast = input_value chan in
close chan;
let structure =
ast
|> Res_ast_conversion.replaceStringLiteralStructure stringData
|> Res_ast_conversion.normalizeReasonArityStructure ~forPrinter:true
|> Res_ast_conversion.structure
in
{
Res_driver.filename;
source = "";
parsetree = structure;
diagnostics = ();
invalid = false;
comments;
});
parseInterface =
(fun ~forPrinter:_ ~filename ->
let chan, close =
if String.length filename == 0 then (stdin, fun _ -> ())
else
let file_chan = open_in_bin filename in
let () = seek_in file_chan 0 in
(file_chan, close_in_noerr)
in
let magic = Config.ast_intf_magic_number in
ignore
((really_input_string [@doesNotRaise]) chan (String.length magic));
let filename = input_value chan in
let comments, stringData =
if filename <> "" then extractConcreteSyntax filename else ([], [])
in
let ast = input_value chan in
close chan;
let signature =
ast
|> Res_ast_conversion.replaceStringLiteralSignature stringData
|> Res_ast_conversion.normalizeReasonAritySignature ~forPrinter:true
|> Res_ast_conversion.signature
in
{
Res_driver.filename;
source = "";
parsetree = signature;
diagnostics = ();
invalid = false;
comments;
});
stringOfDiagnostics = (fun ~source:_ ~filename:_ _diagnostics -> ());
}
|
5115a1b5a3622fcc81303d3667e0a653ab999fa15a88e2f2a7c1062e358f770d | unclebob/ubc-website | zorch.clj | (ns ubc-website.interactors.zorch
(:use [hiccup core page])
(:require
[ubc-website.presenters.util :refer [markdown]]))
(declare display-file)
(defn exec [key]
(cond
(nil? key)
(display-file "nilkey")
(= "" key)
(display-file "badkey")
(.exists (clojure.java.io/file (str "resources/zorch/" (.toLowerCase key))))
(display-file key)
:else
(display-file "badkey")
))
(defn display-file [file]
(let [text (slurp (str "resources/zorch/" file))
content (markdown text)]
(html5
[:head
[:meta {:charset "UTF-8"}]
[:title "ZORCH!"]
(include-css "/css/style.css")]
[:body
[:div#header
[:p#ubc "ZORCH"]]
[:div#content-area
[:div content]
]])
))
| null | https://raw.githubusercontent.com/unclebob/ubc-website/3773ef24e0baef20dfa579661496aecb4326236e/src/ubc_website/interactors/zorch.clj | clojure | (ns ubc-website.interactors.zorch
(:use [hiccup core page])
(:require
[ubc-website.presenters.util :refer [markdown]]))
(declare display-file)
(defn exec [key]
(cond
(nil? key)
(display-file "nilkey")
(= "" key)
(display-file "badkey")
(.exists (clojure.java.io/file (str "resources/zorch/" (.toLowerCase key))))
(display-file key)
:else
(display-file "badkey")
))
(defn display-file [file]
(let [text (slurp (str "resources/zorch/" file))
content (markdown text)]
(html5
[:head
[:meta {:charset "UTF-8"}]
[:title "ZORCH!"]
(include-css "/css/style.css")]
[:body
[:div#header
[:p#ubc "ZORCH"]]
[:div#content-area
[:div content]
]])
))
|
|
a60d7bb7840326638d9c00d10a9894f441995ac0be8d64e87d6b3085923266e6 | openmusic-project/openmusic | win32.lisp | -*- Mode : Lisp ; rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / win32.lisp , v 1.10.1.1 2014/05/27 20:56:57 davef Exp $ " -*-
Copyright ( c ) 1987 - -2015 LispWorks Ltd. All rights reserved .
(in-package "WIN32")
From WINGDI.H
;;; /* pixel types */
(defconstant *PFD-TYPE-RGBA* 0)
(defconstant *PFD-TYPE-COLORINDEX* 1)
;;; /* layer types */
(defconstant *PFD-MAIN-PLANE* 0)
(defconstant *PFD-OVERLAY-PLANE* 1)
(defconstant *PFD-UNDERLAY-PLANE* -1)
;;; /* PIXELFORMATDESCRIPTOR flags */
(defconstant *PFD-DOUBLEBUFFER* #x00000001)
(defconstant *PFD-STEREO* #x00000002)
(defconstant *PFD-DRAW-TO-WINDOW* #x00000004)
(defconstant *PFD-DRAW-TO-BITMAP* #x00000008)
(defconstant *PFD-SUPPORT-GDI* #x00000010)
(defconstant *PFD-SUPPORT-OPENGL* #x00000020)
(defconstant *PFD-GENERIC-FORMAT* #x00000040)
(defconstant *PFD-NEED-PALETTE* #x00000080)
(defconstant *PFD-NEED-SYSTEM-PALETTE* #x00000100)
(defconstant *PFD-SWAP-EXCHANGE* #x00000200)
(defconstant *PFD-SWAP-COPY* #x00000400)
/ * PIXELFORMATDESCRIPTOR flags for use in ChoosePixelFormat only * /
(defconstant *PFD-DOUBLEBUFFER-DONTCARE* #x40000000)
(defconstant *PFD-STEREO-DONTCARE* #x80000000)
(fli:define-c-struct (tag-pixel-format-descriptor (:foreign-name "tagPIXELFORMATDESCRIPTOR"))
(nSize WORD)
(nVersion WORD)
(dwFlags DWORD)
(iPixelType BYTE)
(cColorBits BYTE)
(cRedBits BYTE)
(cRedShift BYTE)
(cGreenBits BYTE)
(cGreenShift BYTE)
(cBlueBits BYTE)
(cBlueShift BYTE)
(cAlphaBits BYTE)
(cAlphaShift BYTE)
(cAccumBits BYTE)
(cAccumRedBits BYTE)
(cAccumGreenBits BYTE)
(cAccumBlueBits BYTE)
(cAccumAlphaBits BYTE)
(cDepthBits BYTE)
(cStencilBits BYTE)
(cAuxBuffers BYTE)
(iLayerType BYTE)
(bReserved BYTE)
(dwLayerMask DWORD)
(dwVisibleMask DWORD)
(dwDamageMask DWORD))
(fli:define-c-typedef (pixel-format-descriptor (:foreign-name "PIXELFORMATDESCRIPTOR"))
(:struct tag-pixel-format-descriptor))
(fli:define-c-typedef (hglrc (:foreign-name "HGLRC"))
HANDLE)
(fli:define-foreign-function (get-pixel-format "GetPixelFormat")
((hdc HDC))
:result-type :int
:documentation "Obtains the index of the specified device context's currently selected pixel format."
:language :ansi-c)
(fli:define-foreign-function (choose-pixel-format "ChoosePixelFormat")
((hdc HDC)
(pfd (:ptr pixel-format-descriptor)))
:result-type :int
:documentation "Attempts to find the pixel format supported by a device context that is the best match to a given pixel format specification."
:language :ansi-c)
(fli:define-foreign-function (set-pixel-format "SetPixelFormat")
((hdc HDC)
(iPixelFormat :int)
(pfd (:ptr pixel-format-descriptor)))
:result-type BOOL
:documentation "Sets the specified device context's pixel format to the format specified by the iPixelFormat index"
:language :ansi-c)
(fli:define-foreign-function (%describe-pixel-format "DescribePixelFormat")
((hdc HDC)
(iPixelFormat :int)
(nBytes :int)
(pfd (:ptr pixel-format-descriptor)))
:result-type :int
:documentation "Obtains information about the pixel format identified by iPixelFormat of the device associated with hdc.
The function sets the members of the PIXELFORMATDESCRIPTOR structure pointed to by ppfd with that pixel format information."
:language :ansi-c)
(defun describe-pixel-format (hdc ipfd pfd)
(%describe-pixel-format hdc ipfd (fli:size-of 'pixel-format-descriptor) pfd))
;;; ------------------------------------------------------------
;;;
(fli:define-foreign-function (wgl-create-context "wglCreateContext")
((hdc HDC))
:documentation "Creates a new OpenGL rendering context, which is suitable for drawing on the device referenced by hdc.
The rendering context has the same pixel format as the device context."
:result-type HGLRC
:language :ansi-c)
(fli:define-foreign-function (wgl-make-current "wglMakeCurrent")
((hdc HDC)
(hglrc HGLRC))
:documentation "Makes a specified OpenGL rendering context the calling thread's current rendering context.
All subsequent OpenGL calls made by the thread are drawn on the device identified by hdc.
You can also use wglMakeCurrent to make the calling thread's current rendering context not current."
:result-type BOOL
:language :ansi-c)
(fli:define-foreign-function (wgl-delete-context "wglDeleteContext")
((hglrc HGLRC))
:result-type BOOL
:language :ansi-c)
(fli:define-foreign-function (wgl-get-current-context "wglGetCurrentContext")
()
:result-type HGLRC
:language :ansi-c)
(fli:define-foreign-function (wgl-get-current-dc "wglGetCurrentDC")
()
:result-type HDC
:language :ansi-c)
(fli:define-foreign-function (swap-buffers "SwapBuffers")
((hdc HDC))
:result-type BOOL
:language :ansi-c)
;;; ----------------------------------------------------------------------
;;; Support for text within double buffered OpenGL panes
;;; ----------------------------------------------------------------------
(defconstant TMPF_TRUETYPE #x04)
(defconstant *WGL-FONT-LINES* 0)
(defconstant *WGL-FONT-POLYGONS* 1)
;;; For extruded 3D fonts
(fli:define-c-struct _POINTFLOAT
(x :float)
(y :float))
(fli:define-c-typedef POINTFLOAT (:struct _POINTFLOAT))
(fli:define-c-struct _GLYPHMETRICSFLOAT
(gmfBlackBoxX :float)
(gmfBlackBoxY :float)
(gmfptGlyphOrigin POINTFLOAT)
(gmfCellIncX :float)
(gmfCellIncY :float))
(fli:define-c-typedef GLYPHMETRICSFLOAT
(:struct _GLYPHMETRICSFLOAT))
(fli:define-foreign-function ( win32::wgl-use-font-outlines
"wglUseFontOutlines" :dbcs)
((hdc HDC)
(first DWORD)
(count DWORD)
(list-base DWORD)
(deviation :float)
(extrusion :float)
(format :int)
:result-type BOOL
:language :ansi-c)
;;; Convert a font to a bitmap.
(fli:define-foreign-function (win32::wgl-use-font-bitmaps
"wglUseFontBitmaps" :dbcs)
((hdc HDC)
(first DWORD)
(count DWORD)
(list-base DWORD))
:result-type BOOL)
;;; (WGL-USE-FONT OPENGL-PANE &key FONT OUTLINEP DEVIATION
;;; EXTRUSION GLYPH-METRIC-POINTER
;;; START COUNT ERRORP LIST-BASE)
;;; Create a display-list for a given font.
;;; Arguments :
OPENGL - PANE : OPENGL - PANE
;;; FONT : capi font specification. If no font is specified then the
font for the OPENGL - PANE will be used .
: BOOLEAN - When NULL - A display list containing bitmap representation
;;; of each font character will be generated.
;;; Otherwise - A display list containing 3d character representation
;;; for each font character will be generated. (Note that
the font must be TrueType in this case )
;;; DEVIATION : FLOAT - chordal deviation from the original outlines
EXTRUSION : FLOAT - how much the font is extruded in the negative z direction .
GLYPH - METRIC - POINTER : Foreign pointer to an array ( length COUNT ) of
Structures that recieve the glyph metrics . If NIL is passed in
;;; then no data will be stored.
START : INTEGER - First of the set of glyphs which will form the display - list
COUNT : INTEGER - Number of glyphs to be used in the creation of the display - list .
ERRORP : BOOLEAN - When true , an error will be signaled when a glerror occurs .
Otherwise NIL will be returned from the WGL - USE - FONT
LIST - BASE : INTEGER - Specifies the start of the display - list .
;;; RESULTS :
;;; The list-base used for creating the font (or NIL indicating an error).
;;; Note that once the font list (pointed to by the list-base) is no longer
required then it should be destroyed by calling OPENGL : GL - DELETE - LISTS
(defun wgl-use-font (opengl-pane &key
(font (gp::get-port-font opengl-pane))
outlinep
(deviation 0.0)
(extrusion 0.1)
glyph-metric-pointer
(start 32) (count 224)
(errorp t)
(list-base (opengl:gl-gen-lists count)))
(let ((gpfont (gp:lookup-font opengl-pane font))
(hdc (win32::wgl-get-current-dc)))
(unwind-protect
(progn
(realize-tool gpfont)
(when (and outlinep
(not (logtest TMPF_TRUETYPE
(logical-font-textmetric-pitch gpfont))))
(opengl:gl-delete-lists list-base count)
(case errorp
(:warn (warn "~s : Outline font must be a TrueType font."
'wgl-use-font))
((nil) nil)
(otherwise (error "~s : Outline font must be a TrueType font."
'wgl-use-font)))
(return-from wgl-use-font nil))
(select-object hdc (drawing-tool-handle gpfont))
;; For some reason - OpenGL on NT sometimes fails to
create the font the first time around . Not sure of
;; the reason why. The simple fix is if the creation
of the font fails the first time - try calling
;; wglUseFont... again to make sure that there really
;; is some form or error???
(unless (if outlinep
(let ((format (if (eq outlinep :lines)
*WGL-FONT-LINES*
*WGL-FONT-POLYGONS*)))
(or
(win32::wgl-use-font-outlines hdc start count list-base
deviation extrusion
format
glyph-metric-pointer)
(win32::wgl-use-font-outlines hdc start count list-base
deviation extrusion
format
glyph-metric-pointer)))
(or (win32::wgl-use-font-bitmaps hdc start count list-base)
(win32::wgl-use-font-bitmaps hdc start count list-base)))
(unwind-protect
(let ((windows-error-message (win32:get-last-error)))
(case errorp
(:warn (warn "~S failed : (getLastError = ~d) " 'wgl-use-font windows-error-message))
((nil) nil)
(otherwise (error "~S failed : (getLastError = ~d)" 'wgl-use-font windows-error-message))))
(opengl:gl-delete-lists list-base count)
(return-from wgl-use-font nil)))
list-base)
(unrealize-tool gpfont))))
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/api/externals/OpenGL/opengl-lw/win32.lisp | lisp | rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / win32.lisp , v 1.10.1.1 2014/05/27 20:56:57 davef Exp $ " -*-
/* pixel types */
/* layer types */
/* PIXELFORMATDESCRIPTOR flags */
------------------------------------------------------------
----------------------------------------------------------------------
Support for text within double buffered OpenGL panes
----------------------------------------------------------------------
For extruded 3D fonts
Convert a font to a bitmap.
(WGL-USE-FONT OPENGL-PANE &key FONT OUTLINEP DEVIATION
EXTRUSION GLYPH-METRIC-POINTER
START COUNT ERRORP LIST-BASE)
Create a display-list for a given font.
Arguments :
FONT : capi font specification. If no font is specified then the
of each font character will be generated.
Otherwise - A display list containing 3d character representation
for each font character will be generated. (Note that
DEVIATION : FLOAT - chordal deviation from the original outlines
then no data will be stored.
RESULTS :
The list-base used for creating the font (or NIL indicating an error).
Note that once the font list (pointed to by the list-base) is no longer
For some reason - OpenGL on NT sometimes fails to
the reason why. The simple fix is if the creation
wglUseFont... again to make sure that there really
is some form or error??? |
Copyright ( c ) 1987 - -2015 LispWorks Ltd. All rights reserved .
(in-package "WIN32")
From WINGDI.H
(defconstant *PFD-TYPE-RGBA* 0)
(defconstant *PFD-TYPE-COLORINDEX* 1)
(defconstant *PFD-MAIN-PLANE* 0)
(defconstant *PFD-OVERLAY-PLANE* 1)
(defconstant *PFD-UNDERLAY-PLANE* -1)
(defconstant *PFD-DOUBLEBUFFER* #x00000001)
(defconstant *PFD-STEREO* #x00000002)
(defconstant *PFD-DRAW-TO-WINDOW* #x00000004)
(defconstant *PFD-DRAW-TO-BITMAP* #x00000008)
(defconstant *PFD-SUPPORT-GDI* #x00000010)
(defconstant *PFD-SUPPORT-OPENGL* #x00000020)
(defconstant *PFD-GENERIC-FORMAT* #x00000040)
(defconstant *PFD-NEED-PALETTE* #x00000080)
(defconstant *PFD-NEED-SYSTEM-PALETTE* #x00000100)
(defconstant *PFD-SWAP-EXCHANGE* #x00000200)
(defconstant *PFD-SWAP-COPY* #x00000400)
/ * PIXELFORMATDESCRIPTOR flags for use in ChoosePixelFormat only * /
(defconstant *PFD-DOUBLEBUFFER-DONTCARE* #x40000000)
(defconstant *PFD-STEREO-DONTCARE* #x80000000)
(fli:define-c-struct (tag-pixel-format-descriptor (:foreign-name "tagPIXELFORMATDESCRIPTOR"))
(nSize WORD)
(nVersion WORD)
(dwFlags DWORD)
(iPixelType BYTE)
(cColorBits BYTE)
(cRedBits BYTE)
(cRedShift BYTE)
(cGreenBits BYTE)
(cGreenShift BYTE)
(cBlueBits BYTE)
(cBlueShift BYTE)
(cAlphaBits BYTE)
(cAlphaShift BYTE)
(cAccumBits BYTE)
(cAccumRedBits BYTE)
(cAccumGreenBits BYTE)
(cAccumBlueBits BYTE)
(cAccumAlphaBits BYTE)
(cDepthBits BYTE)
(cStencilBits BYTE)
(cAuxBuffers BYTE)
(iLayerType BYTE)
(bReserved BYTE)
(dwLayerMask DWORD)
(dwVisibleMask DWORD)
(dwDamageMask DWORD))
(fli:define-c-typedef (pixel-format-descriptor (:foreign-name "PIXELFORMATDESCRIPTOR"))
(:struct tag-pixel-format-descriptor))
(fli:define-c-typedef (hglrc (:foreign-name "HGLRC"))
HANDLE)
(fli:define-foreign-function (get-pixel-format "GetPixelFormat")
((hdc HDC))
:result-type :int
:documentation "Obtains the index of the specified device context's currently selected pixel format."
:language :ansi-c)
(fli:define-foreign-function (choose-pixel-format "ChoosePixelFormat")
((hdc HDC)
(pfd (:ptr pixel-format-descriptor)))
:result-type :int
:documentation "Attempts to find the pixel format supported by a device context that is the best match to a given pixel format specification."
:language :ansi-c)
(fli:define-foreign-function (set-pixel-format "SetPixelFormat")
((hdc HDC)
(iPixelFormat :int)
(pfd (:ptr pixel-format-descriptor)))
:result-type BOOL
:documentation "Sets the specified device context's pixel format to the format specified by the iPixelFormat index"
:language :ansi-c)
(fli:define-foreign-function (%describe-pixel-format "DescribePixelFormat")
((hdc HDC)
(iPixelFormat :int)
(nBytes :int)
(pfd (:ptr pixel-format-descriptor)))
:result-type :int
:documentation "Obtains information about the pixel format identified by iPixelFormat of the device associated with hdc.
The function sets the members of the PIXELFORMATDESCRIPTOR structure pointed to by ppfd with that pixel format information."
:language :ansi-c)
(defun describe-pixel-format (hdc ipfd pfd)
(%describe-pixel-format hdc ipfd (fli:size-of 'pixel-format-descriptor) pfd))
(fli:define-foreign-function (wgl-create-context "wglCreateContext")
((hdc HDC))
:documentation "Creates a new OpenGL rendering context, which is suitable for drawing on the device referenced by hdc.
The rendering context has the same pixel format as the device context."
:result-type HGLRC
:language :ansi-c)
(fli:define-foreign-function (wgl-make-current "wglMakeCurrent")
((hdc HDC)
(hglrc HGLRC))
:documentation "Makes a specified OpenGL rendering context the calling thread's current rendering context.
All subsequent OpenGL calls made by the thread are drawn on the device identified by hdc.
You can also use wglMakeCurrent to make the calling thread's current rendering context not current."
:result-type BOOL
:language :ansi-c)
(fli:define-foreign-function (wgl-delete-context "wglDeleteContext")
((hglrc HGLRC))
:result-type BOOL
:language :ansi-c)
(fli:define-foreign-function (wgl-get-current-context "wglGetCurrentContext")
()
:result-type HGLRC
:language :ansi-c)
(fli:define-foreign-function (wgl-get-current-dc "wglGetCurrentDC")
()
:result-type HDC
:language :ansi-c)
(fli:define-foreign-function (swap-buffers "SwapBuffers")
((hdc HDC))
:result-type BOOL
:language :ansi-c)
(defconstant TMPF_TRUETYPE #x04)
(defconstant *WGL-FONT-LINES* 0)
(defconstant *WGL-FONT-POLYGONS* 1)
(fli:define-c-struct _POINTFLOAT
(x :float)
(y :float))
(fli:define-c-typedef POINTFLOAT (:struct _POINTFLOAT))
(fli:define-c-struct _GLYPHMETRICSFLOAT
(gmfBlackBoxX :float)
(gmfBlackBoxY :float)
(gmfptGlyphOrigin POINTFLOAT)
(gmfCellIncX :float)
(gmfCellIncY :float))
(fli:define-c-typedef GLYPHMETRICSFLOAT
(:struct _GLYPHMETRICSFLOAT))
(fli:define-foreign-function ( win32::wgl-use-font-outlines
"wglUseFontOutlines" :dbcs)
((hdc HDC)
(first DWORD)
(count DWORD)
(list-base DWORD)
(deviation :float)
(extrusion :float)
(format :int)
:result-type BOOL
:language :ansi-c)
(fli:define-foreign-function (win32::wgl-use-font-bitmaps
"wglUseFontBitmaps" :dbcs)
((hdc HDC)
(first DWORD)
(count DWORD)
(list-base DWORD))
:result-type BOOL)
OPENGL - PANE : OPENGL - PANE
font for the OPENGL - PANE will be used .
: BOOLEAN - When NULL - A display list containing bitmap representation
the font must be TrueType in this case )
EXTRUSION : FLOAT - how much the font is extruded in the negative z direction .
GLYPH - METRIC - POINTER : Foreign pointer to an array ( length COUNT ) of
Structures that recieve the glyph metrics . If NIL is passed in
START : INTEGER - First of the set of glyphs which will form the display - list
COUNT : INTEGER - Number of glyphs to be used in the creation of the display - list .
ERRORP : BOOLEAN - When true , an error will be signaled when a glerror occurs .
Otherwise NIL will be returned from the WGL - USE - FONT
LIST - BASE : INTEGER - Specifies the start of the display - list .
required then it should be destroyed by calling OPENGL : GL - DELETE - LISTS
(defun wgl-use-font (opengl-pane &key
(font (gp::get-port-font opengl-pane))
outlinep
(deviation 0.0)
(extrusion 0.1)
glyph-metric-pointer
(start 32) (count 224)
(errorp t)
(list-base (opengl:gl-gen-lists count)))
(let ((gpfont (gp:lookup-font opengl-pane font))
(hdc (win32::wgl-get-current-dc)))
(unwind-protect
(progn
(realize-tool gpfont)
(when (and outlinep
(not (logtest TMPF_TRUETYPE
(logical-font-textmetric-pitch gpfont))))
(opengl:gl-delete-lists list-base count)
(case errorp
(:warn (warn "~s : Outline font must be a TrueType font."
'wgl-use-font))
((nil) nil)
(otherwise (error "~s : Outline font must be a TrueType font."
'wgl-use-font)))
(return-from wgl-use-font nil))
(select-object hdc (drawing-tool-handle gpfont))
create the font the first time around . Not sure of
of the font fails the first time - try calling
(unless (if outlinep
(let ((format (if (eq outlinep :lines)
*WGL-FONT-LINES*
*WGL-FONT-POLYGONS*)))
(or
(win32::wgl-use-font-outlines hdc start count list-base
deviation extrusion
format
glyph-metric-pointer)
(win32::wgl-use-font-outlines hdc start count list-base
deviation extrusion
format
glyph-metric-pointer)))
(or (win32::wgl-use-font-bitmaps hdc start count list-base)
(win32::wgl-use-font-bitmaps hdc start count list-base)))
(unwind-protect
(let ((windows-error-message (win32:get-last-error)))
(case errorp
(:warn (warn "~S failed : (getLastError = ~d) " 'wgl-use-font windows-error-message))
((nil) nil)
(otherwise (error "~S failed : (getLastError = ~d)" 'wgl-use-font windows-error-message))))
(opengl:gl-delete-lists list-base count)
(return-from wgl-use-font nil)))
list-base)
(unrealize-tool gpfont))))
|
0bc76b4834609209cbb2dd998275456c52cd9cc6fc0d78c68ed861aa1844d803 | couchbase/couchdb | cb_auth_info.erl | 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(cb_auth_info).
-export([get/0, trick_dialyzer/1]).
This is a fake cb_auth_info service ( provided by ns_server in couchbase stack )
get() ->
% We can't just return `{auth, <<"admin_user">>, <<"admin_passwd">>}` as
% the dialyzer would complain that it never returns
% `{error, server_not_ready}`. Hence there's another function to trick the
dialyzer . As this module is * only * used to run couchdb without the full
% stack, this is an acceptable trade-off.
trick_dialyzer(auth).
trick_dialyzer(auth) ->
{auth, <<"admin_user">>, <<"admin_passwd">>};
trick_dialyzer(error) ->
{error, server_not_ready}.
| null | https://raw.githubusercontent.com/couchbase/couchdb/8a75fd2faa89f95158de1776354ceccf3e762753/src/couch_dcp/src/cb_auth_info.erl | erlang | 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
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
We can't just return `{auth, <<"admin_user">>, <<"admin_passwd">>}` as
the dialyzer would complain that it never returns
`{error, server_not_ready}`. Hence there's another function to trick the
stack, this is an acceptable trade-off. | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(cb_auth_info).
-export([get/0, trick_dialyzer/1]).
This is a fake cb_auth_info service ( provided by ns_server in couchbase stack )
get() ->
dialyzer . As this module is * only * used to run couchdb without the full
trick_dialyzer(auth).
trick_dialyzer(auth) ->
{auth, <<"admin_user">>, <<"admin_passwd">>};
trick_dialyzer(error) ->
{error, server_not_ready}.
|
38226bc33f6ba54bbd226f30a96bc039731ad60476618babe612b688e372c83b | racket/web-server | dummy-v2-servlet.rkt | #lang racket/base
(define interface-version #f)
(define start #f)
(define manager #f)
(provide (all-defined-out))
| null | https://raw.githubusercontent.com/racket/web-server/f718800b5b3f407f7935adf85dfa663c4bba1651/web-server-doc/web-server/scribblings/dummy-v2-servlet.rkt | racket | #lang racket/base
(define interface-version #f)
(define start #f)
(define manager #f)
(provide (all-defined-out))
|
|
778ef73139699037fc52188ee9cb300987b0e5cd9753e8546d28b74a4c7b4865 | ThomasCrevoisier/chrome-remote-interface-haskell | TH.hs | module Chrome.Target.Message.TH where
import Data.Aeson.TH
import Language.Haskell.TH.Syntax (Dec, Name, Q)
escapeKeywords :: String -> String
escapeKeywords "type" = "_type"
escapeKeywords "data" = "_data"
escapeKeywords str = str
deriveJSONMsg :: Name -> Q [Dec]
deriveJSONMsg = deriveJSON (defaultOptions { omitNothingFields = True, fieldLabelModifier = escapeKeywords })
| null | https://raw.githubusercontent.com/ThomasCrevoisier/chrome-remote-interface-haskell/b7cb4a2367fda40a1e90bc3378a6c4e52578b2d7/src/Chrome/Target/Message/TH.hs | haskell | module Chrome.Target.Message.TH where
import Data.Aeson.TH
import Language.Haskell.TH.Syntax (Dec, Name, Q)
escapeKeywords :: String -> String
escapeKeywords "type" = "_type"
escapeKeywords "data" = "_data"
escapeKeywords str = str
deriveJSONMsg :: Name -> Q [Dec]
deriveJSONMsg = deriveJSON (defaultOptions { omitNothingFields = True, fieldLabelModifier = escapeKeywords })
|
|
9ca12e08ec37de4862c7cf27f7a4a07e32722996e0de40a14720b0bdb5da128d | RichiH/git-annex | UpdateInstead.hs | git - annex UpdateIntead emulation
-
- Copyright 2017 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2017 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Annex.UpdateInstead where
import qualified Annex
import Annex.Common
import Config
import Annex.Version
import Annex.AdjustedBranch
import Git.Branch
import Git.ConfigTypes
{- receive.denyCurrentBranch=updateInstead does not work in direct mode
- repositories or when an adjusted branch is checked out, so must be
- emulated. -}
needUpdateInsteadEmulation :: Annex Bool
needUpdateInsteadEmulation = updateinsteadset <&&> (isDirect <||> isadjusted)
where
updateinsteadset = (== UpdateInstead) . receiveDenyCurrentBranch
<$> Annex.getGitConfig
isadjusted = versionSupportsUnlockedPointers
<&&> (maybe False (isJust . getAdjustment) <$> inRepo Git.Branch.current)
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Annex/UpdateInstead.hs | haskell | receive.denyCurrentBranch=updateInstead does not work in direct mode
- repositories or when an adjusted branch is checked out, so must be
- emulated. | git - annex UpdateIntead emulation
-
- Copyright 2017 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2017 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Annex.UpdateInstead where
import qualified Annex
import Annex.Common
import Config
import Annex.Version
import Annex.AdjustedBranch
import Git.Branch
import Git.ConfigTypes
needUpdateInsteadEmulation :: Annex Bool
needUpdateInsteadEmulation = updateinsteadset <&&> (isDirect <||> isadjusted)
where
updateinsteadset = (== UpdateInstead) . receiveDenyCurrentBranch
<$> Annex.getGitConfig
isadjusted = versionSupportsUnlockedPointers
<&&> (maybe False (isJust . getAdjustment) <$> inRepo Git.Branch.current)
|
f0a0def1af5b558005aa9815e73dc1e9f7242c88d9615f7ee66769d93ac16380 | typedclojure/typedclojure | namespaced_specials.clj | (ns clojure.core.typed.test.namespaced-specials
(:require [typed.clj.checker.test-utils :refer :all]
[clojure.test :refer :all]
[typed.clojure :as t]))
;backwards compatibility tests for type syntax
(deftest value-test
(is-tc-e (ann-form :a ':a))
;old syntax
(is-cf (clojure.core.typed/ann-form :a (clojure.core.typed/Value :a)))
(is-tc-e (ann-form :a (t/Value :a)))
; runtime parsing
(is-tc-e (defalias Foo (t/Value :a)))
; old syntax
(is-cf (clojure.core.typed/defalias Foo (clojure.core.typed/Value :a))))
(deftest quote-test
; bare quote should always resolve to clojure.core/quote
(is-tc-e (do (defalias quote t/Any)
(defalias TAlias (quote :a))
(ann-form :a TAlias)))
(is-tc-e (do (defalias quote t/Any)
(defalias TAlias (quote {:a t/Num}))
(ann-form {:a 1} TAlias))))
(deftest hmap-test
(is-tc-e (ann-form {:a 1} (HMap :mandatory {:a t/Num})))
;old syntax
(is-cf (clojure.core.typed/ann-form {:a 1} (HMap :mandatory {:a clojure.core.typed/Num})))
;new syntax
(is-tc-e (ann-form {:a 1} (t/HMap :mandatory {:a t/Num}))))
(deftest hvec-test
(is-tc-e (ann-form [1] (t/HVec [t/Num])))
;old syntax
(is-cf (clojure.core.typed/ann-form
[1]
(clojure.core.typed/HVec [clojure.core.typed/Num])))
;new syntax
(is-tc-e (ann-form
[1]
(t/HVec [t/Num]))))
(deftest Any-test
(is-tc-e (ann-form {:a 1} t/Any))
;old syntax
(is-cf (clojure.core.typed/ann-form {:a 1} clojure.core.typed/Any))
; new syntax
(is-tc-e (ann-form {:a 1} t/Any)))
(deftest Nothing-test
(is-tc-e (ann-form (fn [] (throw (Exception.)))
[-> t/Nothing]))
;old syntax
(is-cf (clojure.core.typed/ann-form
(fn [] (throw (Exception.)))
[-> clojure.core.typed/Nothing]))
; new syntax
(is-tc-e (ann-form
(fn [] (throw (Exception.)))
[-> t/Nothing])))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/5fd7cdf7941c6e7d1dd5df88bf44474fa35e1fca/typed/clj.checker/test/clojure/core/typed/test/namespaced_specials.clj | clojure | backwards compatibility tests for type syntax
old syntax
runtime parsing
old syntax
bare quote should always resolve to clojure.core/quote
old syntax
new syntax
old syntax
new syntax
old syntax
new syntax
old syntax
new syntax | (ns clojure.core.typed.test.namespaced-specials
(:require [typed.clj.checker.test-utils :refer :all]
[clojure.test :refer :all]
[typed.clojure :as t]))
(deftest value-test
(is-tc-e (ann-form :a ':a))
(is-cf (clojure.core.typed/ann-form :a (clojure.core.typed/Value :a)))
(is-tc-e (ann-form :a (t/Value :a)))
(is-tc-e (defalias Foo (t/Value :a)))
(is-cf (clojure.core.typed/defalias Foo (clojure.core.typed/Value :a))))
(deftest quote-test
(is-tc-e (do (defalias quote t/Any)
(defalias TAlias (quote :a))
(ann-form :a TAlias)))
(is-tc-e (do (defalias quote t/Any)
(defalias TAlias (quote {:a t/Num}))
(ann-form {:a 1} TAlias))))
(deftest hmap-test
(is-tc-e (ann-form {:a 1} (HMap :mandatory {:a t/Num})))
(is-cf (clojure.core.typed/ann-form {:a 1} (HMap :mandatory {:a clojure.core.typed/Num})))
(is-tc-e (ann-form {:a 1} (t/HMap :mandatory {:a t/Num}))))
(deftest hvec-test
(is-tc-e (ann-form [1] (t/HVec [t/Num])))
(is-cf (clojure.core.typed/ann-form
[1]
(clojure.core.typed/HVec [clojure.core.typed/Num])))
(is-tc-e (ann-form
[1]
(t/HVec [t/Num]))))
(deftest Any-test
(is-tc-e (ann-form {:a 1} t/Any))
(is-cf (clojure.core.typed/ann-form {:a 1} clojure.core.typed/Any))
(is-tc-e (ann-form {:a 1} t/Any)))
(deftest Nothing-test
(is-tc-e (ann-form (fn [] (throw (Exception.)))
[-> t/Nothing]))
(is-cf (clojure.core.typed/ann-form
(fn [] (throw (Exception.)))
[-> clojure.core.typed/Nothing]))
(is-tc-e (ann-form
(fn [] (throw (Exception.)))
[-> t/Nothing])))
|
9141892c14d2bd00abcab9e6883f2100b506c11f636ec1f19a347359a3f10678 | haslab/HAAP | Tarefa4_2017li1g180.hs | # LANGUAGE PatternGuards #
module Tarefa4_2017li1g180 where
import LI11718
import Tarefa3_2017li1g180
import Tarefa1_2017li1g180
import Test.QuickCheck.Gen
import Data.List
import Data.Maybe
--import Safe
--import Debug.Trace
testesT4 :: [(Tempo,Jogo,Acao)]
testesT4 = [(0.2,jogoT { carros = ((head $ carros jogoT) { velocidade = (1,0)}) : tail (carros jogoT) },Acao True False True False (Just 0))
,(0.2,jogoT { carros = ((head $ carros jogoT) { velocidade = (3,-1)}) : tail (carros jogoT) },Acao True False False True (Just 0))
,(0.2,jogoT { carros = ((head $ carros jogoT) { velocidade = (0,0)}) : tail (carros jogoT) },Acao False True True False Nothing)
,(0.4,jogoT { carros = ((head $ carros jogoT) { velocidade = (1,0)}) : tail (carros jogoT) },Acao True False True False (Just 0))]
jogoT = jogoInicial $ constroi [Avanca,Avanca,CurvaDir,CurvaDir,Avanca,Avanca,CurvaDir,CurvaDir]
njogadores = 1
qntnitro = 5
jogoInicial :: Mapa -> Jogo
jogoInicial m@(Mapa p t) = Jogo { mapa = m
, pista = standard
, carros = map (carroInicial t (fst p)) [0..njogadores-1]
, nitros = replicate njogadores qntnitro
, historico = replicate njogadores [(fst p)]
}
carroInicial :: Tabuleiro -> Posicao -> Int -> Carro
carroInicial t (a,b) i = Carro { posicao = centroPeca tp (a,b)
, direcao = 0
, velocidade = (0,0)
}
where (Peca tp _) = (t!!b!!a)
centroPeca :: Tipo -> Posicao -> Ponto
centroPeca (Curva Norte) (a,b) = (toEnum a+0.7,toEnum b+0.7)
centroPeca (Curva Este) (a,b) = (toEnum a+0.3,toEnum b+0.7)
centroPeca (Curva Sul) (a,b) = (toEnum a+0.3,toEnum b+0.3)
centroPeca (Curva Oeste) (a,b) = (toEnum a+0.7,toEnum b+0.3)
centroPeca _ (a,b) = (toEnum a+0.5,toEnum b+0.5)
standard = Propriedades (1.5) 1 4 2 15 90
atualiza :: Tempo -> Jogo -> Int -> Acao -> Jogo
atualiza t e j a = lancaNitros t j e e' a
where e' = e { carros = cs', historico = hs' }
Mapa _ m = (mapa e)
c' = moveCarro t e (carros e!!j,a)
h' = atualizaHistorico (carros e!!j) (historico e!!j)
cs' = (take j (carros e))++(c':drop (j+1) (carros e))
hs' = (take j (historico e))++(h':drop (j+1) (historico e))
moveCarro :: Tempo -> Jogo -> (Carro,Acao) -> Carro
moveCarro t e (c,a) = rodaCarro t e (andaCarro t e (c,a) ,a)
rodaCarro :: Tempo -> Jogo -> (Carro,Acao) -> Carro
rodaCarro t e (c,a) | direita a && not (esquerda a) = c { direcao = direcao c - (t*k_roda (pista e))}
| esquerda a && not (direita a) = c { direcao = direcao c + (t*k_roda (pista e))}
| otherwise = c
atualizaHistorico :: Carro -> [Posicao] -> [Posicao]
atualizaHistorico c [] = [(floor (fst (posicao c)), floor (snd (posicao c)))]
atualizaHistorico c (h:hs) = hs'
where (i,j) = (floor (fst (posicao c)), floor (snd (posicao c)))
hs' | h == (i,j) = (h:hs)
| otherwise = (i,j):h:hs
lancaNitros :: Tempo -> Int -> Jogo -> Jogo -> Acao -> Jogo
lancaNitros _ _ e0 e (Acao _ _ _ _ Nothing) = e
lancaNitros t i e0 e (Acao _ _ _ _ (Just j)) | (nitros e)!!i == 0 = e
| otherwise = e { carros = cs', nitros = ns' }
where tNitro = min t (max 0 ((nitros e)!!i))
ns' = (take i (nitros e))++(n':drop (i+1) (nitros e))
cs' = (take j (carros e))++(c':drop (j+1) (carros e))
n' = max 0 (((nitros e)!!i)-tNitro)
c = (carros e)!!j
c0 = (carros e0)!!j
c' = c { velocidade = (velocidade c) .+. (tNitro .*. (nitroVec (pista e) c0)) }
andaCarro :: Tempo -> Jogo -> (Carro,Acao) -> Carro
andaCarro t e (c,a) = c { velocidade = v' }
where v' = (velocidade c) .+. (t .*. ((accelVec ps (c,a)) .+. (dragVec ps c) .+. (driftVec ps c) .+. (gravityVec ps p c)))
ps = pista e
Mapa _ m = mapa e
(i,j) = (floor (fst (posicao c)), floor (snd (posicao c)))
p = m!!j!!i
accelVec :: Propriedades -> (Carro,Acao) -> Velocidade
accelVec ps (c,a) | acelerar a && not (travar a) = arrowToComponents (k_acel ps,direcao c)
| travar a && not (acelerar a) = arrowToComponents (k_acel ps,direcao c + 180)
| otherwise = (0,0)
dragVec :: Propriedades -> Carro -> Velocidade
dragVec ps c = arrowToComponents (v*k_atrito ps,a + 180)
where (v,a) = componentsToArrow (velocidade c)
driftVec :: Propriedades -> Carro -> Velocidade
driftVec ps c = arrowToComponents (driftCoef,driftAngle)
where (v,a) = componentsToArrow $ velocidade c
d = direcao c
driftAngle = if (sin (radians (a-d))) > 0
then d-90 -- going right
else d+90 -- going left
driftCoef = v * k_pneus ps * abs (sin (radians (a-d)))
nitroVec :: Propriedades -> Carro -> Velocidade
nitroVec ps c = arrowToComponents (k_nitro ps,direcao c)
gravityVec :: Propriedades -> Peca -> Carro -> Velocidade
gravityVec ps (Peca (Rampa Sul) _) c = arrowToComponents (k_peso ps, 90)
gravityVec ps (Peca (Rampa Norte) _) c = arrowToComponents (k_peso ps, 270)
gravityVec ps (Peca (Rampa Oeste) _) c = arrowToComponents (k_peso ps, 0)
gravityVec ps (Peca (Rampa Este) _) c = arrowToComponents (k_peso ps, 180)
gravityVec ps _ c = (0,0)
| null | https://raw.githubusercontent.com/haslab/HAAP/5acf9efaf0e5f6cba1c2482e51bda703f405a86f/examples/plab/svn/2017li1g180/src/Tarefa4_2017li1g180.hs | haskell | import Safe
import Debug.Trace
going right
going left | # LANGUAGE PatternGuards #
module Tarefa4_2017li1g180 where
import LI11718
import Tarefa3_2017li1g180
import Tarefa1_2017li1g180
import Test.QuickCheck.Gen
import Data.List
import Data.Maybe
testesT4 :: [(Tempo,Jogo,Acao)]
testesT4 = [(0.2,jogoT { carros = ((head $ carros jogoT) { velocidade = (1,0)}) : tail (carros jogoT) },Acao True False True False (Just 0))
,(0.2,jogoT { carros = ((head $ carros jogoT) { velocidade = (3,-1)}) : tail (carros jogoT) },Acao True False False True (Just 0))
,(0.2,jogoT { carros = ((head $ carros jogoT) { velocidade = (0,0)}) : tail (carros jogoT) },Acao False True True False Nothing)
,(0.4,jogoT { carros = ((head $ carros jogoT) { velocidade = (1,0)}) : tail (carros jogoT) },Acao True False True False (Just 0))]
jogoT = jogoInicial $ constroi [Avanca,Avanca,CurvaDir,CurvaDir,Avanca,Avanca,CurvaDir,CurvaDir]
njogadores = 1
qntnitro = 5
jogoInicial :: Mapa -> Jogo
jogoInicial m@(Mapa p t) = Jogo { mapa = m
, pista = standard
, carros = map (carroInicial t (fst p)) [0..njogadores-1]
, nitros = replicate njogadores qntnitro
, historico = replicate njogadores [(fst p)]
}
carroInicial :: Tabuleiro -> Posicao -> Int -> Carro
carroInicial t (a,b) i = Carro { posicao = centroPeca tp (a,b)
, direcao = 0
, velocidade = (0,0)
}
where (Peca tp _) = (t!!b!!a)
centroPeca :: Tipo -> Posicao -> Ponto
centroPeca (Curva Norte) (a,b) = (toEnum a+0.7,toEnum b+0.7)
centroPeca (Curva Este) (a,b) = (toEnum a+0.3,toEnum b+0.7)
centroPeca (Curva Sul) (a,b) = (toEnum a+0.3,toEnum b+0.3)
centroPeca (Curva Oeste) (a,b) = (toEnum a+0.7,toEnum b+0.3)
centroPeca _ (a,b) = (toEnum a+0.5,toEnum b+0.5)
standard = Propriedades (1.5) 1 4 2 15 90
atualiza :: Tempo -> Jogo -> Int -> Acao -> Jogo
atualiza t e j a = lancaNitros t j e e' a
where e' = e { carros = cs', historico = hs' }
Mapa _ m = (mapa e)
c' = moveCarro t e (carros e!!j,a)
h' = atualizaHistorico (carros e!!j) (historico e!!j)
cs' = (take j (carros e))++(c':drop (j+1) (carros e))
hs' = (take j (historico e))++(h':drop (j+1) (historico e))
moveCarro :: Tempo -> Jogo -> (Carro,Acao) -> Carro
moveCarro t e (c,a) = rodaCarro t e (andaCarro t e (c,a) ,a)
rodaCarro :: Tempo -> Jogo -> (Carro,Acao) -> Carro
rodaCarro t e (c,a) | direita a && not (esquerda a) = c { direcao = direcao c - (t*k_roda (pista e))}
| esquerda a && not (direita a) = c { direcao = direcao c + (t*k_roda (pista e))}
| otherwise = c
atualizaHistorico :: Carro -> [Posicao] -> [Posicao]
atualizaHistorico c [] = [(floor (fst (posicao c)), floor (snd (posicao c)))]
atualizaHistorico c (h:hs) = hs'
where (i,j) = (floor (fst (posicao c)), floor (snd (posicao c)))
hs' | h == (i,j) = (h:hs)
| otherwise = (i,j):h:hs
lancaNitros :: Tempo -> Int -> Jogo -> Jogo -> Acao -> Jogo
lancaNitros _ _ e0 e (Acao _ _ _ _ Nothing) = e
lancaNitros t i e0 e (Acao _ _ _ _ (Just j)) | (nitros e)!!i == 0 = e
| otherwise = e { carros = cs', nitros = ns' }
where tNitro = min t (max 0 ((nitros e)!!i))
ns' = (take i (nitros e))++(n':drop (i+1) (nitros e))
cs' = (take j (carros e))++(c':drop (j+1) (carros e))
n' = max 0 (((nitros e)!!i)-tNitro)
c = (carros e)!!j
c0 = (carros e0)!!j
c' = c { velocidade = (velocidade c) .+. (tNitro .*. (nitroVec (pista e) c0)) }
andaCarro :: Tempo -> Jogo -> (Carro,Acao) -> Carro
andaCarro t e (c,a) = c { velocidade = v' }
where v' = (velocidade c) .+. (t .*. ((accelVec ps (c,a)) .+. (dragVec ps c) .+. (driftVec ps c) .+. (gravityVec ps p c)))
ps = pista e
Mapa _ m = mapa e
(i,j) = (floor (fst (posicao c)), floor (snd (posicao c)))
p = m!!j!!i
accelVec :: Propriedades -> (Carro,Acao) -> Velocidade
accelVec ps (c,a) | acelerar a && not (travar a) = arrowToComponents (k_acel ps,direcao c)
| travar a && not (acelerar a) = arrowToComponents (k_acel ps,direcao c + 180)
| otherwise = (0,0)
dragVec :: Propriedades -> Carro -> Velocidade
dragVec ps c = arrowToComponents (v*k_atrito ps,a + 180)
where (v,a) = componentsToArrow (velocidade c)
driftVec :: Propriedades -> Carro -> Velocidade
driftVec ps c = arrowToComponents (driftCoef,driftAngle)
where (v,a) = componentsToArrow $ velocidade c
d = direcao c
driftAngle = if (sin (radians (a-d))) > 0
driftCoef = v * k_pneus ps * abs (sin (radians (a-d)))
nitroVec :: Propriedades -> Carro -> Velocidade
nitroVec ps c = arrowToComponents (k_nitro ps,direcao c)
gravityVec :: Propriedades -> Peca -> Carro -> Velocidade
gravityVec ps (Peca (Rampa Sul) _) c = arrowToComponents (k_peso ps, 90)
gravityVec ps (Peca (Rampa Norte) _) c = arrowToComponents (k_peso ps, 270)
gravityVec ps (Peca (Rampa Oeste) _) c = arrowToComponents (k_peso ps, 0)
gravityVec ps (Peca (Rampa Este) _) c = arrowToComponents (k_peso ps, 180)
gravityVec ps _ c = (0,0)
|
2adb722f2ae2f7855855b585082228bd218cc7281e5866774382352249468bf6 | mikeizbicki/subhask | Logic.hs | module SubHask.Algebra.Logic
where
import Control.Monad
import Test.QuickCheck.Gen (suchThat,oneof)
import SubHask.Algebra
import SubHask.Category
import SubHask.Internal.Prelude
import SubHask.TemplateHaskell.Deriving
class (Ord r, Ring r) => OrdRing_ r
instance (Ord r, Ring r) => OrdRing_ r
--------------------------------------------------------------------------------
| The fuzzy logic is one of the simpler fuzzy logics .
In particular , it is an example of a Heyting algebra that is not also a Boolean algebra .
--
-- See the <plato.stanford.edu/entries/logic-fuzzy standford encyclopedia of logic>
type Goedel = Goedel_ Rational
newtype Goedel_ r = Goedel_ r
deriveHierarchyFiltered ''Goedel_ [ ''Eq_ ] [ ''Arbitrary ]
instance (OrdRing_ r, Arbitrary r) => Arbitrary (Goedel_ r) where
arbitrary = fmap Goedel_ $ arbitrary `suchThat` ((>=0) && (<=1))
instance OrdRing_ r => POrd_ (Goedel_ r) where
inf (Goedel_ r1) (Goedel_ r2) = Goedel_ $ min r1 r2
instance OrdRing_ r => Lattice_ (Goedel_ r) where
sup (Goedel_ r1) (Goedel_ r2) = Goedel_ $ max r1 r2
instance OrdRing_ r => Ord_ (Goedel_ r)
instance OrdRing_ r => MinBound_ (Goedel_ r) where
minBound = Goedel_ 0
instance OrdRing_ r => Bounded (Goedel_ r) where
maxBound = Goedel_ 1
instance OrdRing_ r => Heyting (Goedel_ r) where
( _ r1)==>(Goedel _ r2 ) = if r1 < = r2 then _ 1 else _ ( 1 - r1 + r2 )
(Goedel_ r1)==>(Goedel_ r2) = if r1 <= r2 then Goedel_ 1 else Goedel_ r2
---------------------------------------
| H3 is the smallest Heyting algebra that is not also a boolean algebra .
-- In addition to true and false, there is a value to represent whether something's truth is unknown.
AFAIK it has no real applications .
--
-- See <#Examples wikipedia>
data H3
= HTrue
| HFalse
| HUnknown
deriving (Read,Show)
instance NFData H3 where
rnf HTrue = ()
rnf HFalse = ()
rnf HUnknown = ()
instance Arbitrary H3 where
arbitrary = oneof $ map return [HTrue, HFalse, HUnknown]
type instance Logic H3 = Bool
instance Eq_ H3 where
HTrue == HTrue = True
HFalse == HFalse = True
HUnknown == HUnknown = True
_ == _ = False
instance POrd_ H3 where
inf HTrue HTrue = HTrue
inf HTrue HUnknown = HUnknown
inf HUnknown HTrue = HUnknown
inf HUnknown HUnknown = HUnknown
inf _ _ = HFalse
instance Lattice_ H3 where
sup HFalse HFalse = HFalse
sup HFalse HUnknown = HUnknown
sup HUnknown HFalse = HUnknown
sup HUnknown HUnknown = HUnknown
sup _ _ = HTrue
instance Ord_ H3
instance MinBound_ H3 where
minBound = HFalse
instance Bounded H3 where
maxBound = HTrue
instance Heyting H3 where
_ ==> HTrue = HTrue
HFalse ==> _ = HTrue
HTrue ==> HFalse = HFalse
HUnknown ==> HUnknown = HTrue
HUnknown ==> HFalse = HFalse
_ ==> _ = HUnknown
---------------------------------------
| K3 stands for Kleene 's 3 - valued logic .
-- In addition to true and false, there is a value to represent whether something's truth is unknown.
K3 is an example of a logic that is neither Boolean nor Heyting .
--
-- See <-valued_logic wikipedia>.
--
FIXME : We need a way to represent implication and negation for logics outside of the Lattice hierarchy .
data K3
= KTrue
| KFalse
| KUnknown
deriving (Read,Show)
instance NFData K3 where
rnf KTrue = ()
rnf KFalse = ()
rnf KUnknown = ()
instance Arbitrary K3 where
arbitrary = oneof $ map return [KTrue, KFalse, KUnknown]
type instance Logic K3 = Bool
instance Eq_ K3 where
KTrue == KTrue = True
KFalse == KFalse = True
KUnknown == KUnknown = True
_ == _ = False
instance POrd_ K3 where
inf KTrue KTrue = KTrue
inf KTrue KUnknown = KUnknown
inf KUnknown KTrue = KUnknown
inf KUnknown KUnknown = KUnknown
inf _ _ = KFalse
instance Lattice_ K3 where
sup KFalse KFalse = KFalse
sup KFalse KUnknown = KUnknown
sup KUnknown KFalse = KUnknown
sup KUnknown KUnknown = KUnknown
sup _ _ = KTrue
instance Ord_ K3
instance MinBound_ K3 where
minBound = KFalse
instance Bounded K3 where
maxBound = KTrue
--------------------------------------------------------------------------------
| A Boolean algebra is a special type of Ring .
-- Their applications (set-like operations) tend to be very different than Rings, so it makes sense for the class hierarchies to be completely unrelated.
The " Boolean2Ring " type , however , provides the correct transformation .
newtype Boolean2Ring b = Boolean2Ring b
deriveHierarchy ''Boolean2Ring [ ''Boolean ]
mkBoolean2Ring :: Boolean b => b -> Boolean2Ring b
mkBoolean2Ring = Boolean2Ring
instance (IsMutable b, Boolean b, ValidLogic b) => Semigroup (Boolean2Ring b) where
(Boolean2Ring b1)+(Boolean2Ring b2) = Boolean2Ring $ (b1 || b2) && not (b1 && b2)
instance (IsMutable b, Boolean b, ValidLogic b) => Abelian (Boolean2Ring b)
instance (IsMutable b, Boolean b, ValidLogic b) => Monoid (Boolean2Ring b) where
zero = Boolean2Ring $ false
instance (IsMutable b, Boolean b, ValidLogic b) => Cancellative (Boolean2Ring b) where
(-)=(+)
instance (IsMutable b, Boolean b, ValidLogic b) => Group (Boolean2Ring b) where
negate = id
instance (IsMutable b, Boolean b, ValidLogic b) => Rg (Boolean2Ring b) where
(Boolean2Ring b1)*(Boolean2Ring b2) = Boolean2Ring $ b1 && b2
instance (IsMutable b, Boolean b, ValidLogic b) => Rig (Boolean2Ring b) where
one = Boolean2Ring $ true
instance (IsMutable b, Boolean b, ValidLogic b) => Ring (Boolean2Ring b)
| null | https://raw.githubusercontent.com/mikeizbicki/subhask/f53fd8f465747681c88276c7dabe3646fbdf7d50/src/SubHask/Algebra/Logic.hs | haskell | ------------------------------------------------------------------------------
See the <plato.stanford.edu/entries/logic-fuzzy standford encyclopedia of logic>
-------------------------------------
In addition to true and false, there is a value to represent whether something's truth is unknown.
See <#Examples wikipedia>
-------------------------------------
In addition to true and false, there is a value to represent whether something's truth is unknown.
See <-valued_logic wikipedia>.
------------------------------------------------------------------------------
Their applications (set-like operations) tend to be very different than Rings, so it makes sense for the class hierarchies to be completely unrelated. | module SubHask.Algebra.Logic
where
import Control.Monad
import Test.QuickCheck.Gen (suchThat,oneof)
import SubHask.Algebra
import SubHask.Category
import SubHask.Internal.Prelude
import SubHask.TemplateHaskell.Deriving
class (Ord r, Ring r) => OrdRing_ r
instance (Ord r, Ring r) => OrdRing_ r
| The fuzzy logic is one of the simpler fuzzy logics .
In particular , it is an example of a Heyting algebra that is not also a Boolean algebra .
type Goedel = Goedel_ Rational
newtype Goedel_ r = Goedel_ r
deriveHierarchyFiltered ''Goedel_ [ ''Eq_ ] [ ''Arbitrary ]
instance (OrdRing_ r, Arbitrary r) => Arbitrary (Goedel_ r) where
arbitrary = fmap Goedel_ $ arbitrary `suchThat` ((>=0) && (<=1))
instance OrdRing_ r => POrd_ (Goedel_ r) where
inf (Goedel_ r1) (Goedel_ r2) = Goedel_ $ min r1 r2
instance OrdRing_ r => Lattice_ (Goedel_ r) where
sup (Goedel_ r1) (Goedel_ r2) = Goedel_ $ max r1 r2
instance OrdRing_ r => Ord_ (Goedel_ r)
instance OrdRing_ r => MinBound_ (Goedel_ r) where
minBound = Goedel_ 0
instance OrdRing_ r => Bounded (Goedel_ r) where
maxBound = Goedel_ 1
instance OrdRing_ r => Heyting (Goedel_ r) where
( _ r1)==>(Goedel _ r2 ) = if r1 < = r2 then _ 1 else _ ( 1 - r1 + r2 )
(Goedel_ r1)==>(Goedel_ r2) = if r1 <= r2 then Goedel_ 1 else Goedel_ r2
| H3 is the smallest Heyting algebra that is not also a boolean algebra .
AFAIK it has no real applications .
data H3
= HTrue
| HFalse
| HUnknown
deriving (Read,Show)
instance NFData H3 where
rnf HTrue = ()
rnf HFalse = ()
rnf HUnknown = ()
instance Arbitrary H3 where
arbitrary = oneof $ map return [HTrue, HFalse, HUnknown]
type instance Logic H3 = Bool
instance Eq_ H3 where
HTrue == HTrue = True
HFalse == HFalse = True
HUnknown == HUnknown = True
_ == _ = False
instance POrd_ H3 where
inf HTrue HTrue = HTrue
inf HTrue HUnknown = HUnknown
inf HUnknown HTrue = HUnknown
inf HUnknown HUnknown = HUnknown
inf _ _ = HFalse
instance Lattice_ H3 where
sup HFalse HFalse = HFalse
sup HFalse HUnknown = HUnknown
sup HUnknown HFalse = HUnknown
sup HUnknown HUnknown = HUnknown
sup _ _ = HTrue
instance Ord_ H3
instance MinBound_ H3 where
minBound = HFalse
instance Bounded H3 where
maxBound = HTrue
instance Heyting H3 where
_ ==> HTrue = HTrue
HFalse ==> _ = HTrue
HTrue ==> HFalse = HFalse
HUnknown ==> HUnknown = HTrue
HUnknown ==> HFalse = HFalse
_ ==> _ = HUnknown
| K3 stands for Kleene 's 3 - valued logic .
K3 is an example of a logic that is neither Boolean nor Heyting .
FIXME : We need a way to represent implication and negation for logics outside of the Lattice hierarchy .
data K3
= KTrue
| KFalse
| KUnknown
deriving (Read,Show)
instance NFData K3 where
rnf KTrue = ()
rnf KFalse = ()
rnf KUnknown = ()
instance Arbitrary K3 where
arbitrary = oneof $ map return [KTrue, KFalse, KUnknown]
type instance Logic K3 = Bool
instance Eq_ K3 where
KTrue == KTrue = True
KFalse == KFalse = True
KUnknown == KUnknown = True
_ == _ = False
instance POrd_ K3 where
inf KTrue KTrue = KTrue
inf KTrue KUnknown = KUnknown
inf KUnknown KTrue = KUnknown
inf KUnknown KUnknown = KUnknown
inf _ _ = KFalse
instance Lattice_ K3 where
sup KFalse KFalse = KFalse
sup KFalse KUnknown = KUnknown
sup KUnknown KFalse = KUnknown
sup KUnknown KUnknown = KUnknown
sup _ _ = KTrue
instance Ord_ K3
instance MinBound_ K3 where
minBound = KFalse
instance Bounded K3 where
maxBound = KTrue
| A Boolean algebra is a special type of Ring .
The " Boolean2Ring " type , however , provides the correct transformation .
newtype Boolean2Ring b = Boolean2Ring b
deriveHierarchy ''Boolean2Ring [ ''Boolean ]
mkBoolean2Ring :: Boolean b => b -> Boolean2Ring b
mkBoolean2Ring = Boolean2Ring
instance (IsMutable b, Boolean b, ValidLogic b) => Semigroup (Boolean2Ring b) where
(Boolean2Ring b1)+(Boolean2Ring b2) = Boolean2Ring $ (b1 || b2) && not (b1 && b2)
instance (IsMutable b, Boolean b, ValidLogic b) => Abelian (Boolean2Ring b)
instance (IsMutable b, Boolean b, ValidLogic b) => Monoid (Boolean2Ring b) where
zero = Boolean2Ring $ false
instance (IsMutable b, Boolean b, ValidLogic b) => Cancellative (Boolean2Ring b) where
(-)=(+)
instance (IsMutable b, Boolean b, ValidLogic b) => Group (Boolean2Ring b) where
negate = id
instance (IsMutable b, Boolean b, ValidLogic b) => Rg (Boolean2Ring b) where
(Boolean2Ring b1)*(Boolean2Ring b2) = Boolean2Ring $ b1 && b2
instance (IsMutable b, Boolean b, ValidLogic b) => Rig (Boolean2Ring b) where
one = Boolean2Ring $ true
instance (IsMutable b, Boolean b, ValidLogic b) => Ring (Boolean2Ring b)
|
82e466aa9490aca8c41722ce07cdf93c43e966c8e85e53a4e5e550ea6a9b3e22 | PrincetonUniversity/lucid | ifToMatch.ml | ifToMatch -- convert if statements to match statements .
Before running this pass , the expressions that if
statements test must be in the following canonical form :
a disjunction of terms ,
where each term is a conjunction of atom ,
where each atom is an equality or inequality check
testing a variable against a constant
TODO : We should merge this with .
The two modules have similar syntaxes for patterns and
rules and there are many duplicated functions .
Before running this pass, the expressions that if
statements test must be in the following canonical form:
a disjunction of terms,
where each term is a conjunction of atom,
where each atom is an equality or inequality check
testing a variable against a constant
TODO: We should merge this with MatchAlgebra.ml.
The two modules have similar syntaxes for patterns and
rules and there are many duplicated functions.
*)
open Core
open CoreSyntax
open TofinoCore
open InterpHelpers
exception Error of string
let error s = raise (Error s)
(* the core algorithm is pulled out of the old backend *)
module FromOldBackend = struct
type pattern = (Cid.t * pat) list
type binary_rule =
| BTrue of pattern
| BFalse of pattern
type binary_rules = binary_rule list
let string_of_pattern pattern =
CL.map
(
fun (cid, pat) -> (
(Cid.to_string cid)
^" : "
^(CorePrinting.pat_to_string pat)
)
)
pattern
|> Caml.String.concat ","
;;
let string_of_patterns brs =
CL.map string_of_pattern brs |> Caml.String.concat "\n"
;;
let string_of_binary_rule br =
match br with
| BTrue(pattern) -> "BTrue("^(string_of_pattern pattern)^")"
| BFalse(pattern) -> "BFalse("^(string_of_pattern pattern)^")"
;;
let string_of_binary_rules brs =
CL.map string_of_binary_rule brs |> Caml.String.concat "\n"
;;
let get_keys exp =
vars_in_exp exp |> MiscUtils.unique_list_of
;;
let get_toplevel_exps = flatten_disjunction
let get_atom_exps = flatten_conjunction
(* get the mapping from key (which appears in the atom) to value *)
let field_pat_of_atom_exp exp : (Cid.t * pat) =
match exp.e with
| EOp (Eq, [evar; eval]) | EOp (Neq, [evar; eval]) ->
( name_from_exp evar
, CoreSyntax.PNum (Z.of_int (int_from_exp eval)))
| _ -> error "unexpected form of expression to convert into a pattern. "
;;
(* get a pattern that encodes exact matches for the keys in the atoms,
and wildcard for the other keys. *)
let pattern_of_atoms keys atoms : pattern =
let pattern = CL.map (field_pat_of_atom_exp) atoms in
let condition_of_key key =
match CL.assoc_opt key pattern with
| Some cond -> cond
| None -> PWild
in
let key_conditions = CL.map condition_of_key keys in
CL.combine keys key_conditions
;;
let binary_rules_from_toplevel_exp keys toplevel_exp : binary_rules =
let atom_exps = get_atom_exps toplevel_exp in
let eqs = CL.filter (filter_eop_kind Eq) atom_exps in
let neqs = CL.filter (filter_eop_kind Neq) atom_exps in
neq_rules -- one rule that evaluates to false for
every atom that does a not equals test
every atom that does a not equals test *)
let neq_rules =
let mapper neq : binary_rule =
BFalse (pattern_of_atoms keys (neq :: eqs))
in
CL.map mapper neqs
in
eq_rules -- one rule for all the conditions that must hold for
the term to evaluate to true , after all the inequalities
have been tested
the term to evaluate to true, after all the inequalities
have been tested *)
let (eq_rules:binary_rule list) = [BTrue (pattern_of_atoms keys eqs)] in
neq_rules @ eq_rules
;;
open MiscUtils
(**** from mergeutils ****)
(* extend a pattern so that it has a column for every var in vars *)
let extend_pat (vars : Cid.t list) (pat : pattern) : pattern =
let conds =
CL.map (fun v -> Caml.Option.value (Cid.lookup_opt pat v) ~default:PWild) vars
in
CL.combine vars conds
;;
make sure that a_pat and b_pat both have the same columns in the same order
let normalize_patterns a_pat b_pat =
let a_vars, _ = CL.split a_pat in
let b_vars, _ = CL.split b_pat in
let vars = unique_list_of (a_vars @ b_vars) in
let a_pat = extend_pat vars a_pat in
let b_pat = extend_pat vars b_pat in
a_pat, b_pat
;;
produce a bitstring condition that is x & & y
return None if the condition is unsatisfiable
return None if the condition is unsatisfiable *)
let rec and_bitstrings (xs: int list) (ys:int list) : (int list option) =
match (xs, ys) with
| ([], []) ->
(* empty bitstrings *)
Some []
| (_, []) | ([], _) ->
error "[and_bitstrings] bitstring length mismatch"
(* length mismatch *)
| (x::xs, y::ys) -> (
let tail_opt = and_bitstrings xs ys in
match tail_opt with
| None -> None
| Some (tail) -> (
match (x, y) with
| (0, 1)
| (1, 0) -> None
| (0, 0)
| (0, -1)
| (-1, 0) -> Some (0::tail)
| (1, 1)
| (1, -1)
| (-1, 1) -> Some (1::tail)
| (-1, -1) -> Some (-1::tail)
| (_, _) -> error "something in a bitstring is not a 0, 1, or -1"
)
)
;;
(* convert an integer into a bitstring *)
let int_to_bitstring (i:z) : int list =
let rec int_to_bits_rev (i:int) : int list =
match (i) with
| 0 -> []
| _ ->
let lastbit = match (Int.(land) i 1) with
| 0 -> 0
| 1 -> 1
| _ -> error "[int_to_bits_rev] impossible case: (i && 1) > 1"
in
lastbit::(int_to_bits_rev (Int.shift_right i 1))
in
CL.rev (int_to_bits_rev (Z.to_int i))
;;
let bitstring_to_maskedint (bs : int list) : int*int =
let to_val_and_mask bit =
match bit with
val : 0 , mask 1
val : 1 , mask 1
val : 0 , mask :0
| _ -> error "invalid bitstring bit"
in
let rec bitstring_to_int bits =
match bits with
| [] -> 0
| hd::tl ->
(Int.shift_left hd (List.length tl)) + (bitstring_to_int tl)
in
let vbits, mbits = CL.map to_val_and_mask bs |> CL.split in
bitstring_to_int vbits, bitstring_to_int mbits
;;
find the intersection of two pats
let intersect_pats a b : pat option =
match (a, b) with
| (PWild, _) -> Some b
| (_, PWild) -> Some a
| (PNum za, PNum zb) -> (
if (Z.equal za zb)
then Some a
else None
)
| (PBit ba, PBit bb) -> (
match (and_bitstrings ba bb) with
| Some ab_bits -> Some (PBit(ab_bits))
| None -> None
)
| (PBit bits, PNum const) | (PNum const , PBit bits) -> (
match (and_bitstrings bits (int_to_bitstring const)) with
| Some ab_bits -> Some (PBit ab_bits)
| None -> None
)
;;
(* find the intersection of patterns a and b *)
let intersect_patterns (a_pat : pattern) (b_pat : pattern) : pattern option =
let a_pat, b_pat = normalize_patterns a_pat b_pat in
let vars, _ = CL.split a_pat in
(* get the intersection conditions *)
let _, a_conds = CL.split a_pat in
let _, b_conds = CL.split b_pat in
let ab_conds = CL.combine a_conds b_conds in
let ab_conds =
CL.map (fun (a_cond, b_cond) -> intersect_pats a_cond b_cond) ab_conds
in
let has_intersect =
CL.fold_left
(fun intersect_exists cond_opt ->
match cond_opt with
| None -> false
| Some _ -> intersect_exists)
true
ab_conds
in
match has_intersect with
(* if there's an intersection, return it *)
| true -> Some (CL.combine vars (CL.map Caml.Option.get ab_conds))
(* *)
| false -> None
;;
* * * end from * * *
let remove_shadow true_rule pred =
(* Poke a hole in pred so that true_rule is not shadowed. *)
match true_rule, pred with
| BTrue _, BTrue _ -> [pred]
| BTrue tpat, BFalse ppat ->
(match intersect_patterns tpat ppat with
| None -> [pred] (* no shadow *)
| Some ipat ->
ipat is the shadow
[BTrue ipat; pred])
| BFalse _, _ -> error "[remove_shadow] it is okay to shadow a false rule."
;;
let rec remove_shadows rule pred_rules =
(* If rule is true, poke holes in any false rules in pred_rules, so that
rule matches. *)
match rule with
| BTrue _ ->
(match pred_rules with
| [] -> []
| [pred_rule] -> remove_shadow rule pred_rule
| pred_rule :: pred_rules ->
remove_shadow rule pred_rule @ remove_shadows rule pred_rules)
| BFalse _ -> pred_rules
;;
let remove_shadow_outer rule_lists =
let remove_shadow_inner pred_lists rule_list =
(* find the positive rule in rule list. *)
let pos_rules =
CL.filter
(fun r ->
match r with
| BTrue _ -> true
| _ -> false)
rule_list
in
let pos_rule = CL.hd pos_rules in
(* poke holes in all the predecessor lists *)
let deshadowed_pred_lists = CL.map (remove_shadows pos_rule) pred_lists in
(* return the list up to here. *)
deshadowed_pred_lists @ [rule_list]
in
CL.fold_left remove_shadow_inner [] rule_lists
;;
(***** from rulesolve *****)
let bitstring_to_maskedint (bs : int list) : int*int =
let to_val_and_mask bit =
match bit with
val : 0 , mask 1
val : 1 , mask 1
val : 0 , mask :0
| _ -> error "invalid bitstring bit"
in
let rec bitstring_to_int bits =
match bits with
| [] -> 0
| hd::tl ->
(Core.Int.shift_left hd (List.length tl)) + (bitstring_to_int tl)
in
let vbits, mbits = CL.map to_val_and_mask bs |> CL.split in
bitstring_to_int vbits, bitstring_to_int mbits
;;
open Z3
open Solver
module Z3Bool = Boolean
module Z3Int = Arithmetic.Integer
module Z3Bit = BitVector
let eqn_of_core_pat ctx (m_exp : pattern) =
for now , use 32 - bit vectors throughout
one term for each field of the pattern
let fold_f (ctx, terms) (m_exp_entry:(Cid.t * CoreSyntax.pat)) =
match m_exp_entry with
| vid, PNum(z) -> (
(* output equation: var == const; *)
let z3_vid = Z3Bit.mk_const_s ctx (Cid.to_string vid) var_bw in
let z3_val = Z3Bit.mk_numeral ctx (string_of_int (Z.to_int z)) var_bw in
let term = Z3Bool.mk_eq ctx z3_vid z3_val in
let = Z3Int.mk_const_s ctx ( Cid.to_string vid ) in
let z3_vint = ( Integer.to_int vint ) in
(* let term = Z3Bool.mk_eq ctx z3_vid z3_vint in *)
ctx, terms @ [term]
)
| vid, PBit bits -> (
output equation : var & & mask = = const ;
let vint, mint = bitstring_to_maskedint bits in
let z3_vid = Z3Bit.mk_const_s ctx (Cid.to_string vid) var_bw in
let z3_v = Z3Bit.mk_numeral ctx (string_of_int vint) var_bw in
let z3_m = Z3Bit.mk_numeral ctx (string_of_int mint) var_bw in
let z3_lhs = Z3Bit.mk_and ctx z3_vid z3_m in
let term = Z3Bool.mk_eq ctx z3_lhs z3_v in
ctx, terms @ [term]
)
| vid, PWild ->
output equation : var & & 0 = = 0 . This says " var may be anything " .
It is important to add a negatable constraint for checking feasibility
of matching rules in sequence .
It is important to add a negatable constraint for checking feasibility
of matching rules in sequence. *)
let z3_vid = Z3Bit.mk_const_s ctx (Cid.to_string vid) var_bw in
let z3_v = Z3Bit.mk_numeral ctx (string_of_int 0) var_bw in
let z3_m = Z3Bit.mk_numeral ctx (string_of_int 0) var_bw in
let z3_lhs = Z3Bit.mk_and ctx z3_vid z3_m in
let term = Z3Bool.mk_eq ctx z3_lhs z3_v in
(* print_endline ("encoded "^(Cid.to_string vid)^"= wild"); *)
ctx, terms @ [term] in
let ctx, terms = CL.fold_left fold_f (ctx, []) m_exp in
let eqn = Z3Bool.mk_and ctx terms in
ctx, eqn
;;
let is_core_pat_still_feasible (pat : pattern) (preds : pattern list) =
print_endline ( " [ is_core_pat_still_feasible ] " ) ;
print_endline ( " ---- " ) ;
print_endline ( " pattern : " ) ;
print_endline ( string_of_pattern pat ) ;
print_endline ( " previous patterns : " ) ;
print_endline ( string_of_patterns ) ;
print_endline ( " ---- " ) ;
print_endline ("----");
print_endline ("pattern:");
print_endline (string_of_pattern pat);
print_endline ("previous patterns:");
print_endline (string_of_patterns preds);
print_endline ("----"); *)
let res = match preds with
| [] -> true
| _ ->
let ctx = mk_context ["model", "true"; "proof", "true"] in
(* encode current rule as equation *)
let ctx, pat_eqn = eqn_of_core_pat ctx pat in
(* encode previous rules as equation *)
let _, pred_eqns = CL.split (CL.map (eqn_of_core_pat ctx) preds) in
(* the previous rules, overall, are an or *)
let preds_eqn = Z3Bool.mk_or ctx pred_eqns in
(* we are interested in something that doesn't match any previous rule *)
let not_preds_eqn = Z3Bool.mk_not ctx preds_eqn in
(* but matches the current rule *)
let intersect_eqn = Z3Bool.mk_and ctx [not_preds_eqn; pat_eqn] in
let solver = Solver.mk_simple_solver ctx in
Solver.add solver [intersect_eqn];
let is_sat = Solver.check solver [] in
(match is_sat with
| UNSATISFIABLE -> false
| SATISFIABLE -> true
| UNKNOWN ->
Printf.printf "unknown\n";
error "unknown sat...")
in
(* print_endline ("RESULT: "^(string_of_bool res)); *)
res
;;
let is_rule_matchable pred_rules rule =
let pat_of_rule r =
match r with
| BTrue pat -> pat
| BFalse pat -> pat
in
let pred_pats = CL.map pat_of_rule pred_rules in
let pat = pat_of_rule rule in
is_core_pat_still_feasible pat pred_pats
;;
(* delete any rules that cannot ever be matched due to
shadows from combined predecessors. *)
let delete_unmatchable_rules rules =
let fold_if_reachable preds rule =
match is_rule_matchable preds rule with
| true -> preds @ [rule]
| false -> preds
in
CL.fold_left fold_if_reachable [] rules
;;
let new_merge keys toplevel_rule_lists =
(* for each true rule in a rule set, make sure that it is not shadowed by
and rules in previous rule lists. *)
let deshadowed_rule_lists = remove_shadow_outer toplevel_rule_lists in
(* flatten the list of rules *)
let rules = CL.flatten deshadowed_rule_lists in
(* add the default rule *)
let default_false = BFalse (pattern_of_atoms keys []) in
let full_rules = rules @ [default_false] in
(* remove any unreachable rules. *)
delete_unmatchable_rules full_rules
;;
(**** THE PRIZE JEWEL
convert an if expression into a list of binary rules,
where ba_true means the expression evals to true, ba_false means it evals to false
****)
let from_if_core exp =
(* get the toplevel expressions *)
let toplevel_exps = get_toplevel_exps exp in
(* get the keys *)
let key_vars = get_keys exp in
(* generate a list of binary rules for each toplevel expression *)
let toplevel_rule_lists =
CL.map (binary_rules_from_toplevel_exp key_vars) toplevel_exps
in
(* merge the rule lists together, being careful about shadows and reachability *)
let rule_list = new_merge key_vars toplevel_rule_lists in
* * * the rule list is a list of binary rules * * *
BA_true means exp evaluates to true
means exp evaluates to false
*** the rule list is a list of binary rules***
BA_true means exp evaluates to true
BA_false means exp evaluates to false
*)
rule_list
;;
end
let binary_rule_to_branch s1 s2 brule =
match brule with
| FromOldBackend.BTrue(pattern) -> (
let pats = CL.split pattern |> snd in
(pats, s1)
)
| FromOldBackend.BFalse(pattern) -> (
let pats = CL.split pattern |> snd in
(pats, s2)
)
;;
let match_of_if exp s1 s2 =
(* calculate rules from exp.
When these rules are applied sequentially,
every BTrue rule is a branch where the exp evaluates to true,
and every BFalse rule is a branch where the exp ecaluates to false
*)
let rules = FromOldBackend.from_if_core exp in
(* print_endline ("rules: ");
print_endline ("----");
FromOldBackend.string_of_binary_rules rules |> print_endline;
print_endline ("----"); *)
(* get keys *)
let key_exps = evars_in_exp exp |> ShareMemopInputs.unique_list_of_eq CoreSyntax.equiv_exp in
(* construct branches from rules and keys *)
let branches = CL.map (binary_rule_to_branch s1 s2) rules in
let res = SMatch(key_exps, branches) in
(* print_endline ("RESULT:"); *)
(* print_endline (CorePrinting.statement_to_string (statement res)); *)
res
;;
let rec process tds =
let v =
object
inherit [_] s_map as super
method! visit_SIf ctx exp s1 s2 =
match_of_if exp
(super#visit_statement ctx s1)
(super#visit_statement ctx s2)
end
in
v#visit_tdecls () tds
;;
(* does the output program have the right form? *)
let no_ifs_form ds =
let v = object
inherit [_] s_iter as super
val mutable pass = true
method pass = pass
method! visit_SIf _ _ _ _ =
pass <- false
end
in
v#visit_tdecls () ds;
v#pass
;;
| null | https://raw.githubusercontent.com/PrincetonUniversity/lucid/627c08aabfa47d165f8fedbf569750ac724ad760/src/lib/backend/transformations/ifToMatch.ml | ocaml | the core algorithm is pulled out of the old backend
get the mapping from key (which appears in the atom) to value
get a pattern that encodes exact matches for the keys in the atoms,
and wildcard for the other keys.
*** from mergeutils ***
extend a pattern so that it has a column for every var in vars
empty bitstrings
length mismatch
convert an integer into a bitstring
find the intersection of patterns a and b
get the intersection conditions
if there's an intersection, return it
Poke a hole in pred so that true_rule is not shadowed.
no shadow
If rule is true, poke holes in any false rules in pred_rules, so that
rule matches.
find the positive rule in rule list.
poke holes in all the predecessor lists
return the list up to here.
**** from rulesolve ****
output equation: var == const;
let term = Z3Bool.mk_eq ctx z3_vid z3_vint in
print_endline ("encoded "^(Cid.to_string vid)^"= wild");
encode current rule as equation
encode previous rules as equation
the previous rules, overall, are an or
we are interested in something that doesn't match any previous rule
but matches the current rule
print_endline ("RESULT: "^(string_of_bool res));
delete any rules that cannot ever be matched due to
shadows from combined predecessors.
for each true rule in a rule set, make sure that it is not shadowed by
and rules in previous rule lists.
flatten the list of rules
add the default rule
remove any unreachable rules.
*** THE PRIZE JEWEL
convert an if expression into a list of binary rules,
where ba_true means the expression evals to true, ba_false means it evals to false
***
get the toplevel expressions
get the keys
generate a list of binary rules for each toplevel expression
merge the rule lists together, being careful about shadows and reachability
calculate rules from exp.
When these rules are applied sequentially,
every BTrue rule is a branch where the exp evaluates to true,
and every BFalse rule is a branch where the exp ecaluates to false
print_endline ("rules: ");
print_endline ("----");
FromOldBackend.string_of_binary_rules rules |> print_endline;
print_endline ("----");
get keys
construct branches from rules and keys
print_endline ("RESULT:");
print_endline (CorePrinting.statement_to_string (statement res));
does the output program have the right form? | ifToMatch -- convert if statements to match statements .
Before running this pass , the expressions that if
statements test must be in the following canonical form :
a disjunction of terms ,
where each term is a conjunction of atom ,
where each atom is an equality or inequality check
testing a variable against a constant
TODO : We should merge this with .
The two modules have similar syntaxes for patterns and
rules and there are many duplicated functions .
Before running this pass, the expressions that if
statements test must be in the following canonical form:
a disjunction of terms,
where each term is a conjunction of atom,
where each atom is an equality or inequality check
testing a variable against a constant
TODO: We should merge this with MatchAlgebra.ml.
The two modules have similar syntaxes for patterns and
rules and there are many duplicated functions.
*)
open Core
open CoreSyntax
open TofinoCore
open InterpHelpers
exception Error of string
let error s = raise (Error s)
module FromOldBackend = struct
type pattern = (Cid.t * pat) list
type binary_rule =
| BTrue of pattern
| BFalse of pattern
type binary_rules = binary_rule list
let string_of_pattern pattern =
CL.map
(
fun (cid, pat) -> (
(Cid.to_string cid)
^" : "
^(CorePrinting.pat_to_string pat)
)
)
pattern
|> Caml.String.concat ","
;;
let string_of_patterns brs =
CL.map string_of_pattern brs |> Caml.String.concat "\n"
;;
let string_of_binary_rule br =
match br with
| BTrue(pattern) -> "BTrue("^(string_of_pattern pattern)^")"
| BFalse(pattern) -> "BFalse("^(string_of_pattern pattern)^")"
;;
let string_of_binary_rules brs =
CL.map string_of_binary_rule brs |> Caml.String.concat "\n"
;;
let get_keys exp =
vars_in_exp exp |> MiscUtils.unique_list_of
;;
let get_toplevel_exps = flatten_disjunction
let get_atom_exps = flatten_conjunction
let field_pat_of_atom_exp exp : (Cid.t * pat) =
match exp.e with
| EOp (Eq, [evar; eval]) | EOp (Neq, [evar; eval]) ->
( name_from_exp evar
, CoreSyntax.PNum (Z.of_int (int_from_exp eval)))
| _ -> error "unexpected form of expression to convert into a pattern. "
;;
let pattern_of_atoms keys atoms : pattern =
let pattern = CL.map (field_pat_of_atom_exp) atoms in
let condition_of_key key =
match CL.assoc_opt key pattern with
| Some cond -> cond
| None -> PWild
in
let key_conditions = CL.map condition_of_key keys in
CL.combine keys key_conditions
;;
let binary_rules_from_toplevel_exp keys toplevel_exp : binary_rules =
let atom_exps = get_atom_exps toplevel_exp in
let eqs = CL.filter (filter_eop_kind Eq) atom_exps in
let neqs = CL.filter (filter_eop_kind Neq) atom_exps in
neq_rules -- one rule that evaluates to false for
every atom that does a not equals test
every atom that does a not equals test *)
let neq_rules =
let mapper neq : binary_rule =
BFalse (pattern_of_atoms keys (neq :: eqs))
in
CL.map mapper neqs
in
eq_rules -- one rule for all the conditions that must hold for
the term to evaluate to true , after all the inequalities
have been tested
the term to evaluate to true, after all the inequalities
have been tested *)
let (eq_rules:binary_rule list) = [BTrue (pattern_of_atoms keys eqs)] in
neq_rules @ eq_rules
;;
open MiscUtils
let extend_pat (vars : Cid.t list) (pat : pattern) : pattern =
let conds =
CL.map (fun v -> Caml.Option.value (Cid.lookup_opt pat v) ~default:PWild) vars
in
CL.combine vars conds
;;
make sure that a_pat and b_pat both have the same columns in the same order
let normalize_patterns a_pat b_pat =
let a_vars, _ = CL.split a_pat in
let b_vars, _ = CL.split b_pat in
let vars = unique_list_of (a_vars @ b_vars) in
let a_pat = extend_pat vars a_pat in
let b_pat = extend_pat vars b_pat in
a_pat, b_pat
;;
produce a bitstring condition that is x & & y
return None if the condition is unsatisfiable
return None if the condition is unsatisfiable *)
let rec and_bitstrings (xs: int list) (ys:int list) : (int list option) =
match (xs, ys) with
| ([], []) ->
Some []
| (_, []) | ([], _) ->
error "[and_bitstrings] bitstring length mismatch"
| (x::xs, y::ys) -> (
let tail_opt = and_bitstrings xs ys in
match tail_opt with
| None -> None
| Some (tail) -> (
match (x, y) with
| (0, 1)
| (1, 0) -> None
| (0, 0)
| (0, -1)
| (-1, 0) -> Some (0::tail)
| (1, 1)
| (1, -1)
| (-1, 1) -> Some (1::tail)
| (-1, -1) -> Some (-1::tail)
| (_, _) -> error "something in a bitstring is not a 0, 1, or -1"
)
)
;;
let int_to_bitstring (i:z) : int list =
let rec int_to_bits_rev (i:int) : int list =
match (i) with
| 0 -> []
| _ ->
let lastbit = match (Int.(land) i 1) with
| 0 -> 0
| 1 -> 1
| _ -> error "[int_to_bits_rev] impossible case: (i && 1) > 1"
in
lastbit::(int_to_bits_rev (Int.shift_right i 1))
in
CL.rev (int_to_bits_rev (Z.to_int i))
;;
let bitstring_to_maskedint (bs : int list) : int*int =
let to_val_and_mask bit =
match bit with
val : 0 , mask 1
val : 1 , mask 1
val : 0 , mask :0
| _ -> error "invalid bitstring bit"
in
let rec bitstring_to_int bits =
match bits with
| [] -> 0
| hd::tl ->
(Int.shift_left hd (List.length tl)) + (bitstring_to_int tl)
in
let vbits, mbits = CL.map to_val_and_mask bs |> CL.split in
bitstring_to_int vbits, bitstring_to_int mbits
;;
find the intersection of two pats
let intersect_pats a b : pat option =
match (a, b) with
| (PWild, _) -> Some b
| (_, PWild) -> Some a
| (PNum za, PNum zb) -> (
if (Z.equal za zb)
then Some a
else None
)
| (PBit ba, PBit bb) -> (
match (and_bitstrings ba bb) with
| Some ab_bits -> Some (PBit(ab_bits))
| None -> None
)
| (PBit bits, PNum const) | (PNum const , PBit bits) -> (
match (and_bitstrings bits (int_to_bitstring const)) with
| Some ab_bits -> Some (PBit ab_bits)
| None -> None
)
;;
let intersect_patterns (a_pat : pattern) (b_pat : pattern) : pattern option =
let a_pat, b_pat = normalize_patterns a_pat b_pat in
let vars, _ = CL.split a_pat in
let _, a_conds = CL.split a_pat in
let _, b_conds = CL.split b_pat in
let ab_conds = CL.combine a_conds b_conds in
let ab_conds =
CL.map (fun (a_cond, b_cond) -> intersect_pats a_cond b_cond) ab_conds
in
let has_intersect =
CL.fold_left
(fun intersect_exists cond_opt ->
match cond_opt with
| None -> false
| Some _ -> intersect_exists)
true
ab_conds
in
match has_intersect with
| true -> Some (CL.combine vars (CL.map Caml.Option.get ab_conds))
| false -> None
;;
* * * end from * * *
let remove_shadow true_rule pred =
match true_rule, pred with
| BTrue _, BTrue _ -> [pred]
| BTrue tpat, BFalse ppat ->
(match intersect_patterns tpat ppat with
| Some ipat ->
ipat is the shadow
[BTrue ipat; pred])
| BFalse _, _ -> error "[remove_shadow] it is okay to shadow a false rule."
;;
let rec remove_shadows rule pred_rules =
match rule with
| BTrue _ ->
(match pred_rules with
| [] -> []
| [pred_rule] -> remove_shadow rule pred_rule
| pred_rule :: pred_rules ->
remove_shadow rule pred_rule @ remove_shadows rule pred_rules)
| BFalse _ -> pred_rules
;;
let remove_shadow_outer rule_lists =
let remove_shadow_inner pred_lists rule_list =
let pos_rules =
CL.filter
(fun r ->
match r with
| BTrue _ -> true
| _ -> false)
rule_list
in
let pos_rule = CL.hd pos_rules in
let deshadowed_pred_lists = CL.map (remove_shadows pos_rule) pred_lists in
deshadowed_pred_lists @ [rule_list]
in
CL.fold_left remove_shadow_inner [] rule_lists
;;
let bitstring_to_maskedint (bs : int list) : int*int =
let to_val_and_mask bit =
match bit with
val : 0 , mask 1
val : 1 , mask 1
val : 0 , mask :0
| _ -> error "invalid bitstring bit"
in
let rec bitstring_to_int bits =
match bits with
| [] -> 0
| hd::tl ->
(Core.Int.shift_left hd (List.length tl)) + (bitstring_to_int tl)
in
let vbits, mbits = CL.map to_val_and_mask bs |> CL.split in
bitstring_to_int vbits, bitstring_to_int mbits
;;
open Z3
open Solver
module Z3Bool = Boolean
module Z3Int = Arithmetic.Integer
module Z3Bit = BitVector
let eqn_of_core_pat ctx (m_exp : pattern) =
for now , use 32 - bit vectors throughout
one term for each field of the pattern
let fold_f (ctx, terms) (m_exp_entry:(Cid.t * CoreSyntax.pat)) =
match m_exp_entry with
| vid, PNum(z) -> (
let z3_vid = Z3Bit.mk_const_s ctx (Cid.to_string vid) var_bw in
let z3_val = Z3Bit.mk_numeral ctx (string_of_int (Z.to_int z)) var_bw in
let term = Z3Bool.mk_eq ctx z3_vid z3_val in
let = Z3Int.mk_const_s ctx ( Cid.to_string vid ) in
let z3_vint = ( Integer.to_int vint ) in
ctx, terms @ [term]
)
| vid, PBit bits -> (
output equation : var & & mask = = const ;
let vint, mint = bitstring_to_maskedint bits in
let z3_vid = Z3Bit.mk_const_s ctx (Cid.to_string vid) var_bw in
let z3_v = Z3Bit.mk_numeral ctx (string_of_int vint) var_bw in
let z3_m = Z3Bit.mk_numeral ctx (string_of_int mint) var_bw in
let z3_lhs = Z3Bit.mk_and ctx z3_vid z3_m in
let term = Z3Bool.mk_eq ctx z3_lhs z3_v in
ctx, terms @ [term]
)
| vid, PWild ->
output equation : var & & 0 = = 0 . This says " var may be anything " .
It is important to add a negatable constraint for checking feasibility
of matching rules in sequence .
It is important to add a negatable constraint for checking feasibility
of matching rules in sequence. *)
let z3_vid = Z3Bit.mk_const_s ctx (Cid.to_string vid) var_bw in
let z3_v = Z3Bit.mk_numeral ctx (string_of_int 0) var_bw in
let z3_m = Z3Bit.mk_numeral ctx (string_of_int 0) var_bw in
let z3_lhs = Z3Bit.mk_and ctx z3_vid z3_m in
let term = Z3Bool.mk_eq ctx z3_lhs z3_v in
ctx, terms @ [term] in
let ctx, terms = CL.fold_left fold_f (ctx, []) m_exp in
let eqn = Z3Bool.mk_and ctx terms in
ctx, eqn
;;
let is_core_pat_still_feasible (pat : pattern) (preds : pattern list) =
print_endline ( " [ is_core_pat_still_feasible ] " ) ;
print_endline ( " ---- " ) ;
print_endline ( " pattern : " ) ;
print_endline ( string_of_pattern pat ) ;
print_endline ( " previous patterns : " ) ;
print_endline ( string_of_patterns ) ;
print_endline ( " ---- " ) ;
print_endline ("----");
print_endline ("pattern:");
print_endline (string_of_pattern pat);
print_endline ("previous patterns:");
print_endline (string_of_patterns preds);
print_endline ("----"); *)
let res = match preds with
| [] -> true
| _ ->
let ctx = mk_context ["model", "true"; "proof", "true"] in
let ctx, pat_eqn = eqn_of_core_pat ctx pat in
let _, pred_eqns = CL.split (CL.map (eqn_of_core_pat ctx) preds) in
let preds_eqn = Z3Bool.mk_or ctx pred_eqns in
let not_preds_eqn = Z3Bool.mk_not ctx preds_eqn in
let intersect_eqn = Z3Bool.mk_and ctx [not_preds_eqn; pat_eqn] in
let solver = Solver.mk_simple_solver ctx in
Solver.add solver [intersect_eqn];
let is_sat = Solver.check solver [] in
(match is_sat with
| UNSATISFIABLE -> false
| SATISFIABLE -> true
| UNKNOWN ->
Printf.printf "unknown\n";
error "unknown sat...")
in
res
;;
let is_rule_matchable pred_rules rule =
let pat_of_rule r =
match r with
| BTrue pat -> pat
| BFalse pat -> pat
in
let pred_pats = CL.map pat_of_rule pred_rules in
let pat = pat_of_rule rule in
is_core_pat_still_feasible pat pred_pats
;;
let delete_unmatchable_rules rules =
let fold_if_reachable preds rule =
match is_rule_matchable preds rule with
| true -> preds @ [rule]
| false -> preds
in
CL.fold_left fold_if_reachable [] rules
;;
let new_merge keys toplevel_rule_lists =
let deshadowed_rule_lists = remove_shadow_outer toplevel_rule_lists in
let rules = CL.flatten deshadowed_rule_lists in
let default_false = BFalse (pattern_of_atoms keys []) in
let full_rules = rules @ [default_false] in
delete_unmatchable_rules full_rules
;;
let from_if_core exp =
let toplevel_exps = get_toplevel_exps exp in
let key_vars = get_keys exp in
let toplevel_rule_lists =
CL.map (binary_rules_from_toplevel_exp key_vars) toplevel_exps
in
let rule_list = new_merge key_vars toplevel_rule_lists in
* * * the rule list is a list of binary rules * * *
BA_true means exp evaluates to true
means exp evaluates to false
*** the rule list is a list of binary rules***
BA_true means exp evaluates to true
BA_false means exp evaluates to false
*)
rule_list
;;
end
let binary_rule_to_branch s1 s2 brule =
match brule with
| FromOldBackend.BTrue(pattern) -> (
let pats = CL.split pattern |> snd in
(pats, s1)
)
| FromOldBackend.BFalse(pattern) -> (
let pats = CL.split pattern |> snd in
(pats, s2)
)
;;
let match_of_if exp s1 s2 =
let rules = FromOldBackend.from_if_core exp in
let key_exps = evars_in_exp exp |> ShareMemopInputs.unique_list_of_eq CoreSyntax.equiv_exp in
let branches = CL.map (binary_rule_to_branch s1 s2) rules in
let res = SMatch(key_exps, branches) in
res
;;
let rec process tds =
let v =
object
inherit [_] s_map as super
method! visit_SIf ctx exp s1 s2 =
match_of_if exp
(super#visit_statement ctx s1)
(super#visit_statement ctx s2)
end
in
v#visit_tdecls () tds
;;
let no_ifs_form ds =
let v = object
inherit [_] s_iter as super
val mutable pass = true
method pass = pass
method! visit_SIf _ _ _ _ =
pass <- false
end
in
v#visit_tdecls () ds;
v#pass
;;
|
4f5766e6c9be13f729f3ddcc8febd5d8b8c6993437d02decf6ddd905d30e8ad8 | wilbowma/cur | cur.rkt | #lang racket/base
(require
racket/function
racket/list
scribble/base
(rename-in
retex
[render-mathpar-judgment _render-mathpar-judgment])
typeset-rewriter
cur/curnel/model/core
redex/reduction-semantics
[except-in
redex/pict
render-term
render-language
render-judgment-form
render-reduction-relation]
pict)
(provide
(all-defined-out)
#;(except-out
(all-from-out redex/pict)
render-term)
table-reduction-style
(all-from-out
cur/curnel/model/core
pict))
(default-font-size 9)
(metafunction-font-size 9)
(label-font-size 9)
(greek-style 'roman)
(upgreek-style 'roman)
(metafunction-style 'swiss)
(label-style 'swiss)
(default-style 'roman)
(literal-style 'roman)
(paren-style 'roman)
(grammar-style (cons 'italic 'roman))
(mathpar-judgment-negspace "-1em")
(current-render-pict-adjust
(λ (x sym) x))
(non-terminal-subscript-style
(cons 'large-script (non-terminal-subscript-style)))
(define-rw-context with-curnel-rws
#:atomic
(['Γc "Γ"])
#:compound
(['type-infer type-infer-rw]
['type-infer-normal
(rw-lambda
[`(type-infer-normal ,Δ ,Γ ,e ,t) =>
`("" ,Δ ";" ,Γ " ⊢ " ,e " ⇒ " ,t "")])]
['type-check
(rw-lambda
[`(type-check ,Δ ,Γ ,e ,t) =>
`("" ,Δ ";" ,Γ " ⊢ " ,e " ⇐ " ,t "")])]
['wf wf-rw]
['valid valid-rw]
['substitute substitute-rw]
['subtype
(rw-lambda
[`(subtype ,Δ ,Γ ,t1 ,t2) =>
`("" ,Δ ";" ,Γ " ⊢ " ,t1 " ≼ " ,t2 "")])]
['convert
(rw-lambda
[`(convert ,Δ ,Γ ,t1 ,t2)
=> (list "" Δ ";" Γ " ⊢ " t1 " ≡ " t2 "")])]
;; NB: Manually compiled because rw-lambda was producing garbage
['λ
(rw-lambda
[`(λ (,x : ,t) ,e) =>
`("" ,(struct-copy lw x [e "λ"] [column (- (lw-column x) 3)]) "" ,x ":" ,t "." ,e "")])]
['Π
(rw-lambda
[`(Π (,x : ,t) ,e) =>
`(""
,(just-before (text "Π" (upgreek-style) (default-font-size)) x)
""
,x ":"
,t "." ,e
"")])]
['elim
(rw-lambda
[`(elim ,D ,motive ,methods ,e) =>
`(""
,(struct-copy lw D [e "elim"] [column (sub1 (lw-column D))])
""
,(just-before
(text (format "~a" (lw-e D)) (non-terminal-subscript-style) (default-font-size))
motive)
" "
,motive
,methods
,e
"")])]
['Γ
(rw-lambda
[`(Γ ,x : ,t) =>
`(""
,(just-before (text "Γ" (grammar-style) (default-font-size)) x)
","
,x
":"
,t
"")])]
['∅
(rw-lambda
[`(∅ (,D : ,n ,t ,Γc)) =>
`(""
,(just-before (text "∅" (literal-style) (default-font-size)) D)
","
,D
":"
"[" ,n "]"
,t
" := "
,Γc
"")]
[`(∅ (,x : ,t)) =>
`(""
,(just-before (text "∅" (literal-style) (default-font-size)) x)
","
,x
":"
,t
"")])]
['Δ
(rw-lambda
[`(Δ (,D : ,n ,t ,Γc)) =>
`(""
,(just-before (text "Δ" (grammar-style) (default-font-size)) D)
","
,D
":"
"[" ,n "]"
,t
" := "
,Γc
"")])]
['Unv
(rw-lambda
[`(Unv ,i) =>
`(""
"Unv "
,i
; ,(just-before (text "Unv" (literal-style) (default-font-size)) i)
; ,(text (format "~a" (lw-e i)) (non-terminal-subscript-style) (default-font-size))
"")])]
['Δ-type-in
(rw-lambda
[`(Δ-type-in ,Δ ,D ,t)
=> (list ""
(set-column D values Δ) " : "
(set-column t (curry + (lw-column-span D)) D) " ∈ "
(set-column Δ (curry + (lw-column-span D) (lw-column-span t) -1) t)
"")])]
['Δ-constr-in
(rw-lambda
[`(Δ-constr-in ,Δ ,c ,t)
=> (list ""
(set-column c values Δ) " : "
(set-column t (curry + (lw-column-span c)) c) " ∈ "
(set-column Δ (curry + (lw-column-span c) (lw-column-span t) -1) t)
"")])]
['Γ-in
(rw-lambda
[`(Γ-in ,Γ ,x ,t)
=>
(list ""
(set-column x values Γ) " : "
(set-column t (curry + (lw-column-span x)) x) " ∈ "
(set-column Γ (curry + (lw-column-span x) (lw-column-span t) -1) t)
"")])]
['unv-type
(lambda (lws)
(define-values (U1 U2)
(values
(list-ref lws 2)
(list-ref lws 3)))
(list "" "(" U1 ", " U2 ") ∈ A" ""))]
['unv-pred
(lambda (lws)
(define-values (U1 U2 U3)
(values
(list-ref lws 2)
(list-ref lws 3)
(list-ref lws 4)))
(list "" "(" U1 ", " U2 ", " U3 ") ∈ R" ""))]
['<=
(lambda (lws)
(define-values (i0 i1)
(values
(list-ref lws 2)
(list-ref lws 3)))
(list "" i0 " ≤ " i1 ""))]
['max
(lambda (lws)
(define-values (max i0 i1)
(values
(list-ref lws 1)
(list-ref lws 2)
(list-ref lws 3)))
(list "" "max(" i0 ", " i1 ")" ""))]
['add1
(lambda (lws)
(define-values (i0)
(values
(list-ref lws 2)))
(list "" i0 " + 1" ""))]))
(define (curnel-format e)
(with-curnel-rws (e)))
(define-syntax-rule (with-curnel e ...)
(curnel-format (thunk e ...)))
(define-syntax-rule (render-term e)
(with-curnel (render-term-cache ttL e)))
(define-syntax-rule (render-term/pretty e)
(with-curnel (render-term/pretty-write ttL (term e))))
(define-syntax-rule (render-judgment-form e)
(with-curnel (render-judgment-form-cache e)))
(define-syntax-rule (render-language e ...)
(with-curnel (render-language-cache e ...)))
(define-syntax-rule (render-reduction-relation e ...)
(with-curnel (render-reduction-relation-cache e ...)))
(define-syntax-rule (render-mathpar-judgment e ...)
(with-curnel (_render-mathpar-judgment e ...)))
| null | https://raw.githubusercontent.com/wilbowma/cur/e039c98941b3d272c6e462387df22846e10b0128/cur-paper/cur.rkt | racket | (except-out
NB: Manually compiled because rw-lambda was producing garbage
,(just-before (text "Unv" (literal-style) (default-font-size)) i)
,(text (format "~a" (lw-e i)) (non-terminal-subscript-style) (default-font-size)) | #lang racket/base
(require
racket/function
racket/list
scribble/base
(rename-in
retex
[render-mathpar-judgment _render-mathpar-judgment])
typeset-rewriter
cur/curnel/model/core
redex/reduction-semantics
[except-in
redex/pict
render-term
render-language
render-judgment-form
render-reduction-relation]
pict)
(provide
(all-defined-out)
(all-from-out redex/pict)
render-term)
table-reduction-style
(all-from-out
cur/curnel/model/core
pict))
(default-font-size 9)
(metafunction-font-size 9)
(label-font-size 9)
(greek-style 'roman)
(upgreek-style 'roman)
(metafunction-style 'swiss)
(label-style 'swiss)
(default-style 'roman)
(literal-style 'roman)
(paren-style 'roman)
(grammar-style (cons 'italic 'roman))
(mathpar-judgment-negspace "-1em")
(current-render-pict-adjust
(λ (x sym) x))
(non-terminal-subscript-style
(cons 'large-script (non-terminal-subscript-style)))
(define-rw-context with-curnel-rws
#:atomic
(['Γc "Γ"])
#:compound
(['type-infer type-infer-rw]
['type-infer-normal
(rw-lambda
[`(type-infer-normal ,Δ ,Γ ,e ,t) =>
`("" ,Δ ";" ,Γ " ⊢ " ,e " ⇒ " ,t "")])]
['type-check
(rw-lambda
[`(type-check ,Δ ,Γ ,e ,t) =>
`("" ,Δ ";" ,Γ " ⊢ " ,e " ⇐ " ,t "")])]
['wf wf-rw]
['valid valid-rw]
['substitute substitute-rw]
['subtype
(rw-lambda
[`(subtype ,Δ ,Γ ,t1 ,t2) =>
`("" ,Δ ";" ,Γ " ⊢ " ,t1 " ≼ " ,t2 "")])]
['convert
(rw-lambda
[`(convert ,Δ ,Γ ,t1 ,t2)
=> (list "" Δ ";" Γ " ⊢ " t1 " ≡ " t2 "")])]
['λ
(rw-lambda
[`(λ (,x : ,t) ,e) =>
`("" ,(struct-copy lw x [e "λ"] [column (- (lw-column x) 3)]) "" ,x ":" ,t "." ,e "")])]
['Π
(rw-lambda
[`(Π (,x : ,t) ,e) =>
`(""
,(just-before (text "Π" (upgreek-style) (default-font-size)) x)
""
,x ":"
,t "." ,e
"")])]
['elim
(rw-lambda
[`(elim ,D ,motive ,methods ,e) =>
`(""
,(struct-copy lw D [e "elim"] [column (sub1 (lw-column D))])
""
,(just-before
(text (format "~a" (lw-e D)) (non-terminal-subscript-style) (default-font-size))
motive)
" "
,motive
,methods
,e
"")])]
['Γ
(rw-lambda
[`(Γ ,x : ,t) =>
`(""
,(just-before (text "Γ" (grammar-style) (default-font-size)) x)
","
,x
":"
,t
"")])]
['∅
(rw-lambda
[`(∅ (,D : ,n ,t ,Γc)) =>
`(""
,(just-before (text "∅" (literal-style) (default-font-size)) D)
","
,D
":"
"[" ,n "]"
,t
" := "
,Γc
"")]
[`(∅ (,x : ,t)) =>
`(""
,(just-before (text "∅" (literal-style) (default-font-size)) x)
","
,x
":"
,t
"")])]
['Δ
(rw-lambda
[`(Δ (,D : ,n ,t ,Γc)) =>
`(""
,(just-before (text "Δ" (grammar-style) (default-font-size)) D)
","
,D
":"
"[" ,n "]"
,t
" := "
,Γc
"")])]
['Unv
(rw-lambda
[`(Unv ,i) =>
`(""
"Unv "
,i
"")])]
['Δ-type-in
(rw-lambda
[`(Δ-type-in ,Δ ,D ,t)
=> (list ""
(set-column D values Δ) " : "
(set-column t (curry + (lw-column-span D)) D) " ∈ "
(set-column Δ (curry + (lw-column-span D) (lw-column-span t) -1) t)
"")])]
['Δ-constr-in
(rw-lambda
[`(Δ-constr-in ,Δ ,c ,t)
=> (list ""
(set-column c values Δ) " : "
(set-column t (curry + (lw-column-span c)) c) " ∈ "
(set-column Δ (curry + (lw-column-span c) (lw-column-span t) -1) t)
"")])]
['Γ-in
(rw-lambda
[`(Γ-in ,Γ ,x ,t)
=>
(list ""
(set-column x values Γ) " : "
(set-column t (curry + (lw-column-span x)) x) " ∈ "
(set-column Γ (curry + (lw-column-span x) (lw-column-span t) -1) t)
"")])]
['unv-type
(lambda (lws)
(define-values (U1 U2)
(values
(list-ref lws 2)
(list-ref lws 3)))
(list "" "(" U1 ", " U2 ") ∈ A" ""))]
['unv-pred
(lambda (lws)
(define-values (U1 U2 U3)
(values
(list-ref lws 2)
(list-ref lws 3)
(list-ref lws 4)))
(list "" "(" U1 ", " U2 ", " U3 ") ∈ R" ""))]
['<=
(lambda (lws)
(define-values (i0 i1)
(values
(list-ref lws 2)
(list-ref lws 3)))
(list "" i0 " ≤ " i1 ""))]
['max
(lambda (lws)
(define-values (max i0 i1)
(values
(list-ref lws 1)
(list-ref lws 2)
(list-ref lws 3)))
(list "" "max(" i0 ", " i1 ")" ""))]
['add1
(lambda (lws)
(define-values (i0)
(values
(list-ref lws 2)))
(list "" i0 " + 1" ""))]))
(define (curnel-format e)
(with-curnel-rws (e)))
(define-syntax-rule (with-curnel e ...)
(curnel-format (thunk e ...)))
(define-syntax-rule (render-term e)
(with-curnel (render-term-cache ttL e)))
(define-syntax-rule (render-term/pretty e)
(with-curnel (render-term/pretty-write ttL (term e))))
(define-syntax-rule (render-judgment-form e)
(with-curnel (render-judgment-form-cache e)))
(define-syntax-rule (render-language e ...)
(with-curnel (render-language-cache e ...)))
(define-syntax-rule (render-reduction-relation e ...)
(with-curnel (render-reduction-relation-cache e ...)))
(define-syntax-rule (render-mathpar-judgment e ...)
(with-curnel (_render-mathpar-judgment e ...)))
|
e11d5ac69b019abd742ca395c7c1af6121829ead1007bb6a49e646b547cffc6a | nyinyithann/favemarks | db.ml | open Core
open Sqlite3
open Core.Result
let get_total_count ~db_path =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql = sprintf "SELECT COUNT(*) FROM bookmarks" in
let stmt = prepare db sql in
ignore @@ step stmt;
let c = column_int stmt 0 in
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok c
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.get_total_count: %s." (Exn.to_string e))
;;
let get_like_clauses search_field search_term =
search_term
|> String.split ~on:','
|> List.fold ~init:"" ~f:(fun acc x ->
let sx = String.strip x in
sprintf "%s %s" (if Common.is_whitespace acc then acc else acc ^ " OR ")
@@ search_field
|> String.split ~on:','
|> List.fold ~init:"" ~f:(fun acc y ->
sprintf
"%s %s LIKE \'%%%s%%\' "
(if Common.is_whitespace acc then acc else acc ^ " OR ")
(String.strip y)
sx))
;;
let get_search_total_count ~db_path ~search_field ~search_term =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql =
sprintf
"SELECT COUNT(*) FROM bookmarks WHERE %s"
(get_like_clauses search_field search_term)
in
let stmt = prepare db sql in
ignore @@ step stmt;
let c = column_int stmt 0 in
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok c
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.get_search_total_count: %s." (Exn.to_string e))
;;
let add ~db_path ~url ~tags =
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
try
let sql =
sprintf
"INSERT INTO bookmarks(url, tags, date) VALUES('%s', '%s', '%s')"
url
tags
(Time.now () |> Time.to_string_utc)
in
let result =
match exec db sql with
| Rc.OK -> Ok (sprintf "%s is added with id %Ld." url (last_insert_rowid db))
| e -> Error (sprintf "db.add: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s ->
ignore @@ db_close db;
Error s
| e ->
ignore @@ db_close db;
Error (sprintf "db.add: %s." (Exn.to_string e))
;;
let update ~db_path ~id ~url ~tags =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql =
sprintf
"UPDATE bookmarks SET url = '%s', tags = '%s', date = '%s' WHERE id = %d"
url
tags
(Time.now () |> Time.to_string_utc)
id
in
let result =
match exec db sql with
| Rc.OK -> Ok (sprintf "Record with id %d is updated." id)
| e -> Error (sprintf "db.update: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.update: %s." (Exn.to_string e))
;;
let delete ~db_path ~id =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql = sprintf "DELETE FROM bookmarks WHERE id = %d" id in
let result =
match exec db sql with
| Rc.OK -> Ok (sprintf "Deleted a record with id %d" id)
| e -> Error (sprintf "db.delete: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.delete: %s." (Exn.to_string e))
;;
let load_all ~db_path =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let data_queue = Queue.create () in
let sql = "SELECT * FROM bookmarks ORDER BY id DESC" in
let stmt = prepare db sql in
while Poly.(step stmt = Rc.ROW) do
let id = column_int stmt 0
and url = column_text stmt 1
and tags = column_text stmt 2
and date = column_text stmt 3 in
Queue.enqueue
data_queue
{ Model.id; mnemonic = ""; url; tags; date = Common.time_of_string date }
done;
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok data_queue
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.load_all: %s." (Exn.to_string e))
;;
let load ~db_path ~mode ~limit ~offset =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let data_queue = Queue.create () in
let sql =
match mode with
| Model.List { sort_field; sort_order } ->
let stf = Option.value sort_field ~default:"id" in
let sto = Option.value sort_order ~default:"DESC" in
sprintf
"SELECT * FROM bookmarks ORDER BY %s %s LIMIT %d OFFSET %d"
stf
sto
limit
offset
| Model.Search { search_field; search_term; sort_field; sort_order } ->
let stf = Option.value sort_field ~default:"id" in
let sto = Option.value sort_order ~default:"DESC" in
sprintf
"SELECT * FROM bookmarks WHERE %s ORDER BY %s %s LIMIT %d OFFSET %d"
(get_like_clauses search_field search_term)
stf
sto
limit
offset
in
let stmt = prepare db sql in
while Poly.(step stmt = Rc.ROW) do
let id = column_int stmt 0
and url = column_text stmt 1
and tags = column_text stmt 2
and date = column_text stmt 3 in
Queue.enqueue
data_queue
{ Model.id; mnemonic = ""; url; tags; date = Common.time_of_string date }
done;
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok data_queue
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.load: %s." (Exn.to_string e))
;;
let db_new ~path =
try
let db = db_open ~uri:true path in
let drop_sql = "DROP TABLE IF EXISTS bookmarks" in
let new_sql =
"CREATE TABLE bookmarks (id INTEGER PRIMARY KEY ASC AUTOINCREMENT UNIQUE,url \
VARCHAR (65536) NOT NULL,tags VARCHAR (65536) NOT NULL,date TEXT)"
in
let result =
match exec db drop_sql with
| Rc.OK ->
(match exec db new_sql with
| Rc.OK -> Ok (sprintf "A new db is created: %s." path)
| e -> Error (sprintf "db.db_new: %s. %s." (Rc.to_string e) (errmsg db)))
| e -> Error (sprintf "db.db_new: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s -> Error s
| e ->
Error
(sprintf
"db.db_new: %s.\nPlease make sure path is valid. e.g. \"/Users/Jazz/fm.db\""
(Exn.to_string e))
;;
| null | https://raw.githubusercontent.com/nyinyithann/favemarks/55fb52d4f3efeae8ef478f1fe098456196e80dea/src/db/db.ml | ocaml | open Core
open Sqlite3
open Core.Result
let get_total_count ~db_path =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql = sprintf "SELECT COUNT(*) FROM bookmarks" in
let stmt = prepare db sql in
ignore @@ step stmt;
let c = column_int stmt 0 in
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok c
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.get_total_count: %s." (Exn.to_string e))
;;
let get_like_clauses search_field search_term =
search_term
|> String.split ~on:','
|> List.fold ~init:"" ~f:(fun acc x ->
let sx = String.strip x in
sprintf "%s %s" (if Common.is_whitespace acc then acc else acc ^ " OR ")
@@ search_field
|> String.split ~on:','
|> List.fold ~init:"" ~f:(fun acc y ->
sprintf
"%s %s LIKE \'%%%s%%\' "
(if Common.is_whitespace acc then acc else acc ^ " OR ")
(String.strip y)
sx))
;;
let get_search_total_count ~db_path ~search_field ~search_term =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql =
sprintf
"SELECT COUNT(*) FROM bookmarks WHERE %s"
(get_like_clauses search_field search_term)
in
let stmt = prepare db sql in
ignore @@ step stmt;
let c = column_int stmt 0 in
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok c
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.get_search_total_count: %s." (Exn.to_string e))
;;
let add ~db_path ~url ~tags =
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
try
let sql =
sprintf
"INSERT INTO bookmarks(url, tags, date) VALUES('%s', '%s', '%s')"
url
tags
(Time.now () |> Time.to_string_utc)
in
let result =
match exec db sql with
| Rc.OK -> Ok (sprintf "%s is added with id %Ld." url (last_insert_rowid db))
| e -> Error (sprintf "db.add: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s ->
ignore @@ db_close db;
Error s
| e ->
ignore @@ db_close db;
Error (sprintf "db.add: %s." (Exn.to_string e))
;;
let update ~db_path ~id ~url ~tags =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql =
sprintf
"UPDATE bookmarks SET url = '%s', tags = '%s', date = '%s' WHERE id = %d"
url
tags
(Time.now () |> Time.to_string_utc)
id
in
let result =
match exec db sql with
| Rc.OK -> Ok (sprintf "Record with id %d is updated." id)
| e -> Error (sprintf "db.update: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.update: %s." (Exn.to_string e))
;;
let delete ~db_path ~id =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let sql = sprintf "DELETE FROM bookmarks WHERE id = %d" id in
let result =
match exec db sql with
| Rc.OK -> Ok (sprintf "Deleted a record with id %d" id)
| e -> Error (sprintf "db.delete: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.delete: %s." (Exn.to_string e))
;;
let load_all ~db_path =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let data_queue = Queue.create () in
let sql = "SELECT * FROM bookmarks ORDER BY id DESC" in
let stmt = prepare db sql in
while Poly.(step stmt = Rc.ROW) do
let id = column_int stmt 0
and url = column_text stmt 1
and tags = column_text stmt 2
and date = column_text stmt 3 in
Queue.enqueue
data_queue
{ Model.id; mnemonic = ""; url; tags; date = Common.time_of_string date }
done;
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok data_queue
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.load_all: %s." (Exn.to_string e))
;;
let load ~db_path ~mode ~limit ~offset =
try
let db = db_open ~mode:`NO_CREATE ~uri:true db_path in
let data_queue = Queue.create () in
let sql =
match mode with
| Model.List { sort_field; sort_order } ->
let stf = Option.value sort_field ~default:"id" in
let sto = Option.value sort_order ~default:"DESC" in
sprintf
"SELECT * FROM bookmarks ORDER BY %s %s LIMIT %d OFFSET %d"
stf
sto
limit
offset
| Model.Search { search_field; search_term; sort_field; sort_order } ->
let stf = Option.value sort_field ~default:"id" in
let sto = Option.value sort_order ~default:"DESC" in
sprintf
"SELECT * FROM bookmarks WHERE %s ORDER BY %s %s LIMIT %d OFFSET %d"
(get_like_clauses search_field search_term)
stf
sto
limit
offset
in
let stmt = prepare db sql in
while Poly.(step stmt = Rc.ROW) do
let id = column_int stmt 0
and url = column_text stmt 1
and tags = column_text stmt 2
and date = column_text stmt 3 in
Queue.enqueue
data_queue
{ Model.id; mnemonic = ""; url; tags; date = Common.time_of_string date }
done;
ignore @@ finalize stmt;
ignore @@ db_close db;
Ok data_queue
with
| SqliteError s -> Error s
| e -> Error (sprintf "db.load: %s." (Exn.to_string e))
;;
let db_new ~path =
try
let db = db_open ~uri:true path in
let drop_sql = "DROP TABLE IF EXISTS bookmarks" in
let new_sql =
"CREATE TABLE bookmarks (id INTEGER PRIMARY KEY ASC AUTOINCREMENT UNIQUE,url \
VARCHAR (65536) NOT NULL,tags VARCHAR (65536) NOT NULL,date TEXT)"
in
let result =
match exec db drop_sql with
| Rc.OK ->
(match exec db new_sql with
| Rc.OK -> Ok (sprintf "A new db is created: %s." path)
| e -> Error (sprintf "db.db_new: %s. %s." (Rc.to_string e) (errmsg db)))
| e -> Error (sprintf "db.db_new: %s. %s." (Rc.to_string e) (errmsg db))
in
ignore @@ db_close db;
result
with
| SqliteError s -> Error s
| e ->
Error
(sprintf
"db.db_new: %s.\nPlease make sure path is valid. e.g. \"/Users/Jazz/fm.db\""
(Exn.to_string e))
;;
|
|
c82112dced515733c486d5f8dafa71d369833d37c2a06dc92e86af117842312b | votinginfoproject/data-processor | tree_xml_postgres_test.clj | (ns vip.data-processor.output.tree-xml-postgres-test
(:require [clojure.test :refer :all]
[korma.core :as korma]
[vip.data-processor.db.postgres :as postgres]
[vip.data-processor.output.tree-xml :refer :all]
[vip.data-processor.pipeline :as pipeline]
[vip.data-processor.test-helpers :refer :all]
[clojure.core.async :as a]))
(use-fixtures :once setup-postgres)
(deftest ^:postgres pipeline-test
(let [import-id (-> postgres/results
(korma/insert
(korma/values {:public_id (name (gensym))}))
:id)
_ (korma/insert postgres/xml-tree-values
(korma/values
[{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.id")
:simple_path (postgres/path->ltree "VipObject.Candidate.id")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "can001"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Name.0")
:simple_path (postgres/path->ltree "VipObject.Candidate.Name")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "Frank"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Party.1")
:simple_path (postgres/path->ltree "VipObject.Candidate.Party")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "Every day"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.0.language")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text.language")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "en"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.0")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "President"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.1.language")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text.language")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "es"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.1")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "\"El\" Presidente"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Nickname.3")
:simple_path (postgres/path->ltree "VipObject.Candidate.Nickname")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "> Ezra"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Contest.1.id")
:simple_path (postgres/path->ltree "VipObject.Contest.id")
:parent_with_id (postgres/path->ltree "VipObject.0.Contest.1.id")
:value "con001"}]))
errors-chan (a/chan 100)
ctx {:spec-version "5.2"
:spec-family "5.2"
:errors-chan errors-chan
:import-id import-id
:pipeline pipeline}
out-ctx (pipeline/run-pipeline ctx)
errors (all-errors errors-chan)]
(assert-no-problems errors {})
(is (= (-> out-ctx
:xml-output-file
.toFile
slurp)
"<?xml version=\"1.0\"?>\n<VipObject xmlns:xsi=\"-instance\" schemaVersion=\"5.2\" xsi:noNamespaceSchemaLocation=\"-specification/v5.2-release/vip_spec.xsd\">\n<Candidate id=\"can001\"><Name>Frank</Name><Party>Every day</Party><Title><Text language=\"en\">President</Text><Text language=\"es\">"El" Presidente</Text></Title><Nickname>> Ezra</Nickname></Candidate><Contest id=\"con001\"></Contest></VipObject>"))))
| null | https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/test/vip/data_processor/output/tree_xml_postgres_test.clj | clojure | (ns vip.data-processor.output.tree-xml-postgres-test
(:require [clojure.test :refer :all]
[korma.core :as korma]
[vip.data-processor.db.postgres :as postgres]
[vip.data-processor.output.tree-xml :refer :all]
[vip.data-processor.pipeline :as pipeline]
[vip.data-processor.test-helpers :refer :all]
[clojure.core.async :as a]))
(use-fixtures :once setup-postgres)
(deftest ^:postgres pipeline-test
(let [import-id (-> postgres/results
(korma/insert
(korma/values {:public_id (name (gensym))}))
:id)
_ (korma/insert postgres/xml-tree-values
(korma/values
[{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.id")
:simple_path (postgres/path->ltree "VipObject.Candidate.id")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "can001"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Name.0")
:simple_path (postgres/path->ltree "VipObject.Candidate.Name")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "Frank"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Party.1")
:simple_path (postgres/path->ltree "VipObject.Candidate.Party")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "Every day"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.0.language")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text.language")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "en"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.0")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "President"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.1.language")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text.language")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "es"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Title.2.Text.1")
:simple_path (postgres/path->ltree "VipObject.Candidate.Title.Text")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "\"El\" Presidente"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Candidate.0.Nickname.3")
:simple_path (postgres/path->ltree "VipObject.Candidate.Nickname")
:parent_with_id (postgres/path->ltree "VipObject.0.Candidate.0.id")
:value "> Ezra"}
{:results_id import-id
:path (postgres/path->ltree "VipObject.0.Contest.1.id")
:simple_path (postgres/path->ltree "VipObject.Contest.id")
:parent_with_id (postgres/path->ltree "VipObject.0.Contest.1.id")
:value "con001"}]))
errors-chan (a/chan 100)
ctx {:spec-version "5.2"
:spec-family "5.2"
:errors-chan errors-chan
:import-id import-id
:pipeline pipeline}
out-ctx (pipeline/run-pipeline ctx)
errors (all-errors errors-chan)]
(assert-no-problems errors {})
(is (= (-> out-ctx
:xml-output-file
.toFile
slurp)
"<?xml version=\"1.0\"?>\n<VipObject xmlns:xsi=\"-instance\" schemaVersion=\"5.2\" xsi:noNamespaceSchemaLocation=\"-specification/v5.2-release/vip_spec.xsd\">\n<Candidate id=\"can001\"><Name>Frank</Name><Party>Every day</Party><Title><Text language=\"en\">President</Text><Text language=\"es\">"El" Presidente</Text></Title><Nickname>> Ezra</Nickname></Candidate><Contest id=\"con001\"></Contest></VipObject>"))))
|
|
474b5f9a03e77e785a9e0227923f008446ea1305650c6844b577fa0a5361c3c2 | technoblogy/lisp-riscv-assembler | RISC-V Assembler.lisp | ;
; RISC-V Assembler - 20th March 2020
; see
;
Print 16 - bit number in hex
(defun x16 (n)
(printhex 4 n))
Print 32 - bit number in hex
(defun x32 (n)
(printhex 8 n))
(defun printhex (m n)
(princ "#x")
(dotimes (j m nil)
(let ((d (logand (ash n (* (- j m -1) 4)) #xf)))
(princ
(code-char (+ d (if (< d 10) (char-code #\0) (char-code #\W))))))))
; Extract register number
(defun regno (sym)
(case sym (zero 0) (ra 1) (sp 2) (gp 3) (tp 4) (s0 8) (fp 8) (s1 9)
(t (let* ((s (string sym))
(c (char s 0))
(n (read-from-string (subseq s 1))))
(case c (#\x n) (#\a (+ n 10)) (#\s (+ n 16)) (#\t (if (<= n 2) (+ n 5) (+ n 25))))))))
; Short 3-bit register
(defun cregp (rd) (<= 8 (regno rd) 15))
(defun cregno (sym) (logand (regno sym) #x7))
; Pack arguments into bit fields
(defun emit (bits &rest args)
(let ((word 0))
(mapc #'(lambda (width value)
(unless (zerop (ash value (- width))) (error* "Won't fit"))
(setq word (logior (ash word width) value)))
bits args)
word))
32 - bit emit
(defun emit* (bits &rest args)
(let ((word (apply #'emit bits args)))
(list (logand word #xffff) (logand (ash word -16) #xffff))))
; Errors
(defun error* (txt) (princ "(pc=") (x16 *pc*) (princ ") ") (princ txt) (terpri))
; Test range of immediate values
(defun immp (x b)
(<= (- (ash 1 (1- b))) x (1- (ash 1 (1- b)))))
; Extract bitfield
(defun bits (x a &optional b)
(if b (logand (ash x (- b)) (1- (ash 1 (- a b -1))))
(logand (ash x (- a)) 1)))
(defun offset (label) (- label *pc*))
; Instruction formats
(defun register (funct7 rs2 rs1 funct3 rd op)
(emit* '(7 5 5 3 5 7) funct7 (regno rs2) (regno rs1) funct3 (regno rd) op))
(defun cregister (op3 op1 op2 rd op2b rs2)
(cond
((and (cregp rd) (cregp rs2))
(emit '(3 1 2 3 2 3 2) op3 op1 op2 (cregno rd) op2b (cregno rs2) 1))
(t (error* "C won't fit"))))
(defun immed (imm12 rs1 funct3 rd op)
(cond
((immp imm12 12)
(emit* '(12 5 3 5 7) (logand imm12 #xfff) (regno rs1) funct3 (regno rd) op))
(t
(error* "Immediate value out of range"))))
(defun cimmed (imm12 rs1 funct3 rd op)
(emit* '(12 5 3 5 7) imm12 (regno rs1) funct3 (regno rd) op))
(defun branch (imm12 rs2 rs1 funct3 funct7)
(let ((off (offset imm12)))
(emit* '(1 6 5 5 3 4 1 7)
(bits off 12) (bits off 10 5) (regno rs2)
(regno rs1) funct3 (bits off 4 1) (bits off 11) funct7)))
(defun jump (imm20 imm10-1 imm11 imm19-12 rd op)
(emit* '(1 10 1 8 5 7) imm20 imm10-1 imm11 imm19-12 rd op))
(defun muldiv (rs2 rs1 funct3 rd funct7)
(emit* '(7 5 5 3 5 7) 1 (regno rs2) (regno rs1) funct3 (regno rd) funct7))
(defun store (imm src base op)
(emit* '(7 5 5 3 5 7) (bits imm 11 5) (regno src) (regno base) op (bits imm 4 0) #x23))
(defun cimm6 (rd imm op1 op2)
(emit '(3 1 5 5 2) op1 (bits imm 5) (regno rd) (bits imm 4 0) op2))
(defun cimm6* (rd imm op1 op2 op3)
(emit '(3 1 2 3 5 2) op1 (bits imm 5) op2 (cregno rd) (bits imm 4 0) op3))
;
; Alphabetical list of mnemonics
;
(defun $add (rd rs1 rs2)
(cond
((eq rd rs1)
(emit '(3 1 5 5 2) 4 1 (regno rd) (regno rs2) 2))
(t (register 0 rs2 rs1 0 rd #x33))))
(defun $addi (rd rs1 imm)
(cond
((and (eq rd rs1) (immp imm 6))
(cimm6 rd imm 0 1))
((and (= (regno rd) 2) (= (regno rs1) 2) (immp imm 10))
(emit '(3 1 5 1 1 2 1 2) 3 (bits imm 9) 2 (bits imm 4) (bits imm 6) (bits imm 8 7) (bits imm 5) 1))
(t (immed imm rs1 0 rd #x13))))
(defun $addiw (rd rs1 imm)
(cond
((and (eq rd rs1) (immp imm 5))
(cimm6 rd imm 1 1))
(t (immed imm rs1 0 rd #x1b))))
(defun $addw (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 1 3 rd 1 rs2))
(t (register 0 rs2 rs1 0 rd #x3b))))
(defun $and (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 3 rs2))
(t (register 0 rs2 rs1 7 rd #x33))))
(defun $andi (rd rs1 imm)
(cond
((and (eq rd rs1) (cregp rd) (immp imm 5))
(cimm6* rd imm 4 2 1))
(t (immed imm rs1 7 rd #x13))))
(defun $auipc (rd imm)
(cond
((zerop (logand imm #xfff))
(emit* '(20 5 7) (bits imm 31 12) (regno rd) #x17))
(t (error* "auipc no good"))))
(defun $beq (rs1 rs2 imm12)
(branch imm12 rs2 rs1 0 #x63))
(defun $beqz (rs imm)
(let ((off (offset imm)))
(cond
((and (immp off 8) (cregp rs))
(emit '(3 1 2 3 2 2 1 2) 6 (bits off 8) (bits off 4 3)
(cregno rs) (bits off 7 6) (bits off 2 1) (bits off 5) 1))
(t ($beq rs 'x0 imm)))))
(defun $ble (rs1 rs2 imm12)
($bge rs2 rs1 imm12))
(defun $bne (rs1 rs2 imm12)
(branch imm12 rs2 rs1 1 #x63))
(defun $bnez (rs imm)
(let ((off (offset imm)))
(cond
((and (immp off 8) (cregp rs))
(emit '(3 1 2 3 2 2 1 2) 7 (bits off 8) (bits off 4 3)
(cregno rs) (bits off 7 6) (bits off 2 1) (bits off 5) 1))
(t ($bne rs 'x0 imm)))))
(defun $bge (rs1 rs2 imm12)
(branch imm12 rs2 rs1 5 #x63))
(defun $bgez (rs1 imm12)
($bge rs1 'x0 imm12))
(defun $bgtz (rs1 imm12)
($blt 'x0 rs1 imm12))
(defun $blt (rs1 rs2 imm12)
(branch imm12 rs2 rs1 4 #x63))
(defun $bltu (rs1 rs2 imm12)
(branch imm12 rs2 rs1 6 #x63))
(defun $bltz (rs1 imm12)
($blt rs1 'x0 imm12))
(defun $bgeu (rs1 rs2 imm12)
(branch imm12 rs2 rs1 7 #x63))
(defun $bleu (rs1 rs2 imm12)
($bgeu rs2 rs1 imm12))
(defun $blez (rs1 imm12)
($bge 'x0 rs1 imm12))
(defun $div (rd rs1 rs2)
(muldiv rs2 rs1 4 rd #x33))
(defun $divu (rd rs1 rs2)
(muldiv rs2 rs1 5 rd #x33))
(defun $divw (rd rs1 rs2)
(muldiv rs2 rs1 4 rd #x3b))
(defun $divuw (rd rs1 rs2)
(muldiv rs2 rs1 5 rd #x3b))
(defun $fence () (emit* '(16 16) #x0ff0 #x000f))
(defun $j (label)
(let ((off (offset label)))
(emit '(3 1 1 2 1 1 1 3 1 2) 5 (bits off 11) (bits off 4) (bits off 9 8)
(bits off 10) (bits off 6) (bits off 7) (bits off 3 1) (bits off 5) 1)))
C.JAL is RV32 only
(defun $jal (rd &optional label)
(when (null label) (setq label rd rd 'ra))
(let ((off (offset label)))
(emit* '(1 10 1 8 5 7) (bits off 20) (bits off 10 1) (bits off 11) (bits off 19 12) (regno rd) #x6f)))
(defun $jalr (label lst)
(let ((off (+ (offset label) 4)))
(emit* '(12 5 3 5 7) (bits off 11 0) (regno (car lst)) 0 (regno (car lst)) #x67)))
(defun $jr (rs1)
(emit '(3 1 5 5 2) 4 0 (regno rs1) 0 2))
(defun $lb (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 0 rd 3))))
(defun $lbu (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 4 rd 3))))
(defun $ld (rd imm lst)
(cond
; rs1 = sp
((and (listp lst) (= (regno (car lst)) 2) (zerop (logand imm #xfe07)))
(emit '(3 1 5 2 3 2) 3 (bits imm 5) (regno rd) (bits imm 4 3) (bits imm 8 6) 2))
; rs1 = general
((and (listp lst) (zerop (logand imm #xff07)) (cregp (car lst)) (cregp rd))
(emit '(3 3 3 2 3 2) 3 (bits imm 5 3) (cregno (car lst)) (bits imm 7 6) (cregno rd) 0))
((listp lst)
(immed imm (car lst) 3 rd 3))))
(defun $lh (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 1 rd 3))))
(defun $lhu (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 5 rd 3))))
li pseudoinstruction - will load 32 - bit immediates
(defun $li (rd imm)
(cond
((immp imm 6)
(cimm6 rd imm 2 1))
(t (let ((imm12 (logand imm #x00000fff))
(imm20 (logand imm #xfffff000)))
(append
($lui rd (if (= (logand imm12 #x800) #x800) (+ imm20 #x1000) imm20))
; $addi
(emit* '(12 5 3 5 7) imm12 (regno rd) 0 (regno rd) #x13))))))
(defun $lui (rd imm)
(cond
((zerop (logand imm #xfff))
(emit* '(20 5 7) (bits imm 31 12) (regno rd) #x37))
(t (error* "lui no good"))))
(defun $lw (rd imm lst)
(cond
((listp lst)
(let ((base (car lst)))
(cond
; rs1 = sp
((and (= (regno base) 2))
(emit '(3 1 5 3 2 2) 2 (bits imm 5) (regno rd) (bits imm 4 2) (bits imm 7 6) 2))
; rs1 = general
((and (cregp rd) (cregp base))
(emit '(3 3 3 1 1 3 2) 2 (bits imm 5 3) (cregno base) (bits imm 2) (bits imm 6) (cregno rd) 0))
(t (immed imm base 2 rd 3)))))
(t (error* "Illegal 3rd arg"))))
(defun $lwu (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 6 rd 3))))
(defun $mul (rd rs1 rs2)
(muldiv rs2 rs1 0 rd #x33))
(defun $mulh (rd rs1 rs2)
(muldiv rs2 rs1 1 rd #x33))
(defun $mulhsu (rd rs1 rs2)
(muldiv rs2 rs1 2 rd #x33))
(defun $mulhu (rd rs1 rs2)
(muldiv rs2 rs1 3 rd #x33))
(defun $mulw (rd rs1 rs2)
(muldiv rs2 rs1 0 rd #x3b))
(defun $mv (rd rs1)
(emit '(3 1 5 5 2) 4 0 (regno rd) (regno rs1) 2))
(defun $nop ()
($addi 'x0 'x0 0))
(defun $or (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 2 rs2))
(t (register 0 rs2 rs1 6 rd #x33))))
(defun $ori (rd rs1 imm)
(immed imm rs1 6 rd #x13))
(defun $rem (rd rs1 rs2)
(muldiv rs2 rs1 6 rd #x33))
(defun $remu (rd rs1 rs2)
(muldiv rs2 rs1 7 rd #x33))
(defun $remw (rd rs1 rs2)
(muldiv rs2 rs1 6 rd #x3b))
(defun $remuw (rd rs1 rs2)
(muldiv rs2 rs1 7 rd #x3b))
(defun $ret ()
($jr 'ra))
(defun $sb (src imm lst)
(cond
((listp lst)
(store imm src (car lst) 0))))
(defun $sd (src imm lst)
(cond
((listp lst)
(let ((base (car lst)))
(cond
; base = sp
((and (= (regno base) 2) (zerop (logand imm #xfe07)))
(emit '(3 3 3 5 2) 7 (bits imm 5 3) (bits imm 8 6) (regno src) 2))
; base = general
((and (cregp src) (cregp base))
(emit '(3 3 3 2 3 2) 7 (bits imm 5 3) (cregno base) (bits imm 7 6) (cregno src) 0))
(t (store imm src base 3)))))
(t (error* "Illegal 3rd arg"))))
(defun $sext.w (rd rs)
($addiw rd rs 0))
(defun $sh (src imm lst)
(cond
((listp lst)
(store imm src (car lst) 1))))
(defun $sll (rd rs1 rs2)
(register 0 rs2 rs1 1 rd #x33))
(defun $slli (rd rs1 imm)
(cond
((and (eq rd rs1))
(cimm6 rd imm 0 2))
(t (emit* '(6 6 5 3 5 7) 0 imm (regno rs1) 1 (regno rd) #x13))))
(defun $sllw (rd rs1 rs2)
(register 0 rs2 rs1 1 rd #x3b))
(defun $slt (rd rs1 rs2)
(register 0 rs2 rs1 2 rd #x33))
(defun $sra (rd rs1 rs2)
(register #x20 rs2 rs1 2 rd #x33))
(defun $srai (rd rs1 imm)
(cond
((and (eq rd rs1) (cregp rd))
(cimm6* rd imm 4 1 1))
(t (emit* '(6 6 5 3 5 7) #x10 imm (regno rs1) 5 (regno rd) #x13))))
(defun $sraw (rd rs1 rs2)
(register #x20 rs2 rs1 5 rd #x3b))
(defun $srl (rd rs1 rs2)
(register 0 rs2 rs1 5 rd #x33))
(defun $srli (rd rs1 imm)
(cond
((and (eq rd rs1) (cregp rd))
(cimm6* rd imm 4 0 1))
(t (emit* '(6 6 5 3 5 7) 0 imm (regno rs1) 5 (regno rd) #x13))))
(defun $srlw (rd rs1 rs2)
(register 0 rs2 rs1 5 rd #x3b))
(defun $sub (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 0 rs2))
(t (register #x20 rs2 rs1 0 rd #x33))))
(defun $subw (rd rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 1 3 rd 0 rs2))
(t (register #x20 rs2 rs1 0 rd #x3b))))
(defun $sw (src imm lst)
(cond
((listp lst)
(let ((base (car lst)))
(cond
; base = sp
((and (= (regno base) 2))
(emit '(3 4 2 5 2) 6 (bits imm 5 2) (bits imm 7 6) (regno src) 2))
; base = general
((and (cregp src) (cregp base))
(emit '(3 3 3 1 1 3 2) 6 (bits imm 5 3) (cregno base) (bits imm 2) (bits imm 6) (cregno src) 0))
(t (store imm src base 2)))))
(t (error* "Illegal 3rd arg"))))
(defun $xor (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 1 rs2))
(t (register 0 rs2 rs1 4 rd #x33))))
(defun $xori (rd rs1 imm)
(immed imm rs1 4 rd #x13))
| null | https://raw.githubusercontent.com/technoblogy/lisp-riscv-assembler/de1f66b29dbabb205c32ee896968b3fb577f0956/RISC-V%20Assembler.lisp | lisp |
RISC-V Assembler - 20th March 2020
see
Extract register number
Short 3-bit register
Pack arguments into bit fields
Errors
Test range of immediate values
Extract bitfield
Instruction formats
Alphabetical list of mnemonics
rs1 = sp
rs1 = general
$addi
rs1 = sp
rs1 = general
base = sp
base = general
base = sp
base = general |
Print 16 - bit number in hex
(defun x16 (n)
(printhex 4 n))
Print 32 - bit number in hex
(defun x32 (n)
(printhex 8 n))
(defun printhex (m n)
(princ "#x")
(dotimes (j m nil)
(let ((d (logand (ash n (* (- j m -1) 4)) #xf)))
(princ
(code-char (+ d (if (< d 10) (char-code #\0) (char-code #\W))))))))
(defun regno (sym)
(case sym (zero 0) (ra 1) (sp 2) (gp 3) (tp 4) (s0 8) (fp 8) (s1 9)
(t (let* ((s (string sym))
(c (char s 0))
(n (read-from-string (subseq s 1))))
(case c (#\x n) (#\a (+ n 10)) (#\s (+ n 16)) (#\t (if (<= n 2) (+ n 5) (+ n 25))))))))
(defun cregp (rd) (<= 8 (regno rd) 15))
(defun cregno (sym) (logand (regno sym) #x7))
(defun emit (bits &rest args)
(let ((word 0))
(mapc #'(lambda (width value)
(unless (zerop (ash value (- width))) (error* "Won't fit"))
(setq word (logior (ash word width) value)))
bits args)
word))
32 - bit emit
(defun emit* (bits &rest args)
(let ((word (apply #'emit bits args)))
(list (logand word #xffff) (logand (ash word -16) #xffff))))
(defun error* (txt) (princ "(pc=") (x16 *pc*) (princ ") ") (princ txt) (terpri))
(defun immp (x b)
(<= (- (ash 1 (1- b))) x (1- (ash 1 (1- b)))))
(defun bits (x a &optional b)
(if b (logand (ash x (- b)) (1- (ash 1 (- a b -1))))
(logand (ash x (- a)) 1)))
(defun offset (label) (- label *pc*))
(defun register (funct7 rs2 rs1 funct3 rd op)
(emit* '(7 5 5 3 5 7) funct7 (regno rs2) (regno rs1) funct3 (regno rd) op))
(defun cregister (op3 op1 op2 rd op2b rs2)
(cond
((and (cregp rd) (cregp rs2))
(emit '(3 1 2 3 2 3 2) op3 op1 op2 (cregno rd) op2b (cregno rs2) 1))
(t (error* "C won't fit"))))
(defun immed (imm12 rs1 funct3 rd op)
(cond
((immp imm12 12)
(emit* '(12 5 3 5 7) (logand imm12 #xfff) (regno rs1) funct3 (regno rd) op))
(t
(error* "Immediate value out of range"))))
(defun cimmed (imm12 rs1 funct3 rd op)
(emit* '(12 5 3 5 7) imm12 (regno rs1) funct3 (regno rd) op))
(defun branch (imm12 rs2 rs1 funct3 funct7)
(let ((off (offset imm12)))
(emit* '(1 6 5 5 3 4 1 7)
(bits off 12) (bits off 10 5) (regno rs2)
(regno rs1) funct3 (bits off 4 1) (bits off 11) funct7)))
(defun jump (imm20 imm10-1 imm11 imm19-12 rd op)
(emit* '(1 10 1 8 5 7) imm20 imm10-1 imm11 imm19-12 rd op))
(defun muldiv (rs2 rs1 funct3 rd funct7)
(emit* '(7 5 5 3 5 7) 1 (regno rs2) (regno rs1) funct3 (regno rd) funct7))
(defun store (imm src base op)
(emit* '(7 5 5 3 5 7) (bits imm 11 5) (regno src) (regno base) op (bits imm 4 0) #x23))
(defun cimm6 (rd imm op1 op2)
(emit '(3 1 5 5 2) op1 (bits imm 5) (regno rd) (bits imm 4 0) op2))
(defun cimm6* (rd imm op1 op2 op3)
(emit '(3 1 2 3 5 2) op1 (bits imm 5) op2 (cregno rd) (bits imm 4 0) op3))
(defun $add (rd rs1 rs2)
(cond
((eq rd rs1)
(emit '(3 1 5 5 2) 4 1 (regno rd) (regno rs2) 2))
(t (register 0 rs2 rs1 0 rd #x33))))
(defun $addi (rd rs1 imm)
(cond
((and (eq rd rs1) (immp imm 6))
(cimm6 rd imm 0 1))
((and (= (regno rd) 2) (= (regno rs1) 2) (immp imm 10))
(emit '(3 1 5 1 1 2 1 2) 3 (bits imm 9) 2 (bits imm 4) (bits imm 6) (bits imm 8 7) (bits imm 5) 1))
(t (immed imm rs1 0 rd #x13))))
(defun $addiw (rd rs1 imm)
(cond
((and (eq rd rs1) (immp imm 5))
(cimm6 rd imm 1 1))
(t (immed imm rs1 0 rd #x1b))))
(defun $addw (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 1 3 rd 1 rs2))
(t (register 0 rs2 rs1 0 rd #x3b))))
(defun $and (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 3 rs2))
(t (register 0 rs2 rs1 7 rd #x33))))
(defun $andi (rd rs1 imm)
(cond
((and (eq rd rs1) (cregp rd) (immp imm 5))
(cimm6* rd imm 4 2 1))
(t (immed imm rs1 7 rd #x13))))
(defun $auipc (rd imm)
(cond
((zerop (logand imm #xfff))
(emit* '(20 5 7) (bits imm 31 12) (regno rd) #x17))
(t (error* "auipc no good"))))
(defun $beq (rs1 rs2 imm12)
(branch imm12 rs2 rs1 0 #x63))
(defun $beqz (rs imm)
(let ((off (offset imm)))
(cond
((and (immp off 8) (cregp rs))
(emit '(3 1 2 3 2 2 1 2) 6 (bits off 8) (bits off 4 3)
(cregno rs) (bits off 7 6) (bits off 2 1) (bits off 5) 1))
(t ($beq rs 'x0 imm)))))
(defun $ble (rs1 rs2 imm12)
($bge rs2 rs1 imm12))
(defun $bne (rs1 rs2 imm12)
(branch imm12 rs2 rs1 1 #x63))
(defun $bnez (rs imm)
(let ((off (offset imm)))
(cond
((and (immp off 8) (cregp rs))
(emit '(3 1 2 3 2 2 1 2) 7 (bits off 8) (bits off 4 3)
(cregno rs) (bits off 7 6) (bits off 2 1) (bits off 5) 1))
(t ($bne rs 'x0 imm)))))
(defun $bge (rs1 rs2 imm12)
(branch imm12 rs2 rs1 5 #x63))
(defun $bgez (rs1 imm12)
($bge rs1 'x0 imm12))
(defun $bgtz (rs1 imm12)
($blt 'x0 rs1 imm12))
(defun $blt (rs1 rs2 imm12)
(branch imm12 rs2 rs1 4 #x63))
(defun $bltu (rs1 rs2 imm12)
(branch imm12 rs2 rs1 6 #x63))
(defun $bltz (rs1 imm12)
($blt rs1 'x0 imm12))
(defun $bgeu (rs1 rs2 imm12)
(branch imm12 rs2 rs1 7 #x63))
(defun $bleu (rs1 rs2 imm12)
($bgeu rs2 rs1 imm12))
(defun $blez (rs1 imm12)
($bge 'x0 rs1 imm12))
(defun $div (rd rs1 rs2)
(muldiv rs2 rs1 4 rd #x33))
(defun $divu (rd rs1 rs2)
(muldiv rs2 rs1 5 rd #x33))
(defun $divw (rd rs1 rs2)
(muldiv rs2 rs1 4 rd #x3b))
(defun $divuw (rd rs1 rs2)
(muldiv rs2 rs1 5 rd #x3b))
(defun $fence () (emit* '(16 16) #x0ff0 #x000f))
(defun $j (label)
(let ((off (offset label)))
(emit '(3 1 1 2 1 1 1 3 1 2) 5 (bits off 11) (bits off 4) (bits off 9 8)
(bits off 10) (bits off 6) (bits off 7) (bits off 3 1) (bits off 5) 1)))
C.JAL is RV32 only
(defun $jal (rd &optional label)
(when (null label) (setq label rd rd 'ra))
(let ((off (offset label)))
(emit* '(1 10 1 8 5 7) (bits off 20) (bits off 10 1) (bits off 11) (bits off 19 12) (regno rd) #x6f)))
(defun $jalr (label lst)
(let ((off (+ (offset label) 4)))
(emit* '(12 5 3 5 7) (bits off 11 0) (regno (car lst)) 0 (regno (car lst)) #x67)))
(defun $jr (rs1)
(emit '(3 1 5 5 2) 4 0 (regno rs1) 0 2))
(defun $lb (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 0 rd 3))))
(defun $lbu (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 4 rd 3))))
(defun $ld (rd imm lst)
(cond
((and (listp lst) (= (regno (car lst)) 2) (zerop (logand imm #xfe07)))
(emit '(3 1 5 2 3 2) 3 (bits imm 5) (regno rd) (bits imm 4 3) (bits imm 8 6) 2))
((and (listp lst) (zerop (logand imm #xff07)) (cregp (car lst)) (cregp rd))
(emit '(3 3 3 2 3 2) 3 (bits imm 5 3) (cregno (car lst)) (bits imm 7 6) (cregno rd) 0))
((listp lst)
(immed imm (car lst) 3 rd 3))))
(defun $lh (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 1 rd 3))))
(defun $lhu (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 5 rd 3))))
li pseudoinstruction - will load 32 - bit immediates
(defun $li (rd imm)
(cond
((immp imm 6)
(cimm6 rd imm 2 1))
(t (let ((imm12 (logand imm #x00000fff))
(imm20 (logand imm #xfffff000)))
(append
($lui rd (if (= (logand imm12 #x800) #x800) (+ imm20 #x1000) imm20))
(emit* '(12 5 3 5 7) imm12 (regno rd) 0 (regno rd) #x13))))))
(defun $lui (rd imm)
(cond
((zerop (logand imm #xfff))
(emit* '(20 5 7) (bits imm 31 12) (regno rd) #x37))
(t (error* "lui no good"))))
(defun $lw (rd imm lst)
(cond
((listp lst)
(let ((base (car lst)))
(cond
((and (= (regno base) 2))
(emit '(3 1 5 3 2 2) 2 (bits imm 5) (regno rd) (bits imm 4 2) (bits imm 7 6) 2))
((and (cregp rd) (cregp base))
(emit '(3 3 3 1 1 3 2) 2 (bits imm 5 3) (cregno base) (bits imm 2) (bits imm 6) (cregno rd) 0))
(t (immed imm base 2 rd 3)))))
(t (error* "Illegal 3rd arg"))))
(defun $lwu (rd imm lst)
(cond
((listp lst)
(immed imm (car lst) 6 rd 3))))
(defun $mul (rd rs1 rs2)
(muldiv rs2 rs1 0 rd #x33))
(defun $mulh (rd rs1 rs2)
(muldiv rs2 rs1 1 rd #x33))
(defun $mulhsu (rd rs1 rs2)
(muldiv rs2 rs1 2 rd #x33))
(defun $mulhu (rd rs1 rs2)
(muldiv rs2 rs1 3 rd #x33))
(defun $mulw (rd rs1 rs2)
(muldiv rs2 rs1 0 rd #x3b))
(defun $mv (rd rs1)
(emit '(3 1 5 5 2) 4 0 (regno rd) (regno rs1) 2))
(defun $nop ()
($addi 'x0 'x0 0))
(defun $or (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 2 rs2))
(t (register 0 rs2 rs1 6 rd #x33))))
(defun $ori (rd rs1 imm)
(immed imm rs1 6 rd #x13))
(defun $rem (rd rs1 rs2)
(muldiv rs2 rs1 6 rd #x33))
(defun $remu (rd rs1 rs2)
(muldiv rs2 rs1 7 rd #x33))
(defun $remw (rd rs1 rs2)
(muldiv rs2 rs1 6 rd #x3b))
(defun $remuw (rd rs1 rs2)
(muldiv rs2 rs1 7 rd #x3b))
(defun $ret ()
($jr 'ra))
(defun $sb (src imm lst)
(cond
((listp lst)
(store imm src (car lst) 0))))
(defun $sd (src imm lst)
(cond
((listp lst)
(let ((base (car lst)))
(cond
((and (= (regno base) 2) (zerop (logand imm #xfe07)))
(emit '(3 3 3 5 2) 7 (bits imm 5 3) (bits imm 8 6) (regno src) 2))
((and (cregp src) (cregp base))
(emit '(3 3 3 2 3 2) 7 (bits imm 5 3) (cregno base) (bits imm 7 6) (cregno src) 0))
(t (store imm src base 3)))))
(t (error* "Illegal 3rd arg"))))
(defun $sext.w (rd rs)
($addiw rd rs 0))
(defun $sh (src imm lst)
(cond
((listp lst)
(store imm src (car lst) 1))))
(defun $sll (rd rs1 rs2)
(register 0 rs2 rs1 1 rd #x33))
(defun $slli (rd rs1 imm)
(cond
((and (eq rd rs1))
(cimm6 rd imm 0 2))
(t (emit* '(6 6 5 3 5 7) 0 imm (regno rs1) 1 (regno rd) #x13))))
(defun $sllw (rd rs1 rs2)
(register 0 rs2 rs1 1 rd #x3b))
(defun $slt (rd rs1 rs2)
(register 0 rs2 rs1 2 rd #x33))
(defun $sra (rd rs1 rs2)
(register #x20 rs2 rs1 2 rd #x33))
(defun $srai (rd rs1 imm)
(cond
((and (eq rd rs1) (cregp rd))
(cimm6* rd imm 4 1 1))
(t (emit* '(6 6 5 3 5 7) #x10 imm (regno rs1) 5 (regno rd) #x13))))
(defun $sraw (rd rs1 rs2)
(register #x20 rs2 rs1 5 rd #x3b))
(defun $srl (rd rs1 rs2)
(register 0 rs2 rs1 5 rd #x33))
(defun $srli (rd rs1 imm)
(cond
((and (eq rd rs1) (cregp rd))
(cimm6* rd imm 4 0 1))
(t (emit* '(6 6 5 3 5 7) 0 imm (regno rs1) 5 (regno rd) #x13))))
(defun $srlw (rd rs1 rs2)
(register 0 rs2 rs1 5 rd #x3b))
(defun $sub (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 0 rs2))
(t (register #x20 rs2 rs1 0 rd #x33))))
(defun $subw (rd rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 1 3 rd 0 rs2))
(t (register #x20 rs2 rs1 0 rd #x3b))))
(defun $sw (src imm lst)
(cond
((listp lst)
(let ((base (car lst)))
(cond
((and (= (regno base) 2))
(emit '(3 4 2 5 2) 6 (bits imm 5 2) (bits imm 7 6) (regno src) 2))
((and (cregp src) (cregp base))
(emit '(3 3 3 1 1 3 2) 6 (bits imm 5 3) (cregno base) (bits imm 2) (bits imm 6) (cregno src) 0))
(t (store imm src base 2)))))
(t (error* "Illegal 3rd arg"))))
(defun $xor (rd rs1 rs2)
(cond
((and (eq rd rs1) (cregp rd) (cregp rs2))
(cregister 4 0 3 rd 1 rs2))
(t (register 0 rs2 rs1 4 rd #x33))))
(defun $xori (rd rs1 imm)
(immed imm rs1 4 rd #x13))
|
89e1a21dabb76472b4fc68f4e1b89424dcb2efddb5f212d55e8c0fa8383ac61a | nikodemus/sb-cga | ecl.lisp | By < > , 2010 .
;;;;
;;;; Permission is hereby granted, free of charge, to any person
;;;; obtaining a copy of this software and associated documentation files
( the " Software " ) , to deal in the Software without restriction ,
;;;; including without limitation the rights to use, copy, modify, merge,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
;;;; subject to the following conditions:
;;;;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
;;;; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
;;;; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;;;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
unoptimized ECL port
;;;
(in-package :sb-cga)
#-ecl
(error "This file is ecl only!")
(defun single-float-quiet-nan ()
ca n't build with literal NaNs as of 10.3.1
(declare (notinline /))
(/ 0 0f0))
(defun double-float-quiet-nan ()
(declare (notinline /))
(/ 0 0d0))
(defun float-nan-p (x)
hmm , this returns NIL for , T for floats in 9.8.3 , 10.3.1 ?
(not (sys:float-nan-p x)))
(declaim (inline cbrt))
(defun cbrt (float)
"Cube root of FLOAT."
;; todo: inline c or ffi?
(if (minusp float)
(- (expt (- float) 1/3))
(expt float 1/3)))
| null | https://raw.githubusercontent.com/nikodemus/sb-cga/8d83e4a045f6aa408c82b26dcec5b196849ec1bf/ports/ecl.lisp | lisp |
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
including without limitation the rights to use, copy, modify, merge,
subject to the following conditions:
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
todo: inline c or ffi? | By < > , 2010 .
( the " Software " ) , to deal in the Software without restriction ,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
unoptimized ECL port
(in-package :sb-cga)
#-ecl
(error "This file is ecl only!")
(defun single-float-quiet-nan ()
ca n't build with literal NaNs as of 10.3.1
(declare (notinline /))
(/ 0 0f0))
(defun double-float-quiet-nan ()
(declare (notinline /))
(/ 0 0d0))
(defun float-nan-p (x)
hmm , this returns NIL for , T for floats in 9.8.3 , 10.3.1 ?
(not (sys:float-nan-p x)))
(declaim (inline cbrt))
(defun cbrt (float)
"Cube root of FLOAT."
(if (minusp float)
(- (expt (- float) 1/3))
(expt float 1/3)))
|
bcf06fb3638f9102566e98b601ba17260121cac4fdfddf68d33ea67762fd5c21 | ddmcdonald/sparser | drugs.lisp | ;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*-
Copyright ( c ) 2014 - 2017 SIFT LLC . All Rights Reserved
;;;
;;; File: "drugs"
;;; Module: "grammar/model/sl/biology/
version : May 2017
Define drugs based on results gleaned from the cureRAS corpus with SketchEngine
;; NOTE: there are a number of mis-spelling here -- neeed to figure out how to deal with them
RJB 12/13/2014 make " drug " and " inhibitor " drugs -- not sure about this , but they are treated like that for the annotation
added a couple of new drugs 885 - A and sb590885
RJB 12/16/2014 added drugs starting with CI- and others found during that search
;; LB 5/10/2017 moved inhibitors here since they specialize drug
(in-package :sparser)
;;--- Drugs
; MAPK pathway inhibitors. MAPK pathway inhibition, MAPK inhibitors
; PLX4032 treatment
; potentiated the effects of PLX4032
following treatment with the MEK inhibitor AZD6244
retaining transcriptional response to and AZD6244
#| MOVED to non-academic-drugs
(define-category inhibitor :specializes drug
:realization (:noun "inhibitor"
:m target
:of target))
;; THIS NEEDS WORK
(define-category repressor :specializes inhibitor
:realization (:noun "repressor"))
(define-category suppressor :specializes inhibitor
:realization (:noun "suppressor"))
(noun "therapeutics" :super drug) ;; keyword: (ics N)
|#
#+ignore
(defun define-drug (drug-name)
(eval `(np-head ,drug-name :super 'drug :rule-label 'drug)))
;;(define-drug "inhibitor")
(defun define-drug (drug-name &key (synonyms nil))
(if synonyms
(def-bio/expr drug-name 'drug :takes-plurals nil :synonyms synonyms)
(def-bio/expr drug-name 'drug :takes-plurals nil)))
;; amazing name for sorafenib
;(define-drug "N -(3-trifluoromethyl-4-chlorophenyl)- N '-(4-(2-methylcarbamoyl pyridin-4-yl)oxyphenyl)urea)")
#+ccl(define-drug "fcγriib")
(define-drug "4-OHT")
(define-drug "4-hydroxytamoxifen")
(define-drug "885-A")
(define-drug "AZ3146")
;(define-drug "BAY43-9006") ;; also known as sorefenib!!
(define-drug "BKM120")
(define-drug "CI-1033")
(define-drug "CI-1040")
(define-drug "CI-994")
(define-drug "LY294002")
(define-drug "NGH.S4")
(define-drug "abciximab")
(define-drug "abl-ib")
(define-drug "activity-dasatinib")
(define-drug "adalimumab")
(define-drug "adriamycin")
;(define-drug "afatinib")
(define-drug "aib")
(define-drug "alectinib")
(define-drug "alemtuzumab")
(define-drug "alisertib")
(define-drug "alvocidib")
(define-drug "anisomycin")
(define-drug "anti-adalimumab")
(define-drug "anti-infliximab")
(define-drug "antib")
(define-drug "arhgdib")
(define-drug "arry-142886")
(define-drug "arry300")
(define-drug "arry438162")
(define-drug "arry4704")
(define-drug "arry8162")
(define-drug "augib")
(define-drug "axitinib")
(define-drug "azd0530")
(define-drug "azd0865")
(define-drug "azd1152")
(define-drug "azd2014")
(define-drug "azd2171")
(define-drug "azd2281")
(define-drug "azd4547")
(define-drug "azd5363")
(define-drug "azd6224")
(define-drug "azd6244")
(define-drug "azd6244+")
(define-drug "azd628")
(define-drug "azd6482")
(define-drug "azd64823")
(define-drug "azd7451")
(define-drug "azd8055")
(define-drug "azd8330")
(define-drug "azd8931")
(define-drug "azd9291")
(define-drug "barasertib")
(define-drug "basiliximab")
(define-drug "bay61-3606")
;(define-drug "bevacizumab")
;(define-drug "bevasizumab")
;(define-drug "bib")
(define-drug "blinatumomab")
;(define-drug "bortezomib")
(define-drug "bosutinib")
(define-drug "brentuximab")
(define-drug "brivanib")
(define-drug "brodalumab")
(define-drug "c-abl-ib")
(define-drug "cabozantinib")
(define-drug "calfizomib")
(define-drug "canertinib")
(define-drug "capecitabine")
(define-drug "carfilzomib")
(define-drug "carflizomib")
(define-drug "cediranib")
( define - drug " celecoxib " )
;(define-drug "celexoxib")
(define-drug "ceritinib")
(define-drug "certolizumab")
;(define-drug "cetuximab")
(define-drug "cixutumumab")
( define - drug " cobimetinib " )
(define-drug "crenolanib")
(define-drug "cresib")
(define-drug "crib")
(define-drug "critzotinib")
(define-drug "crizotanib")
(define-drug "crizotinib")
;(define-drug "dabrafenib")
;(define-drug "dabrafinib")
;(define-drug "dabrefenib")
;(define-drug "dacarbazine")
(define-drug "dacetuzumab")
(define-drug "dacomitinib")
(define-drug "dalotuzumab")
;(define-drug "dasatanib")
;(define-drug "dasatinib")
(define-drug "denosumab")
(define-drug "describ")
(define-drug "dib")
;(define-drug "dinaciclib")
;(define-drug "dinaclib")
;(define-drug "docetaxel")
;(define-drug "dovitinib")
(define-drug "dtic-ipilimumab")
(define-drug "e6201")
(define-drug "eculizumab")
(define-drug "efalizumab")
;(define-drug "erlotinib")
(define-drug "etaracizumab")
(define-drug "etrolizumab")
;(define-drug "everolimus")
(define-drug "ficlatuzumab")
(define-drug "figitumumab")
(define-drug "fitc-adalimumab")
(define-drug "fluvastatin-celecoxib")
(define-drug "folfiri-cetuximab")
(define-drug "folfox-plus-cetuximab")
;(define-drug "foretinib")
(define-drug "fostamatinib")
(define-drug "fresolimumab")
;(define-drug "ganetespib")
( define - drug " ganetispib " )
(define-drug "ganitumab")
(define-drug "gdc0941")
;(define-drug "gefinitib")
;(define-drug "gefitinib")
(define-drug "gefitnib")
(define-drug "gelfitinib")
(define-drug "gemtuzumab")
(define-drug "getfinib")
(define-drug "gharib")
(define-drug "gib")
(define-drug "glembatumumab")
(define-drug "golimumab")
(define-drug "gse20051")
(define-drug "gsk1059615")
(define-drug "gsk1070916")
(define-drug "gsk1070916a")
(define-drug "gsk112012")
(define-drug "gsk1120212")
(define-drug "gsk1120212b")
(define-drug "gsk1220212")
(define-drug "gsk1363089")
(define-drug "gsk2080806a")
(define-drug "gsk2091975")
(define-drug "gsk2091976")
(define-drug "gsk2110183")
(define-drug "gsk2110212")
(define-drug "gsk21118436")
(define-drug "gsk2118236")
(define-drug "gsk2118436")
(define-drug "gsk211843617")
(define-drug "gsk2118436a")
(define-drug "gsk2118438")
(define-drug "gsk2119563a")
(define-drug "gsk212")
(define-drug "gsk2126458")
(define-drug "gsk2126458*")
(define-drug "gsk2141765")
(define-drug "gsk2141795")
(define-drug "gsk2141795b")
(define-drug "gsk2366297")
(define-drug "gsk2366297a")
(define-drug "gsk2636771")
(define-drug "gsk269962a")
(define-drug "gsk3052230")
(define-drug "gsk436")
(define-drug "gsk461364")
(define-drug "gsk661637")
(define-drug "gsk690693")
(define-drug "gsk795")
(define-drug "gsk923295")
(define-drug "habib")
(define-drug "haib")
(define-drug "hib")
(define-drug "hirmab")
(define-drug "ib")
(define-drug "ibritumomab")
;(define-drug "ibrutinib")
(define-drug "icotinib")
(define-drug "ii-iiib")
(define-drug "iib")
(define-drug "iiib")
;(define-drug "imanitib")
(define-drug "in-a-fib")
(define-drug "infliximab")
(define-drug "inflixmab")
(define-drug "iniparib")
(define-drug "interferon alfacon-1" :synonyms '("interferon alfacon1"))
(define-drug "ionafarnib")
(define-drug "ionomycin")
(define-drug "ipilimumab")
(define-drug "ipilumumab")
(define-drug "irinotecan")
(define-drug "irinotecan-bevacizumab")
(define-drug "irinotecan-cetuximab")
(define-drug "ixekizumab")
(define-drug "jtp-74057")
(define-drug "khatib")
(define-drug "kit-imatinib")
(define-drug "lambrolizumab")
;(define-drug "lapatanib")
;(define-drug "lapatinib")
(define-drug "lenvantinib")
(define-drug "lenvatinib")
(define-drug "leptomycin")
(define-drug "lerdelimumab")
(define-drug "lestaurtinib")
(define-drug "levatinib")
(define-drug "lexatumumab")
(define-drug "lgib")
(define-drug "lgx818")
(define-drug "lib")
( define - drug " " )
(define-drug "lomeguatrib")
(define-drug "lonafarnib")
(define-drug "lucatumumab")
(define-drug "m-vimentib")
(define-drug "mab")
(define-drug "manual-lib")
(define-drug "mapatumumab")
;(define-drug "marizomib")
(define-drug "masitinib")
(define-drug "matuzumab")
(define-drug "mepolizumab")
(define-drug "metelimumab")
(define-drug "metmab")
(define-drug "mib")
(define-drug "mk2006")
(define-drug "mk2206")
(define-drug "motesanib")
(define-drug "moxetumomab")
(define-drug "mutalib")
(define-drug "n-desmethyl-selumetinib")
(define-drug "natalizumab")
(define-drug "necitumumab")
(define-drug "neratinib")
(define-drug "nib")
(define-drug "nilotinib")
(define-drug "nimesulide")
(define-drug "nimotuzumab")
(define-drug "nimozutumab")
(define-drug "nintedanib")
(define-drug "nivolumab")
(define-drug "nocodazole")
(define-drug "non-crizotinib")
(define-drug "non-ipilimumab")
(define-drug "nonbevacizumab")
(define-drug "nortezomib")
(define-drug "nvgib")
(define-drug "nvugib")
(define-drug "ofatumumab")
(define-drug "ogib")
;(define-drug "olaparib")
(define-drug "omalizumab")
(define-drug "onartuzumab")
(define-drug "ornatuzumab")
(define-drug "overt-ogib")
( define - drug " oxaliplatin " )
(define-drug "paclitaxel")
(define-drug "pacritinib")
;(define-drug "palbociclib")
(define-drug "panitumimab")
(define-drug "panitumumab")
;(define-drug "pazopanib")
(define-drug "pd03250901")
(define-drug "pd03259019")
(define-drug "pd0332991")
(define-drug "pd035901")
(define-drug "pd0925301")
(define-drug "pd098059")
(define-drug "pd09805937")
(define-drug "pd148352")
(define-drug "pd150606")
(define-drug "pd153035")
(define-drug "pd166326")
(define-drug "pd166866")
(define-drug "pd173074")
(define-drug "pd184352")
(define-drug "pd325901")
(define-drug "pd352901")
(define-drug "pd4283")
(define-drug "pd4289")
(define-drug "pd4292")
(define-drug "pd4301")
(define-drug "pd4301d")
(define-drug "pd5863")
(define-drug "pd5866")
(define-drug "pd5868")
(define-drug "pd5874")
(define-drug "pd5878")
(define-drug "pd5888")
(define-drug "pd5891")
(define-drug "pd901")
(define-drug "pd98059")
(define-drug "pe-mab")
(define-drug "pelitinib")
(define-drug "pertuzumab")
(define-drug "peykabl-ib")
(define-drug "pidilizumab")
(define-drug "pimasertib")
(define-drug "pioglitazone")
(define-drug "plx")
(define-drug "plx3603")
(define-drug "plx40")
(define-drug "plx4023")
(define-drug "plx4032")
(define-drug "plx40323")
(define-drug "plx40324")
(define-drug "plx470")
(define-drug "plx4720")
(define-drug "plx47200")
(define-drug "plx472013")
(define-drug "plx472018")
(define-drug "plx47206")
(define-drug "plx4723")
(define-drug "plx5568")
(define-drug "plx7486")
(define-drug "plx7904")
(define-drug "plx8394")
(define-drug "ponatinib")
(define-drug "popabl-ib")
(define-drug "post-ipilimumab")
(define-drug "post-sorafenib")
(define-drug "post-vemurafenib")
(define-drug "poziotinib")
(define-drug "pre-imatinib")
(define-drug "pre-vemurafenib")
(define-drug "quizartinib")
(define-drug "racotumomab")
(define-drug "ramcirumab")
(define-drug "ramucirumab")
;(define-drug "rapamycin")
(define-drug "ratib")
(define-drug "recentin")
(define-drug "refametinib")
;(define-drug "regorafenib")
(define-drug "reslizumab")
(define-drug "rg7204")
(define-drug "rhumab")
;(define-drug "rib")
;(define-drug "ribs")
(define-drug "rilotumumab")
(define-drug "rituxamab")
(define-drug "rituximab")
(define-drug "ro5185426")
(define-drug "ro5212054")
(define-drug "rofecoxib")
(define-drug "ruxolitinib")
(define-drug "saha")
(define-drug "salirasib")
(define-drug "saracatinib")
(define-drug "sb-202190")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-431542")
(define-drug "sb-431542")
(define-drug "sb-431542")
(define-drug "sb-431542")
(define-drug "sb-590885")
(define-drug "sb-657510")
(define-drug "sb-743921")
(define-drug "sb202190")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb431542")
(define-drug "sb431542")
(define-drug "sb431542")
(define-drug "sb590885")
(define-drug "sb657510")
(define-drug "sb743921")
(define-drug "scrib")
(define-drug "secukinumab")
(define-drug "seliciclib")
;(define-drug "selumetinib")
;(define-drug "selumitinib")
(define-drug "semaxanib")
(define-drug "semaxinib")
(define-drug "sfib")
(define-drug "shakib")
(define-drug "sib")
(define-drug "siltuximab")
;(define-drug "sorafenib")
;(define-drug "sorafinib")
( define - drug " " )
;(define-drug "sorfenib")
;(define-drug "sort-lines")
(define-drug "suni-tinib")
(define-drug "sunintib")
(define-drug "sunitib")
;(define-drug "sunitinib")
(define-drug "tandutinib")
;(define-drug "temozolomide")
(define-drug "tib")
;(define-drug "tipifarnib")
(define-drug "tivantinib")
(define-drug "tivozanib")
(define-drug "toceranib")
(define-drug "tocilizumab")
;(define-drug "tofacitinib")
(define-drug "tositumomab")
;(define-drug "trametenib")
;(define-drug "trameti-nib")
;(define-drug "trametinib")
;(define-drug "trastuzumab")
;(define-drug "trastuzumab-lapatinib")
;(define-drug "traszumab")
(define-drug "tremelimumab")
(define-drug "tremetinib")
(define-drug "trib")
(define-drug "u0126")
(define-drug "ugib")
(define-drug "urelumab")
(define-drug "ustekinumab")
(define-drug "vanctitumab")
;(define-drug "vandetanib")
(define-drug "vatalanib")
(define-drug "vedolizumab")
(define-drug "veliparib")
;(define-drug "vemurafe-nib")
;(define-drug "vemurafemib")
( define - drug " " )
;(define-drug "vemurafinib")
(define-drug "vendetanib")
;(define-drug "vermurafenib")
(define-drug "vib")
;(define-drug "vismodegib")
( define - drug " visomodegib " )
(define-drug "xl880")
(define-drug "yetrib")
(define-drug "zalutumumab")
(define-drug "zerbib")
;; overnight
;;(define-drug "nct01143753raf")
;;(define-drug "raf265")
(define-drug "GGTI")
(define-drug "Geranylgeranyl transferase 1 inhibitor")
| null | https://raw.githubusercontent.com/ddmcdonald/sparser/4bb59f0989152f059f7b008ca4bfd89501bae04c/Sparser/code/s/grammar/model/sl/biology/drugs.lisp | lisp | -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER COMMON-LISP) -*-
File: "drugs"
Module: "grammar/model/sl/biology/
NOTE: there are a number of mis-spelling here -- neeed to figure out how to deal with them
LB 5/10/2017 moved inhibitors here since they specialize drug
--- Drugs
MAPK pathway inhibitors. MAPK pathway inhibition, MAPK inhibitors
PLX4032 treatment
potentiated the effects of PLX4032
MOVED to non-academic-drugs
(define-category inhibitor :specializes drug
:realization (:noun "inhibitor"
:m target
:of target))
;; THIS NEEDS WORK
(define-category repressor :specializes inhibitor
:realization (:noun "repressor"))
(define-category suppressor :specializes inhibitor
:realization (:noun "suppressor"))
(noun "therapeutics" :super drug) ;; keyword: (ics N)
(define-drug "inhibitor")
amazing name for sorafenib
(define-drug "N -(3-trifluoromethyl-4-chlorophenyl)- N '-(4-(2-methylcarbamoyl pyridin-4-yl)oxyphenyl)urea)")
(define-drug "BAY43-9006") ;; also known as sorefenib!!
(define-drug "afatinib")
(define-drug "bevacizumab")
(define-drug "bevasizumab")
(define-drug "bib")
(define-drug "bortezomib")
(define-drug "celexoxib")
(define-drug "cetuximab")
(define-drug "dabrafenib")
(define-drug "dabrafinib")
(define-drug "dabrefenib")
(define-drug "dacarbazine")
(define-drug "dasatanib")
(define-drug "dasatinib")
(define-drug "dinaciclib")
(define-drug "dinaclib")
(define-drug "docetaxel")
(define-drug "dovitinib")
(define-drug "erlotinib")
(define-drug "everolimus")
(define-drug "foretinib")
(define-drug "ganetespib")
(define-drug "gefinitib")
(define-drug "gefitinib")
(define-drug "ibrutinib")
(define-drug "imanitib")
(define-drug "lapatanib")
(define-drug "lapatinib")
(define-drug "marizomib")
(define-drug "olaparib")
(define-drug "palbociclib")
(define-drug "pazopanib")
(define-drug "rapamycin")
(define-drug "regorafenib")
(define-drug "rib")
(define-drug "ribs")
(define-drug "selumetinib")
(define-drug "selumitinib")
(define-drug "sorafenib")
(define-drug "sorafinib")
(define-drug "sorfenib")
(define-drug "sort-lines")
(define-drug "sunitinib")
(define-drug "temozolomide")
(define-drug "tipifarnib")
(define-drug "tofacitinib")
(define-drug "trametenib")
(define-drug "trameti-nib")
(define-drug "trametinib")
(define-drug "trastuzumab")
(define-drug "trastuzumab-lapatinib")
(define-drug "traszumab")
(define-drug "vandetanib")
(define-drug "vemurafe-nib")
(define-drug "vemurafemib")
(define-drug "vemurafinib")
(define-drug "vermurafenib")
(define-drug "vismodegib")
overnight
(define-drug "nct01143753raf")
(define-drug "raf265") | Copyright ( c ) 2014 - 2017 SIFT LLC . All Rights Reserved
version : May 2017
Define drugs based on results gleaned from the cureRAS corpus with SketchEngine
RJB 12/13/2014 make " drug " and " inhibitor " drugs -- not sure about this , but they are treated like that for the annotation
added a couple of new drugs 885 - A and sb590885
RJB 12/16/2014 added drugs starting with CI- and others found during that search
(in-package :sparser)
following treatment with the MEK inhibitor AZD6244
retaining transcriptional response to and AZD6244
#+ignore
(defun define-drug (drug-name)
(eval `(np-head ,drug-name :super 'drug :rule-label 'drug)))
(defun define-drug (drug-name &key (synonyms nil))
(if synonyms
(def-bio/expr drug-name 'drug :takes-plurals nil :synonyms synonyms)
(def-bio/expr drug-name 'drug :takes-plurals nil)))
#+ccl(define-drug "fcγriib")
(define-drug "4-OHT")
(define-drug "4-hydroxytamoxifen")
(define-drug "885-A")
(define-drug "AZ3146")
(define-drug "BKM120")
(define-drug "CI-1033")
(define-drug "CI-1040")
(define-drug "CI-994")
(define-drug "LY294002")
(define-drug "NGH.S4")
(define-drug "abciximab")
(define-drug "abl-ib")
(define-drug "activity-dasatinib")
(define-drug "adalimumab")
(define-drug "adriamycin")
(define-drug "aib")
(define-drug "alectinib")
(define-drug "alemtuzumab")
(define-drug "alisertib")
(define-drug "alvocidib")
(define-drug "anisomycin")
(define-drug "anti-adalimumab")
(define-drug "anti-infliximab")
(define-drug "antib")
(define-drug "arhgdib")
(define-drug "arry-142886")
(define-drug "arry300")
(define-drug "arry438162")
(define-drug "arry4704")
(define-drug "arry8162")
(define-drug "augib")
(define-drug "axitinib")
(define-drug "azd0530")
(define-drug "azd0865")
(define-drug "azd1152")
(define-drug "azd2014")
(define-drug "azd2171")
(define-drug "azd2281")
(define-drug "azd4547")
(define-drug "azd5363")
(define-drug "azd6224")
(define-drug "azd6244")
(define-drug "azd6244+")
(define-drug "azd628")
(define-drug "azd6482")
(define-drug "azd64823")
(define-drug "azd7451")
(define-drug "azd8055")
(define-drug "azd8330")
(define-drug "azd8931")
(define-drug "azd9291")
(define-drug "barasertib")
(define-drug "basiliximab")
(define-drug "bay61-3606")
(define-drug "blinatumomab")
(define-drug "bosutinib")
(define-drug "brentuximab")
(define-drug "brivanib")
(define-drug "brodalumab")
(define-drug "c-abl-ib")
(define-drug "cabozantinib")
(define-drug "calfizomib")
(define-drug "canertinib")
(define-drug "capecitabine")
(define-drug "carfilzomib")
(define-drug "carflizomib")
(define-drug "cediranib")
( define - drug " celecoxib " )
(define-drug "ceritinib")
(define-drug "certolizumab")
(define-drug "cixutumumab")
( define - drug " cobimetinib " )
(define-drug "crenolanib")
(define-drug "cresib")
(define-drug "crib")
(define-drug "critzotinib")
(define-drug "crizotanib")
(define-drug "crizotinib")
(define-drug "dacetuzumab")
(define-drug "dacomitinib")
(define-drug "dalotuzumab")
(define-drug "denosumab")
(define-drug "describ")
(define-drug "dib")
(define-drug "dtic-ipilimumab")
(define-drug "e6201")
(define-drug "eculizumab")
(define-drug "efalizumab")
(define-drug "etaracizumab")
(define-drug "etrolizumab")
(define-drug "ficlatuzumab")
(define-drug "figitumumab")
(define-drug "fitc-adalimumab")
(define-drug "fluvastatin-celecoxib")
(define-drug "folfiri-cetuximab")
(define-drug "folfox-plus-cetuximab")
(define-drug "fostamatinib")
(define-drug "fresolimumab")
( define - drug " ganetispib " )
(define-drug "ganitumab")
(define-drug "gdc0941")
(define-drug "gefitnib")
(define-drug "gelfitinib")
(define-drug "gemtuzumab")
(define-drug "getfinib")
(define-drug "gharib")
(define-drug "gib")
(define-drug "glembatumumab")
(define-drug "golimumab")
(define-drug "gse20051")
(define-drug "gsk1059615")
(define-drug "gsk1070916")
(define-drug "gsk1070916a")
(define-drug "gsk112012")
(define-drug "gsk1120212")
(define-drug "gsk1120212b")
(define-drug "gsk1220212")
(define-drug "gsk1363089")
(define-drug "gsk2080806a")
(define-drug "gsk2091975")
(define-drug "gsk2091976")
(define-drug "gsk2110183")
(define-drug "gsk2110212")
(define-drug "gsk21118436")
(define-drug "gsk2118236")
(define-drug "gsk2118436")
(define-drug "gsk211843617")
(define-drug "gsk2118436a")
(define-drug "gsk2118438")
(define-drug "gsk2119563a")
(define-drug "gsk212")
(define-drug "gsk2126458")
(define-drug "gsk2126458*")
(define-drug "gsk2141765")
(define-drug "gsk2141795")
(define-drug "gsk2141795b")
(define-drug "gsk2366297")
(define-drug "gsk2366297a")
(define-drug "gsk2636771")
(define-drug "gsk269962a")
(define-drug "gsk3052230")
(define-drug "gsk436")
(define-drug "gsk461364")
(define-drug "gsk661637")
(define-drug "gsk690693")
(define-drug "gsk795")
(define-drug "gsk923295")
(define-drug "habib")
(define-drug "haib")
(define-drug "hib")
(define-drug "hirmab")
(define-drug "ib")
(define-drug "ibritumomab")
(define-drug "icotinib")
(define-drug "ii-iiib")
(define-drug "iib")
(define-drug "iiib")
(define-drug "in-a-fib")
(define-drug "infliximab")
(define-drug "inflixmab")
(define-drug "iniparib")
(define-drug "interferon alfacon-1" :synonyms '("interferon alfacon1"))
(define-drug "ionafarnib")
(define-drug "ionomycin")
(define-drug "ipilimumab")
(define-drug "ipilumumab")
(define-drug "irinotecan")
(define-drug "irinotecan-bevacizumab")
(define-drug "irinotecan-cetuximab")
(define-drug "ixekizumab")
(define-drug "jtp-74057")
(define-drug "khatib")
(define-drug "kit-imatinib")
(define-drug "lambrolizumab")
(define-drug "lenvantinib")
(define-drug "lenvatinib")
(define-drug "leptomycin")
(define-drug "lerdelimumab")
(define-drug "lestaurtinib")
(define-drug "levatinib")
(define-drug "lexatumumab")
(define-drug "lgib")
(define-drug "lgx818")
(define-drug "lib")
( define - drug " " )
(define-drug "lomeguatrib")
(define-drug "lonafarnib")
(define-drug "lucatumumab")
(define-drug "m-vimentib")
(define-drug "mab")
(define-drug "manual-lib")
(define-drug "mapatumumab")
(define-drug "masitinib")
(define-drug "matuzumab")
(define-drug "mepolizumab")
(define-drug "metelimumab")
(define-drug "metmab")
(define-drug "mib")
(define-drug "mk2006")
(define-drug "mk2206")
(define-drug "motesanib")
(define-drug "moxetumomab")
(define-drug "mutalib")
(define-drug "n-desmethyl-selumetinib")
(define-drug "natalizumab")
(define-drug "necitumumab")
(define-drug "neratinib")
(define-drug "nib")
(define-drug "nilotinib")
(define-drug "nimesulide")
(define-drug "nimotuzumab")
(define-drug "nimozutumab")
(define-drug "nintedanib")
(define-drug "nivolumab")
(define-drug "nocodazole")
(define-drug "non-crizotinib")
(define-drug "non-ipilimumab")
(define-drug "nonbevacizumab")
(define-drug "nortezomib")
(define-drug "nvgib")
(define-drug "nvugib")
(define-drug "ofatumumab")
(define-drug "ogib")
(define-drug "omalizumab")
(define-drug "onartuzumab")
(define-drug "ornatuzumab")
(define-drug "overt-ogib")
( define - drug " oxaliplatin " )
(define-drug "paclitaxel")
(define-drug "pacritinib")
(define-drug "panitumimab")
(define-drug "panitumumab")
(define-drug "pd03250901")
(define-drug "pd03259019")
(define-drug "pd0332991")
(define-drug "pd035901")
(define-drug "pd0925301")
(define-drug "pd098059")
(define-drug "pd09805937")
(define-drug "pd148352")
(define-drug "pd150606")
(define-drug "pd153035")
(define-drug "pd166326")
(define-drug "pd166866")
(define-drug "pd173074")
(define-drug "pd184352")
(define-drug "pd325901")
(define-drug "pd352901")
(define-drug "pd4283")
(define-drug "pd4289")
(define-drug "pd4292")
(define-drug "pd4301")
(define-drug "pd4301d")
(define-drug "pd5863")
(define-drug "pd5866")
(define-drug "pd5868")
(define-drug "pd5874")
(define-drug "pd5878")
(define-drug "pd5888")
(define-drug "pd5891")
(define-drug "pd901")
(define-drug "pd98059")
(define-drug "pe-mab")
(define-drug "pelitinib")
(define-drug "pertuzumab")
(define-drug "peykabl-ib")
(define-drug "pidilizumab")
(define-drug "pimasertib")
(define-drug "pioglitazone")
(define-drug "plx")
(define-drug "plx3603")
(define-drug "plx40")
(define-drug "plx4023")
(define-drug "plx4032")
(define-drug "plx40323")
(define-drug "plx40324")
(define-drug "plx470")
(define-drug "plx4720")
(define-drug "plx47200")
(define-drug "plx472013")
(define-drug "plx472018")
(define-drug "plx47206")
(define-drug "plx4723")
(define-drug "plx5568")
(define-drug "plx7486")
(define-drug "plx7904")
(define-drug "plx8394")
(define-drug "ponatinib")
(define-drug "popabl-ib")
(define-drug "post-ipilimumab")
(define-drug "post-sorafenib")
(define-drug "post-vemurafenib")
(define-drug "poziotinib")
(define-drug "pre-imatinib")
(define-drug "pre-vemurafenib")
(define-drug "quizartinib")
(define-drug "racotumomab")
(define-drug "ramcirumab")
(define-drug "ramucirumab")
(define-drug "ratib")
(define-drug "recentin")
(define-drug "refametinib")
(define-drug "reslizumab")
(define-drug "rg7204")
(define-drug "rhumab")
(define-drug "rilotumumab")
(define-drug "rituxamab")
(define-drug "rituximab")
(define-drug "ro5185426")
(define-drug "ro5212054")
(define-drug "rofecoxib")
(define-drug "ruxolitinib")
(define-drug "saha")
(define-drug "salirasib")
(define-drug "saracatinib")
(define-drug "sb-202190")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-203580")
(define-drug "sb-431542")
(define-drug "sb-431542")
(define-drug "sb-431542")
(define-drug "sb-431542")
(define-drug "sb-590885")
(define-drug "sb-657510")
(define-drug "sb-743921")
(define-drug "sb202190")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb203580")
(define-drug "sb431542")
(define-drug "sb431542")
(define-drug "sb431542")
(define-drug "sb590885")
(define-drug "sb657510")
(define-drug "sb743921")
(define-drug "scrib")
(define-drug "secukinumab")
(define-drug "seliciclib")
(define-drug "semaxanib")
(define-drug "semaxinib")
(define-drug "sfib")
(define-drug "shakib")
(define-drug "sib")
(define-drug "siltuximab")
( define - drug " " )
(define-drug "suni-tinib")
(define-drug "sunintib")
(define-drug "sunitib")
(define-drug "tandutinib")
(define-drug "tib")
(define-drug "tivantinib")
(define-drug "tivozanib")
(define-drug "toceranib")
(define-drug "tocilizumab")
(define-drug "tositumomab")
(define-drug "tremelimumab")
(define-drug "tremetinib")
(define-drug "trib")
(define-drug "u0126")
(define-drug "ugib")
(define-drug "urelumab")
(define-drug "ustekinumab")
(define-drug "vanctitumab")
(define-drug "vatalanib")
(define-drug "vedolizumab")
(define-drug "veliparib")
( define - drug " " )
(define-drug "vendetanib")
(define-drug "vib")
( define - drug " visomodegib " )
(define-drug "xl880")
(define-drug "yetrib")
(define-drug "zalutumumab")
(define-drug "zerbib")
(define-drug "GGTI")
(define-drug "Geranylgeranyl transferase 1 inhibitor")
|
e693e04ef6ca050866ad96693f540a4f5cd240196f75a9c73a90352d29a079f7 | walmartlabs/schematic | lang.clj | Copyright ( c ) 2017 - present , Walmart Inc.
;;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; -2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns ^:no-doc com.walmartlabs.schematic.lang
"Internal utilities used by Schematic.")
(defn map-vals
"Maps f over every value in the hash-map mm and returns a new
hash-map. E.g (map-vals inc {:a 1 :b 2}) => {:a 2 :b 3}"
[f mm]
(->> mm
(reduce-kv (fn [output k v]
(assoc! output
k (f v)))
(transient {}))
persistent!))
(defn deep-merge
"Like merge, but merges maps recursively."
[& maps]
(if (every? (some-fn nil? map?) maps)
(apply merge-with deep-merge maps)
(last maps)))
(defn mapify-seq
"For a seq input, returns a map of each entry mapped to itself.
If a map is provided, it is returned unchanged.
(mapify-seq [1 2])
=> {1 1 2 2}"
[coll]
(if (sequential? coll)
(zipmap coll coll)
coll))
| null | https://raw.githubusercontent.com/walmartlabs/schematic/9d2eb16eb3550f06d3030b3b0ff9d519b803f88a/src/com/walmartlabs/schematic/lang.clj | clojure |
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. | Copyright ( c ) 2017 - present , Walmart Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
(ns ^:no-doc com.walmartlabs.schematic.lang
"Internal utilities used by Schematic.")
(defn map-vals
"Maps f over every value in the hash-map mm and returns a new
hash-map. E.g (map-vals inc {:a 1 :b 2}) => {:a 2 :b 3}"
[f mm]
(->> mm
(reduce-kv (fn [output k v]
(assoc! output
k (f v)))
(transient {}))
persistent!))
(defn deep-merge
"Like merge, but merges maps recursively."
[& maps]
(if (every? (some-fn nil? map?) maps)
(apply merge-with deep-merge maps)
(last maps)))
(defn mapify-seq
"For a seq input, returns a map of each entry mapped to itself.
If a map is provided, it is returned unchanged.
(mapify-seq [1 2])
=> {1 1 2 2}"
[coll]
(if (sequential? coll)
(zipmap coll coll)
coll))
|
64595231b300b49b805e31de673f1092333b2f815a602791e39c4a5d6e520eef | janestreet/merlin-jst | ast_iterator.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, LexiFi
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
A generic Parsetree mapping class
[ @@@ocaml.warning " +9 " ]
( * Ensure that record patterns do n't miss any field .
[@@@ocaml.warning "+9"]
(* Ensure that record patterns don't miss any field. *)
*)
open Parsetree
open Location
type iterator = {
attribute: iterator -> attribute -> unit;
attributes: iterator -> attribute list -> unit;
binding_op: iterator -> binding_op -> unit;
case: iterator -> case -> unit;
cases: iterator -> case list -> unit;
class_declaration: iterator -> class_declaration -> unit;
class_description: iterator -> class_description -> unit;
class_expr: iterator -> class_expr -> unit;
class_field: iterator -> class_field -> unit;
class_signature: iterator -> class_signature -> unit;
class_structure: iterator -> class_structure -> unit;
class_type: iterator -> class_type -> unit;
class_type_declaration: iterator -> class_type_declaration -> unit;
class_type_field: iterator -> class_type_field -> unit;
constructor_declaration: iterator -> constructor_declaration -> unit;
expr: iterator -> expression -> unit;
extension: iterator -> extension -> unit;
extension_constructor: iterator -> extension_constructor -> unit;
include_declaration: iterator -> include_declaration -> unit;
include_description: iterator -> include_description -> unit;
label_declaration: iterator -> label_declaration -> unit;
location: iterator -> Location.t -> unit;
module_binding: iterator -> module_binding -> unit;
module_declaration: iterator -> module_declaration -> unit;
module_substitution: iterator -> module_substitution -> unit;
module_expr: iterator -> module_expr -> unit;
module_type: iterator -> module_type -> unit;
module_type_declaration: iterator -> module_type_declaration -> unit;
open_declaration: iterator -> open_declaration -> unit;
open_description: iterator -> open_description -> unit;
pat: iterator -> pattern -> unit;
payload: iterator -> payload -> unit;
signature: iterator -> signature -> unit;
signature_item: iterator -> signature_item -> unit;
structure: iterator -> structure -> unit;
structure_item: iterator -> structure_item -> unit;
typ: iterator -> core_type -> unit;
row_field: iterator -> row_field -> unit;
object_field: iterator -> object_field -> unit;
type_declaration: iterator -> type_declaration -> unit;
type_extension: iterator -> type_extension -> unit;
type_exception: iterator -> type_exception -> unit;
type_kind: iterator -> type_kind -> unit;
value_binding: iterator -> value_binding -> unit;
value_description: iterator -> value_description -> unit;
with_constraint: iterator -> with_constraint -> unit;
}
* A [ iterator ] record implements one " method " per syntactic category ,
using an open recursion style : each method takes as its first
argument the iterator to be applied to children in the syntax
tree .
using an open recursion style: each method takes as its first
argument the iterator to be applied to children in the syntax
tree. *)
let iter_fst f (x, _) = f x
let iter_snd f (_, y) = f y
let iter_tuple f1 f2 (x, y) = f1 x; f2 y
let iter_tuple3 f1 f2 f3 (x, y, z) = f1 x; f2 y; f3 z
let iter_opt f = function None -> () | Some x -> f x
let iter_loc sub {loc; txt = _} = sub.location sub loc
module T = struct
(* Type expressions for the core language *)
let row_field sub {
prf_desc;
prf_loc;
prf_attributes;
} =
sub.location sub prf_loc;
sub.attributes sub prf_attributes;
match prf_desc with
| Rtag (_, _, tl) -> List.iter (sub.typ sub) tl
| Rinherit t -> sub.typ sub t
let object_field sub {
pof_desc;
pof_loc;
pof_attributes;
} =
sub.location sub pof_loc;
sub.attributes sub pof_attributes;
match pof_desc with
| Otag (_, t) -> sub.typ sub t
| Oinherit t -> sub.typ sub t
let iter sub {ptyp_desc = desc; ptyp_loc = loc; ptyp_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Ptyp_any
| Ptyp_var _ -> ()
| Ptyp_arrow (_lab, t1, t2) ->
sub.typ sub t1; sub.typ sub t2
| Ptyp_tuple tyl -> List.iter (sub.typ sub) tyl
| Ptyp_constr (lid, tl) ->
iter_loc sub lid; List.iter (sub.typ sub) tl
| Ptyp_object (ol, _o) ->
List.iter (object_field sub) ol
| Ptyp_class (lid, tl) ->
iter_loc sub lid; List.iter (sub.typ sub) tl
| Ptyp_alias (t, _) -> sub.typ sub t
| Ptyp_variant (rl, _b, _ll) ->
List.iter (row_field sub) rl
| Ptyp_poly (_, t) -> sub.typ sub t
| Ptyp_package (lid, l) ->
iter_loc sub lid;
List.iter (iter_tuple (iter_loc sub) (sub.typ sub)) l
| Ptyp_extension x -> sub.extension sub x
let iter_type_declaration sub
{ptype_name; ptype_params; ptype_cstrs;
ptype_kind;
ptype_private = _;
ptype_manifest;
ptype_attributes;
ptype_loc} =
iter_loc sub ptype_name;
List.iter (iter_fst (sub.typ sub)) ptype_params;
List.iter
(iter_tuple3 (sub.typ sub) (sub.typ sub) (sub.location sub))
ptype_cstrs;
sub.type_kind sub ptype_kind;
iter_opt (sub.typ sub) ptype_manifest;
sub.location sub ptype_loc;
sub.attributes sub ptype_attributes
let iter_type_kind sub = function
| Ptype_abstract -> ()
| Ptype_variant l ->
List.iter (sub.constructor_declaration sub) l
| Ptype_record l -> List.iter (sub.label_declaration sub) l
| Ptype_open -> ()
let iter_constructor_arguments sub = function
| Pcstr_tuple l -> List.iter (sub.typ sub) l
| Pcstr_record l ->
List.iter (sub.label_declaration sub) l
let iter_type_extension sub
{ptyext_path; ptyext_params;
ptyext_constructors;
ptyext_private = _;
ptyext_loc;
ptyext_attributes} =
iter_loc sub ptyext_path;
List.iter (sub.extension_constructor sub) ptyext_constructors;
List.iter (iter_fst (sub.typ sub)) ptyext_params;
sub.location sub ptyext_loc;
sub.attributes sub ptyext_attributes
let iter_type_exception sub
{ptyexn_constructor; ptyexn_loc; ptyexn_attributes} =
sub.extension_constructor sub ptyexn_constructor;
sub.location sub ptyexn_loc;
sub.attributes sub ptyexn_attributes
let iter_extension_constructor_kind sub = function
Pext_decl(ctl, cto) ->
iter_constructor_arguments sub ctl; iter_opt (sub.typ sub) cto
| Pext_rebind li ->
iter_loc sub li
let iter_extension_constructor sub
{pext_name;
pext_kind;
pext_loc;
pext_attributes} =
iter_loc sub pext_name;
iter_extension_constructor_kind sub pext_kind;
sub.location sub pext_loc;
sub.attributes sub pext_attributes
end
module CT = struct
(* Type expressions for the class language *)
let iter sub {pcty_loc = loc; pcty_desc = desc; pcty_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pcty_constr (lid, tys) ->
iter_loc sub lid; List.iter (sub.typ sub) tys
| Pcty_signature x -> sub.class_signature sub x
| Pcty_arrow (_lab, t, ct) ->
sub.typ sub t; sub.class_type sub ct
| Pcty_extension x -> sub.extension sub x
| Pcty_open (o, e) ->
sub.open_description sub o; sub.class_type sub e
let iter_field sub {pctf_desc = desc; pctf_loc = loc; pctf_attributes = attrs}
=
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pctf_inherit ct -> sub.class_type sub ct
| Pctf_val (_s, _m, _v, t) -> sub.typ sub t
| Pctf_method (_s, _p, _v, t) -> sub.typ sub t
| Pctf_constraint (t1, t2) ->
sub.typ sub t1; sub.typ sub t2
| Pctf_attribute x -> sub.attribute sub x
| Pctf_extension x -> sub.extension sub x
let iter_signature sub {pcsig_self; pcsig_fields} =
sub.typ sub pcsig_self;
List.iter (sub.class_type_field sub) pcsig_fields
end
let iter_functor_param sub = function
| Unit -> ()
| Named (name, mty) ->
iter_loc sub name;
sub.module_type sub mty
module MT = struct
(* Type expressions for the module language *)
let iter sub {pmty_desc = desc; pmty_loc = loc; pmty_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pmty_ident s -> iter_loc sub s
| Pmty_alias s -> iter_loc sub s
| Pmty_signature sg -> sub.signature sub sg
| Pmty_functor (param, mt2) ->
iter_functor_param sub param;
sub.module_type sub mt2
| Pmty_with (mt, l) ->
sub.module_type sub mt;
List.iter (sub.with_constraint sub) l
| Pmty_typeof me -> sub.module_expr sub me
| Pmty_extension x -> sub.extension sub x
let iter_with_constraint sub = function
| Pwith_type (lid, d) ->
iter_loc sub lid; sub.type_declaration sub d
| Pwith_module (lid, lid2) ->
iter_loc sub lid; iter_loc sub lid2
| Pwith_modtype (lid, mty) ->
iter_loc sub lid; sub.module_type sub mty
| Pwith_typesubst (lid, d) ->
iter_loc sub lid; sub.type_declaration sub d
| Pwith_modsubst (s, lid) ->
iter_loc sub s; iter_loc sub lid
| Pwith_modtypesubst (lid, mty) ->
iter_loc sub lid; sub.module_type sub mty
let iter_signature_item sub {psig_desc = desc; psig_loc = loc} =
sub.location sub loc;
match desc with
| Psig_value vd -> sub.value_description sub vd
| Psig_type (_, l)
| Psig_typesubst l ->
List.iter (sub.type_declaration sub) l
| Psig_typext te -> sub.type_extension sub te
| Psig_exception ed -> sub.type_exception sub ed
| Psig_module x -> sub.module_declaration sub x
| Psig_modsubst x -> sub.module_substitution sub x
| Psig_recmodule l ->
List.iter (sub.module_declaration sub) l
| Psig_modtype x | Psig_modtypesubst x -> sub.module_type_declaration sub x
| Psig_open x -> sub.open_description sub x
| Psig_include x -> sub.include_description sub x
| Psig_class l -> List.iter (sub.class_description sub) l
| Psig_class_type l ->
List.iter (sub.class_type_declaration sub) l
| Psig_extension (x, attrs) ->
sub.attributes sub attrs;
sub.extension sub x
| Psig_attribute x -> sub.attribute sub x
end
module M = struct
(* Value expressions for the module language *)
let iter sub {pmod_loc = loc; pmod_desc = desc; pmod_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pmod_ident x -> iter_loc sub x
| Pmod_structure str -> sub.structure sub str
| Pmod_functor (param, body) ->
iter_functor_param sub param;
sub.module_expr sub body
| Pmod_apply (m1, m2) ->
sub.module_expr sub m1; sub.module_expr sub m2
| Pmod_constraint (m, mty) ->
sub.module_expr sub m; sub.module_type sub mty
| Pmod_unpack e -> sub.expr sub e
| Pmod_extension x -> sub.extension sub x
let iter_structure_item sub {pstr_loc = loc; pstr_desc = desc} =
sub.location sub loc;
match desc with
| Pstr_eval (x, attrs) ->
sub.attributes sub attrs; sub.expr sub x
| Pstr_value (_r, vbs) -> List.iter (sub.value_binding sub) vbs
| Pstr_primitive vd -> sub.value_description sub vd
| Pstr_type (_rf, l) -> List.iter (sub.type_declaration sub) l
| Pstr_typext te -> sub.type_extension sub te
| Pstr_exception ed -> sub.type_exception sub ed
| Pstr_module x -> sub.module_binding sub x
| Pstr_recmodule l -> List.iter (sub.module_binding sub) l
| Pstr_modtype x -> sub.module_type_declaration sub x
| Pstr_open x -> sub.open_declaration sub x
| Pstr_class l -> List.iter (sub.class_declaration sub) l
| Pstr_class_type l ->
List.iter (sub.class_type_declaration sub) l
| Pstr_include x -> sub.include_declaration sub x
| Pstr_extension (x, attrs) ->
sub.attributes sub attrs; sub.extension sub x
| Pstr_attribute x -> sub.attribute sub x
end
module E = struct
(* Value expressions for the core language *)
let iter sub {pexp_loc = loc; pexp_desc = desc; pexp_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pexp_ident x -> iter_loc sub x
| Pexp_constant _ -> ()
| Pexp_let (_r, vbs, e) ->
List.iter (sub.value_binding sub) vbs;
sub.expr sub e
| Pexp_fun (_lab, def, p, e) ->
iter_opt (sub.expr sub) def;
sub.pat sub p;
sub.expr sub e
| Pexp_function pel -> sub.cases sub pel
| Pexp_apply (e, l) ->
sub.expr sub e; List.iter (iter_snd (sub.expr sub)) l
| Pexp_match (e, pel) ->
sub.expr sub e; sub.cases sub pel
| Pexp_try (e, pel) -> sub.expr sub e; sub.cases sub pel
| Pexp_tuple el -> List.iter (sub.expr sub) el
| Pexp_construct (lid, arg) ->
iter_loc sub lid; iter_opt (sub.expr sub) arg
| Pexp_variant (_lab, eo) ->
iter_opt (sub.expr sub) eo
| Pexp_record (l, eo) ->
List.iter (iter_tuple (iter_loc sub) (sub.expr sub)) l;
iter_opt (sub.expr sub) eo
| Pexp_field (e, lid) ->
sub.expr sub e; iter_loc sub lid
| Pexp_setfield (e1, lid, e2) ->
sub.expr sub e1; iter_loc sub lid;
sub.expr sub e2
| Pexp_array el -> List.iter (sub.expr sub) el
| Pexp_ifthenelse (e1, e2, e3) ->
sub.expr sub e1; sub.expr sub e2;
iter_opt (sub.expr sub) e3
| Pexp_sequence (e1, e2) ->
sub.expr sub e1; sub.expr sub e2
| Pexp_while (e1, e2) ->
sub.expr sub e1; sub.expr sub e2
| Pexp_for (p, e1, e2, _d, e3) ->
sub.pat sub p; sub.expr sub e1; sub.expr sub e2;
sub.expr sub e3
| Pexp_coerce (e, t1, t2) ->
sub.expr sub e; iter_opt (sub.typ sub) t1;
sub.typ sub t2
| Pexp_constraint (e, t) ->
sub.expr sub e; sub.typ sub t
| Pexp_send (e, _s) -> sub.expr sub e
| Pexp_new lid -> iter_loc sub lid
| Pexp_setinstvar (s, e) ->
iter_loc sub s; sub.expr sub e
| Pexp_override sel ->
List.iter (iter_tuple (iter_loc sub) (sub.expr sub)) sel
| Pexp_letmodule (s, me, e) ->
iter_loc sub s; sub.module_expr sub me;
sub.expr sub e
| Pexp_letexception (cd, e) ->
sub.extension_constructor sub cd;
sub.expr sub e
| Pexp_assert e -> sub.expr sub e
| Pexp_lazy e -> sub.expr sub e
| Pexp_poly (e, t) ->
sub.expr sub e; iter_opt (sub.typ sub) t
| Pexp_object cls -> sub.class_structure sub cls
| Pexp_newtype (_s, e) -> sub.expr sub e
| Pexp_pack me -> sub.module_expr sub me
| Pexp_open (o, e) ->
sub.open_declaration sub o; sub.expr sub e
| Pexp_letop {let_; ands; body} ->
sub.binding_op sub let_;
List.iter (sub.binding_op sub) ands;
sub.expr sub body
| Pexp_extension x -> sub.extension sub x
| Pexp_unreachable -> ()
let iter_binding_op sub {pbop_op; pbop_pat; pbop_exp; pbop_loc} =
iter_loc sub pbop_op;
sub.pat sub pbop_pat;
sub.expr sub pbop_exp;
sub.location sub pbop_loc
end
module P = struct
(* Patterns *)
let iter sub {ppat_desc = desc; ppat_loc = loc; ppat_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Ppat_any -> ()
| Ppat_var s -> iter_loc sub s
| Ppat_alias (p, s) -> sub.pat sub p; iter_loc sub s
| Ppat_constant _ -> ()
| Ppat_interval _ -> ()
| Ppat_tuple pl -> List.iter (sub.pat sub) pl
| Ppat_construct (l, p) ->
iter_loc sub l;
iter_opt
(fun (vl,p) ->
List.iter (iter_loc sub) vl;
sub.pat sub p)
p
| Ppat_variant (_l, p) -> iter_opt (sub.pat sub) p
| Ppat_record (lpl, _cf) ->
List.iter (iter_tuple (iter_loc sub) (sub.pat sub)) lpl
| Ppat_array pl -> List.iter (sub.pat sub) pl
| Ppat_or (p1, p2) -> sub.pat sub p1; sub.pat sub p2
| Ppat_constraint (p, t) ->
sub.pat sub p; sub.typ sub t
| Ppat_type s -> iter_loc sub s
| Ppat_lazy p -> sub.pat sub p
| Ppat_unpack s -> iter_loc sub s
| Ppat_exception p -> sub.pat sub p
| Ppat_extension x -> sub.extension sub x
| Ppat_open (lid, p) ->
iter_loc sub lid; sub.pat sub p
end
module CE = struct
(* Value expressions for the class language *)
let iter sub {pcl_loc = loc; pcl_desc = desc; pcl_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pcl_constr (lid, tys) ->
iter_loc sub lid; List.iter (sub.typ sub) tys
| Pcl_structure s ->
sub.class_structure sub s
| Pcl_fun (_lab, e, p, ce) ->
iter_opt (sub.expr sub) e;
sub.pat sub p;
sub.class_expr sub ce
| Pcl_apply (ce, l) ->
sub.class_expr sub ce;
List.iter (iter_snd (sub.expr sub)) l
| Pcl_let (_r, vbs, ce) ->
List.iter (sub.value_binding sub) vbs;
sub.class_expr sub ce
| Pcl_constraint (ce, ct) ->
sub.class_expr sub ce; sub.class_type sub ct
| Pcl_extension x -> sub.extension sub x
| Pcl_open (o, e) ->
sub.open_description sub o; sub.class_expr sub e
let iter_kind sub = function
| Cfk_concrete (_o, e) -> sub.expr sub e
| Cfk_virtual t -> sub.typ sub t
let iter_field sub {pcf_desc = desc; pcf_loc = loc; pcf_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pcf_inherit (_o, ce, _s) -> sub.class_expr sub ce
| Pcf_val (s, _m, k) -> iter_loc sub s; iter_kind sub k
| Pcf_method (s, _p, k) ->
iter_loc sub s; iter_kind sub k
| Pcf_constraint (t1, t2) ->
sub.typ sub t1; sub.typ sub t2
| Pcf_initializer e -> sub.expr sub e
| Pcf_attribute x -> sub.attribute sub x
| Pcf_extension x -> sub.extension sub x
let iter_structure sub {pcstr_self; pcstr_fields} =
sub.pat sub pcstr_self;
List.iter (sub.class_field sub) pcstr_fields
let class_infos sub f {pci_virt = _; pci_params = pl; pci_name; pci_expr;
pci_loc; pci_attributes} =
List.iter (iter_fst (sub.typ sub)) pl;
iter_loc sub pci_name;
f pci_expr;
sub.location sub pci_loc;
sub.attributes sub pci_attributes
end
Now , a generic AST mapper , to be extended to cover all kinds and
cases of the OCaml grammar . The default behavior of the mapper is
the identity .
cases of the OCaml grammar. The default behavior of the mapper is
the identity. *)
let default_iterator =
{
structure = (fun this l -> List.iter (this.structure_item this) l);
structure_item = M.iter_structure_item;
module_expr = M.iter;
signature = (fun this l -> List.iter (this.signature_item this) l);
signature_item = MT.iter_signature_item;
module_type = MT.iter;
with_constraint = MT.iter_with_constraint;
class_declaration =
(fun this -> CE.class_infos this (this.class_expr this));
class_expr = CE.iter;
class_field = CE.iter_field;
class_structure = CE.iter_structure;
class_type = CT.iter;
class_type_field = CT.iter_field;
class_signature = CT.iter_signature;
class_type_declaration =
(fun this -> CE.class_infos this (this.class_type this));
class_description =
(fun this -> CE.class_infos this (this.class_type this));
type_declaration = T.iter_type_declaration;
type_kind = T.iter_type_kind;
typ = T.iter;
row_field = T.row_field;
object_field = T.object_field;
type_extension = T.iter_type_extension;
type_exception = T.iter_type_exception;
extension_constructor = T.iter_extension_constructor;
value_description =
(fun this {pval_name; pval_type; pval_prim = _; pval_loc;
pval_attributes} ->
iter_loc this pval_name;
this.typ this pval_type;
this.location this pval_loc;
this.attributes this pval_attributes;
);
pat = P.iter;
expr = E.iter;
binding_op = E.iter_binding_op;
module_declaration =
(fun this {pmd_name; pmd_type; pmd_attributes; pmd_loc} ->
iter_loc this pmd_name;
this.module_type this pmd_type;
this.location this pmd_loc;
this.attributes this pmd_attributes;
);
module_substitution =
(fun this {pms_name; pms_manifest; pms_attributes; pms_loc} ->
iter_loc this pms_name;
iter_loc this pms_manifest;
this.location this pms_loc;
this.attributes this pms_attributes;
);
module_type_declaration =
(fun this {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} ->
iter_loc this pmtd_name;
iter_opt (this.module_type this) pmtd_type;
this.location this pmtd_loc;
this.attributes this pmtd_attributes;
);
module_binding =
(fun this {pmb_name; pmb_expr; pmb_attributes; pmb_loc} ->
iter_loc this pmb_name; this.module_expr this pmb_expr;
this.location this pmb_loc;
this.attributes this pmb_attributes;
);
open_declaration =
(fun this {popen_expr; popen_override = _; popen_attributes; popen_loc} ->
this.module_expr this popen_expr;
this.location this popen_loc;
this.attributes this popen_attributes
);
open_description =
(fun this {popen_expr; popen_override = _; popen_attributes; popen_loc} ->
iter_loc this popen_expr;
this.location this popen_loc;
this.attributes this popen_attributes
);
include_description =
(fun this {pincl_mod; pincl_attributes; pincl_loc} ->
this.module_type this pincl_mod;
this.location this pincl_loc;
this.attributes this pincl_attributes
);
include_declaration =
(fun this {pincl_mod; pincl_attributes; pincl_loc} ->
this.module_expr this pincl_mod;
this.location this pincl_loc;
this.attributes this pincl_attributes
);
value_binding =
(fun this {pvb_pat; pvb_expr; pvb_attributes; pvb_loc} ->
this.pat this pvb_pat;
this.expr this pvb_expr;
this.location this pvb_loc;
this.attributes this pvb_attributes
);
constructor_declaration =
(fun this {pcd_name; pcd_args; pcd_res; pcd_loc; pcd_attributes} ->
iter_loc this pcd_name;
T.iter_constructor_arguments this pcd_args;
iter_opt (this.typ this) pcd_res;
this.location this pcd_loc;
this.attributes this pcd_attributes
);
label_declaration =
(fun this {pld_name; pld_type; pld_loc; pld_mutable = _; pld_attributes}->
iter_loc this pld_name;
this.typ this pld_type;
this.location this pld_loc;
this.attributes this pld_attributes
);
cases = (fun this l -> List.iter (this.case this) l);
case =
(fun this {pc_lhs; pc_guard; pc_rhs} ->
this.pat this pc_lhs;
iter_opt (this.expr this) pc_guard;
this.expr this pc_rhs
);
location = (fun _this _l -> ());
extension = (fun this (s, e) -> iter_loc this s; this.payload this e);
attribute = (fun this a ->
iter_loc this a.attr_name;
this.payload this a.attr_payload;
this.location this a.attr_loc
);
attributes = (fun this l -> List.iter (this.attribute this) l);
payload =
(fun this -> function
| PStr x -> this.structure this x
| PSig x -> this.signature this x
| PTyp x -> this.typ this x
| PPat (x, g) -> this.pat this x; iter_opt (this.expr this) g
);
}
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/upstream/ocaml_413/parsing/ast_iterator.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Ensure that record patterns don't miss any field.
Type expressions for the core language
Type expressions for the class language
Type expressions for the module language
Value expressions for the module language
Value expressions for the core language
Patterns
Value expressions for the class language | , LexiFi
Copyright 2012 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
A generic Parsetree mapping class
[ @@@ocaml.warning " +9 " ]
( * Ensure that record patterns do n't miss any field .
[@@@ocaml.warning "+9"]
*)
open Parsetree
open Location
type iterator = {
attribute: iterator -> attribute -> unit;
attributes: iterator -> attribute list -> unit;
binding_op: iterator -> binding_op -> unit;
case: iterator -> case -> unit;
cases: iterator -> case list -> unit;
class_declaration: iterator -> class_declaration -> unit;
class_description: iterator -> class_description -> unit;
class_expr: iterator -> class_expr -> unit;
class_field: iterator -> class_field -> unit;
class_signature: iterator -> class_signature -> unit;
class_structure: iterator -> class_structure -> unit;
class_type: iterator -> class_type -> unit;
class_type_declaration: iterator -> class_type_declaration -> unit;
class_type_field: iterator -> class_type_field -> unit;
constructor_declaration: iterator -> constructor_declaration -> unit;
expr: iterator -> expression -> unit;
extension: iterator -> extension -> unit;
extension_constructor: iterator -> extension_constructor -> unit;
include_declaration: iterator -> include_declaration -> unit;
include_description: iterator -> include_description -> unit;
label_declaration: iterator -> label_declaration -> unit;
location: iterator -> Location.t -> unit;
module_binding: iterator -> module_binding -> unit;
module_declaration: iterator -> module_declaration -> unit;
module_substitution: iterator -> module_substitution -> unit;
module_expr: iterator -> module_expr -> unit;
module_type: iterator -> module_type -> unit;
module_type_declaration: iterator -> module_type_declaration -> unit;
open_declaration: iterator -> open_declaration -> unit;
open_description: iterator -> open_description -> unit;
pat: iterator -> pattern -> unit;
payload: iterator -> payload -> unit;
signature: iterator -> signature -> unit;
signature_item: iterator -> signature_item -> unit;
structure: iterator -> structure -> unit;
structure_item: iterator -> structure_item -> unit;
typ: iterator -> core_type -> unit;
row_field: iterator -> row_field -> unit;
object_field: iterator -> object_field -> unit;
type_declaration: iterator -> type_declaration -> unit;
type_extension: iterator -> type_extension -> unit;
type_exception: iterator -> type_exception -> unit;
type_kind: iterator -> type_kind -> unit;
value_binding: iterator -> value_binding -> unit;
value_description: iterator -> value_description -> unit;
with_constraint: iterator -> with_constraint -> unit;
}
* A [ iterator ] record implements one " method " per syntactic category ,
using an open recursion style : each method takes as its first
argument the iterator to be applied to children in the syntax
tree .
using an open recursion style: each method takes as its first
argument the iterator to be applied to children in the syntax
tree. *)
let iter_fst f (x, _) = f x
let iter_snd f (_, y) = f y
let iter_tuple f1 f2 (x, y) = f1 x; f2 y
let iter_tuple3 f1 f2 f3 (x, y, z) = f1 x; f2 y; f3 z
let iter_opt f = function None -> () | Some x -> f x
let iter_loc sub {loc; txt = _} = sub.location sub loc
module T = struct
let row_field sub {
prf_desc;
prf_loc;
prf_attributes;
} =
sub.location sub prf_loc;
sub.attributes sub prf_attributes;
match prf_desc with
| Rtag (_, _, tl) -> List.iter (sub.typ sub) tl
| Rinherit t -> sub.typ sub t
let object_field sub {
pof_desc;
pof_loc;
pof_attributes;
} =
sub.location sub pof_loc;
sub.attributes sub pof_attributes;
match pof_desc with
| Otag (_, t) -> sub.typ sub t
| Oinherit t -> sub.typ sub t
let iter sub {ptyp_desc = desc; ptyp_loc = loc; ptyp_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Ptyp_any
| Ptyp_var _ -> ()
| Ptyp_arrow (_lab, t1, t2) ->
sub.typ sub t1; sub.typ sub t2
| Ptyp_tuple tyl -> List.iter (sub.typ sub) tyl
| Ptyp_constr (lid, tl) ->
iter_loc sub lid; List.iter (sub.typ sub) tl
| Ptyp_object (ol, _o) ->
List.iter (object_field sub) ol
| Ptyp_class (lid, tl) ->
iter_loc sub lid; List.iter (sub.typ sub) tl
| Ptyp_alias (t, _) -> sub.typ sub t
| Ptyp_variant (rl, _b, _ll) ->
List.iter (row_field sub) rl
| Ptyp_poly (_, t) -> sub.typ sub t
| Ptyp_package (lid, l) ->
iter_loc sub lid;
List.iter (iter_tuple (iter_loc sub) (sub.typ sub)) l
| Ptyp_extension x -> sub.extension sub x
let iter_type_declaration sub
{ptype_name; ptype_params; ptype_cstrs;
ptype_kind;
ptype_private = _;
ptype_manifest;
ptype_attributes;
ptype_loc} =
iter_loc sub ptype_name;
List.iter (iter_fst (sub.typ sub)) ptype_params;
List.iter
(iter_tuple3 (sub.typ sub) (sub.typ sub) (sub.location sub))
ptype_cstrs;
sub.type_kind sub ptype_kind;
iter_opt (sub.typ sub) ptype_manifest;
sub.location sub ptype_loc;
sub.attributes sub ptype_attributes
let iter_type_kind sub = function
| Ptype_abstract -> ()
| Ptype_variant l ->
List.iter (sub.constructor_declaration sub) l
| Ptype_record l -> List.iter (sub.label_declaration sub) l
| Ptype_open -> ()
let iter_constructor_arguments sub = function
| Pcstr_tuple l -> List.iter (sub.typ sub) l
| Pcstr_record l ->
List.iter (sub.label_declaration sub) l
let iter_type_extension sub
{ptyext_path; ptyext_params;
ptyext_constructors;
ptyext_private = _;
ptyext_loc;
ptyext_attributes} =
iter_loc sub ptyext_path;
List.iter (sub.extension_constructor sub) ptyext_constructors;
List.iter (iter_fst (sub.typ sub)) ptyext_params;
sub.location sub ptyext_loc;
sub.attributes sub ptyext_attributes
let iter_type_exception sub
{ptyexn_constructor; ptyexn_loc; ptyexn_attributes} =
sub.extension_constructor sub ptyexn_constructor;
sub.location sub ptyexn_loc;
sub.attributes sub ptyexn_attributes
let iter_extension_constructor_kind sub = function
Pext_decl(ctl, cto) ->
iter_constructor_arguments sub ctl; iter_opt (sub.typ sub) cto
| Pext_rebind li ->
iter_loc sub li
let iter_extension_constructor sub
{pext_name;
pext_kind;
pext_loc;
pext_attributes} =
iter_loc sub pext_name;
iter_extension_constructor_kind sub pext_kind;
sub.location sub pext_loc;
sub.attributes sub pext_attributes
end
module CT = struct
let iter sub {pcty_loc = loc; pcty_desc = desc; pcty_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pcty_constr (lid, tys) ->
iter_loc sub lid; List.iter (sub.typ sub) tys
| Pcty_signature x -> sub.class_signature sub x
| Pcty_arrow (_lab, t, ct) ->
sub.typ sub t; sub.class_type sub ct
| Pcty_extension x -> sub.extension sub x
| Pcty_open (o, e) ->
sub.open_description sub o; sub.class_type sub e
let iter_field sub {pctf_desc = desc; pctf_loc = loc; pctf_attributes = attrs}
=
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pctf_inherit ct -> sub.class_type sub ct
| Pctf_val (_s, _m, _v, t) -> sub.typ sub t
| Pctf_method (_s, _p, _v, t) -> sub.typ sub t
| Pctf_constraint (t1, t2) ->
sub.typ sub t1; sub.typ sub t2
| Pctf_attribute x -> sub.attribute sub x
| Pctf_extension x -> sub.extension sub x
let iter_signature sub {pcsig_self; pcsig_fields} =
sub.typ sub pcsig_self;
List.iter (sub.class_type_field sub) pcsig_fields
end
let iter_functor_param sub = function
| Unit -> ()
| Named (name, mty) ->
iter_loc sub name;
sub.module_type sub mty
module MT = struct
let iter sub {pmty_desc = desc; pmty_loc = loc; pmty_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pmty_ident s -> iter_loc sub s
| Pmty_alias s -> iter_loc sub s
| Pmty_signature sg -> sub.signature sub sg
| Pmty_functor (param, mt2) ->
iter_functor_param sub param;
sub.module_type sub mt2
| Pmty_with (mt, l) ->
sub.module_type sub mt;
List.iter (sub.with_constraint sub) l
| Pmty_typeof me -> sub.module_expr sub me
| Pmty_extension x -> sub.extension sub x
let iter_with_constraint sub = function
| Pwith_type (lid, d) ->
iter_loc sub lid; sub.type_declaration sub d
| Pwith_module (lid, lid2) ->
iter_loc sub lid; iter_loc sub lid2
| Pwith_modtype (lid, mty) ->
iter_loc sub lid; sub.module_type sub mty
| Pwith_typesubst (lid, d) ->
iter_loc sub lid; sub.type_declaration sub d
| Pwith_modsubst (s, lid) ->
iter_loc sub s; iter_loc sub lid
| Pwith_modtypesubst (lid, mty) ->
iter_loc sub lid; sub.module_type sub mty
let iter_signature_item sub {psig_desc = desc; psig_loc = loc} =
sub.location sub loc;
match desc with
| Psig_value vd -> sub.value_description sub vd
| Psig_type (_, l)
| Psig_typesubst l ->
List.iter (sub.type_declaration sub) l
| Psig_typext te -> sub.type_extension sub te
| Psig_exception ed -> sub.type_exception sub ed
| Psig_module x -> sub.module_declaration sub x
| Psig_modsubst x -> sub.module_substitution sub x
| Psig_recmodule l ->
List.iter (sub.module_declaration sub) l
| Psig_modtype x | Psig_modtypesubst x -> sub.module_type_declaration sub x
| Psig_open x -> sub.open_description sub x
| Psig_include x -> sub.include_description sub x
| Psig_class l -> List.iter (sub.class_description sub) l
| Psig_class_type l ->
List.iter (sub.class_type_declaration sub) l
| Psig_extension (x, attrs) ->
sub.attributes sub attrs;
sub.extension sub x
| Psig_attribute x -> sub.attribute sub x
end
module M = struct
let iter sub {pmod_loc = loc; pmod_desc = desc; pmod_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pmod_ident x -> iter_loc sub x
| Pmod_structure str -> sub.structure sub str
| Pmod_functor (param, body) ->
iter_functor_param sub param;
sub.module_expr sub body
| Pmod_apply (m1, m2) ->
sub.module_expr sub m1; sub.module_expr sub m2
| Pmod_constraint (m, mty) ->
sub.module_expr sub m; sub.module_type sub mty
| Pmod_unpack e -> sub.expr sub e
| Pmod_extension x -> sub.extension sub x
let iter_structure_item sub {pstr_loc = loc; pstr_desc = desc} =
sub.location sub loc;
match desc with
| Pstr_eval (x, attrs) ->
sub.attributes sub attrs; sub.expr sub x
| Pstr_value (_r, vbs) -> List.iter (sub.value_binding sub) vbs
| Pstr_primitive vd -> sub.value_description sub vd
| Pstr_type (_rf, l) -> List.iter (sub.type_declaration sub) l
| Pstr_typext te -> sub.type_extension sub te
| Pstr_exception ed -> sub.type_exception sub ed
| Pstr_module x -> sub.module_binding sub x
| Pstr_recmodule l -> List.iter (sub.module_binding sub) l
| Pstr_modtype x -> sub.module_type_declaration sub x
| Pstr_open x -> sub.open_declaration sub x
| Pstr_class l -> List.iter (sub.class_declaration sub) l
| Pstr_class_type l ->
List.iter (sub.class_type_declaration sub) l
| Pstr_include x -> sub.include_declaration sub x
| Pstr_extension (x, attrs) ->
sub.attributes sub attrs; sub.extension sub x
| Pstr_attribute x -> sub.attribute sub x
end
module E = struct
let iter sub {pexp_loc = loc; pexp_desc = desc; pexp_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pexp_ident x -> iter_loc sub x
| Pexp_constant _ -> ()
| Pexp_let (_r, vbs, e) ->
List.iter (sub.value_binding sub) vbs;
sub.expr sub e
| Pexp_fun (_lab, def, p, e) ->
iter_opt (sub.expr sub) def;
sub.pat sub p;
sub.expr sub e
| Pexp_function pel -> sub.cases sub pel
| Pexp_apply (e, l) ->
sub.expr sub e; List.iter (iter_snd (sub.expr sub)) l
| Pexp_match (e, pel) ->
sub.expr sub e; sub.cases sub pel
| Pexp_try (e, pel) -> sub.expr sub e; sub.cases sub pel
| Pexp_tuple el -> List.iter (sub.expr sub) el
| Pexp_construct (lid, arg) ->
iter_loc sub lid; iter_opt (sub.expr sub) arg
| Pexp_variant (_lab, eo) ->
iter_opt (sub.expr sub) eo
| Pexp_record (l, eo) ->
List.iter (iter_tuple (iter_loc sub) (sub.expr sub)) l;
iter_opt (sub.expr sub) eo
| Pexp_field (e, lid) ->
sub.expr sub e; iter_loc sub lid
| Pexp_setfield (e1, lid, e2) ->
sub.expr sub e1; iter_loc sub lid;
sub.expr sub e2
| Pexp_array el -> List.iter (sub.expr sub) el
| Pexp_ifthenelse (e1, e2, e3) ->
sub.expr sub e1; sub.expr sub e2;
iter_opt (sub.expr sub) e3
| Pexp_sequence (e1, e2) ->
sub.expr sub e1; sub.expr sub e2
| Pexp_while (e1, e2) ->
sub.expr sub e1; sub.expr sub e2
| Pexp_for (p, e1, e2, _d, e3) ->
sub.pat sub p; sub.expr sub e1; sub.expr sub e2;
sub.expr sub e3
| Pexp_coerce (e, t1, t2) ->
sub.expr sub e; iter_opt (sub.typ sub) t1;
sub.typ sub t2
| Pexp_constraint (e, t) ->
sub.expr sub e; sub.typ sub t
| Pexp_send (e, _s) -> sub.expr sub e
| Pexp_new lid -> iter_loc sub lid
| Pexp_setinstvar (s, e) ->
iter_loc sub s; sub.expr sub e
| Pexp_override sel ->
List.iter (iter_tuple (iter_loc sub) (sub.expr sub)) sel
| Pexp_letmodule (s, me, e) ->
iter_loc sub s; sub.module_expr sub me;
sub.expr sub e
| Pexp_letexception (cd, e) ->
sub.extension_constructor sub cd;
sub.expr sub e
| Pexp_assert e -> sub.expr sub e
| Pexp_lazy e -> sub.expr sub e
| Pexp_poly (e, t) ->
sub.expr sub e; iter_opt (sub.typ sub) t
| Pexp_object cls -> sub.class_structure sub cls
| Pexp_newtype (_s, e) -> sub.expr sub e
| Pexp_pack me -> sub.module_expr sub me
| Pexp_open (o, e) ->
sub.open_declaration sub o; sub.expr sub e
| Pexp_letop {let_; ands; body} ->
sub.binding_op sub let_;
List.iter (sub.binding_op sub) ands;
sub.expr sub body
| Pexp_extension x -> sub.extension sub x
| Pexp_unreachable -> ()
let iter_binding_op sub {pbop_op; pbop_pat; pbop_exp; pbop_loc} =
iter_loc sub pbop_op;
sub.pat sub pbop_pat;
sub.expr sub pbop_exp;
sub.location sub pbop_loc
end
module P = struct
let iter sub {ppat_desc = desc; ppat_loc = loc; ppat_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Ppat_any -> ()
| Ppat_var s -> iter_loc sub s
| Ppat_alias (p, s) -> sub.pat sub p; iter_loc sub s
| Ppat_constant _ -> ()
| Ppat_interval _ -> ()
| Ppat_tuple pl -> List.iter (sub.pat sub) pl
| Ppat_construct (l, p) ->
iter_loc sub l;
iter_opt
(fun (vl,p) ->
List.iter (iter_loc sub) vl;
sub.pat sub p)
p
| Ppat_variant (_l, p) -> iter_opt (sub.pat sub) p
| Ppat_record (lpl, _cf) ->
List.iter (iter_tuple (iter_loc sub) (sub.pat sub)) lpl
| Ppat_array pl -> List.iter (sub.pat sub) pl
| Ppat_or (p1, p2) -> sub.pat sub p1; sub.pat sub p2
| Ppat_constraint (p, t) ->
sub.pat sub p; sub.typ sub t
| Ppat_type s -> iter_loc sub s
| Ppat_lazy p -> sub.pat sub p
| Ppat_unpack s -> iter_loc sub s
| Ppat_exception p -> sub.pat sub p
| Ppat_extension x -> sub.extension sub x
| Ppat_open (lid, p) ->
iter_loc sub lid; sub.pat sub p
end
module CE = struct
let iter sub {pcl_loc = loc; pcl_desc = desc; pcl_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pcl_constr (lid, tys) ->
iter_loc sub lid; List.iter (sub.typ sub) tys
| Pcl_structure s ->
sub.class_structure sub s
| Pcl_fun (_lab, e, p, ce) ->
iter_opt (sub.expr sub) e;
sub.pat sub p;
sub.class_expr sub ce
| Pcl_apply (ce, l) ->
sub.class_expr sub ce;
List.iter (iter_snd (sub.expr sub)) l
| Pcl_let (_r, vbs, ce) ->
List.iter (sub.value_binding sub) vbs;
sub.class_expr sub ce
| Pcl_constraint (ce, ct) ->
sub.class_expr sub ce; sub.class_type sub ct
| Pcl_extension x -> sub.extension sub x
| Pcl_open (o, e) ->
sub.open_description sub o; sub.class_expr sub e
let iter_kind sub = function
| Cfk_concrete (_o, e) -> sub.expr sub e
| Cfk_virtual t -> sub.typ sub t
let iter_field sub {pcf_desc = desc; pcf_loc = loc; pcf_attributes = attrs} =
sub.location sub loc;
sub.attributes sub attrs;
match desc with
| Pcf_inherit (_o, ce, _s) -> sub.class_expr sub ce
| Pcf_val (s, _m, k) -> iter_loc sub s; iter_kind sub k
| Pcf_method (s, _p, k) ->
iter_loc sub s; iter_kind sub k
| Pcf_constraint (t1, t2) ->
sub.typ sub t1; sub.typ sub t2
| Pcf_initializer e -> sub.expr sub e
| Pcf_attribute x -> sub.attribute sub x
| Pcf_extension x -> sub.extension sub x
let iter_structure sub {pcstr_self; pcstr_fields} =
sub.pat sub pcstr_self;
List.iter (sub.class_field sub) pcstr_fields
let class_infos sub f {pci_virt = _; pci_params = pl; pci_name; pci_expr;
pci_loc; pci_attributes} =
List.iter (iter_fst (sub.typ sub)) pl;
iter_loc sub pci_name;
f pci_expr;
sub.location sub pci_loc;
sub.attributes sub pci_attributes
end
Now , a generic AST mapper , to be extended to cover all kinds and
cases of the OCaml grammar . The default behavior of the mapper is
the identity .
cases of the OCaml grammar. The default behavior of the mapper is
the identity. *)
let default_iterator =
{
structure = (fun this l -> List.iter (this.structure_item this) l);
structure_item = M.iter_structure_item;
module_expr = M.iter;
signature = (fun this l -> List.iter (this.signature_item this) l);
signature_item = MT.iter_signature_item;
module_type = MT.iter;
with_constraint = MT.iter_with_constraint;
class_declaration =
(fun this -> CE.class_infos this (this.class_expr this));
class_expr = CE.iter;
class_field = CE.iter_field;
class_structure = CE.iter_structure;
class_type = CT.iter;
class_type_field = CT.iter_field;
class_signature = CT.iter_signature;
class_type_declaration =
(fun this -> CE.class_infos this (this.class_type this));
class_description =
(fun this -> CE.class_infos this (this.class_type this));
type_declaration = T.iter_type_declaration;
type_kind = T.iter_type_kind;
typ = T.iter;
row_field = T.row_field;
object_field = T.object_field;
type_extension = T.iter_type_extension;
type_exception = T.iter_type_exception;
extension_constructor = T.iter_extension_constructor;
value_description =
(fun this {pval_name; pval_type; pval_prim = _; pval_loc;
pval_attributes} ->
iter_loc this pval_name;
this.typ this pval_type;
this.location this pval_loc;
this.attributes this pval_attributes;
);
pat = P.iter;
expr = E.iter;
binding_op = E.iter_binding_op;
module_declaration =
(fun this {pmd_name; pmd_type; pmd_attributes; pmd_loc} ->
iter_loc this pmd_name;
this.module_type this pmd_type;
this.location this pmd_loc;
this.attributes this pmd_attributes;
);
module_substitution =
(fun this {pms_name; pms_manifest; pms_attributes; pms_loc} ->
iter_loc this pms_name;
iter_loc this pms_manifest;
this.location this pms_loc;
this.attributes this pms_attributes;
);
module_type_declaration =
(fun this {pmtd_name; pmtd_type; pmtd_attributes; pmtd_loc} ->
iter_loc this pmtd_name;
iter_opt (this.module_type this) pmtd_type;
this.location this pmtd_loc;
this.attributes this pmtd_attributes;
);
module_binding =
(fun this {pmb_name; pmb_expr; pmb_attributes; pmb_loc} ->
iter_loc this pmb_name; this.module_expr this pmb_expr;
this.location this pmb_loc;
this.attributes this pmb_attributes;
);
open_declaration =
(fun this {popen_expr; popen_override = _; popen_attributes; popen_loc} ->
this.module_expr this popen_expr;
this.location this popen_loc;
this.attributes this popen_attributes
);
open_description =
(fun this {popen_expr; popen_override = _; popen_attributes; popen_loc} ->
iter_loc this popen_expr;
this.location this popen_loc;
this.attributes this popen_attributes
);
include_description =
(fun this {pincl_mod; pincl_attributes; pincl_loc} ->
this.module_type this pincl_mod;
this.location this pincl_loc;
this.attributes this pincl_attributes
);
include_declaration =
(fun this {pincl_mod; pincl_attributes; pincl_loc} ->
this.module_expr this pincl_mod;
this.location this pincl_loc;
this.attributes this pincl_attributes
);
value_binding =
(fun this {pvb_pat; pvb_expr; pvb_attributes; pvb_loc} ->
this.pat this pvb_pat;
this.expr this pvb_expr;
this.location this pvb_loc;
this.attributes this pvb_attributes
);
constructor_declaration =
(fun this {pcd_name; pcd_args; pcd_res; pcd_loc; pcd_attributes} ->
iter_loc this pcd_name;
T.iter_constructor_arguments this pcd_args;
iter_opt (this.typ this) pcd_res;
this.location this pcd_loc;
this.attributes this pcd_attributes
);
label_declaration =
(fun this {pld_name; pld_type; pld_loc; pld_mutable = _; pld_attributes}->
iter_loc this pld_name;
this.typ this pld_type;
this.location this pld_loc;
this.attributes this pld_attributes
);
cases = (fun this l -> List.iter (this.case this) l);
case =
(fun this {pc_lhs; pc_guard; pc_rhs} ->
this.pat this pc_lhs;
iter_opt (this.expr this) pc_guard;
this.expr this pc_rhs
);
location = (fun _this _l -> ());
extension = (fun this (s, e) -> iter_loc this s; this.payload this e);
attribute = (fun this a ->
iter_loc this a.attr_name;
this.payload this a.attr_payload;
this.location this a.attr_loc
);
attributes = (fun this l -> List.iter (this.attribute this) l);
payload =
(fun this -> function
| PStr x -> this.structure this x
| PSig x -> this.signature this x
| PTyp x -> this.typ this x
| PPat (x, g) -> this.pat this x; iter_opt (this.expr this) g
);
}
|
c1a4beacf1c3dd797bb254928129d3b8390812bd530d62cb8b954d973703716e | agrafix/openai-hs | ApiSpec.hs | module ApiSpec (apiSpec) where
import qualified Data.Text as T
import qualified Data.Vector as V
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import OpenAI.Client
import System.Environment (getEnv)
import Test.Hspec
makeClient :: IO OpenAIClient
makeClient =
do
manager <- newManager tlsManagerSettings
apiKey <- T.pack <$> getEnv "OPENAI_KEY"
pure (makeOpenAIClient apiKey manager 2)
forceSuccess :: (MonadFail m, Show a) => m (Either a b) -> m b
forceSuccess req =
req >>= \res ->
case res of
Left err -> fail (show err)
Right ok -> pure ok
apiSpec :: Spec
apiSpec =
describe "core api" apiTests
apiTests :: SpecWith ()
apiTests =
beforeAll makeClient $
do
describe "file api" $
do
it "allows creating one" $ \cli ->
do
let file =
FileCreate
{ fcPurpose = "search",
fcDocuments = [FhSearch $ SearchHunk "Test 1" Nothing, FhSearch $ SearchHunk "text 2" (Just "foo")]
}
_ <- forceSuccess $ createFile cli file
pure ()
describe "answer api" $
do
it "works" $ \cli ->
do
let file =
FileCreate
{ fcPurpose = "search",
fcDocuments =
[ FhSearch $ SearchHunk "Cities in California: San Francisco, Los Angeles" (Just "cali"),
FhSearch $ SearchHunk "Tasty fruit: Apple, Orange" (Just "fruit"),
FhSearch $ SearchHunk "Cities in Germany: Freiburg, Berlin" (Just "germany")
]
}
res <- forceSuccess $ createFile cli file
let searchReq =
AnswerReq
{ arFile = Just (fId res),
arDocuments = Nothing,
arQuestion = "Where is San Francisco?",
arSearchModel = EngineId "babbage",
arModel = EngineId "davinci",
arExamplesContext = "Good programming languages: Haskell, PureScript",
arExamples = [["Is PHP a good programming language?", "No, sorry."]],
arReturnMetadata = True
}
answerRes <- forceSuccess $ getAnswer cli searchReq
T.unpack (head (arsAnswers answerRes)) `shouldContain` ("California" :: String)
pure ()
describe "embeddings" $ do
it "computes embeddings" $ \cli -> do
res <- forceSuccess $ createEmbedding cli (EngineId "babbage-similarity") (EmbeddingCreate "This is nice")
V.null (olData res) `shouldBe` False
let embedding = V.head (olData res)
V.length (eEmbedding embedding) `shouldBe` 2048
describe "fine tuning" $ do
it "allows creating fine-tuning" $ \cli -> do
let file =
FileCreate
{ fcPurpose = "fine-tune",
fcDocuments =
[ FhFineTune $ FineTuneHunk "So sad. Label:" "sad",
FhFineTune $ FineTuneHunk "So happy. Label:" "happy"
]
}
createRes <- forceSuccess $ createFile cli file
let ftc = defaultFineTuneCreate (fId createRes)
res <- forceSuccess $ createFineTune cli ftc
ftStatus res `shouldBe` "pending"
describe "engines" $
do
it "lists engines" $ \cli ->
do
res <- forceSuccess $ listEngines cli
V.null (olData res) `shouldBe` False
it "retrieve engine" $ \cli ->
do
engineList <- forceSuccess $ listEngines cli
let firstEngine = V.head (olData engineList)
engine <- forceSuccess $ getEngine cli (eId firstEngine)
engine `shouldBe` firstEngine
describe "text completion" $
do
it "works (smoke test)" $ \cli ->
do
firstEngine <- V.head . olData <$> forceSuccess (listEngines cli)
completionResults <-
forceSuccess $
completeText cli (eId firstEngine) $
(defaultTextCompletionCreate "Why is the house ")
{ tccrMaxTokens = Just 2
}
V.length (tcChoices completionResults) `shouldBe` 1
T.length (tccText (V.head (tcChoices completionResults))) `shouldNotBe` 0
describe "document search" $
do
it "works (smoke test)" $ \cli ->
do
firstEngine <- V.head . olData <$> forceSuccess (listEngines cli)
searchResults <-
forceSuccess $
searchDocuments cli (eId firstEngine) $
SearchResultCreate
{ sccrDocuments = Just $ V.fromList ["pool", "gym", "night club"],
sccrFile = Nothing,
sccrQuery = "swimmer",
sccrReturnMetadata = False
}
V.length (olData searchResults) `shouldBe` 3
describe "file based document search" $
do
it "works" $ \cli ->
do
let file =
FileCreate
{ fcPurpose = "search",
fcDocuments =
[ FhSearch $ SearchHunk "pool" (Just "pool"),
FhSearch $ SearchHunk "gym" (Just "gym"),
FhSearch $ SearchHunk "night club" (Just "nc")
]
}
createRes <- forceSuccess $ createFile cli file
let searchReq =
SearchResultCreate
{ sccrFile = Just (fId createRes),
sccrDocuments = Nothing,
sccrQuery = "pool",
sccrReturnMetadata = True
}
searchRes <- forceSuccess $ searchDocuments cli (EngineId "ada") searchReq
let res = V.head (olData searchRes)
srDocument res `shouldBe` 0 -- pool
srMetadata res `shouldBe` Just "pool"
pure ()
| null | https://raw.githubusercontent.com/agrafix/openai-hs/e4be98ddedf2d566623826bb1c5d45bba1869571/openai-hs/test/ApiSpec.hs | haskell | pool | module ApiSpec (apiSpec) where
import qualified Data.Text as T
import qualified Data.Vector as V
import Network.HTTP.Client
import Network.HTTP.Client.TLS
import OpenAI.Client
import System.Environment (getEnv)
import Test.Hspec
makeClient :: IO OpenAIClient
makeClient =
do
manager <- newManager tlsManagerSettings
apiKey <- T.pack <$> getEnv "OPENAI_KEY"
pure (makeOpenAIClient apiKey manager 2)
forceSuccess :: (MonadFail m, Show a) => m (Either a b) -> m b
forceSuccess req =
req >>= \res ->
case res of
Left err -> fail (show err)
Right ok -> pure ok
apiSpec :: Spec
apiSpec =
describe "core api" apiTests
apiTests :: SpecWith ()
apiTests =
beforeAll makeClient $
do
describe "file api" $
do
it "allows creating one" $ \cli ->
do
let file =
FileCreate
{ fcPurpose = "search",
fcDocuments = [FhSearch $ SearchHunk "Test 1" Nothing, FhSearch $ SearchHunk "text 2" (Just "foo")]
}
_ <- forceSuccess $ createFile cli file
pure ()
describe "answer api" $
do
it "works" $ \cli ->
do
let file =
FileCreate
{ fcPurpose = "search",
fcDocuments =
[ FhSearch $ SearchHunk "Cities in California: San Francisco, Los Angeles" (Just "cali"),
FhSearch $ SearchHunk "Tasty fruit: Apple, Orange" (Just "fruit"),
FhSearch $ SearchHunk "Cities in Germany: Freiburg, Berlin" (Just "germany")
]
}
res <- forceSuccess $ createFile cli file
let searchReq =
AnswerReq
{ arFile = Just (fId res),
arDocuments = Nothing,
arQuestion = "Where is San Francisco?",
arSearchModel = EngineId "babbage",
arModel = EngineId "davinci",
arExamplesContext = "Good programming languages: Haskell, PureScript",
arExamples = [["Is PHP a good programming language?", "No, sorry."]],
arReturnMetadata = True
}
answerRes <- forceSuccess $ getAnswer cli searchReq
T.unpack (head (arsAnswers answerRes)) `shouldContain` ("California" :: String)
pure ()
describe "embeddings" $ do
it "computes embeddings" $ \cli -> do
res <- forceSuccess $ createEmbedding cli (EngineId "babbage-similarity") (EmbeddingCreate "This is nice")
V.null (olData res) `shouldBe` False
let embedding = V.head (olData res)
V.length (eEmbedding embedding) `shouldBe` 2048
describe "fine tuning" $ do
it "allows creating fine-tuning" $ \cli -> do
let file =
FileCreate
{ fcPurpose = "fine-tune",
fcDocuments =
[ FhFineTune $ FineTuneHunk "So sad. Label:" "sad",
FhFineTune $ FineTuneHunk "So happy. Label:" "happy"
]
}
createRes <- forceSuccess $ createFile cli file
let ftc = defaultFineTuneCreate (fId createRes)
res <- forceSuccess $ createFineTune cli ftc
ftStatus res `shouldBe` "pending"
describe "engines" $
do
it "lists engines" $ \cli ->
do
res <- forceSuccess $ listEngines cli
V.null (olData res) `shouldBe` False
it "retrieve engine" $ \cli ->
do
engineList <- forceSuccess $ listEngines cli
let firstEngine = V.head (olData engineList)
engine <- forceSuccess $ getEngine cli (eId firstEngine)
engine `shouldBe` firstEngine
describe "text completion" $
do
it "works (smoke test)" $ \cli ->
do
firstEngine <- V.head . olData <$> forceSuccess (listEngines cli)
completionResults <-
forceSuccess $
completeText cli (eId firstEngine) $
(defaultTextCompletionCreate "Why is the house ")
{ tccrMaxTokens = Just 2
}
V.length (tcChoices completionResults) `shouldBe` 1
T.length (tccText (V.head (tcChoices completionResults))) `shouldNotBe` 0
describe "document search" $
do
it "works (smoke test)" $ \cli ->
do
firstEngine <- V.head . olData <$> forceSuccess (listEngines cli)
searchResults <-
forceSuccess $
searchDocuments cli (eId firstEngine) $
SearchResultCreate
{ sccrDocuments = Just $ V.fromList ["pool", "gym", "night club"],
sccrFile = Nothing,
sccrQuery = "swimmer",
sccrReturnMetadata = False
}
V.length (olData searchResults) `shouldBe` 3
describe "file based document search" $
do
it "works" $ \cli ->
do
let file =
FileCreate
{ fcPurpose = "search",
fcDocuments =
[ FhSearch $ SearchHunk "pool" (Just "pool"),
FhSearch $ SearchHunk "gym" (Just "gym"),
FhSearch $ SearchHunk "night club" (Just "nc")
]
}
createRes <- forceSuccess $ createFile cli file
let searchReq =
SearchResultCreate
{ sccrFile = Just (fId createRes),
sccrDocuments = Nothing,
sccrQuery = "pool",
sccrReturnMetadata = True
}
searchRes <- forceSuccess $ searchDocuments cli (EngineId "ada") searchReq
let res = V.head (olData searchRes)
srMetadata res `shouldBe` Just "pool"
pure ()
|
7d856ffe4beae84d3dcd81df2030d65504c446653ff5f664541831fbc411fa6e | erlang/otp | erl_scan.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2022 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
Erlang token scanning functions of io library .
%% For handling ISO 8859-1 (Latin-1) we use the following type
%% information:
%%
000 - 037 NUL - US control
040 - 057 SPC - / punctuation
060 - 071 0 - 9 digit
072 - 100 : - @ punctuation
101 - 132 A - Z uppercase
133 - 140 [ - ` punctuation
141 - 172 a - z lowercase
173 - 176 { - ~ punctuation
177 DEL control
200 - 237 control
240 - 277 NBSP - ¿ punctuation
300 - 326 À - Ö uppercase
327 × punctuation
330 - 336 Ø - Þ uppercase
337 - 366 ß - ö lowercase
367 ÷ punctuation
370 - 377 ø - ÿ lowercase
%%
%% Many punctuation characters have special meaning:
%% $\s, $_, $", $$, $%, $', $.
DEL is a punctuation .
%%
%% Must watch using × \327, very close to x \170.
-module(erl_scan).
%%% External exports
-export([string/1,string/2,string/3,tokens/3,tokens/4,
format_error/1,reserved_word/1,
f_reserved_word/1]).
-export([column/1,end_location/1,line/1,location/1,text/1,
category/1,symbol/1]).
%%% Private
-export([continuation_location/1]).
-export_type([error_info/0,
options/0,
return_cont/0,
token/0, tokens/0,
tokens_result/0]).
%% Removed functions and types
-removed([{set_attribute,3,"use erl_anno:set_line/2 instead"},
{attributes_info,'_',
"use erl_anno:{column,line,location,text}/1 instead"},
{token_info,'_',
"use erl_scan:{category,column,line,location,symbol,text}/1 instead"}]).
-removed_type([{column,0,"use erl_anno:column() instead"},
{line,0,"use erl_anno:line() instead"},
{location,0,"use erl_anno:location() instead"}]).
%%%
%%% Defines and type definitions
%%%
-define(COLUMN(C), (is_integer(C) andalso C >= 1)).
Line numbers less than zero have always been allowed :
-define(ALINE(L), is_integer(L)).
-define(STRING(S), is_list(S)).
-define(RESWORDFUN(F), is_function(F, 1)).
-type category() :: atom().
-type resword_fun() :: fun((atom()) -> boolean()).
-type text_fun() :: fun((atom(), string()) -> boolean()).
-type option() :: 'return' | 'return_white_spaces' | 'return_comments'
| 'text' | {'reserved_word_fun', resword_fun()}
| {'text_fun', text_fun()} | {'compiler_internal', [term()]}.
-type options() :: option() | [option()].
-type symbol() :: atom() | float() | integer() | string().
-type token() :: {category(), Anno :: erl_anno:anno(), symbol()}
| {category(), Anno :: erl_anno:anno()}.
-type tokens() :: [token()].
-type error_description() :: term().
-type error_info() :: {erl_anno:location(), module(), error_description()}.
%%% Local record.
-record(erl_scan,
{resword_fun = fun reserved_word/1 :: resword_fun(),
text_fun = fun(_, _) -> false end :: text_fun(),
ws = false :: boolean(),
comment = false :: boolean(),
has_fun = false :: boolean(),
%% True if requested to parse %ssa%-check comments
checks = false :: boolean(),
%% True if we're scanning inside a %ssa%-check comment
in_check = false :: boolean()}).
%%----------------------------------------------------------------------------
-spec format_error(ErrorDescriptor) -> string() when
ErrorDescriptor :: error_description().
format_error({string,Quote,Head}) ->
lists:flatten(["unterminated " ++ string_thing(Quote) ++
" starting with " ++
io_lib:write_string(Head, Quote)]);
format_error({illegal,Type}) ->
lists:flatten(io_lib:fwrite("illegal ~w", [Type]));
format_error(char) -> "unterminated character";
format_error({base,Base}) ->
lists:flatten(io_lib:fwrite("illegal base '~w'", [Base]));
format_error(Other) ->
lists:flatten(io_lib:write(Other)).
-spec string(String) -> Return when
String :: string(),
Return :: {'ok', Tokens :: tokens(), EndLocation}
| {'error', ErrorInfo :: error_info(), ErrorLocation},
EndLocation :: erl_anno:location(),
ErrorLocation :: erl_anno:location().
string(String) ->
string(String, 1, []).
-spec string(String, StartLocation) -> Return when
String :: string(),
Return :: {'ok', Tokens :: tokens(), EndLocation}
| {'error', ErrorInfo :: error_info(), ErrorLocation},
StartLocation :: erl_anno:location(),
EndLocation :: erl_anno:location(),
ErrorLocation :: erl_anno:location().
string(String, StartLocation) ->
string(String, StartLocation, []).
-spec string(String, StartLocation, Options) -> Return when
String :: string(),
Options :: options(),
Return :: {'ok', Tokens :: tokens(), EndLocation}
| {'error', ErrorInfo :: error_info(), ErrorLocation},
StartLocation :: erl_anno:location(),
EndLocation :: erl_anno:location(),
ErrorLocation :: erl_anno:location().
string(String, Line, Options) when ?STRING(String), ?ALINE(Line) ->
string1(String, options(Options), Line, no_col, []);
string(String, {Line,Column}, Options) when ?STRING(String),
?ALINE(Line),
?COLUMN(Column) ->
string1(String, options(Options), Line, Column, []).
-type char_spec() :: string() | 'eof'.
-type cont_fun() :: fun((char_spec(), #erl_scan{},
erl_anno:line(), erl_anno:column(),
tokens(), any()) -> any()).
-opaque return_cont() :: {erl_scan_continuation,
string(), erl_anno:column(), tokens(),
erl_anno:line(),
#erl_scan{}, any(), cont_fun()}.
-type tokens_result() :: {'ok', Tokens :: tokens(),
EndLocation :: erl_anno:location()}
| {'eof', EndLocation :: erl_anno:location()}
| {'error', ErrorInfo :: error_info(),
EndLocation :: erl_anno:location()}.
-spec tokens(Continuation, CharSpec, StartLocation) -> Return when
Continuation :: return_cont() | [],
CharSpec :: char_spec(),
StartLocation :: erl_anno:location(),
Return :: {'done',Result :: tokens_result(),LeftOverChars :: char_spec()}
| {'more', Continuation1 :: return_cont()}.
tokens(Cont, CharSpec, StartLocation) ->
tokens(Cont, CharSpec, StartLocation, []).
-spec tokens(Continuation, CharSpec, StartLocation, Options) -> Return when
Continuation :: return_cont() | [],
CharSpec :: char_spec(),
StartLocation :: erl_anno:location(),
Options :: options(),
Return :: {'done',Result :: tokens_result(),LeftOverChars :: char_spec()}
| {'more', Continuation1 :: return_cont()}.
tokens([], CharSpec, Line, Options) when ?ALINE(Line) ->
tokens1(CharSpec, options(Options), Line, no_col, [], fun scan/6, []);
tokens([], CharSpec, {Line,Column}, Options) when ?ALINE(Line),
?COLUMN(Column) ->
tokens1(CharSpec, options(Options), Line, Column, [], fun scan/6, []);
tokens({erl_scan_continuation,Cs,Col,Toks,Line,St,Any,Fun},
CharSpec, _Loc, _Opts) ->
tokens1(Cs++CharSpec, St, Line, Col, Toks, Fun, Any).
continuation_location({erl_scan_continuation,_,no_col,_,Line,_,_,_}) ->
Line;
continuation_location({erl_scan_continuation,_,Col,_,Line,_,_,_}) ->
{Line,Col}.
-spec column(Token) -> erl_anno:column() | 'undefined' when
Token :: token().
column(Token) ->
erl_anno:column(element(2, Token)).
-spec end_location(Token) -> erl_anno:location() | 'undefined' when
Token :: token().
end_location(Token) ->
erl_anno:end_location(element(2, Token)).
-spec line(Token) -> erl_anno:line() when
Token :: token().
line(Token) ->
erl_anno:line(element(2, Token)).
-spec location(Token) -> erl_anno:location() when
Token :: token().
location(Token) ->
erl_anno:location(element(2, Token)).
-spec text(Token) -> erl_anno:text() | 'undefined' when
Token :: token().
text(Token) ->
erl_anno:text(element(2, Token)).
-spec category(Token) -> category() when
Token :: token().
category({Category,_Anno}) ->
Category;
category({Category,_Anno,_Symbol}) ->
Category;
category(T) ->
erlang:error(badarg, [T]).
-spec symbol(Token) -> symbol() when
Token :: token().
symbol({Category,_Anno}) ->
Category;
symbol({_Category,_Anno,Symbol}) ->
Symbol;
symbol(T) ->
erlang:error(badarg, [T]).
%%%
%%% Local functions
%%%
' Stupid Emacs
string_thing(_) -> "string".
-define(WHITE_SPACE(C),
is_integer(C) andalso
(C >= $\000 andalso C =< $\s orelse C >= $\200 andalso C =< $\240)).
-define(DIGIT(C), (is_integer(C) andalso $0 =< C andalso C =< $9)).
-define(CHAR(C), (is_integer(C) andalso 0 =< C andalso C < 16#110000)).
-define(UNICODE(C),
(is_integer(C) andalso
(C >= 0 andalso C < 16#D800 orelse
C > 16#DFFF andalso C < 16#FFFE orelse
C > 16#FFFF andalso C =< 16#10FFFF))).
-define(UNI255(C), (is_integer(C) andalso 0 =< C andalso C =< 16#ff)).
options(Opts0) when is_list(Opts0) ->
Opts = lists:foldr(fun expand_opt/2, [], Opts0),
[RW_fun] =
case opts(Opts, [reserved_word_fun], []) of
badarg ->
erlang:error(badarg, [Opts0]);
R ->
R
end,
Comment = proplists:get_bool(return_comments, Opts),
WS = proplists:get_bool(return_white_spaces, Opts),
Txt = proplists:get_bool(text, Opts),
TxtFunOpt = proplists:get_value(text_fun, Opts, none),
Internal = proplists:get_value(compiler_internal, Opts, []),
Checks = proplists:get_bool(ssa_checks, Internal),
DefTxtFun = fun(_, _) -> Txt end,
{HasFun, TxtFun} =
if
Txt -> {Txt, DefTxtFun};
TxtFunOpt == none -> {Txt, DefTxtFun};
true -> {true, TxtFunOpt}
end,
#erl_scan{resword_fun = RW_fun,
comment = Comment,
ws = WS,
text_fun = TxtFun,
has_fun = HasFun,
checks = Checks};
options(Opt) ->
options([Opt]).
opts(Options, [Key|Keys], L) ->
V = case lists:keyfind(Key, 1, Options) of
{reserved_word_fun,F} when ?RESWORDFUN(F) ->
{ok,F};
{Key,_} ->
badarg;
false ->
{ok,default_option(Key)}
end,
case V of
badarg ->
badarg;
{ok,Value} ->
opts(Options, Keys, [Value|L])
end;
opts(_Options, [], L) ->
lists:reverse(L).
default_option(reserved_word_fun) ->
fun reserved_word/1.
expand_opt(return, Os) ->
[return_comments,return_white_spaces|Os];
expand_opt(O, Os) ->
[O|Os].
tokens1(Cs, St, Line, Col, Toks, Fun, Any) when ?STRING(Cs); Cs =:= eof ->
case Fun(Cs, St, Line, Col, Toks, Any) of
{more,{Cs0,Nst,Ncol,Ntoks,Nline,Nany,Nfun}} ->
{more,{erl_scan_continuation,Cs0,Ncol,Ntoks,Nline,Nst,Nany,Nfun}};
{ok,Toks0,eof,Nline,Ncol} ->
Res = case Toks0 of
[] ->
{eof,location(Nline, Ncol)};
_ ->
{ok,lists:reverse(Toks0),location(Nline,Ncol)}
end,
{done,Res,eof};
{ok,Toks0,Rest,Nline,Ncol} ->
{done,{ok,lists:reverse(Toks0),location(Nline, Ncol)},Rest};
{{error,_,_}=Error,Rest} ->
{done,Error,Rest}
end.
string1(Cs, St, Line, Col, Toks) ->
case scan1(Cs, St, Line, Col, Toks) of
{more,{Cs0,Nst,Ncol,Ntoks,Nline,Any,Fun}} ->
case Fun(Cs0++eof, Nst, Nline, Ncol, Ntoks, Any) of
{ok,Toks1,_Rest,Line2,Col2} ->
{ok,lists:reverse(Toks1),location(Line2, Col2)};
{{error,_,_}=Error,_Rest} ->
Error
end;
{ok,Ntoks,[_|_]=Rest,Nline,Ncol} ->
string1(Rest, St, Nline, Ncol, Ntoks);
{ok,Ntoks,_,Nline,Ncol} ->
{ok,lists:reverse(Ntoks),location(Nline, Ncol)};
{{error,_,_}=Error,_Rest} ->
Error
end.
scan(Cs, #erl_scan{}=St, Line, Col, Toks, _) ->
scan1(Cs, St, Line, Col, Toks).
scan1([$\s|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
scan_spcs(Cs, St, Line, Col, Toks, 1);
scan1([$\s|Cs], St, Line, Col, Toks) ->
skip_white_space(Cs, St, Line, Col, Toks, 1);
scan1([$\n|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
scan_newline(Cs, St, Line, Col, Toks);
scan1([$\n|Cs], St, Line, Col, Toks) ->
skip_white_space(Cs, St, Line+1, new_column(Col, 1), Toks, 0);
%% Optimization: some very common punctuation characters:
scan1([$,|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ",", ',', 1);
scan1([$(|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "(", '(', 1);
scan1([$)|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ")", ')', 1);
scan1([${|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "{", '{', 1);
scan1([$}|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "}", '}', 1);
scan1([$[|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "[", '[', 1);
scan1([$]|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "]", ']', 1);
scan1([$;|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ";", ';', 1);
scan1([$_=C|Cs], St, Line, Col, Toks) ->
scan_variable(Cs, St, Line, Col, Toks, [C]);
= C|Cs ] , St , Line , Col , Toks ) when St#erl_scan.checks - >
scan_check(Cs, St, Line, Col, Toks, [C]);
|Cs ] , St , Line , Col , Toks ) when not St#erl_scan.comment - >
skip_comment(Cs, St, Line, Col, Toks, 1);
= C|Cs ] , St , Line , Col , Toks ) - >
scan_comment(Cs, St, Line, Col, Toks, [C]);
%% More punctuation characters below.
scan1([C|_], _St, _Line, _Col0, _Toks) when not ?CHAR(C) ->
error({not_character,C});
scan1([C|Cs], St, Line, Col, Toks) when C >= $A, C =< $Z ->
scan_variable(Cs, St, Line, Col, Toks, [C]);
scan1([C|Cs], St, Line, Col, Toks) when C >= $a, C =< $z ->
scan_atom(Cs, St, Line, Col, Toks, [C]);
scan1([C|Cs], St, Line, Col, Toks) when ?DIGIT(C) ->
scan_number(Cs, St, Line, Col, Toks, [C], no_underscore);
scan1("..."++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "...", '...', 3);
scan1(".."=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1(".."++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "..", '..', 2);
scan1("."=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1([$.=C|Cs], St, Line, Col, Toks) ->
scan_dot(Cs, St, Line, Col, Toks, [C]);
scan1([$"|Cs], St, Line, Col, Toks) -> %" Emacs
State0 = {[],[],Line,Col},
scan_string(Cs, St, Line, incr_column(Col, 1), Toks, State0);
' Emacs
State0 = {[],[],Line,Col},
scan_qatom(Cs, St, Line, incr_column(Col, 1), Toks, State0);
scan1([$$|Cs], St, Line, Col, Toks) ->
scan_char(Cs, St, Line, Col, Toks);
scan1([$\r|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
white_space_end(Cs, St, Line, Col, Toks, 1, "\r");
scan1([C|Cs], St, Line, Col, Toks) when C >= $ß, C =< $ÿ, C =/= $÷ ->
scan_atom(Cs, St, Line, Col, Toks, [C]);
scan1([C|Cs], St, Line, Col, Toks) when C >= $À, C =< $Þ, C /= $× ->
scan_variable(Cs, St, Line, Col, Toks, [C]);
scan1([$\t|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
scan_tabs(Cs, St, Line, Col, Toks, 1);
scan1([$\t|Cs], St, Line, Col, Toks) ->
skip_white_space(Cs, St, Line, Col, Toks, 1);
scan1([C|Cs], St, Line, Col, Toks) when ?WHITE_SPACE(C) ->
case St#erl_scan.ws of
true ->
scan_white_space(Cs, St, Line, Col, Toks, [C]);
false ->
skip_white_space(Cs, St, Line, Col, Toks, 1)
end;
Punctuation characters and operators , first recognise multiples .
%% ?= for the maybe ... else ... end construct
scan1("?="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "?=", '?=', 2);
scan1("?"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% << <- <=
scan1("<<"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<<", '<<', 2);
scan1("<-"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<-", '<-', 2);
scan1("<="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<=", '<=', 2);
scan1("<"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% >> >=
scan1(">>"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ">>", '>>', 2);
scan1(">="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ">=", '>=', 2);
scan1(">"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% -> --
scan1("->"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "->", '->', 2);
scan1("--"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "--", '--', 2);
scan1("-"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% ++
scan1("++"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "++", '++', 2);
scan1("+"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% =:= =/= =< == =>
scan1("=:="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=:=", '=:=', 3);
scan1("=:"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("=/="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=/=", '=/=', 3);
scan1("=/"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("=<"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=<", '=<', 2);
scan1("=>"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=>", '=>', 2);
scan1("=="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "==", '==', 2);
scan1("="=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% /=
scan1("/="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "/=", '/=', 2);
scan1("/"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% ||
scan1("||"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "||", '||', 2);
scan1("|"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
%% :=
scan1(":="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ":=", ':=', 2);
%% :: for typed records
scan1("::"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "::", '::', 2);
scan1(":"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
Optimization : punctuation characters less than 127 :
scan1([$=|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=", '=', 1);
scan1([$:|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ":", ':', 1);
scan1([$||Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "|", '|', 1);
scan1([$#|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "#", '#', 1);
scan1([$/|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "/", '/', 1);
scan1([$?|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "?", '?', 1);
scan1([$-|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "-", '-', 1);
scan1([$+|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "+", '+', 1);
scan1([$*|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "*", '*', 1);
scan1([$<|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<", '<', 1);
scan1([$>|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ">", '>', 1);
scan1([$!|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "!", '!', 1);
scan1([$@|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "@", '@', 1);
scan1([$\\|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "\\", '\\', 1);
scan1([$^|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "^", '^', 1);
scan1([$`|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "`", '`', 1);
scan1([$~|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "~", '~', 1);
scan1([$&|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "&", '&', 1);
%% End of optimization.
scan1([C|Cs], St, Line, Col, Toks) when ?UNI255(C) ->
Str = [C],
tok2(Cs, St, Line, Col, Toks, Str, list_to_atom(Str), 1);
scan1([C|Cs], _St, Line, Col, _Toks) when ?CHAR(C) ->
Ncol = incr_column(Col, 1),
scan_error({illegal,character}, Line, Col, Line, Ncol, Cs);
scan1([]=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1(eof=Cs, _St, Line, Col, Toks) ->
{ok,Toks,Cs,Line,Col}.
scan_atom_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_atom(Cs, St, Line, Col, Toks, Ncs).
scan_atom(Cs0, St, Line, Col, Toks, Ncs0) ->
case scan_name(Cs0, Ncs0) of
{more,Ncs} ->
{more,{[],St,Col,Toks,Line,Ncs,fun scan_atom_fun/6}};
{Wcs,Cs} ->
try list_to_atom(Wcs) of
Name ->
case (St#erl_scan.resword_fun)(Name) of
true ->
tok2(Cs, St, Line, Col, Toks, Wcs, Name);
false ->
tok3(Cs, St, Line, Col, Toks, atom, Wcs, Name)
end
catch
_:_ ->
Ncol = incr_column(Col, length(Wcs)),
scan_error({illegal,atom}, Line, Col, Line, Ncol, Cs)
end
end.
scan_variable_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_variable(Cs, St, Line, Col, Toks, Ncs).
scan_variable(Cs0, St, Line, Col, Toks, Ncs0) ->
case scan_name(Cs0, Ncs0) of
{more,Ncs} ->
{more,{[],St,Col,Toks,Line,Ncs,fun scan_variable_fun/6}};
{Wcs,Cs} ->
try list_to_atom(Wcs) of
Name ->
tok3(Cs, St, Line, Col, Toks, var, Wcs, Name)
catch
_:_ ->
Ncol = incr_column(Col, length(Wcs)),
scan_error({illegal,var}, Line, Col, Line, Ncol, Cs)
end
end.
scan_name([C|_]=Cs, Ncs) when not ?CHAR(C) ->
{lists:reverse(Ncs),Cs};
scan_name([C|Cs], Ncs) when C >= $a, C =< $z ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when C >= $A, C =< $Z ->
scan_name(Cs, [C|Ncs]);
scan_name([$_=C|Cs], Ncs) ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when ?DIGIT(C) ->
scan_name(Cs, [C|Ncs]);
scan_name([$@=C|Cs], Ncs) ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when C >= $ß, C =< $ÿ, C =/= $÷ ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when C >= $À, C =< $Þ, C =/= $× ->
scan_name(Cs, [C|Ncs]);
scan_name([], Ncs) ->
{more,Ncs};
scan_name(Cs, Ncs) ->
{lists:reverse(Ncs),Cs}.
-define(STR(Cl, St, S),
case (St#erl_scan.has_fun)
andalso (St#erl_scan.text_fun)(Cl, S) of
true -> S;
false -> []
end).
scan_dot([C|_]=Cs, St, Line, Col, Toks, Ncs)
when St#erl_scan.in_check, C =/= $. ->
tok2(Cs, St#erl_scan{in_check=false}, Line, Col, Toks, Ncs, '.', 1);
|_]=Cs , St , Line , Col , Toks , Ncs ) - >
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs)),
{ok,[{dot,Anno}|Toks],Cs,Line,incr_column(Col, 1)};
scan_dot([$\n=C|Cs], St, Line, Col, Toks, Ncs) ->
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs++[C])),
{ok,[{dot,Anno}|Toks],Cs,Line+1,new_column(Col, 1)};
scan_dot([C|Cs], St, Line, Col, Toks, Ncs) when ?WHITE_SPACE(C) ->
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs++[C])),
{ok,[{dot,Anno}|Toks],Cs,Line,incr_column(Col, 2)};
scan_dot(eof=Cs, St, Line, Col, Toks, Ncs) ->
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs)),
{ok,[{dot,Anno}|Toks],Cs,Line,incr_column(Col, 1)};
scan_dot(Cs, St, Line, Col, Toks, Ncs) ->
tok2(Cs, St, Line, Col, Toks, Ncs, '.', 1).
%%% White space characters are very common, so it is worthwhile to
%%% scan them fast and store them compactly. (The words "whitespace"
and " white space " usually mean the same thing . The Erlang
%%% specification denotes the characters with ASCII code in the
interval 0 to 32 as " white space " . )
%%%
%%% Convention: if there is a white newline ($\n) it will always be
the first character in the text string . As a consequence , there
can not be more than one newline in a white_space token string .
%%%
%%% Some common combinations are recognized, some are not. Examples
%%% of the latter are tab(s) followed by space(s), like "\t ".
( They will be represented by two ( or more ) tokens . )
%%%
%%% Note: the character sequence "\r\n" is *not* recognized since it
would violate the property that $ \n will always be the first
%%% character. (But since "\r\n\r\n" is common, it pays off to
recognize " " . )
scan_newline([$\s|Cs], St, Line, Col, Toks) ->
scan_nl_spcs(Cs, St, Line, Col, Toks, 2);
scan_newline([$\t|Cs], St, Line, Col, Toks) ->
scan_nl_tabs(Cs, St, Line, Col, Toks, 2);
scan_newline([$\r|Cs], St, Line, Col, Toks) ->
newline_end(Cs, St, Line, Col, Toks, 2, "\n\r");
scan_newline([$\f|Cs], St, Line, Col, Toks) ->
newline_end(Cs, St, Line, Col, Toks, 2, "\n\f");
scan_newline([], St, Line, Col, Toks) ->
{more,{[$\n],St,Col,Toks,Line,[],fun scan/6}};
scan_newline(Cs, St, Line, Col, Toks) ->
scan_nl_white_space(Cs, St, Line, Col, Toks, "\n").
scan_nl_spcs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N) ->
scan_nl_spcs(Cs, St, Line, Col, Toks, N).
scan_nl_spcs([$\s|Cs], St, Line, Col, Toks, N) when N < 17 ->
scan_nl_spcs(Cs, St, Line, Col, Toks, N+1);
scan_nl_spcs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_nl_spcs_fun/6}};
scan_nl_spcs(Cs, St, Line, Col, Toks, N) ->
newline_end(Cs, St, Line, Col, Toks, N, nl_spcs(N)).
scan_nl_tabs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N) ->
scan_nl_tabs(Cs, St, Line, Col, Toks, N).
scan_nl_tabs([$\t|Cs], St, Line, Col, Toks, N) when N < 11 ->
scan_nl_tabs(Cs, St, Line, Col, Toks, N+1);
scan_nl_tabs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_nl_tabs_fun/6}};
scan_nl_tabs(Cs, St, Line, Col, Toks, N) ->
newline_end(Cs, St, Line, Col, Toks, N, nl_tabs(N)).
scan_nl_white_space_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_nl_white_space(Cs, St, Line, Col, Toks, Ncs).
%% Note: returning {more,Cont} is meaningless here; one could just as
%% well return several tokens. But since tokens() scans up to a full
%% stop anyway, nothing is gained by not collecting all white spaces.
scan_nl_white_space([$\n|Cs], #erl_scan{has_fun = false}=St, Line, no_col=Col,
Toks0, Ncs) ->
Toks = [{white_space,anno(Line),lists:reverse(Ncs)}|Toks0],
scan_newline(Cs, St, Line+1, Col, Toks);
scan_nl_white_space([$\n|Cs], St, Line, Col, Toks, Ncs0) ->
Ncs = lists:reverse(Ncs0),
Anno = anno(Line, Col, St, ?STR(white_space, St, Ncs)),
Token = {white_space,Anno,Ncs},
scan_newline(Cs, St, Line+1, new_column(Col, length(Ncs)), [Token|Toks]);
scan_nl_white_space([C|Cs], St, Line, Col, Toks, Ncs)
when ?WHITE_SPACE(C) ->
scan_nl_white_space(Cs, St, Line, Col, Toks, [C|Ncs]);
scan_nl_white_space([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_nl_white_space_fun/6}};
scan_nl_white_space(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col,
Toks, Ncs) ->
Anno = anno(Line),
scan1(Cs, St, Line+1, Col, [{white_space,Anno,lists:reverse(Ncs)}|Toks]);
scan_nl_white_space(Cs, St, Line, Col, Toks, Ncs0) ->
Ncs = lists:reverse(Ncs0),
Anno = anno(Line, Col, St, ?STR(white_space, St, Ncs)),
Token = {white_space,Anno,Ncs},
scan1(Cs, St, Line+1, new_column(Col, length(Ncs)), [Token|Toks]).
newline_end(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col,
Toks, _N, Ncs) ->
scan1(Cs, St, Line+1, Col, [{white_space,anno(Line),Ncs}|Toks]);
newline_end(Cs, #erl_scan{}=St, Line, Col, Toks, N, Ncs) ->
Anno = anno(Line, Col, St, ?STR(white_space, St, Ncs)),
scan1(Cs, St, Line+1, new_column(Col, N), [{white_space,Anno,Ncs}|Toks]).
scan_spcs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N), N >= 1 ->
scan_spcs(Cs, St, Line, Col, Toks, N).
scan_spcs([$\s|Cs], St, Line, Col, Toks, N) when N < 16 ->
scan_spcs(Cs, St, Line, Col, Toks, N+1);
scan_spcs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_spcs_fun/6}};
scan_spcs(Cs, St, Line, Col, Toks, N) ->
white_space_end(Cs, St, Line, Col, Toks, N, spcs(N)).
scan_tabs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N), N >= 1 ->
scan_tabs(Cs, St, Line, Col, Toks, N).
scan_tabs([$\t|Cs], St, Line, Col, Toks, N) when N < 10 ->
scan_tabs(Cs, St, Line, Col, Toks, N+1);
scan_tabs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_tabs_fun/6}};
scan_tabs(Cs, St, Line, Col, Toks, N) ->
white_space_end(Cs, St, Line, Col, Toks, N, tabs(N)).
skip_white_space_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N) ->
skip_white_space(Cs, St, Line, Col, Toks, N).
skip_white_space([$\n|Cs], St, Line, Col, Toks, _N) ->
skip_white_space(Cs, St, Line+1, new_column(Col, 1), Toks, 0);
skip_white_space([C|Cs], St, Line, Col, Toks, N) when ?WHITE_SPACE(C) ->
skip_white_space(Cs, St, Line, Col, Toks, N+1);
skip_white_space([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun skip_white_space_fun/6}};
skip_white_space(Cs, St, Line, Col, Toks, N) ->
scan1(Cs, St, Line, incr_column(Col, N), Toks).
scan_white_space_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_white_space(Cs, St, Line, Col, Toks, Ncs).
Maybe \t and \s should break the loop .
scan_white_space([$\n|_]=Cs, St, Line, Col, Toks, Ncs) ->
white_space_end(Cs, St, Line, Col, Toks, length(Ncs), lists:reverse(Ncs));
scan_white_space([C|Cs], St, Line, Col, Toks, Ncs) when ?WHITE_SPACE(C) ->
scan_white_space(Cs, St, Line, Col, Toks, [C|Ncs]);
scan_white_space([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_white_space_fun/6}};
scan_white_space(Cs, St, Line, Col, Toks, Ncs) ->
white_space_end(Cs, St, Line, Col, Toks, length(Ncs), lists:reverse(Ncs)).
-compile({inline,[white_space_end/7]}).
white_space_end(Cs, St, Line, Col, Toks, N, Ncs) ->
tok3(Cs, St, Line, Col, Toks, white_space, Ncs, Ncs, N).
scan_char([$\\|Cs]=Cs0, St, Line, Col, Toks) ->
case scan_escape(Cs, incr_column(Col, 2)) of
more ->
{more,{[$$|Cs0],St,Col,Toks,Line,[],fun scan/6}};
{error,Ncs,Error,Ncol} ->
scan_error(Error, Line, Col, Line, Ncol, Ncs);
{eof,Ncol} ->
scan_error(char, Line, Col, Line, Ncol, eof);
{nl,Val,Str,Ncs,Ncol} ->
Anno = anno(Line, Col, St, ?STR(char, St, "$\\"++Str)), %"
Ntoks = [{char,Anno,Val}|Toks],
scan1(Ncs, St, Line+1, Ncol, Ntoks);
{Val,Str,Ncs,Ncol} ->
Anno = anno(Line, Col, St, ?STR(char, St, "$\\"++Str)), %"
Ntoks = [{char,Anno,Val}|Toks],
scan1(Ncs, St, Line, Ncol, Ntoks)
end;
scan_char([$\n=C|Cs], St, Line, Col, Toks) ->
Anno = anno(Line, Col, St, ?STR(char, St, [$$,C])),
scan1(Cs, St, Line+1, new_column(Col, 1), [{char,Anno,C}|Toks]);
scan_char([C|Cs], St, Line, Col, Toks) when ?UNICODE(C) ->
Anno = anno(Line, Col, St, ?STR(char, St, [$$,C])),
scan1(Cs, St, Line, incr_column(Col, 2), [{char,Anno,C}|Toks]);
scan_char([C|_Cs], _St, Line, Col, _Toks) when ?CHAR(C) ->
scan_error({illegal,character}, Line, Col, Line, incr_column(Col, 1), eof);
scan_char([], St, Line, Col, Toks) ->
{more,{[$$],St,Col,Toks,Line,[],fun scan/6}};
scan_char(eof, _St, Line, Col, _Toks) ->
scan_error(char, Line, Col, Line, incr_column(Col, 1), eof).
scan_string(Cs, #erl_scan{}=St, Line, Col, Toks, {Wcs,Str,Line0,Col0}) ->
case scan_string0(Cs, St, Line, Col, $\", Str, Wcs) of %"
{more,Ncs,Nline,Ncol,Nstr,Nwcs} ->
State = {Nwcs,Nstr,Line0,Col0},
{more,{Ncs,St,Ncol,Toks,Nline,State,fun scan_string/6}};
{char_error,Ncs,Error,Nline,Ncol,EndCol} ->
scan_error(Error, Nline, Ncol, Nline, EndCol, Ncs);
{error,Nline,Ncol,Nwcs,Ncs} ->
Estr = string:slice(Nwcs, 0, 16), % Expanded escape chars.
scan_error({string,$\",Estr}, Line0, Col0, Nline, Ncol, Ncs); %"
{Ncs,Nline,Ncol,Nstr,Nwcs} ->
Anno = anno(Line0, Col0, St, ?STR(string, St, Nstr)),
scan1(Ncs, St, Nline, Ncol, [{string,Anno,Nwcs}|Toks])
end.
scan_qatom(Cs, #erl_scan{}=St, Line, Col, Toks, {Wcs,Str,Line0,Col0}) ->
case scan_string0(Cs, St, Line, Col, $\', Str, Wcs) of %'
{more,Ncs,Nline,Ncol,Nstr,Nwcs} ->
State = {Nwcs,Nstr,Line0,Col0},
{more,{Ncs,St,Ncol,Toks,Nline,State,fun scan_qatom/6}};
{char_error,Ncs,Error,Nline,Ncol,EndCol} ->
scan_error(Error, Nline, Ncol, Nline, EndCol, Ncs);
{error,Nline,Ncol,Nwcs,Ncs} ->
Estr = string:slice(Nwcs, 0, 16), % Expanded escape chars.
scan_error({string,$\',Estr}, Line0, Col0, Nline, Ncol, Ncs); %'
{Ncs,Nline,Ncol,Nstr,Nwcs} ->
try list_to_atom(Nwcs) of
A when is_atom(A) ->
Anno = anno(Line0, Col0, St, ?STR(atom, St, Nstr)),
scan1(Ncs, St, Nline, Ncol, [{atom,Anno,A}|Toks])
catch
_:_ ->
scan_error({illegal,atom}, Line0, Col0, Nline, Ncol, Ncs)
end
end.
scan_string0(Cs, #erl_scan{has_fun=false}, Line, no_col=Col, Q, [], Wcs) ->
scan_string_no_col(Cs, Line, Col, Q, Wcs);
scan_string0(Cs, #erl_scan{has_fun=true}, Line, no_col=Col, Q, Str, Wcs) ->
scan_string1(Cs, Line, Col, Q, Str, Wcs);
scan_string0(Cs, St, Line, Col, Q, [], Wcs) ->
scan_string_col(Cs, St, Line, Col, Q, Wcs);
scan_string0(Cs, _St, Line, Col, Q, Str, Wcs) ->
scan_string1(Cs, Line, Col, Q, Str, Wcs).
%% Optimization. Col =:= no_col.
scan_string_no_col([Q|Cs], Line, Col, Q, Wcs) ->
{Cs,Line,Col,_DontCare=[],lists:reverse(Wcs)};
scan_string_no_col([$\n=C|Cs], Line, Col, Q, Wcs) ->
scan_string_no_col(Cs, Line+1, Col, Q, [C|Wcs]);
scan_string_no_col([C|Cs], Line, Col, Q, Wcs) when C =/= $\\, ?UNICODE(C) ->
scan_string_no_col(Cs, Line, Col, Q, [C|Wcs]);
scan_string_no_col(Cs, Line, Col, Q, Wcs) ->
scan_string1(Cs, Line, Col, Q, Wcs, Wcs).
%% Optimization. Col =/= no_col.
scan_string_col([Q|Cs], St, Line, Col, Q, Wcs0) ->
Wcs = lists:reverse(Wcs0),
Str = ?STR(atom, St, [Q|Wcs++[Q]]),
{Cs,Line,Col+1,Str,Wcs};
scan_string_col([$\n=C|Cs], St, Line, _xCol, Q, Wcs) ->
scan_string_col(Cs, St, Line+1, 1, Q, [C|Wcs]);
scan_string_col([C|Cs], St, Line, Col, Q, Wcs) when C =/= $\\, ?UNICODE(C) ->
scan_string_col(Cs, St, Line, Col+1, Q, [C|Wcs]);
scan_string_col(Cs, _St, Line, Col, Q, Wcs) ->
scan_string1(Cs, Line, Col, Q, Wcs, Wcs).
%% Note: in those cases when a 'char_error' tuple is returned below it
is tempting to skip over characters up to the first Q character ,
%% but then the end location of the error tuple would not correspond
%% to the start location of the returned Rest string. (Maybe the end
%% location could be modified, but that too is ugly.)
scan_string1([Q|Cs], Line, Col, Q, Str0, Wcs0) ->
Wcs = lists:reverse(Wcs0),
Str = [Q|lists:reverse(Str0, [Q])],
{Cs,Line,incr_column(Col, 1),Str,Wcs};
scan_string1([$\n=C|Cs], Line, Col, Q, Str, Wcs) ->
Ncol = new_column(Col, 1),
scan_string1(Cs, Line+1, Ncol, Q, [C|Str], [C|Wcs]);
scan_string1([$\\|Cs]=Cs0, Line, Col, Q, Str, Wcs) ->
case scan_escape(Cs, Col) of
more ->
{more,Cs0,Line,Col,Str,Wcs};
{error,Ncs,Error,Ncol} ->
{char_error,Ncs,Error,Line,Col,incr_column(Ncol, 1)};
{eof,Ncol} ->
{error,Line,incr_column(Ncol, 1),lists:reverse(Wcs),eof};
{nl,Val,ValStr,Ncs,Ncol} ->
Nstr = lists:reverse(ValStr, [$\\|Str]),
Nwcs = [Val|Wcs],
scan_string1(Ncs, Line+1, Ncol, Q, Nstr, Nwcs);
{Val,ValStr,Ncs,Ncol} ->
Nstr = lists:reverse(ValStr, [$\\|Str]),
Nwcs = [Val|Wcs],
scan_string1(Ncs, Line, incr_column(Ncol, 1), Q, Nstr, Nwcs)
end;
scan_string1([C|Cs], Line, no_col=Col, Q, Str, Wcs) when ?UNICODE(C) ->
scan_string1(Cs, Line, Col, Q, [C|Str], [C|Wcs]);
scan_string1([C|Cs], Line, Col, Q, Str, Wcs) when ?UNICODE(C) ->
scan_string1(Cs, Line, Col+1, Q, [C|Str], [C|Wcs]);
scan_string1([C|Cs], Line, Col, _Q, _Str, _Wcs) when ?CHAR(C) ->
{char_error,Cs,{illegal,character},Line,Col,incr_column(Col, 1)};
scan_string1([]=Cs, Line, Col, _Q, Str, Wcs) ->
{more,Cs,Line,Col,Str,Wcs};
scan_string1(eof, Line, Col, _Q, _Str, Wcs) ->
{error,Line,Col,lists:reverse(Wcs),eof}.
-define(OCT(C), (is_integer(C) andalso $0 =< C andalso C =< $7)).
-define(HEX(C), (is_integer(C) andalso
(C >= $0 andalso C =< $9 orelse
C >= $A andalso C =< $F orelse
C >= $a andalso C =< $f))).
%% \<1-3> octal digits
scan_escape([O1,O2,O3|Cs], Col) when ?OCT(O1), ?OCT(O2), ?OCT(O3) ->
Val = (O1*8 + O2)*8 + O3 - 73*$0,
{Val,[O1,O2,O3],Cs,incr_column(Col, 3)};
scan_escape([O1,O2], _Col) when ?OCT(O1), ?OCT(O2) ->
more;
scan_escape([O1,O2|Cs], Col) when ?OCT(O1), ?OCT(O2) ->
Val = (O1*8 + O2) - 9*$0,
{Val,[O1,O2],Cs,incr_column(Col, 2)};
scan_escape([O1], _Col) when ?OCT(O1) ->
more;
scan_escape([O1|Cs], Col) when ?OCT(O1) ->
{O1 - $0,[O1],Cs,incr_column(Col, 1)};
%% \x{<hex digits>}
scan_escape([$x,${|Cs], Col) ->
scan_hex(Cs, incr_column(Col, 2), []);
scan_escape([$x], _Col) ->
more;
scan_escape([$x|eof], Col) ->
{eof,incr_column(Col, 1)};
%% \x<2> hexadecimal digits
scan_escape([$x,H1,H2|Cs], Col) when ?HEX(H1), ?HEX(H2) ->
Val = erlang:list_to_integer([H1,H2], 16),
{Val,[$x,H1,H2],Cs,incr_column(Col, 3)};
scan_escape([$x,H1], _Col) when ?HEX(H1) ->
more;
scan_escape([$x|Cs], Col) ->
{error,Cs,{illegal,character},incr_column(Col, 1)};
%% \^X -> Control-X
scan_escape([$^=C0,C|Cs], Col) when ?CHAR(C) ->
case caret_char_code(C) of
error ->
{error,[C|Cs],{illegal,character},incr_column(Col, 1)};
Code ->
{Code,[C0,C],Cs,incr_column(Col, 2)}
end;
scan_escape([$^], _Col) ->
more;
scan_escape([$^|eof], Col) ->
{eof,incr_column(Col, 1)};
scan_escape([$\n=C|Cs], Col) ->
{nl,C,[C],Cs,new_column(Col, 1)};
scan_escape([C0|Cs], Col) when ?UNICODE(C0) ->
C = escape_char(C0),
{C,[C0],Cs,incr_column(Col, 1)};
scan_escape([C|Cs], Col) when ?CHAR(C) ->
{error,Cs,{illegal,character},incr_column(Col, 1)};
scan_escape([], _Col) ->
more;
scan_escape(eof, Col) ->
{eof,Col}.
scan_hex([C|Cs], Col, Wcs) when ?HEX(C) ->
scan_hex(Cs, incr_column(Col, 1), [C|Wcs]);
scan_hex(Cs, Col, Wcs) ->
scan_hex_end(Cs, Col, Wcs, "x{").
scan_hex_end([$}|Cs], Col, [], _Str) ->
%% Empty escape sequence.
{error,Cs,{illegal,character},incr_column(Col, 1)};
scan_hex_end([$}|Cs], Col, Wcs0, Str0) ->
Wcs = lists:reverse(Wcs0),
try list_to_integer(Wcs, 16) of
Val when ?UNICODE(Val) ->
{Val,Str0++Wcs++[$}],Cs,incr_column(Col, 1)};
_Val ->
{error,Cs,{illegal,character},incr_column(Col, 1)}
catch
error:system_limit ->
%% Extremely unlikely to occur in practice.
{error,Cs,{illegal,character},incr_column(Col, 1)}
end;
scan_hex_end([], _Col, _Wcs, _Str0) ->
more;
scan_hex_end(eof, Col, _Wcs, _Str0) ->
{eof,Col};
scan_hex_end(Cs, Col, _Wcs, _Str0) ->
{error,Cs,{illegal,character},Col}.
escape_char($n) -> $\n; % \n = LF
\r = CR
escape_char($t) -> $\t; % \t = TAB
\v = VT
escape_char($b) -> $\b; % \b = BS
escape_char($f) -> $\f; % \f = FF
escape_char($e) -> $\e; % \e = ESC
escape_char($s) -> $\s; % \s = SPC
\d = DEL
escape_char(C) -> C.
caret_char_code($?) -> 16#7f;
caret_char_code(C) when $@ =< C, C =< $_; $a =< C, C =< $z -> C band 16#1f;
caret_char_code(_) -> error.
scan_number(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs, Us}) ->
scan_number(Cs, St, Line, Col, Toks, Ncs, Us).
scan_number([C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_number(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_number([$_,Next|Cs], St, Line, Col, Toks, [Prev|_]=Ncs, _Us) when
?DIGIT(Next) andalso ?DIGIT(Prev) ->
scan_number(Cs, St, Line, Col, Toks, [Next,$_|Ncs], with_underscore);
scan_number([$_]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_number/6}};
scan_number([$.,C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_fraction(Cs, St, Line, Col, Toks, [C,$.|Ncs], Us);
scan_number([$.]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_number/6}};
scan_number([$#|Cs]=Cs0, St, Line, Col, Toks, Ncs0, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_integer(remove_digit_separators(Ncs, Us)) of
B when is_integer(B), 2 =< B, B =< 1+$Z-$A+10 ->
Bcs = Ncs++[$#],
scan_based_int(Cs, St, Line, Col, Toks, B, [], Bcs, no_underscore);
B when is_integer(B) ->
Len = length(Ncs),
scan_error({base,B}, Line, Col, Line, incr_column(Col, Len), Cs0)
catch
error:system_limit ->
%% Extremely unlikely to occur in practice.
scan_error({illegal,base}, Line, Col, Line, Col, Cs0)
end;
scan_number([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_number/6}};
scan_number(Cs, St, Line, Col, Toks, Ncs0, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_integer(remove_digit_separators(Ncs, Us), 10) of
N ->
tok3(Cs, St, Line, Col, Toks, integer, Ncs, N)
catch
error:system_limit ->
%% Extremely unlikely to occur in practice.
Ncol = incr_column(Col, length(Ncs)),
scan_error({illegal,integer}, Line, Col, Line, Ncol, Cs)
end.
remove_digit_separators(Number, no_underscore) ->
Number;
remove_digit_separators(Number, with_underscore) ->
[C || C <- Number, C =/= $_].
-define(BASED_DIGIT(C, B),
(is_integer(C)
andalso
((?DIGIT(C) andalso C < $0 + B)
orelse (C >= $A andalso B > 10 andalso C < $A + B - 10)
orelse (C >= $a andalso B > 10 andalso C < $a + B - 10)))).
scan_based_int(Cs, #erl_scan{}=St, Line, Col, Toks, {B,NCs,BCs,Us})
when is_integer(B), 2 =< B, B =< 1+$Z-$A+10 ->
scan_based_int(Cs, St, Line, Col, Toks, B, NCs, BCs, Us).
scan_based_int([C|Cs], St, Line, Col, Toks, B, Ncs, Bcs, Us) when
?BASED_DIGIT(C, B) ->
scan_based_int(Cs, St, Line, Col, Toks, B, [C|Ncs], Bcs, Us);
scan_based_int([$_,Next|Cs], St, Line, Col, Toks, B, [Prev|_]=Ncs, Bcs, _Us)
when ?BASED_DIGIT(Next, B) andalso ?BASED_DIGIT(Prev, B) ->
scan_based_int(Cs, St, Line, Col, Toks, B, [Next,$_|Ncs], Bcs,
with_underscore);
scan_based_int([$_]=Cs, St, Line, Col, Toks, B, NCs, BCs, Us) ->
{more,{Cs,St,Col,Toks,Line,{B,NCs,BCs,Us},fun scan_based_int/6}};
scan_based_int([]=Cs, St, Line, Col, Toks, B, NCs, BCs, Us) ->
{more,{Cs,St,Col,Toks,Line,{B,NCs,BCs,Us},fun scan_based_int/6}};
scan_based_int(Cs, _St, Line, Col, _Toks, _B, [], Bcs, _Us) ->
%% No actual digits following the base.
Len = length(Bcs),
Ncol = incr_column(Col, Len),
scan_error({illegal,integer}, Line, Col, Line, Ncol, Cs);
scan_based_int(Cs, St, Line, Col, Toks, B, Ncs0, [_|_]=Bcs, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_integer(remove_digit_separators(Ncs, Us), B) of
N ->
tok3(Cs, St, Line, Col, Toks, integer, Bcs++Ncs, N)
catch
error:system_limit ->
%% Extremely unlikely to occur in practice.
Len = length(Bcs)+length(Ncs),
Ncol = incr_column(Col, Len),
scan_error({illegal,integer}, Line, Col, Line, Ncol, Cs)
end.
scan_fraction(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs,Us}) ->
scan_fraction(Cs, St, Line, Col, Toks, Ncs, Us).
scan_fraction([C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_fraction(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_fraction([$_,Next|Cs], St, Line, Col, Toks, [Prev|_]=Ncs, _Us) when
?DIGIT(Next) andalso ?DIGIT(Prev) ->
scan_fraction(Cs, St, Line, Col, Toks, [Next,$_|Ncs], with_underscore);
scan_fraction([$_]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_fraction/6}};
scan_fraction([E|Cs], St, Line, Col, Toks, Ncs, Us) when E =:= $e; E =:= $E ->
scan_exponent_sign(Cs, St, Line, Col, Toks, [E|Ncs], Us);
scan_fraction([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_fraction/6}};
scan_fraction(Cs, St, Line, Col, Toks, Ncs, Us) ->
float_end(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent_sign(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs, Us}) ->
scan_exponent_sign(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent_sign([C|Cs], St, Line, Col, Toks, Ncs, Us) when
C =:= $+; C =:= $- ->
scan_exponent(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_exponent_sign([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_exponent_sign/6}};
scan_exponent_sign(Cs, St, Line, Col, Toks, Ncs, Us) ->
scan_exponent(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs, Us}) ->
scan_exponent(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent([C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_exponent(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_exponent([$_,Next|Cs], St, Line, Col, Toks, [Prev|_]=Ncs, _) when
?DIGIT(Next) andalso ?DIGIT(Prev) ->
scan_exponent(Cs, St, Line, Col, Toks, [Next,$_|Ncs], with_underscore);
scan_exponent([$_]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_exponent/6}};
scan_exponent([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_exponent/6}};
scan_exponent(Cs, St, Line, Col, Toks, Ncs, Us) ->
float_end(Cs, St, Line, Col, Toks, Ncs, Us).
float_end(Cs, St, Line, Col, Toks, Ncs0, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_float(remove_digit_separators(Ncs, Us)) of
F ->
tok3(Cs, St, Line, Col, Toks, float, Ncs, F)
catch
_:_ ->
Ncol = incr_column(Col, length(Ncs)),
scan_error({illegal,float}, Line, Col, Line, Ncol, Cs)
end.
skip_comment_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N) ->
skip_comment(Cs, St, Line, Col, Toks, N).
skip_comment([C|Cs], St, Line, Col, Toks, N) when C =/= $\n, ?CHAR(C) ->
case ?UNICODE(C) of
true ->
skip_comment(Cs, St, Line, Col, Toks, N+1);
false ->
Ncol = incr_column(Col, N+1),
scan_error({illegal,character}, Line, Col, Line, Ncol, Cs)
end;
skip_comment([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun skip_comment_fun/6}};
skip_comment(Cs, St, Line, Col, Toks, N) ->
scan1(Cs, St, Line, incr_column(Col, N), Toks).
scan_comment_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_comment(Cs, St, Line, Col, Toks, Ncs).
scan_comment([C|Cs], St, Line, Col, Toks, Ncs)
when C =/= $\n, ?CHAR(C) ->
case ?UNICODE(C) of
true ->
scan_comment(Cs, St, Line, Col, Toks, [C|Ncs]);
false ->
Ncol = incr_column(Col, length(Ncs)+1),
scan_error({illegal,character}, Line, Col, Line, Ncol, Cs)
end;
scan_comment([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_comment_fun/6}};
scan_comment(Cs, St, Line, Col, Toks, Ncs0) ->
Ncs = lists:reverse(Ncs0),
tok3(Cs, St, Line, Col, Toks, comment, Ncs, Ncs).
scan_check("%%ssa%" ++ Cs, St, Line, Col, Toks, _Ncs) ->
scan_check1(Cs, St, Line, Toks, Col, 7);
scan_check("%%ssa"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%%ss"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%%s"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%%"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%ssa%" ++ Cs, St, Line, Col, Toks, _Ncs) ->
scan_check1(Cs, St, Line, Toks, Col, 6);
scan_check("%ssa"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%ss"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%s"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("ssa%" ++ Cs, St, Line, Col, Toks, _Ncs) ->
scan_check1(Cs, St, Line, Toks, Col, 5);
scan_check("ssa"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("ss"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("s"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check(Cs, St=#erl_scan{comment=true}, Line, Col, Toks, Ncs) ->
scan_comment(Cs, St, Line, Col, Toks, Ncs);
scan_check(Cs, St, Line, Col, Toks, _Ncs) ->
skip_comment(Cs, St, Line, Col, Toks, 1).
scan_check1(Cs, St=#erl_scan{in_check=true}, Line, Toks, Col, NoofCols) ->
%% Skip as we are already in the check mode
scan1(Cs, St, Line, incr_column(Col, NoofCols), Toks);
scan_check1(Cs, St, Line, Toks, Col, NoofCols) ->
tok2(Cs, St#erl_scan{in_check=true}, Line,
ssa% ' , NoofCols ) .
tok2(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, _Wcs, P) ->
scan1(Cs, St, Line, Col, [{P,anno(Line)}|Toks]);
tok2(Cs, #erl_scan{}=St, Line, Col, Toks, Wcs, P) ->
Anno = anno(Line, Col, St, ?STR(P, St, Wcs)),
scan1(Cs, St, Line, incr_column(Col, length(Wcs)), [{P,Anno}|Toks]).
tok2(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, _Wcs, P, _N) ->
scan1(Cs, St, Line, Col, [{P,anno(Line)}|Toks]);
tok2(Cs, #erl_scan{}=St, Line, Col, Toks, Wcs, P, N) ->
Anno = anno(Line, Col, St, ?STR(P,St,Wcs)),
scan1(Cs, St, Line, incr_column(Col, N), [{P,Anno}|Toks]).
tok3(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, Item, _S, Sym) ->
scan1(Cs, St, Line, Col, [{Item,anno(Line),Sym}|Toks]);
tok3(Cs, #erl_scan{}=St, Line, Col, Toks, Item, String, Sym) ->
Token = {Item,anno(Line, Col, St, ?STR(Item, St, String)),Sym},
scan1(Cs, St, Line, incr_column(Col, length(String)), [Token|Toks]).
tok3(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, Item,
_String, Sym, _Length) ->
scan1(Cs, St, Line, Col, [{Item,anno(Line),Sym}|Toks]);
tok3(Cs, #erl_scan{}=St, Line, Col, Toks, Item, String, Sym, Length) ->
Token = {Item,anno(Line, Col, St, ?STR(Item, St, String)),Sym},
scan1(Cs, St, Line, incr_column(Col, Length), [Token|Toks]).
scan_error(Error, Line, Col, EndLine, EndCol, Rest) ->
Loc = location(Line, Col),
EndLoc = location(EndLine, EndCol),
scan_error(Error, Loc, EndLoc, Rest).
scan_error(Error, ErrorLoc, EndLoc, Rest) ->
{{error,{ErrorLoc,?MODULE,Error},EndLoc},Rest}.
-compile({inline,[anno/4]}).
anno(Line, no_col, #erl_scan{has_fun = false}, _String) ->
anno(Line);
anno(Line, no_col, #erl_scan{has_fun = true}, []) ->
anno(Line);
anno(Line, no_col, #erl_scan{has_fun = true}, String) ->
Anno = anno(Line),
erl_anno:set_text(String, Anno);
anno(Line, Col, #erl_scan{has_fun = false}, _String) ->
anno({Line, Col});
anno(Line, Col, #erl_scan{has_fun = true}, []) ->
anno({Line, Col});
anno(Line, Col, #erl_scan{has_fun = true}, String) ->
Anno = anno({Line, Col}),
erl_anno:set_text(String, Anno).
location(Line, no_col) ->
Line;
location(Line, Col) when is_integer(Col) ->
{Line,Col}.
-compile({inline,[anno/1,incr_column/2,new_column/2]}).
anno(Location) ->
erl_anno:new(Location).
incr_column(no_col=Col, _N) ->
Col;
incr_column(Col, N) when is_integer(Col) ->
Col + N.
new_column(no_col=Col, _Ncol) ->
Col;
new_column(Col, Ncol) when is_integer(Col) ->
Ncol.
nl_spcs(2) -> "\n ";
nl_spcs(3) -> "\n ";
nl_spcs(4) -> "\n ";
nl_spcs(5) -> "\n ";
nl_spcs(6) -> "\n ";
nl_spcs(7) -> "\n ";
nl_spcs(8) -> "\n ";
nl_spcs(9) -> "\n ";
nl_spcs(10) -> "\n ";
nl_spcs(11) -> "\n ";
nl_spcs(12) -> "\n ";
nl_spcs(13) -> "\n ";
nl_spcs(14) -> "\n ";
nl_spcs(15) -> "\n ";
nl_spcs(16) -> "\n ";
nl_spcs(17) -> "\n ".
spcs(1) -> " ";
spcs(2) -> " ";
spcs(3) -> " ";
spcs(4) -> " ";
spcs(5) -> " ";
spcs(6) -> " ";
spcs(7) -> " ";
spcs(8) -> " ";
spcs(9) -> " ";
spcs(10) -> " ";
spcs(11) -> " ";
spcs(12) -> " ";
spcs(13) -> " ";
spcs(14) -> " ";
spcs(15) -> " ";
spcs(16) -> " ".
nl_tabs(2) -> "\n\t";
nl_tabs(3) -> "\n\t\t";
nl_tabs(4) -> "\n\t\t\t";
nl_tabs(5) -> "\n\t\t\t\t";
nl_tabs(6) -> "\n\t\t\t\t\t";
nl_tabs(7) -> "\n\t\t\t\t\t\t";
nl_tabs(8) -> "\n\t\t\t\t\t\t\t";
nl_tabs(9) -> "\n\t\t\t\t\t\t\t\t";
nl_tabs(10) -> "\n\t\t\t\t\t\t\t\t\t";
nl_tabs(11) -> "\n\t\t\t\t\t\t\t\t\t\t".
tabs(1) -> "\t";
tabs(2) -> "\t\t";
tabs(3) -> "\t\t\t";
tabs(4) -> "\t\t\t\t";
tabs(5) -> "\t\t\t\t\t";
tabs(6) -> "\t\t\t\t\t\t";
tabs(7) -> "\t\t\t\t\t\t\t";
tabs(8) -> "\t\t\t\t\t\t\t\t";
tabs(9) -> "\t\t\t\t\t\t\t\t\t";
tabs(10) -> "\t\t\t\t\t\t\t\t\t\t".
Dynamic version of reserved_word that knows about the possibility
%% that enabled features might change the set of reserved words.
-spec reserved_word(Atom :: atom()) -> boolean().
reserved_word(Atom) ->
case f_reserved_word(Atom) of
true -> true;
false ->
lists:member(Atom, erl_features:keywords())
end.
Static version of reserved_words . These represent the fixed set of
%% reserved words.
f_reserved_word('after') -> true;
f_reserved_word('begin') -> true;
f_reserved_word('case') -> true;
f_reserved_word('try') -> true;
f_reserved_word('cond') -> true;
f_reserved_word('catch') -> true;
f_reserved_word('andalso') -> true;
f_reserved_word('orelse') -> true;
f_reserved_word('end') -> true;
f_reserved_word('fun') -> true;
f_reserved_word('if') -> true;
f_reserved_word('let') -> true;
f_reserved_word('of') -> true;
f_reserved_word('receive') -> true;
f_reserved_word('when') -> true;
f_reserved_word('bnot') -> true;
f_reserved_word('not') -> true;
f_reserved_word('div') -> true;
f_reserved_word('rem') -> true;
f_reserved_word('band') -> true;
f_reserved_word('and') -> true;
f_reserved_word('bor') -> true;
f_reserved_word('bxor') -> true;
f_reserved_word('bsl') -> true;
f_reserved_word('bsr') -> true;
f_reserved_word('or') -> true;
f_reserved_word('xor') -> true;
f_reserved_word(_) -> false.
| null | https://raw.githubusercontent.com/erlang/otp/1a3e3c492378d119e96a0f24f71b9d0313076447/lib/stdlib/src/erl_scan.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
For handling ISO 8859-1 (Latin-1) we use the following type
information:
Many punctuation characters have special meaning:
$\s, $_, $", $$, $%, $', $.
Must watch using × \327, very close to x \170.
External exports
Private
Removed functions and types
Defines and type definitions
Local record.
True if requested to parse %ssa%-check comments
True if we're scanning inside a %ssa%-check comment
----------------------------------------------------------------------------
Local functions
Optimization: some very common punctuation characters:
More punctuation characters below.
?= for the maybe ... else ... end construct
<< <- <=
>> >=
-> --
++
=:= =/= =< == =>
/=
||
:=
:: for typed records
End of optimization.
White space characters are very common, so it is worthwhile to
scan them fast and store them compactly. (The words "whitespace"
specification denotes the characters with ASCII code in the
Convention: if there is a white newline ($\n) it will always be
Some common combinations are recognized, some are not. Examples
of the latter are tab(s) followed by space(s), like "\t ".
Note: the character sequence "\r\n" is *not* recognized since it
character. (But since "\r\n\r\n" is common, it pays off to
Note: returning {more,Cont} is meaningless here; one could just as
well return several tokens. But since tokens() scans up to a full
stop anyway, nothing is gained by not collecting all white spaces.
"
"
Expanded escape chars.
'
Expanded escape chars.
'
Optimization. Col =:= no_col.
Optimization. Col =/= no_col.
Note: in those cases when a 'char_error' tuple is returned below it
but then the end location of the error tuple would not correspond
to the start location of the returned Rest string. (Maybe the end
location could be modified, but that too is ugly.)
\<1-3> octal digits
\x{<hex digits>}
\x<2> hexadecimal digits
\^X -> Control-X
Empty escape sequence.
Extremely unlikely to occur in practice.
\n = LF
\t = TAB
\b = BS
\f = FF
\e = ESC
\s = SPC
Extremely unlikely to occur in practice.
Extremely unlikely to occur in practice.
No actual digits following the base.
Extremely unlikely to occur in practice.
Skip as we are already in the check mode
' , NoofCols ) .
that enabled features might change the set of reserved words.
reserved words. | Copyright Ericsson AB 1996 - 2022 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
Erlang token scanning functions of io library .
000 - 037 NUL - US control
040 - 057 SPC - / punctuation
060 - 071 0 - 9 digit
072 - 100 : - @ punctuation
101 - 132 A - Z uppercase
133 - 140 [ - ` punctuation
141 - 172 a - z lowercase
173 - 176 { - ~ punctuation
177 DEL control
200 - 237 control
240 - 277 NBSP - ¿ punctuation
300 - 326 À - Ö uppercase
327 × punctuation
330 - 336 Ø - Þ uppercase
337 - 366 ß - ö lowercase
367 ÷ punctuation
370 - 377 ø - ÿ lowercase
DEL is a punctuation .
-module(erl_scan).
-export([string/1,string/2,string/3,tokens/3,tokens/4,
format_error/1,reserved_word/1,
f_reserved_word/1]).
-export([column/1,end_location/1,line/1,location/1,text/1,
category/1,symbol/1]).
-export([continuation_location/1]).
-export_type([error_info/0,
options/0,
return_cont/0,
token/0, tokens/0,
tokens_result/0]).
-removed([{set_attribute,3,"use erl_anno:set_line/2 instead"},
{attributes_info,'_',
"use erl_anno:{column,line,location,text}/1 instead"},
{token_info,'_',
"use erl_scan:{category,column,line,location,symbol,text}/1 instead"}]).
-removed_type([{column,0,"use erl_anno:column() instead"},
{line,0,"use erl_anno:line() instead"},
{location,0,"use erl_anno:location() instead"}]).
-define(COLUMN(C), (is_integer(C) andalso C >= 1)).
Line numbers less than zero have always been allowed :
-define(ALINE(L), is_integer(L)).
-define(STRING(S), is_list(S)).
-define(RESWORDFUN(F), is_function(F, 1)).
-type category() :: atom().
-type resword_fun() :: fun((atom()) -> boolean()).
-type text_fun() :: fun((atom(), string()) -> boolean()).
-type option() :: 'return' | 'return_white_spaces' | 'return_comments'
| 'text' | {'reserved_word_fun', resword_fun()}
| {'text_fun', text_fun()} | {'compiler_internal', [term()]}.
-type options() :: option() | [option()].
-type symbol() :: atom() | float() | integer() | string().
-type token() :: {category(), Anno :: erl_anno:anno(), symbol()}
| {category(), Anno :: erl_anno:anno()}.
-type tokens() :: [token()].
-type error_description() :: term().
-type error_info() :: {erl_anno:location(), module(), error_description()}.
-record(erl_scan,
{resword_fun = fun reserved_word/1 :: resword_fun(),
text_fun = fun(_, _) -> false end :: text_fun(),
ws = false :: boolean(),
comment = false :: boolean(),
has_fun = false :: boolean(),
checks = false :: boolean(),
in_check = false :: boolean()}).
-spec format_error(ErrorDescriptor) -> string() when
ErrorDescriptor :: error_description().
format_error({string,Quote,Head}) ->
lists:flatten(["unterminated " ++ string_thing(Quote) ++
" starting with " ++
io_lib:write_string(Head, Quote)]);
format_error({illegal,Type}) ->
lists:flatten(io_lib:fwrite("illegal ~w", [Type]));
format_error(char) -> "unterminated character";
format_error({base,Base}) ->
lists:flatten(io_lib:fwrite("illegal base '~w'", [Base]));
format_error(Other) ->
lists:flatten(io_lib:write(Other)).
-spec string(String) -> Return when
String :: string(),
Return :: {'ok', Tokens :: tokens(), EndLocation}
| {'error', ErrorInfo :: error_info(), ErrorLocation},
EndLocation :: erl_anno:location(),
ErrorLocation :: erl_anno:location().
string(String) ->
string(String, 1, []).
-spec string(String, StartLocation) -> Return when
String :: string(),
Return :: {'ok', Tokens :: tokens(), EndLocation}
| {'error', ErrorInfo :: error_info(), ErrorLocation},
StartLocation :: erl_anno:location(),
EndLocation :: erl_anno:location(),
ErrorLocation :: erl_anno:location().
string(String, StartLocation) ->
string(String, StartLocation, []).
-spec string(String, StartLocation, Options) -> Return when
String :: string(),
Options :: options(),
Return :: {'ok', Tokens :: tokens(), EndLocation}
| {'error', ErrorInfo :: error_info(), ErrorLocation},
StartLocation :: erl_anno:location(),
EndLocation :: erl_anno:location(),
ErrorLocation :: erl_anno:location().
string(String, Line, Options) when ?STRING(String), ?ALINE(Line) ->
string1(String, options(Options), Line, no_col, []);
string(String, {Line,Column}, Options) when ?STRING(String),
?ALINE(Line),
?COLUMN(Column) ->
string1(String, options(Options), Line, Column, []).
-type char_spec() :: string() | 'eof'.
-type cont_fun() :: fun((char_spec(), #erl_scan{},
erl_anno:line(), erl_anno:column(),
tokens(), any()) -> any()).
-opaque return_cont() :: {erl_scan_continuation,
string(), erl_anno:column(), tokens(),
erl_anno:line(),
#erl_scan{}, any(), cont_fun()}.
-type tokens_result() :: {'ok', Tokens :: tokens(),
EndLocation :: erl_anno:location()}
| {'eof', EndLocation :: erl_anno:location()}
| {'error', ErrorInfo :: error_info(),
EndLocation :: erl_anno:location()}.
-spec tokens(Continuation, CharSpec, StartLocation) -> Return when
Continuation :: return_cont() | [],
CharSpec :: char_spec(),
StartLocation :: erl_anno:location(),
Return :: {'done',Result :: tokens_result(),LeftOverChars :: char_spec()}
| {'more', Continuation1 :: return_cont()}.
tokens(Cont, CharSpec, StartLocation) ->
tokens(Cont, CharSpec, StartLocation, []).
-spec tokens(Continuation, CharSpec, StartLocation, Options) -> Return when
Continuation :: return_cont() | [],
CharSpec :: char_spec(),
StartLocation :: erl_anno:location(),
Options :: options(),
Return :: {'done',Result :: tokens_result(),LeftOverChars :: char_spec()}
| {'more', Continuation1 :: return_cont()}.
tokens([], CharSpec, Line, Options) when ?ALINE(Line) ->
tokens1(CharSpec, options(Options), Line, no_col, [], fun scan/6, []);
tokens([], CharSpec, {Line,Column}, Options) when ?ALINE(Line),
?COLUMN(Column) ->
tokens1(CharSpec, options(Options), Line, Column, [], fun scan/6, []);
tokens({erl_scan_continuation,Cs,Col,Toks,Line,St,Any,Fun},
CharSpec, _Loc, _Opts) ->
tokens1(Cs++CharSpec, St, Line, Col, Toks, Fun, Any).
continuation_location({erl_scan_continuation,_,no_col,_,Line,_,_,_}) ->
Line;
continuation_location({erl_scan_continuation,_,Col,_,Line,_,_,_}) ->
{Line,Col}.
-spec column(Token) -> erl_anno:column() | 'undefined' when
Token :: token().
column(Token) ->
erl_anno:column(element(2, Token)).
-spec end_location(Token) -> erl_anno:location() | 'undefined' when
Token :: token().
end_location(Token) ->
erl_anno:end_location(element(2, Token)).
-spec line(Token) -> erl_anno:line() when
Token :: token().
line(Token) ->
erl_anno:line(element(2, Token)).
-spec location(Token) -> erl_anno:location() when
Token :: token().
location(Token) ->
erl_anno:location(element(2, Token)).
-spec text(Token) -> erl_anno:text() | 'undefined' when
Token :: token().
text(Token) ->
erl_anno:text(element(2, Token)).
-spec category(Token) -> category() when
Token :: token().
category({Category,_Anno}) ->
Category;
category({Category,_Anno,_Symbol}) ->
Category;
category(T) ->
erlang:error(badarg, [T]).
-spec symbol(Token) -> symbol() when
Token :: token().
symbol({Category,_Anno}) ->
Category;
symbol({_Category,_Anno,Symbol}) ->
Symbol;
symbol(T) ->
erlang:error(badarg, [T]).
' Stupid Emacs
string_thing(_) -> "string".
-define(WHITE_SPACE(C),
is_integer(C) andalso
(C >= $\000 andalso C =< $\s orelse C >= $\200 andalso C =< $\240)).
-define(DIGIT(C), (is_integer(C) andalso $0 =< C andalso C =< $9)).
-define(CHAR(C), (is_integer(C) andalso 0 =< C andalso C < 16#110000)).
-define(UNICODE(C),
(is_integer(C) andalso
(C >= 0 andalso C < 16#D800 orelse
C > 16#DFFF andalso C < 16#FFFE orelse
C > 16#FFFF andalso C =< 16#10FFFF))).
-define(UNI255(C), (is_integer(C) andalso 0 =< C andalso C =< 16#ff)).
options(Opts0) when is_list(Opts0) ->
Opts = lists:foldr(fun expand_opt/2, [], Opts0),
[RW_fun] =
case opts(Opts, [reserved_word_fun], []) of
badarg ->
erlang:error(badarg, [Opts0]);
R ->
R
end,
Comment = proplists:get_bool(return_comments, Opts),
WS = proplists:get_bool(return_white_spaces, Opts),
Txt = proplists:get_bool(text, Opts),
TxtFunOpt = proplists:get_value(text_fun, Opts, none),
Internal = proplists:get_value(compiler_internal, Opts, []),
Checks = proplists:get_bool(ssa_checks, Internal),
DefTxtFun = fun(_, _) -> Txt end,
{HasFun, TxtFun} =
if
Txt -> {Txt, DefTxtFun};
TxtFunOpt == none -> {Txt, DefTxtFun};
true -> {true, TxtFunOpt}
end,
#erl_scan{resword_fun = RW_fun,
comment = Comment,
ws = WS,
text_fun = TxtFun,
has_fun = HasFun,
checks = Checks};
options(Opt) ->
options([Opt]).
opts(Options, [Key|Keys], L) ->
V = case lists:keyfind(Key, 1, Options) of
{reserved_word_fun,F} when ?RESWORDFUN(F) ->
{ok,F};
{Key,_} ->
badarg;
false ->
{ok,default_option(Key)}
end,
case V of
badarg ->
badarg;
{ok,Value} ->
opts(Options, Keys, [Value|L])
end;
opts(_Options, [], L) ->
lists:reverse(L).
default_option(reserved_word_fun) ->
fun reserved_word/1.
expand_opt(return, Os) ->
[return_comments,return_white_spaces|Os];
expand_opt(O, Os) ->
[O|Os].
tokens1(Cs, St, Line, Col, Toks, Fun, Any) when ?STRING(Cs); Cs =:= eof ->
case Fun(Cs, St, Line, Col, Toks, Any) of
{more,{Cs0,Nst,Ncol,Ntoks,Nline,Nany,Nfun}} ->
{more,{erl_scan_continuation,Cs0,Ncol,Ntoks,Nline,Nst,Nany,Nfun}};
{ok,Toks0,eof,Nline,Ncol} ->
Res = case Toks0 of
[] ->
{eof,location(Nline, Ncol)};
_ ->
{ok,lists:reverse(Toks0),location(Nline,Ncol)}
end,
{done,Res,eof};
{ok,Toks0,Rest,Nline,Ncol} ->
{done,{ok,lists:reverse(Toks0),location(Nline, Ncol)},Rest};
{{error,_,_}=Error,Rest} ->
{done,Error,Rest}
end.
string1(Cs, St, Line, Col, Toks) ->
case scan1(Cs, St, Line, Col, Toks) of
{more,{Cs0,Nst,Ncol,Ntoks,Nline,Any,Fun}} ->
case Fun(Cs0++eof, Nst, Nline, Ncol, Ntoks, Any) of
{ok,Toks1,_Rest,Line2,Col2} ->
{ok,lists:reverse(Toks1),location(Line2, Col2)};
{{error,_,_}=Error,_Rest} ->
Error
end;
{ok,Ntoks,[_|_]=Rest,Nline,Ncol} ->
string1(Rest, St, Nline, Ncol, Ntoks);
{ok,Ntoks,_,Nline,Ncol} ->
{ok,lists:reverse(Ntoks),location(Nline, Ncol)};
{{error,_,_}=Error,_Rest} ->
Error
end.
scan(Cs, #erl_scan{}=St, Line, Col, Toks, _) ->
scan1(Cs, St, Line, Col, Toks).
scan1([$\s|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
scan_spcs(Cs, St, Line, Col, Toks, 1);
scan1([$\s|Cs], St, Line, Col, Toks) ->
skip_white_space(Cs, St, Line, Col, Toks, 1);
scan1([$\n|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
scan_newline(Cs, St, Line, Col, Toks);
scan1([$\n|Cs], St, Line, Col, Toks) ->
skip_white_space(Cs, St, Line+1, new_column(Col, 1), Toks, 0);
scan1([$,|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ",", ',', 1);
scan1([$(|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "(", '(', 1);
scan1([$)|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ")", ')', 1);
scan1([${|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "{", '{', 1);
scan1([$}|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "}", '}', 1);
scan1([$[|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "[", '[', 1);
scan1([$]|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "]", ']', 1);
scan1([$;|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ";", ';', 1);
scan1([$_=C|Cs], St, Line, Col, Toks) ->
scan_variable(Cs, St, Line, Col, Toks, [C]);
= C|Cs ] , St , Line , Col , Toks ) when St#erl_scan.checks - >
scan_check(Cs, St, Line, Col, Toks, [C]);
|Cs ] , St , Line , Col , Toks ) when not St#erl_scan.comment - >
skip_comment(Cs, St, Line, Col, Toks, 1);
= C|Cs ] , St , Line , Col , Toks ) - >
scan_comment(Cs, St, Line, Col, Toks, [C]);
scan1([C|_], _St, _Line, _Col0, _Toks) when not ?CHAR(C) ->
error({not_character,C});
scan1([C|Cs], St, Line, Col, Toks) when C >= $A, C =< $Z ->
scan_variable(Cs, St, Line, Col, Toks, [C]);
scan1([C|Cs], St, Line, Col, Toks) when C >= $a, C =< $z ->
scan_atom(Cs, St, Line, Col, Toks, [C]);
scan1([C|Cs], St, Line, Col, Toks) when ?DIGIT(C) ->
scan_number(Cs, St, Line, Col, Toks, [C], no_underscore);
scan1("..."++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "...", '...', 3);
scan1(".."=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1(".."++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "..", '..', 2);
scan1("."=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1([$.=C|Cs], St, Line, Col, Toks) ->
scan_dot(Cs, St, Line, Col, Toks, [C]);
scan1([$"|Cs], St, Line, Col, Toks) -> %" Emacs
State0 = {[],[],Line,Col},
scan_string(Cs, St, Line, incr_column(Col, 1), Toks, State0);
' Emacs
State0 = {[],[],Line,Col},
scan_qatom(Cs, St, Line, incr_column(Col, 1), Toks, State0);
scan1([$$|Cs], St, Line, Col, Toks) ->
scan_char(Cs, St, Line, Col, Toks);
scan1([$\r|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
white_space_end(Cs, St, Line, Col, Toks, 1, "\r");
scan1([C|Cs], St, Line, Col, Toks) when C >= $ß, C =< $ÿ, C =/= $÷ ->
scan_atom(Cs, St, Line, Col, Toks, [C]);
scan1([C|Cs], St, Line, Col, Toks) when C >= $À, C =< $Þ, C /= $× ->
scan_variable(Cs, St, Line, Col, Toks, [C]);
scan1([$\t|Cs], St, Line, Col, Toks) when St#erl_scan.ws ->
scan_tabs(Cs, St, Line, Col, Toks, 1);
scan1([$\t|Cs], St, Line, Col, Toks) ->
skip_white_space(Cs, St, Line, Col, Toks, 1);
scan1([C|Cs], St, Line, Col, Toks) when ?WHITE_SPACE(C) ->
case St#erl_scan.ws of
true ->
scan_white_space(Cs, St, Line, Col, Toks, [C]);
false ->
skip_white_space(Cs, St, Line, Col, Toks, 1)
end;
Punctuation characters and operators , first recognise multiples .
scan1("?="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "?=", '?=', 2);
scan1("?"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("<<"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<<", '<<', 2);
scan1("<-"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<-", '<-', 2);
scan1("<="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<=", '<=', 2);
scan1("<"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1(">>"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ">>", '>>', 2);
scan1(">="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ">=", '>=', 2);
scan1(">"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("->"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "->", '->', 2);
scan1("--"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "--", '--', 2);
scan1("-"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("++"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "++", '++', 2);
scan1("+"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("=:="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=:=", '=:=', 3);
scan1("=:"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("=/="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=/=", '=/=', 3);
scan1("=/"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("=<"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=<", '=<', 2);
scan1("=>"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=>", '=>', 2);
scan1("=="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "==", '==', 2);
scan1("="=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("/="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "/=", '/=', 2);
scan1("/"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1("||"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "||", '||', 2);
scan1("|"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1(":="++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ":=", ':=', 2);
scan1("::"++Cs, St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "::", '::', 2);
scan1(":"=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
Optimization : punctuation characters less than 127 :
scan1([$=|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "=", '=', 1);
scan1([$:|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ":", ':', 1);
scan1([$||Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "|", '|', 1);
scan1([$#|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "#", '#', 1);
scan1([$/|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "/", '/', 1);
scan1([$?|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "?", '?', 1);
scan1([$-|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "-", '-', 1);
scan1([$+|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "+", '+', 1);
scan1([$*|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "*", '*', 1);
scan1([$<|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "<", '<', 1);
scan1([$>|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, ">", '>', 1);
scan1([$!|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "!", '!', 1);
scan1([$@|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "@", '@', 1);
scan1([$\\|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "\\", '\\', 1);
scan1([$^|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "^", '^', 1);
scan1([$`|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "`", '`', 1);
scan1([$~|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "~", '~', 1);
scan1([$&|Cs], St, Line, Col, Toks) ->
tok2(Cs, St, Line, Col, Toks, "&", '&', 1);
scan1([C|Cs], St, Line, Col, Toks) when ?UNI255(C) ->
Str = [C],
tok2(Cs, St, Line, Col, Toks, Str, list_to_atom(Str), 1);
scan1([C|Cs], _St, Line, Col, _Toks) when ?CHAR(C) ->
Ncol = incr_column(Col, 1),
scan_error({illegal,character}, Line, Col, Line, Ncol, Cs);
scan1([]=Cs, St, Line, Col, Toks) ->
{more,{Cs,St,Col,Toks,Line,[],fun scan/6}};
scan1(eof=Cs, _St, Line, Col, Toks) ->
{ok,Toks,Cs,Line,Col}.
scan_atom_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_atom(Cs, St, Line, Col, Toks, Ncs).
scan_atom(Cs0, St, Line, Col, Toks, Ncs0) ->
case scan_name(Cs0, Ncs0) of
{more,Ncs} ->
{more,{[],St,Col,Toks,Line,Ncs,fun scan_atom_fun/6}};
{Wcs,Cs} ->
try list_to_atom(Wcs) of
Name ->
case (St#erl_scan.resword_fun)(Name) of
true ->
tok2(Cs, St, Line, Col, Toks, Wcs, Name);
false ->
tok3(Cs, St, Line, Col, Toks, atom, Wcs, Name)
end
catch
_:_ ->
Ncol = incr_column(Col, length(Wcs)),
scan_error({illegal,atom}, Line, Col, Line, Ncol, Cs)
end
end.
scan_variable_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_variable(Cs, St, Line, Col, Toks, Ncs).
scan_variable(Cs0, St, Line, Col, Toks, Ncs0) ->
case scan_name(Cs0, Ncs0) of
{more,Ncs} ->
{more,{[],St,Col,Toks,Line,Ncs,fun scan_variable_fun/6}};
{Wcs,Cs} ->
try list_to_atom(Wcs) of
Name ->
tok3(Cs, St, Line, Col, Toks, var, Wcs, Name)
catch
_:_ ->
Ncol = incr_column(Col, length(Wcs)),
scan_error({illegal,var}, Line, Col, Line, Ncol, Cs)
end
end.
scan_name([C|_]=Cs, Ncs) when not ?CHAR(C) ->
{lists:reverse(Ncs),Cs};
scan_name([C|Cs], Ncs) when C >= $a, C =< $z ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when C >= $A, C =< $Z ->
scan_name(Cs, [C|Ncs]);
scan_name([$_=C|Cs], Ncs) ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when ?DIGIT(C) ->
scan_name(Cs, [C|Ncs]);
scan_name([$@=C|Cs], Ncs) ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when C >= $ß, C =< $ÿ, C =/= $÷ ->
scan_name(Cs, [C|Ncs]);
scan_name([C|Cs], Ncs) when C >= $À, C =< $Þ, C =/= $× ->
scan_name(Cs, [C|Ncs]);
scan_name([], Ncs) ->
{more,Ncs};
scan_name(Cs, Ncs) ->
{lists:reverse(Ncs),Cs}.
-define(STR(Cl, St, S),
case (St#erl_scan.has_fun)
andalso (St#erl_scan.text_fun)(Cl, S) of
true -> S;
false -> []
end).
scan_dot([C|_]=Cs, St, Line, Col, Toks, Ncs)
when St#erl_scan.in_check, C =/= $. ->
tok2(Cs, St#erl_scan{in_check=false}, Line, Col, Toks, Ncs, '.', 1);
|_]=Cs , St , Line , Col , Toks , Ncs ) - >
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs)),
{ok,[{dot,Anno}|Toks],Cs,Line,incr_column(Col, 1)};
scan_dot([$\n=C|Cs], St, Line, Col, Toks, Ncs) ->
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs++[C])),
{ok,[{dot,Anno}|Toks],Cs,Line+1,new_column(Col, 1)};
scan_dot([C|Cs], St, Line, Col, Toks, Ncs) when ?WHITE_SPACE(C) ->
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs++[C])),
{ok,[{dot,Anno}|Toks],Cs,Line,incr_column(Col, 2)};
scan_dot(eof=Cs, St, Line, Col, Toks, Ncs) ->
Anno = anno(Line, Col, St, ?STR(dot, St, Ncs)),
{ok,[{dot,Anno}|Toks],Cs,Line,incr_column(Col, 1)};
scan_dot(Cs, St, Line, Col, Toks, Ncs) ->
tok2(Cs, St, Line, Col, Toks, Ncs, '.', 1).
and " white space " usually mean the same thing . The Erlang
interval 0 to 32 as " white space " . )
the first character in the text string . As a consequence , there
can not be more than one newline in a white_space token string .
( They will be represented by two ( or more ) tokens . )
would violate the property that $ \n will always be the first
recognize " " . )
scan_newline([$\s|Cs], St, Line, Col, Toks) ->
scan_nl_spcs(Cs, St, Line, Col, Toks, 2);
scan_newline([$\t|Cs], St, Line, Col, Toks) ->
scan_nl_tabs(Cs, St, Line, Col, Toks, 2);
scan_newline([$\r|Cs], St, Line, Col, Toks) ->
newline_end(Cs, St, Line, Col, Toks, 2, "\n\r");
scan_newline([$\f|Cs], St, Line, Col, Toks) ->
newline_end(Cs, St, Line, Col, Toks, 2, "\n\f");
scan_newline([], St, Line, Col, Toks) ->
{more,{[$\n],St,Col,Toks,Line,[],fun scan/6}};
scan_newline(Cs, St, Line, Col, Toks) ->
scan_nl_white_space(Cs, St, Line, Col, Toks, "\n").
scan_nl_spcs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N) ->
scan_nl_spcs(Cs, St, Line, Col, Toks, N).
scan_nl_spcs([$\s|Cs], St, Line, Col, Toks, N) when N < 17 ->
scan_nl_spcs(Cs, St, Line, Col, Toks, N+1);
scan_nl_spcs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_nl_spcs_fun/6}};
scan_nl_spcs(Cs, St, Line, Col, Toks, N) ->
newline_end(Cs, St, Line, Col, Toks, N, nl_spcs(N)).
scan_nl_tabs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N) ->
scan_nl_tabs(Cs, St, Line, Col, Toks, N).
scan_nl_tabs([$\t|Cs], St, Line, Col, Toks, N) when N < 11 ->
scan_nl_tabs(Cs, St, Line, Col, Toks, N+1);
scan_nl_tabs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_nl_tabs_fun/6}};
scan_nl_tabs(Cs, St, Line, Col, Toks, N) ->
newline_end(Cs, St, Line, Col, Toks, N, nl_tabs(N)).
scan_nl_white_space_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_nl_white_space(Cs, St, Line, Col, Toks, Ncs).
scan_nl_white_space([$\n|Cs], #erl_scan{has_fun = false}=St, Line, no_col=Col,
Toks0, Ncs) ->
Toks = [{white_space,anno(Line),lists:reverse(Ncs)}|Toks0],
scan_newline(Cs, St, Line+1, Col, Toks);
scan_nl_white_space([$\n|Cs], St, Line, Col, Toks, Ncs0) ->
Ncs = lists:reverse(Ncs0),
Anno = anno(Line, Col, St, ?STR(white_space, St, Ncs)),
Token = {white_space,Anno,Ncs},
scan_newline(Cs, St, Line+1, new_column(Col, length(Ncs)), [Token|Toks]);
scan_nl_white_space([C|Cs], St, Line, Col, Toks, Ncs)
when ?WHITE_SPACE(C) ->
scan_nl_white_space(Cs, St, Line, Col, Toks, [C|Ncs]);
scan_nl_white_space([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_nl_white_space_fun/6}};
scan_nl_white_space(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col,
Toks, Ncs) ->
Anno = anno(Line),
scan1(Cs, St, Line+1, Col, [{white_space,Anno,lists:reverse(Ncs)}|Toks]);
scan_nl_white_space(Cs, St, Line, Col, Toks, Ncs0) ->
Ncs = lists:reverse(Ncs0),
Anno = anno(Line, Col, St, ?STR(white_space, St, Ncs)),
Token = {white_space,Anno,Ncs},
scan1(Cs, St, Line+1, new_column(Col, length(Ncs)), [Token|Toks]).
newline_end(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col,
Toks, _N, Ncs) ->
scan1(Cs, St, Line+1, Col, [{white_space,anno(Line),Ncs}|Toks]);
newline_end(Cs, #erl_scan{}=St, Line, Col, Toks, N, Ncs) ->
Anno = anno(Line, Col, St, ?STR(white_space, St, Ncs)),
scan1(Cs, St, Line+1, new_column(Col, N), [{white_space,Anno,Ncs}|Toks]).
scan_spcs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N), N >= 1 ->
scan_spcs(Cs, St, Line, Col, Toks, N).
scan_spcs([$\s|Cs], St, Line, Col, Toks, N) when N < 16 ->
scan_spcs(Cs, St, Line, Col, Toks, N+1);
scan_spcs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_spcs_fun/6}};
scan_spcs(Cs, St, Line, Col, Toks, N) ->
white_space_end(Cs, St, Line, Col, Toks, N, spcs(N)).
scan_tabs_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N)
when is_integer(N), N >= 1 ->
scan_tabs(Cs, St, Line, Col, Toks, N).
scan_tabs([$\t|Cs], St, Line, Col, Toks, N) when N < 10 ->
scan_tabs(Cs, St, Line, Col, Toks, N+1);
scan_tabs([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun scan_tabs_fun/6}};
scan_tabs(Cs, St, Line, Col, Toks, N) ->
white_space_end(Cs, St, Line, Col, Toks, N, tabs(N)).
skip_white_space_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N) ->
skip_white_space(Cs, St, Line, Col, Toks, N).
skip_white_space([$\n|Cs], St, Line, Col, Toks, _N) ->
skip_white_space(Cs, St, Line+1, new_column(Col, 1), Toks, 0);
skip_white_space([C|Cs], St, Line, Col, Toks, N) when ?WHITE_SPACE(C) ->
skip_white_space(Cs, St, Line, Col, Toks, N+1);
skip_white_space([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun skip_white_space_fun/6}};
skip_white_space(Cs, St, Line, Col, Toks, N) ->
scan1(Cs, St, Line, incr_column(Col, N), Toks).
scan_white_space_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_white_space(Cs, St, Line, Col, Toks, Ncs).
Maybe \t and \s should break the loop .
scan_white_space([$\n|_]=Cs, St, Line, Col, Toks, Ncs) ->
white_space_end(Cs, St, Line, Col, Toks, length(Ncs), lists:reverse(Ncs));
scan_white_space([C|Cs], St, Line, Col, Toks, Ncs) when ?WHITE_SPACE(C) ->
scan_white_space(Cs, St, Line, Col, Toks, [C|Ncs]);
scan_white_space([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_white_space_fun/6}};
scan_white_space(Cs, St, Line, Col, Toks, Ncs) ->
white_space_end(Cs, St, Line, Col, Toks, length(Ncs), lists:reverse(Ncs)).
-compile({inline,[white_space_end/7]}).
white_space_end(Cs, St, Line, Col, Toks, N, Ncs) ->
tok3(Cs, St, Line, Col, Toks, white_space, Ncs, Ncs, N).
scan_char([$\\|Cs]=Cs0, St, Line, Col, Toks) ->
case scan_escape(Cs, incr_column(Col, 2)) of
more ->
{more,{[$$|Cs0],St,Col,Toks,Line,[],fun scan/6}};
{error,Ncs,Error,Ncol} ->
scan_error(Error, Line, Col, Line, Ncol, Ncs);
{eof,Ncol} ->
scan_error(char, Line, Col, Line, Ncol, eof);
{nl,Val,Str,Ncs,Ncol} ->
Ntoks = [{char,Anno,Val}|Toks],
scan1(Ncs, St, Line+1, Ncol, Ntoks);
{Val,Str,Ncs,Ncol} ->
Ntoks = [{char,Anno,Val}|Toks],
scan1(Ncs, St, Line, Ncol, Ntoks)
end;
scan_char([$\n=C|Cs], St, Line, Col, Toks) ->
Anno = anno(Line, Col, St, ?STR(char, St, [$$,C])),
scan1(Cs, St, Line+1, new_column(Col, 1), [{char,Anno,C}|Toks]);
scan_char([C|Cs], St, Line, Col, Toks) when ?UNICODE(C) ->
Anno = anno(Line, Col, St, ?STR(char, St, [$$,C])),
scan1(Cs, St, Line, incr_column(Col, 2), [{char,Anno,C}|Toks]);
scan_char([C|_Cs], _St, Line, Col, _Toks) when ?CHAR(C) ->
scan_error({illegal,character}, Line, Col, Line, incr_column(Col, 1), eof);
scan_char([], St, Line, Col, Toks) ->
{more,{[$$],St,Col,Toks,Line,[],fun scan/6}};
scan_char(eof, _St, Line, Col, _Toks) ->
scan_error(char, Line, Col, Line, incr_column(Col, 1), eof).
scan_string(Cs, #erl_scan{}=St, Line, Col, Toks, {Wcs,Str,Line0,Col0}) ->
case scan_string0(Cs, St, Line, Col, $\", Str, Wcs) of %"
{more,Ncs,Nline,Ncol,Nstr,Nwcs} ->
State = {Nwcs,Nstr,Line0,Col0},
{more,{Ncs,St,Ncol,Toks,Nline,State,fun scan_string/6}};
{char_error,Ncs,Error,Nline,Ncol,EndCol} ->
scan_error(Error, Nline, Ncol, Nline, EndCol, Ncs);
{error,Nline,Ncol,Nwcs,Ncs} ->
scan_error({string,$\",Estr}, Line0, Col0, Nline, Ncol, Ncs); %"
{Ncs,Nline,Ncol,Nstr,Nwcs} ->
Anno = anno(Line0, Col0, St, ?STR(string, St, Nstr)),
scan1(Ncs, St, Nline, Ncol, [{string,Anno,Nwcs}|Toks])
end.
scan_qatom(Cs, #erl_scan{}=St, Line, Col, Toks, {Wcs,Str,Line0,Col0}) ->
{more,Ncs,Nline,Ncol,Nstr,Nwcs} ->
State = {Nwcs,Nstr,Line0,Col0},
{more,{Ncs,St,Ncol,Toks,Nline,State,fun scan_qatom/6}};
{char_error,Ncs,Error,Nline,Ncol,EndCol} ->
scan_error(Error, Nline, Ncol, Nline, EndCol, Ncs);
{error,Nline,Ncol,Nwcs,Ncs} ->
{Ncs,Nline,Ncol,Nstr,Nwcs} ->
try list_to_atom(Nwcs) of
A when is_atom(A) ->
Anno = anno(Line0, Col0, St, ?STR(atom, St, Nstr)),
scan1(Ncs, St, Nline, Ncol, [{atom,Anno,A}|Toks])
catch
_:_ ->
scan_error({illegal,atom}, Line0, Col0, Nline, Ncol, Ncs)
end
end.
scan_string0(Cs, #erl_scan{has_fun=false}, Line, no_col=Col, Q, [], Wcs) ->
scan_string_no_col(Cs, Line, Col, Q, Wcs);
scan_string0(Cs, #erl_scan{has_fun=true}, Line, no_col=Col, Q, Str, Wcs) ->
scan_string1(Cs, Line, Col, Q, Str, Wcs);
scan_string0(Cs, St, Line, Col, Q, [], Wcs) ->
scan_string_col(Cs, St, Line, Col, Q, Wcs);
scan_string0(Cs, _St, Line, Col, Q, Str, Wcs) ->
scan_string1(Cs, Line, Col, Q, Str, Wcs).
scan_string_no_col([Q|Cs], Line, Col, Q, Wcs) ->
{Cs,Line,Col,_DontCare=[],lists:reverse(Wcs)};
scan_string_no_col([$\n=C|Cs], Line, Col, Q, Wcs) ->
scan_string_no_col(Cs, Line+1, Col, Q, [C|Wcs]);
scan_string_no_col([C|Cs], Line, Col, Q, Wcs) when C =/= $\\, ?UNICODE(C) ->
scan_string_no_col(Cs, Line, Col, Q, [C|Wcs]);
scan_string_no_col(Cs, Line, Col, Q, Wcs) ->
scan_string1(Cs, Line, Col, Q, Wcs, Wcs).
scan_string_col([Q|Cs], St, Line, Col, Q, Wcs0) ->
Wcs = lists:reverse(Wcs0),
Str = ?STR(atom, St, [Q|Wcs++[Q]]),
{Cs,Line,Col+1,Str,Wcs};
scan_string_col([$\n=C|Cs], St, Line, _xCol, Q, Wcs) ->
scan_string_col(Cs, St, Line+1, 1, Q, [C|Wcs]);
scan_string_col([C|Cs], St, Line, Col, Q, Wcs) when C =/= $\\, ?UNICODE(C) ->
scan_string_col(Cs, St, Line, Col+1, Q, [C|Wcs]);
scan_string_col(Cs, _St, Line, Col, Q, Wcs) ->
scan_string1(Cs, Line, Col, Q, Wcs, Wcs).
is tempting to skip over characters up to the first Q character ,
scan_string1([Q|Cs], Line, Col, Q, Str0, Wcs0) ->
Wcs = lists:reverse(Wcs0),
Str = [Q|lists:reverse(Str0, [Q])],
{Cs,Line,incr_column(Col, 1),Str,Wcs};
scan_string1([$\n=C|Cs], Line, Col, Q, Str, Wcs) ->
Ncol = new_column(Col, 1),
scan_string1(Cs, Line+1, Ncol, Q, [C|Str], [C|Wcs]);
scan_string1([$\\|Cs]=Cs0, Line, Col, Q, Str, Wcs) ->
case scan_escape(Cs, Col) of
more ->
{more,Cs0,Line,Col,Str,Wcs};
{error,Ncs,Error,Ncol} ->
{char_error,Ncs,Error,Line,Col,incr_column(Ncol, 1)};
{eof,Ncol} ->
{error,Line,incr_column(Ncol, 1),lists:reverse(Wcs),eof};
{nl,Val,ValStr,Ncs,Ncol} ->
Nstr = lists:reverse(ValStr, [$\\|Str]),
Nwcs = [Val|Wcs],
scan_string1(Ncs, Line+1, Ncol, Q, Nstr, Nwcs);
{Val,ValStr,Ncs,Ncol} ->
Nstr = lists:reverse(ValStr, [$\\|Str]),
Nwcs = [Val|Wcs],
scan_string1(Ncs, Line, incr_column(Ncol, 1), Q, Nstr, Nwcs)
end;
scan_string1([C|Cs], Line, no_col=Col, Q, Str, Wcs) when ?UNICODE(C) ->
scan_string1(Cs, Line, Col, Q, [C|Str], [C|Wcs]);
scan_string1([C|Cs], Line, Col, Q, Str, Wcs) when ?UNICODE(C) ->
scan_string1(Cs, Line, Col+1, Q, [C|Str], [C|Wcs]);
scan_string1([C|Cs], Line, Col, _Q, _Str, _Wcs) when ?CHAR(C) ->
{char_error,Cs,{illegal,character},Line,Col,incr_column(Col, 1)};
scan_string1([]=Cs, Line, Col, _Q, Str, Wcs) ->
{more,Cs,Line,Col,Str,Wcs};
scan_string1(eof, Line, Col, _Q, _Str, Wcs) ->
{error,Line,Col,lists:reverse(Wcs),eof}.
-define(OCT(C), (is_integer(C) andalso $0 =< C andalso C =< $7)).
-define(HEX(C), (is_integer(C) andalso
(C >= $0 andalso C =< $9 orelse
C >= $A andalso C =< $F orelse
C >= $a andalso C =< $f))).
scan_escape([O1,O2,O3|Cs], Col) when ?OCT(O1), ?OCT(O2), ?OCT(O3) ->
Val = (O1*8 + O2)*8 + O3 - 73*$0,
{Val,[O1,O2,O3],Cs,incr_column(Col, 3)};
scan_escape([O1,O2], _Col) when ?OCT(O1), ?OCT(O2) ->
more;
scan_escape([O1,O2|Cs], Col) when ?OCT(O1), ?OCT(O2) ->
Val = (O1*8 + O2) - 9*$0,
{Val,[O1,O2],Cs,incr_column(Col, 2)};
scan_escape([O1], _Col) when ?OCT(O1) ->
more;
scan_escape([O1|Cs], Col) when ?OCT(O1) ->
{O1 - $0,[O1],Cs,incr_column(Col, 1)};
scan_escape([$x,${|Cs], Col) ->
scan_hex(Cs, incr_column(Col, 2), []);
scan_escape([$x], _Col) ->
more;
scan_escape([$x|eof], Col) ->
{eof,incr_column(Col, 1)};
scan_escape([$x,H1,H2|Cs], Col) when ?HEX(H1), ?HEX(H2) ->
Val = erlang:list_to_integer([H1,H2], 16),
{Val,[$x,H1,H2],Cs,incr_column(Col, 3)};
scan_escape([$x,H1], _Col) when ?HEX(H1) ->
more;
scan_escape([$x|Cs], Col) ->
{error,Cs,{illegal,character},incr_column(Col, 1)};
scan_escape([$^=C0,C|Cs], Col) when ?CHAR(C) ->
case caret_char_code(C) of
error ->
{error,[C|Cs],{illegal,character},incr_column(Col, 1)};
Code ->
{Code,[C0,C],Cs,incr_column(Col, 2)}
end;
scan_escape([$^], _Col) ->
more;
scan_escape([$^|eof], Col) ->
{eof,incr_column(Col, 1)};
scan_escape([$\n=C|Cs], Col) ->
{nl,C,[C],Cs,new_column(Col, 1)};
scan_escape([C0|Cs], Col) when ?UNICODE(C0) ->
C = escape_char(C0),
{C,[C0],Cs,incr_column(Col, 1)};
scan_escape([C|Cs], Col) when ?CHAR(C) ->
{error,Cs,{illegal,character},incr_column(Col, 1)};
scan_escape([], _Col) ->
more;
scan_escape(eof, Col) ->
{eof,Col}.
scan_hex([C|Cs], Col, Wcs) when ?HEX(C) ->
scan_hex(Cs, incr_column(Col, 1), [C|Wcs]);
scan_hex(Cs, Col, Wcs) ->
scan_hex_end(Cs, Col, Wcs, "x{").
scan_hex_end([$}|Cs], Col, [], _Str) ->
{error,Cs,{illegal,character},incr_column(Col, 1)};
scan_hex_end([$}|Cs], Col, Wcs0, Str0) ->
Wcs = lists:reverse(Wcs0),
try list_to_integer(Wcs, 16) of
Val when ?UNICODE(Val) ->
{Val,Str0++Wcs++[$}],Cs,incr_column(Col, 1)};
_Val ->
{error,Cs,{illegal,character},incr_column(Col, 1)}
catch
error:system_limit ->
{error,Cs,{illegal,character},incr_column(Col, 1)}
end;
scan_hex_end([], _Col, _Wcs, _Str0) ->
more;
scan_hex_end(eof, Col, _Wcs, _Str0) ->
{eof,Col};
scan_hex_end(Cs, Col, _Wcs, _Str0) ->
{error,Cs,{illegal,character},Col}.
\r = CR
\v = VT
\d = DEL
escape_char(C) -> C.
caret_char_code($?) -> 16#7f;
caret_char_code(C) when $@ =< C, C =< $_; $a =< C, C =< $z -> C band 16#1f;
caret_char_code(_) -> error.
scan_number(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs, Us}) ->
scan_number(Cs, St, Line, Col, Toks, Ncs, Us).
scan_number([C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_number(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_number([$_,Next|Cs], St, Line, Col, Toks, [Prev|_]=Ncs, _Us) when
?DIGIT(Next) andalso ?DIGIT(Prev) ->
scan_number(Cs, St, Line, Col, Toks, [Next,$_|Ncs], with_underscore);
scan_number([$_]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_number/6}};
scan_number([$.,C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_fraction(Cs, St, Line, Col, Toks, [C,$.|Ncs], Us);
scan_number([$.]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_number/6}};
scan_number([$#|Cs]=Cs0, St, Line, Col, Toks, Ncs0, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_integer(remove_digit_separators(Ncs, Us)) of
B when is_integer(B), 2 =< B, B =< 1+$Z-$A+10 ->
Bcs = Ncs++[$#],
scan_based_int(Cs, St, Line, Col, Toks, B, [], Bcs, no_underscore);
B when is_integer(B) ->
Len = length(Ncs),
scan_error({base,B}, Line, Col, Line, incr_column(Col, Len), Cs0)
catch
error:system_limit ->
scan_error({illegal,base}, Line, Col, Line, Col, Cs0)
end;
scan_number([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_number/6}};
scan_number(Cs, St, Line, Col, Toks, Ncs0, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_integer(remove_digit_separators(Ncs, Us), 10) of
N ->
tok3(Cs, St, Line, Col, Toks, integer, Ncs, N)
catch
error:system_limit ->
Ncol = incr_column(Col, length(Ncs)),
scan_error({illegal,integer}, Line, Col, Line, Ncol, Cs)
end.
remove_digit_separators(Number, no_underscore) ->
Number;
remove_digit_separators(Number, with_underscore) ->
[C || C <- Number, C =/= $_].
-define(BASED_DIGIT(C, B),
(is_integer(C)
andalso
((?DIGIT(C) andalso C < $0 + B)
orelse (C >= $A andalso B > 10 andalso C < $A + B - 10)
orelse (C >= $a andalso B > 10 andalso C < $a + B - 10)))).
scan_based_int(Cs, #erl_scan{}=St, Line, Col, Toks, {B,NCs,BCs,Us})
when is_integer(B), 2 =< B, B =< 1+$Z-$A+10 ->
scan_based_int(Cs, St, Line, Col, Toks, B, NCs, BCs, Us).
scan_based_int([C|Cs], St, Line, Col, Toks, B, Ncs, Bcs, Us) when
?BASED_DIGIT(C, B) ->
scan_based_int(Cs, St, Line, Col, Toks, B, [C|Ncs], Bcs, Us);
scan_based_int([$_,Next|Cs], St, Line, Col, Toks, B, [Prev|_]=Ncs, Bcs, _Us)
when ?BASED_DIGIT(Next, B) andalso ?BASED_DIGIT(Prev, B) ->
scan_based_int(Cs, St, Line, Col, Toks, B, [Next,$_|Ncs], Bcs,
with_underscore);
scan_based_int([$_]=Cs, St, Line, Col, Toks, B, NCs, BCs, Us) ->
{more,{Cs,St,Col,Toks,Line,{B,NCs,BCs,Us},fun scan_based_int/6}};
scan_based_int([]=Cs, St, Line, Col, Toks, B, NCs, BCs, Us) ->
{more,{Cs,St,Col,Toks,Line,{B,NCs,BCs,Us},fun scan_based_int/6}};
scan_based_int(Cs, _St, Line, Col, _Toks, _B, [], Bcs, _Us) ->
Len = length(Bcs),
Ncol = incr_column(Col, Len),
scan_error({illegal,integer}, Line, Col, Line, Ncol, Cs);
scan_based_int(Cs, St, Line, Col, Toks, B, Ncs0, [_|_]=Bcs, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_integer(remove_digit_separators(Ncs, Us), B) of
N ->
tok3(Cs, St, Line, Col, Toks, integer, Bcs++Ncs, N)
catch
error:system_limit ->
Len = length(Bcs)+length(Ncs),
Ncol = incr_column(Col, Len),
scan_error({illegal,integer}, Line, Col, Line, Ncol, Cs)
end.
scan_fraction(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs,Us}) ->
scan_fraction(Cs, St, Line, Col, Toks, Ncs, Us).
scan_fraction([C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_fraction(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_fraction([$_,Next|Cs], St, Line, Col, Toks, [Prev|_]=Ncs, _Us) when
?DIGIT(Next) andalso ?DIGIT(Prev) ->
scan_fraction(Cs, St, Line, Col, Toks, [Next,$_|Ncs], with_underscore);
scan_fraction([$_]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_fraction/6}};
scan_fraction([E|Cs], St, Line, Col, Toks, Ncs, Us) when E =:= $e; E =:= $E ->
scan_exponent_sign(Cs, St, Line, Col, Toks, [E|Ncs], Us);
scan_fraction([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_fraction/6}};
scan_fraction(Cs, St, Line, Col, Toks, Ncs, Us) ->
float_end(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent_sign(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs, Us}) ->
scan_exponent_sign(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent_sign([C|Cs], St, Line, Col, Toks, Ncs, Us) when
C =:= $+; C =:= $- ->
scan_exponent(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_exponent_sign([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_exponent_sign/6}};
scan_exponent_sign(Cs, St, Line, Col, Toks, Ncs, Us) ->
scan_exponent(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent(Cs, #erl_scan{}=St, Line, Col, Toks, {Ncs, Us}) ->
scan_exponent(Cs, St, Line, Col, Toks, Ncs, Us).
scan_exponent([C|Cs], St, Line, Col, Toks, Ncs, Us) when ?DIGIT(C) ->
scan_exponent(Cs, St, Line, Col, Toks, [C|Ncs], Us);
scan_exponent([$_,Next|Cs], St, Line, Col, Toks, [Prev|_]=Ncs, _) when
?DIGIT(Next) andalso ?DIGIT(Prev) ->
scan_exponent(Cs, St, Line, Col, Toks, [Next,$_|Ncs], with_underscore);
scan_exponent([$_]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_exponent/6}};
scan_exponent([]=Cs, St, Line, Col, Toks, Ncs, Us) ->
{more,{Cs,St,Col,Toks,Line,{Ncs,Us},fun scan_exponent/6}};
scan_exponent(Cs, St, Line, Col, Toks, Ncs, Us) ->
float_end(Cs, St, Line, Col, Toks, Ncs, Us).
float_end(Cs, St, Line, Col, Toks, Ncs0, Us) ->
Ncs = lists:reverse(Ncs0),
try list_to_float(remove_digit_separators(Ncs, Us)) of
F ->
tok3(Cs, St, Line, Col, Toks, float, Ncs, F)
catch
_:_ ->
Ncol = incr_column(Col, length(Ncs)),
scan_error({illegal,float}, Line, Col, Line, Ncol, Cs)
end.
skip_comment_fun(Cs, #erl_scan{}=St, Line, Col, Toks, N) ->
skip_comment(Cs, St, Line, Col, Toks, N).
skip_comment([C|Cs], St, Line, Col, Toks, N) when C =/= $\n, ?CHAR(C) ->
case ?UNICODE(C) of
true ->
skip_comment(Cs, St, Line, Col, Toks, N+1);
false ->
Ncol = incr_column(Col, N+1),
scan_error({illegal,character}, Line, Col, Line, Ncol, Cs)
end;
skip_comment([]=Cs, St, Line, Col, Toks, N) ->
{more,{Cs,St,Col,Toks,Line,N,fun skip_comment_fun/6}};
skip_comment(Cs, St, Line, Col, Toks, N) ->
scan1(Cs, St, Line, incr_column(Col, N), Toks).
scan_comment_fun(Cs, #erl_scan{}=St, Line, Col, Toks, Ncs) ->
scan_comment(Cs, St, Line, Col, Toks, Ncs).
scan_comment([C|Cs], St, Line, Col, Toks, Ncs)
when C =/= $\n, ?CHAR(C) ->
case ?UNICODE(C) of
true ->
scan_comment(Cs, St, Line, Col, Toks, [C|Ncs]);
false ->
Ncol = incr_column(Col, length(Ncs)+1),
scan_error({illegal,character}, Line, Col, Line, Ncol, Cs)
end;
scan_comment([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_comment_fun/6}};
scan_comment(Cs, St, Line, Col, Toks, Ncs0) ->
Ncs = lists:reverse(Ncs0),
tok3(Cs, St, Line, Col, Toks, comment, Ncs, Ncs).
scan_check("%%ssa%" ++ Cs, St, Line, Col, Toks, _Ncs) ->
scan_check1(Cs, St, Line, Toks, Col, 7);
scan_check("%%ssa"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%%ss"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%%s"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%%"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%ssa%" ++ Cs, St, Line, Col, Toks, _Ncs) ->
scan_check1(Cs, St, Line, Toks, Col, 6);
scan_check("%ssa"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%ss"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("%s"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("ssa%" ++ Cs, St, Line, Col, Toks, _Ncs) ->
scan_check1(Cs, St, Line, Toks, Col, 5);
scan_check("ssa"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("ss"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check("s"=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check([]=Cs, St, Line, Col, Toks, Ncs) ->
{more,{Cs,St,Col,Toks,Line,Ncs,fun scan_check/6}};
scan_check(Cs, St=#erl_scan{comment=true}, Line, Col, Toks, Ncs) ->
scan_comment(Cs, St, Line, Col, Toks, Ncs);
scan_check(Cs, St, Line, Col, Toks, _Ncs) ->
skip_comment(Cs, St, Line, Col, Toks, 1).
scan_check1(Cs, St=#erl_scan{in_check=true}, Line, Toks, Col, NoofCols) ->
scan1(Cs, St, Line, incr_column(Col, NoofCols), Toks);
scan_check1(Cs, St, Line, Toks, Col, NoofCols) ->
tok2(Cs, St#erl_scan{in_check=true}, Line,
tok2(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, _Wcs, P) ->
scan1(Cs, St, Line, Col, [{P,anno(Line)}|Toks]);
tok2(Cs, #erl_scan{}=St, Line, Col, Toks, Wcs, P) ->
Anno = anno(Line, Col, St, ?STR(P, St, Wcs)),
scan1(Cs, St, Line, incr_column(Col, length(Wcs)), [{P,Anno}|Toks]).
tok2(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, _Wcs, P, _N) ->
scan1(Cs, St, Line, Col, [{P,anno(Line)}|Toks]);
tok2(Cs, #erl_scan{}=St, Line, Col, Toks, Wcs, P, N) ->
Anno = anno(Line, Col, St, ?STR(P,St,Wcs)),
scan1(Cs, St, Line, incr_column(Col, N), [{P,Anno}|Toks]).
tok3(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, Item, _S, Sym) ->
scan1(Cs, St, Line, Col, [{Item,anno(Line),Sym}|Toks]);
tok3(Cs, #erl_scan{}=St, Line, Col, Toks, Item, String, Sym) ->
Token = {Item,anno(Line, Col, St, ?STR(Item, St, String)),Sym},
scan1(Cs, St, Line, incr_column(Col, length(String)), [Token|Toks]).
tok3(Cs, #erl_scan{has_fun = false}=St, Line, no_col=Col, Toks, Item,
_String, Sym, _Length) ->
scan1(Cs, St, Line, Col, [{Item,anno(Line),Sym}|Toks]);
tok3(Cs, #erl_scan{}=St, Line, Col, Toks, Item, String, Sym, Length) ->
Token = {Item,anno(Line, Col, St, ?STR(Item, St, String)),Sym},
scan1(Cs, St, Line, incr_column(Col, Length), [Token|Toks]).
scan_error(Error, Line, Col, EndLine, EndCol, Rest) ->
Loc = location(Line, Col),
EndLoc = location(EndLine, EndCol),
scan_error(Error, Loc, EndLoc, Rest).
scan_error(Error, ErrorLoc, EndLoc, Rest) ->
{{error,{ErrorLoc,?MODULE,Error},EndLoc},Rest}.
-compile({inline,[anno/4]}).
anno(Line, no_col, #erl_scan{has_fun = false}, _String) ->
anno(Line);
anno(Line, no_col, #erl_scan{has_fun = true}, []) ->
anno(Line);
anno(Line, no_col, #erl_scan{has_fun = true}, String) ->
Anno = anno(Line),
erl_anno:set_text(String, Anno);
anno(Line, Col, #erl_scan{has_fun = false}, _String) ->
anno({Line, Col});
anno(Line, Col, #erl_scan{has_fun = true}, []) ->
anno({Line, Col});
anno(Line, Col, #erl_scan{has_fun = true}, String) ->
Anno = anno({Line, Col}),
erl_anno:set_text(String, Anno).
location(Line, no_col) ->
Line;
location(Line, Col) when is_integer(Col) ->
{Line,Col}.
-compile({inline,[anno/1,incr_column/2,new_column/2]}).
anno(Location) ->
erl_anno:new(Location).
incr_column(no_col=Col, _N) ->
Col;
incr_column(Col, N) when is_integer(Col) ->
Col + N.
new_column(no_col=Col, _Ncol) ->
Col;
new_column(Col, Ncol) when is_integer(Col) ->
Ncol.
nl_spcs(2) -> "\n ";
nl_spcs(3) -> "\n ";
nl_spcs(4) -> "\n ";
nl_spcs(5) -> "\n ";
nl_spcs(6) -> "\n ";
nl_spcs(7) -> "\n ";
nl_spcs(8) -> "\n ";
nl_spcs(9) -> "\n ";
nl_spcs(10) -> "\n ";
nl_spcs(11) -> "\n ";
nl_spcs(12) -> "\n ";
nl_spcs(13) -> "\n ";
nl_spcs(14) -> "\n ";
nl_spcs(15) -> "\n ";
nl_spcs(16) -> "\n ";
nl_spcs(17) -> "\n ".
spcs(1) -> " ";
spcs(2) -> " ";
spcs(3) -> " ";
spcs(4) -> " ";
spcs(5) -> " ";
spcs(6) -> " ";
spcs(7) -> " ";
spcs(8) -> " ";
spcs(9) -> " ";
spcs(10) -> " ";
spcs(11) -> " ";
spcs(12) -> " ";
spcs(13) -> " ";
spcs(14) -> " ";
spcs(15) -> " ";
spcs(16) -> " ".
nl_tabs(2) -> "\n\t";
nl_tabs(3) -> "\n\t\t";
nl_tabs(4) -> "\n\t\t\t";
nl_tabs(5) -> "\n\t\t\t\t";
nl_tabs(6) -> "\n\t\t\t\t\t";
nl_tabs(7) -> "\n\t\t\t\t\t\t";
nl_tabs(8) -> "\n\t\t\t\t\t\t\t";
nl_tabs(9) -> "\n\t\t\t\t\t\t\t\t";
nl_tabs(10) -> "\n\t\t\t\t\t\t\t\t\t";
nl_tabs(11) -> "\n\t\t\t\t\t\t\t\t\t\t".
tabs(1) -> "\t";
tabs(2) -> "\t\t";
tabs(3) -> "\t\t\t";
tabs(4) -> "\t\t\t\t";
tabs(5) -> "\t\t\t\t\t";
tabs(6) -> "\t\t\t\t\t\t";
tabs(7) -> "\t\t\t\t\t\t\t";
tabs(8) -> "\t\t\t\t\t\t\t\t";
tabs(9) -> "\t\t\t\t\t\t\t\t\t";
tabs(10) -> "\t\t\t\t\t\t\t\t\t\t".
Dynamic version of reserved_word that knows about the possibility
-spec reserved_word(Atom :: atom()) -> boolean().
reserved_word(Atom) ->
case f_reserved_word(Atom) of
true -> true;
false ->
lists:member(Atom, erl_features:keywords())
end.
Static version of reserved_words . These represent the fixed set of
f_reserved_word('after') -> true;
f_reserved_word('begin') -> true;
f_reserved_word('case') -> true;
f_reserved_word('try') -> true;
f_reserved_word('cond') -> true;
f_reserved_word('catch') -> true;
f_reserved_word('andalso') -> true;
f_reserved_word('orelse') -> true;
f_reserved_word('end') -> true;
f_reserved_word('fun') -> true;
f_reserved_word('if') -> true;
f_reserved_word('let') -> true;
f_reserved_word('of') -> true;
f_reserved_word('receive') -> true;
f_reserved_word('when') -> true;
f_reserved_word('bnot') -> true;
f_reserved_word('not') -> true;
f_reserved_word('div') -> true;
f_reserved_word('rem') -> true;
f_reserved_word('band') -> true;
f_reserved_word('and') -> true;
f_reserved_word('bor') -> true;
f_reserved_word('bxor') -> true;
f_reserved_word('bsl') -> true;
f_reserved_word('bsr') -> true;
f_reserved_word('or') -> true;
f_reserved_word('xor') -> true;
f_reserved_word(_) -> false.
|
5bf1b23b7780bad2906f9dcd6f18a44828fbcf8d66f31f47bf281b19ccee6eed | ErlyORM/boss_db | boss_db_sup.erl | -module(boss_db_sup).
-author('').
-behaviour(supervisor).
-export([start_link/0, start_link/1]).
-export([init/1]).
start_link() ->
start_link([]).
start_link(StartArgs) ->
supervisor:start_link({local, ?MODULE}, ?MODULE, StartArgs).
init(StartArgs) ->
Args = StartArgs ++ [{name, {local, boss_db_pool}},
{worker_module, boss_db_controller},
{size, 5}, {max_overflow, 10}],
PoolSpec = {db_controller, {poolboy, start_link, [Args]}, permanent, 2000, worker, [poolboy]},
{ok, {{one_for_one, 10, 10}, [PoolSpec]}}.
| null | https://raw.githubusercontent.com/ErlyORM/boss_db/20060a061d3c4120929e4a4fedae1bb5e5830426/src/boss_db_sup.erl | erlang | -module(boss_db_sup).
-author('').
-behaviour(supervisor).
-export([start_link/0, start_link/1]).
-export([init/1]).
start_link() ->
start_link([]).
start_link(StartArgs) ->
supervisor:start_link({local, ?MODULE}, ?MODULE, StartArgs).
init(StartArgs) ->
Args = StartArgs ++ [{name, {local, boss_db_pool}},
{worker_module, boss_db_controller},
{size, 5}, {max_overflow, 10}],
PoolSpec = {db_controller, {poolboy, start_link, [Args]}, permanent, 2000, worker, [poolboy]},
{ok, {{one_for_one, 10, 10}, [PoolSpec]}}.
|
|
836bafc22c418134657a851ad9f432bbacc4d201efdc3547573988447579a42b | synrc/mad | mad_cubical.erl | -module(mad_cubical).
-copyright('Maxim Sokhatsky').
-compile(export_all).
compile(File,_Inc,_Bin,_Opt,_Deps) ->
{_,Res,Msg} = sh:run(sh:executable("cubical"), ["-b", File], binary, "."),
case Res of
1 -> true;
0 -> case binary:match(Msg,[<<"File loaded.">>]) of
nomatch -> io:format("Error: ~p~n",[Msg]), true;
_ -> io:format("OK: ~p.~n",[filename:basename(File)]), false end end.
| null | https://raw.githubusercontent.com/synrc/mad/b8811aebd662c2a281c9f87642b5cab9321cf543/src/compile/mad_cubical.erl | erlang | -module(mad_cubical).
-copyright('Maxim Sokhatsky').
-compile(export_all).
compile(File,_Inc,_Bin,_Opt,_Deps) ->
{_,Res,Msg} = sh:run(sh:executable("cubical"), ["-b", File], binary, "."),
case Res of
1 -> true;
0 -> case binary:match(Msg,[<<"File loaded.">>]) of
nomatch -> io:format("Error: ~p~n",[Msg]), true;
_ -> io:format("OK: ~p.~n",[filename:basename(File)]), false end end.
|
|
453c45799af404ffc57d3a5497e2fc4eea61fe1923fd4d8bfa25c42649f80218 | BitGameEN/bitgamex | hello.erl | %% File : hello.erl
Purpose : Brief demonstration of Luerl basics .
Use $ erlc hello.erl & & erl -pa ./ebin -s hello run -s init stop -noshell
%% Or $ make hello
-module(hello).
-export([run/0]).
run() ->
% execute a string
luerl:do("print(\"Hello, Robert(o)!\")"),
% execute a file
luerl:dofile("./hello.lua"),
% separately parse, then execute
State0 = luerl:init(),
{ok, Chunk, State1} = luerl:load("print(\"Hello, Chunk!\")", State0),
{_Ret, _NewState} = luerl:do(Chunk, State1),
done.
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/luerl/examples/hello/hello.erl | erlang | File : hello.erl
Or $ make hello
execute a string
execute a file
separately parse, then execute | Purpose : Brief demonstration of Luerl basics .
Use $ erlc hello.erl & & erl -pa ./ebin -s hello run -s init stop -noshell
-module(hello).
-export([run/0]).
run() ->
luerl:do("print(\"Hello, Robert(o)!\")"),
luerl:dofile("./hello.lua"),
State0 = luerl:init(),
{ok, Chunk, State1} = luerl:load("print(\"Hello, Chunk!\")", State0),
{_Ret, _NewState} = luerl:do(Chunk, State1),
done.
|
2e0d4819fd47cfb46a094672d09b1fad02a1582edf7b9c5549f0680d85493b03 | facebookarchive/duckling_old | duration.clj | ; Durations / Periods
(
"second (unit-of-duration)"
#"(?i)sec(ond[oi])?"
{:dim :unit-of-duration
width of interval when " in 10 secs "
"minute (unit-of-duration)"
#"(?i)min(ut[oi])?"
{:dim :unit-of-duration
:grain :minute}
"hour (unit-of-duration)"
#"(?i)or[ae]"
{:dim :unit-of-duration
:grain :hour}
"day (unit-of-duration)"
#"(?i)giorn[oi]"
{:dim :unit-of-duration
:grain :day}
"week (unit-of-duration)"
#"(?i)settiman[ae]"
{:dim :unit-of-duration
:grain :week}
"month (unit-of-duration)"
#"(?i)mes[ei]"
{:dim :unit-of-duration
:grain :month}
"year (unit-of-duration)"
#"(?i)ann[oi]"
{:dim :unit-of-duration
:grain :year}
"<integer> <unit-of-duration>"
[(integer 0) (dim :unit-of-duration)] ;prevent negative duration...
{:dim :duration
:value (duration (:grain %2) (:value %1))}
"une <unit-of-duration>"
[#"(?i)un[a']?" (dim :unit-of-duration)]
{:dim :duration
:value (duration (:grain %2) 1)}
"un quarto d'ora"
[#"(?i)un quarto d['i] ?ora"]
{:dim :duration
:value (duration :minute 15)}
"mezz'ora"
[#"(?i)mezz[a'] ?ora"]
{:dim :duration
:value (duration :minute 30)}
"tre quarti d'ora"
[#"(?i)(3|tre) quarti d['i] ?ora"]
{:dim :duration
:value (duration :minute 45)}
"in/after <duration>"
[#"(?i)[tf]ra|dopo" (dim :duration)]
(in-duration (:value %2))
"<duration> ago"
[(dim :duration) #"(?i)fa"]
(duration-ago (:value %2))
)
| null | https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/it/rules/duration.clj | clojure | Durations / Periods
prevent negative duration... |
(
"second (unit-of-duration)"
#"(?i)sec(ond[oi])?"
{:dim :unit-of-duration
width of interval when " in 10 secs "
"minute (unit-of-duration)"
#"(?i)min(ut[oi])?"
{:dim :unit-of-duration
:grain :minute}
"hour (unit-of-duration)"
#"(?i)or[ae]"
{:dim :unit-of-duration
:grain :hour}
"day (unit-of-duration)"
#"(?i)giorn[oi]"
{:dim :unit-of-duration
:grain :day}
"week (unit-of-duration)"
#"(?i)settiman[ae]"
{:dim :unit-of-duration
:grain :week}
"month (unit-of-duration)"
#"(?i)mes[ei]"
{:dim :unit-of-duration
:grain :month}
"year (unit-of-duration)"
#"(?i)ann[oi]"
{:dim :unit-of-duration
:grain :year}
"<integer> <unit-of-duration>"
{:dim :duration
:value (duration (:grain %2) (:value %1))}
"une <unit-of-duration>"
[#"(?i)un[a']?" (dim :unit-of-duration)]
{:dim :duration
:value (duration (:grain %2) 1)}
"un quarto d'ora"
[#"(?i)un quarto d['i] ?ora"]
{:dim :duration
:value (duration :minute 15)}
"mezz'ora"
[#"(?i)mezz[a'] ?ora"]
{:dim :duration
:value (duration :minute 30)}
"tre quarti d'ora"
[#"(?i)(3|tre) quarti d['i] ?ora"]
{:dim :duration
:value (duration :minute 45)}
"in/after <duration>"
[#"(?i)[tf]ra|dopo" (dim :duration)]
(in-duration (:value %2))
"<duration> ago"
[(dim :duration) #"(?i)fa"]
(duration-ago (:value %2))
)
|
1e3c7239d21d8dcdafc1f5bb1b3f44a12bc57373a86df99004c165b600020439 | IxpertaSolutions/freer-effects | Coroutine.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
module Tests.Coroutine (tests)
where
import Prelude ((+), even)
import Control.Applicative ((<*>), pure)
import Control.Monad ((>>), (>>=), unless)
import Data.Bool (Bool, (&&))
import Data.Eq ((==))
import Data.Function (($), (.))
import Data.Functor ((<$>))
import Data.Int (Int)
import Data.Tuple (snd)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Control.Monad.Freer (Eff, Members, run)
import Control.Monad.Freer.Coroutine
( Status(Continue, Done)
, Yield
, runC
, yield
)
import Control.Monad.Freer.State (State, modify, runState)
tests :: TestTree
tests = testGroup "Coroutine Eff tests"
[ testProperty "Counting consecutive pairs of odds"
$ \list -> runTestCoroutine list == countOddDuoPrefix list
]
-- | Counts number of consecutive pairs of odd elements at beginning of a list.
countOddDuoPrefix :: [Int] -> Int
countOddDuoPrefix list = count list 0
where
count (i1:i2:is) n = if even i1 && even i2 then n else count is (n + 1)
count _ n = n
runTestCoroutine :: [Int] -> Int
runTestCoroutine list = snd . run $ runState effTestCoroutine 0
where
testCoroutine :: Members '[Yield () Int, State Int] r => Eff r ()
testCoroutine = do
Yield for two elements and hope they 're both odd .
b <- (&&)
<$> yield () (even :: Int -> Bool)
<*> yield () (even :: Int -> Bool)
unless b $ modify (+ (1 :: Int)) >> testCoroutine
effTestCoroutine = runC testCoroutine >>= handleStatus list
where
handleStatus _ (Done ()) = pure ()
handleStatus (i:is) (Continue () k) = k i >>= handleStatus is
handleStatus [] _ = pure ()
| null | https://raw.githubusercontent.com/IxpertaSolutions/freer-effects/39a7e62cc049d43d36ece4ac24ba19e545f0b726/tests/Tests/Coroutine.hs | haskell | # LANGUAGE ConstraintKinds #
| Counts number of consecutive pairs of odd elements at beginning of a list. | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
module Tests.Coroutine (tests)
where
import Prelude ((+), even)
import Control.Applicative ((<*>), pure)
import Control.Monad ((>>), (>>=), unless)
import Data.Bool (Bool, (&&))
import Data.Eq ((==))
import Data.Function (($), (.))
import Data.Functor ((<$>))
import Data.Int (Int)
import Data.Tuple (snd)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Control.Monad.Freer (Eff, Members, run)
import Control.Monad.Freer.Coroutine
( Status(Continue, Done)
, Yield
, runC
, yield
)
import Control.Monad.Freer.State (State, modify, runState)
tests :: TestTree
tests = testGroup "Coroutine Eff tests"
[ testProperty "Counting consecutive pairs of odds"
$ \list -> runTestCoroutine list == countOddDuoPrefix list
]
countOddDuoPrefix :: [Int] -> Int
countOddDuoPrefix list = count list 0
where
count (i1:i2:is) n = if even i1 && even i2 then n else count is (n + 1)
count _ n = n
runTestCoroutine :: [Int] -> Int
runTestCoroutine list = snd . run $ runState effTestCoroutine 0
where
testCoroutine :: Members '[Yield () Int, State Int] r => Eff r ()
testCoroutine = do
Yield for two elements and hope they 're both odd .
b <- (&&)
<$> yield () (even :: Int -> Bool)
<*> yield () (even :: Int -> Bool)
unless b $ modify (+ (1 :: Int)) >> testCoroutine
effTestCoroutine = runC testCoroutine >>= handleStatus list
where
handleStatus _ (Done ()) = pure ()
handleStatus (i:is) (Continue () k) = k i >>= handleStatus is
handleStatus [] _ = pure ()
|
32c6e3e92cc99e7c0f083e3882d5f90f01fdaa49fbc33ad5a7095ce23936ae8b | argp/bap | debug.ml | let logfile = ref stderr
let set_logfile log = logfile := log
let debug_string s = output_string !logfile s
let debug_endline s =
debug_string s;
debug_string "\n";
flush !logfile
(* Disabling global debugging turns off all debug functionality for all modules *)
let global_debug = ref true
let set_global_debug v = global_debug := v
(* Use the appropriate logfile, as per environment variables *)
let () =
try
let filename = Sys.getenv "BAP_LOGFILE" in
set_logfile (open_out_gen [Open_append;Open_creat] 0o664 filename)
with Not_found -> ()
let get_env_options varname defvalue =
let default _ = defvalue in
try
let modules = Sys.getenv varname in
let len = String.length modules in
let lookup name =
let rec f spos =
let npos =
try String.index_from modules spos ':'
with Not_found -> len
in
if npos = spos then true else
let (sub, res) =
if String.get modules spos = '!'
then (String.sub modules (spos+1) (npos-spos-1), false)
else (String.sub modules spos (npos-spos), true)
in
if sub = "" || sub = name then res
else if npos < len then f (npos+1) else defvalue
in
f 0
in
lookup
with Not_found ->
default
(* [has_debug d s] returns true when debugging is enabled for s. d is the
default behavior.
See documentation on [BAP_DEBUG_MODULES] at the top.
*)
let has_debug d s =
get_env_options " BAP_DEBUG_MODULES "
if !global_debug then get_env_options "BAP_DEBUG_MODULES" d s
else false
[ has_warn s ] returns true when warnings are enabled for s.
See documention on [ BAP_WARN_MODULES ] at the top
See documention on [BAP_WARN_MODULES] at the top *)
let has_warn =
get_env_options "BAP_WARN_MODULES" true
let indent = ref 0
let inc_indent () = indent := !indent + 1
let dec_indent () = indent := !indent - 1
let pindent () =
let tab_is = 4 in (* number of "normal" indents *)
let rec helper = function
| 0 -> ()
| n when n >= tab_is -> (debug_string "\t"; helper (n-tab_is))
| n -> (debug_string " "; helper (n-1))
in
helper (!indent)
let ptime_unix() =
debug_string(Printf.sprintf "[%.3f]" (Unix.gettimeofday()))
let ptime_iso() =
let secs = Unix.gettimeofday() in
let t = Unix.localtime secs in
Printf.ksprintf debug_string "[%4d-%2d-%2d_%2d:%2d:%2d]"
t.Unix.tm_year t.Unix.tm_mon t.Unix.tm_mday
t.Unix.tm_hour t.Unix.tm_min t.Unix.tm_sec
let ptime_none() = ()
let ptime =
try
match Sys.getenv "BAP_DEBUG_TIMESTAMPS" with
| "" | "unix" | "Unix" -> ptime_unix
| "iso" | "ISO" -> ptime_iso
| "none" | "None" -> ptime_none
| "elapsed" ->
let t0 = Unix.gettimeofday () in
(fun () ->
Printf.ksprintf debug_string "[%f]" ((Unix.gettimeofday ()) -. t0) )
| s ->
prerr_endline("Warning: Unknown BAP_DEBUG_TIMESTAMPS value ("^s^")");
ptime_unix
with Not_found ->
ptime_none
module type DEBUG =
sig
val debug : unit -> bool
val warn : bool
val pdebug : string -> unit
val dprintf : ('a, unit, string, unit) format4 -> 'a
val dtrace : before:('a->unit) -> f:('a->'b) -> after:('b->unit) -> 'a -> 'b
(* more should get added here *)
val pwarn : string -> unit
val wprintf : ('a, unit, string, unit) format4 -> 'a
end
module type DEBUG_MOD_INFO =
sig
val name : string
val default : [ `Debug | `NoDebug ]
end
module NoDebug : DEBUG =
struct
let debug _ = false
let pdebug = (fun _ -> ())
let dprintf fmt = Printf.ksprintf ignore fmt
let dtrace = (fun ~before ~f ~after -> f)
let warn = false
let pwarn = (fun _ -> ())
let wprintf fmt = Printf.ksprintf ignore fmt
end
module Make(Module:DEBUG_MOD_INFO) : DEBUG =
struct
let debug _ = has_debug (Module.default = `Debug) Module.name
let pdebug s =
pindent(); ptime();
debug_string Module.name; debug_string ": ";
debug_endline s
let pdebug a = if debug() then pdebug a else NoDebug.pdebug a
let dprintf fmt = Printf.ksprintf pdebug fmt
let dprintf a = if debug() then dprintf a else NoDebug.dprintf a
let dtrace ~before ~f ~after x =
before x;
inc_indent ();
let r = f x in
dec_indent ();
after r;
r
let dtrace = if debug() then dtrace else NoDebug.dtrace
let warn = has_warn Module.name
let pwarn s =
pindent(); ptime();
debug_string "WARNING (";
debug_string Module.name;
debug_string "): ";
debug_endline s
let pwarn = if warn then pwarn else NoDebug.pwarn
let wprintf fmt = Printf.ksprintf pwarn fmt
let wprintf = if warn then wprintf else NoDebug.wprintf
end
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocaml/debug.ml | ocaml | Disabling global debugging turns off all debug functionality for all modules
Use the appropriate logfile, as per environment variables
[has_debug d s] returns true when debugging is enabled for s. d is the
default behavior.
See documentation on [BAP_DEBUG_MODULES] at the top.
number of "normal" indents
more should get added here | let logfile = ref stderr
let set_logfile log = logfile := log
let debug_string s = output_string !logfile s
let debug_endline s =
debug_string s;
debug_string "\n";
flush !logfile
let global_debug = ref true
let set_global_debug v = global_debug := v
let () =
try
let filename = Sys.getenv "BAP_LOGFILE" in
set_logfile (open_out_gen [Open_append;Open_creat] 0o664 filename)
with Not_found -> ()
let get_env_options varname defvalue =
let default _ = defvalue in
try
let modules = Sys.getenv varname in
let len = String.length modules in
let lookup name =
let rec f spos =
let npos =
try String.index_from modules spos ':'
with Not_found -> len
in
if npos = spos then true else
let (sub, res) =
if String.get modules spos = '!'
then (String.sub modules (spos+1) (npos-spos-1), false)
else (String.sub modules spos (npos-spos), true)
in
if sub = "" || sub = name then res
else if npos < len then f (npos+1) else defvalue
in
f 0
in
lookup
with Not_found ->
default
let has_debug d s =
get_env_options " BAP_DEBUG_MODULES "
if !global_debug then get_env_options "BAP_DEBUG_MODULES" d s
else false
[ has_warn s ] returns true when warnings are enabled for s.
See documention on [ BAP_WARN_MODULES ] at the top
See documention on [BAP_WARN_MODULES] at the top *)
let has_warn =
get_env_options "BAP_WARN_MODULES" true
let indent = ref 0
let inc_indent () = indent := !indent + 1
let dec_indent () = indent := !indent - 1
let pindent () =
let rec helper = function
| 0 -> ()
| n when n >= tab_is -> (debug_string "\t"; helper (n-tab_is))
| n -> (debug_string " "; helper (n-1))
in
helper (!indent)
let ptime_unix() =
debug_string(Printf.sprintf "[%.3f]" (Unix.gettimeofday()))
let ptime_iso() =
let secs = Unix.gettimeofday() in
let t = Unix.localtime secs in
Printf.ksprintf debug_string "[%4d-%2d-%2d_%2d:%2d:%2d]"
t.Unix.tm_year t.Unix.tm_mon t.Unix.tm_mday
t.Unix.tm_hour t.Unix.tm_min t.Unix.tm_sec
let ptime_none() = ()
let ptime =
try
match Sys.getenv "BAP_DEBUG_TIMESTAMPS" with
| "" | "unix" | "Unix" -> ptime_unix
| "iso" | "ISO" -> ptime_iso
| "none" | "None" -> ptime_none
| "elapsed" ->
let t0 = Unix.gettimeofday () in
(fun () ->
Printf.ksprintf debug_string "[%f]" ((Unix.gettimeofday ()) -. t0) )
| s ->
prerr_endline("Warning: Unknown BAP_DEBUG_TIMESTAMPS value ("^s^")");
ptime_unix
with Not_found ->
ptime_none
module type DEBUG =
sig
val debug : unit -> bool
val warn : bool
val pdebug : string -> unit
val dprintf : ('a, unit, string, unit) format4 -> 'a
val dtrace : before:('a->unit) -> f:('a->'b) -> after:('b->unit) -> 'a -> 'b
val pwarn : string -> unit
val wprintf : ('a, unit, string, unit) format4 -> 'a
end
module type DEBUG_MOD_INFO =
sig
val name : string
val default : [ `Debug | `NoDebug ]
end
module NoDebug : DEBUG =
struct
let debug _ = false
let pdebug = (fun _ -> ())
let dprintf fmt = Printf.ksprintf ignore fmt
let dtrace = (fun ~before ~f ~after -> f)
let warn = false
let pwarn = (fun _ -> ())
let wprintf fmt = Printf.ksprintf ignore fmt
end
module Make(Module:DEBUG_MOD_INFO) : DEBUG =
struct
let debug _ = has_debug (Module.default = `Debug) Module.name
let pdebug s =
pindent(); ptime();
debug_string Module.name; debug_string ": ";
debug_endline s
let pdebug a = if debug() then pdebug a else NoDebug.pdebug a
let dprintf fmt = Printf.ksprintf pdebug fmt
let dprintf a = if debug() then dprintf a else NoDebug.dprintf a
let dtrace ~before ~f ~after x =
before x;
inc_indent ();
let r = f x in
dec_indent ();
after r;
r
let dtrace = if debug() then dtrace else NoDebug.dtrace
let warn = has_warn Module.name
let pwarn s =
pindent(); ptime();
debug_string "WARNING (";
debug_string Module.name;
debug_string "): ";
debug_endline s
let pwarn = if warn then pwarn else NoDebug.pwarn
let wprintf fmt = Printf.ksprintf pwarn fmt
let wprintf = if warn then wprintf else NoDebug.wprintf
end
|
46ab626290cd0f7d4e445da9755366f717d562a9de9c495d97a69c1a0f0d05a0 | dbuenzli/mu | articulation.ml | (* This code is in the public domain *)
open Mu
open Mu.Syntax
let art m a = M.phrase [`Art a] m
let arts = [ `Staccato Q.(1 #/ 4);
`Legato Q.(int 4);
`Slurred Q.(int 4); ]
let boogie = M.line M.[c 4 en; e 4 en; g 4 en; a 4 en]
let song = boogie ^ M.line (List.map (art boogie) arts)
let main () = Mu_player.main (Music.map Pnote.of_pitch song)
let () = if !Sys.interactive then () else main ()
| null | https://raw.githubusercontent.com/dbuenzli/mu/f6028ba4515bd49eb076b7394dee39e8f35e13fa/test/articulation.ml | ocaml | This code is in the public domain |
open Mu
open Mu.Syntax
let art m a = M.phrase [`Art a] m
let arts = [ `Staccato Q.(1 #/ 4);
`Legato Q.(int 4);
`Slurred Q.(int 4); ]
let boogie = M.line M.[c 4 en; e 4 en; g 4 en; a 4 en]
let song = boogie ^ M.line (List.map (art boogie) arts)
let main () = Mu_player.main (Music.map Pnote.of_pitch song)
let () = if !Sys.interactive then () else main ()
|
5b3b3f0263e225cb0a066c1e26c8c6a0e03ac20f8b0dcfdf31652cb2853a39b7 | pink-gorilla/goldly | css_theme.clj | (ns goldly.config.build.css-theme)
; the lazy-css loader loads the entire css for an extension, when this
; extension gets lazy-loaded.
; therefore we need to have a map of key:module-name => value module-css-theme
; this is different to the webly static loaded css themes
; which is run at run-time.
(defn- extension-css-theme [themes
{:keys [lazy name theme]
:or {theme {:available {} :current {}}}}]
(if lazy
(assoc themes name theme)
themes))
(defn css-theme-config [exts]
(reduce extension-css-theme {} (vals exts)))
(comment
(require '[goldly.config.discover :refer [discover]])
(->> (discover {:lazy true})
(css-theme-config))
;
)
| null | https://raw.githubusercontent.com/pink-gorilla/goldly/9589dc51c8fe894319e9eededdc1c965c3314491/goldly/src/goldly/config/build/css_theme.clj | clojure | the lazy-css loader loads the entire css for an extension, when this
extension gets lazy-loaded.
therefore we need to have a map of key:module-name => value module-css-theme
this is different to the webly static loaded css themes
which is run at run-time.
| (ns goldly.config.build.css-theme)
(defn- extension-css-theme [themes
{:keys [lazy name theme]
:or {theme {:available {} :current {}}}}]
(if lazy
(assoc themes name theme)
themes))
(defn css-theme-config [exts]
(reduce extension-css-theme {} (vals exts)))
(comment
(require '[goldly.config.discover :refer [discover]])
(->> (discover {:lazy true})
(css-theme-config))
)
|
c0dc1f6ad173ee3005921429d9d0d4bc29f0d9fd1520b43ebf437427aad38f3b | elizabethsiegle/reddit-slack-bot | AvailablePhoneNumber.hs | # LANGUAGE MultiParamTypeClasses #
{-#LANGUAGE OverloadedStrings #-}
module Twilio.AvailablePhoneNumber
( -- * Resource
AvailablePhoneNumber(..)
) where
import Control.Applicative
import Control.Error.Safe
import Control.Monad
import Data.Aeson
import Data.Text (Text)
import Twilio.Types
import Twilio.Internal.Parser
Resource
data AvailablePhoneNumber = AvailablePhoneNumber
{ friendlyName :: !Text
, phoneNumber :: !Text
, lata :: !(Maybe Integer)
, rateCenter :: !(Maybe Text)
, latitude :: !(Maybe Double)
, longitude :: !(Maybe Double)
, region :: !Text
, postalCode :: !(Maybe Integer)
, isoCountry :: !ISOCountryCode
, addressRequirements :: !(Maybe AddressRequirement)
, capabilities :: !Capabilities
} deriving (Eq, Show)
instance FromJSON AvailablePhoneNumber where
parseJSON (Object v) = AvailablePhoneNumber
<$> v .: "friendly_name"
<*> v .: "phone_number"
<*> (v .: "lata" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "rate_center"
<*> (v .: "latitude" <&> (=<<) readZ
>>= maybeReturn')
<*> (v .: "longitude" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "region"
<*> (v .: "postal_code" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "iso_country"
<*> v .: "address_requirements"
<*> (v .: "capabilities" >>= parseJSON)
parseJSON _ = mzero
| null | https://raw.githubusercontent.com/elizabethsiegle/reddit-slack-bot/a52ab60dcaae8e16bee8cdba22fce627157a42d8/twilio-haskell-move-to-stack/src/Twilio/AvailablePhoneNumber.hs | haskell | #LANGUAGE OverloadedStrings #
* Resource | # LANGUAGE MultiParamTypeClasses #
module Twilio.AvailablePhoneNumber
AvailablePhoneNumber(..)
) where
import Control.Applicative
import Control.Error.Safe
import Control.Monad
import Data.Aeson
import Data.Text (Text)
import Twilio.Types
import Twilio.Internal.Parser
Resource
data AvailablePhoneNumber = AvailablePhoneNumber
{ friendlyName :: !Text
, phoneNumber :: !Text
, lata :: !(Maybe Integer)
, rateCenter :: !(Maybe Text)
, latitude :: !(Maybe Double)
, longitude :: !(Maybe Double)
, region :: !Text
, postalCode :: !(Maybe Integer)
, isoCountry :: !ISOCountryCode
, addressRequirements :: !(Maybe AddressRequirement)
, capabilities :: !Capabilities
} deriving (Eq, Show)
instance FromJSON AvailablePhoneNumber where
parseJSON (Object v) = AvailablePhoneNumber
<$> v .: "friendly_name"
<*> v .: "phone_number"
<*> (v .: "lata" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "rate_center"
<*> (v .: "latitude" <&> (=<<) readZ
>>= maybeReturn')
<*> (v .: "longitude" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "region"
<*> (v .: "postal_code" <&> (=<<) readZ
>>= maybeReturn')
<*> v .: "iso_country"
<*> v .: "address_requirements"
<*> (v .: "capabilities" >>= parseJSON)
parseJSON _ = mzero
|
8e28e658d8d931952a67273cc9f7b7688c55d00b92c3061cbd170d3da08f4782 | Appliscale/xprof | xprof_core_lib.erl | -module(xprof_core_lib).
-export([mfaspec2atom/1,
mfa2atom/1,
mfaspec2id/1,
now2epoch/1,
set_mode/1,
get_mode/0,
get_mode_cb/0,
set_event_handler/1,
unset_event_handler/0,
notify_event_handler/1,
prefix/2,
prefix_rest/2,
err/1, err/2, err/3,
fmt_err/1, fmt_err/2, fmt_err/3
]).
-spec mfaspec2atom(xprof_core:mfa_spec()) -> xprof_core:mfa_name().
mfaspec2atom({MFAId, {_MSOff, _MSOn}}) ->
mfa2atom(MFAId).
-spec mfa2atom(xprof_core:mfa_id()) -> xprof_core:mfa_name().
mfa2atom({M,F,A}) ->
list_to_atom(string:join(["xprof_", atom_to_list(M),
atom_to_list(F), integer_to_list(A)], "_")).
-spec mfaspec2id(xprof_core:mfa_spec()) -> xprof_core:mfa_id().
mfaspec2id({MFAId, {_, _}}) ->
MFAId.
now2epoch({MS, S, _US}) ->
MS * 1000000 + S.
-spec set_mode(xprof_core:mode()) -> ok.
set_mode(Mode) when Mode =:= elixir; Mode =:= erlang ->
application:set_env(xprof_core, mode, Mode).
-spec get_mode() -> xprof_core:mode().
get_mode() ->
case application:get_env(xprof_core, mode) of
undefined ->
Mode = detect_mode(),
set_mode(Mode),
Mode;
{ok, Mode} ->
Mode
end.
-spec get_mode_cb() -> module().
get_mode_cb() ->
case get_mode() of
erlang -> xprof_core_erlang_syntax;
elixir -> xprof_core_elixir_syntax
end.
set_event_handler(EventHandler) ->
application:set_env(xprof_core, event_handler, EventHandler).
unset_event_handler() ->
application:unset_env(xprof_core, event_handler).
notify_event_handler(Msg) ->
case application:get_env(xprof_core, event_handler) of
undefined ->
ok;
{ok, Pid} ->
try Pid ! Msg
catch _:_ ->
%% ignore crash
{error, no_event_handler}
end
end.
-spec detect_mode() -> xprof_core:mode().
detect_mode() ->
case lists:keymember(elixir, 1, application:which_applications()) of
true -> elixir;
false -> erlang
end.
-spec prefix(binary(), binary()) -> boolean().
prefix(Prefix, Bin) ->
PrefixSize = byte_size(Prefix),
case Bin of
<<Prefix:PrefixSize/binary, _/binary>> -> true;
_ -> false
end.
-spec prefix_rest(binary(), binary()) -> false | binary().
prefix_rest(Prefix, Bin) ->
PrefixSize = byte_size(Prefix),
case Bin of
<<Prefix:PrefixSize/binary, Rest/binary>> -> Rest;
_ -> false
end.
%% @doc Throw an error in a common format
-spec err(string()) -> no_return().
err(Fmt) ->
throw(fmt_err(Fmt)).
-spec err(string(), list()) -> no_return().
err(Fmt, Args) ->
throw(fmt_err(Fmt, Args)).
-spec err(tuple() | integer(), module(), term()) -> no_return().
err(Loc, Mod, Err) ->
throw(fmt_err(Loc, Mod, Err)).
%% @doc Return an error in a common format
-spec fmt_err(string()) -> {error, string()}.
fmt_err(Fmt) ->
{error, fmt(Fmt, [])}.
-spec fmt_err(string(), list()) -> {error, string()}.
fmt_err(Fmt, Args) ->
{error, fmt(Fmt, Args)}.
-spec fmt_err(tuple() | integer(), module(), term()) -> {error, string()}.
fmt_err({1, StartCol, _EndCol}, Mod, Err) ->
fmt_err({1, StartCol}, Mod, Err);
fmt_err({1, Col}, Mod, Err) ->
{error, fmt("~s at column ~p", [Mod:format_error(Err), Col])};
fmt_err(1, Mod, Err) ->
{error, fmt(Mod:format_error(Err), [])}.
fmt(Fmt, Args) ->
lists:flatten(io_lib:format(Fmt, Args)).
| null | https://raw.githubusercontent.com/Appliscale/xprof/fbe4c1743fd9caf003ed5fd77e2ac20a4eab4349/apps/xprof_core/src/xprof_core_lib.erl | erlang | ignore crash
@doc Throw an error in a common format
@doc Return an error in a common format | -module(xprof_core_lib).
-export([mfaspec2atom/1,
mfa2atom/1,
mfaspec2id/1,
now2epoch/1,
set_mode/1,
get_mode/0,
get_mode_cb/0,
set_event_handler/1,
unset_event_handler/0,
notify_event_handler/1,
prefix/2,
prefix_rest/2,
err/1, err/2, err/3,
fmt_err/1, fmt_err/2, fmt_err/3
]).
-spec mfaspec2atom(xprof_core:mfa_spec()) -> xprof_core:mfa_name().
mfaspec2atom({MFAId, {_MSOff, _MSOn}}) ->
mfa2atom(MFAId).
-spec mfa2atom(xprof_core:mfa_id()) -> xprof_core:mfa_name().
mfa2atom({M,F,A}) ->
list_to_atom(string:join(["xprof_", atom_to_list(M),
atom_to_list(F), integer_to_list(A)], "_")).
-spec mfaspec2id(xprof_core:mfa_spec()) -> xprof_core:mfa_id().
mfaspec2id({MFAId, {_, _}}) ->
MFAId.
now2epoch({MS, S, _US}) ->
MS * 1000000 + S.
-spec set_mode(xprof_core:mode()) -> ok.
set_mode(Mode) when Mode =:= elixir; Mode =:= erlang ->
application:set_env(xprof_core, mode, Mode).
-spec get_mode() -> xprof_core:mode().
get_mode() ->
case application:get_env(xprof_core, mode) of
undefined ->
Mode = detect_mode(),
set_mode(Mode),
Mode;
{ok, Mode} ->
Mode
end.
-spec get_mode_cb() -> module().
get_mode_cb() ->
case get_mode() of
erlang -> xprof_core_erlang_syntax;
elixir -> xprof_core_elixir_syntax
end.
set_event_handler(EventHandler) ->
application:set_env(xprof_core, event_handler, EventHandler).
unset_event_handler() ->
application:unset_env(xprof_core, event_handler).
notify_event_handler(Msg) ->
case application:get_env(xprof_core, event_handler) of
undefined ->
ok;
{ok, Pid} ->
try Pid ! Msg
catch _:_ ->
{error, no_event_handler}
end
end.
-spec detect_mode() -> xprof_core:mode().
detect_mode() ->
case lists:keymember(elixir, 1, application:which_applications()) of
true -> elixir;
false -> erlang
end.
-spec prefix(binary(), binary()) -> boolean().
prefix(Prefix, Bin) ->
PrefixSize = byte_size(Prefix),
case Bin of
<<Prefix:PrefixSize/binary, _/binary>> -> true;
_ -> false
end.
-spec prefix_rest(binary(), binary()) -> false | binary().
prefix_rest(Prefix, Bin) ->
PrefixSize = byte_size(Prefix),
case Bin of
<<Prefix:PrefixSize/binary, Rest/binary>> -> Rest;
_ -> false
end.
-spec err(string()) -> no_return().
err(Fmt) ->
throw(fmt_err(Fmt)).
-spec err(string(), list()) -> no_return().
err(Fmt, Args) ->
throw(fmt_err(Fmt, Args)).
-spec err(tuple() | integer(), module(), term()) -> no_return().
err(Loc, Mod, Err) ->
throw(fmt_err(Loc, Mod, Err)).
-spec fmt_err(string()) -> {error, string()}.
fmt_err(Fmt) ->
{error, fmt(Fmt, [])}.
-spec fmt_err(string(), list()) -> {error, string()}.
fmt_err(Fmt, Args) ->
{error, fmt(Fmt, Args)}.
-spec fmt_err(tuple() | integer(), module(), term()) -> {error, string()}.
fmt_err({1, StartCol, _EndCol}, Mod, Err) ->
fmt_err({1, StartCol}, Mod, Err);
fmt_err({1, Col}, Mod, Err) ->
{error, fmt("~s at column ~p", [Mod:format_error(Err), Col])};
fmt_err(1, Mod, Err) ->
{error, fmt(Mod:format_error(Err), [])}.
fmt(Fmt, Args) ->
lists:flatten(io_lib:format(Fmt, Args)).
|
318ec587edd6904d48d499a2945b55af60f8ba20597f855dd6fd6eeb4a47bb46 | evrim/core-server | authorize.lisp | ;; -------------------------------------------------------------------------
;; Authorization
;; -------------------------------------------------------------------------
Author : >
Date : 11/3/2012
(in-package :core-server)
;; -------------------------------------------------------------------------
;; Secure Object
;; -------------------------------------------------------------------------
(defparameter +umask+
'((owner . 1) (group . 0) (other . 0) (anonymous . 0) (unauthorized . -1)))
(defclass+ secure-object ()
((owner :host local :type abstract-user :export nil :reader secure.owner
:initarg :owner :initform (error "Provide :owner"))
(group :host local :type abstract-group :export nil :reader secure.group
:initarg :group :initform (error "Provide :group"))
(levels :host local :export nil :reader secure.levels
:initform '(secure-object/unauthorized secure-object/authorized))
(permissions :host local :export nil :reader secure.permissions
:initform +umask+))
(:ctor make-secure-object))
(defclass+ secure-object/authorized ()
((secure-object :host lift :type secure-object :reader secure-object)
(owner :lift t :host local :export nil :type abstract-user
:reader secure.owner)
(group :lift t :host local :export nil :type abstract-group
:reader secure.group)
(user :host local :export nil :initform (error "Provide :user")
:type abstract-user :reader secure.user)
(current-application :host local :export nil
:initform (error "Provide :current-application")
:type application
:reader secure.application)))
(defmethod component.application ((self secure-object/authorized))
(secure.application self))
(defclass+ secure-object/unauthorized ()
((secure-object :host lift :type secure-object)
(current-application :host local :export nil
:initform (error "Provide :current-application")
:type application
:reader secure.application)))
(defmethod component.application ((self secure-object/unauthorized))
(current-application self))
;; -------------------------------------------------------------------------
;; Authorization Helpers
;; -------------------------------------------------------------------------
(defmethod level->constructor ((self secure-object) (level integer) &optional levels)
(let ((levels (or levels (secure.levels self))))
(cond
((>= level (length levels)) (car (reverse levels)))
((< level 0) (car levels))
(t (nth level levels)))))
(defmethod %secure-constructor ((self secure-object) (user anonymous-user)
&optional levels)
(let ((level (or (cdr (assoc 'anonymous (secure.permissions self)))
(cdr (assoc 'unauthorized (secure.permissions self)))
-1)))
(level->constructor self level levels)))
(defmethod %secure-constructor ((self secure-object) (user abstract-user)
&optional levels)
(let* ((levels (or levels (secure.levels self)))
(level (cond
;; Grant Maximum Permission
((or (user.has-group user "editor")
(user.has-group user "admin"))
(- (length (secure.permissions self)) 1))
Owner Match
((eq user (secure.owner self))
(cdr (assoc 'owner (secure.permissions self))))
;; Group Match
((find (group.name (secure.group self)) (user.groups user)
:key #'group.name :test #'equal)
(cdr (assoc 'group (secure.permissions self))))
;; Default Permission
(t (cdr (assoc 'other (secure.permissions self)))))))
(level->constructor self level)))
;; -------------------------------------------------------------------------
;; Authorization Protocol
;; -------------------------------------------------------------------------
(defmethod copy-lifted-slot ((self secure-object/authorized)
(slot standard-slot-definition) value)
(if (slot-definition-authorize slot)
(authorize (secure.application self) (secure.user self) value)
value))
(defmethod copy-lifted-slot ((self secure-object/unauthorized)
(slot standard-slot-definition) value)
(if (slot-definition-authorize slot)
(authorize (secure.application self) (make-anonymous-user) value)
value))
(defmethod authorize ((application application) (user abstract-user)
(object t))
object)
(defmethod authorize ((application application) (user abstract-user)
(object list))
(mapcar (curry #'authorize application user) object))
(defmethod authorize ((application application) (user abstract-user)
(object secure-object/authorized))
object)
(defmethod authorize ((application application) (user abstract-user)
(object secure-object/unauthorized))
object)
(defmethod authorize ((application application)
(user abstract-user) (object secure-object))
(apply (%secure-constructor object user)
(list :secure-object object :user user :current-application application
:owner (secure.owner object)
:group (secure.group object))))
| null | https://raw.githubusercontent.com/evrim/core-server/200ea8151d2f8d81b593d605b183a9cddae1e82d/src/security/authorize.lisp | lisp | -------------------------------------------------------------------------
Authorization
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Secure Object
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Authorization Helpers
-------------------------------------------------------------------------
Grant Maximum Permission
Group Match
Default Permission
-------------------------------------------------------------------------
Authorization Protocol
------------------------------------------------------------------------- | Author : >
Date : 11/3/2012
(in-package :core-server)
(defparameter +umask+
'((owner . 1) (group . 0) (other . 0) (anonymous . 0) (unauthorized . -1)))
(defclass+ secure-object ()
((owner :host local :type abstract-user :export nil :reader secure.owner
:initarg :owner :initform (error "Provide :owner"))
(group :host local :type abstract-group :export nil :reader secure.group
:initarg :group :initform (error "Provide :group"))
(levels :host local :export nil :reader secure.levels
:initform '(secure-object/unauthorized secure-object/authorized))
(permissions :host local :export nil :reader secure.permissions
:initform +umask+))
(:ctor make-secure-object))
(defclass+ secure-object/authorized ()
((secure-object :host lift :type secure-object :reader secure-object)
(owner :lift t :host local :export nil :type abstract-user
:reader secure.owner)
(group :lift t :host local :export nil :type abstract-group
:reader secure.group)
(user :host local :export nil :initform (error "Provide :user")
:type abstract-user :reader secure.user)
(current-application :host local :export nil
:initform (error "Provide :current-application")
:type application
:reader secure.application)))
(defmethod component.application ((self secure-object/authorized))
(secure.application self))
(defclass+ secure-object/unauthorized ()
((secure-object :host lift :type secure-object)
(current-application :host local :export nil
:initform (error "Provide :current-application")
:type application
:reader secure.application)))
(defmethod component.application ((self secure-object/unauthorized))
(current-application self))
(defmethod level->constructor ((self secure-object) (level integer) &optional levels)
(let ((levels (or levels (secure.levels self))))
(cond
((>= level (length levels)) (car (reverse levels)))
((< level 0) (car levels))
(t (nth level levels)))))
(defmethod %secure-constructor ((self secure-object) (user anonymous-user)
&optional levels)
(let ((level (or (cdr (assoc 'anonymous (secure.permissions self)))
(cdr (assoc 'unauthorized (secure.permissions self)))
-1)))
(level->constructor self level levels)))
(defmethod %secure-constructor ((self secure-object) (user abstract-user)
&optional levels)
(let* ((levels (or levels (secure.levels self)))
(level (cond
((or (user.has-group user "editor")
(user.has-group user "admin"))
(- (length (secure.permissions self)) 1))
Owner Match
((eq user (secure.owner self))
(cdr (assoc 'owner (secure.permissions self))))
((find (group.name (secure.group self)) (user.groups user)
:key #'group.name :test #'equal)
(cdr (assoc 'group (secure.permissions self))))
(t (cdr (assoc 'other (secure.permissions self)))))))
(level->constructor self level)))
(defmethod copy-lifted-slot ((self secure-object/authorized)
(slot standard-slot-definition) value)
(if (slot-definition-authorize slot)
(authorize (secure.application self) (secure.user self) value)
value))
(defmethod copy-lifted-slot ((self secure-object/unauthorized)
(slot standard-slot-definition) value)
(if (slot-definition-authorize slot)
(authorize (secure.application self) (make-anonymous-user) value)
value))
(defmethod authorize ((application application) (user abstract-user)
(object t))
object)
(defmethod authorize ((application application) (user abstract-user)
(object list))
(mapcar (curry #'authorize application user) object))
(defmethod authorize ((application application) (user abstract-user)
(object secure-object/authorized))
object)
(defmethod authorize ((application application) (user abstract-user)
(object secure-object/unauthorized))
object)
(defmethod authorize ((application application)
(user abstract-user) (object secure-object))
(apply (%secure-constructor object user)
(list :secure-object object :user user :current-application application
:owner (secure.owner object)
:group (secure.group object))))
|
30156fb9aae5a84e07b42182b87402f1d6eb688cf534c08cac371778f88e927c | informatikr/hedis | ClusterMain.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Test.Framework as Test
import Database.Redis
import Tests
main :: IO ()
main = do
-- We're looking for the cluster on a non-default port to support running
-- this test in parallel witht the regular non-cluster tests. To quickly
-- spin up a cluster on this port using docker you can run:
--
docker run -e " IP=0.0.0.0 " -p 7000 - 7010:7000 - 7010 grokzen / redis - cluster:5.0.6
conn <- connectCluster defaultConnectInfo { connectPort = PortNumber 7000 }
Test.defaultMain (tests conn)
tests :: Connection -> [Test.Test]
tests conn = map ($conn) $ concat
[ testsMisc, testsKeys, testsStrings, [testHashes], testsLists, testsSets, [testHyperLogLog]
, testsZSets, [testTransaction], [testScripting]
, testsConnection, testsServer, [testSScan, testHScan, testZScan], [testZrangelex]
, [testXAddRead, testXReadGroup, testXRange, testXpending, testXClaim, testXInfo, testXDel, testXTrim]
-- should always be run last as connection gets closed after it
, [testQuit]
]
testsServer :: [Test]
testsServer =
[testBgrewriteaof, testFlushall, testSlowlog, testDebugObject]
testsConnection :: [Test]
testsConnection = [ testConnectAuthUnexpected, testEcho, testPing
]
testsKeys :: [Test]
testsKeys = [ testKeys, testExpireAt, testSortCluster, testGetType, testObject ]
testSortCluster :: Test
testSortCluster = testCase "sort" $ do
lpush "{same}ids" ["1","2","3"] >>=? 3
sort "{same}ids" defaultSortOpts >>=? ["1","2","3"]
sortStore "{same}ids" "{same}anotherKey" defaultSortOpts >>=? 3
let opts = defaultSortOpts { sortOrder = Desc, sortAlpha = True
, sortLimit = (1,2)
, sortBy = Nothing
, sortGet = [] }
sort "{same}ids" opts >>=? ["2", "1"]
| null | https://raw.githubusercontent.com/informatikr/hedis/8b61416f44d7ae781f2cd1e4d842577971243aba/test/ClusterMain.hs | haskell | # LANGUAGE OverloadedStrings #
We're looking for the cluster on a non-default port to support running
this test in parallel witht the regular non-cluster tests. To quickly
spin up a cluster on this port using docker you can run:
should always be run last as connection gets closed after it | # LANGUAGE LambdaCase #
module Main (main) where
import qualified Test.Framework as Test
import Database.Redis
import Tests
main :: IO ()
main = do
docker run -e " IP=0.0.0.0 " -p 7000 - 7010:7000 - 7010 grokzen / redis - cluster:5.0.6
conn <- connectCluster defaultConnectInfo { connectPort = PortNumber 7000 }
Test.defaultMain (tests conn)
tests :: Connection -> [Test.Test]
tests conn = map ($conn) $ concat
[ testsMisc, testsKeys, testsStrings, [testHashes], testsLists, testsSets, [testHyperLogLog]
, testsZSets, [testTransaction], [testScripting]
, testsConnection, testsServer, [testSScan, testHScan, testZScan], [testZrangelex]
, [testXAddRead, testXReadGroup, testXRange, testXpending, testXClaim, testXInfo, testXDel, testXTrim]
, [testQuit]
]
testsServer :: [Test]
testsServer =
[testBgrewriteaof, testFlushall, testSlowlog, testDebugObject]
testsConnection :: [Test]
testsConnection = [ testConnectAuthUnexpected, testEcho, testPing
]
testsKeys :: [Test]
testsKeys = [ testKeys, testExpireAt, testSortCluster, testGetType, testObject ]
testSortCluster :: Test
testSortCluster = testCase "sort" $ do
lpush "{same}ids" ["1","2","3"] >>=? 3
sort "{same}ids" defaultSortOpts >>=? ["1","2","3"]
sortStore "{same}ids" "{same}anotherKey" defaultSortOpts >>=? 3
let opts = defaultSortOpts { sortOrder = Desc, sortAlpha = True
, sortLimit = (1,2)
, sortBy = Nothing
, sortGet = [] }
sort "{same}ids" opts >>=? ["2", "1"]
|
564d5713757d7532068d9272496921d8d0fc3f22226d4d6c48d53e33e542730e | acieroid/scala-am | mutex2.scm | (letrec ((lock (atom #f))
(acq (lambda ()
(if (compare-and-set! lock #f #t)
#t
(acq))))
(rel (lambda ()
(set! lock #f)))
(counter 0)
(inc (lambda ()
(acq)
(set! counter (+ counter 1))
(rel)))
(t1 (future (inc)))
(t2 (future (inc))))
(deref t1)
(deref t2)
(= counter 2)) | null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/futures/variations/mutex2.scm | scheme | (letrec ((lock (atom #f))
(acq (lambda ()
(if (compare-and-set! lock #f #t)
#t
(acq))))
(rel (lambda ()
(set! lock #f)))
(counter 0)
(inc (lambda ()
(acq)
(set! counter (+ counter 1))
(rel)))
(t1 (future (inc)))
(t2 (future (inc))))
(deref t1)
(deref t2)
(= counter 2)) |
|
abcc592ad7e5574dd8c57c1153a786bcc01d442d06ea9cdc1487faab5db64ec0 | oxidizing/letters | test.ml | open Letters
let stream_to_string s =
let b = Buffer.create 4096 in
let rec go () =
match s () with
| Some (buf, off, len) ->
Buffer.add_substring b buf off len;
go ()
| None -> Buffer.contents b
in
go ()
;;
let test_create_plain_text_email _ () =
let recipients = [ To "" ] in
let subject = "Hello" in
let body = Plain "Hello Dave" in
let mail = create_email ~from:"" ~recipients ~subject ~body () in
let stream =
match mail with
| Ok mail -> Mrmime.Mt.to_stream mail
| Error reason -> failwith reason
in
let message = stream_to_string stream in
Lwt.return (print_string message)
;;
let test_create_html_email _ () =
let recipients = [ To "" ] in
let subject = "Hello" in
let body = Html "<i>Hello Dave</i>" in
let mail = create_email ~from:"" ~recipients ~subject ~body () in
let stream =
match mail with
| Ok mail -> Mrmime.Mt.to_stream mail
| Error reason -> failwith reason
in
let message = stream_to_string stream in
Lwt.return (print_string message)
;;
let test_create_mixed_body_email _ () =
let recipients = [ To "" ] in
let subject = "Hello" in
let body = Mixed ("Hello Dave", "<i>Hello Dave</i>", Some "blaablaa") in
let mail = create_email ~from:"" ~recipients ~subject ~body () in
let stream =
match mail with
| Ok mail -> Mrmime.Mt.to_stream mail
| Error reason -> failwith reason
in
let message = stream_to_string stream in
Lwt.return (print_string message)
;;
let test_create_config () =
(* check for config compatibility *)
let username, password, hostname, with_starttls =
"SomeUser", "password", "localhost", true
in
let[@warning "-3"] (_ : Config.t) =
Config.make ~username ~password ~hostname ~with_starttls
in
let (_ : Config.t) = Config.create ~username ~password ~hostname ~with_starttls () in
let (_ : Config.t) =
Config.create
~mechanism:Sendmail.LOGIN
~username
~password
~hostname
~with_starttls
()
in
()
;;
let () =
let () =
Alcotest.(
run "model" [ "config", [ test_case "create config" `Quick test_create_config ] ])
in
Lwt_main.run
(Alcotest_lwt.run
"Email creation"
[ ( "Generating body"
, [ Alcotest_lwt.test_case
"email with plain text body"
`Quick
test_create_plain_text_email
; Alcotest_lwt.test_case
"email with HTML text body"
`Quick
test_create_html_email
; Alcotest_lwt.test_case
"email with mixed plain text and HTML body"
`Quick
test_create_mixed_body_email
] )
])
;;
| null | https://raw.githubusercontent.com/oxidizing/letters/35f7594d15e3e670a5b99c8f6f75248bad9f7f85/test/test.ml | ocaml | check for config compatibility | open Letters
let stream_to_string s =
let b = Buffer.create 4096 in
let rec go () =
match s () with
| Some (buf, off, len) ->
Buffer.add_substring b buf off len;
go ()
| None -> Buffer.contents b
in
go ()
;;
let test_create_plain_text_email _ () =
let recipients = [ To "" ] in
let subject = "Hello" in
let body = Plain "Hello Dave" in
let mail = create_email ~from:"" ~recipients ~subject ~body () in
let stream =
match mail with
| Ok mail -> Mrmime.Mt.to_stream mail
| Error reason -> failwith reason
in
let message = stream_to_string stream in
Lwt.return (print_string message)
;;
let test_create_html_email _ () =
let recipients = [ To "" ] in
let subject = "Hello" in
let body = Html "<i>Hello Dave</i>" in
let mail = create_email ~from:"" ~recipients ~subject ~body () in
let stream =
match mail with
| Ok mail -> Mrmime.Mt.to_stream mail
| Error reason -> failwith reason
in
let message = stream_to_string stream in
Lwt.return (print_string message)
;;
let test_create_mixed_body_email _ () =
let recipients = [ To "" ] in
let subject = "Hello" in
let body = Mixed ("Hello Dave", "<i>Hello Dave</i>", Some "blaablaa") in
let mail = create_email ~from:"" ~recipients ~subject ~body () in
let stream =
match mail with
| Ok mail -> Mrmime.Mt.to_stream mail
| Error reason -> failwith reason
in
let message = stream_to_string stream in
Lwt.return (print_string message)
;;
let test_create_config () =
let username, password, hostname, with_starttls =
"SomeUser", "password", "localhost", true
in
let[@warning "-3"] (_ : Config.t) =
Config.make ~username ~password ~hostname ~with_starttls
in
let (_ : Config.t) = Config.create ~username ~password ~hostname ~with_starttls () in
let (_ : Config.t) =
Config.create
~mechanism:Sendmail.LOGIN
~username
~password
~hostname
~with_starttls
()
in
()
;;
let () =
let () =
Alcotest.(
run "model" [ "config", [ test_case "create config" `Quick test_create_config ] ])
in
Lwt_main.run
(Alcotest_lwt.run
"Email creation"
[ ( "Generating body"
, [ Alcotest_lwt.test_case
"email with plain text body"
`Quick
test_create_plain_text_email
; Alcotest_lwt.test_case
"email with HTML text body"
`Quick
test_create_html_email
; Alcotest_lwt.test_case
"email with mixed plain text and HTML body"
`Quick
test_create_mixed_body_email
] )
])
;;
|
9e74d7b47d5c263eb8d19b66cb1058f28aa9da17f9a1840d30400e56f807448d | noitcudni/google-search-console-bulk-url-removal | project.clj | (defproject noitcudni/google-webmaster-tools-bulk-url-removal "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"]
[org.clojure/core.async "0.4.500"]
[binaryage/chromex "0.8.1"]
;; [binaryage/chromex "0.8.5"]
[binaryage/devtools "0.9.10"]
[com.cognitect/transit-cljs "0.8.256"]
[com.andrewmcveigh/cljs-time "0.5.2"]
[com.cemerick/url "0.1.1"]
[hipo "0.5.2"]
[prismatic/dommy "1.1.0"]
[testdouble/clojurescript.csv "0.4.5"]
[domina "1.0.3"]
[reagent "0.8.1"]
[re-com "2.6.0"]
[figwheel "0.5.19"]
[environ "1.1.0"]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.19"]
[lein-shell "0.5.0"]
[lein-environ "1.1.0"]
[lein-cooper "1.2.2"]]
:source-paths ["src/background"
"src/popup"
"src/content_script"]
:clean-targets ^{:protect false} ["target"
"resources/unpacked/compiled"
"resources/release/compiled"]
prevent -cljsbuild/issues/413
:profiles {:unpacked
{:cljsbuild {:builds
{:background
{:source-paths ["src/background"]
:figwheel true
:compiler {:output-to "resources/unpacked/compiled/background/main.js"
:output-dir "resources/unpacked/compiled/background"
:asset-path "compiled/background"
:preloads [devtools.preload figwheel.preload]
:main google-webmaster-tools-bulk-url-removal.background
:optimizations :none
:source-map true}}
:popup
{:source-paths ["src/popup"]
:figwheel true
:compiler {:output-to "resources/unpacked/compiled/popup/main.js"
:output-dir "resources/unpacked/compiled/popup"
:asset-path "compiled/popup"
:preloads [devtools.preload figwheel.preload]
:main google-webmaster-tools-bulk-url-removal.popup
:optimizations :none
:source-map true}}}}}
:unpacked-content-script
{:cljsbuild {:builds
{:content-script
{:source-paths ["src/content_script"]
:compiler {:output-to "resources/unpacked/compiled/content-script/main.js"
:output-dir "resources/unpacked/compiled/content-script"
:asset-path "compiled/content-script"
:main google-webmaster-tools-bulk-url-removal.content-script
;:optimizations :whitespace ; content scripts cannot do eval / load script dynamically
let 's use advanced build with pseudo - names for now , there seems to be a bug in ordering under : whitespace mode
:pseudo-names true
:pretty-print true}}
;; :content-script-2
;; {:source-paths ["src/content_script"]
;; :compiler {:output-to "resources/unpacked/compiled/removals_request/removals_request.js"
;; :output-dir "resources/unpacked/compiled/removals_request"
;; :asset-path "compiled/removals_request"
;; :main google-webmaster-tools-bulk-url-removal.removals-request
;; ;:optimizations :whitespace ; content scripts cannot do eval / load script dynamically
: optimizations : advanced ; let 's use advanced build with pseudo - names for now , there seems to be a bug in ordering under : whitespace mode
;; :pseudo-names true
;; :pretty-print true}}
}}}
:checkouts
; DON'T FORGET TO UPDATE scripts/ensure-checkouts.sh
{:cljsbuild {:builds
{:background {:source-paths ["checkouts/cljs-devtools/src/lib"
"checkouts/chromex/src/lib"
"checkouts/chromex/src/exts"]}
:popup {:source-paths ["checkouts/cljs-devtools/src/lib"
"checkouts/chromex/src/lib"
"checkouts/chromex/src/exts"]}}}}
:checkouts-content-script
; DON'T FORGET TO UPDATE scripts/ensure-checkouts.sh
{:cljsbuild {:builds
{:content-script {:source-paths ["checkouts/cljs-devtools/src/lib"
"checkouts/chromex/src/lib"
"checkouts/chromex/src/exts"]}
;; :content-script-2 {:source-paths ["checkouts/cljs-devtools/src/lib"
" checkouts / chromex / src / lib "
" checkouts / chromex / src / exts " ] }
}}}
:figwheel
{:figwheel {:server-port 6888
:server-logfile ".figwheel.log"
:repl true}}
:disable-figwheel-repl
{:figwheel {:repl false}}
:cooper
{:cooper {"content-dev" ["lein" "content-dev"]
"fig-dev-no-repl" ["lein" "fig-dev-no-repl"]
"browser" ["scripts/launch-test-browser.sh"]}}
:release
{:env {:chromex-elide-verbose-logging "true"}
:cljsbuild {:builds
{:background
{:source-paths ["src/background"]
:compiler {:output-to "resources/release/compiled/background.js"
:output-dir "resources/release/compiled/background"
:asset-path "compiled/background"
:main google-webmaster-tools-bulk-url-removal.background
:optimizations :advanced
:elide-asserts true}}
:popup
{:source-paths ["src/popup"]
:compiler {:output-to "resources/release/compiled/popup.js"
:output-dir "resources/release/compiled/popup"
:asset-path "compiled/popup"
:main google-webmaster-tools-bulk-url-removal.popup
:optimizations :advanced
:elide-asserts true}}
:content-script
{:source-paths ["src/content_script"]
:compiler {:output-to "resources/release/compiled/content-script.js"
:output-dir "resources/release/compiled/content-script"
:asset-path "compiled/content-script"
:main google-webmaster-tools-bulk-url-removal.content-script
:optimizations :advanced
:elide-asserts true}}
;; :content-script-2
;; {:source-paths ["src/content_script"]
;; :compiler {:output-to "resources/release/compiled/removals_request.js"
;; :output-dir "resources/release/compiled/removals_request"
;; :asset-path "compiled/removals_request"
;; :main google-webmaster-tools-bulk-url-removal.removals-request
;; :optimizations :advanced
;; :elide-asserts true}}
}}}}
:aliases {"dev-build" ["with-profile" "+unpacked,+unpacked-content-script,+checkouts,+checkouts-content-script" "cljsbuild" "once"]
"fig" ["with-profile" "+unpacked,+figwheel" "figwheel" "background" "popup"]
" content " [ " with - profile " " + unpacked - content - script " " cljsbuild " " auto " " content - script " " content - script-2 " ]
"content" ["with-profile" "+unpacked-content-script" "cljsbuild" "auto" "content-script"]
"fig-dev-no-repl" ["with-profile" "+unpacked,+figwheel,+disable-figwheel-repl,+checkouts" "figwheel" "background" "popup"]
"content-dev" ["with-profile" "+unpacked-content-script,+checkouts-content-script" "cljsbuild" "auto"]
"devel" ["with-profile" "+cooper" "do" ; for mac only
["shell" "scripts/ensure-checkouts.sh"]
["cooper"]]
"release" ["with-profile" "+release" "do"
["clean"]
;; ["cljsbuild" "once" "background" "popup" "content-script" "content-script-2"]
["cljsbuild" "once" "background" "popup" "content-script"]
]
"package" ["shell" "scripts/package.sh"]})
| null | https://raw.githubusercontent.com/noitcudni/google-search-console-bulk-url-removal/0f922c7301e26fba0c7ec75e73e4f8df29962348/project.clj | clojure | [binaryage/chromex "0.8.5"]
:optimizations :whitespace ; content scripts cannot do eval / load script dynamically
:content-script-2
{:source-paths ["src/content_script"]
:compiler {:output-to "resources/unpacked/compiled/removals_request/removals_request.js"
:output-dir "resources/unpacked/compiled/removals_request"
:asset-path "compiled/removals_request"
:main google-webmaster-tools-bulk-url-removal.removals-request
;:optimizations :whitespace ; content scripts cannot do eval / load script dynamically
let 's use advanced build with pseudo - names for now , there seems to be a bug in ordering under : whitespace mode
:pseudo-names true
:pretty-print true}}
DON'T FORGET TO UPDATE scripts/ensure-checkouts.sh
DON'T FORGET TO UPDATE scripts/ensure-checkouts.sh
:content-script-2 {:source-paths ["checkouts/cljs-devtools/src/lib"
:content-script-2
{:source-paths ["src/content_script"]
:compiler {:output-to "resources/release/compiled/removals_request.js"
:output-dir "resources/release/compiled/removals_request"
:asset-path "compiled/removals_request"
:main google-webmaster-tools-bulk-url-removal.removals-request
:optimizations :advanced
:elide-asserts true}}
for mac only
["cljsbuild" "once" "background" "popup" "content-script" "content-script-2"] | (defproject noitcudni/google-webmaster-tools-bulk-url-removal "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/clojurescript "1.10.520"]
[org.clojure/core.async "0.4.500"]
[binaryage/chromex "0.8.1"]
[binaryage/devtools "0.9.10"]
[com.cognitect/transit-cljs "0.8.256"]
[com.andrewmcveigh/cljs-time "0.5.2"]
[com.cemerick/url "0.1.1"]
[hipo "0.5.2"]
[prismatic/dommy "1.1.0"]
[testdouble/clojurescript.csv "0.4.5"]
[domina "1.0.3"]
[reagent "0.8.1"]
[re-com "2.6.0"]
[figwheel "0.5.19"]
[environ "1.1.0"]]
:plugins [[lein-cljsbuild "1.1.7"]
[lein-figwheel "0.5.19"]
[lein-shell "0.5.0"]
[lein-environ "1.1.0"]
[lein-cooper "1.2.2"]]
:source-paths ["src/background"
"src/popup"
"src/content_script"]
:clean-targets ^{:protect false} ["target"
"resources/unpacked/compiled"
"resources/release/compiled"]
prevent -cljsbuild/issues/413
:profiles {:unpacked
{:cljsbuild {:builds
{:background
{:source-paths ["src/background"]
:figwheel true
:compiler {:output-to "resources/unpacked/compiled/background/main.js"
:output-dir "resources/unpacked/compiled/background"
:asset-path "compiled/background"
:preloads [devtools.preload figwheel.preload]
:main google-webmaster-tools-bulk-url-removal.background
:optimizations :none
:source-map true}}
:popup
{:source-paths ["src/popup"]
:figwheel true
:compiler {:output-to "resources/unpacked/compiled/popup/main.js"
:output-dir "resources/unpacked/compiled/popup"
:asset-path "compiled/popup"
:preloads [devtools.preload figwheel.preload]
:main google-webmaster-tools-bulk-url-removal.popup
:optimizations :none
:source-map true}}}}}
:unpacked-content-script
{:cljsbuild {:builds
{:content-script
{:source-paths ["src/content_script"]
:compiler {:output-to "resources/unpacked/compiled/content-script/main.js"
:output-dir "resources/unpacked/compiled/content-script"
:asset-path "compiled/content-script"
:main google-webmaster-tools-bulk-url-removal.content-script
let 's use advanced build with pseudo - names for now , there seems to be a bug in ordering under : whitespace mode
:pseudo-names true
:pretty-print true}}
}}}
:checkouts
{:cljsbuild {:builds
{:background {:source-paths ["checkouts/cljs-devtools/src/lib"
"checkouts/chromex/src/lib"
"checkouts/chromex/src/exts"]}
:popup {:source-paths ["checkouts/cljs-devtools/src/lib"
"checkouts/chromex/src/lib"
"checkouts/chromex/src/exts"]}}}}
:checkouts-content-script
{:cljsbuild {:builds
{:content-script {:source-paths ["checkouts/cljs-devtools/src/lib"
"checkouts/chromex/src/lib"
"checkouts/chromex/src/exts"]}
" checkouts / chromex / src / lib "
" checkouts / chromex / src / exts " ] }
}}}
:figwheel
{:figwheel {:server-port 6888
:server-logfile ".figwheel.log"
:repl true}}
:disable-figwheel-repl
{:figwheel {:repl false}}
:cooper
{:cooper {"content-dev" ["lein" "content-dev"]
"fig-dev-no-repl" ["lein" "fig-dev-no-repl"]
"browser" ["scripts/launch-test-browser.sh"]}}
:release
{:env {:chromex-elide-verbose-logging "true"}
:cljsbuild {:builds
{:background
{:source-paths ["src/background"]
:compiler {:output-to "resources/release/compiled/background.js"
:output-dir "resources/release/compiled/background"
:asset-path "compiled/background"
:main google-webmaster-tools-bulk-url-removal.background
:optimizations :advanced
:elide-asserts true}}
:popup
{:source-paths ["src/popup"]
:compiler {:output-to "resources/release/compiled/popup.js"
:output-dir "resources/release/compiled/popup"
:asset-path "compiled/popup"
:main google-webmaster-tools-bulk-url-removal.popup
:optimizations :advanced
:elide-asserts true}}
:content-script
{:source-paths ["src/content_script"]
:compiler {:output-to "resources/release/compiled/content-script.js"
:output-dir "resources/release/compiled/content-script"
:asset-path "compiled/content-script"
:main google-webmaster-tools-bulk-url-removal.content-script
:optimizations :advanced
:elide-asserts true}}
}}}}
:aliases {"dev-build" ["with-profile" "+unpacked,+unpacked-content-script,+checkouts,+checkouts-content-script" "cljsbuild" "once"]
"fig" ["with-profile" "+unpacked,+figwheel" "figwheel" "background" "popup"]
" content " [ " with - profile " " + unpacked - content - script " " cljsbuild " " auto " " content - script " " content - script-2 " ]
"content" ["with-profile" "+unpacked-content-script" "cljsbuild" "auto" "content-script"]
"fig-dev-no-repl" ["with-profile" "+unpacked,+figwheel,+disable-figwheel-repl,+checkouts" "figwheel" "background" "popup"]
"content-dev" ["with-profile" "+unpacked-content-script,+checkouts-content-script" "cljsbuild" "auto"]
["shell" "scripts/ensure-checkouts.sh"]
["cooper"]]
"release" ["with-profile" "+release" "do"
["clean"]
["cljsbuild" "once" "background" "popup" "content-script"]
]
"package" ["shell" "scripts/package.sh"]})
|
e33ac12573e61cecfb575e4363c05e259c7b2ef8e4a71eb217ffeb327a650b73 | achirkin/vulkan | VK_EXT_shader_demote_to_helper_invocation.hs | # OPTIONS_HADDOCK not - home #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MagicHash #-}
# LANGUAGE PatternSynonyms #
{-# LANGUAGE Strict #-}
{-# LANGUAGE ViewPatterns #-}
module Graphics.Vulkan.Ext.VK_EXT_shader_demote_to_helper_invocation
* Vulkan extension : @VK_EXT_shader_demote_to_helper_invocation@
-- |
--
-- supported: @vulkan@
--
contact : @Jeff Bolz @jeffbolznv@
--
-- author: @EXT@
--
-- type: @device@
--
Extension number :
--
-- Required extensions: 'VK_KHR_get_physical_device_properties2'.
--
-- ** Required extensions: 'VK_KHR_get_physical_device_properties2'.
module Graphics.Vulkan.Marshal, AHardwareBuffer(),
ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkPhysicalDeviceFeatures,
VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT,
VkStructureType(..),
-- > #include "vk_platform.h"
VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION,
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION,
VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME,
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION = 1
type VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION = 1
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ::
CString
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME <-
(is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ->
True)
where
VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
= _VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
# INLINE _ VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
#
#-}
_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ::
CString
_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
= Ptr "VK_EXT_shader_demote_to_helper_invocation\NUL"#
{-# INLINE is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
#-}
is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ::
CString -> Bool
is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
= (EQ ==) .
cmpCStrings
_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
type VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME =
"VK_EXT_shader_demote_to_helper_invocation"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT
= VkStructureType 1000276000
| null | https://raw.githubusercontent.com/achirkin/vulkan/b2e0568c71b5135010f4bba939cd8dcf7a05c361/vulkan-api/src-gen/Graphics/Vulkan/Ext/VK_EXT_shader_demote_to_helper_invocation.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE MagicHash #
# LANGUAGE Strict #
# LANGUAGE ViewPatterns #
|
supported: @vulkan@
author: @EXT@
type: @device@
Required extensions: 'VK_KHR_get_physical_device_properties2'.
** Required extensions: 'VK_KHR_get_physical_device_properties2'.
> #include "vk_platform.h"
# INLINE is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
# | # OPTIONS_HADDOCK not - home #
# LANGUAGE PatternSynonyms #
module Graphics.Vulkan.Ext.VK_EXT_shader_demote_to_helper_invocation
* Vulkan extension : @VK_EXT_shader_demote_to_helper_invocation@
contact : @Jeff Bolz @jeffbolznv@
Extension number :
module Graphics.Vulkan.Marshal, AHardwareBuffer(),
ANativeWindow(), CAMetalLayer(), VkBool32(..), VkDeviceAddress(..),
VkDeviceSize(..), VkFlags(..), VkSampleMask(..),
VkAndroidSurfaceCreateFlagsKHR(..), VkBufferViewCreateFlags(..),
VkBuildAccelerationStructureFlagsNV(..),
VkCommandPoolTrimFlags(..), VkCommandPoolTrimFlagsKHR(..),
VkDebugUtilsMessengerCallbackDataFlagsEXT(..),
VkDebugUtilsMessengerCreateFlagsEXT(..),
VkDescriptorBindingFlagsEXT(..), VkDescriptorPoolResetFlags(..),
VkDescriptorUpdateTemplateCreateFlags(..),
VkDescriptorUpdateTemplateCreateFlagsKHR(..),
VkDeviceCreateFlags(..), VkDirectFBSurfaceCreateFlagsEXT(..),
VkDisplayModeCreateFlagsKHR(..),
VkDisplaySurfaceCreateFlagsKHR(..), VkEventCreateFlags(..),
VkExternalFenceFeatureFlagsKHR(..),
VkExternalFenceHandleTypeFlagsKHR(..),
VkExternalMemoryFeatureFlagsKHR(..),
VkExternalMemoryHandleTypeFlagsKHR(..),
VkExternalSemaphoreFeatureFlagsKHR(..),
VkExternalSemaphoreHandleTypeFlagsKHR(..),
VkFenceImportFlagsKHR(..), VkGeometryFlagsNV(..),
VkGeometryInstanceFlagsNV(..), VkHeadlessSurfaceCreateFlagsEXT(..),
VkIOSSurfaceCreateFlagsMVK(..),
VkImagePipeSurfaceCreateFlagsFUCHSIA(..),
VkInstanceCreateFlags(..), VkMacOSSurfaceCreateFlagsMVK(..),
VkMemoryAllocateFlagsKHR(..), VkMemoryMapFlags(..),
VkMetalSurfaceCreateFlagsEXT(..), VkPeerMemoryFeatureFlagsKHR(..),
VkPipelineColorBlendStateCreateFlags(..),
VkPipelineCoverageModulationStateCreateFlagsNV(..),
VkPipelineCoverageReductionStateCreateFlagsNV(..),
VkPipelineCoverageToColorStateCreateFlagsNV(..),
VkPipelineDepthStencilStateCreateFlags(..),
VkPipelineDiscardRectangleStateCreateFlagsEXT(..),
VkPipelineDynamicStateCreateFlags(..),
VkPipelineInputAssemblyStateCreateFlags(..),
VkPipelineLayoutCreateFlags(..),
VkPipelineMultisampleStateCreateFlags(..),
VkPipelineRasterizationConservativeStateCreateFlagsEXT(..),
VkPipelineRasterizationDepthClipStateCreateFlagsEXT(..),
VkPipelineRasterizationStateCreateFlags(..),
VkPipelineRasterizationStateStreamCreateFlagsEXT(..),
VkPipelineTessellationStateCreateFlags(..),
VkPipelineVertexInputStateCreateFlags(..),
VkPipelineViewportStateCreateFlags(..),
VkPipelineViewportSwizzleStateCreateFlagsNV(..),
VkQueryPoolCreateFlags(..), VkResolveModeFlagsKHR(..),
VkSemaphoreCreateFlags(..), VkSemaphoreImportFlagsKHR(..),
VkSemaphoreWaitFlagsKHR(..),
VkStreamDescriptorSurfaceCreateFlagsGGP(..),
VkValidationCacheCreateFlagsEXT(..), VkViSurfaceCreateFlagsNN(..),
VkWaylandSurfaceCreateFlagsKHR(..),
VkWin32SurfaceCreateFlagsKHR(..), VkXcbSurfaceCreateFlagsKHR(..),
VkXlibSurfaceCreateFlagsKHR(..), VkDeviceCreateInfo,
VkDeviceDiagnosticsConfigBitmaskNV(..), VkDeviceEventTypeEXT(..),
VkDeviceGroupPresentModeBitmaskKHR(..), VkDeviceCreateFlagBits(..),
VkDeviceDiagnosticsConfigFlagBitsNV(),
VkDeviceDiagnosticsConfigFlagsNV(),
VkDeviceGroupPresentModeFlagBitsKHR(),
VkDeviceGroupPresentModeFlagsKHR(), VkDeviceQueueCreateBitmask(..),
VkDeviceQueueCreateFlagBits(), VkDeviceQueueCreateFlags(),
VkDeviceQueueCreateInfo, VkPhysicalDeviceFeatures,
VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT,
VkStructureType(..),
VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION,
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION,
VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME,
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME,
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT)
where
import GHC.Ptr (Ptr (..))
import Graphics.Vulkan.Marshal
import Graphics.Vulkan.Types.BaseTypes
import Graphics.Vulkan.Types.Bitmasks
import Graphics.Vulkan.Types.Enum.Device
import Graphics.Vulkan.Types.Enum.StructureType
import Graphics.Vulkan.Types.Struct.Device (VkDeviceCreateInfo, VkDeviceQueueCreateInfo)
import Graphics.Vulkan.Types.Struct.PhysicalDevice (VkPhysicalDeviceFeatures2,
VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT)
import Graphics.Vulkan.Types.Struct.PhysicalDeviceFeatures (VkPhysicalDeviceFeatures)
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION ::
(Num a, Eq a) => a
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION = 1
type VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_SPEC_VERSION = 1
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ::
CString
pattern VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME <-
(is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ->
True)
where
VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
= _VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
# INLINE _ VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
#
#-}
_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ::
CString
_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
= Ptr "VK_EXT_shader_demote_to_helper_invocation\NUL"#
is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME ::
CString -> Bool
is_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
= (EQ ==) .
cmpCStrings
_VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME
type VK_EXT_SHADER_DEMOTE_TO_HELPER_INVOCATION_EXTENSION_NAME =
"VK_EXT_shader_demote_to_helper_invocation"
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT
:: VkStructureType
pattern VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT
= VkStructureType 1000276000
|
78e5b3e0c8634150960255fce143e6384c793eb8c80a88950d147d7d4084f001 | b0-system/b0 | b0_cmd_log.ml | ---------------------------------------------------------------------------
Copyright ( c ) 2020 The b0 programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2020 The b0 programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open B0_std
open B0_std.Result.Syntax
let log c details format op_selector =
Log.if_error ~use:B00_cli.Exit.some_error @@
let don't = B0_driver.Conf.no_pager c || format = `Trace_event in
let b0_dir = B0_driver.Conf.b0_dir c in
(* FIXME
This should also be fixed b00-cache / B00_cli.Memo.log_file *)
let log_file = Fpath.(b0_dir / "b" / "user" / "_log") in
let* pager = B00_pager.find ~don't () in
let* () = B00_pager.page_stdout pager in
let* l = B00_cli.Memo.Log.read log_file in
B00_cli.Memo.Log.out Fmt.stdout format details op_selector ~path:log_file l;
Ok B00_cli.Exit.ok
(* Command line interface *)
open Cmdliner
let cmd =
let doc = "Show build logs" in
let exits = B0_driver.Exit.infos in
let man = [
`S Manpage.s_description;
`P "The $(tname) command shows build information and operations in \
various formats.";
`S Manpage.s_options;
`S B00_cli.s_output_format_options;
`S B00_cli.Op.s_selection_options;
`Blocks B00_cli.Op.query_man;
B0_b0.Cli.man_see_manual; ]
in
Cmd.v (Cmd.info "log" ~doc ~exits ~man)
Term.(const log $ B0_driver.Cli.conf $ B00_cli.Arg.output_format () $
B00_cli.Memo.Log.out_format_cli () $ B00_cli.Op.query_cli ())
---------------------------------------------------------------------------
Copyright ( c ) 2020 The b0 programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2020 The b0 programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/b0-system/b0/cbe12b8a55da6b50ab01ed058b339dbed3cfe894/tool-b0/b0_cmd_log.ml | ocaml | FIXME
This should also be fixed b00-cache / B00_cli.Memo.log_file
Command line interface | ---------------------------------------------------------------------------
Copyright ( c ) 2020 The b0 programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2020 The b0 programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open B0_std
open B0_std.Result.Syntax
let log c details format op_selector =
Log.if_error ~use:B00_cli.Exit.some_error @@
let don't = B0_driver.Conf.no_pager c || format = `Trace_event in
let b0_dir = B0_driver.Conf.b0_dir c in
let log_file = Fpath.(b0_dir / "b" / "user" / "_log") in
let* pager = B00_pager.find ~don't () in
let* () = B00_pager.page_stdout pager in
let* l = B00_cli.Memo.Log.read log_file in
B00_cli.Memo.Log.out Fmt.stdout format details op_selector ~path:log_file l;
Ok B00_cli.Exit.ok
open Cmdliner
let cmd =
let doc = "Show build logs" in
let exits = B0_driver.Exit.infos in
let man = [
`S Manpage.s_description;
`P "The $(tname) command shows build information and operations in \
various formats.";
`S Manpage.s_options;
`S B00_cli.s_output_format_options;
`S B00_cli.Op.s_selection_options;
`Blocks B00_cli.Op.query_man;
B0_b0.Cli.man_see_manual; ]
in
Cmd.v (Cmd.info "log" ~doc ~exits ~man)
Term.(const log $ B0_driver.Cli.conf $ B00_cli.Arg.output_format () $
B00_cli.Memo.Log.out_format_cli () $ B00_cli.Op.query_cli ())
---------------------------------------------------------------------------
Copyright ( c ) 2020 The b0 programmers
Permission to use , copy , modify , and/or distribute this software for any
purpose with or without fee is hereby granted , provided that the above
copyright notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
---------------------------------------------------------------------------
Copyright (c) 2020 The b0 programmers
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---------------------------------------------------------------------------*)
|
45cae2503c2239d1b98dee20014f3b7a20696b7afb6cc832f06b281eba86d551 | jarvinet/scheme | section334_sample_simulation.scm | ;;; Sample simulation
(define the-agenda (make-agenda))
(define inverter-delay 2)
(define and-gate-delay 3)
(define or-gate-delay 5)
(define input-1 (make-wire))
(define input-2 (make-wire))
(define sum (make-wire))
(define carry (make-wire))
(probe 'sum sum)
(probe 'carry carry)
(half-adder input-1 input-2 sum carry)
(set-signal! input-1 1)
(propagate)
(set-signal! input-2 1)
(propagate)
| null | https://raw.githubusercontent.com/jarvinet/scheme/47633d7fc4d82d739a62ceec75c111f6549b1650/Book/Edition1/section334_sample_simulation.scm | scheme | Sample simulation |
(define the-agenda (make-agenda))
(define inverter-delay 2)
(define and-gate-delay 3)
(define or-gate-delay 5)
(define input-1 (make-wire))
(define input-2 (make-wire))
(define sum (make-wire))
(define carry (make-wire))
(probe 'sum sum)
(probe 'carry carry)
(half-adder input-1 input-2 sum carry)
(set-signal! input-1 1)
(propagate)
(set-signal! input-2 1)
(propagate)
|
cff52efa12324a3b4dbcc0fa75e01308de4d0f1f561891c0dc1c3cbb2313d00b | slipstream/SlipStreamServer | acl.clj | (ns com.sixsq.slipstream.db.es.acl
(:require
[com.sixsq.slipstream.db.es.filter :as ef]
[com.sixsq.slipstream.db.utils.acl :as acl-utils]))
(def ^:private query-no-result (ef/term-query "id" ""))
(defn and-acl
"Enriches query-builder by adding a clause on ACL (extracted from options)"
[query-builder {:keys [user-name user-roles] :as options}]
(let [user-name-clause (when user-name [[(name acl-utils/acl-users) user-name]])
user-roles-clauses (map vector (repeat (name acl-utils/acl-roles)) user-roles)
acl-clauses (concat user-name-clause user-roles-clauses)
acl-queries (map (fn [[field value]] (ef/term-query field value)) acl-clauses)
query-acl (if (empty? acl-queries) query-no-result (ef/or-query acl-queries))]
(ef/and-query [query-acl query-builder])))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/db-binding/src/com/sixsq/slipstream/db/es/acl.clj | clojure | (ns com.sixsq.slipstream.db.es.acl
(:require
[com.sixsq.slipstream.db.es.filter :as ef]
[com.sixsq.slipstream.db.utils.acl :as acl-utils]))
(def ^:private query-no-result (ef/term-query "id" ""))
(defn and-acl
"Enriches query-builder by adding a clause on ACL (extracted from options)"
[query-builder {:keys [user-name user-roles] :as options}]
(let [user-name-clause (when user-name [[(name acl-utils/acl-users) user-name]])
user-roles-clauses (map vector (repeat (name acl-utils/acl-roles)) user-roles)
acl-clauses (concat user-name-clause user-roles-clauses)
acl-queries (map (fn [[field value]] (ef/term-query field value)) acl-clauses)
query-acl (if (empty? acl-queries) query-no-result (ef/or-query acl-queries))]
(ef/and-query [query-acl query-builder])))
|
|
1b43f324a76e8b87b0687bce0d0dba1d69e6e34ffd1b14f9eae444758c3c9b8a | gdamore/tree-sitter-d | typeof.scm | ==================
Typeof expression
==================
auto t = typeof(0);
---
(source_file
(auto_declaration
(storage_class (auto))
(identifier)
(typeof_expression (typeof) (expression (int_literal)))
)
)
==================
Typeof expression (return)
==================
auto t = typeof (return);
---
(source_file
(auto_declaration
(storage_class (auto))
(identifier)
(typeof_expression (typeof) (return))
)
)
| null | https://raw.githubusercontent.com/gdamore/tree-sitter-d/d7b3cc1f9f1f59518457696a8547e0e1bb1a64b4/test/corpus/typeof.scm | scheme | ==================
Typeof expression
==================
---
(source_file
(auto_declaration
(storage_class (auto))
(identifier)
(typeof_expression (typeof) (expression (int_literal)))
)
)
==================
Typeof expression (return)
==================
---
(source_file
(auto_declaration
(storage_class (auto))
(identifier)
(typeof_expression (typeof) (return))
)
)
|
|
d32098efe8cba2b05f15c3f8c6c3c1c4a635ba6b21e2254db0f79b2eda502dbe | jarohen/graph-zip | merge_graph.clj | (ns graph-zip.merge-graph
(:use [graph-zip.core]
[graph-zip.in-memory :only [my-map build-in-memory-graph]]))
(defrecord MergeGraph [graphs]
Graph
(props-map [this node direction]
(let [maps (map #(props-map % node direction) graphs)
non-empty-maps (filter #(not (empty? %)) maps)]
(apply merge-with (comp flatten conj) non-empty-maps)))
(prop-values [this node prop direction]
(flatten (filter #(not (empty? %)) (map #(prop-values % node prop direction) graphs)))))
(defn make-merge-graph [& graphs]
(MergeGraph. graphs))
;; TESTS -----------------------
(def additional-map (build-in-memory-graph [{:subject "prod-host" :property :instance :object "prod-host/instance3"}
{:subject "prod-host" :property "cmdb:hostname" :object "prod-server.example.com"}
{:subject "prod-host/instance3" :property "label" :object "3"}]))
(def merged-zipper (graph-zip (MergeGraph. [my-map additional-map]) "prod-host"))
(zip1-> merged-zipper
:instance
(prop= "label" "3")
node) ;; -> "prod-host/instance3"
(zip1-> merged-zipper
:instance
(prop= "label" "1")
node) ;; -> "prod-host/instance"
(zip-> merged-zipper
:instance
- > ( " prod - host / instance3 " " prod - host / instance2 " " prod - host / instance " )
| null | https://raw.githubusercontent.com/jarohen/graph-zip/fdcd533cee64140758624f15b36de9e0a6e1c789/src/graph_zip/merge_graph.clj | clojure | TESTS -----------------------
-> "prod-host/instance3"
-> "prod-host/instance" | (ns graph-zip.merge-graph
(:use [graph-zip.core]
[graph-zip.in-memory :only [my-map build-in-memory-graph]]))
(defrecord MergeGraph [graphs]
Graph
(props-map [this node direction]
(let [maps (map #(props-map % node direction) graphs)
non-empty-maps (filter #(not (empty? %)) maps)]
(apply merge-with (comp flatten conj) non-empty-maps)))
(prop-values [this node prop direction]
(flatten (filter #(not (empty? %)) (map #(prop-values % node prop direction) graphs)))))
(defn make-merge-graph [& graphs]
(MergeGraph. graphs))
(def additional-map (build-in-memory-graph [{:subject "prod-host" :property :instance :object "prod-host/instance3"}
{:subject "prod-host" :property "cmdb:hostname" :object "prod-server.example.com"}
{:subject "prod-host/instance3" :property "label" :object "3"}]))
(def merged-zipper (graph-zip (MergeGraph. [my-map additional-map]) "prod-host"))
(zip1-> merged-zipper
:instance
(prop= "label" "3")
(zip1-> merged-zipper
:instance
(prop= "label" "1")
(zip-> merged-zipper
:instance
- > ( " prod - host / instance3 " " prod - host / instance2 " " prod - host / instance " )
|
f12b0c17fbf69fa6959101f21e3eb1447b39cfb4cd88f3549ca210d1ef120526 | NorfairKing/validity | Map.hs | # OPTIONS_GHC -fno - warn - orphans #
module Data.Validity.Map
( decorateMap,
)
where
import Data.Map (Map)
import qualified Data.Map as M
import Data.Validity
-- | A 'Map' of things is valid if all the keys and values are valid and the 'Map' itself
-- is valid.
instance (Show k, Ord k, Validity k, Validity v) => Validity (Map k v) where
validate m =
mconcat
[ declare "The Map structure is valid." $ M.valid m,
decorate "Map elements" $
decorateMap m $ \k v -> mconcat [delve "The key" k, delve "The value" v]
]
decorateMap :: Show k => Map k v -> (k -> v -> Validation) -> Validation
decorateMap m func = M.foldMapWithKey go m
where
go k v = decorate ("The key/value at key " ++ show k) $ func k v
| null | https://raw.githubusercontent.com/NorfairKing/validity/1c3671a662673e21a1c5e8056eef5a7b0e8720ea/validity-containers/src/Data/Validity/Map.hs | haskell | | A 'Map' of things is valid if all the keys and values are valid and the 'Map' itself
is valid. | # OPTIONS_GHC -fno - warn - orphans #
module Data.Validity.Map
( decorateMap,
)
where
import Data.Map (Map)
import qualified Data.Map as M
import Data.Validity
instance (Show k, Ord k, Validity k, Validity v) => Validity (Map k v) where
validate m =
mconcat
[ declare "The Map structure is valid." $ M.valid m,
decorate "Map elements" $
decorateMap m $ \k v -> mconcat [delve "The key" k, delve "The value" v]
]
decorateMap :: Show k => Map k v -> (k -> v -> Validation) -> Validation
decorateMap m func = M.foldMapWithKey go m
where
go k v = decorate ("The key/value at key " ++ show k) $ func k v
|
306c6d59dcf52824a35553149dde732e0a4896c2f7bb829610f4e981b7fd6866 | 2600hz-archive/whistle | rabbit_msg_store_index.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2007 - 2011 VMware , Inc. All rights reserved .
%%
-module(rabbit_msg_store_index).
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
[{new, 1},
{recover, 1},
{lookup, 2},
{insert, 2},
{update, 2},
{update_fields, 3},
{delete, 2},
{delete_by_file, 2},
{terminate, 1}];
behaviour_info(_Other) ->
undefined.
| null | https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/lib/rabbitmq_server-2.4.1/src/rabbit_msg_store_index.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.
| The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2007 - 2011 VMware , Inc. All rights reserved .
-module(rabbit_msg_store_index).
-export([behaviour_info/1]).
behaviour_info(callbacks) ->
[{new, 1},
{recover, 1},
{lookup, 2},
{insert, 2},
{update, 2},
{update_fields, 3},
{delete, 2},
{delete_by_file, 2},
{terminate, 1}];
behaviour_info(_Other) ->
undefined.
|
911b1170573ad9a5a6d94890d9936b2982b64f2c25736d17339e88051ffc82c1 | uw-unsat/serval-sosp19 | basic.rkt | #lang rosette
(require (except-in rackunit fail)
rackunit/text-ui
rosette/lib/roseunit
serval/lib/unittest
(prefix-in core: serval/lib/core)
(prefix-in riscv: serval/riscv/objdump)
(prefix-in keystone: "symbols.rkt")
(prefix-in keystone: "generated/monitors/keystone.asm.rkt"))
(define (check-keystone)
; Start a CPU in fresh, just-after-reset state
(define cpu0 (riscv:init-cpu keystone:symbols keystone:globals))
hartid = 1
(riscv:gpr-set! cpu0 'a0 (bv 1 (riscv:XLEN)))
Interpret the monitor until the first
(riscv:interpret-objdump-program cpu0 keystone:instructions)
Set new PC to be
(riscv:set-cpu-pc! cpu0 (riscv:csr-ref cpu0 'mtvec))
; Trash every GPR
(for ([i (range 32)])
(riscv:gpr-havoc! cpu0 i))
EXC_ECALL_S
(riscv:gpr-set! cpu0 'a7 (bv 13 (riscv:XLEN))) ; Resume enclave
; Run again (from machine_trap_vector this time)
(define as (with-asserts-only (riscv:interpret-objdump-program cpu0 keystone:instructions)))
(check-equal? (asserts) null)
(displayln "Checking asserts")
(check-unsat? (verify (assert (apply && as))))
(define return-code (riscv:gpr-ref cpu0 'a0))
(check-unsat? (verify (assert (|| (bveq return-code (bv 0 64))
(bveq return-code (bvneg (bv 22 64)))))))
(void))
(define (check-keystone-symbols)
(check-equal? (core:find-overlapping-symbol keystone:symbols) #f "Symbol overlap check failed"))
(define keystone-tests
(test-suite+ "Encmon verification tests"
;(test-case+ "Check keystone" (check-keystone))
(test-case+ "Encmon symbol check" (check-keystone-symbols))
))
(module+ test
(time (run-tests keystone-tests)))
| null | https://raw.githubusercontent.com/uw-unsat/serval-sosp19/175c42660fad84b44e4c9f6f723fd3c9450d65d4/monitors/keystone/verif/basic.rkt | racket | Start a CPU in fresh, just-after-reset state
Trash every GPR
Resume enclave
Run again (from machine_trap_vector this time)
(test-case+ "Check keystone" (check-keystone)) | #lang rosette
(require (except-in rackunit fail)
rackunit/text-ui
rosette/lib/roseunit
serval/lib/unittest
(prefix-in core: serval/lib/core)
(prefix-in riscv: serval/riscv/objdump)
(prefix-in keystone: "symbols.rkt")
(prefix-in keystone: "generated/monitors/keystone.asm.rkt"))
(define (check-keystone)
(define cpu0 (riscv:init-cpu keystone:symbols keystone:globals))
hartid = 1
(riscv:gpr-set! cpu0 'a0 (bv 1 (riscv:XLEN)))
Interpret the monitor until the first
(riscv:interpret-objdump-program cpu0 keystone:instructions)
Set new PC to be
(riscv:set-cpu-pc! cpu0 (riscv:csr-ref cpu0 'mtvec))
(for ([i (range 32)])
(riscv:gpr-havoc! cpu0 i))
EXC_ECALL_S
(define as (with-asserts-only (riscv:interpret-objdump-program cpu0 keystone:instructions)))
(check-equal? (asserts) null)
(displayln "Checking asserts")
(check-unsat? (verify (assert (apply && as))))
(define return-code (riscv:gpr-ref cpu0 'a0))
(check-unsat? (verify (assert (|| (bveq return-code (bv 0 64))
(bveq return-code (bvneg (bv 22 64)))))))
(void))
(define (check-keystone-symbols)
(check-equal? (core:find-overlapping-symbol keystone:symbols) #f "Symbol overlap check failed"))
(define keystone-tests
(test-suite+ "Encmon verification tests"
(test-case+ "Encmon symbol check" (check-keystone-symbols))
))
(module+ test
(time (run-tests keystone-tests)))
|
09e96c1f4ddf6dc0fa434e49e6699d8b2ea9db506c6730e50050cafaf5a7eeb2 | solita/mnt-teet | user_tx.clj | (ns teet.user.user-tx
(:require [datomic.client.api :as d]
[teet.meta.meta-model :as meta-model]
[datomic.ion :as ion])
(:import (java.util Date)))
(defn ensure-unique-email [db email tx-data]
(if-not email
tx-data
(let [{db-after :db-after} (d/with db {:tx-data tx-data})
users (d/q '[:find ?u
:where
[?u :user/id _]
[?u :user/email ?email]
:in $ ?email] db-after email)]
(if (> (count users) 1)
(ion/cancel {:cognitect.anomalies/category :cognitect.anomalies/conflict
:cognitect.anomalies/message "Duplicate email"
:teet/error :email-address-already-in-use})
tx-data))))
(defn set-global-role
[db modifying-user user-eid role]
(let [now (Date.)
user-id (:db/id (d/pull db [:db/id] user-eid))
permissions (mapv
first
(d/q '[:find (pull ?p [:permission/role :db/id])
:in $ ?u
:where
[?u :user/permissions ?p]
[(missing? $ ?p :permission/projects)]
[(missing? $ ?p :permission/valid-until)]]
db
user-id))
existing-role (some
#(when (= (:permission/role %) role)
%)
permissions)]
(->> (for [p permissions
:when (not= p existing-role)]
(merge {:db/id (:db/id p)
:permission/valid-until now}
NIL in migration
(meta-model/modification-meta modifying-user))))
(concat
(when (and (not existing-role) (some? role))
[{:db/id user-id
:user/permissions
[(merge
TO support multiple user permissions per tx
:permission/role role
:permission/valid-from now}
NIL in migration
(meta-model/creation-meta modifying-user)))]}]))
(remove nil?)
vec)))
| null | https://raw.githubusercontent.com/solita/mnt-teet/7a5124975ce1c7f3e7a7c55fe23257ca3f7b6411/app/backend/src/clj/teet/user/user_tx.clj | clojure | (ns teet.user.user-tx
(:require [datomic.client.api :as d]
[teet.meta.meta-model :as meta-model]
[datomic.ion :as ion])
(:import (java.util Date)))
(defn ensure-unique-email [db email tx-data]
(if-not email
tx-data
(let [{db-after :db-after} (d/with db {:tx-data tx-data})
users (d/q '[:find ?u
:where
[?u :user/id _]
[?u :user/email ?email]
:in $ ?email] db-after email)]
(if (> (count users) 1)
(ion/cancel {:cognitect.anomalies/category :cognitect.anomalies/conflict
:cognitect.anomalies/message "Duplicate email"
:teet/error :email-address-already-in-use})
tx-data))))
(defn set-global-role
[db modifying-user user-eid role]
(let [now (Date.)
user-id (:db/id (d/pull db [:db/id] user-eid))
permissions (mapv
first
(d/q '[:find (pull ?p [:permission/role :db/id])
:in $ ?u
:where
[?u :user/permissions ?p]
[(missing? $ ?p :permission/projects)]
[(missing? $ ?p :permission/valid-until)]]
db
user-id))
existing-role (some
#(when (= (:permission/role %) role)
%)
permissions)]
(->> (for [p permissions
:when (not= p existing-role)]
(merge {:db/id (:db/id p)
:permission/valid-until now}
NIL in migration
(meta-model/modification-meta modifying-user))))
(concat
(when (and (not existing-role) (some? role))
[{:db/id user-id
:user/permissions
[(merge
TO support multiple user permissions per tx
:permission/role role
:permission/valid-from now}
NIL in migration
(meta-model/creation-meta modifying-user)))]}]))
(remove nil?)
vec)))
|
|
290d6951ff6097f62f9a8ec7ea6c91fdb261875fb9f63350a3183e8278c23e23 | cnuernber/tmdjs | cljs_ajax.cljs | (ns tech.v3.libs.cljs-ajax
"Bindings to use the dataset handlers in cljs GET/POST calls."
(:require [ajax.core :as ajax]
[ajax.interceptors :as ajax-interceptors]
[ajax.transit :as ajax-transit]
[tech.v3.dataset :as ds]
[tech.v3.datatype.datetime :as dtype-dt]
[java.time :refer [LocalDate Instant]]
[cognitect.transit :as t]))
(defonce write-handlers* (atom (ds/transit-write-handler-map)))
(defonce read-handlers* (atom (ds/transit-read-handler-map)))
(defn add-transit-io-handlers!
[datatype tag read-fn write-fn]
(swap! write-handlers* assoc datatype (t/write-handler (constantly tag) write-fn))
(swap! read-handlers* assoc tag read-fn))
(defn add-java-time-handlers!
"Add handlers for java.time.LocalDate and java.time.Instant"
[]
(add-transit-io-handlers! LocalDate "java.time.LocalDate"
dtype-dt/epoch-days->local-date
dtype-dt/local-date->epoch-days)
(add-transit-io-handlers! Instant "java.time.Instant"
dtype-dt/epoch-milliseconds->instant
dtype-dt/instant->epoch-milliseconds))
(defn writer
"Transit writer used for writing transit-json datasets and uses
`ds/transit-write-handler-map`"
[]
(t/writer :json {:handlers @write-handlers*}))
(defn response-format
"cljs-ajax interceptor that hardwires content-type to application/transit+json
and uses `ds/transit-read-handler-map`."
[& [content-type]]
(ajax-interceptors/map->ResponseFormat
{:content-type (or content-type ["application/transit+json"])
:description "Transit response"
:read (ajax-transit/transit-read-fn {:handlers @read-handlers*})}))
(defn opt-map
"Options map that must be included in the cljs-ajax request in order
to activate dataset->transit pathways."
[]
{:writer (writer) :response-format (response-format)})
(defn transit-request
"Perform a cljs-ajax request using the select cljs-ajax.core method and merging
[[opt-map]] first into the options."
[method url options]
(method url (merge (opt-map) options)))
(defn GET
"Drop in replacement for cljs-ajax.core/GET"
[url options] (transit-request ajax/GET url options))
(defn POST
"Drop in replacement for cljs-ajax.core/POST"
[url options] (transit-request ajax/POST url options))
| null | https://raw.githubusercontent.com/cnuernber/tmdjs/c0086716801cc0fa3161813a4598772241909410/src/tech/v3/libs/cljs_ajax.cljs | clojure | (ns tech.v3.libs.cljs-ajax
"Bindings to use the dataset handlers in cljs GET/POST calls."
(:require [ajax.core :as ajax]
[ajax.interceptors :as ajax-interceptors]
[ajax.transit :as ajax-transit]
[tech.v3.dataset :as ds]
[tech.v3.datatype.datetime :as dtype-dt]
[java.time :refer [LocalDate Instant]]
[cognitect.transit :as t]))
(defonce write-handlers* (atom (ds/transit-write-handler-map)))
(defonce read-handlers* (atom (ds/transit-read-handler-map)))
(defn add-transit-io-handlers!
[datatype tag read-fn write-fn]
(swap! write-handlers* assoc datatype (t/write-handler (constantly tag) write-fn))
(swap! read-handlers* assoc tag read-fn))
(defn add-java-time-handlers!
"Add handlers for java.time.LocalDate and java.time.Instant"
[]
(add-transit-io-handlers! LocalDate "java.time.LocalDate"
dtype-dt/epoch-days->local-date
dtype-dt/local-date->epoch-days)
(add-transit-io-handlers! Instant "java.time.Instant"
dtype-dt/epoch-milliseconds->instant
dtype-dt/instant->epoch-milliseconds))
(defn writer
"Transit writer used for writing transit-json datasets and uses
`ds/transit-write-handler-map`"
[]
(t/writer :json {:handlers @write-handlers*}))
(defn response-format
"cljs-ajax interceptor that hardwires content-type to application/transit+json
and uses `ds/transit-read-handler-map`."
[& [content-type]]
(ajax-interceptors/map->ResponseFormat
{:content-type (or content-type ["application/transit+json"])
:description "Transit response"
:read (ajax-transit/transit-read-fn {:handlers @read-handlers*})}))
(defn opt-map
"Options map that must be included in the cljs-ajax request in order
to activate dataset->transit pathways."
[]
{:writer (writer) :response-format (response-format)})
(defn transit-request
"Perform a cljs-ajax request using the select cljs-ajax.core method and merging
[[opt-map]] first into the options."
[method url options]
(method url (merge (opt-map) options)))
(defn GET
"Drop in replacement for cljs-ajax.core/GET"
[url options] (transit-request ajax/GET url options))
(defn POST
"Drop in replacement for cljs-ajax.core/POST"
[url options] (transit-request ajax/POST url options))
|
|
e5a3679bffcadb57cee213e81aee2ceaae9ca64d98326630ff61facaf507b1da | dyzsr/ocaml-selectml | disable_warnings_classes.ml | (* TEST
flags = " -w +A "
* expect
*)
class c = object
val a =
let b = 5 in ()
[@@warning "-26"]
val x =
let y = 5 in ()
end;;
[%%expect {|
Line 8, characters 8-9:
8 | let y = 5 in ()
^
Warning 26 [unused-var]: unused variable y.
class c : object val a : unit val x : unit end
|}];;
class c = object
method a =
let b = 5 in ()
[@@warning "-26"]
method x =
let y = 5 in ()
end;;
[%%expect {|
Line 8, characters 8-9:
8 | let y = 5 in ()
^
Warning 26 [unused-var]: unused variable y.
class c : object method a : unit method x : unit end
|}];;
class c = object
initializer
let b = 5 in ()
[@@warning "-26"]
initializer
let y = 5 in ()
end;;
[%%expect {|
Line 8, characters 8-9:
8 | let y = 5 in ()
^
Warning 26 [unused-var]: unused variable y.
class c : object end
|}];;
class c = (object
val a =
let b = 5 in ()
end [@warning "-26"])
[%%expect {|
class c : object val a : unit end
|}];;
class c = object
val a =
let b = 5 in ()
[@@@warning "-26"]
val x =
let y = 5 in ()
end;;
[%%expect {|
Line 4, characters 8-9:
4 | let b = 5 in ()
^
Warning 26 [unused-var]: unused variable b.
class c : object val a : unit val x : unit end
|}];;
type dep
[@@deprecated "deprecated"]
class type c = object
val a : dep
[@@warning "-3"]
val x : dep
end;;
[%%expect {|
type dep
Line 9, characters 10-13:
9 | val x : dep
^^^
Alert deprecated: dep
deprecated
class type c = object val a : dep val x : dep end
|}];;
class type c = object
method a : dep
[@@warning "-3"]
method x : dep
end;;
[%%expect {|
Line 6, characters 13-16:
6 | method x : dep
^^^
Alert deprecated: dep
deprecated
class type c = object method a : dep method x : dep end
|}];;
class type c = object [@warning "-3"]
val a : dep
end
[%%expect {|
class type c = object val a : dep end
|}];;
class type c = object
val a : dep
[@@@warning "-3"]
val x : dep
end;;
[%%expect {|
Line 3, characters 10-13:
3 | val a : dep
^^^
Alert deprecated: dep
deprecated
class type c = object val a : dep val x : dep end
|}];;
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-warnings/disable_warnings_classes.ml | ocaml | TEST
flags = " -w +A "
* expect
|
class c = object
val a =
let b = 5 in ()
[@@warning "-26"]
val x =
let y = 5 in ()
end;;
[%%expect {|
Line 8, characters 8-9:
8 | let y = 5 in ()
^
Warning 26 [unused-var]: unused variable y.
class c : object val a : unit val x : unit end
|}];;
class c = object
method a =
let b = 5 in ()
[@@warning "-26"]
method x =
let y = 5 in ()
end;;
[%%expect {|
Line 8, characters 8-9:
8 | let y = 5 in ()
^
Warning 26 [unused-var]: unused variable y.
class c : object method a : unit method x : unit end
|}];;
class c = object
initializer
let b = 5 in ()
[@@warning "-26"]
initializer
let y = 5 in ()
end;;
[%%expect {|
Line 8, characters 8-9:
8 | let y = 5 in ()
^
Warning 26 [unused-var]: unused variable y.
class c : object end
|}];;
class c = (object
val a =
let b = 5 in ()
end [@warning "-26"])
[%%expect {|
class c : object val a : unit end
|}];;
class c = object
val a =
let b = 5 in ()
[@@@warning "-26"]
val x =
let y = 5 in ()
end;;
[%%expect {|
Line 4, characters 8-9:
4 | let b = 5 in ()
^
Warning 26 [unused-var]: unused variable b.
class c : object val a : unit val x : unit end
|}];;
type dep
[@@deprecated "deprecated"]
class type c = object
val a : dep
[@@warning "-3"]
val x : dep
end;;
[%%expect {|
type dep
Line 9, characters 10-13:
9 | val x : dep
^^^
Alert deprecated: dep
deprecated
class type c = object val a : dep val x : dep end
|}];;
class type c = object
method a : dep
[@@warning "-3"]
method x : dep
end;;
[%%expect {|
Line 6, characters 13-16:
6 | method x : dep
^^^
Alert deprecated: dep
deprecated
class type c = object method a : dep method x : dep end
|}];;
class type c = object [@warning "-3"]
val a : dep
end
[%%expect {|
class type c = object val a : dep end
|}];;
class type c = object
val a : dep
[@@@warning "-3"]
val x : dep
end;;
[%%expect {|
Line 3, characters 10-13:
3 | val a : dep
^^^
Alert deprecated: dep
deprecated
class type c = object val a : dep val x : dep end
|}];;
|
1631d2a6c02e8fd1528e47a6e00b0ca8128a670694c2927017783bfc7970eb15 | jimpil/fudje | sweet.clj | (ns fudje.sweet
(:require [fudje.checkers :as checkers]
[fudje.core :refer [mocking]]))
(defonce anything
(fudje.checkers/->AnythingChecker))
(defonce irrelevant anything) ;; just a synonym
(defonce truthy
(checkers/->TruthyChecker))
(defonce falsey
(checkers/->FalseyChecker))
(defmacro contains
"A macro to help us simulate the `contains` checker."
[x & modifiers]
`(fudje.checkers/->ContainsChecker ~x ~(zipmap modifiers (repeat true))))
(defmacro just
"A macro to help us simulate the `just` argument-checker."
[x & modifiers]
`(fudje.checkers/->JustChecker ~x ~(zipmap modifiers (repeat true))))
(defmacro checker
"A macro to help us simulate the `checker` checker."
[& x]
catch this syntactic quirk of
`(fudje.checkers/->CustomChecker (fn ~@x))
`(fudje.checkers/->CustomChecker ~(first x))))
(defmacro n-of
"A macro to help us simulate the `n-of` checker."
[x y]
`(fudje.checkers/->NofChecker ~x ~y))
(defmacro one-of
"A macro to help us simulate the `one-of` checker."
[x]
`(n-of ~x 1))
(defmacro two-of
"A macro to help us simulate the `two-of` checker."
[x]
`(n-of ~x 2))
(defmacro three-of
"A macro to help us simulate the `three-of` checker."
[x]
`(n-of ~x 3))
(defmacro four-of
"A macro to help us simulate the `four-of` checker."
[x]
`(n-of ~x 4))
(defmacro five-of
"A macro to help us simulate the `five-of` checker."
[x]
`(n-of ~x 5))
(defmacro six-of
"A macro to help us simulate the `six-of` checker."
[x]
`(n-of ~x 6))
(defmacro seven-of
"A macro to help us simulate the `seven-of` checker."
[x]
`(n-of ~x 7))
(defmacro eight-of
"A macro to help us simulate the `eight-of` checker."
[x]
`(n-of ~x 8))
(defmacro nine-of
"A macro to help us simulate the `nine-of` checker."
[x]
`(n-of ~x 9))
(defmacro ten-of
"A macro to help us simulate the `ten-of` checker."
[x]
`(n-of ~x 10))
(defmacro has
"A macro to help us simulate the `has` checker."
[x y]
`(fudje.checkers/->HasChecker ~x ~y))
(defmacro roughly
"A macro to help us simulate the `roughly` checker."
[x & y]
`(let [x# ~x]
(assert (number? x#) "First argument to `roughly` MUST be a number!")
(fudje.checkers/->RoughlyChecker x# ~(first y))))
(defmacro every-checker
"A macro to help us simulate the `every-checker` checker."
[& checkers]
`(let [cs# ~(vec checkers)]
(assert (every? fudje.util/poly-checker? cs#) "`every-checker` expects checkers!")
(fudje.checkers/->EveryChecker cs#)))
(defmacro split-in-provided-without-metaconstants
"Given a some typical Midje code where some `provided` clauses (mocks) follow the actual test assertions,
separate the assertions from the mocks. Also replaces all meta-constants with keywords.
Returns a vector of [<forms-before-provided (assertions)> <forms-after-provided (mocks)>]."
[forms]
`(->> ~forms
(split-with #(if (list? %)
(not= :provided (keyword (symbol (first %))))
true))
(map (partial clojure.walk/postwalk (fn [form#]
(let [[mc?# to-replace#] (fudje.util/metaconstant? form#)]
(if mc?#
(fudje.util/metaconstant->kw form# to-replace#)
we do not support replacing , check for the Exception object here
(throw to-replace#)
form#))))))))
(defn- expand-tests
"Map midje symbols `=>` & `=throws=>` to `is` & `(is (thrown? ...` respectively."
[tests]
(for [[t symb res] tests]
(condp = symb
'=> `(let [expected# ~res] ;; this is the common case
(if (fudje.util/poly-checker? expected#)
(clojure.test/is (~'compatible expected# ~t))
(clojure.test/is (= ~res ~t))))
'=throws=> (let [[xxx msg] res ;; <xxx> will either be a Class or an Exception object
xxx-klass (cond-> xxx
(fudje.util/throwable? xxx) class)]
(if (nil? msg)
`(clojure.test/is (~'thrown? ~xxx-klass ~t))
`(clojure.test/is (~'thrown-with-msg? ~xxx-klass ~(cond-> msg
(string? msg) re-pattern) ~t))))
(throw (IllegalArgumentException. ^String (format "arrow %s not recognised!" (str symb)))))))
(defmacro fact
"An (almost) drop-in replacement for `midje.sweet/fact` which rewrites the code to not use Midje..
ATTENTION: `let` bindings right after a `midje.sweet.fact` should be manually pulled one level up, before switching to `fudje.sweet/fact`."
[& forms]
;; MAKE SURE THERE IS NO EXPRESSION SHADOWING THE MOCKS:
;; we want to avoid a situation where the `provided` clauses are not visible when splitting the entire `fact` into assertions & mocks.
For example the following is bad because there are 2 nesting levels separating the ` fact ` & ` provided ` symbols , whereas there should only be 1 .
;;(fact ""
( let [ a 1 ]
( x a ) = > 5
;; (provided
( y 2 ) = > 6 ) ) )
;;
;; Instead of bypassing this silently (which renders the test useless), we want to make this a compile-time error.
;; However, we need to take extra care to allow for similar looking expressions that don't violate the rule.
;; For example the following should be allowed:
;;
;; (fact ""
( let [ a 1 ]
( x a ) ) = > 5 ; notice how the ` let ` closes here instead of at the end
;; (provided
( y 2 ) = > 6 ) )
;; first thing we need to know is whether the original expression we're rewriting comtains any mocks
(let [fform (first forms)
[description forms] (if (string? fform)
[fform (rest forms)]
["" forms])
mocks-present? (some true? (map #(with-local-vars [mocks? false]
(clojure.walk/prewalk (fn mock-flag? [x]
(do (when (= 'provided x)
(var-set mocks? true))
x))
%)
(var-get mocks?))
forms))
[pre-provided post-provided] (fudje.sweet/split-in-provided-without-metaconstants forms)
;; following assertion covers the case where the mock expressions have been shadowed by some expression (e.g `let`),
and as such the whole expression can not be reliably split into assertions VS mocks . There is just no way to get well - formed assertions ,
;; if there is a `let` right under the `fact` and is consuming the whole body of the `fact`. The only way to get well-formed assertions while mixing e.g. `let` expressions,
;; is to limit the `let`'s scope to either the left, or the right side of the assertion, in which case it is perfectly legal to do so and should be allowed.
_ (assert (zero? (rem (count pre-provided) 3))
"Well-formed assertions should have 3 identifiable parts (e.g. `x => y`)...\nIt is likely that some expression (e.g `let`) is shadowing your assertion(s), and potentially the mocks as well! If so, manually lift that expression outside the `fact`, and try again.")
mocks (-> post-provided first rest)
;; following assertion will fire if the mocks are empty, or if they are not well-formed (as triplets similar to the assertions).
;; In absence of spelling errors, and since the assertion before it covers the 'shadowing' issue, the mocks should never be empty at this point
;; (given that the original expression did contain a 'provided symbol). So here, we're mainly checking that the mocks are indeed triplets.
_ (when mocks-present?
(assert (and (not-empty post-provided)
(zero? (rem (count mocks) 3))) "Well-formed mocks should have 3 identifiable parts (e.g. `x => y`)... "))
tests (->> pre-provided
(partition 3)
(map (fn [[t _ r :as x]]
(if (and (list? r)
(= 'throws (symbol (first r))))
[t '=throws=> (rest r)] ;; this requires special treatment (see `expand-tests`)
x)))
)
mocks (-> post-provided first rest)]
`(clojure.test/testing ~description
(fudje.core/mocking ~mocks
~@(fudje.sweet/expand-tests tests)))
))
(defmacro are* ;;
"Slightly patched version of `clojure.test/are` that assumes that <expr> is a `fact` or `mocking`.
Only difference is that <expr> is NOT evaluated within the context of a `clojure.test/is` as the `fact` takes care of that.
Not really intended for public use but it has to stay a public Var."
{:added "1.1"}
[argv expr & args]
(if (or
(and (empty? argv) (empty? args))
(and (pos? (count argv))
(pos? (count args))
(zero? (mod (count args) (count argv)))))
`(clojure.template/do-template ~argv ~expr ~@args)
(throw (IllegalArgumentException. "The number of args doesn't match are's argv."))))
(defmacro tabular [fact-expr & body]
(with-local-vars [arga #{}]
(clojure.walk/prewalk (fn [x]
(if (fudje.util/qmark? x)
(do (var-set arga (conj @arga x)) x)
x))
fact-expr)
(let [[args assertions] (split-at (count @arga) body)]
`(fudje.sweet/are* ~(vec args) ~fact-expr ~@assertions))
)
)
credit for the following goes to ( )
(defmacro facts
"An (almost) drop-in replacement for `midje.sweet/facts`"
[& body]
`(fact ~@body))
(defmacro contains-in [x]
"A macro for nested checking of data in the `contains` form"
(cond (map? x)
`(fudje.sweet/contains ~(reduce-kv (fn [out k v]
(assoc out k `(fudje.sweet/contains-in ~v)))
{}
x))
(vector? x)
`(fudje.sweet/contains ~(reduce (fn [out v]
(conj out `(fudje.sweet/contains-in ~v)))
[]
x))
:else x))
(defmacro just-in [x]
"A macro for nested checking of data in the `just` form"
(cond (map? x)
`(just ~(reduce-kv (fn [out k v]
(assoc out k `(just-in ~v)))
{}
x))
(vector? x)
`(just ~(reduce (fn [out v]
(conj out `(just-in ~v)))
[]
x))
:else x))
| null | https://raw.githubusercontent.com/jimpil/fudje/dfe042303887b2d33bd0b30f5ec6cbec1a18dbc2/src/clojure/fudje/sweet.clj | clojure | just a synonym
this is the common case
<xxx> will either be a Class or an Exception object
MAKE SURE THERE IS NO EXPRESSION SHADOWING THE MOCKS:
we want to avoid a situation where the `provided` clauses are not visible when splitting the entire `fact` into assertions & mocks.
(fact ""
(provided
Instead of bypassing this silently (which renders the test useless), we want to make this a compile-time error.
However, we need to take extra care to allow for similar looking expressions that don't violate the rule.
For example the following should be allowed:
(fact ""
notice how the ` let ` closes here instead of at the end
(provided
first thing we need to know is whether the original expression we're rewriting comtains any mocks
following assertion covers the case where the mock expressions have been shadowed by some expression (e.g `let`),
if there is a `let` right under the `fact` and is consuming the whole body of the `fact`. The only way to get well-formed assertions while mixing e.g. `let` expressions,
is to limit the `let`'s scope to either the left, or the right side of the assertion, in which case it is perfectly legal to do so and should be allowed.
following assertion will fire if the mocks are empty, or if they are not well-formed (as triplets similar to the assertions).
In absence of spelling errors, and since the assertion before it covers the 'shadowing' issue, the mocks should never be empty at this point
(given that the original expression did contain a 'provided symbol). So here, we're mainly checking that the mocks are indeed triplets.
this requires special treatment (see `expand-tests`)
| (ns fudje.sweet
(:require [fudje.checkers :as checkers]
[fudje.core :refer [mocking]]))
(defonce anything
(fudje.checkers/->AnythingChecker))
(defonce truthy
(checkers/->TruthyChecker))
(defonce falsey
(checkers/->FalseyChecker))
(defmacro contains
"A macro to help us simulate the `contains` checker."
[x & modifiers]
`(fudje.checkers/->ContainsChecker ~x ~(zipmap modifiers (repeat true))))
(defmacro just
"A macro to help us simulate the `just` argument-checker."
[x & modifiers]
`(fudje.checkers/->JustChecker ~x ~(zipmap modifiers (repeat true))))
(defmacro checker
"A macro to help us simulate the `checker` checker."
[& x]
catch this syntactic quirk of
`(fudje.checkers/->CustomChecker (fn ~@x))
`(fudje.checkers/->CustomChecker ~(first x))))
(defmacro n-of
"A macro to help us simulate the `n-of` checker."
[x y]
`(fudje.checkers/->NofChecker ~x ~y))
(defmacro one-of
"A macro to help us simulate the `one-of` checker."
[x]
`(n-of ~x 1))
(defmacro two-of
"A macro to help us simulate the `two-of` checker."
[x]
`(n-of ~x 2))
(defmacro three-of
"A macro to help us simulate the `three-of` checker."
[x]
`(n-of ~x 3))
(defmacro four-of
"A macro to help us simulate the `four-of` checker."
[x]
`(n-of ~x 4))
(defmacro five-of
"A macro to help us simulate the `five-of` checker."
[x]
`(n-of ~x 5))
(defmacro six-of
"A macro to help us simulate the `six-of` checker."
[x]
`(n-of ~x 6))
(defmacro seven-of
"A macro to help us simulate the `seven-of` checker."
[x]
`(n-of ~x 7))
(defmacro eight-of
"A macro to help us simulate the `eight-of` checker."
[x]
`(n-of ~x 8))
(defmacro nine-of
"A macro to help us simulate the `nine-of` checker."
[x]
`(n-of ~x 9))
(defmacro ten-of
"A macro to help us simulate the `ten-of` checker."
[x]
`(n-of ~x 10))
(defmacro has
"A macro to help us simulate the `has` checker."
[x y]
`(fudje.checkers/->HasChecker ~x ~y))
(defmacro roughly
"A macro to help us simulate the `roughly` checker."
[x & y]
`(let [x# ~x]
(assert (number? x#) "First argument to `roughly` MUST be a number!")
(fudje.checkers/->RoughlyChecker x# ~(first y))))
(defmacro every-checker
"A macro to help us simulate the `every-checker` checker."
[& checkers]
`(let [cs# ~(vec checkers)]
(assert (every? fudje.util/poly-checker? cs#) "`every-checker` expects checkers!")
(fudje.checkers/->EveryChecker cs#)))
(defmacro split-in-provided-without-metaconstants
"Given a some typical Midje code where some `provided` clauses (mocks) follow the actual test assertions,
separate the assertions from the mocks. Also replaces all meta-constants with keywords.
Returns a vector of [<forms-before-provided (assertions)> <forms-after-provided (mocks)>]."
[forms]
`(->> ~forms
(split-with #(if (list? %)
(not= :provided (keyword (symbol (first %))))
true))
(map (partial clojure.walk/postwalk (fn [form#]
(let [[mc?# to-replace#] (fudje.util/metaconstant? form#)]
(if mc?#
(fudje.util/metaconstant->kw form# to-replace#)
we do not support replacing , check for the Exception object here
(throw to-replace#)
form#))))))))
(defn- expand-tests
"Map midje symbols `=>` & `=throws=>` to `is` & `(is (thrown? ...` respectively."
[tests]
(for [[t symb res] tests]
(condp = symb
(if (fudje.util/poly-checker? expected#)
(clojure.test/is (~'compatible expected# ~t))
(clojure.test/is (= ~res ~t))))
xxx-klass (cond-> xxx
(fudje.util/throwable? xxx) class)]
(if (nil? msg)
`(clojure.test/is (~'thrown? ~xxx-klass ~t))
`(clojure.test/is (~'thrown-with-msg? ~xxx-klass ~(cond-> msg
(string? msg) re-pattern) ~t))))
(throw (IllegalArgumentException. ^String (format "arrow %s not recognised!" (str symb)))))))
(defmacro fact
"An (almost) drop-in replacement for `midje.sweet/fact` which rewrites the code to not use Midje..
ATTENTION: `let` bindings right after a `midje.sweet.fact` should be manually pulled one level up, before switching to `fudje.sweet/fact`."
[& forms]
For example the following is bad because there are 2 nesting levels separating the ` fact ` & ` provided ` symbols , whereas there should only be 1 .
( let [ a 1 ]
( x a ) = > 5
( y 2 ) = > 6 ) ) )
( let [ a 1 ]
( y 2 ) = > 6 ) )
(let [fform (first forms)
[description forms] (if (string? fform)
[fform (rest forms)]
["" forms])
mocks-present? (some true? (map #(with-local-vars [mocks? false]
(clojure.walk/prewalk (fn mock-flag? [x]
(do (when (= 'provided x)
(var-set mocks? true))
x))
%)
(var-get mocks?))
forms))
[pre-provided post-provided] (fudje.sweet/split-in-provided-without-metaconstants forms)
and as such the whole expression can not be reliably split into assertions VS mocks . There is just no way to get well - formed assertions ,
_ (assert (zero? (rem (count pre-provided) 3))
"Well-formed assertions should have 3 identifiable parts (e.g. `x => y`)...\nIt is likely that some expression (e.g `let`) is shadowing your assertion(s), and potentially the mocks as well! If so, manually lift that expression outside the `fact`, and try again.")
mocks (-> post-provided first rest)
_ (when mocks-present?
(assert (and (not-empty post-provided)
(zero? (rem (count mocks) 3))) "Well-formed mocks should have 3 identifiable parts (e.g. `x => y`)... "))
tests (->> pre-provided
(partition 3)
(map (fn [[t _ r :as x]]
(if (and (list? r)
(= 'throws (symbol (first r))))
x)))
)
mocks (-> post-provided first rest)]
`(clojure.test/testing ~description
(fudje.core/mocking ~mocks
~@(fudje.sweet/expand-tests tests)))
))
"Slightly patched version of `clojure.test/are` that assumes that <expr> is a `fact` or `mocking`.
Only difference is that <expr> is NOT evaluated within the context of a `clojure.test/is` as the `fact` takes care of that.
Not really intended for public use but it has to stay a public Var."
{:added "1.1"}
[argv expr & args]
(if (or
(and (empty? argv) (empty? args))
(and (pos? (count argv))
(pos? (count args))
(zero? (mod (count args) (count argv)))))
`(clojure.template/do-template ~argv ~expr ~@args)
(throw (IllegalArgumentException. "The number of args doesn't match are's argv."))))
(defmacro tabular [fact-expr & body]
(with-local-vars [arga #{}]
(clojure.walk/prewalk (fn [x]
(if (fudje.util/qmark? x)
(do (var-set arga (conj @arga x)) x)
x))
fact-expr)
(let [[args assertions] (split-at (count @arga) body)]
`(fudje.sweet/are* ~(vec args) ~fact-expr ~@assertions))
)
)
credit for the following goes to ( )
(defmacro facts
"An (almost) drop-in replacement for `midje.sweet/facts`"
[& body]
`(fact ~@body))
(defmacro contains-in [x]
"A macro for nested checking of data in the `contains` form"
(cond (map? x)
`(fudje.sweet/contains ~(reduce-kv (fn [out k v]
(assoc out k `(fudje.sweet/contains-in ~v)))
{}
x))
(vector? x)
`(fudje.sweet/contains ~(reduce (fn [out v]
(conj out `(fudje.sweet/contains-in ~v)))
[]
x))
:else x))
(defmacro just-in [x]
"A macro for nested checking of data in the `just` form"
(cond (map? x)
`(just ~(reduce-kv (fn [out k v]
(assoc out k `(just-in ~v)))
{}
x))
(vector? x)
`(just ~(reduce (fn [out v]
(conj out `(just-in ~v)))
[]
x))
:else x))
|
f93ac15ce7b489261a90a21028a6e29dfcbb12f57f567ac987e26ecf3700b99d | apg/cfdg | spiral.rkt | #lang s-exp cfdg/language
(set background "DimGray")
(set width 1000)
(set height 1000)
(set size 50)
(set luminance 80)
(set rotation 0)
(set saturation 90)
(set nesting 100)
(set alpha 0)
(rule brick
(square)
(if (> .2 (random))
(brick 'r -13 'a 0.3 'x 1.7 's 0.95 'b .2)
(brick 'r -20 'a 0.2 'x 1.3 's 0.9 'b .25)))
(rule first
(brick)
(brick 'r 72 'c 51)
(brick 'r 144 'c 102)
(brick 'r 216 'c 153)
(brick 'r 288 'c 204))
(start-rule first 'b 220 'r 0 'c 0 't 200 'a 0)
| null | https://raw.githubusercontent.com/apg/cfdg/95cb006c6ea43cc09c47d68fe9c7dc4597a3ed3e/cfdg/examples/spiral.rkt | racket | #lang s-exp cfdg/language
(set background "DimGray")
(set width 1000)
(set height 1000)
(set size 50)
(set luminance 80)
(set rotation 0)
(set saturation 90)
(set nesting 100)
(set alpha 0)
(rule brick
(square)
(if (> .2 (random))
(brick 'r -13 'a 0.3 'x 1.7 's 0.95 'b .2)
(brick 'r -20 'a 0.2 'x 1.3 's 0.9 'b .25)))
(rule first
(brick)
(brick 'r 72 'c 51)
(brick 'r 144 'c 102)
(brick 'r 216 'c 153)
(brick 'r 288 'c 204))
(start-rule first 'b 220 'r 0 'c 0 't 200 'a 0)
|
|
269b9f964634b3990bed215778c7bc50ccb504b39cf40854858ab0382f2394ef | jrheard/voke | movement.cljs | (ns voke.system.movement
(:require [cljs.spec :as s]
[voke.system.collision.system :refer [attempt-to-move!]]))
; A dumb-as-rocks velocity/acceleration system.
; Based on -2d-vector-physics-acceleration-orientation-and-friction/ .
;
; If I were a better man, I would have implemented /
; or -algebra-for-game-developers-part-2/
;
; This system was easy to implement and I don't need all the bells/whistles in the linear-algebra-based
; articles, though, so I don't feel *too* bad.
May have made collision resolution a bit more fiddly / less elegant than it could have been , though .
(def friction-value 0.80)
(def min-velocity 0.05)
(defn should-update-velocity?
"Entities' velocity should be updated if they're intending to move somewhere
or if they're currently moving and affected by friction."
[entity]
(or (get-in entity [:component/motion :motion/direction])
(and
(get-in entity [:component/motion :motion/affected-by-friction])
(or
(not= (get-in entity [:component/motion :motion/velocity :geometry/x]) 0)
(not= (get-in entity [:component/motion :motion/velocity :geometry/y]) 0)))))
(s/fdef should-update-velocity?
:args (s/cat :entity :entity/entity)
:ret boolean?)
(defn get-acceleration
[entity]
(if (get-in entity [:component/motion :motion/direction])
(get-in entity [:component/motion :motion/max-acceleration])
0))
(s/fdef get-acceleration
:args (s/cat :entity :entity/entity)
:ret number?)
(defn -update-axis-velocity
[entity axis trig-fn]
(let [axis-velocity (get-in entity [:component/motion :motion/velocity axis])
new-velocity (+ axis-velocity
(* (get-acceleration entity)
(trig-fn (get-in entity [:component/motion :motion/direction]))))]
(if (> (Math/abs new-velocity) min-velocity)
(assoc-in entity [:component/motion :motion/velocity axis] new-velocity)
(assoc-in entity [:component/motion :motion/velocity axis] 0))))
(s/fdef -update-axis-velocity
:args (s/and (s/cat :entity :entity/entity
:axis :geometry/axis
:trig-fn fn?)
#(contains? (% :entity) :component/motion))
:ret :entity/entity)
(defn cap-velocity
"Ensures that entities can't travel faster than their :motion/max-speed."
[entity]
(let [velocity (get-in entity [:component/motion :motion/velocity])
x-velocity (velocity :geometry/x)
y-velocity (velocity :geometry/y)
max-speed (get-in entity [:component/motion :motion/max-speed])
amplitude (Math/sqrt (+ (* x-velocity x-velocity)
(* y-velocity y-velocity)))
multiplier (if (> amplitude max-speed)
(/ max-speed amplitude)
1)]
(assoc-in entity
[:component/motion :motion/velocity]
{:geometry/x (* x-velocity multiplier)
:geometry/y (* y-velocity multiplier)})))
(s/fdef cap-velocity
:args (s/and (s/cat :entity :entity/entity)
#(contains? (% :entity) :component/motion))
:ret :entity/entity)
(defn update-velocity
[entity]
(if (should-update-velocity? entity)
(-> entity
(-update-axis-velocity :geometry/x Math/cos)
(-update-axis-velocity :geometry/y Math/sin)
cap-velocity)
entity))
(s/fdef update-velocity
:args (s/cat :entity :entity/entity)
:ret :entity/entity)
(defn apply-friction
[entity]
(if (get-in entity [:component/motion :motion/affected-by-friction])
(reduce
(fn [entity axis]
(update-in entity [:component/motion :motion/velocity axis] #(* % friction-value)))
entity
[:geometry/x :geometry/y])
entity))
(s/fdef apply-friction
:args (s/and (s/cat :entity :entity/entity)
#(contains? (% :entity) :component/motion))
:ret :entity/entity)
(defn update-position
[entity]
(let [velocity (-> entity :component/motion :motion/velocity)
center (-> entity :component/shape :shape/center)]
(assoc-in entity
[:component/shape :shape/center]
{:geometry/x (+ (velocity :geometry/x) (center :geometry/x))
:geometry/y (+ (velocity :geometry/y) (center :geometry/y))})))
(s/fdef update-position
:args (s/and (s/cat :entity :entity/entity)
#(contains? (% :entity) :component/motion)
#(contains? (% :entity) :component/shape))
:ret :entity/entity)
(defn relevant-to-movement-system?
[entity]
(or
(get-in entity [:component/motion :motion/direction])
(not= (get-in entity [:component/motion :motion/velocity :geometry/x] 0) 0)
(not= (get-in entity [:component/motion :motion/velocity :geometry/y] 0) 0)))
(s/fdef relevant-to-movement-system?
:args (s/cat :entity :entity/entity)
:ret boolean?)
;; System definition
(def system
{:system/tick-fn (fn move-system-tick [entities]
(doseq [entity (filter relevant-to-movement-system? entities)]
(let [moved-entity (-> entity
update-velocity
apply-friction
update-position)]
(when (not= moved-entity entity)
(attempt-to-move! entity
(-> moved-entity :component/shape :shape/center)
(-> moved-entity :component/motion :motion/velocity)
entities)))))})
| null | https://raw.githubusercontent.com/jrheard/voke/15b272955d214ce0c531fb2b8d645feb217255c2/src/voke/system/movement.cljs | clojure | A dumb-as-rocks velocity/acceleration system.
Based on -2d-vector-physics-acceleration-orientation-and-friction/ .
If I were a better man, I would have implemented /
or -algebra-for-game-developers-part-2/
This system was easy to implement and I don't need all the bells/whistles in the linear-algebra-based
articles, though, so I don't feel *too* bad.
System definition | (ns voke.system.movement
(:require [cljs.spec :as s]
[voke.system.collision.system :refer [attempt-to-move!]]))
May have made collision resolution a bit more fiddly / less elegant than it could have been , though .
(def friction-value 0.80)
(def min-velocity 0.05)
(defn should-update-velocity?
"Entities' velocity should be updated if they're intending to move somewhere
or if they're currently moving and affected by friction."
[entity]
(or (get-in entity [:component/motion :motion/direction])
(and
(get-in entity [:component/motion :motion/affected-by-friction])
(or
(not= (get-in entity [:component/motion :motion/velocity :geometry/x]) 0)
(not= (get-in entity [:component/motion :motion/velocity :geometry/y]) 0)))))
(s/fdef should-update-velocity?
:args (s/cat :entity :entity/entity)
:ret boolean?)
(defn get-acceleration
[entity]
(if (get-in entity [:component/motion :motion/direction])
(get-in entity [:component/motion :motion/max-acceleration])
0))
(s/fdef get-acceleration
:args (s/cat :entity :entity/entity)
:ret number?)
(defn -update-axis-velocity
[entity axis trig-fn]
(let [axis-velocity (get-in entity [:component/motion :motion/velocity axis])
new-velocity (+ axis-velocity
(* (get-acceleration entity)
(trig-fn (get-in entity [:component/motion :motion/direction]))))]
(if (> (Math/abs new-velocity) min-velocity)
(assoc-in entity [:component/motion :motion/velocity axis] new-velocity)
(assoc-in entity [:component/motion :motion/velocity axis] 0))))
(s/fdef -update-axis-velocity
:args (s/and (s/cat :entity :entity/entity
:axis :geometry/axis
:trig-fn fn?)
#(contains? (% :entity) :component/motion))
:ret :entity/entity)
(defn cap-velocity
"Ensures that entities can't travel faster than their :motion/max-speed."
[entity]
(let [velocity (get-in entity [:component/motion :motion/velocity])
x-velocity (velocity :geometry/x)
y-velocity (velocity :geometry/y)
max-speed (get-in entity [:component/motion :motion/max-speed])
amplitude (Math/sqrt (+ (* x-velocity x-velocity)
(* y-velocity y-velocity)))
multiplier (if (> amplitude max-speed)
(/ max-speed amplitude)
1)]
(assoc-in entity
[:component/motion :motion/velocity]
{:geometry/x (* x-velocity multiplier)
:geometry/y (* y-velocity multiplier)})))
(s/fdef cap-velocity
:args (s/and (s/cat :entity :entity/entity)
#(contains? (% :entity) :component/motion))
:ret :entity/entity)
(defn update-velocity
[entity]
(if (should-update-velocity? entity)
(-> entity
(-update-axis-velocity :geometry/x Math/cos)
(-update-axis-velocity :geometry/y Math/sin)
cap-velocity)
entity))
(s/fdef update-velocity
:args (s/cat :entity :entity/entity)
:ret :entity/entity)
(defn apply-friction
[entity]
(if (get-in entity [:component/motion :motion/affected-by-friction])
(reduce
(fn [entity axis]
(update-in entity [:component/motion :motion/velocity axis] #(* % friction-value)))
entity
[:geometry/x :geometry/y])
entity))
(s/fdef apply-friction
:args (s/and (s/cat :entity :entity/entity)
#(contains? (% :entity) :component/motion))
:ret :entity/entity)
(defn update-position
[entity]
(let [velocity (-> entity :component/motion :motion/velocity)
center (-> entity :component/shape :shape/center)]
(assoc-in entity
[:component/shape :shape/center]
{:geometry/x (+ (velocity :geometry/x) (center :geometry/x))
:geometry/y (+ (velocity :geometry/y) (center :geometry/y))})))
(s/fdef update-position
:args (s/and (s/cat :entity :entity/entity)
#(contains? (% :entity) :component/motion)
#(contains? (% :entity) :component/shape))
:ret :entity/entity)
(defn relevant-to-movement-system?
[entity]
(or
(get-in entity [:component/motion :motion/direction])
(not= (get-in entity [:component/motion :motion/velocity :geometry/x] 0) 0)
(not= (get-in entity [:component/motion :motion/velocity :geometry/y] 0) 0)))
(s/fdef relevant-to-movement-system?
:args (s/cat :entity :entity/entity)
:ret boolean?)
(def system
{:system/tick-fn (fn move-system-tick [entities]
(doseq [entity (filter relevant-to-movement-system? entities)]
(let [moved-entity (-> entity
update-velocity
apply-friction
update-position)]
(when (not= moved-entity entity)
(attempt-to-move! entity
(-> moved-entity :component/shape :shape/center)
(-> moved-entity :component/motion :motion/velocity)
entities)))))})
|
a01875a61b7516f1c8e78bc6eb730f911ebede13a7b85a893838533f150dc16c | emina/rosette | fragment.rkt | #lang racket
(require "program.rkt" rosette/query/eval)
(provide fragment fragment->syntax)
Given a BV program and a solution , returns
; a sorted fragment of all instructions on which the final (output)
; instruction is data dependent according to the given solution.
; The output takes the form of a list in which the ith element is
; the instruction with output location i iff the output depends on
the value produced that instruction . Otherwise , the ith element is # f.
(define (fragment prog sol)
(let* ([lib (prog-insts prog)]
[locs (sort (for/list ([inst lib])
(list* inst
(sol (inst-out inst))
(map sol (inst-in inst))))
> #:key cadr)]
[reached (for/fold ([reached (apply set (cdar locs))]) ([ls (cdr locs)])
(if (set-member? reached (cadr ls))
(set-union reached (apply set (cddr ls)))
reached))])
(reverse (for/list ([ls locs]) (and (set-member? reached (cadr ls)) (car ls))))))
; Given a solution, a library of instructions, and list of syntactic identifiers
; to use as names for inputs to the code fragment, produces a syntactic representation
; of a lambda-expression for the given library with respect to the given solution.
; The solution must have a concrete binding for input and output locations of every
; instruction in the given library.
(define (fragment->syntax inputs prog sol)
(let* ([fragment (filter identity (fragment prog sol))]
[reg-ids (generate-temporaries (make-list (length fragment) 't))]
[loc-table (make-hash)]
[loc->id (begin (for ([(in idx) (in-indexed inputs)])
(hash-set! loc-table idx in))
(for ([reg reg-ids] [inst fragment])
(hash-set! loc-table (sol (inst-out inst)) reg))
(compose1 (curry hash-ref loc-table) sol))])
#`(lambda #,inputs
(let* #,(for/list ([inst fragment])
(let ([id (loc->id (inst-out inst))])
(if (null? (inst-in inst))
#`[#,id #,(evaluate ((inst-op inst)) sol)] ; constant
#`[#,id (#,(op-id (inst-op inst)) #,@(map loc->id (inst-in inst)))])))
#,(last reg-ids)))))
| null | https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/sdsl/bv/lang/fragment.rkt | racket | a sorted fragment of all instructions on which the final (output)
instruction is data dependent according to the given solution.
The output takes the form of a list in which the ith element is
the instruction with output location i iff the output depends on
Given a solution, a library of instructions, and list of syntactic identifiers
to use as names for inputs to the code fragment, produces a syntactic representation
of a lambda-expression for the given library with respect to the given solution.
The solution must have a concrete binding for input and output locations of every
instruction in the given library.
constant | #lang racket
(require "program.rkt" rosette/query/eval)
(provide fragment fragment->syntax)
Given a BV program and a solution , returns
the value produced that instruction . Otherwise , the ith element is # f.
(define (fragment prog sol)
(let* ([lib (prog-insts prog)]
[locs (sort (for/list ([inst lib])
(list* inst
(sol (inst-out inst))
(map sol (inst-in inst))))
> #:key cadr)]
[reached (for/fold ([reached (apply set (cdar locs))]) ([ls (cdr locs)])
(if (set-member? reached (cadr ls))
(set-union reached (apply set (cddr ls)))
reached))])
(reverse (for/list ([ls locs]) (and (set-member? reached (cadr ls)) (car ls))))))
(define (fragment->syntax inputs prog sol)
(let* ([fragment (filter identity (fragment prog sol))]
[reg-ids (generate-temporaries (make-list (length fragment) 't))]
[loc-table (make-hash)]
[loc->id (begin (for ([(in idx) (in-indexed inputs)])
(hash-set! loc-table idx in))
(for ([reg reg-ids] [inst fragment])
(hash-set! loc-table (sol (inst-out inst)) reg))
(compose1 (curry hash-ref loc-table) sol))])
#`(lambda #,inputs
(let* #,(for/list ([inst fragment])
(let ([id (loc->id (inst-out inst))])
(if (null? (inst-in inst))
#`[#,id (#,(op-id (inst-op inst)) #,@(map loc->id (inst-in inst)))])))
#,(last reg-ids)))))
|
544188bc5c9141231f3128cfef1b6aa867b6de343abb622f4dc66c9335ab6675 | clojure-interop/aws-api | core.clj | (ns com.amazonaws.services.marketplacemetering.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMetering])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringAsync])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringAsyncClient])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringAsyncClientBuilder])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringClient])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringClientBuilder])
(require '[com.amazonaws.services.marketplacemetering.AbstractAWSMarketplaceMetering])
(require '[com.amazonaws.services.marketplacemetering.AbstractAWSMarketplaceMeteringAsync])
| null | https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.marketplacemetering/src/com/amazonaws/services/marketplacemetering/core.clj | clojure | (ns com.amazonaws.services.marketplacemetering.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMetering])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringAsync])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringAsyncClient])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringAsyncClientBuilder])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringClient])
(require '[com.amazonaws.services.marketplacemetering.AWSMarketplaceMeteringClientBuilder])
(require '[com.amazonaws.services.marketplacemetering.AbstractAWSMarketplaceMetering])
(require '[com.amazonaws.services.marketplacemetering.AbstractAWSMarketplaceMeteringAsync])
|
|
309f8e2c67312273ffaead8db68e97cd642cb8fa672f948b9a41f4351076f45a | spurious/sagittarius-scheme-mirror | args-fold.scm | #!core
(library (srfi :37 args-fold)
(export args-fold
;; issue, option is already defined, so import can not
;; figure out which one should take.
;;(rename (make-option option))
option
option?
option-names
option-required-arg?
option-optional-arg?
option-processor)
(import (rnrs))
(define-record-type (option: option option?)
(fields
(immutable names option-names)
(immutable required-arg? option-required-arg?)
(immutable optional-arg? option-optional-arg?)
(immutable processor option-processor))
(protocol
(lambda (c)
(lambda (n ra oa p)
(if (and
(and (list? n)
(positive? (length n))
(for-all (lambda (x)
(or (and (string? x) (positive? (string-length x)))
(char? x)))
n))
(boolean? ra)
(boolean? oa)
(not (and ra oa))
(procedure? p))
(c n ra oa p)
(assertion-violation 'option "invalid arguments" n ra oa p))))))
(define args-fold
(lambda (args
options
unrecognized-option-proc
operand-proc
. seeds)
(letrec
((find
(lambda (l ?)
(cond ((null? l) #f)
((? (car l)) (car l))
(else (find (cdr l) ?)))))
(find-option
;; ISSUE: This is a brute force search. Could use a table.
(lambda (name)
(find
options
(lambda (option)
(find
(option-names option)
(lambda (test-name)
(equal? name test-name)))))))
(scan-short-options
(lambda (index shorts args seeds)
(if (= index (string-length shorts))
(scan-args args seeds)
(let* ((name (string-ref shorts index))
(option (or (find-option name)
(option (list name)
#f
#f
unrecognized-option-proc))))
(cond ((and (< (+ index 1) (string-length shorts))
(or (option-required-arg? option)
(option-optional-arg? option)))
(let-values
((seeds (apply (option-processor option)
option
name
(substring
shorts
(+ index 1)
(string-length shorts))
seeds)))
(scan-args args seeds)))
((and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds)))
(else
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-short-options
(+ index 1)
shorts
args
seeds))))))))
(scan-operands
(lambda (operands seeds)
(if (null? operands)
(apply values seeds)
(let-values ((seeds (apply operand-proc
(car operands)
seeds)))
(scan-operands (cdr operands) seeds)))))
(scan-args
(lambda (args seeds)
(if (null? args)
(apply values seeds)
(let ((arg (car args))
(args (cdr args)))
;; NOTE: This string matching code would be simpler
;; using a regular expression matcher.
(cond
( rx bos " -- " eos )
(string=? "--" arg)
;; End option scanning:
(scan-operands args seeds))
(;;(rx bos
;; "--"
( submatch ( + ( ~ " = " ) ) )
;; "="
( submatch ( * any ) ) )
(and (> (string-length arg) 4)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1))
(not (char=? #\= (string-ref arg 2)))
(let loop ((index 3))
(cond ((= index (string-length arg))
#f)
((char=? #\= (string-ref arg index))
index)
(else
(loop (+ 1 index))))))
;; Found long option with arg:
=> (lambda (=-index)
(let*-values
(((name)
(substring arg 2 =-index))
((option-arg)
(substring arg
(+ =-index 1)
(string-length arg)))
((option)
(or (find-option name)
(option (list name)
#t
#f
unrecognized-option-proc)))
(seeds
(apply (option-processor option)
option
name
option-arg
seeds)))
(scan-args args seeds))))
( rx bos " -- " ( submatch ( + any ) ) )
(and (> (string-length arg) 3)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1)))
;; Found long option:
(let* ((name (substring arg 2 (string-length arg)))
(option (or (find-option name)
(option
(list name)
#f
#f
unrecognized-option-proc))))
(if (and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds))
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-args args seeds)))))
( rx bos " - " ( submatch ( + any ) ) )
(and (> (string-length arg) 1)
(char=? #\- (string-ref arg 0)))
;; Found short options
(let ((shorts (substring arg 1 (string-length arg))))
(scan-short-options 0 shorts args seeds)))
(else
(let-values ((seeds (apply operand-proc arg seeds)))
(scan-args args seeds)))))))))
(scan-args args seeds))))
)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/srfi/%253a37/args-fold.scm | scheme | issue, option is already defined, so import can not
figure out which one should take.
(rename (make-option option))
ISSUE: This is a brute force search. Could use a table.
NOTE: This string matching code would be simpler
using a regular expression matcher.
End option scanning:
(rx bos
"--"
"="
Found long option with arg:
Found long option:
Found short options | #!core
(library (srfi :37 args-fold)
(export args-fold
option
option?
option-names
option-required-arg?
option-optional-arg?
option-processor)
(import (rnrs))
(define-record-type (option: option option?)
(fields
(immutable names option-names)
(immutable required-arg? option-required-arg?)
(immutable optional-arg? option-optional-arg?)
(immutable processor option-processor))
(protocol
(lambda (c)
(lambda (n ra oa p)
(if (and
(and (list? n)
(positive? (length n))
(for-all (lambda (x)
(or (and (string? x) (positive? (string-length x)))
(char? x)))
n))
(boolean? ra)
(boolean? oa)
(not (and ra oa))
(procedure? p))
(c n ra oa p)
(assertion-violation 'option "invalid arguments" n ra oa p))))))
(define args-fold
(lambda (args
options
unrecognized-option-proc
operand-proc
. seeds)
(letrec
((find
(lambda (l ?)
(cond ((null? l) #f)
((? (car l)) (car l))
(else (find (cdr l) ?)))))
(find-option
(lambda (name)
(find
options
(lambda (option)
(find
(option-names option)
(lambda (test-name)
(equal? name test-name)))))))
(scan-short-options
(lambda (index shorts args seeds)
(if (= index (string-length shorts))
(scan-args args seeds)
(let* ((name (string-ref shorts index))
(option (or (find-option name)
(option (list name)
#f
#f
unrecognized-option-proc))))
(cond ((and (< (+ index 1) (string-length shorts))
(or (option-required-arg? option)
(option-optional-arg? option)))
(let-values
((seeds (apply (option-processor option)
option
name
(substring
shorts
(+ index 1)
(string-length shorts))
seeds)))
(scan-args args seeds)))
((and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds)))
(else
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-short-options
(+ index 1)
shorts
args
seeds))))))))
(scan-operands
(lambda (operands seeds)
(if (null? operands)
(apply values seeds)
(let-values ((seeds (apply operand-proc
(car operands)
seeds)))
(scan-operands (cdr operands) seeds)))))
(scan-args
(lambda (args seeds)
(if (null? args)
(apply values seeds)
(let ((arg (car args))
(args (cdr args)))
(cond
( rx bos " -- " eos )
(string=? "--" arg)
(scan-operands args seeds))
( submatch ( + ( ~ " = " ) ) )
( submatch ( * any ) ) )
(and (> (string-length arg) 4)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1))
(not (char=? #\= (string-ref arg 2)))
(let loop ((index 3))
(cond ((= index (string-length arg))
#f)
((char=? #\= (string-ref arg index))
index)
(else
(loop (+ 1 index))))))
=> (lambda (=-index)
(let*-values
(((name)
(substring arg 2 =-index))
((option-arg)
(substring arg
(+ =-index 1)
(string-length arg)))
((option)
(or (find-option name)
(option (list name)
#t
#f
unrecognized-option-proc)))
(seeds
(apply (option-processor option)
option
name
option-arg
seeds)))
(scan-args args seeds))))
( rx bos " -- " ( submatch ( + any ) ) )
(and (> (string-length arg) 3)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1)))
(let* ((name (substring arg 2 (string-length arg)))
(option (or (find-option name)
(option
(list name)
#f
#f
unrecognized-option-proc))))
(if (and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds))
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-args args seeds)))))
( rx bos " - " ( submatch ( + any ) ) )
(and (> (string-length arg) 1)
(char=? #\- (string-ref arg 0)))
(let ((shorts (substring arg 1 (string-length arg))))
(scan-short-options 0 shorts args seeds)))
(else
(let-values ((seeds (apply operand-proc arg seeds)))
(scan-args args seeds)))))))))
(scan-args args seeds))))
)
|
ff9c82494cbec65e988843df1b6e7853b2a4c0e3eacb3684351afb2eb2cee416 | maralorn/kassandra | Config.hs | module Backend.Config (
readConfig,
BackendConfig (..),
) where
import Dhall (FromDhall)
import Kassandra.Config (
AccountConfig,
Dict,
)
import Kassandra.Config.Dhall (
DhallLoadConfig (
DhallLoadConfig
),
defaultConfig,
defaultFile,
envName,
loadDhallConfig,
)
import Kassandra.Standalone.Config (
BackendConfig (..),
)
readConfig :: Maybe Text -> IO BackendConfig
readConfig =
loadDhallConfig
DhallLoadConfig
{ envName = "KASSANDRA_BACKEND_CONFIG"
, defaultFile = "~/.config/kassandra/backend.dhall"
, defaultConfig = "{ = }"
}
| null | https://raw.githubusercontent.com/maralorn/kassandra/598133b89ab4e4a6209da920636e9e6ee540f38a/apps/kassandra/backend/src/Backend/Config.hs | haskell | module Backend.Config (
readConfig,
BackendConfig (..),
) where
import Dhall (FromDhall)
import Kassandra.Config (
AccountConfig,
Dict,
)
import Kassandra.Config.Dhall (
DhallLoadConfig (
DhallLoadConfig
),
defaultConfig,
defaultFile,
envName,
loadDhallConfig,
)
import Kassandra.Standalone.Config (
BackendConfig (..),
)
readConfig :: Maybe Text -> IO BackendConfig
readConfig =
loadDhallConfig
DhallLoadConfig
{ envName = "KASSANDRA_BACKEND_CONFIG"
, defaultFile = "~/.config/kassandra/backend.dhall"
, defaultConfig = "{ = }"
}
|
|
b4eac20ac12cf02c72239d450fc10ffd70e9221682585e6b225cfa1de2886f09 | Vortecsmaster/EmurgoAcademyPlutusExamples | NFTsV2.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
module NFTsV2
( printRedeemer,
serialisedScript,
scriptSBS,
script,
writeSerialisedScript,
)
where
Related to Serialization ( could be in Deploy module )
import Cardano.Api (PlutusScript, PlutusScriptV2, writeFileTextEnvelope)
import Cardano.Api.Shelley (PlutusScript (..),
ScriptDataJsonSchema (ScriptDataJsonDetailedSchema),
fromPlutusData,
scriptDataToJson)
import Codec.Serialise
-- Related to minting policy validator code and types
import qualified Ledger.Typed.Scripts as Scripts
import Ledger.Value as Value
import qualified Plutus.Script.Utils.V2.Typed.Scripts as Utils.V2
import qualified Plutus.V1.Ledger.Api as PlutusV1
import qualified Plutus.V2.Ledger.Api as PlutusV2
import Plutus.V2.Ledger.Contexts (ownCurrencySymbol)
import qualified PlutusTx
import PlutusTx.Prelude as Plutus hiding
(Semigroup (..), unless, (.))
import Prelude (IO, Semigroup (..), Show (..), print, (.))
import Data.Aeson as A
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Short as SBS
import Data.Functor (void)
data NFTParams = NFTParams -- doesn't need more than the TxOutRef
mpTokenName : : ! .
mpAmount :: !Integer
, mpTxOutRef :: !PlutusV2.TxOutRef
, : : ! . PubKeyHash
} deriving Show
PlutusTx.makeLift ''NFTParams
PlutusTx.unstableMakeIsData ''NFTParams
redeemer :: NFTParams
redeemer = NFTParams { mpAmount = 1,
mpTxOutRef = PlutusV2.TxOutRef {txOutRefId = "612f766282d47b091e3c7372405a3728d752e918ea79251db456d367bbac5ddb"
, txOutRefIdx = 0}
}
printRedeemer = print $ "Redeemer: " <> A.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData $ PlutusV2.toData redeemer)
{-# INLINABLE mkPolicy #-}
mkPolicy :: NFTParams -> BuiltinData -> PlutusV2.ScriptContext -> Bool
mkPolicy p _ ctx = traceIfFalse "UTxO not consumed" hasUTxO &&
traceIfFalse "wrong amount minted" checkNFTAmount
where
info :: PlutusV2.TxInfo
info = PlutusV2.scriptContextTxInfo ctx
hasUTxO :: Bool
hasUTxO = any (\i -> PlutusV2.txInInfoOutRef i == mpTxOutRef p) $ PlutusV2.txInfoInputs info
checkNFTAmount :: Bool
checkNFTAmount = case Value.flattenValue (PlutusV2.txInfoMint info) of
[(cs, tn', amt)] -> cs == ownCurrencySymbol ctx && amt == 1
_ -> False
Compile into UPLC
policy :: NFTParams -> Scripts.MintingPolicy
policy mp = PlutusV2.mkMintingPolicyScript $
$$(PlutusTx.compile [|| wrap ||])
`PlutusTx.applyCode`
PlutusTx.liftCode mp
where
wrap mp' = Utils.V2.mkUntypedMintingPolicy $ mkPolicy mp'
{- As a Script -}
script :: PlutusV2.Script
script = PlutusV2.unMintingPolicyScript $ policy redeemer
{- As a Short Byte String -}
scriptSBS :: SBS.ShortByteString
scriptSBS = SBS.toShort . LBS.toStrict $ serialise script
{- As a Serialised Script -}
serialisedScript :: PlutusScript PlutusScriptV2
serialisedScript = PlutusScriptSerialised scriptSBS
writeSerialisedScript :: IO ()
writeSerialisedScript = void $ writeFileTextEnvelope "testnet/nftMintV2.plutus" Nothing serialisedScript | null | https://raw.githubusercontent.com/Vortecsmaster/EmurgoAcademyPlutusExamples/7a360ac043e9ceb6146cf73cbd2a546af492c984/V1/NativeTokens/src/NFTsV2.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeOperators #
Related to minting policy validator code and types
doesn't need more than the TxOutRef
# INLINABLE mkPolicy #
As a Script
As a Short Byte String
As a Serialised Script | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
module NFTsV2
( printRedeemer,
serialisedScript,
scriptSBS,
script,
writeSerialisedScript,
)
where
Related to Serialization ( could be in Deploy module )
import Cardano.Api (PlutusScript, PlutusScriptV2, writeFileTextEnvelope)
import Cardano.Api.Shelley (PlutusScript (..),
ScriptDataJsonSchema (ScriptDataJsonDetailedSchema),
fromPlutusData,
scriptDataToJson)
import Codec.Serialise
import qualified Ledger.Typed.Scripts as Scripts
import Ledger.Value as Value
import qualified Plutus.Script.Utils.V2.Typed.Scripts as Utils.V2
import qualified Plutus.V1.Ledger.Api as PlutusV1
import qualified Plutus.V2.Ledger.Api as PlutusV2
import Plutus.V2.Ledger.Contexts (ownCurrencySymbol)
import qualified PlutusTx
import PlutusTx.Prelude as Plutus hiding
(Semigroup (..), unless, (.))
import Prelude (IO, Semigroup (..), Show (..), print, (.))
import Data.Aeson as A
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Short as SBS
import Data.Functor (void)
mpTokenName : : ! .
mpAmount :: !Integer
, mpTxOutRef :: !PlutusV2.TxOutRef
, : : ! . PubKeyHash
} deriving Show
PlutusTx.makeLift ''NFTParams
PlutusTx.unstableMakeIsData ''NFTParams
redeemer :: NFTParams
redeemer = NFTParams { mpAmount = 1,
mpTxOutRef = PlutusV2.TxOutRef {txOutRefId = "612f766282d47b091e3c7372405a3728d752e918ea79251db456d367bbac5ddb"
, txOutRefIdx = 0}
}
printRedeemer = print $ "Redeemer: " <> A.encode (scriptDataToJson ScriptDataJsonDetailedSchema $ fromPlutusData $ PlutusV2.toData redeemer)
mkPolicy :: NFTParams -> BuiltinData -> PlutusV2.ScriptContext -> Bool
mkPolicy p _ ctx = traceIfFalse "UTxO not consumed" hasUTxO &&
traceIfFalse "wrong amount minted" checkNFTAmount
where
info :: PlutusV2.TxInfo
info = PlutusV2.scriptContextTxInfo ctx
hasUTxO :: Bool
hasUTxO = any (\i -> PlutusV2.txInInfoOutRef i == mpTxOutRef p) $ PlutusV2.txInfoInputs info
checkNFTAmount :: Bool
checkNFTAmount = case Value.flattenValue (PlutusV2.txInfoMint info) of
[(cs, tn', amt)] -> cs == ownCurrencySymbol ctx && amt == 1
_ -> False
Compile into UPLC
policy :: NFTParams -> Scripts.MintingPolicy
policy mp = PlutusV2.mkMintingPolicyScript $
$$(PlutusTx.compile [|| wrap ||])
`PlutusTx.applyCode`
PlutusTx.liftCode mp
where
wrap mp' = Utils.V2.mkUntypedMintingPolicy $ mkPolicy mp'
script :: PlutusV2.Script
script = PlutusV2.unMintingPolicyScript $ policy redeemer
scriptSBS :: SBS.ShortByteString
scriptSBS = SBS.toShort . LBS.toStrict $ serialise script
serialisedScript :: PlutusScript PlutusScriptV2
serialisedScript = PlutusScriptSerialised scriptSBS
writeSerialisedScript :: IO ()
writeSerialisedScript = void $ writeFileTextEnvelope "testnet/nftMintV2.plutus" Nothing serialisedScript |
e4ea314d9f7631ec8eadc2ae939dfe1acb337f0ca4a53e940da0f978155e0922 | generateme/inferme | pencil_factory.clj | (ns anglican.pencil-factory
(:require [fastmath.core :as m]
[fastmath.random :as r]
[fastmath.stats :as stats]
[inferme.core :refer :all]
[inferme.plot :as plot]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defmodel run-pencil-factory
[p (:uniform-real)]
(model-result [(observe1 (distr :bernoulli {:p p}) 0)]))
(def sampler (infer :metropolis-hastings run-pencil-factory {:samples 10000
:step-scale 0.5
:thin 5}))
(:acceptance-ratio sampler)
= > 0.3294395150250123
= > 0.054428165186102016
(plot/histogram (trace sampler :p))
(plot/lag (trace sampler :p))
;;
(defn exp-beta
"expectation of beta distribution"
^double [^double a ^double b]
(/ a (+ a b)))
(defn var-beta
"variance of beta distribution"
^double [^double a ^double b]
(/ (* a b) (* (m/pow (+ a b) 2.0) (+ a b 1.0))))
(defn exp-beta-pos
"posterior expectation of beta distribution having observed K successes from N trials"
[^double a ^double b ^double N ^double K]
(exp-beta (+ a K) (- (+ b N) K)))
(defn var-beta-pos
"posterior variance of beta distribution having observed K successes from N trials"
[^double a ^double b ^double N ^double K]
(var-beta (+ a K) (- (+ b N) K)))
(defn run-pencil-factory-fn1
[a b n k]
(make-model
[p (:beta {:alpha a :beta b})]
(model-result [(observe1 (distr :binomial {:trials n :p p}) k)])))
(def sampler (infer :metropolis-hastings (run-pencil-factory-fn1 10 3 7 0) {:samples 10000
:step-scale 0.3
:thin 2}))
(:acceptance-ratio sampler)
= > 0.5015896500032446
= > 0.011820122246159248
= > 0.5
= > 0.011904761904761908
(plot/histogram (trace sampler :p))
(plot/lag (trace sampler :p))
;;
(defn run-pencil-factory-fn2
[n k]
(make-model
[z (:exponential {:mean 2})]
(let [p (min z 1.0)]
(model-result [(observe1 (distr :binomial {:trials n :p p}) k)]))))
(def sampler (infer :metropolis-hastings (run-pencil-factory-fn2 10 3) {:samples 10000
:step-scale 0.2
:thin 5}))
(:acceptance-ratio sampler)
= > 0.3267021029649186
= > 0.01680762227591559
(plot/histogram (trace sampler :z))
(plot/lag (trace sampler :z))
| null | https://raw.githubusercontent.com/generateme/inferme/3cee4695bdf2c9c4d79d5257184f5db5e4774bdf/notebooks/anglican/pencil_factory.clj | clojure | (ns anglican.pencil-factory
(:require [fastmath.core :as m]
[fastmath.random :as r]
[fastmath.stats :as stats]
[inferme.core :refer :all]
[inferme.plot :as plot]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defmodel run-pencil-factory
[p (:uniform-real)]
(model-result [(observe1 (distr :bernoulli {:p p}) 0)]))
(def sampler (infer :metropolis-hastings run-pencil-factory {:samples 10000
:step-scale 0.5
:thin 5}))
(:acceptance-ratio sampler)
= > 0.3294395150250123
= > 0.054428165186102016
(plot/histogram (trace sampler :p))
(plot/lag (trace sampler :p))
(defn exp-beta
"expectation of beta distribution"
^double [^double a ^double b]
(/ a (+ a b)))
(defn var-beta
"variance of beta distribution"
^double [^double a ^double b]
(/ (* a b) (* (m/pow (+ a b) 2.0) (+ a b 1.0))))
(defn exp-beta-pos
"posterior expectation of beta distribution having observed K successes from N trials"
[^double a ^double b ^double N ^double K]
(exp-beta (+ a K) (- (+ b N) K)))
(defn var-beta-pos
"posterior variance of beta distribution having observed K successes from N trials"
[^double a ^double b ^double N ^double K]
(var-beta (+ a K) (- (+ b N) K)))
(defn run-pencil-factory-fn1
[a b n k]
(make-model
[p (:beta {:alpha a :beta b})]
(model-result [(observe1 (distr :binomial {:trials n :p p}) k)])))
(def sampler (infer :metropolis-hastings (run-pencil-factory-fn1 10 3 7 0) {:samples 10000
:step-scale 0.3
:thin 2}))
(:acceptance-ratio sampler)
= > 0.5015896500032446
= > 0.011820122246159248
= > 0.5
= > 0.011904761904761908
(plot/histogram (trace sampler :p))
(plot/lag (trace sampler :p))
(defn run-pencil-factory-fn2
[n k]
(make-model
[z (:exponential {:mean 2})]
(let [p (min z 1.0)]
(model-result [(observe1 (distr :binomial {:trials n :p p}) k)]))))
(def sampler (infer :metropolis-hastings (run-pencil-factory-fn2 10 3) {:samples 10000
:step-scale 0.2
:thin 5}))
(:acceptance-ratio sampler)
= > 0.3267021029649186
= > 0.01680762227591559
(plot/histogram (trace sampler :z))
(plot/lag (trace sampler :z))
|
|
8b86c1a5632fa29f6010b1593db2be9da168c29cc1a14c5ea8980fc7c4d3b043 | geophf/1HaskellADay | Solution.hs | {-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module Y2018.M01.D02.Solution where
-
OOH ! HAPPY NEW YEAR , ALL YE HASKELLERS !
Yesterday we scanned our archive of articles and resolved our DatedArticle
type so that we could , finally , upload all 100 articles to the database .
And even before that , we handled optionality ( that we did n't know we had )
gracefully so that we loaded a majority of the articles into the database .
Great !
Now , let 's start refining the upload process . We currently do not process :
authors , sections , and keywords .
The level of complexity , as I see it , is as follows ( easiest to hardest ):
keywords ,
authors ,
sections .
Let 's process keywords today .
Well , here 's the thing about keywords : they are Values that are either Strings
or Numbers , so their show - representation reduces to String , which , in that case
we are now dealing with the Subject - type from before .
So , the trick , today , is to convert a Value to a Subject type and store those
Subject values as we did before .
-
OOH! HAPPY NEW YEAR, ALL YE HASKELLERS!
Yesterday we scanned our archive of articles and resolved our DatedArticle
type so that we could, finally, upload all 100 articles to the database.
And even before that, we handled optionality (that we didn't know we had)
gracefully so that we loaded a majority of the articles into the database.
Great!
Now, let's start refining the upload process. We currently do not process:
authors, sections, and keywords.
The level of complexity, as I see it, is as follows (easiest to hardest):
keywords,
authors,
sections.
Let's process keywords today.
Well, here's the thing about keywords: they are Values that are either Strings
or Numbers, so their show-representation reduces to String, which, in that case
we are now dealing with the Subject-type from before.
So, the trick, today, is to convert a Value to a Subject type and store those
Subject values as we did before.
--}
import Control.Arrow (first, second)
import Control.Monad.State
import Control.Monad.Writer (runWriter)
import Data.Aeson
import Data.Functor.Identity (Identity)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import qualified Data.Text as T
import Database.PostgreSQL.Simple (Connection)
import Database.PostgreSQL.Simple.ToField (ToField)
Below imports available via 1HaskellADay git repository
import Control.DList (dlToList)
import qualified Data.MemoizingTable as MT
import Store.SQL.Connection (withConnection)
import Store.SQL.Util.Indexed
import Store.SQL.Util.Pivots
import Y2017.M10.D03.Solution -- for Subject storage and retrieval
import Y2017.M12.D20.Solution -- for Block
import Y2017.M12.D26.Solution -- for inserting staged articles
for DatedArticle
for filtering out AP articles
sample :: FilePath
sample = "Y2017/M12/D20/sample.json"
kw2subj :: Value -> Subject
kw2subj = Subj . showVal
-
> > > blcks < - rows < $ > readSample sample
> > > ( arts , log ) = ( elide apArt blcks )
> > > keywords < $ > ( snd . head $ tail arts )
Just [ String " chesaepake",String " city council",String " panhandling " ,
String " beg",String " rules",String " " ordinance",String " # po6 " ]
> > > map . keywords < $ > ( snd . head $ tail arts )
Just [ Subj { subj = " chesaepake"},Subj { subj = " city council " } ,
{ subj = " panhandling"},Subj { subj = " beg"},Subj { subj = " rules " } ,
{ subj = " laws"},Subj { subj = " ordinance"},Subj { subj = " # po6 " } ]
And we have our subjects . That means we can follow the module to read subjects
from the database and update the subject table .
-
>>> blcks <- rows <$> readSample sample
>>> (arts, log) = runWriter (elide apArt blcks)
>>> keywords <$> (snd . head $ tail arts)
Just [String "chesaepake",String "city council",String "panhandling",
String "beg",String "rules",String "laws",String "ordinance",String "#po6"]
>>> map kw2subj . keywords <$> (snd . head $ tail arts)
Just [Subj {subj = "chesaepake"},Subj {subj = "city council"},
Subj {subj = "panhandling"},Subj {subj = "beg"},Subj {subj = "rules"},
Subj {subj = "laws"},Subj {subj = "ordinance"},Subj {subj = "#po6"}]
And we have our subjects. That means we can follow the module to read subjects
from the database and update the subject table.
--}
-- the keywords are already parsed from the articles, so we simply repurpose
-- art2Subj as (map kw2subj . keywords) and rock and roll
instance Subjective (DatedArticle a) where
subjects = map kw2subj . keywords
- BONUS -----------------------------------------------------------------
Store the articles as per Y2017.M12.D29.Exercise and , add to the ETL process
storing ancilliary information , which in this case is storing the keywords
as subjects .
-
Store the articles as per Y2017.M12.D29.Exercise and, add to the ETL process
storing ancilliary information, which in this case is storing the keywords
as subjects.
--}
-- parseArticles extracts the blocks, their parsed articles, and the log of
-- the parsing action.
parseArticles :: FromJSON a => BlockParser Identity a -> FilePath
-> IO ([(Block,Maybe (DatedArticle a))], [String])
parseArticles generator json =
rows <$> readSample json >>=
return . second dlToList . runWriter . elide generator apArt
storeArticles :: ToField a => Connection -> [(Block, Maybe (DatedArticle a))]
-> IO [IxValue (DatedArticle a)]
storeArticles conn blxArts =
insertStagedArt conn (map fst blxArts) >>= \ixs ->
let zips = zipWith (\ix (_,mbart) -> sequence (ix,mbart)) ixs blxArts
ins = unzip (catMaybes zips) in
flip (zipWith IxV) (snd ins) <$> (map idx <$> uncurry (insertArts conn) ins)
storeSubjects :: Connection -> [IxValue (DatedArticle a)] -> IO ()
storeSubjects conn ixarts =
fetchSubjects conn >>= \presubs ->
let memtable = MT.start (map ix2tup presubs)
(ids,arts) = unzip (map ix2tup ixarts)
stat = execState (zipWithM_ MT.triageM ids (map subjects arts))
(memtable,Map.empty)
substate = fst stat
in uploadMT conn substate >>= \ixsubs ->
let table = MT.update (map ix2tup ixsubs) substate
in insertSubjPivot conn (evalState buildSubjectPivots (table, snd stat))
storeAncilliary :: Connection -> [IxValue (DatedArticle a)] -> IO ()
storeAncilliary = storeSubjects -- but expanded laterz
etl :: ToField a => FromJSON a => BlockParser Identity a
-> (Connection -> [IxValue (DatedArticle a)] -> IO ())
-> Connection -> FilePath -> IO ()
etl generator ancilliaryFn conn json =
parseArticles generator json >>=
storeArticles conn . fst >>=
ancilliaryFn conn
-
> > > withConnection ( flip ( etl pb storeAncilliary ) sample )
$ select count(1 ) from subject ;
453
$ select * from subject ;
i d subject
525 candidacy
526 captain hook
527 car
528 careercast
529
530 cash - balance plan
531 cat corner
532 cat toy
533 cbn
534 cellphone
535 chamber of commerce
536 charity
$ select * from article_subject ;
i d article_id subject_id
502 853 454
503 854 539
504 854 557
505 854 758
506 854 508
507 854 802
508 854 687
509 854 753
510 854 467
511 855 820
512 855 715
513 855 582
514 855 746
-
>>> withConnection (flip (etl pb storeAncilliary) sample)
$ select count(1) from subject;
453
$ select * from subject;
id subject
525 candidacy
526 captain hook
527 car
528 careercast
529 casey roberts
530 cash-balance plan
531 cat corner
532 cat toy
533 cbn
534 cellphone
535 chamber of commerce
536 charity
$ select * from article_subject;
id article_id subject_id
502 853 454
503 854 539
504 854 557
505 854 758
506 854 508
507 854 802
508 854 687
509 854 753
510 854 467
511 855 820
512 855 715
513 855 582
514 855 746
--}
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2018/M01/D02/Solution.hs | haskell | # LANGUAGE QuasiQuotes, OverloadedStrings #
}
for Subject storage and retrieval
for Block
for inserting staged articles
}
the keywords are already parsed from the articles, so we simply repurpose
art2Subj as (map kw2subj . keywords) and rock and roll
---------------------------------------------------------------
}
parseArticles extracts the blocks, their parsed articles, and the log of
the parsing action.
but expanded laterz
} |
module Y2018.M01.D02.Solution where
-
OOH ! HAPPY NEW YEAR , ALL YE HASKELLERS !
Yesterday we scanned our archive of articles and resolved our DatedArticle
type so that we could , finally , upload all 100 articles to the database .
And even before that , we handled optionality ( that we did n't know we had )
gracefully so that we loaded a majority of the articles into the database .
Great !
Now , let 's start refining the upload process . We currently do not process :
authors , sections , and keywords .
The level of complexity , as I see it , is as follows ( easiest to hardest ):
keywords ,
authors ,
sections .
Let 's process keywords today .
Well , here 's the thing about keywords : they are Values that are either Strings
or Numbers , so their show - representation reduces to String , which , in that case
we are now dealing with the Subject - type from before .
So , the trick , today , is to convert a Value to a Subject type and store those
Subject values as we did before .
-
OOH! HAPPY NEW YEAR, ALL YE HASKELLERS!
Yesterday we scanned our archive of articles and resolved our DatedArticle
type so that we could, finally, upload all 100 articles to the database.
And even before that, we handled optionality (that we didn't know we had)
gracefully so that we loaded a majority of the articles into the database.
Great!
Now, let's start refining the upload process. We currently do not process:
authors, sections, and keywords.
The level of complexity, as I see it, is as follows (easiest to hardest):
keywords,
authors,
sections.
Let's process keywords today.
Well, here's the thing about keywords: they are Values that are either Strings
or Numbers, so their show-representation reduces to String, which, in that case
we are now dealing with the Subject-type from before.
So, the trick, today, is to convert a Value to a Subject type and store those
Subject values as we did before.
import Control.Arrow (first, second)
import Control.Monad.State
import Control.Monad.Writer (runWriter)
import Data.Aeson
import Data.Functor.Identity (Identity)
import qualified Data.Map as Map
import Data.Maybe (catMaybes)
import qualified Data.Text as T
import Database.PostgreSQL.Simple (Connection)
import Database.PostgreSQL.Simple.ToField (ToField)
Below imports available via 1HaskellADay git repository
import Control.DList (dlToList)
import qualified Data.MemoizingTable as MT
import Store.SQL.Connection (withConnection)
import Store.SQL.Util.Indexed
import Store.SQL.Util.Pivots
for DatedArticle
for filtering out AP articles
sample :: FilePath
sample = "Y2017/M12/D20/sample.json"
kw2subj :: Value -> Subject
kw2subj = Subj . showVal
-
> > > blcks < - rows < $ > readSample sample
> > > ( arts , log ) = ( elide apArt blcks )
> > > keywords < $ > ( snd . head $ tail arts )
Just [ String " chesaepake",String " city council",String " panhandling " ,
String " beg",String " rules",String " " ordinance",String " # po6 " ]
> > > map . keywords < $ > ( snd . head $ tail arts )
Just [ Subj { subj = " chesaepake"},Subj { subj = " city council " } ,
{ subj = " panhandling"},Subj { subj = " beg"},Subj { subj = " rules " } ,
{ subj = " laws"},Subj { subj = " ordinance"},Subj { subj = " # po6 " } ]
And we have our subjects . That means we can follow the module to read subjects
from the database and update the subject table .
-
>>> blcks <- rows <$> readSample sample
>>> (arts, log) = runWriter (elide apArt blcks)
>>> keywords <$> (snd . head $ tail arts)
Just [String "chesaepake",String "city council",String "panhandling",
String "beg",String "rules",String "laws",String "ordinance",String "#po6"]
>>> map kw2subj . keywords <$> (snd . head $ tail arts)
Just [Subj {subj = "chesaepake"},Subj {subj = "city council"},
Subj {subj = "panhandling"},Subj {subj = "beg"},Subj {subj = "rules"},
Subj {subj = "laws"},Subj {subj = "ordinance"},Subj {subj = "#po6"}]
And we have our subjects. That means we can follow the module to read subjects
from the database and update the subject table.
instance Subjective (DatedArticle a) where
subjects = map kw2subj . keywords
Store the articles as per Y2017.M12.D29.Exercise and , add to the ETL process
storing ancilliary information , which in this case is storing the keywords
as subjects .
-
Store the articles as per Y2017.M12.D29.Exercise and, add to the ETL process
storing ancilliary information, which in this case is storing the keywords
as subjects.
parseArticles :: FromJSON a => BlockParser Identity a -> FilePath
-> IO ([(Block,Maybe (DatedArticle a))], [String])
parseArticles generator json =
rows <$> readSample json >>=
return . second dlToList . runWriter . elide generator apArt
storeArticles :: ToField a => Connection -> [(Block, Maybe (DatedArticle a))]
-> IO [IxValue (DatedArticle a)]
storeArticles conn blxArts =
insertStagedArt conn (map fst blxArts) >>= \ixs ->
let zips = zipWith (\ix (_,mbart) -> sequence (ix,mbart)) ixs blxArts
ins = unzip (catMaybes zips) in
flip (zipWith IxV) (snd ins) <$> (map idx <$> uncurry (insertArts conn) ins)
storeSubjects :: Connection -> [IxValue (DatedArticle a)] -> IO ()
storeSubjects conn ixarts =
fetchSubjects conn >>= \presubs ->
let memtable = MT.start (map ix2tup presubs)
(ids,arts) = unzip (map ix2tup ixarts)
stat = execState (zipWithM_ MT.triageM ids (map subjects arts))
(memtable,Map.empty)
substate = fst stat
in uploadMT conn substate >>= \ixsubs ->
let table = MT.update (map ix2tup ixsubs) substate
in insertSubjPivot conn (evalState buildSubjectPivots (table, snd stat))
storeAncilliary :: Connection -> [IxValue (DatedArticle a)] -> IO ()
etl :: ToField a => FromJSON a => BlockParser Identity a
-> (Connection -> [IxValue (DatedArticle a)] -> IO ())
-> Connection -> FilePath -> IO ()
etl generator ancilliaryFn conn json =
parseArticles generator json >>=
storeArticles conn . fst >>=
ancilliaryFn conn
-
> > > withConnection ( flip ( etl pb storeAncilliary ) sample )
$ select count(1 ) from subject ;
453
$ select * from subject ;
i d subject
525 candidacy
526 captain hook
527 car
528 careercast
529
530 cash - balance plan
531 cat corner
532 cat toy
533 cbn
534 cellphone
535 chamber of commerce
536 charity
$ select * from article_subject ;
i d article_id subject_id
502 853 454
503 854 539
504 854 557
505 854 758
506 854 508
507 854 802
508 854 687
509 854 753
510 854 467
511 855 820
512 855 715
513 855 582
514 855 746
-
>>> withConnection (flip (etl pb storeAncilliary) sample)
$ select count(1) from subject;
453
$ select * from subject;
id subject
525 candidacy
526 captain hook
527 car
528 careercast
529 casey roberts
530 cash-balance plan
531 cat corner
532 cat toy
533 cbn
534 cellphone
535 chamber of commerce
536 charity
$ select * from article_subject;
id article_id subject_id
502 853 454
503 854 539
504 854 557
505 854 758
506 854 508
507 854 802
508 854 687
509 854 753
510 854 467
511 855 820
512 855 715
513 855 582
514 855 746
|
7cc68cf65b220e6d07ccc68b8ea6a10d852552cc9e461b9781ec84a8501c9404 | spechub/Hets | SortItem.hs | |
Module : ./CASL / SortItem.hs
Description : parser for SORT - ITEMs
Copyright : ( c ) , Uni Bremen 2002 - 2004
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
for SORT - ITEMs ( sort and subsort declarations and definitions )
Module : ./CASL/SortItem.hs
Description : parser for SORT-ITEMs
Copyright : (c) Christian Maeder, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
Parser for SORT-ITEMs (sort and subsort declarations and definitions)
-}
parse SORT - ITEM and " sort / sorts SORT - ITEM ; ... ; SORT - ITEM "
parse DATATYPE - DECL
/
from 25 March 2001
Basic Specifications with Subsorts
parse SORT-ITEM and "sort/sorts SORT-ITEM ; ... ; SORT-ITEM"
parse DATATYPE-DECL
/
from 25 March 2001
C.2.1 Basic Specifications with Subsorts
-}
module CASL.SortItem
( sortItem
, datatype
, subSortDecl
, commaSortDecl
, isoDecl
, parseDatatype
) where
import CASL.AS_Basic_CASL
import CASL.Formula
import Common.AS_Annotation
import Common.AnnoState
import Common.Id
import Common.Keywords
import Common.Lexer
import Common.Parsec
import Common.Token
import Text.ParserCombinators.Parsec
-- * sortItem
commaSortDecl :: [String] -> Id -> AParser st (SORT_ITEM f)
commaSortDecl ks s =
do c <- anComma
(is, cs) <- sortId ks `separatedBy` anComma
let l = s : is
p = catRange (c : cs)
subSortDecl ks (l, p) <|> return (Sort_decl l p)
isoDecl :: TermParser f => [String] -> Id -> AParser st (SORT_ITEM f)
isoDecl ks s =
do e <- equalT
subSortDefn ks (s, tokPos e) <|> do
(l, p) <- sortId ks `separatedBy` equalT
return (Iso_decl (s : l) (catRange (e : p)))
subSortDefn :: TermParser f => [String] -> (Id, Range)
-> AParser st (SORT_ITEM f)
subSortDefn ks (s, e) =
do a <- annos
o <- oBraceT << addAnnos
v <- varId ks
c <- colonT
t <- sortId ks
d <- dotT
f <- formula ks
a2 <- annos
p <- cBraceT
return $ Subsort_defn s v t (Annoted f nullRange a a2)
(e `appRange` catRange [o, c, d, p])
subSortDecl :: [String] -> ([Id], Range) -> AParser st (SORT_ITEM f)
subSortDecl ks (l, p) =
do t <- lessT
s <- sortId ks
return $ Subsort_decl l s (p `appRange` tokPos t)
sortItem :: TermParser f => [String] -> AParser st (SORT_ITEM f)
sortItem ks =
do s <- sortId ks
subSortDecl ks ([s], nullRange) <|> commaSortDecl ks s
<|> isoDecl ks s <|> return (Sort_decl [s] nullRange)
-- * typeItem
datatype :: [String] -> AParser st DATATYPE_DECL
datatype ks = do
s <- sortId ks
e <- asKey defnS
parseDatatype ks s e
parseDatatype :: [String] -> SORT -> Token -> AParser st DATATYPE_DECL
parseDatatype ks s e = do
a <- getAnnos
(Annoted v _ _ b : alts, ps) <- aAlternative ks `separatedBy` barT
return $ Datatype_decl s (Annoted v nullRange a b : alts)
$ catRange $ e : ps
aAlternative :: [String] -> AParser st (Annoted ALTERNATIVE)
aAlternative ks = do
a <- alternative ks
an <- lineAnnos
return (Annoted a nullRange [] an)
alternative :: [String] -> AParser st ALTERNATIVE
alternative ks =
do s <- pluralKeyword sortS
(ts, cs) <- sortId ks `separatedBy` anComma
return (Subsorts ts (catRange (s : cs)))
<|> (consId ks >>= optComps ks)
optComps :: [String] -> Id -> AParser st ALTERNATIVE
optComps ks i = do
o <- wrapAnnos oParenT
(cs, ps) <- component ks `separatedBy` anSemiOrComma
c <- addAnnos >> cParenT
optQuMarkAlt i (concat cs) $ toRange o ps c
<|> return (Alt_construct Total i [] nullRange)
optQuMarkAlt :: Id -> [COMPONENTS] -> Range -> AParser st ALTERNATIVE
optQuMarkAlt i cs qs = do
q <- try (addAnnos >> quMarkT)
return (Alt_construct Partial i cs (qs `appRange` tokPos q))
<|> return (Alt_construct Total i cs qs)
isSortId :: Id -> Bool
isSortId (Id is _ _) = case is of
[Token (c : _) _] -> caslLetters c
_ -> False
component :: [String] -> AParser st [COMPONENTS]
component ks =
do (is, cs) <- parseId ks `separatedBy` anComma
if all isSortId is then
compSort ks is cs <|> return (map Sort is)
else compSort ks is cs
compSort :: [String] -> [OP_NAME] -> [Token] -> AParser st [COMPONENTS]
compSort ks is cs =
do c <- anColon
(b, t, qs) <- opSort ks
let p = catRange (cs ++ [c]) `appRange` qs
return [Cons_select (if b then Partial else Total) is t p]
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/CASL/SortItem.hs | haskell | * sortItem
* typeItem | |
Module : ./CASL / SortItem.hs
Description : parser for SORT - ITEMs
Copyright : ( c ) , Uni Bremen 2002 - 2004
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
for SORT - ITEMs ( sort and subsort declarations and definitions )
Module : ./CASL/SortItem.hs
Description : parser for SORT-ITEMs
Copyright : (c) Christian Maeder, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
Parser for SORT-ITEMs (sort and subsort declarations and definitions)
-}
parse SORT - ITEM and " sort / sorts SORT - ITEM ; ... ; SORT - ITEM "
parse DATATYPE - DECL
/
from 25 March 2001
Basic Specifications with Subsorts
parse SORT-ITEM and "sort/sorts SORT-ITEM ; ... ; SORT-ITEM"
parse DATATYPE-DECL
/
from 25 March 2001
C.2.1 Basic Specifications with Subsorts
-}
module CASL.SortItem
( sortItem
, datatype
, subSortDecl
, commaSortDecl
, isoDecl
, parseDatatype
) where
import CASL.AS_Basic_CASL
import CASL.Formula
import Common.AS_Annotation
import Common.AnnoState
import Common.Id
import Common.Keywords
import Common.Lexer
import Common.Parsec
import Common.Token
import Text.ParserCombinators.Parsec
commaSortDecl :: [String] -> Id -> AParser st (SORT_ITEM f)
commaSortDecl ks s =
do c <- anComma
(is, cs) <- sortId ks `separatedBy` anComma
let l = s : is
p = catRange (c : cs)
subSortDecl ks (l, p) <|> return (Sort_decl l p)
isoDecl :: TermParser f => [String] -> Id -> AParser st (SORT_ITEM f)
isoDecl ks s =
do e <- equalT
subSortDefn ks (s, tokPos e) <|> do
(l, p) <- sortId ks `separatedBy` equalT
return (Iso_decl (s : l) (catRange (e : p)))
subSortDefn :: TermParser f => [String] -> (Id, Range)
-> AParser st (SORT_ITEM f)
subSortDefn ks (s, e) =
do a <- annos
o <- oBraceT << addAnnos
v <- varId ks
c <- colonT
t <- sortId ks
d <- dotT
f <- formula ks
a2 <- annos
p <- cBraceT
return $ Subsort_defn s v t (Annoted f nullRange a a2)
(e `appRange` catRange [o, c, d, p])
subSortDecl :: [String] -> ([Id], Range) -> AParser st (SORT_ITEM f)
subSortDecl ks (l, p) =
do t <- lessT
s <- sortId ks
return $ Subsort_decl l s (p `appRange` tokPos t)
sortItem :: TermParser f => [String] -> AParser st (SORT_ITEM f)
sortItem ks =
do s <- sortId ks
subSortDecl ks ([s], nullRange) <|> commaSortDecl ks s
<|> isoDecl ks s <|> return (Sort_decl [s] nullRange)
datatype :: [String] -> AParser st DATATYPE_DECL
datatype ks = do
s <- sortId ks
e <- asKey defnS
parseDatatype ks s e
parseDatatype :: [String] -> SORT -> Token -> AParser st DATATYPE_DECL
parseDatatype ks s e = do
a <- getAnnos
(Annoted v _ _ b : alts, ps) <- aAlternative ks `separatedBy` barT
return $ Datatype_decl s (Annoted v nullRange a b : alts)
$ catRange $ e : ps
aAlternative :: [String] -> AParser st (Annoted ALTERNATIVE)
aAlternative ks = do
a <- alternative ks
an <- lineAnnos
return (Annoted a nullRange [] an)
alternative :: [String] -> AParser st ALTERNATIVE
alternative ks =
do s <- pluralKeyword sortS
(ts, cs) <- sortId ks `separatedBy` anComma
return (Subsorts ts (catRange (s : cs)))
<|> (consId ks >>= optComps ks)
optComps :: [String] -> Id -> AParser st ALTERNATIVE
optComps ks i = do
o <- wrapAnnos oParenT
(cs, ps) <- component ks `separatedBy` anSemiOrComma
c <- addAnnos >> cParenT
optQuMarkAlt i (concat cs) $ toRange o ps c
<|> return (Alt_construct Total i [] nullRange)
optQuMarkAlt :: Id -> [COMPONENTS] -> Range -> AParser st ALTERNATIVE
optQuMarkAlt i cs qs = do
q <- try (addAnnos >> quMarkT)
return (Alt_construct Partial i cs (qs `appRange` tokPos q))
<|> return (Alt_construct Total i cs qs)
isSortId :: Id -> Bool
isSortId (Id is _ _) = case is of
[Token (c : _) _] -> caslLetters c
_ -> False
component :: [String] -> AParser st [COMPONENTS]
component ks =
do (is, cs) <- parseId ks `separatedBy` anComma
if all isSortId is then
compSort ks is cs <|> return (map Sort is)
else compSort ks is cs
compSort :: [String] -> [OP_NAME] -> [Token] -> AParser st [COMPONENTS]
compSort ks is cs =
do c <- anColon
(b, t, qs) <- opSort ks
let p = catRange (cs ++ [c]) `appRange` qs
return [Cons_select (if b then Partial else Total) is t p]
|
04ad0e420b5109702c634d6ac1183bfa84c96a65580d93771c88fb680189f51b | m4b/rdr | MachLoadCommandTypes.ml | (* ==================================== *)
Load Commands from mach - o /
(* ==================================== *)
type load_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
}
let sizeof_load_command = 8
(* NOTE: str is _not_ apart of the lc_str struct, but added for convenience *)
type lc_str = {
offset: int [@size 4];
str: string [@computed];
}
let sizeof_lc_str = 4
struct section_64 { ( * for 64 - bit architectures
struct section_64 { (* for 64-bit architectures *)
char sectname[16]; (* name of this section *)
char segname[16]; (* segment this section goes in *)
uint64_t addr; (* memory address of this section *)
uint64_t size; (* size in bytes of this section *)
uint32_t offset; (* file offset of this section *)
section alignment ( power of 2 )
uint32_t reloff; (* file offset of relocation entries *)
uint32_t nreloc; (* number of relocation entries *)
uint32_t flags; (* flags (section type and attributes)*)
uint32_t reserved1; (* reserved (for offset or index) *)
uint32_t reserved2; (* reserved (for count or sizeof) *)
uint32_t reserved3; (* reserved *)
};
*)
type section = {
sectname: string [@size 16];
segname: string [@size 16];
addr: int [@size 4];
size: int [@size 4];
offset: int [@size 4];
align: int [@size 4];
reloff: int [@size 4];
nreloc: int [@size 4];
flags: int [@size 4];
reserved1: int [@size 4];
reserved2: int [@size 4];
}
let sizeof_section = 68 (* bytes *)
type section_64 = {
sectname: string [@size 16];
segname: string [@size 16];
addr: int [@size 8];
size: int [@size 8];
offset: int [@size 4];
align: int [@size 4];
reloff: int [@size 4];
nreloc: int [@size 4];
flags: int [@size 4];
reserved1: int [@size 4];
reserved2: int [@size 4];
reserved3: int [@size 4];
}
let sizeof_section_64 = 80 (* bytes *)
type segment_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
segname: string [@size 16];
vmaddr: int [@size 4];
vmsize: int [@size 4];
fileoff: int [@size 4];
filesize: int [@size 4];
maxprot: int [@size 4];
initprot: int [@size 4];
nsects: int [@size 4];
flags: int [@size 4];
sections: section list [@computed nsects];
}
let sizeof_segment_command_64 = 56
type segment_command_64 = {
cmd: int [@size 4];
cmdsize: int [@size 4];
segname: string [@size 16];
vmaddr: int [@size 8];
vmsize: int [@size 8];
fileoff: int [@size 8];
filesize: int [@size 8];
maxprot: int [@size 4];
initprot: int [@size 4];
nsects: int [@size 4];
flags: int [@size 4];
sections: section_64 list [@computed nsects];
}
let sizeof_segment_command_64 = 72
* Fixed virtual memory shared libraries are identified by two things . The
* target pathname ( the name of the library as found for execution ) , and the
* minor version number . The address of where the headers are loaded is in
* header_addr . ( THIS IS OBSOLETE and no longer supported ) .
* Fixed virtual memory shared libraries are identified by two things. The
* target pathname (the name of the library as found for execution), and the
* minor version number. The address of where the headers are loaded is in
* header_addr. (THIS IS OBSOLETE and no longer supported).
*)
type fvmlib = {
name: lc_str [@size 4]; (* library's target pathname *)
minor_version: int [@size 4]; (* library's minor version number *)
header_addr: int [@size 4]; (* library's header address *)
}
let sizeof_fvmlib = 12
(*
* A fixed virtual shared library (filetype == MH_FVMLIB in the mach header)
* contains a fvmlib_command (cmd == LC_IDFVMLIB) to identify the library.
* An object that uses a fixed virtual shared library also contains a
* fvmlib_command (cmd == LC_LOADFVMLIB) for each library it uses.
* (THIS IS OBSOLETE and no longer supported).
*)
type fvmlib_command = {
LC_IDFVMLIB or LC_LOADFVMLIB
cmdsize: int [@size 4]; (* includes pathname string *)
fvmlib: fvmlib [@size 4]; (* the library identification *)
}
let sizeof_fvmlib_command = 20
*
* Dynamicly linked shared libraries are identified by two things . The
* pathname ( the name of the library as found for execution ) , and the
* compatibility version number . The pathname must match and the compatibility
* number in the user of the library must be greater than or equal to the
* library being used . The time stamp is used to record the time a library was
* built and copied into user so it can be use to determined if the library used
* at runtime is exactly the same as used to built the program .
*
struct dylib {
union lc_str name ; ( * library 's path name
*
* Dynamicly linked shared libraries are identified by two things. The
* pathname (the name of the library as found for execution), and the
* compatibility version number. The pathname must match and the compatibility
* number in the user of the library must be greater than or equal to the
* library being used. The time stamp is used to record the time a library was
* built and copied into user so it can be use to determined if the library used
* at runtime is exactly the same as used to built the program.
*
struct dylib {
union lc_str name; (* library's path name *)
uint32_t timestamp; (* library's build time stamp *)
uint32_t current_version; (* library's current version number *)
uint32_t compatibility_version; (* library's compatibility vers number*)
};
*)
(*
*
* A dynamically linked shared library (filetype == MH_DYLIB in the mach header)
* contains a dylib_command (cmd == LC_ID_DYLIB) to identify the library.
* An object that uses a dynamically linked shared library also contains a
* dylib_command (cmd == LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, or
* LC_REEXPORT_DYLIB) for each library it uses.
*
*)
type dylib = {
name: lc_str [@size 4]; (* library's path name *)
timestamp: int [@size 4]; (* library's build time stamp *)
current_version: int [@size 4]; (* library's current version number *)
compatibility_version: int [@size 4]; (* library's compatibility vers number*)
}
let sizeof_dylib = 16
type dylib_command =
{
cmd: int [@size 4]; (* LC_ID_DYLIB, LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB *)
cmdsize: int [@size 4]; (* includes pathname string *)
dylib: dylib [@size 16]; (* the library identification *)
}
let sizeof_dylib_command = 20 (*bytes*)
(*
* A dynamically linked shared library may be a subframework of an umbrella
* framework. If so it will be linked with "-umbrella umbrella_name" where
* Where "umbrella_name" is the name of the umbrella framework. A subframework
* can only be linked against by its umbrella framework or other subframeworks
* that are part of the same umbrella framework. Otherwise the static link
* editor produces an error and states to link against the umbrella framework.
* The name of the umbrella framework for subframeworks is recorded in the
* following structure.
*)
type sub_framework_command = {
LC_SUB_FRAMEWORK
cmdsize: int [@size 4]; (* includes umbrella string *)
umbrella: lc_str [@size 4]; (* the umbrella framework name *)
}
let sizeof_sub_framework_command= 12
* For dynamically linked shared libraries that are subframework of an umbrella
* framework they can allow clients other than the umbrella framework or other
* subframeworks in the same umbrella framework . To do this the subframework
* is built with " -allowable_client client_name " and an LC_SUB_CLIENT load
* command is created for each -allowable_client flag . The client_name is
* usually a framework name . It can also be a name used for bundles clients
* where the bundle is built with " -client_name client_name " .
* For dynamically linked shared libraries that are subframework of an umbrella
* framework they can allow clients other than the umbrella framework or other
* subframeworks in the same umbrella framework. To do this the subframework
* is built with "-allowable_client client_name" and an LC_SUB_CLIENT load
* command is created for each -allowable_client flag. The client_name is
* usually a framework name. It can also be a name used for bundles clients
* where the bundle is built with "-client_name client_name".
*)
type sub_client_command = {
LC_SUB_CLIENT
cmdsize: int [@size 4]; (* includes client string *)
client: lc_str [@size 4]; (* the client name *)
}
let sizeof_sub_client_command = 12
* A dynamically linked shared library may be a sub_umbrella of an umbrella
* framework . If so it will be linked with " -sub_umbrella umbrella_name " where
* Where " umbrella_name " is the name of the sub_umbrella framework . When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* umbrella framework will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks to be implicited linked in . Any other
* dependent dynamic libraries will not be linked it when -twolevel_namespace
* is in effect . The primary library recorded by the static linker when
* resolving a symbol in these libraries will be the umbrella framework .
* Zero or more sub_umbrella frameworks may be use by an umbrella framework .
* The name of a sub_umbrella framework is recorded in the following structure .
* A dynamically linked shared library may be a sub_umbrella of an umbrella
* framework. If so it will be linked with "-sub_umbrella umbrella_name" where
* Where "umbrella_name" is the name of the sub_umbrella framework. When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* umbrella framework will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks to be implicited linked in. Any other
* dependent dynamic libraries will not be linked it when -twolevel_namespace
* is in effect. The primary library recorded by the static linker when
* resolving a symbol in these libraries will be the umbrella framework.
* Zero or more sub_umbrella frameworks may be use by an umbrella framework.
* The name of a sub_umbrella framework is recorded in the following structure.
*)
type sub_umbrella_command = {
LC_SUB_UMBRELLA
cmdsize: int [@size 4]; (* includes sub_umbrella string *)
the sub_umbrella framework name
}
let sizeof_sub_umbrella_command = 12
* A dynamically linked shared library may be a sub_library of another shared
* library . If so it will be linked with " -sub_library library_name " where
* Where " library_name " is the name of the sub_library shared library . When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* shared library will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks and libraries listed as sub_libraries to
* be implicited linked in . Any other dependent dynamic libraries will not be
* linked it when -twolevel_namespace is in effect . The primary library
* recorded by the static linker when resolving a symbol in these libraries
* will be the umbrella framework ( or dynamic library ) . Zero or more sub_library
* shared libraries may be use by an umbrella framework or ( or dynamic library ) .
* The name of a sub_library framework is recorded in the following structure .
* For example /usr / lib / libobjc_profile . A.dylib would be recorded as " libobjc " .
* A dynamically linked shared library may be a sub_library of another shared
* library. If so it will be linked with "-sub_library library_name" where
* Where "library_name" is the name of the sub_library shared library. When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* shared library will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks and libraries listed as sub_libraries to
* be implicited linked in. Any other dependent dynamic libraries will not be
* linked it when -twolevel_namespace is in effect. The primary library
* recorded by the static linker when resolving a symbol in these libraries
* will be the umbrella framework (or dynamic library). Zero or more sub_library
* shared libraries may be use by an umbrella framework or (or dynamic library).
* The name of a sub_library framework is recorded in the following structure.
* For example /usr/lib/libobjc_profile.A.dylib would be recorded as "libobjc".
*)
type sub_library_command = {
cmd: int [@size 4]; (* LC_SUB_LIBRARY *)
includes sub_library string
the sub_library name
}
let sizeof_sub_library_command = 12
* A program ( filetype = = MH_EXECUTE ) that is
* prebound to its dynamic libraries has one of these for each library that
* the static linker used in prebinding . It contains a bit vector for the
* modules in the library . The bits indicate which modules are bound ( 1 ) and
* which are not ( 0 ) from the library . The bit for module 0 is the low bit
* of the first byte . So the bit for the Nth module is :
* ( linked_modules[N/8 ] > > N%8 ) & 1
* A program (filetype == MH_EXECUTE) that is
* prebound to its dynamic libraries has one of these for each library that
* the static linker used in prebinding. It contains a bit vector for the
* modules in the library. The bits indicate which modules are bound (1) and
* which are not (0) from the library. The bit for module 0 is the low bit
* of the first byte. So the bit for the Nth module is:
* (linked_modules[N/8] >> N%8) & 1
*)
type prebound_dylib_command = {
cmd: int [@size 4]; (* LC_PREBOUND_DYLIB *)
cmdsize: int [@size 4]; (* includes strings *)
name: lc_str [@size 4]; (* library's path name *)
nmodules: int [@size 4]; (* number of modules in library *)
linked_modules: lc_str [@size 4]; (* bit vector of linked modules *)
}
let sizeof_prebound_dylib_command = 20
type dylinker_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
name: lc_str [@size 4];
}
let sizeof_dylinker_command = 12
* Thread commands contain machine - specific data structures suitable for
* use in the thread state primitives . The machine specific data structures
* follow the struct thread_command as follows .
* Each flavor of machine specific data structure is preceded by an unsigned
* long constant for the flavor of that data structure , an uint32_t
* that is the count of longs of the size of the state data structure and then
* the state data structure follows . This triple may be repeated for many
* flavors . The constants for the flavors , counts and state data structure
* definitions are expected to be in the header file < machine / thread_status.h > .
* These machine specific data structures sizes must be multiples of
* 4 bytes The cmdsize reflects the total size of the thread_command
* and all of the sizes of the constants for the flavors , counts and state
* data structures .
*
* For executable objects that are unix processes there will be one
* thread_command ( cmd = = LC_UNIXTHREAD ) created for it by the link - editor .
* This is the same as a LC_THREAD , except that a stack is automatically
* created ( based on the shell 's limit for the stack size ) . Command arguments
* and environment variables are copied onto that stack .
* Thread commands contain machine-specific data structures suitable for
* use in the thread state primitives. The machine specific data structures
* follow the struct thread_command as follows.
* Each flavor of machine specific data structure is preceded by an unsigned
* long constant for the flavor of that data structure, an uint32_t
* that is the count of longs of the size of the state data structure and then
* the state data structure follows. This triple may be repeated for many
* flavors. The constants for the flavors, counts and state data structure
* definitions are expected to be in the header file <machine/thread_status.h>.
* These machine specific data structures sizes must be multiples of
* 4 bytes The cmdsize reflects the total size of the thread_command
* and all of the sizes of the constants for the flavors, counts and state
* data structures.
*
* For executable objects that are unix processes there will be one
* thread_command (cmd == LC_UNIXTHREAD) created for it by the link-editor.
* This is the same as a LC_THREAD, except that a stack is automatically
* created (based on the shell's limit for the stack size). Command arguments
* and environment variables are copied onto that stack.
*)
unimplemented , see machine / thread_status.h for rest of values :
uint32_t flavor flavor of thread state
uint32_t count count of longs in thread state
struct XXX_thread_state state thread state for this flavor
...
uint32_t flavor flavor of thread state
uint32_t count count of longs in thread state
struct XXX_thread_state state thread state for this flavor
... *)
type thread_command = {
LC_THREAD or LC_UNIXTHREAD
cmdsize: int [@size 4]; (* total size of this command *)
thread_state: MachThread64.t;
}
* The routines command contains the address of the dynamic shared library
* initialization routine and an index into the module table for the module
* that defines the routine . Before any modules are used from the library the
* dynamic linker fully binds the module that defines the initialization routine
* and then calls it . This gets called before any module initialization
* routines ( used for C++ static constructors ) in the library .
* The routines command contains the address of the dynamic shared library
* initialization routine and an index into the module table for the module
* that defines the routine. Before any modules are used from the library the
* dynamic linker fully binds the module that defines the initialization routine
* and then calls it. This gets called before any module initialization
* routines (used for C++ static constructors) in the library.
*)
for 32 - bit architectures
LC_ROUTINES
cmdsize: int [@size 4]; (* total size of this command *)
init_address: int [@size 4]; (* address of initialization routine *)
init_module: int [@size 4]; (* index into the module table that the init routine is defined in *)
reserved1: int [@size 4];
reserved2: int [@size 4];
reserved3: int [@size 4];
reserved4: int [@size 4];
reserved5: int [@size 4];
reserved6: int [@size 4];
}
* The 64 - bit routines command . Same use as above .
* The 64-bit routines command. Same use as above.
*)
for 64 - bit architectures
LC_ROUTINES_64
cmdsize: int [@size 4]; (* total size of this command *)
init_address: int [@size 8];(* address of initialization routine *)
index into the module table that the init routine is defined in 8 bytes each
reserved1: int [@size 8];
reserved2: int [@size 8];
reserved3: int [@size 8];
reserved4: int [@size 8];
reserved5: int [@size 8];
reserved6: int [@size 8];
}
type symtab_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
symoff: int [@size 4];
nsyms: int [@size 4];
stroff: int [@size 4];
strsize: int [@size 4];
}
let sizeof_symtab_command = 24
* This is the second set of the symbolic information which is used to support
* the data structures for the dynamically link editor .
*
* The original set of symbolic information in the symtab_command which contains
* the symbol and string tables must also be present when this load command is
* present . When this load command is present the symbol table is organized
* into three groups of symbols :
* local symbols ( static and debugging symbols ) - grouped by module
* defined external symbols - grouped by module ( sorted by name if not lib )
* undefined external symbols ( sorted by name if MH_BINDATLOAD is not set ,
* and in order the were seen by the static
* linker if MH_BINDATLOAD is set )
* In this load command there are offsets and counts to each of the three groups
* of symbols .
*
* This load command contains a the offsets and sizes of the following new
* symbolic information tables :
* table of contents
* module table
* reference symbol table
* indirect symbol table
* The first three tables above ( the table of contents , module table and
* reference symbol table ) are only present if the file is a dynamically linked
* shared library . For executable and object modules , which are files
* containing only one module , the information that would be in these three
* tables is determined as follows :
* table of contents - the defined external symbols are sorted by name
* module table - the file contains only one module so everything in the
* file is part of the module .
* reference symbol table - is the defined and undefined external symbols
*
* For dynamically linked shared library files this load command also contains
* offsets and sizes to the pool of relocation entries for all sections
* separated into two groups :
* external relocation entries
* local relocation entries
* For executable and object modules the relocation entries continue to hang
* off the section structures .
* This is the second set of the symbolic information which is used to support
* the data structures for the dynamically link editor.
*
* The original set of symbolic information in the symtab_command which contains
* the symbol and string tables must also be present when this load command is
* present. When this load command is present the symbol table is organized
* into three groups of symbols:
* local symbols (static and debugging symbols) - grouped by module
* defined external symbols - grouped by module (sorted by name if not lib)
* undefined external symbols (sorted by name if MH_BINDATLOAD is not set,
* and in order the were seen by the static
* linker if MH_BINDATLOAD is set)
* In this load command there are offsets and counts to each of the three groups
* of symbols.
*
* This load command contains a the offsets and sizes of the following new
* symbolic information tables:
* table of contents
* module table
* reference symbol table
* indirect symbol table
* The first three tables above (the table of contents, module table and
* reference symbol table) are only present if the file is a dynamically linked
* shared library. For executable and object modules, which are files
* containing only one module, the information that would be in these three
* tables is determined as follows:
* table of contents - the defined external symbols are sorted by name
* module table - the file contains only one module so everything in the
* file is part of the module.
* reference symbol table - is the defined and undefined external symbols
*
* For dynamically linked shared library files this load command also contains
* offsets and sizes to the pool of relocation entries for all sections
* separated into two groups:
* external relocation entries
* local relocation entries
* For executable and object modules the relocation entries continue to hang
* off the section structures.
*)
type dysymtab_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
ilocalsym: int [@size 4]; (* index to local symbols *)
nlocalsym: int [@size 4]; (* number of local symbols *)
iextdefsym: int [@size 4]; (* index to externally defined symbols *)
nextdefsym: int [@size 4]; (* number of externally defined symbols *)
iundefsym: int [@size 4]; (* index to undefined symbols *)
nundefsym: int [@size 4]; (* number of undefined symbols *)
tocoff: int [@size 4]; (* file offset to table of contents *)
ntoc: int [@size 4]; (* number of entries in table of contents *)
modtaboff: int [@size 4]; (* file offset to module table *)
nmodtab: int [@size 4]; (* number of module table entries *)
extrefsymoff: int [@size 4]; (* offset to referenced symbol table *)
nextrefsyms: int [@size 4]; (* number of referenced symbol table entries *)
indirectsymoff: int [@size 4]; (* file offset to the indirect symbol table *)
nindirectsyms: int [@size 4]; (* number of indirect symbol table entries *)
extreloff: int [@size 4]; (* offset to external relocation entries *)
nextrel: int [@size 4]; (* number of external relocation entries *)
locreloff: int [@size 4]; (* offset to local relocation entries *)
nlocrel: int [@size 4]; (* number of local relocation entries *)
}
let sizeof_dysymtab_command = 80 (* bytes *)
(* TODO: unimplemented *)
(* a table of contents entry *)
type dylib_table_of_contents = {
symbol_index: int [@size 4]; (* the defined external symbol (index into the symbol table) *)
module_index: int [@size 4]; (* index into the module table this symbol is defined in *)
}
(* TODO: unimplemented *)
(* a module table entry *)
type dylib_module = {
module_name: int [@size 4]; (* the module name (index into string table) *)
iextdefsym: int [@size 4]; (*index into externally defined symbols *)
nextdefsym: int [@size 4]; (*number of externally defined symbols *)
irefsym: int [@size 4]; (* index into reference symbol table *)
nrefsym: int [@size 4]; (*number of reference symbol table entries *)
ilocalsym: int [@size 4]; (* index into symbols for local symbols *)
nlocalsym: int [@size 4]; (*number of local symbols *)
iextrel: int [@size 4]; (* index into external relocation entries *)
nextrel: int [@size 4]; (* number of external relocation entries *)
low 16 bits are the index into the init section , high 16 bits are the index into the term section
low 16 bits are the number of init section entries , high 16 bits are the number of term section entries
objc_module_info_addr: int [@size 4]; (* the (__OBJC,__module_info) section *)
objc_module_info_size: int [@size 4]; (* the (__OBJC,__module_info) section *)
}
(* TODO: unimplemented *)
a 64 - bit module table entry
type dylib_module_64 = {
module_name: int [@size 4]; (* the module name (index into string table) *)
iextdefsym: int [@size 4]; (* index into externally defined symbols *)
nextdefsym: int [@size 4]; (* number of externally defined symbols *)
irefsym: int [@size 4]; (* index into reference symbol table *)
nrefsym: int [@size 4]; (* number of reference symbol table entries *)
ilocalsym: int [@size 4]; (* index into symbols for local symbols *)
nlocalsym: int [@size 4]; (* number of local symbols *)
iextrel: int [@size 4]; (* index into external relocation entries *)
nextrel: int [@size 4]; (* number of external relocation entries *)
low 16 bits are the index into the init section , high 16 bits are the index into the term section
low 16 bits are the number of init section entries , high 16 bits are the number of term section entries
objc_module_info_size: int [@size 4]; (* the (__OBJC,__module_info) section *)
objc_module_info_addr: int [@size 8]; (* the (__OBJC,__module_info) section *)
}
(*
* The entries in the reference symbol table are used when loading the module
* (both by the static and dynamic link editors) and if the module is unloaded
* or replaced. Therefore all external symbols (defined and undefined) are
* listed in the module's reference table. The flags describe the type of
* reference that is being made. The constants for the flags are defined in
* <mach-o/nlist.h> as they are also used for symbol table entries.
*)
(* TODO: unimplemented, BIT FIELDS *)
type dylib_reference = {
24 bits bit - field index into the symbol table
flags: int [@size 8]; (* flags to indicate the type of reference *)
}
* The twolevel_hints_command contains the offset and number of hints in the
* two - level namespace lookup hints table .
* The twolevel_hints_command contains the offset and number of hints in the
* two-level namespace lookup hints table.
*)
(* TODO: unimplemented *)
type twolevel_hints_command = {
cmd: int [@size 4];(* LC_TWOLEVEL_HINTS *)
cmdsize: int [@size 4]; (* sizeof(struct twolevel_hints_command) *)
offset: int [@size 4]; (* offset to the hint table *)
nhints: int [@size 4]; (* number of hints in the hint table *)
}
* The entries in the two - level namespace lookup hints table are twolevel_hint
* structs . These provide hints to the dynamic link editor where to start
* looking for an undefined symbol in a two - level namespace image . The
* isub_image field is an index into the sub - images ( sub - frameworks and
* sub - umbrellas list ) that made up the two - level image that the undefined
* symbol was found in when it was built by the static link editor . If
* isub - image is 0 the the symbol is expected to be defined in library and not
* in the sub - images . If isub - image is non - zero it is an index into the array
* of sub - images for the umbrella with the first index in the sub - images being
* 1 . The array of sub - images is the ordered list of sub - images of the umbrella
* that would be searched for a symbol that has the umbrella recorded as its
* primary library . The table of contents index is an index into the
* library 's table of contents . This is used as the starting point of the
* binary search or a directed linear search .
* The entries in the two-level namespace lookup hints table are twolevel_hint
* structs. These provide hints to the dynamic link editor where to start
* looking for an undefined symbol in a two-level namespace image. The
* isub_image field is an index into the sub-images (sub-frameworks and
* sub-umbrellas list) that made up the two-level image that the undefined
* symbol was found in when it was built by the static link editor. If
* isub-image is 0 the the symbol is expected to be defined in library and not
* in the sub-images. If isub-image is non-zero it is an index into the array
* of sub-images for the umbrella with the first index in the sub-images being
* 1. The array of sub-images is the ordered list of sub-images of the umbrella
* that would be searched for a symbol that has the umbrella recorded as its
* primary library. The table of contents index is an index into the
* library's table of contents. This is used as the starting point of the
* binary search or a directed linear search.
*)
TODO : unimplemented , BITFIELDS
type twolevel_hint = {
isub_image: int [@size 8]; (* index into the sub images *)
24 bit field index into the table of contents
}
* The prebind_cksum_command contains the value of the original check sum for
* prebound files or zero . When a prebound file is first created or modified
* for other than updating its prebinding information the value of the check sum
* is set to zero . When the file has it prebinding re - done and if the value of
* the check sum is zero the original check sum is calculated and stored in
* cksum field of this load command in the output file . If when the prebinding
* is re - done and the cksum field is non - zero it is left unchanged from the
* input file .
* The prebind_cksum_command contains the value of the original check sum for
* prebound files or zero. When a prebound file is first created or modified
* for other than updating its prebinding information the value of the check sum
* is set to zero. When the file has it prebinding re-done and if the value of
* the check sum is zero the original check sum is calculated and stored in
* cksum field of this load command in the output file. If when the prebinding
* is re-done and the cksum field is non-zero it is left unchanged from the
* input file.
*)
(* TODO: unimplemented *)
type prebind_cksum_command = {
cmd: int [@size 4]; (* LC_PREBIND_CKSUM *)
cmdsize: int [@size 4]; (* sizeof(struct prebind_cksum_command) *)
the check sum or zero
}
* The uuid load command contains a single 128 - bit unique random number that
* identifies an object produced by the static link editor .
* The uuid load command contains a single 128-bit unique random number that
* identifies an object produced by the static link editor.
*)
type uuid_command = {
cmd: int [@size 4]; (* LC_UUID *)
cmdsize: int [@size 4]; (* sizeof(struct uuid_command) *)
16 bytes the 128 - bit uuid
}
let sizeof_uuid_command = 24
(*
* The rpath_command contains a path which at runtime should be added to
* the current run path used to find @rpath prefixed dylibs.
*)
type rpath_command = {
cmd: int [@size 4]; (* LC_RPATH *)
cmdsize: int [@size 4]; (* includes string *)
path: lc_str [@size 4]; (* path to add to run path *)
}
let sizeof_rpath_command = 12
* The linkedit_data_command contains the offsets and sizes of a blob
* of data in the _ _ LINKEDIT segment .
* The linkedit_data_command contains the offsets and sizes of a blob
* of data in the __LINKEDIT segment.
*)
type linkedit_data_command = {
LC_CODE_SIGNATURE , , , LC_DATA_IN_CODE , LC_DYLIB_CODE_SIGN_DRS or LC_LINKER_OPTIMIZATION_HINT .
cmdsize: int [@size 4]; (* sizeof(struct linkedit_data_command) *)
file offset of data in _ _ LINKEDIT segment
file size of data in _ _ LINKEDIT segment
}
let sizeof_linkedit_data_command = 16
(*
* The encryption_info_command contains the file offset and size of an
* of an encrypted segment.
*)
type encryption_info_command = {
LC_ENCRYPTION_INFO
cmdsize: int [@size 4]; (* sizeof(struct encryption_info_command) *)
cryptoff: int [@size 4]; (* file offset of encrypted range *)
cryptsize: int [@size 4]; (* file size of encrypted range *)
cryptid: int [@size 4]; (* which enryption system, 0 means not-encrypted yet *)
}
let sizeof_encryption_info_command = 20
* The encryption_info_command_64 contains the file offset and size of an
* of an encrypted segment ( for use in x86_64 targets ) .
* The encryption_info_command_64 contains the file offset and size of an
* of an encrypted segment (for use in x86_64 targets).
*)
type encryption_info_command_64 = {
cmd: int [@size 4]; (* LC_ENCRYPTION_INFO_64 *)
cmdsize: int [@size 4]; (* sizeof(struct encryption_info_command_64) *)
cryptoff: int [@size 4]; (* file offset of encrypted range *)
cryptsize: int [@size 4]; (* file size of encrypted range *)
cryptid: int [@size 4]; (* which enryption system, 0 means not-encrypted yet *)
padding to make this struct 's size a multiple of 8 bytes
}
let sizeof_encryption_info_command_64 = 24
(*
* The version_min_command contains the min OS version on which this
* binary was built to run.
*
* LC_VERSION_MIN_MACOSX or LC_VERSION_MIN_IPHONEOS *)
type version_min_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
X.Y.Z is encoded in nibbles xxxx.yy.zz
X.Y.Z is encoded in nibbles xxxx.yy.zz
}
let sizeof_version_min_command = 16 (* bytes *)
(*
struct dyld_info_command {
uint32_t cmd; (* LC_DYLD_INFO or LC_DYLD_INFO_ONLY *)
uint32_t cmdsize; (* sizeof(struct dyld_info_command) *)
uint32_t rebase_off; (* file offset to rebase info *)
uint32_t rebase_size; (* size of rebase info *)
uint32_t bind_off; (* file offset to binding info *)
uint32_t bind_size; (* size of binding info *)
uint32_t weak_bind_off; (* file offset to weak binding info *)
uint32_t weak_bind_size; (* size of weak binding info *)
uint32_t lazy_bind_off; (* file offset to lazy binding info *)
uint32_t lazy_bind_size; (* size of lazy binding infs *)
uint32_t export_off; (* file offset to lazy binding info *)
uint32_t export_size; (* size of lazy binding infs *)
};
*)
type dyld_info_command =
{
cmd: int [@size 4];
cmdsize: int [@size 4];
rebase_off: int [@size 4];
rebase_size: int [@size 4];
bind_off: int [@size 4];
bind_size: int [@size 4];
weak_bind_off: int [@size 4];
weak_bind_size: int [@size 4];
lazy_bind_off: int [@size 4];
lazy_bind_size: int [@size 4];
export_off: int [@size 4];
export_size: int [@size 4];
}
let sizeof_dylib_info_command = 48
(*
* The linker_option_command contains linker options embedded in object files.
*)
type linker_option_command = {
LC_LINKER_OPTION only used in MH_OBJECT filetypes
cmdsize: int [@size 4];
number of strings concatenation of zero terminated UTF8 strings . Zero filled at end to align
}
let sizeof_linker_option_command = 12
* The symseg_command contains the offset and size of the GNU style
* symbol table information as described in the header file < symseg.h > .
* The symbol roots of the symbol segments must also be aligned properly
* in the file . So the requirement of keeping the offsets aligned to a
* multiple of a 4 bytes translates to the length field of the symbol
* roots also being a multiple of a long . Also the padding must again be
* zeroed . ( THIS IS OBSOLETE and no longer supported ) .
* The symseg_command contains the offset and size of the GNU style
* symbol table information as described in the header file <symseg.h>.
* The symbol roots of the symbol segments must also be aligned properly
* in the file. So the requirement of keeping the offsets aligned to a
* multiple of a 4 bytes translates to the length field of the symbol
* roots also being a multiple of a long. Also the padding must again be
* zeroed. (THIS IS OBSOLETE and no longer supported).
*)
type symseg_command = {
cmdsize: int [@size 4]; (* sizeof(struct symseg_command) *)
offset: int [@size 4]; (* symbol segment offset *)
size: int [@size 4]; (* symbol segment size in bytes *)
}
let sizeof_symseg_command = 16
* The ident_command contains a free format string table following the
* ident_command structure . The strings are null terminated and the size of
* the command is padded out with zero bytes to a multiple of 4 bytes/
* ( THIS IS OBSOLETE and no longer supported ) .
* The ident_command contains a free format string table following the
* ident_command structure. The strings are null terminated and the size of
* the command is padded out with zero bytes to a multiple of 4 bytes/
* (THIS IS OBSOLETE and no longer supported).
*)
type ident_command = {
LC_IDENT
cmdsize: int [@size 4]; (* strings that follow this command *)
}
let sizeof_ident_command = 8
(*
* The fvmfile_command contains a reference to a file to be loaded at the
* specified virtual address. (Presently, this command is reserved for
* internal use. The kernel ignores this command when loading a program into
* memory).
*)
type fvmfile_command = {
LC_FVMFILE
cmdsize: int [@size 4]; (* includes pathname string *)
name: lc_str [@size 4]; (* files pathname *)
header_addr: int [@size 4]; (* files virtual address *)
}
let sizeof_fvmfile_command = 16
(*
* The entry_point_command is a replacement for thread_command.
* It is used for main executables to specify the location (file offset)
* of main(). If -stack_size was used at link time, the stacksize
* field will contain the stack size need for the main thread.
*)
type entry_point_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
entryoff: int [@size 8]; (* uint64_t file __TEXT offset of main *)
uint64_t if not zero , initial stack size
}
let sizeof_entry_point_command = 24 (* bytes *)
(*
* The source_version_command is an optional load command containing
* the version of the sources used to build the binary.
*)
type source_version_command = {
cmd: int [@size 4]; (* LC_SOURCE_VERSION *)
cmdsize: int [@size 4];
A.B.C.D.E packed as a24.b10.c10.d10.e10
}
* The LC_DATA_IN_CODE load commands uses a linkedit_data_command
* to point to an array of data_in_code_entry entries . Each entry
* describes a range of data in a code section .
* The LC_DATA_IN_CODE load commands uses a linkedit_data_command
* to point to an array of data_in_code_entry entries. Each entry
* describes a range of data in a code section.
*)
type data_in_code_entry = {
offset: int [@size 4]; (* from mach_header to start of data range*)
length: int [@size 2]; (* number of bytes in data range *)
kind: int [@size 2]; (* a DICE_KIND_* value *)
}
(* ==================================== *)
(* END Load Commands *)
(* ==================================== *)
(* undefined, or internal commands not in loader.h *)
type unimplemented_command = {
cmd : int ; ( * 4
type unimplemented_command = {
cmd: int; (* 4 *)
4 we 'll just read past the cmdsize and hope that it actually has a cmdsize value ...
}
*)
let kLC_REQ_DYLD = 0x80000000
let kLC_LOAD_WEAK_DYLIB = 0x18 lor kLC_REQ_DYLD
let kLC_RPATH = 0x1c lor kLC_REQ_DYLD
let kLC_REEXPORT_DYLIB = 0x1f lor kLC_REQ_DYLD
let kLC_DYLD_INFO_ONLY = 0x22 lor kLC_REQ_DYLD
let kLC_LOAD_UPWARD_DYLIB = 0x23 lor kLC_REQ_DYLD
let kLC_MAIN = 0x28 lor kLC_REQ_DYLD
exception Bad_load_command of int * string
type cmd =
| LC_SEGMENT
| LC_SYMTAB
| LC_SYMSEG
| LC_THREAD
| LC_UNIXTHREAD
| LC_LOADFVMLIB
| LC_IDFVMLIB
| LC_IDENT
| LC_FVMFILE
| LC_PREPAGE
| LC_DYSYMTAB
| LC_LOAD_DYLIB
| LC_ID_DYLIB
| LC_LOAD_DYLINKER
| LC_ID_DYLINKER
| LC_PREBOUND_DYLIB
| LC_ROUTINES
| LC_SUB_FRAMEWORK
| LC_SUB_UMBRELLA
| LC_SUB_CLIENT
| LC_SUB_LIBRARY
| LC_TWOLEVEL_HINTS
| LC_PREBIND_CKSUM
| LC_LOAD_WEAK_DYLIB
| LC_SEGMENT_64
| LC_ROUTINES_64
| LC_UUID
| LC_RPATH
| LC_CODE_SIGNATURE
| LC_SEGMENT_SPLIT_INFO
| LC_REEXPORT_DYLIB
| LC_LAZY_LOAD_DYLIB
| LC_ENCRYPTION_INFO
| LC_DYLD_INFO
| LC_DYLD_INFO_ONLY
| LC_LOAD_UPWARD_DYLIB
| LC_VERSION_MIN_MACOSX
| LC_VERSION_MIN_IPHONEOS
| LC_FUNCTION_STARTS
| LC_DYLD_ENVIRONMENT
| LC_MAIN
| LC_DATA_IN_CODE
| LC_SOURCE_VERSION
| LC_DYLIB_CODE_SIGN_DRS
| LC_ENCRYPTION_INFO_64
| LC_LINKER_OPTION
| LC_LINKER_OPTIMIZATION_HINT
let cmd_int_to_string =
function
| 0x1 -> "LC_SEGMENT"
| 0x2 -> "LC_SYMTAB"
| 0x3 -> "LC_SYMSEG"
| 0x4 -> "LC_THREAD"
| 0x5 -> "LC_UNIXTHREAD"
| 0x6 -> "LC_LOADFVMLIB"
| 0x7 -> "LC_IDFVMLIB"
| 0x8 -> "LC_IDENT"
| 0x9 -> "LC_FVMFILE"
| 0xa -> "LC_PREPAGE"
| 0xb -> "LC_DYSYMTAB"
| 0xc -> "LC_LOAD_DYLIB"
| 0xd -> "LC_ID_DYLIB"
| 0xe -> "LC_LOAD_DYLINKER"
| 0xf -> "LC_ID_DYLINKER"
| 0x10 -> "LC_PREBOUND_DYLIB"
| 0x11 -> "LC_ROUTINES"
| 0x12 -> "LC_SUB_FRAMEWORK"
| 0x13 -> "LC_SUB_UMBRELLA"
| 0x14 -> "LC_SUB_CLIENT"
| 0x15 -> "LC_SUB_LIBRARY"
| 0x16 -> "LC_TWOLEVEL_HINTS"
| 0x17 -> "LC_PREBIND_CKSUM"
| cmd when cmd = kLC_LOAD_WEAK_DYLIB -> "LC_LOAD_WEAK_DYLIB"
| 0x19 -> "LC_SEGMENT_64"
| 0x1a -> "LC_ROUTINES_64"
| 0x1b -> "LC_UUID"
| cmd when cmd = kLC_RPATH -> "LC_RPATH"
| 0x1d -> "LC_CODE_SIGNATURE"
| 0x1e -> "LC_SEGMENT_SPLIT_INFO"
| cmd when cmd = kLC_REEXPORT_DYLIB -> "LC_REEXPORT_DYLIB"
| 0x20 -> "LC_LAZY_LOAD_DYLIB"
| 0x21 -> "LC_ENCRYPTION_INFO"
| 0x22 -> "LC_DYLD_INFO"
| cmd when cmd = kLC_DYLD_INFO_ONLY -> "LC_DYLD_INFO_ONLY"
| cmd when cmd = kLC_LOAD_UPWARD_DYLIB -> "LC_LOAD_UPWARD_DYLIB"
| 0x24 -> "LC_VERSION_MIN_MACOSX"
| 0x25 -> "LC_VERSION_MIN_IPHONEOS"
| 0x26 -> "LC_FUNCTION_STARTS"
| 0x27 -> "LC_DYLD_ENVIRONMENT"
| cmd when cmd = kLC_MAIN -> "LC_MAIN"
| 0x29 -> "LC_DATA_IN_CODE"
| 0x2A -> "LC_SOURCE_VERSION"
| 0x2B -> "LC_DYLIB_CODE_SIGN_DRS"
| 0x2C -> "LC_ENCRYPTION_INFO_64"
| 0x2D -> "LC_LINKER_OPTION"
| 0x2E -> "LC_LINKER_OPTIMIZATION_HINT"
| cmd -> Printf.sprintf "UKNOWN LOAD COMMAND 0x%x" cmd
let to_cmd =
function
| 0x1 -> LC_SEGMENT
| 0x2 -> LC_SYMTAB
| 0x3 -> LC_SYMSEG
| 0x4 -> LC_THREAD
| 0x5 -> LC_UNIXTHREAD
| 0x6 -> LC_LOADFVMLIB
| 0x7 -> LC_IDFVMLIB
| 0x8 -> LC_IDENT
| 0x9 -> LC_FVMFILE
| 0xa -> LC_PREPAGE
| 0xb -> LC_DYSYMTAB
| 0xc -> LC_LOAD_DYLIB
| 0xd -> LC_ID_DYLIB
| 0xe -> LC_LOAD_DYLINKER
| 0xf -> LC_ID_DYLINKER
| 0x10 -> LC_PREBOUND_DYLIB
| 0x11 -> LC_ROUTINES
| 0x12 -> LC_SUB_FRAMEWORK
| 0x13 -> LC_SUB_UMBRELLA
| 0x14 -> LC_SUB_CLIENT
| 0x15 -> LC_SUB_LIBRARY
| 0x16 -> LC_TWOLEVEL_HINTS
| 0x17 -> LC_PREBIND_CKSUM
| cmd when cmd = kLC_LOAD_WEAK_DYLIB -> LC_LOAD_WEAK_DYLIB
| 0x19 -> LC_SEGMENT_64
| 0x1a -> LC_ROUTINES_64
| 0x1b -> LC_UUID
| cmd when cmd = kLC_RPATH -> LC_RPATH
| 0x1d -> LC_CODE_SIGNATURE
| 0x1e -> LC_SEGMENT_SPLIT_INFO
| cmd when cmd = kLC_REEXPORT_DYLIB -> LC_REEXPORT_DYLIB
| 0x20 -> LC_LAZY_LOAD_DYLIB
| 0x21 -> LC_ENCRYPTION_INFO
| 0x22 -> LC_DYLD_INFO
| cmd when cmd = kLC_DYLD_INFO_ONLY -> LC_DYLD_INFO_ONLY
| cmd when cmd = kLC_LOAD_UPWARD_DYLIB -> LC_LOAD_UPWARD_DYLIB
| 0x24 -> LC_VERSION_MIN_MACOSX
| 0x25 -> LC_VERSION_MIN_IPHONEOS
| 0x26 -> LC_FUNCTION_STARTS
| 0x27 -> LC_DYLD_ENVIRONMENT
| cmd when cmd = kLC_MAIN -> LC_MAIN
| 0x29 -> LC_DATA_IN_CODE
| 0x2A -> LC_SOURCE_VERSION
| 0x2B -> LC_DYLIB_CODE_SIGN_DRS
| 0x2C -> LC_ENCRYPTION_INFO_64
| 0x2D -> LC_LINKER_OPTION
| 0x2E -> LC_LINKER_OPTIMIZATION_HINT
| cmd -> raise @@ Bad_load_command (cmd,(Printf.sprintf "0x%x" cmd))
let cmd_to_int =
function
| LC_SEGMENT -> 0x1
| LC_SYMTAB -> 0x2
| LC_SYMSEG -> 0x3
| LC_THREAD -> 0x4
| LC_UNIXTHREAD -> 0x5
| LC_LOADFVMLIB -> 0x6
| LC_IDFVMLIB -> 0x7
| LC_IDENT -> 0x8
| LC_FVMFILE -> 0x9
| LC_PREPAGE -> 0xa
| LC_DYSYMTAB -> 0xb
| LC_LOAD_DYLIB -> 0xc
| LC_ID_DYLIB -> 0xd
| LC_LOAD_DYLINKER -> 0xe
| LC_ID_DYLINKER -> 0xf
| LC_PREBOUND_DYLIB -> 0x10
| LC_ROUTINES -> 0x11
| LC_SUB_FRAMEWORK -> 0x12
| LC_SUB_UMBRELLA -> 0x13
| LC_SUB_CLIENT -> 0x14
| LC_SUB_LIBRARY -> 0x15
| LC_TWOLEVEL_HINTS -> 0x16
| LC_PREBIND_CKSUM -> 0x17
| LC_LOAD_WEAK_DYLIB -> kLC_LOAD_WEAK_DYLIB
| LC_SEGMENT_64 -> 0x19
| LC_ROUTINES_64 -> 0x1a
| LC_UUID -> 0x1b
| LC_RPATH -> kLC_RPATH
| LC_CODE_SIGNATURE -> 0x1d
| LC_SEGMENT_SPLIT_INFO -> 0x1e
| LC_REEXPORT_DYLIB -> kLC_REEXPORT_DYLIB
| LC_LAZY_LOAD_DYLIB -> 0x20
| LC_ENCRYPTION_INFO -> 0x21
| LC_DYLD_INFO -> 0x22
| LC_DYLD_INFO_ONLY -> kLC_DYLD_INFO_ONLY
| LC_LOAD_UPWARD_DYLIB -> kLC_LOAD_UPWARD_DYLIB
| LC_VERSION_MIN_MACOSX -> 0x24
| LC_VERSION_MIN_IPHONEOS -> 0x25
| LC_FUNCTION_STARTS -> 0x26
| LC_DYLD_ENVIRONMENT -> 0x27
| LC_MAIN -> kLC_MAIN
| LC_DATA_IN_CODE -> 0x29
| LC_SOURCE_VERSION -> 0x2A
| LC_DYLIB_CODE_SIGN_DRS -> 0x2B
| LC_ENCRYPTION_INFO_64 -> 0x2C
| LC_LINKER_OPTION -> 0x2D
| LC_LINKER_OPTIMIZATION_HINT -> 0x2E
let cmd_to_string cmd = cmd_to_int cmd |> cmd_int_to_string
type lc_t =
(* Constants for the cmd field of all load commands, the type *)
| LC_SEGMENT of segment_command
| LC_SYMTAB of symtab_command
| LC_SYMSEG of symseg_command
| LC_THREAD of thread_command
| LC_UNIXTHREAD of thread_command
| LC_LOADFVMLIB of fvmlib_command
| LC_IDFVMLIB of fvmlib_command
| LC_IDENT of ident_command
| LC_FVMFILE of fvmfile_command
| LC_PREPAGE of load_command
| LC_DYSYMTAB of dysymtab_command
| LC_LOAD_DYLIB of dylib_command
| LC_ID_DYLIB of dylib_command
| LC_LOAD_DYLINKER of dylinker_command
| LC_ID_DYLINKER of dylinker_command
| LC_PREBOUND_DYLIB of prebound_dylib_command
| LC_ROUTINES of routines_command
| LC_SUB_FRAMEWORK of sub_framework_command
| LC_SUB_UMBRELLA of sub_umbrella_command
| LC_SUB_CLIENT of sub_client_command
| LC_SUB_LIBRARY of sub_library_command
| LC_TWOLEVEL_HINTS of twolevel_hints_command
| LC_PREBIND_CKSUM of prebind_cksum_command
| LC_LOAD_WEAK_DYLIB of dylib_command
| LC_SEGMENT_64 of segment_command_64
| LC_ROUTINES_64 of routines_command_64
| LC_UUID of uuid_command
| LC_RPATH of rpath_command
| LC_CODE_SIGNATURE of linkedit_data_command
| LC_SEGMENT_SPLIT_INFO of linkedit_data_command
| LC_REEXPORT_DYLIB of dylib_command
| LC_LAZY_LOAD_DYLIB of dylib_command (* not in header file *)
| LC_ENCRYPTION_INFO of encryption_info_command
| LC_DYLD_INFO of dyld_info_command
| LC_DYLD_INFO_ONLY of dyld_info_command
| LC_LOAD_UPWARD_DYLIB of dylib_command (* not in header file *)
| LC_VERSION_MIN_MACOSX of version_min_command
| LC_VERSION_MIN_IPHONEOS of version_min_command
| LC_FUNCTION_STARTS of linkedit_data_command
| LC_DYLD_ENVIRONMENT of dylinker_command
| LC_MAIN of entry_point_command
| LC_DATA_IN_CODE of linkedit_data_command
| LC_SOURCE_VERSION of source_version_command
| LC_DYLIB_CODE_SIGN_DRS of linkedit_data_command
| LC_ENCRYPTION_INFO_64 of encryption_info_command_64
| LC_LINKER_OPTION of linkedit_data_command
| LC_LINKER_OPTIMIZATION_HINT of linkedit_data_command
| LC_UNIMPLEMENTED of load_command
(*
let get cmd f =
match cmd with
| 0x1 -> LC_SEGMENT (* segment of this file to be mapped *)
| 0x2 -> LC_SYMTAB (* link-edit stab symbol table info *)
| 0x3 -> LC_SYMSEG (* link-edit gdb symbol table info (obsolete) *)
| 0x4 -> LC_THREAD (* thread *)
| 0x5 -> LC_UNIXTHREAD (* unix thread (includes a stack) *)
| 0x6 -> LC_LOADFVMLIB (* load a specified fixed VM shared library *)
| 0x7 -> LC_IDFVMLIB (* fixed VM shared library identification *)
| 0x8 -> LC_IDENT (* object identification info (obsolete) *)
| 0x9 -> LC_FVMFILE (* fixed VM file inclusion (internal use) *)
| 0xa -> LC_PREPAGE (* prepage command (internal use) *)
| 0xb -> LC_DYSYMTAB (* dynamic link-edit symbol table info *)
| 0xc -> LC_LOAD_DYLIB (* load a dynamically linked shared library *)
| 0xd -> LC_ID_DYLIB (* dynamically linked shared lib ident *)
| 0xe -> LC_LOAD_DYLINKER (* load a dynamic linker *)
| 0xf -> LC_ID_DYLINKER (* dynamic linker identification *)
| 0x10 -> LC_PREBOUND_DYLIB (* modules prebound for a dynamically *)
(* linked shared library *)
| 0x11 -> LC_ROUTINES (* image routines *)
| 0x12 ->LC_SUB_FRAMEWORK (* sub framework *)
| 0x13 -> LC_SUB_UMBRELLA (* sub umbrella *)
| 0x14 -> LC_SUB_CLIENT (* sub client *)
| 0x15 -> LC_SUB_LIBRARY (* sub library *)
two - level namespace lookup hints
| 0x17 -> LC_PREBIND_CKSUM (* prebind checksum *)
(*
* load a dynamically linked shared library that is allowed to be missing
* (all symbols are weak imported).
*)
| cmd when cmd = kLC_LOAD_WEAK_DYLIB -> LC_LOAD_WEAK_DYLIB
64 - bit segment of this file to be mapped
64 - bit image routines
| 0x1b -> LC_UUID (* the uuid *)
| cmd when cmd = kLC_RPATH -> LC_RPATH (* runpath additions *)
| 0x1d -> LC_CODE_SIGNATURE (* local of code signature *)
| 0x1e -> LC_SEGMENT_SPLIT_INFO (* local of info to split segments *)
| cmd when cmd = kLC_REEXPORT_DYLIB -> LC_REEXPORT_DYLIB (* load and re-export dylib *)
delay load of dylib until first use
| 0x21 -> LC_ENCRYPTION_INFO (* encrypted segment information *)
compressed dyld information
compressed dyld information only
| cmd when cmd = kLC_LOAD_UPWARD_DYLIB -> LC_LOAD_UPWARD_DYLIB (* load upward dylib *)
| 0x24 -> LC_VERSION_MIN_MACOSX (* build for MacOSX min OS version *)
| 0x25 -> LC_VERSION_MIN_IPHONEOS (* build for iPhoneOS min OS version *)
| 0x26 -> LC_FUNCTION_STARTS (* compressed table of function start addresses *)
| 0x27 -> LC_DYLD_ENVIRONMENT (* string for dyld to treat like environment variable *)
replacement for LC_UNIXTHREAD
| 0x29 -> LC_DATA_IN_CODE (* table of non-instructions in __text *)
| 0x2A -> LC_SOURCE_VERSION (* source version used to build binary *)
Code signing DRs copied from linked dylibs
64 - bit encrypted segment information
linker options in MH_OBJECT files
optimization hints in MH_OBJECT files
| cmd -> raise @@ Bad_load_command cmd
*)
type lc = {
4 bytes
4
t: lc_t;
}
| null | https://raw.githubusercontent.com/m4b/rdr/2bf1f73fc317cd74f8c7cacd542889df729bd003/lib/mach/MachLoadCommandTypes.ml | ocaml | ====================================
====================================
NOTE: str is _not_ apart of the lc_str struct, but added for convenience
for 64-bit architectures
name of this section
segment this section goes in
memory address of this section
size in bytes of this section
file offset of this section
file offset of relocation entries
number of relocation entries
flags (section type and attributes)
reserved (for offset or index)
reserved (for count or sizeof)
reserved
bytes
bytes
library's target pathname
library's minor version number
library's header address
* A fixed virtual shared library (filetype == MH_FVMLIB in the mach header)
* contains a fvmlib_command (cmd == LC_IDFVMLIB) to identify the library.
* An object that uses a fixed virtual shared library also contains a
* fvmlib_command (cmd == LC_LOADFVMLIB) for each library it uses.
* (THIS IS OBSOLETE and no longer supported).
includes pathname string
the library identification
library's path name
library's build time stamp
library's current version number
library's compatibility vers number
*
* A dynamically linked shared library (filetype == MH_DYLIB in the mach header)
* contains a dylib_command (cmd == LC_ID_DYLIB) to identify the library.
* An object that uses a dynamically linked shared library also contains a
* dylib_command (cmd == LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, or
* LC_REEXPORT_DYLIB) for each library it uses.
*
library's path name
library's build time stamp
library's current version number
library's compatibility vers number
LC_ID_DYLIB, LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB
includes pathname string
the library identification
bytes
* A dynamically linked shared library may be a subframework of an umbrella
* framework. If so it will be linked with "-umbrella umbrella_name" where
* Where "umbrella_name" is the name of the umbrella framework. A subframework
* can only be linked against by its umbrella framework or other subframeworks
* that are part of the same umbrella framework. Otherwise the static link
* editor produces an error and states to link against the umbrella framework.
* The name of the umbrella framework for subframeworks is recorded in the
* following structure.
includes umbrella string
the umbrella framework name
includes client string
the client name
includes sub_umbrella string
LC_SUB_LIBRARY
LC_PREBOUND_DYLIB
includes strings
library's path name
number of modules in library
bit vector of linked modules
total size of this command
total size of this command
address of initialization routine
index into the module table that the init routine is defined in
total size of this command
address of initialization routine
index to local symbols
number of local symbols
index to externally defined symbols
number of externally defined symbols
index to undefined symbols
number of undefined symbols
file offset to table of contents
number of entries in table of contents
file offset to module table
number of module table entries
offset to referenced symbol table
number of referenced symbol table entries
file offset to the indirect symbol table
number of indirect symbol table entries
offset to external relocation entries
number of external relocation entries
offset to local relocation entries
number of local relocation entries
bytes
TODO: unimplemented
a table of contents entry
the defined external symbol (index into the symbol table)
index into the module table this symbol is defined in
TODO: unimplemented
a module table entry
the module name (index into string table)
index into externally defined symbols
number of externally defined symbols
index into reference symbol table
number of reference symbol table entries
index into symbols for local symbols
number of local symbols
index into external relocation entries
number of external relocation entries
the (__OBJC,__module_info) section
the (__OBJC,__module_info) section
TODO: unimplemented
the module name (index into string table)
index into externally defined symbols
number of externally defined symbols
index into reference symbol table
number of reference symbol table entries
index into symbols for local symbols
number of local symbols
index into external relocation entries
number of external relocation entries
the (__OBJC,__module_info) section
the (__OBJC,__module_info) section
* The entries in the reference symbol table are used when loading the module
* (both by the static and dynamic link editors) and if the module is unloaded
* or replaced. Therefore all external symbols (defined and undefined) are
* listed in the module's reference table. The flags describe the type of
* reference that is being made. The constants for the flags are defined in
* <mach-o/nlist.h> as they are also used for symbol table entries.
TODO: unimplemented, BIT FIELDS
flags to indicate the type of reference
TODO: unimplemented
LC_TWOLEVEL_HINTS
sizeof(struct twolevel_hints_command)
offset to the hint table
number of hints in the hint table
index into the sub images
TODO: unimplemented
LC_PREBIND_CKSUM
sizeof(struct prebind_cksum_command)
LC_UUID
sizeof(struct uuid_command)
* The rpath_command contains a path which at runtime should be added to
* the current run path used to find @rpath prefixed dylibs.
LC_RPATH
includes string
path to add to run path
sizeof(struct linkedit_data_command)
* The encryption_info_command contains the file offset and size of an
* of an encrypted segment.
sizeof(struct encryption_info_command)
file offset of encrypted range
file size of encrypted range
which enryption system, 0 means not-encrypted yet
LC_ENCRYPTION_INFO_64
sizeof(struct encryption_info_command_64)
file offset of encrypted range
file size of encrypted range
which enryption system, 0 means not-encrypted yet
* The version_min_command contains the min OS version on which this
* binary was built to run.
*
* LC_VERSION_MIN_MACOSX or LC_VERSION_MIN_IPHONEOS
bytes
struct dyld_info_command {
uint32_t cmd; (* LC_DYLD_INFO or LC_DYLD_INFO_ONLY
sizeof(struct dyld_info_command)
file offset to rebase info
size of rebase info
file offset to binding info
size of binding info
file offset to weak binding info
size of weak binding info
file offset to lazy binding info
size of lazy binding infs
file offset to lazy binding info
size of lazy binding infs
* The linker_option_command contains linker options embedded in object files.
sizeof(struct symseg_command)
symbol segment offset
symbol segment size in bytes
strings that follow this command
* The fvmfile_command contains a reference to a file to be loaded at the
* specified virtual address. (Presently, this command is reserved for
* internal use. The kernel ignores this command when loading a program into
* memory).
includes pathname string
files pathname
files virtual address
* The entry_point_command is a replacement for thread_command.
* It is used for main executables to specify the location (file offset)
* of main(). If -stack_size was used at link time, the stacksize
* field will contain the stack size need for the main thread.
uint64_t file __TEXT offset of main
bytes
* The source_version_command is an optional load command containing
* the version of the sources used to build the binary.
LC_SOURCE_VERSION
from mach_header to start of data range
number of bytes in data range
a DICE_KIND_* value
====================================
END Load Commands
====================================
undefined, or internal commands not in loader.h
4
Constants for the cmd field of all load commands, the type
not in header file
not in header file
let get cmd f =
match cmd with
| 0x1 -> LC_SEGMENT (* segment of this file to be mapped
link-edit stab symbol table info
link-edit gdb symbol table info (obsolete)
thread
unix thread (includes a stack)
load a specified fixed VM shared library
fixed VM shared library identification
object identification info (obsolete)
fixed VM file inclusion (internal use)
prepage command (internal use)
dynamic link-edit symbol table info
load a dynamically linked shared library
dynamically linked shared lib ident
load a dynamic linker
dynamic linker identification
modules prebound for a dynamically
linked shared library
image routines
sub framework
sub umbrella
sub client
sub library
prebind checksum
* load a dynamically linked shared library that is allowed to be missing
* (all symbols are weak imported).
the uuid
runpath additions
local of code signature
local of info to split segments
load and re-export dylib
encrypted segment information
load upward dylib
build for MacOSX min OS version
build for iPhoneOS min OS version
compressed table of function start addresses
string for dyld to treat like environment variable
table of non-instructions in __text
source version used to build binary | Load Commands from mach - o /
type load_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
}
let sizeof_load_command = 8
type lc_str = {
offset: int [@size 4];
str: string [@computed];
}
let sizeof_lc_str = 4
struct section_64 { ( * for 64 - bit architectures
section alignment ( power of 2 )
};
*)
type section = {
sectname: string [@size 16];
segname: string [@size 16];
addr: int [@size 4];
size: int [@size 4];
offset: int [@size 4];
align: int [@size 4];
reloff: int [@size 4];
nreloc: int [@size 4];
flags: int [@size 4];
reserved1: int [@size 4];
reserved2: int [@size 4];
}
type section_64 = {
sectname: string [@size 16];
segname: string [@size 16];
addr: int [@size 8];
size: int [@size 8];
offset: int [@size 4];
align: int [@size 4];
reloff: int [@size 4];
nreloc: int [@size 4];
flags: int [@size 4];
reserved1: int [@size 4];
reserved2: int [@size 4];
reserved3: int [@size 4];
}
type segment_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
segname: string [@size 16];
vmaddr: int [@size 4];
vmsize: int [@size 4];
fileoff: int [@size 4];
filesize: int [@size 4];
maxprot: int [@size 4];
initprot: int [@size 4];
nsects: int [@size 4];
flags: int [@size 4];
sections: section list [@computed nsects];
}
let sizeof_segment_command_64 = 56
type segment_command_64 = {
cmd: int [@size 4];
cmdsize: int [@size 4];
segname: string [@size 16];
vmaddr: int [@size 8];
vmsize: int [@size 8];
fileoff: int [@size 8];
filesize: int [@size 8];
maxprot: int [@size 4];
initprot: int [@size 4];
nsects: int [@size 4];
flags: int [@size 4];
sections: section_64 list [@computed nsects];
}
let sizeof_segment_command_64 = 72
* Fixed virtual memory shared libraries are identified by two things . The
* target pathname ( the name of the library as found for execution ) , and the
* minor version number . The address of where the headers are loaded is in
* header_addr . ( THIS IS OBSOLETE and no longer supported ) .
* Fixed virtual memory shared libraries are identified by two things. The
* target pathname (the name of the library as found for execution), and the
* minor version number. The address of where the headers are loaded is in
* header_addr. (THIS IS OBSOLETE and no longer supported).
*)
type fvmlib = {
}
let sizeof_fvmlib = 12
type fvmlib_command = {
LC_IDFVMLIB or LC_LOADFVMLIB
}
let sizeof_fvmlib_command = 20
*
* Dynamicly linked shared libraries are identified by two things . The
* pathname ( the name of the library as found for execution ) , and the
* compatibility version number . The pathname must match and the compatibility
* number in the user of the library must be greater than or equal to the
* library being used . The time stamp is used to record the time a library was
* built and copied into user so it can be use to determined if the library used
* at runtime is exactly the same as used to built the program .
*
struct dylib {
union lc_str name ; ( * library 's path name
*
* Dynamicly linked shared libraries are identified by two things. The
* pathname (the name of the library as found for execution), and the
* compatibility version number. The pathname must match and the compatibility
* number in the user of the library must be greater than or equal to the
* library being used. The time stamp is used to record the time a library was
* built and copied into user so it can be use to determined if the library used
* at runtime is exactly the same as used to built the program.
*
struct dylib {
};
*)
type dylib = {
}
let sizeof_dylib = 16
type dylib_command =
{
}
type sub_framework_command = {
LC_SUB_FRAMEWORK
}
let sizeof_sub_framework_command= 12
* For dynamically linked shared libraries that are subframework of an umbrella
* framework they can allow clients other than the umbrella framework or other
* subframeworks in the same umbrella framework . To do this the subframework
* is built with " -allowable_client client_name " and an LC_SUB_CLIENT load
* command is created for each -allowable_client flag . The client_name is
* usually a framework name . It can also be a name used for bundles clients
* where the bundle is built with " -client_name client_name " .
* For dynamically linked shared libraries that are subframework of an umbrella
* framework they can allow clients other than the umbrella framework or other
* subframeworks in the same umbrella framework. To do this the subframework
* is built with "-allowable_client client_name" and an LC_SUB_CLIENT load
* command is created for each -allowable_client flag. The client_name is
* usually a framework name. It can also be a name used for bundles clients
* where the bundle is built with "-client_name client_name".
*)
type sub_client_command = {
LC_SUB_CLIENT
}
let sizeof_sub_client_command = 12
* A dynamically linked shared library may be a sub_umbrella of an umbrella
* framework . If so it will be linked with " -sub_umbrella umbrella_name " where
* Where " umbrella_name " is the name of the sub_umbrella framework . When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* umbrella framework will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks to be implicited linked in . Any other
* dependent dynamic libraries will not be linked it when -twolevel_namespace
* is in effect . The primary library recorded by the static linker when
* resolving a symbol in these libraries will be the umbrella framework .
* Zero or more sub_umbrella frameworks may be use by an umbrella framework .
* The name of a sub_umbrella framework is recorded in the following structure .
* A dynamically linked shared library may be a sub_umbrella of an umbrella
* framework. If so it will be linked with "-sub_umbrella umbrella_name" where
* Where "umbrella_name" is the name of the sub_umbrella framework. When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* umbrella framework will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks to be implicited linked in. Any other
* dependent dynamic libraries will not be linked it when -twolevel_namespace
* is in effect. The primary library recorded by the static linker when
* resolving a symbol in these libraries will be the umbrella framework.
* Zero or more sub_umbrella frameworks may be use by an umbrella framework.
* The name of a sub_umbrella framework is recorded in the following structure.
*)
type sub_umbrella_command = {
LC_SUB_UMBRELLA
the sub_umbrella framework name
}
let sizeof_sub_umbrella_command = 12
* A dynamically linked shared library may be a sub_library of another shared
* library . If so it will be linked with " -sub_library library_name " where
* Where " library_name " is the name of the sub_library shared library . When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* shared library will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks and libraries listed as sub_libraries to
* be implicited linked in . Any other dependent dynamic libraries will not be
* linked it when -twolevel_namespace is in effect . The primary library
* recorded by the static linker when resolving a symbol in these libraries
* will be the umbrella framework ( or dynamic library ) . Zero or more sub_library
* shared libraries may be use by an umbrella framework or ( or dynamic library ) .
* The name of a sub_library framework is recorded in the following structure .
* For example /usr / lib / libobjc_profile . A.dylib would be recorded as " libobjc " .
* A dynamically linked shared library may be a sub_library of another shared
* library. If so it will be linked with "-sub_library library_name" where
* Where "library_name" is the name of the sub_library shared library. When
* staticly linking when -twolevel_namespace is in effect a twolevel namespace
* shared library will only cause its subframeworks and those frameworks
* listed as sub_umbrella frameworks and libraries listed as sub_libraries to
* be implicited linked in. Any other dependent dynamic libraries will not be
* linked it when -twolevel_namespace is in effect. The primary library
* recorded by the static linker when resolving a symbol in these libraries
* will be the umbrella framework (or dynamic library). Zero or more sub_library
* shared libraries may be use by an umbrella framework or (or dynamic library).
* The name of a sub_library framework is recorded in the following structure.
* For example /usr/lib/libobjc_profile.A.dylib would be recorded as "libobjc".
*)
type sub_library_command = {
includes sub_library string
the sub_library name
}
let sizeof_sub_library_command = 12
* A program ( filetype = = MH_EXECUTE ) that is
* prebound to its dynamic libraries has one of these for each library that
* the static linker used in prebinding . It contains a bit vector for the
* modules in the library . The bits indicate which modules are bound ( 1 ) and
* which are not ( 0 ) from the library . The bit for module 0 is the low bit
* of the first byte . So the bit for the Nth module is :
* ( linked_modules[N/8 ] > > N%8 ) & 1
* A program (filetype == MH_EXECUTE) that is
* prebound to its dynamic libraries has one of these for each library that
* the static linker used in prebinding. It contains a bit vector for the
* modules in the library. The bits indicate which modules are bound (1) and
* which are not (0) from the library. The bit for module 0 is the low bit
* of the first byte. So the bit for the Nth module is:
* (linked_modules[N/8] >> N%8) & 1
*)
type prebound_dylib_command = {
}
let sizeof_prebound_dylib_command = 20
type dylinker_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
name: lc_str [@size 4];
}
let sizeof_dylinker_command = 12
* Thread commands contain machine - specific data structures suitable for
* use in the thread state primitives . The machine specific data structures
* follow the struct thread_command as follows .
* Each flavor of machine specific data structure is preceded by an unsigned
* long constant for the flavor of that data structure , an uint32_t
* that is the count of longs of the size of the state data structure and then
* the state data structure follows . This triple may be repeated for many
* flavors . The constants for the flavors , counts and state data structure
* definitions are expected to be in the header file < machine / thread_status.h > .
* These machine specific data structures sizes must be multiples of
* 4 bytes The cmdsize reflects the total size of the thread_command
* and all of the sizes of the constants for the flavors , counts and state
* data structures .
*
* For executable objects that are unix processes there will be one
* thread_command ( cmd = = LC_UNIXTHREAD ) created for it by the link - editor .
* This is the same as a LC_THREAD , except that a stack is automatically
* created ( based on the shell 's limit for the stack size ) . Command arguments
* and environment variables are copied onto that stack .
* Thread commands contain machine-specific data structures suitable for
* use in the thread state primitives. The machine specific data structures
* follow the struct thread_command as follows.
* Each flavor of machine specific data structure is preceded by an unsigned
* long constant for the flavor of that data structure, an uint32_t
* that is the count of longs of the size of the state data structure and then
* the state data structure follows. This triple may be repeated for many
* flavors. The constants for the flavors, counts and state data structure
* definitions are expected to be in the header file <machine/thread_status.h>.
* These machine specific data structures sizes must be multiples of
* 4 bytes The cmdsize reflects the total size of the thread_command
* and all of the sizes of the constants for the flavors, counts and state
* data structures.
*
* For executable objects that are unix processes there will be one
* thread_command (cmd == LC_UNIXTHREAD) created for it by the link-editor.
* This is the same as a LC_THREAD, except that a stack is automatically
* created (based on the shell's limit for the stack size). Command arguments
* and environment variables are copied onto that stack.
*)
unimplemented , see machine / thread_status.h for rest of values :
uint32_t flavor flavor of thread state
uint32_t count count of longs in thread state
struct XXX_thread_state state thread state for this flavor
...
uint32_t flavor flavor of thread state
uint32_t count count of longs in thread state
struct XXX_thread_state state thread state for this flavor
... *)
type thread_command = {
LC_THREAD or LC_UNIXTHREAD
thread_state: MachThread64.t;
}
* The routines command contains the address of the dynamic shared library
* initialization routine and an index into the module table for the module
* that defines the routine . Before any modules are used from the library the
* dynamic linker fully binds the module that defines the initialization routine
* and then calls it . This gets called before any module initialization
* routines ( used for C++ static constructors ) in the library .
* The routines command contains the address of the dynamic shared library
* initialization routine and an index into the module table for the module
* that defines the routine. Before any modules are used from the library the
* dynamic linker fully binds the module that defines the initialization routine
* and then calls it. This gets called before any module initialization
* routines (used for C++ static constructors) in the library.
*)
for 32 - bit architectures
LC_ROUTINES
reserved1: int [@size 4];
reserved2: int [@size 4];
reserved3: int [@size 4];
reserved4: int [@size 4];
reserved5: int [@size 4];
reserved6: int [@size 4];
}
* The 64 - bit routines command . Same use as above .
* The 64-bit routines command. Same use as above.
*)
for 64 - bit architectures
LC_ROUTINES_64
index into the module table that the init routine is defined in 8 bytes each
reserved1: int [@size 8];
reserved2: int [@size 8];
reserved3: int [@size 8];
reserved4: int [@size 8];
reserved5: int [@size 8];
reserved6: int [@size 8];
}
type symtab_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
symoff: int [@size 4];
nsyms: int [@size 4];
stroff: int [@size 4];
strsize: int [@size 4];
}
let sizeof_symtab_command = 24
* This is the second set of the symbolic information which is used to support
* the data structures for the dynamically link editor .
*
* The original set of symbolic information in the symtab_command which contains
* the symbol and string tables must also be present when this load command is
* present . When this load command is present the symbol table is organized
* into three groups of symbols :
* local symbols ( static and debugging symbols ) - grouped by module
* defined external symbols - grouped by module ( sorted by name if not lib )
* undefined external symbols ( sorted by name if MH_BINDATLOAD is not set ,
* and in order the were seen by the static
* linker if MH_BINDATLOAD is set )
* In this load command there are offsets and counts to each of the three groups
* of symbols .
*
* This load command contains a the offsets and sizes of the following new
* symbolic information tables :
* table of contents
* module table
* reference symbol table
* indirect symbol table
* The first three tables above ( the table of contents , module table and
* reference symbol table ) are only present if the file is a dynamically linked
* shared library . For executable and object modules , which are files
* containing only one module , the information that would be in these three
* tables is determined as follows :
* table of contents - the defined external symbols are sorted by name
* module table - the file contains only one module so everything in the
* file is part of the module .
* reference symbol table - is the defined and undefined external symbols
*
* For dynamically linked shared library files this load command also contains
* offsets and sizes to the pool of relocation entries for all sections
* separated into two groups :
* external relocation entries
* local relocation entries
* For executable and object modules the relocation entries continue to hang
* off the section structures .
* This is the second set of the symbolic information which is used to support
* the data structures for the dynamically link editor.
*
* The original set of symbolic information in the symtab_command which contains
* the symbol and string tables must also be present when this load command is
* present. When this load command is present the symbol table is organized
* into three groups of symbols:
* local symbols (static and debugging symbols) - grouped by module
* defined external symbols - grouped by module (sorted by name if not lib)
* undefined external symbols (sorted by name if MH_BINDATLOAD is not set,
* and in order the were seen by the static
* linker if MH_BINDATLOAD is set)
* In this load command there are offsets and counts to each of the three groups
* of symbols.
*
* This load command contains a the offsets and sizes of the following new
* symbolic information tables:
* table of contents
* module table
* reference symbol table
* indirect symbol table
* The first three tables above (the table of contents, module table and
* reference symbol table) are only present if the file is a dynamically linked
* shared library. For executable and object modules, which are files
* containing only one module, the information that would be in these three
* tables is determined as follows:
* table of contents - the defined external symbols are sorted by name
* module table - the file contains only one module so everything in the
* file is part of the module.
* reference symbol table - is the defined and undefined external symbols
*
* For dynamically linked shared library files this load command also contains
* offsets and sizes to the pool of relocation entries for all sections
* separated into two groups:
* external relocation entries
* local relocation entries
* For executable and object modules the relocation entries continue to hang
* off the section structures.
*)
type dysymtab_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
}
type dylib_table_of_contents = {
}
type dylib_module = {
low 16 bits are the index into the init section , high 16 bits are the index into the term section
low 16 bits are the number of init section entries , high 16 bits are the number of term section entries
}
a 64 - bit module table entry
type dylib_module_64 = {
low 16 bits are the index into the init section , high 16 bits are the index into the term section
low 16 bits are the number of init section entries , high 16 bits are the number of term section entries
}
type dylib_reference = {
24 bits bit - field index into the symbol table
}
* The twolevel_hints_command contains the offset and number of hints in the
* two - level namespace lookup hints table .
* The twolevel_hints_command contains the offset and number of hints in the
* two-level namespace lookup hints table.
*)
type twolevel_hints_command = {
}
* The entries in the two - level namespace lookup hints table are twolevel_hint
* structs . These provide hints to the dynamic link editor where to start
* looking for an undefined symbol in a two - level namespace image . The
* isub_image field is an index into the sub - images ( sub - frameworks and
* sub - umbrellas list ) that made up the two - level image that the undefined
* symbol was found in when it was built by the static link editor . If
* isub - image is 0 the the symbol is expected to be defined in library and not
* in the sub - images . If isub - image is non - zero it is an index into the array
* of sub - images for the umbrella with the first index in the sub - images being
* 1 . The array of sub - images is the ordered list of sub - images of the umbrella
* that would be searched for a symbol that has the umbrella recorded as its
* primary library . The table of contents index is an index into the
* library 's table of contents . This is used as the starting point of the
* binary search or a directed linear search .
* The entries in the two-level namespace lookup hints table are twolevel_hint
* structs. These provide hints to the dynamic link editor where to start
* looking for an undefined symbol in a two-level namespace image. The
* isub_image field is an index into the sub-images (sub-frameworks and
* sub-umbrellas list) that made up the two-level image that the undefined
* symbol was found in when it was built by the static link editor. If
* isub-image is 0 the the symbol is expected to be defined in library and not
* in the sub-images. If isub-image is non-zero it is an index into the array
* of sub-images for the umbrella with the first index in the sub-images being
* 1. The array of sub-images is the ordered list of sub-images of the umbrella
* that would be searched for a symbol that has the umbrella recorded as its
* primary library. The table of contents index is an index into the
* library's table of contents. This is used as the starting point of the
* binary search or a directed linear search.
*)
TODO : unimplemented , BITFIELDS
type twolevel_hint = {
24 bit field index into the table of contents
}
* The prebind_cksum_command contains the value of the original check sum for
* prebound files or zero . When a prebound file is first created or modified
* for other than updating its prebinding information the value of the check sum
* is set to zero . When the file has it prebinding re - done and if the value of
* the check sum is zero the original check sum is calculated and stored in
* cksum field of this load command in the output file . If when the prebinding
* is re - done and the cksum field is non - zero it is left unchanged from the
* input file .
* The prebind_cksum_command contains the value of the original check sum for
* prebound files or zero. When a prebound file is first created or modified
* for other than updating its prebinding information the value of the check sum
* is set to zero. When the file has it prebinding re-done and if the value of
* the check sum is zero the original check sum is calculated and stored in
* cksum field of this load command in the output file. If when the prebinding
* is re-done and the cksum field is non-zero it is left unchanged from the
* input file.
*)
type prebind_cksum_command = {
the check sum or zero
}
* The uuid load command contains a single 128 - bit unique random number that
* identifies an object produced by the static link editor .
* The uuid load command contains a single 128-bit unique random number that
* identifies an object produced by the static link editor.
*)
type uuid_command = {
16 bytes the 128 - bit uuid
}
let sizeof_uuid_command = 24
type rpath_command = {
}
let sizeof_rpath_command = 12
* The linkedit_data_command contains the offsets and sizes of a blob
* of data in the _ _ LINKEDIT segment .
* The linkedit_data_command contains the offsets and sizes of a blob
* of data in the __LINKEDIT segment.
*)
type linkedit_data_command = {
LC_CODE_SIGNATURE , , , LC_DATA_IN_CODE , LC_DYLIB_CODE_SIGN_DRS or LC_LINKER_OPTIMIZATION_HINT .
file offset of data in _ _ LINKEDIT segment
file size of data in _ _ LINKEDIT segment
}
let sizeof_linkedit_data_command = 16
type encryption_info_command = {
LC_ENCRYPTION_INFO
}
let sizeof_encryption_info_command = 20
* The encryption_info_command_64 contains the file offset and size of an
* of an encrypted segment ( for use in x86_64 targets ) .
* The encryption_info_command_64 contains the file offset and size of an
* of an encrypted segment (for use in x86_64 targets).
*)
type encryption_info_command_64 = {
padding to make this struct 's size a multiple of 8 bytes
}
let sizeof_encryption_info_command_64 = 24
type version_min_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
X.Y.Z is encoded in nibbles xxxx.yy.zz
X.Y.Z is encoded in nibbles xxxx.yy.zz
}
};
*)
type dyld_info_command =
{
cmd: int [@size 4];
cmdsize: int [@size 4];
rebase_off: int [@size 4];
rebase_size: int [@size 4];
bind_off: int [@size 4];
bind_size: int [@size 4];
weak_bind_off: int [@size 4];
weak_bind_size: int [@size 4];
lazy_bind_off: int [@size 4];
lazy_bind_size: int [@size 4];
export_off: int [@size 4];
export_size: int [@size 4];
}
let sizeof_dylib_info_command = 48
type linker_option_command = {
LC_LINKER_OPTION only used in MH_OBJECT filetypes
cmdsize: int [@size 4];
number of strings concatenation of zero terminated UTF8 strings . Zero filled at end to align
}
let sizeof_linker_option_command = 12
* The symseg_command contains the offset and size of the GNU style
* symbol table information as described in the header file < symseg.h > .
* The symbol roots of the symbol segments must also be aligned properly
* in the file . So the requirement of keeping the offsets aligned to a
* multiple of a 4 bytes translates to the length field of the symbol
* roots also being a multiple of a long . Also the padding must again be
* zeroed . ( THIS IS OBSOLETE and no longer supported ) .
* The symseg_command contains the offset and size of the GNU style
* symbol table information as described in the header file <symseg.h>.
* The symbol roots of the symbol segments must also be aligned properly
* in the file. So the requirement of keeping the offsets aligned to a
* multiple of a 4 bytes translates to the length field of the symbol
* roots also being a multiple of a long. Also the padding must again be
* zeroed. (THIS IS OBSOLETE and no longer supported).
*)
type symseg_command = {
}
let sizeof_symseg_command = 16
* The ident_command contains a free format string table following the
* ident_command structure . The strings are null terminated and the size of
* the command is padded out with zero bytes to a multiple of 4 bytes/
* ( THIS IS OBSOLETE and no longer supported ) .
* The ident_command contains a free format string table following the
* ident_command structure. The strings are null terminated and the size of
* the command is padded out with zero bytes to a multiple of 4 bytes/
* (THIS IS OBSOLETE and no longer supported).
*)
type ident_command = {
LC_IDENT
}
let sizeof_ident_command = 8
type fvmfile_command = {
LC_FVMFILE
}
let sizeof_fvmfile_command = 16
type entry_point_command = {
cmd: int [@size 4];
cmdsize: int [@size 4];
uint64_t if not zero , initial stack size
}
type source_version_command = {
cmdsize: int [@size 4];
A.B.C.D.E packed as a24.b10.c10.d10.e10
}
* The LC_DATA_IN_CODE load commands uses a linkedit_data_command
* to point to an array of data_in_code_entry entries . Each entry
* describes a range of data in a code section .
* The LC_DATA_IN_CODE load commands uses a linkedit_data_command
* to point to an array of data_in_code_entry entries. Each entry
* describes a range of data in a code section.
*)
type data_in_code_entry = {
}
type unimplemented_command = {
cmd : int ; ( * 4
type unimplemented_command = {
4 we 'll just read past the cmdsize and hope that it actually has a cmdsize value ...
}
*)
let kLC_REQ_DYLD = 0x80000000
let kLC_LOAD_WEAK_DYLIB = 0x18 lor kLC_REQ_DYLD
let kLC_RPATH = 0x1c lor kLC_REQ_DYLD
let kLC_REEXPORT_DYLIB = 0x1f lor kLC_REQ_DYLD
let kLC_DYLD_INFO_ONLY = 0x22 lor kLC_REQ_DYLD
let kLC_LOAD_UPWARD_DYLIB = 0x23 lor kLC_REQ_DYLD
let kLC_MAIN = 0x28 lor kLC_REQ_DYLD
exception Bad_load_command of int * string
type cmd =
| LC_SEGMENT
| LC_SYMTAB
| LC_SYMSEG
| LC_THREAD
| LC_UNIXTHREAD
| LC_LOADFVMLIB
| LC_IDFVMLIB
| LC_IDENT
| LC_FVMFILE
| LC_PREPAGE
| LC_DYSYMTAB
| LC_LOAD_DYLIB
| LC_ID_DYLIB
| LC_LOAD_DYLINKER
| LC_ID_DYLINKER
| LC_PREBOUND_DYLIB
| LC_ROUTINES
| LC_SUB_FRAMEWORK
| LC_SUB_UMBRELLA
| LC_SUB_CLIENT
| LC_SUB_LIBRARY
| LC_TWOLEVEL_HINTS
| LC_PREBIND_CKSUM
| LC_LOAD_WEAK_DYLIB
| LC_SEGMENT_64
| LC_ROUTINES_64
| LC_UUID
| LC_RPATH
| LC_CODE_SIGNATURE
| LC_SEGMENT_SPLIT_INFO
| LC_REEXPORT_DYLIB
| LC_LAZY_LOAD_DYLIB
| LC_ENCRYPTION_INFO
| LC_DYLD_INFO
| LC_DYLD_INFO_ONLY
| LC_LOAD_UPWARD_DYLIB
| LC_VERSION_MIN_MACOSX
| LC_VERSION_MIN_IPHONEOS
| LC_FUNCTION_STARTS
| LC_DYLD_ENVIRONMENT
| LC_MAIN
| LC_DATA_IN_CODE
| LC_SOURCE_VERSION
| LC_DYLIB_CODE_SIGN_DRS
| LC_ENCRYPTION_INFO_64
| LC_LINKER_OPTION
| LC_LINKER_OPTIMIZATION_HINT
let cmd_int_to_string =
function
| 0x1 -> "LC_SEGMENT"
| 0x2 -> "LC_SYMTAB"
| 0x3 -> "LC_SYMSEG"
| 0x4 -> "LC_THREAD"
| 0x5 -> "LC_UNIXTHREAD"
| 0x6 -> "LC_LOADFVMLIB"
| 0x7 -> "LC_IDFVMLIB"
| 0x8 -> "LC_IDENT"
| 0x9 -> "LC_FVMFILE"
| 0xa -> "LC_PREPAGE"
| 0xb -> "LC_DYSYMTAB"
| 0xc -> "LC_LOAD_DYLIB"
| 0xd -> "LC_ID_DYLIB"
| 0xe -> "LC_LOAD_DYLINKER"
| 0xf -> "LC_ID_DYLINKER"
| 0x10 -> "LC_PREBOUND_DYLIB"
| 0x11 -> "LC_ROUTINES"
| 0x12 -> "LC_SUB_FRAMEWORK"
| 0x13 -> "LC_SUB_UMBRELLA"
| 0x14 -> "LC_SUB_CLIENT"
| 0x15 -> "LC_SUB_LIBRARY"
| 0x16 -> "LC_TWOLEVEL_HINTS"
| 0x17 -> "LC_PREBIND_CKSUM"
| cmd when cmd = kLC_LOAD_WEAK_DYLIB -> "LC_LOAD_WEAK_DYLIB"
| 0x19 -> "LC_SEGMENT_64"
| 0x1a -> "LC_ROUTINES_64"
| 0x1b -> "LC_UUID"
| cmd when cmd = kLC_RPATH -> "LC_RPATH"
| 0x1d -> "LC_CODE_SIGNATURE"
| 0x1e -> "LC_SEGMENT_SPLIT_INFO"
| cmd when cmd = kLC_REEXPORT_DYLIB -> "LC_REEXPORT_DYLIB"
| 0x20 -> "LC_LAZY_LOAD_DYLIB"
| 0x21 -> "LC_ENCRYPTION_INFO"
| 0x22 -> "LC_DYLD_INFO"
| cmd when cmd = kLC_DYLD_INFO_ONLY -> "LC_DYLD_INFO_ONLY"
| cmd when cmd = kLC_LOAD_UPWARD_DYLIB -> "LC_LOAD_UPWARD_DYLIB"
| 0x24 -> "LC_VERSION_MIN_MACOSX"
| 0x25 -> "LC_VERSION_MIN_IPHONEOS"
| 0x26 -> "LC_FUNCTION_STARTS"
| 0x27 -> "LC_DYLD_ENVIRONMENT"
| cmd when cmd = kLC_MAIN -> "LC_MAIN"
| 0x29 -> "LC_DATA_IN_CODE"
| 0x2A -> "LC_SOURCE_VERSION"
| 0x2B -> "LC_DYLIB_CODE_SIGN_DRS"
| 0x2C -> "LC_ENCRYPTION_INFO_64"
| 0x2D -> "LC_LINKER_OPTION"
| 0x2E -> "LC_LINKER_OPTIMIZATION_HINT"
| cmd -> Printf.sprintf "UKNOWN LOAD COMMAND 0x%x" cmd
let to_cmd =
function
| 0x1 -> LC_SEGMENT
| 0x2 -> LC_SYMTAB
| 0x3 -> LC_SYMSEG
| 0x4 -> LC_THREAD
| 0x5 -> LC_UNIXTHREAD
| 0x6 -> LC_LOADFVMLIB
| 0x7 -> LC_IDFVMLIB
| 0x8 -> LC_IDENT
| 0x9 -> LC_FVMFILE
| 0xa -> LC_PREPAGE
| 0xb -> LC_DYSYMTAB
| 0xc -> LC_LOAD_DYLIB
| 0xd -> LC_ID_DYLIB
| 0xe -> LC_LOAD_DYLINKER
| 0xf -> LC_ID_DYLINKER
| 0x10 -> LC_PREBOUND_DYLIB
| 0x11 -> LC_ROUTINES
| 0x12 -> LC_SUB_FRAMEWORK
| 0x13 -> LC_SUB_UMBRELLA
| 0x14 -> LC_SUB_CLIENT
| 0x15 -> LC_SUB_LIBRARY
| 0x16 -> LC_TWOLEVEL_HINTS
| 0x17 -> LC_PREBIND_CKSUM
| cmd when cmd = kLC_LOAD_WEAK_DYLIB -> LC_LOAD_WEAK_DYLIB
| 0x19 -> LC_SEGMENT_64
| 0x1a -> LC_ROUTINES_64
| 0x1b -> LC_UUID
| cmd when cmd = kLC_RPATH -> LC_RPATH
| 0x1d -> LC_CODE_SIGNATURE
| 0x1e -> LC_SEGMENT_SPLIT_INFO
| cmd when cmd = kLC_REEXPORT_DYLIB -> LC_REEXPORT_DYLIB
| 0x20 -> LC_LAZY_LOAD_DYLIB
| 0x21 -> LC_ENCRYPTION_INFO
| 0x22 -> LC_DYLD_INFO
| cmd when cmd = kLC_DYLD_INFO_ONLY -> LC_DYLD_INFO_ONLY
| cmd when cmd = kLC_LOAD_UPWARD_DYLIB -> LC_LOAD_UPWARD_DYLIB
| 0x24 -> LC_VERSION_MIN_MACOSX
| 0x25 -> LC_VERSION_MIN_IPHONEOS
| 0x26 -> LC_FUNCTION_STARTS
| 0x27 -> LC_DYLD_ENVIRONMENT
| cmd when cmd = kLC_MAIN -> LC_MAIN
| 0x29 -> LC_DATA_IN_CODE
| 0x2A -> LC_SOURCE_VERSION
| 0x2B -> LC_DYLIB_CODE_SIGN_DRS
| 0x2C -> LC_ENCRYPTION_INFO_64
| 0x2D -> LC_LINKER_OPTION
| 0x2E -> LC_LINKER_OPTIMIZATION_HINT
| cmd -> raise @@ Bad_load_command (cmd,(Printf.sprintf "0x%x" cmd))
let cmd_to_int =
function
| LC_SEGMENT -> 0x1
| LC_SYMTAB -> 0x2
| LC_SYMSEG -> 0x3
| LC_THREAD -> 0x4
| LC_UNIXTHREAD -> 0x5
| LC_LOADFVMLIB -> 0x6
| LC_IDFVMLIB -> 0x7
| LC_IDENT -> 0x8
| LC_FVMFILE -> 0x9
| LC_PREPAGE -> 0xa
| LC_DYSYMTAB -> 0xb
| LC_LOAD_DYLIB -> 0xc
| LC_ID_DYLIB -> 0xd
| LC_LOAD_DYLINKER -> 0xe
| LC_ID_DYLINKER -> 0xf
| LC_PREBOUND_DYLIB -> 0x10
| LC_ROUTINES -> 0x11
| LC_SUB_FRAMEWORK -> 0x12
| LC_SUB_UMBRELLA -> 0x13
| LC_SUB_CLIENT -> 0x14
| LC_SUB_LIBRARY -> 0x15
| LC_TWOLEVEL_HINTS -> 0x16
| LC_PREBIND_CKSUM -> 0x17
| LC_LOAD_WEAK_DYLIB -> kLC_LOAD_WEAK_DYLIB
| LC_SEGMENT_64 -> 0x19
| LC_ROUTINES_64 -> 0x1a
| LC_UUID -> 0x1b
| LC_RPATH -> kLC_RPATH
| LC_CODE_SIGNATURE -> 0x1d
| LC_SEGMENT_SPLIT_INFO -> 0x1e
| LC_REEXPORT_DYLIB -> kLC_REEXPORT_DYLIB
| LC_LAZY_LOAD_DYLIB -> 0x20
| LC_ENCRYPTION_INFO -> 0x21
| LC_DYLD_INFO -> 0x22
| LC_DYLD_INFO_ONLY -> kLC_DYLD_INFO_ONLY
| LC_LOAD_UPWARD_DYLIB -> kLC_LOAD_UPWARD_DYLIB
| LC_VERSION_MIN_MACOSX -> 0x24
| LC_VERSION_MIN_IPHONEOS -> 0x25
| LC_FUNCTION_STARTS -> 0x26
| LC_DYLD_ENVIRONMENT -> 0x27
| LC_MAIN -> kLC_MAIN
| LC_DATA_IN_CODE -> 0x29
| LC_SOURCE_VERSION -> 0x2A
| LC_DYLIB_CODE_SIGN_DRS -> 0x2B
| LC_ENCRYPTION_INFO_64 -> 0x2C
| LC_LINKER_OPTION -> 0x2D
| LC_LINKER_OPTIMIZATION_HINT -> 0x2E
let cmd_to_string cmd = cmd_to_int cmd |> cmd_int_to_string
type lc_t =
| LC_SEGMENT of segment_command
| LC_SYMTAB of symtab_command
| LC_SYMSEG of symseg_command
| LC_THREAD of thread_command
| LC_UNIXTHREAD of thread_command
| LC_LOADFVMLIB of fvmlib_command
| LC_IDFVMLIB of fvmlib_command
| LC_IDENT of ident_command
| LC_FVMFILE of fvmfile_command
| LC_PREPAGE of load_command
| LC_DYSYMTAB of dysymtab_command
| LC_LOAD_DYLIB of dylib_command
| LC_ID_DYLIB of dylib_command
| LC_LOAD_DYLINKER of dylinker_command
| LC_ID_DYLINKER of dylinker_command
| LC_PREBOUND_DYLIB of prebound_dylib_command
| LC_ROUTINES of routines_command
| LC_SUB_FRAMEWORK of sub_framework_command
| LC_SUB_UMBRELLA of sub_umbrella_command
| LC_SUB_CLIENT of sub_client_command
| LC_SUB_LIBRARY of sub_library_command
| LC_TWOLEVEL_HINTS of twolevel_hints_command
| LC_PREBIND_CKSUM of prebind_cksum_command
| LC_LOAD_WEAK_DYLIB of dylib_command
| LC_SEGMENT_64 of segment_command_64
| LC_ROUTINES_64 of routines_command_64
| LC_UUID of uuid_command
| LC_RPATH of rpath_command
| LC_CODE_SIGNATURE of linkedit_data_command
| LC_SEGMENT_SPLIT_INFO of linkedit_data_command
| LC_REEXPORT_DYLIB of dylib_command
| LC_ENCRYPTION_INFO of encryption_info_command
| LC_DYLD_INFO of dyld_info_command
| LC_DYLD_INFO_ONLY of dyld_info_command
| LC_VERSION_MIN_MACOSX of version_min_command
| LC_VERSION_MIN_IPHONEOS of version_min_command
| LC_FUNCTION_STARTS of linkedit_data_command
| LC_DYLD_ENVIRONMENT of dylinker_command
| LC_MAIN of entry_point_command
| LC_DATA_IN_CODE of linkedit_data_command
| LC_SOURCE_VERSION of source_version_command
| LC_DYLIB_CODE_SIGN_DRS of linkedit_data_command
| LC_ENCRYPTION_INFO_64 of encryption_info_command_64
| LC_LINKER_OPTION of linkedit_data_command
| LC_LINKER_OPTIMIZATION_HINT of linkedit_data_command
| LC_UNIMPLEMENTED of load_command
two - level namespace lookup hints
| cmd when cmd = kLC_LOAD_WEAK_DYLIB -> LC_LOAD_WEAK_DYLIB
64 - bit segment of this file to be mapped
64 - bit image routines
delay load of dylib until first use
compressed dyld information
compressed dyld information only
replacement for LC_UNIXTHREAD
Code signing DRs copied from linked dylibs
64 - bit encrypted segment information
linker options in MH_OBJECT files
optimization hints in MH_OBJECT files
| cmd -> raise @@ Bad_load_command cmd
*)
type lc = {
4 bytes
4
t: lc_t;
}
|
0fe88c6b602bee982e44382db3312e11812625ef9ae110a4aa77277886b298f9 | wangsix/VMO_repeated_themes_discovery | converter.lisp |
;(in-package :common-lisp-user)
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/csv-files.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/humdrum-by-col.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/midi-save.lisp"))
(setq
*path&name*
(concatenate
'string *music-data-root*
"/beethovenOp2No1Mvt3/polyphonic"))
(setq
csv-destination
(concatenate
'string *path&name* "/csv/sonata01-3.csv"))
(setq
MIDI-destination
(concatenate
'string *path&name* "/midi/sonata01-3.mid"))
(setq
dataset-destination
(concatenate
'string *path&name* "/lisp/sonata01-3.txt"))
(progn
(setq *scale* 1000)
(setq *anacrusis* -1)
(setq
dataset
(humdrum-file2dataset-by-col
(concatenate
'string *path&name* "/kern/sonata01-3.krn")))
(saveit
MIDI-destination
(modify-to-check-dataset dataset *scale*))
(write-to-file
(mapcar
#'(lambda (x)
(append
(list (+ (first x) *anacrusis*))
(rest x)))
dataset)
dataset-destination)
(dataset2csv
dataset-destination csv-destination))
| null | https://raw.githubusercontent.com/wangsix/VMO_repeated_themes_discovery/0082b3c55e64ed447c8b68bcb705fd6da8e3541f/JKUPDD-Aug2013/groundTruth/beethovenOp2No1Mvt3/polyphonic/script/converter.lisp | lisp | (in-package :common-lisp-user) |
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/csv-files.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/humdrum-by-col.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/midi-save.lisp"))
(setq
*path&name*
(concatenate
'string *music-data-root*
"/beethovenOp2No1Mvt3/polyphonic"))
(setq
csv-destination
(concatenate
'string *path&name* "/csv/sonata01-3.csv"))
(setq
MIDI-destination
(concatenate
'string *path&name* "/midi/sonata01-3.mid"))
(setq
dataset-destination
(concatenate
'string *path&name* "/lisp/sonata01-3.txt"))
(progn
(setq *scale* 1000)
(setq *anacrusis* -1)
(setq
dataset
(humdrum-file2dataset-by-col
(concatenate
'string *path&name* "/kern/sonata01-3.krn")))
(saveit
MIDI-destination
(modify-to-check-dataset dataset *scale*))
(write-to-file
(mapcar
#'(lambda (x)
(append
(list (+ (first x) *anacrusis*))
(rest x)))
dataset)
dataset-destination)
(dataset2csv
dataset-destination csv-destination))
|
ae8e06a7486b26b10aebd7d4fd477588ca2c1c470c48954f8d83e528ee06b37c | aryx/ocamltarzan | path.mli | File : path.mli
Copyright ( C ) 2005-
Jane Street Holding , LLC
Author :
email : mmottl\@janestcapital.com
WWW :
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Copyright (C) 2005-
Jane Street Holding, LLC
Author: Markus Mottl
email: mmottl\@janestcapital.com
WWW:
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
WL YM for : Some other functions that would be useful : get_opt , insert_record_field ,
remove_record_field
remove_record_field *)
(** Path: Module for Substitutions within S-expressions *)
(** {6 Types} *)
(** Type of substitution elements *)
type el =
| Pos of int (** [Pos n] denotes [n]th element in a tuple *)
| Match of string * int
(** [Match (tag, n)] denotes [n]th argument of sum matching [tag] *)
| Rec of string (** [Rec name] denotes the record field having [name] *)
(** Type of substitution paths *)
type t = el list
* { 6 High - level functions }
val parse : string -> t
* [ parse str ] @return a substitution path represented by string [ str ] .
Syntax :
" . " - >
separates path elements ; must be present at start of string .
" \[4\ ] " - >
specifies the 4th element in a tuple .
" some_tag\[4\ ] " - >
tries to match [ some_tag ] , then denotes its 4th argument .
" name " - >
denotes record field having [ name ]
Example from test code :
" .t.x . B[1 ] " - > choose record field with name [ t ] , then subfield
[ x ] . Match this value against [ B ] , and denote its first argument .
Syntax:
"." ->
separates path elements; must be present at start of string.
"\[4\]" ->
specifies the 4th element in a tuple.
"some_tag\[4\]" ->
tries to match [some_tag], then denotes its 4th argument.
"name" ->
denotes record field having [name]
Example from test code:
".t.x.B[1]" -> choose record field with name [t], then subfield
[x]. Match this value against [B], and denote its first argument.
*)
val get : ?path : t -> ?str : string -> Sexp.t -> Sexp.t
* [ get ? path ? sexp ] if [ path ] is provided , use it as path .
Otherwise , if [ str ] is provided , parse it as a path . If neither
is provided , assume an empty path . @return the sub - expression from
S - expression [ sexp ] denoted by the path .
Otherwise, if [str] is provided, parse it as a path. If neither
is provided, assume an empty path. @return the sub-expression from
S-expression [sexp] denoted by the path. *)
val replace : ?path : t -> ?str : string -> Sexp.t -> subst : Sexp.t -> Sexp.t
(** [replace ?path ?str sexp ~subst] like [get], but does not extract
a sub-expression but substitutes it with [subst]. @return resulting
S-expression. *)
val replace_no_path : str : string -> Sexp.t -> subst : Sexp.t -> Sexp.t
(** [replace_no_path ~str sexp ~subst] like [replace], but does not take
optional arguments. [str] must be specified. *)
val subst_path : Sexp.t -> t -> (Sexp.t -> Sexp.t) * Sexp.t
(** [subst_path sexp path] @return the tuple [(subst, sub)], where [subst]
is a function that returns an S-expression in which the subexpression
denoted by [path] in [sexp] has been substituted by its argument.
[sub] is the denoted subexpression. Note that [subst sub = sexp]. *)
* { 6 Low - level functions }
val extract_pos : int -> Sexp.t -> (Sexp.t option -> Sexp.t) * Sexp.t
(** [extract_pos n sexp] @return the tuple [(subst, sub)], where [subst]
is a function that returns an S-expression in which the subexpression
denoted at position [n] in [sexp], which must be a list, has been
substituted by [value] if the optional argument is [Some value], or
removes the denoted subexpression if the optional argument is [None].
[sub] is the denoted subexpression. Note that [subst (Some sub) =
sexp]. *)
val extract_match :
string -> int -> Sexp.t -> (Sexp.t option -> Sexp.t) * Sexp.t
(** [extract_match tag n sexp] @return the tuple [(subst, sub)], where
[subst] is a function that returns an S-expression in which the
subexpression denoted by matching [tag] and taking its [n]th argument
in [sexp] has been substituted by [value] if the argument is [Some
value], or removes the denoted subexpression if the optional argument
is [None]. [sub] is the denoted subexpression. Note that [subst
(Some sub) = sexp]. *)
val extract_rec : string -> Sexp.t -> (Sexp.t -> Sexp.t) * Sexp.t
(** [extract_rec name sexp] @return the tuple [(subst, sub)], where
[subst] is a function that returns an S-expression in which the
subexpression denoted by matching field name [name] in [sexp] has
been substituted by its argument. [sub] is the denoted subexpression.
Note that [subst (Some sub) = sexp]. *)
| null | https://raw.githubusercontent.com/aryx/ocamltarzan/4140f5102cee83a2ca7be996ca2d92e9cb035f9c/lib-sexp/path.mli | ocaml | * Path: Module for Substitutions within S-expressions
* {6 Types}
* Type of substitution elements
* [Pos n] denotes [n]th element in a tuple
* [Match (tag, n)] denotes [n]th argument of sum matching [tag]
* [Rec name] denotes the record field having [name]
* Type of substitution paths
* [replace ?path ?str sexp ~subst] like [get], but does not extract
a sub-expression but substitutes it with [subst]. @return resulting
S-expression.
* [replace_no_path ~str sexp ~subst] like [replace], but does not take
optional arguments. [str] must be specified.
* [subst_path sexp path] @return the tuple [(subst, sub)], where [subst]
is a function that returns an S-expression in which the subexpression
denoted by [path] in [sexp] has been substituted by its argument.
[sub] is the denoted subexpression. Note that [subst sub = sexp].
* [extract_pos n sexp] @return the tuple [(subst, sub)], where [subst]
is a function that returns an S-expression in which the subexpression
denoted at position [n] in [sexp], which must be a list, has been
substituted by [value] if the optional argument is [Some value], or
removes the denoted subexpression if the optional argument is [None].
[sub] is the denoted subexpression. Note that [subst (Some sub) =
sexp].
* [extract_match tag n sexp] @return the tuple [(subst, sub)], where
[subst] is a function that returns an S-expression in which the
subexpression denoted by matching [tag] and taking its [n]th argument
in [sexp] has been substituted by [value] if the argument is [Some
value], or removes the denoted subexpression if the optional argument
is [None]. [sub] is the denoted subexpression. Note that [subst
(Some sub) = sexp].
* [extract_rec name sexp] @return the tuple [(subst, sub)], where
[subst] is a function that returns an S-expression in which the
subexpression denoted by matching field name [name] in [sexp] has
been substituted by its argument. [sub] is the denoted subexpression.
Note that [subst (Some sub) = sexp]. | File : path.mli
Copyright ( C ) 2005-
Jane Street Holding , LLC
Author :
email : mmottl\@janestcapital.com
WWW :
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Copyright (C) 2005-
Jane Street Holding, LLC
Author: Markus Mottl
email: mmottl\@janestcapital.com
WWW:
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
WL YM for : Some other functions that would be useful : get_opt , insert_record_field ,
remove_record_field
remove_record_field *)
type el =
| Match of string * int
type t = el list
* { 6 High - level functions }
val parse : string -> t
* [ parse str ] @return a substitution path represented by string [ str ] .
Syntax :
" . " - >
separates path elements ; must be present at start of string .
" \[4\ ] " - >
specifies the 4th element in a tuple .
" some_tag\[4\ ] " - >
tries to match [ some_tag ] , then denotes its 4th argument .
" name " - >
denotes record field having [ name ]
Example from test code :
" .t.x . B[1 ] " - > choose record field with name [ t ] , then subfield
[ x ] . Match this value against [ B ] , and denote its first argument .
Syntax:
"." ->
separates path elements; must be present at start of string.
"\[4\]" ->
specifies the 4th element in a tuple.
"some_tag\[4\]" ->
tries to match [some_tag], then denotes its 4th argument.
"name" ->
denotes record field having [name]
Example from test code:
".t.x.B[1]" -> choose record field with name [t], then subfield
[x]. Match this value against [B], and denote its first argument.
*)
val get : ?path : t -> ?str : string -> Sexp.t -> Sexp.t
* [ get ? path ? sexp ] if [ path ] is provided , use it as path .
Otherwise , if [ str ] is provided , parse it as a path . If neither
is provided , assume an empty path . @return the sub - expression from
S - expression [ sexp ] denoted by the path .
Otherwise, if [str] is provided, parse it as a path. If neither
is provided, assume an empty path. @return the sub-expression from
S-expression [sexp] denoted by the path. *)
val replace : ?path : t -> ?str : string -> Sexp.t -> subst : Sexp.t -> Sexp.t
val replace_no_path : str : string -> Sexp.t -> subst : Sexp.t -> Sexp.t
val subst_path : Sexp.t -> t -> (Sexp.t -> Sexp.t) * Sexp.t
* { 6 Low - level functions }
val extract_pos : int -> Sexp.t -> (Sexp.t option -> Sexp.t) * Sexp.t
val extract_match :
string -> int -> Sexp.t -> (Sexp.t option -> Sexp.t) * Sexp.t
val extract_rec : string -> Sexp.t -> (Sexp.t -> Sexp.t) * Sexp.t
|
3c7416772af98b31266386429bd5d4edc30a01c939b2daed70031c07a948927a | johnridesabike/acutis | data.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2022 .
(* *)
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 /.
(* *)
(**************************************************************************)
open Acutis
open Js_of_ocaml
module Ty = Typescheme
module EPath = Error.DecodePath
type 'a map = 'a Stdlib.Map.Make(String).t
type t = Js.Unsafe.any
let stringify (j : t) =
match Js.to_string (Js.typeof j) with
| "undefined" -> "undefined"
| _ -> Js._JSON##stringify j |> Js.to_string
let pp ppf j = Format.pp_print_string ppf (stringify j)
let decode_error = Error.decode pp
module Table : sig
* When we convert JavaScript objects into Acutis records , we can not convert
every value at once , e.g. by mapping the result of [ Js.object_keys ] .
JavaScript objects may use getter functions for accessing values , and
those can cause side - effects .
By only accessing the precise values that we need , we avoid triggering
unexpected behavior .
every value at once, e.g. by mapping the result of [Js.object_keys].
JavaScript objects may use getter functions for accessing values, and
those can cause side-effects.
By only accessing the precise values that we need, we avoid triggering
unexpected behavior. *)
type t
val unsafe_of_js : Js.Unsafe.any -> t
val find_exn : string -> t -> Js.Unsafe.any
val find_opt : string -> t -> Js.Unsafe.any option
val fold : (string -> Js.Unsafe.any -> 'a -> 'a) -> t -> 'a -> 'a
end = struct
type t = Js.Unsafe.any
let unsafe_of_js j = j
let get : t -> Js.js_string Js.t -> Js.Unsafe.any Js.Optdef.t = Js.Unsafe.get
let unsafe_get : t -> Js.js_string Js.t -> Js.Unsafe.any = Js.Unsafe.get
let find_exn k m =
let r = get m (Js.string k) in
Js.Optdef.get r (fun () -> raise Not_found)
let find_opt k m = get m (Js.string k) |> Js.Optdef.to_option
let fold f m init =
Js.object_keys m |> Js.to_array
|> Array.fold_left
(fun init k -> f (Js.to_string k) (unsafe_get m k) init)
init
end
type tagged =
| Js_null
| Js_bool of bool
| Js_string of string
| Js_float of float
| Js_object of Table.t
| Js_array of t array
let classify j =
match Js.to_string (Js.typeof j) with
| "string" -> Js_string (Js.Unsafe.coerce j |> Js.to_string)
| "number" -> Js_float (Js.Unsafe.coerce j |> Js.float_of_number)
| "boolean" -> Js_bool (Js.Unsafe.coerce j |> Js.to_bool)
| "undefined" -> Js_null
| _ -> (
match Js.Opt.to_option (Js.some j) with
| None -> Js_null
| Some j ->
if Js.instanceof j Js.array_empty then
Js_array (Js.Unsafe.coerce j |> Js.to_array)
else Js_object (Table.unsafe_of_js j))
let boolean ty path cases j =
match classify j with
| Js_bool b ->
let i = match b with false -> 0 | true -> 1 in
if Set.Int.mem i cases then Data.bool i else Error.bad_enum pp ty path j
| _ -> decode_error ty path j
let string ty path cases j =
match classify j with
| Js_string s -> (
match cases with
| None -> Data.string s
| Some cases ->
if Set.String.mem s cases then Data.string s
else Error.bad_enum pp ty path j)
| _ -> decode_error ty path j
let int ty path cases j =
match classify j with
| Js_float f -> (
let i = int_of_float f in
match cases with
| None -> Data.int i
| Some cases ->
if Set.Int.mem i cases then Data.int i
else Error.bad_enum pp ty path j)
| _ -> decode_error ty path j
let float path j =
match classify j with
| Js_float f -> Data.float f
| _ -> decode_error (Ty.float ()) path j
let rec nullable path ty j =
match classify j with
| Js_null -> Data.null
| _ -> Data.some (make (EPath.nullable path) ty j)
and list path ty j =
match classify j with
| Js_array a ->
let len = Array.length a in
let l = ref Data.list_empty in
for i = 0 to len - 1 do
let x = Array.unsafe_get a i in
l := Data.list_cons (make (EPath.index i path) ty x) !l
done;
Data.list_rev !l
| _ -> decode_error (Ty.list ty) path j
and dict path ty j =
match classify j with
| Js_object o ->
Table.fold
(fun k v map -> Map.String.add k (make (EPath.key k path) ty v) map)
o Map.String.empty
|> Data.dict
| _ -> decode_error (Ty.dict ty) path j
and tuple ty path tys j =
match classify j with
| Js_array a ->
let tys = Array.of_list tys in
if Array.length a = Array.length tys then
Array.map2 (fun ty x -> (ty, x)) tys a
|> Array.mapi (fun i (ty, x) -> make (EPath.index i path) ty x)
|> Data.tuple
else decode_error ty path j
| _ -> decode_error ty path j
and record_aux path tys j =
Map.String.mapi
(fun k ty ->
match (ty, Table.find_opt k j) with
| { contents = Ty.Nullable _ | Unknown _ }, None -> Data.null
| ty, Some j -> make (EPath.key k path) ty j
| _ -> Error.missing_key path (Ty.internal_record (ref tys)) k)
tys
and record path tys j =
match classify j with
| Js_object o -> record_aux path !tys o |> Data.dict
| _ -> decode_error (Ty.internal_record tys) path j
and union path ty key Ty.Variant.{ cases; extra; _ } j =
match classify j with
| Js_object o ->
let tag, tys =
try
let tag = Table.find_exn key o in
match (classify tag, cases, extra) with
| Js_bool false, VInt map, Bool ->
let tag = 0 in
(Data.bool tag, Map.Int.find tag map)
| Js_bool true, VInt map, Bool ->
let tag = 1 in
(Data.bool tag, Map.Int.find tag map)
| Js_float tag, VInt map, Not_bool ->
let tag = int_of_float tag in
(Data.int tag, Map.Int.find tag map)
| Js_string tag, VString map, Not_bool ->
(Data.string tag, Map.String.find tag map)
| _ -> raise Not_found
with Not_found -> decode_error ty path j
in
let r = record_aux path !tys o in
Data.dict (Map.String.add key tag r)
| _ -> decode_error ty path j
and make path ty j =
match !ty with
| Ty.Unknown _ -> Data.other j
| Nullable ty -> nullable path ty j
| Enum { extra = Bool; cases = VInt cases; _ } -> boolean ty path cases j
| String | Enum { row = `Open; cases = VString _; _ } -> string ty path None j
| Enum { row = `Closed; cases = VString cases; _ } ->
string ty path (Some cases) j
| Int | Enum { row = `Open; cases = VInt _; _ } -> int ty path None j
| Enum { row = `Closed; cases = VInt cases; _ } -> int ty path (Some cases) j
| Float -> float path j
| List ty -> list path ty j
| Dict (ty, _) -> dict path ty j
| Tuple tys -> tuple ty path tys j
| Record tys -> record path tys j
| Union (key, variant) -> union path ty key variant j
let decode ~name tys j =
let path = EPath.make name in
match classify j with
| Js_object o -> record_aux path tys o
| _ -> decode_error (Ty.internal_record (ref tys)) path j
let coerce = Js.Unsafe.coerce
let rec record_to_js ty t =
Map.String.merge
(fun _ ty t ->
match (ty, t) with Some ty, Some t -> Some (to_js ty t) | _ -> None)
ty t
|> Map.String.bindings
and to_js ty t =
match (!ty, t) with
| _, Data.Other j -> j
| _, Const (Float f) -> Js.number_of_float f |> coerce
| _, Const (String s) -> Js.string s |> coerce
| Ty.Enum { extra = Bool; _ }, Const (Int 0) -> coerce Js._false
| Ty.Enum { extra = Bool; _ }, Const (Int _) -> coerce Js._true
| (Enum _ | Int), Const (Int i) ->
float_of_int i |> Js.number_of_float |> coerce
| Nullable _, Nil -> Js.Unsafe.inject Js.null
| Nullable ty, Array [| t |] -> to_js ty t
| List ty, t ->
let rec aux acc = function
| Data.Nil -> List.rev acc |> Array.of_list |> Js.array |> coerce
| Array [| hd; tl |] -> aux (to_js ty hd :: acc) tl
| _ -> Error.internal __POS__ "Lists may only contain Array or Nil."
in
aux [] t
| Tuple tys, Array a ->
Array.map2 to_js (Array.of_list tys) a |> Js.array |> coerce
| Dict (ty, _), Dict m ->
Map.String.map (to_js ty) m
|> Map.String.to_seq |> Array.of_seq |> Js.Unsafe.obj
| Record tys, Dict m -> record_to_js !tys m |> Array.of_list |> Js.Unsafe.obj
| Union (k, { cases; extra; _ }), Dict m ->
let tag = Map.String.find k m in
let record_tys =
match (cases, tag) with
| VInt m, Const (Int i) -> Map.Int.find i m
| VString m, Const (String s) -> Map.String.find s m
| _ -> Error.internal __POS__ "Type mismatch while encoding a union."
in
let tag =
match tag with
| Const (String s) -> coerce @@ Js.string s
| Const (Int i) -> (
match (extra, i) with
| Bool, 0 -> coerce Js._false
| Bool, _ -> coerce Js._true
| Not_bool, i -> float_of_int i |> Js.number_of_float |> coerce)
| _ -> Error.internal __POS__ "Union tags may only be ints or strings."
in
let l = record_to_js !record_tys m in
(k, tag) :: l |> Array.of_list |> Js.Unsafe.obj
| _ -> Error.internal __POS__ "Type mismatch while encoding data."
let encode tys j = record_to_js tys j |> Array.of_list |> Js.Unsafe.obj
| null | https://raw.githubusercontent.com/johnridesabike/acutis/aafe2b8479c25a16e382621654430f87a2aa8cd7/lib/data-js/data.ml | ocaml | ************************************************************************
************************************************************************ | Copyright ( c ) 2022 .
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 /.
open Acutis
open Js_of_ocaml
module Ty = Typescheme
module EPath = Error.DecodePath
type 'a map = 'a Stdlib.Map.Make(String).t
type t = Js.Unsafe.any
let stringify (j : t) =
match Js.to_string (Js.typeof j) with
| "undefined" -> "undefined"
| _ -> Js._JSON##stringify j |> Js.to_string
let pp ppf j = Format.pp_print_string ppf (stringify j)
let decode_error = Error.decode pp
module Table : sig
* When we convert JavaScript objects into Acutis records , we can not convert
every value at once , e.g. by mapping the result of [ Js.object_keys ] .
JavaScript objects may use getter functions for accessing values , and
those can cause side - effects .
By only accessing the precise values that we need , we avoid triggering
unexpected behavior .
every value at once, e.g. by mapping the result of [Js.object_keys].
JavaScript objects may use getter functions for accessing values, and
those can cause side-effects.
By only accessing the precise values that we need, we avoid triggering
unexpected behavior. *)
type t
val unsafe_of_js : Js.Unsafe.any -> t
val find_exn : string -> t -> Js.Unsafe.any
val find_opt : string -> t -> Js.Unsafe.any option
val fold : (string -> Js.Unsafe.any -> 'a -> 'a) -> t -> 'a -> 'a
end = struct
type t = Js.Unsafe.any
let unsafe_of_js j = j
let get : t -> Js.js_string Js.t -> Js.Unsafe.any Js.Optdef.t = Js.Unsafe.get
let unsafe_get : t -> Js.js_string Js.t -> Js.Unsafe.any = Js.Unsafe.get
let find_exn k m =
let r = get m (Js.string k) in
Js.Optdef.get r (fun () -> raise Not_found)
let find_opt k m = get m (Js.string k) |> Js.Optdef.to_option
let fold f m init =
Js.object_keys m |> Js.to_array
|> Array.fold_left
(fun init k -> f (Js.to_string k) (unsafe_get m k) init)
init
end
type tagged =
| Js_null
| Js_bool of bool
| Js_string of string
| Js_float of float
| Js_object of Table.t
| Js_array of t array
let classify j =
match Js.to_string (Js.typeof j) with
| "string" -> Js_string (Js.Unsafe.coerce j |> Js.to_string)
| "number" -> Js_float (Js.Unsafe.coerce j |> Js.float_of_number)
| "boolean" -> Js_bool (Js.Unsafe.coerce j |> Js.to_bool)
| "undefined" -> Js_null
| _ -> (
match Js.Opt.to_option (Js.some j) with
| None -> Js_null
| Some j ->
if Js.instanceof j Js.array_empty then
Js_array (Js.Unsafe.coerce j |> Js.to_array)
else Js_object (Table.unsafe_of_js j))
let boolean ty path cases j =
match classify j with
| Js_bool b ->
let i = match b with false -> 0 | true -> 1 in
if Set.Int.mem i cases then Data.bool i else Error.bad_enum pp ty path j
| _ -> decode_error ty path j
let string ty path cases j =
match classify j with
| Js_string s -> (
match cases with
| None -> Data.string s
| Some cases ->
if Set.String.mem s cases then Data.string s
else Error.bad_enum pp ty path j)
| _ -> decode_error ty path j
let int ty path cases j =
match classify j with
| Js_float f -> (
let i = int_of_float f in
match cases with
| None -> Data.int i
| Some cases ->
if Set.Int.mem i cases then Data.int i
else Error.bad_enum pp ty path j)
| _ -> decode_error ty path j
let float path j =
match classify j with
| Js_float f -> Data.float f
| _ -> decode_error (Ty.float ()) path j
let rec nullable path ty j =
match classify j with
| Js_null -> Data.null
| _ -> Data.some (make (EPath.nullable path) ty j)
and list path ty j =
match classify j with
| Js_array a ->
let len = Array.length a in
let l = ref Data.list_empty in
for i = 0 to len - 1 do
let x = Array.unsafe_get a i in
l := Data.list_cons (make (EPath.index i path) ty x) !l
done;
Data.list_rev !l
| _ -> decode_error (Ty.list ty) path j
and dict path ty j =
match classify j with
| Js_object o ->
Table.fold
(fun k v map -> Map.String.add k (make (EPath.key k path) ty v) map)
o Map.String.empty
|> Data.dict
| _ -> decode_error (Ty.dict ty) path j
and tuple ty path tys j =
match classify j with
| Js_array a ->
let tys = Array.of_list tys in
if Array.length a = Array.length tys then
Array.map2 (fun ty x -> (ty, x)) tys a
|> Array.mapi (fun i (ty, x) -> make (EPath.index i path) ty x)
|> Data.tuple
else decode_error ty path j
| _ -> decode_error ty path j
and record_aux path tys j =
Map.String.mapi
(fun k ty ->
match (ty, Table.find_opt k j) with
| { contents = Ty.Nullable _ | Unknown _ }, None -> Data.null
| ty, Some j -> make (EPath.key k path) ty j
| _ -> Error.missing_key path (Ty.internal_record (ref tys)) k)
tys
and record path tys j =
match classify j with
| Js_object o -> record_aux path !tys o |> Data.dict
| _ -> decode_error (Ty.internal_record tys) path j
and union path ty key Ty.Variant.{ cases; extra; _ } j =
match classify j with
| Js_object o ->
let tag, tys =
try
let tag = Table.find_exn key o in
match (classify tag, cases, extra) with
| Js_bool false, VInt map, Bool ->
let tag = 0 in
(Data.bool tag, Map.Int.find tag map)
| Js_bool true, VInt map, Bool ->
let tag = 1 in
(Data.bool tag, Map.Int.find tag map)
| Js_float tag, VInt map, Not_bool ->
let tag = int_of_float tag in
(Data.int tag, Map.Int.find tag map)
| Js_string tag, VString map, Not_bool ->
(Data.string tag, Map.String.find tag map)
| _ -> raise Not_found
with Not_found -> decode_error ty path j
in
let r = record_aux path !tys o in
Data.dict (Map.String.add key tag r)
| _ -> decode_error ty path j
and make path ty j =
match !ty with
| Ty.Unknown _ -> Data.other j
| Nullable ty -> nullable path ty j
| Enum { extra = Bool; cases = VInt cases; _ } -> boolean ty path cases j
| String | Enum { row = `Open; cases = VString _; _ } -> string ty path None j
| Enum { row = `Closed; cases = VString cases; _ } ->
string ty path (Some cases) j
| Int | Enum { row = `Open; cases = VInt _; _ } -> int ty path None j
| Enum { row = `Closed; cases = VInt cases; _ } -> int ty path (Some cases) j
| Float -> float path j
| List ty -> list path ty j
| Dict (ty, _) -> dict path ty j
| Tuple tys -> tuple ty path tys j
| Record tys -> record path tys j
| Union (key, variant) -> union path ty key variant j
let decode ~name tys j =
let path = EPath.make name in
match classify j with
| Js_object o -> record_aux path tys o
| _ -> decode_error (Ty.internal_record (ref tys)) path j
let coerce = Js.Unsafe.coerce
let rec record_to_js ty t =
Map.String.merge
(fun _ ty t ->
match (ty, t) with Some ty, Some t -> Some (to_js ty t) | _ -> None)
ty t
|> Map.String.bindings
and to_js ty t =
match (!ty, t) with
| _, Data.Other j -> j
| _, Const (Float f) -> Js.number_of_float f |> coerce
| _, Const (String s) -> Js.string s |> coerce
| Ty.Enum { extra = Bool; _ }, Const (Int 0) -> coerce Js._false
| Ty.Enum { extra = Bool; _ }, Const (Int _) -> coerce Js._true
| (Enum _ | Int), Const (Int i) ->
float_of_int i |> Js.number_of_float |> coerce
| Nullable _, Nil -> Js.Unsafe.inject Js.null
| Nullable ty, Array [| t |] -> to_js ty t
| List ty, t ->
let rec aux acc = function
| Data.Nil -> List.rev acc |> Array.of_list |> Js.array |> coerce
| Array [| hd; tl |] -> aux (to_js ty hd :: acc) tl
| _ -> Error.internal __POS__ "Lists may only contain Array or Nil."
in
aux [] t
| Tuple tys, Array a ->
Array.map2 to_js (Array.of_list tys) a |> Js.array |> coerce
| Dict (ty, _), Dict m ->
Map.String.map (to_js ty) m
|> Map.String.to_seq |> Array.of_seq |> Js.Unsafe.obj
| Record tys, Dict m -> record_to_js !tys m |> Array.of_list |> Js.Unsafe.obj
| Union (k, { cases; extra; _ }), Dict m ->
let tag = Map.String.find k m in
let record_tys =
match (cases, tag) with
| VInt m, Const (Int i) -> Map.Int.find i m
| VString m, Const (String s) -> Map.String.find s m
| _ -> Error.internal __POS__ "Type mismatch while encoding a union."
in
let tag =
match tag with
| Const (String s) -> coerce @@ Js.string s
| Const (Int i) -> (
match (extra, i) with
| Bool, 0 -> coerce Js._false
| Bool, _ -> coerce Js._true
| Not_bool, i -> float_of_int i |> Js.number_of_float |> coerce)
| _ -> Error.internal __POS__ "Union tags may only be ints or strings."
in
let l = record_to_js !record_tys m in
(k, tag) :: l |> Array.of_list |> Js.Unsafe.obj
| _ -> Error.internal __POS__ "Type mismatch while encoding data."
let encode tys j = record_to_js tys j |> Array.of_list |> Js.Unsafe.obj
|
5b5e665ddcfc2d4b38b15b674cb71bd7d4292552c821b14a3097f03fcac021bb | clojure-liberator/liberator | core.clj | (ns liberator.core
(:require [liberator.conneg :as conneg]
[liberator.representation :refer
[Representation as-response ring-response]]
[liberator.util :refer
[as-date http-date parse-http-date
combine make-function is-protocol-exception?]]
[clojure.string :refer [join upper-case]])
(:import (clojure.lang ExceptionInfo)))
(defmulti coll-validator
"Return a function that evaluaties if the give argument
a) is contained in a collection
b) equals an argument
c) when applied to a function evaluates as true"
(fn [x] (cond
(coll? x) :col
(fn? x) :fn)))
(defmethod coll-validator :col [xs]
(fn [x] (some #{x} xs)))
(defmethod coll-validator :fn [f]
f)
(defmethod coll-validator :default [x]
(partial = x))
(defn console-logger [category values]
#(apply println "LOG " category " " values))
(def ^:dynamic *loggers* nil)
(defmacro with-logger [logger & body]
`(binding [*loggers* (conj (or *loggers* []) ~logger)]
~@body))
(defmacro with-console-logger [& body]
`(with-logger console-logger
~@body))
(defn atom-logger [atom]
(fn [& args]
(swap! atom conj args)))
(defn log! [category & values]
(doseq [l *loggers*]
(l category values)))
(declare if-none-match-exists?)
(defn map-values [f m]
(persistent! (reduce-kv (fn [out-m k v] (assoc! out-m k (f v))) (transient {}) m)))
(defn request-method-in [& methods]
#(some #{(:request-method (:request %))} methods))
(defn gen-etag [context]
(if-let [f (get-in context [:resource :etag])]
(if-let [etag-val (f context)]
(format "\"%s\"" etag-val))))
(defn ^java.util.Date gen-last-modified [context]
(if-let [f (get-in context [:resource :last-modified])]
(if-let [lm-val (f context)]
(as-date lm-val))))
(defn update-context [context context-update]
(cond
(map? context-update) (combine context context-update)
(fn? context-update) (context-update)
:otherwise context))
(declare handle-exception)
(defn decide [name test then else {:keys [resource request] :as context}]
(if (or test
(contains? resource name))
(try
(let [ftest (or (resource name) test)
ftest (make-function ftest)
fthen (make-function then)
felse (make-function else)
decision (ftest context)
result (if (vector? decision) (first decision) decision)
context-update (if (vector? decision) (second decision) decision)
context (update-context context context-update)]
(log! :decision name decision)
((if result fthen felse) context))
(catch Exception e
(handle-exception (assoc context :exception e))))
{:status 500 :body (str "No handler found for key \"" name "\"."
" Keys defined for resource are " (keys resource))}))
(defn defdecision*
[name test then else]
`(defn ~name [~'context]
(decide ~(keyword name) ~test ~then ~else ~'context)))
(defmacro defdecision
([name then else]
(defdecision* name nil then else))
([name test then else]
(defdecision* name test then else)))
(defmacro defaction [name next]
`(defdecision ~name ~next ~next))
(defn set-header-maybe [headers name value]
(if-not (empty? value)
(assoc headers name value)
headers))
(defn build-vary-header [{:keys [media-type charset language encoding] :as representation}]
(->> [(when-not (empty? media-type) "Accept")
(when-not (empty? charset) "Accept-Charset")
(when-not (empty? language) "Accept-Language")
(when-not (or (empty? encoding) (= "identity" encoding)) "Accept-Encoding")]
(remove nil?)
(interpose ", ")
(apply str)))
(defn build-allow-header [resource]
(join ", " (map (comp upper-case name) ((:allowed-methods resource)))))
(defn build-options-headers [resource]
(merge {"Allow" (build-allow-header resource)}
(if (some #{:patch} ((:allowed-methods resource)))
{"Accept-Patch" (join "," ((:patch-content-types resource)))}
{})))
(defn run-handler [name status message
{:keys [resource request representation] :as context}]
(let [context
(merge {:status status :message message} context)
response
(merge-with
combine
;; Status
{:status (:status context)}
ETags
(when-let [etag (gen-etag context)]
{:headers {"ETag" etag}})
;; Last modified
(when-let [last-modified (gen-last-modified context)]
{:headers {"Last-Modified" (http-date last-modified)}})
201 created required a location header to be send
(when (#{201 301 303 307} (:status context))
(if-let [f (or (get context :location)
(get resource :location))]
{:headers {"Location" (str ((make-function f) context))}}))
(do
(log! :handler (keyword name))
Content negotiations
(merge-with
merge
{:headers
(-> {}
(set-header-maybe "Content-Type"
(str (:media-type representation)
(when-let [charset (:charset representation)]
(str ";charset=" charset))))
(set-header-maybe "Content-Language" (:language representation))
(set-header-maybe "Content-Encoding"
(let [e (:encoding representation)]
(if-not (= "identity" e) e)))
(set-header-maybe "Vary" (build-vary-header representation)))}
;; Finally the result of the handler. We allow the handler to
;; override the status and headers.
(when-let [result (if-let [handler (get resource (keyword name))]
(handler context)
(get context :message))]
(let [as-response (:as-response resource)]
(as-response result context))))))]
(cond
(or (= :options (:request-method request)) (= 405 (:status response)))
(merge-with combine
{:headers (build-options-headers resource)}
response)
(= :head (:request-method request))
(dissoc response :body)
:else response)))
(defmacro ^:private defhandler [name status message]
`(defn ~name [context#]
(run-handler '~name ~status ~message context#)))
(defn header-exists? [header context]
(get-in context [:request :headers header]))
(defn if-match-star [context]
(= "*" (get-in context [:request :headers "if-match"])))
(defn =method [method context]
(= (get-in context [:request :request-method]) method))
(defmulti to-location type)
(defmethod to-location String [uri] (ring-response {:headers {"Location" uri}}))
(defmethod to-location clojure.lang.APersistentMap [this] this)
(defmethod to-location java.net.URI [^java.net.URI uri] (to-location (.toString uri)))
(defmethod to-location java.net.URL [^java.net.URL url] (to-location (.toString url)))
(defmethod to-location nil [this] this)
(defn- handle-moved [{resource :resource :as context}]
(if-let [f (or (get context :location)
(get resource :location))]
(to-location ((make-function f) context))
{:status 500
:body (format "Internal Server error: no location specified for status %s" (:status context))}))
;; Provide :see-other which returns a location or override :handle-see-other
(defhandler handle-see-other 303 nil)
(defhandler handle-ok 200 "OK")
(defhandler handle-no-content 204 nil)
(defhandler handle-multiple-representations 300 nil) ; nil body because the body is reserved to reveal the actual representations available.
(defhandler handle-accepted 202 "Accepted")
(defdecision multiple-representations? handle-multiple-representations handle-ok)
(defdecision respond-with-entity? multiple-representations? handle-no-content)
(defhandler handle-created 201 nil)
(defdecision new? handle-created respond-with-entity?)
(defdecision post-redirect? handle-see-other new?)
(defdecision post-enacted? post-redirect? handle-accepted)
(defdecision put-enacted? new? handle-accepted)
(defhandler handle-not-found 404 "Resource not found.")
(defhandler handle-gone 410 "Resource is gone.")
(defaction post! post-enacted?)
(defdecision can-post-to-missing? post! handle-not-found)
(defdecision post-to-missing? (partial =method :post)
can-post-to-missing? handle-not-found)
(defhandler handle-moved-permanently 301 nil)
(defhandler handle-moved-temporarily 307 nil)
(defdecision can-post-to-gone? post! handle-gone)
(defdecision post-to-gone? (partial =method :post) can-post-to-gone? handle-gone)
(defdecision moved-temporarily? handle-moved-temporarily post-to-gone?)
(defdecision moved-permanently? handle-moved-permanently moved-temporarily?)
(defdecision existed? moved-permanently? post-to-missing?)
(defhandler handle-conflict 409 "Conflict.")
(defdecision patch-enacted? respond-with-entity? handle-accepted)
(defaction patch! patch-enacted?)
(defaction put! put-enacted?)
(defdecision method-post? (partial =method :post) post! put!)
(defdecision conflict? handle-conflict method-post?)
(defhandler handle-not-implemented 501 "Not implemented.")
(defdecision can-put-to-missing? conflict? handle-not-implemented)
(defdecision put-to-different-url? handle-moved-permanently can-put-to-missing?)
(defdecision method-put? (partial =method :put) put-to-different-url? existed?)
(defhandler handle-precondition-failed 412 "Precondition failed.")
(defdecision if-match-star-exists-for-missing?
if-match-star
handle-precondition-failed
method-put?)
(defhandler handle-not-modified 304 nil)
(defdecision if-none-match?
#(#{ :head :get} (get-in % [:request :request-method]))
handle-not-modified
handle-precondition-failed)
(defdecision put-to-existing? (partial =method :put)
conflict? multiple-representations?)
(defdecision post-to-existing? (partial =method :post)
conflict? put-to-existing?)
(defdecision delete-enacted? respond-with-entity? handle-accepted)
(defaction delete! delete-enacted?)
(defdecision method-patch? (partial =method :patch) patch! post-to-existing?)
(defdecision method-delete?
(partial =method :delete)
delete!
method-patch?)
(defdecision modified-since?
(fn [context]
(let [last-modified (gen-last-modified context)]
[(or (not last-modified) (.after last-modified (::if-modified-since-date context)))
{::last-modified last-modified}]))
method-delete?
handle-not-modified)
(defdecision if-modified-since-valid-date?
(fn [context]
(if-let [date (parse-http-date (get-in context [:request :headers "if-modified-since"]))]
{::if-modified-since-date date}))
modified-since?
method-delete?)
(defdecision if-modified-since-exists?
(partial header-exists? "if-modified-since")
if-modified-since-valid-date?
method-delete?)
(defdecision etag-matches-for-if-none?
(fn [context]
(let [etag (gen-etag context)]
[(= (get-in context [:request :headers "if-none-match"]) etag)
{::etag etag}]))
if-none-match?
if-modified-since-exists?)
(defdecision if-none-match-star?
#(= "*" (get-in % [:request :headers "if-none-match"]))
if-none-match?
etag-matches-for-if-none?)
(defdecision if-none-match-exists? (partial header-exists? "if-none-match")
if-none-match-star? if-modified-since-exists?)
(defdecision unmodified-since?
(fn [context]
(let [last-modified (gen-last-modified context)]
[(and last-modified
(.after last-modified
(::if-unmodified-since-date context)))
{::last-modified last-modified}]))
handle-precondition-failed
if-none-match-exists?)
(defdecision if-unmodified-since-valid-date?
(fn [context]
(when-let [date (parse-http-date (get-in context [:request :headers "if-unmodified-since"]))]
{::if-unmodified-since-date date}))
unmodified-since?
if-none-match-exists?)
(defdecision if-unmodified-since-exists? (partial header-exists? "if-unmodified-since")
if-unmodified-since-valid-date? if-none-match-exists?)
(defdecision etag-matches-for-if-match?
(fn [context]
(let [etag (gen-etag context)]
[(= etag (get-in context [:request :headers "if-match"]))
{::etag etag}]))
if-unmodified-since-exists?
handle-precondition-failed)
(defdecision if-match-star?
if-match-star if-unmodified-since-exists? etag-matches-for-if-match?)
(defdecision if-match-exists? (partial header-exists? "if-match")
if-match-star? if-unmodified-since-exists?)
(defdecision exists? if-match-exists? if-match-star-exists-for-missing?)
(defhandler handle-unprocessable-entity 422 "Unprocessable entity.")
(defdecision processable? exists? handle-unprocessable-entity)
(defhandler handle-not-acceptable 406 "No acceptable resource available.")
(defdecision encoding-available?
(fn [ctx]
(when-let [encoding (conneg/best-allowed-encoding
(get-in ctx [:request :headers "accept-encoding"])
((get-in ctx [:resource :available-encodings]) ctx))]
{:representation {:encoding encoding}}))
processable? handle-not-acceptable)
(defmacro try-header [header & body]
`(try ~@body
(catch ExceptionInfo e#
(if (is-protocol-exception? e#)
(throw (ex-info (format "Malformed %s header" ~header)
{:inner-exception e#}))
(throw e#)))))
(defdecision accept-encoding-exists? (partial header-exists? "accept-encoding")
encoding-available? processable?)
(defdecision charset-available?
#(when-let [charset (conneg/best-allowed-charset
(get-in % [:request :headers "accept-charset"])
((get-in context [:resource :available-charsets]) context))]
(if (= charset "*")
true
{:representation {:charset charset}}))
accept-encoding-exists? handle-not-acceptable)
(defdecision accept-charset-exists? (partial header-exists? "accept-charset")
charset-available? accept-encoding-exists?)
(defdecision language-available?
#(when-let [lang (conneg/best-allowed-language
(get-in % [:request :headers "accept-language"])
((get-in context [:resource :available-languages]) context))]
(if (= lang "*")
true
{:representation {:language lang}}))
accept-charset-exists? handle-not-acceptable)
(defdecision accept-language-exists? (partial header-exists? "accept-language")
language-available? accept-charset-exists?)
(defn negotiate-media-type [context]
(try-header "Accept"
(when-let [type (conneg/best-allowed-content-type
(get-in context [:request :headers "accept"])
((get-in context [:resource :available-media-types] (constantly "text/html")) context))]
{:representation {:media-type (conneg/stringify type)}})))
(defdecision media-type-available? negotiate-media-type
accept-language-exists? handle-not-acceptable)
(defdecision accept-exists?
#(if (header-exists? "accept" %)
true
;; "If no Accept header field is present, then it is assumed that the
;; client accepts all media types" [p100]
;; in this case we do content-type negotiation using */* as the accept
;; specification
(if-let [type (liberator.conneg/best-allowed-content-type
"*/*"
((get-in context [:resource :available-media-types]) context))]
[false {:representation {:media-type (liberator.conneg/stringify type)}}]
false))
media-type-available?
accept-language-exists?)
(defhandler handle-options 200 nil)
(defdecision is-options? #(= :options (:request-method (:request %))) handle-options accept-exists?)
(defhandler handle-request-entity-too-large 413 "Request entity too large.")
(defdecision valid-entity-length? is-options? handle-request-entity-too-large)
(defhandler handle-unsupported-media-type 415 "Unsupported media type.")
(defdecision known-content-type? valid-entity-length? handle-unsupported-media-type)
(defdecision valid-content-header? known-content-type? handle-not-implemented)
(defhandler handle-forbidden 403 "Forbidden.")
(defdecision allowed? valid-content-header? handle-forbidden)
(defhandler handle-unauthorized 401 "Not authorized.")
(defdecision authorized? allowed? handle-unauthorized)
(defhandler handle-malformed 400 "Bad request.")
(defdecision malformed? handle-malformed authorized?)
(defhandler handle-method-not-allowed 405 "Method not allowed.")
(defdecision method-allowed? coll-validator malformed? handle-method-not-allowed)
(defhandler handle-uri-too-long 414 "Request URI too long.")
(defdecision uri-too-long? handle-uri-too-long method-allowed?)
(defhandler handle-unknown-method 501 "Unknown method.")
(defdecision known-method? uri-too-long? handle-unknown-method)
(defhandler handle-service-not-available 503 "Service not available.")
(defdecision service-available? known-method? handle-service-not-available)
(defaction initialize-context service-available?)
(defhandler handle-exception 500 "Internal server error.")
(defn handle-exception-rethrow [{e :exception}]
(throw e))
(defn test-request-method [valid-methods-key]
(fn [{{m :request-method} :request
{vm valid-methods-key} :resource
:as ctx}]
(some #{m} (vm ctx))))
(def default-functions
{
:initialize-context {}
;; Decisions
:service-available? true
:known-methods [:get :head :options :put :post :delete :trace :patch]
:known-method? (test-request-method :known-methods)
:uri-too-long? false
:allowed-methods [:get :head]
:method-allowed? (test-request-method :allowed-methods)
:malformed? false
;; :encoding-available? true
;; :charset-available? true
:authorized? true
:allowed? true
:valid-content-header? true
:known-content-type? true
:valid-entity-length? true
:exists? true
:existed? false
:respond-with-entity? false
:new? true
:post-redirect? false
:put-to-different-url? false
:multiple-representations? false
:conflict? false
:can-post-to-missing? true
:can-put-to-missing? true
:moved-permanently? false
:moved-temporarily? false
:post-enacted? true
:put-enacted? true
:patch-enacted? true
:delete-enacted? true
:processable? true
;; Handlers
:handle-ok "OK"
:handle-see-other handle-moved
:handle-moved-temporarily handle-moved
:handle-moved-permanently handle-moved
:handle-exception handle-exception-rethrow
;; Imperatives. Doesn't matter about decision outcome, both
;; outcomes follow the same route.
:post! true
:put! true
:delete! true
:patch! true
To support , this is used for OPTIONS Accept - Patch
;; header
:patch-content-types []
;; The default function used extract a ring response from a handler's response
:as-response (fn [data ctx]
(when data (as-response data ctx)))
;; Directives
:available-media-types []
;; "If no Content-Language is specified, the default is that the
;; content is intended for all language audiences. This might mean
;; that the sender does not consider it to be specific to any
;; natural language, or that the sender does not know for which
;; language it is intended."
:available-languages ["*"]
:available-charsets ["UTF-8"]
:available-encodings ["identity"]})
;; resources are a map of implementation methods
(defn run-resource [request kvs]
(try
(initialize-context {:request request
:resource (map-values make-function (merge default-functions kvs))
:representation {}})
(catch ExceptionInfo e
(if (is-protocol-exception? e) ; this indicates a client error
{:status 400
:headers {"Content-Type" "text/plain"}
:body (.getMessage e)
::throwable e} ; ::throwable gets picked up by an error renderer
(throw e)))))
(defn get-options
[kvs]
(if (map? (first kvs))
(merge (first kvs) (apply hash-map (rest kvs)))
(apply hash-map kvs)))
(defn resource [& kvs]
(fn [request]
(run-resource request (get-options kvs))))
(defmacro defresource [name & resource-decl]
(let [[docstring resource-decl] (if (string? (first resource-decl))
[(first resource-decl) (rest resource-decl)]
[nil resource-decl])
[args kvs] (if (vector? (first resource-decl))
[(first resource-decl) (rest resource-decl)]
[nil resource-decl])
;; Rather than call `resource` directly, create an anonymous
;; function in the caller's namespace for better debugability.
resource-fn `(fn [request#]
(run-resource request# (get-options (list ~@kvs))))]
(if args
(if docstring
`(defn ~name ~docstring [~@args] ~resource-fn)
`(defn ~name [~@args] ~resource-fn))
(if docstring
`(def ~name ~docstring ~resource-fn)
`(def ~name ~resource-fn)))))
(defn by-method
"returns a handler function that uses the request method to
lookup a function from the map and delegates to it.
Example:
(by-method {:get \"This is the entity\"
:delete \"Entity was deleted successfully.\"})"
[map]
(fn [ctx] ((make-function (get map (get-in ctx [:request :request-method]) ctx)) ctx)))
| null | https://raw.githubusercontent.com/clojure-liberator/liberator/4de95d28b259f12f130bdccfae5d3ad7f8447cd9/src/liberator/core.clj | clojure | Status
Last modified
Finally the result of the handler. We allow the handler to
override the status and headers.
Provide :see-other which returns a location or override :handle-see-other
nil body because the body is reserved to reveal the actual representations available.
"If no Accept header field is present, then it is assumed that the
client accepts all media types" [p100]
in this case we do content-type negotiation using */* as the accept
specification
Decisions
:encoding-available? true
:charset-available? true
Handlers
Imperatives. Doesn't matter about decision outcome, both
outcomes follow the same route.
header
The default function used extract a ring response from a handler's response
Directives
"If no Content-Language is specified, the default is that the
content is intended for all language audiences. This might mean
that the sender does not consider it to be specific to any
natural language, or that the sender does not know for which
language it is intended."
resources are a map of implementation methods
this indicates a client error
::throwable gets picked up by an error renderer
Rather than call `resource` directly, create an anonymous
function in the caller's namespace for better debugability. | (ns liberator.core
(:require [liberator.conneg :as conneg]
[liberator.representation :refer
[Representation as-response ring-response]]
[liberator.util :refer
[as-date http-date parse-http-date
combine make-function is-protocol-exception?]]
[clojure.string :refer [join upper-case]])
(:import (clojure.lang ExceptionInfo)))
(defmulti coll-validator
"Return a function that evaluaties if the give argument
a) is contained in a collection
b) equals an argument
c) when applied to a function evaluates as true"
(fn [x] (cond
(coll? x) :col
(fn? x) :fn)))
(defmethod coll-validator :col [xs]
(fn [x] (some #{x} xs)))
(defmethod coll-validator :fn [f]
f)
(defmethod coll-validator :default [x]
(partial = x))
(defn console-logger [category values]
#(apply println "LOG " category " " values))
(def ^:dynamic *loggers* nil)
(defmacro with-logger [logger & body]
`(binding [*loggers* (conj (or *loggers* []) ~logger)]
~@body))
(defmacro with-console-logger [& body]
`(with-logger console-logger
~@body))
(defn atom-logger [atom]
(fn [& args]
(swap! atom conj args)))
(defn log! [category & values]
(doseq [l *loggers*]
(l category values)))
(declare if-none-match-exists?)
(defn map-values [f m]
(persistent! (reduce-kv (fn [out-m k v] (assoc! out-m k (f v))) (transient {}) m)))
(defn request-method-in [& methods]
#(some #{(:request-method (:request %))} methods))
(defn gen-etag [context]
(if-let [f (get-in context [:resource :etag])]
(if-let [etag-val (f context)]
(format "\"%s\"" etag-val))))
(defn ^java.util.Date gen-last-modified [context]
(if-let [f (get-in context [:resource :last-modified])]
(if-let [lm-val (f context)]
(as-date lm-val))))
(defn update-context [context context-update]
(cond
(map? context-update) (combine context context-update)
(fn? context-update) (context-update)
:otherwise context))
(declare handle-exception)
(defn decide [name test then else {:keys [resource request] :as context}]
(if (or test
(contains? resource name))
(try
(let [ftest (or (resource name) test)
ftest (make-function ftest)
fthen (make-function then)
felse (make-function else)
decision (ftest context)
result (if (vector? decision) (first decision) decision)
context-update (if (vector? decision) (second decision) decision)
context (update-context context context-update)]
(log! :decision name decision)
((if result fthen felse) context))
(catch Exception e
(handle-exception (assoc context :exception e))))
{:status 500 :body (str "No handler found for key \"" name "\"."
" Keys defined for resource are " (keys resource))}))
(defn defdecision*
[name test then else]
`(defn ~name [~'context]
(decide ~(keyword name) ~test ~then ~else ~'context)))
(defmacro defdecision
([name then else]
(defdecision* name nil then else))
([name test then else]
(defdecision* name test then else)))
(defmacro defaction [name next]
`(defdecision ~name ~next ~next))
(defn set-header-maybe [headers name value]
(if-not (empty? value)
(assoc headers name value)
headers))
(defn build-vary-header [{:keys [media-type charset language encoding] :as representation}]
(->> [(when-not (empty? media-type) "Accept")
(when-not (empty? charset) "Accept-Charset")
(when-not (empty? language) "Accept-Language")
(when-not (or (empty? encoding) (= "identity" encoding)) "Accept-Encoding")]
(remove nil?)
(interpose ", ")
(apply str)))
(defn build-allow-header [resource]
(join ", " (map (comp upper-case name) ((:allowed-methods resource)))))
(defn build-options-headers [resource]
(merge {"Allow" (build-allow-header resource)}
(if (some #{:patch} ((:allowed-methods resource)))
{"Accept-Patch" (join "," ((:patch-content-types resource)))}
{})))
(defn run-handler [name status message
{:keys [resource request representation] :as context}]
(let [context
(merge {:status status :message message} context)
response
(merge-with
combine
{:status (:status context)}
ETags
(when-let [etag (gen-etag context)]
{:headers {"ETag" etag}})
(when-let [last-modified (gen-last-modified context)]
{:headers {"Last-Modified" (http-date last-modified)}})
201 created required a location header to be send
(when (#{201 301 303 307} (:status context))
(if-let [f (or (get context :location)
(get resource :location))]
{:headers {"Location" (str ((make-function f) context))}}))
(do
(log! :handler (keyword name))
Content negotiations
(merge-with
merge
{:headers
(-> {}
(set-header-maybe "Content-Type"
(str (:media-type representation)
(when-let [charset (:charset representation)]
(str ";charset=" charset))))
(set-header-maybe "Content-Language" (:language representation))
(set-header-maybe "Content-Encoding"
(let [e (:encoding representation)]
(if-not (= "identity" e) e)))
(set-header-maybe "Vary" (build-vary-header representation)))}
(when-let [result (if-let [handler (get resource (keyword name))]
(handler context)
(get context :message))]
(let [as-response (:as-response resource)]
(as-response result context))))))]
(cond
(or (= :options (:request-method request)) (= 405 (:status response)))
(merge-with combine
{:headers (build-options-headers resource)}
response)
(= :head (:request-method request))
(dissoc response :body)
:else response)))
(defmacro ^:private defhandler [name status message]
`(defn ~name [context#]
(run-handler '~name ~status ~message context#)))
(defn header-exists? [header context]
(get-in context [:request :headers header]))
(defn if-match-star [context]
(= "*" (get-in context [:request :headers "if-match"])))
(defn =method [method context]
(= (get-in context [:request :request-method]) method))
(defmulti to-location type)
(defmethod to-location String [uri] (ring-response {:headers {"Location" uri}}))
(defmethod to-location clojure.lang.APersistentMap [this] this)
(defmethod to-location java.net.URI [^java.net.URI uri] (to-location (.toString uri)))
(defmethod to-location java.net.URL [^java.net.URL url] (to-location (.toString url)))
(defmethod to-location nil [this] this)
(defn- handle-moved [{resource :resource :as context}]
(if-let [f (or (get context :location)
(get resource :location))]
(to-location ((make-function f) context))
{:status 500
:body (format "Internal Server error: no location specified for status %s" (:status context))}))
(defhandler handle-see-other 303 nil)
(defhandler handle-ok 200 "OK")
(defhandler handle-no-content 204 nil)
(defhandler handle-accepted 202 "Accepted")
(defdecision multiple-representations? handle-multiple-representations handle-ok)
(defdecision respond-with-entity? multiple-representations? handle-no-content)
(defhandler handle-created 201 nil)
(defdecision new? handle-created respond-with-entity?)
(defdecision post-redirect? handle-see-other new?)
(defdecision post-enacted? post-redirect? handle-accepted)
(defdecision put-enacted? new? handle-accepted)
(defhandler handle-not-found 404 "Resource not found.")
(defhandler handle-gone 410 "Resource is gone.")
(defaction post! post-enacted?)
(defdecision can-post-to-missing? post! handle-not-found)
(defdecision post-to-missing? (partial =method :post)
can-post-to-missing? handle-not-found)
(defhandler handle-moved-permanently 301 nil)
(defhandler handle-moved-temporarily 307 nil)
(defdecision can-post-to-gone? post! handle-gone)
(defdecision post-to-gone? (partial =method :post) can-post-to-gone? handle-gone)
(defdecision moved-temporarily? handle-moved-temporarily post-to-gone?)
(defdecision moved-permanently? handle-moved-permanently moved-temporarily?)
(defdecision existed? moved-permanently? post-to-missing?)
(defhandler handle-conflict 409 "Conflict.")
(defdecision patch-enacted? respond-with-entity? handle-accepted)
(defaction patch! patch-enacted?)
(defaction put! put-enacted?)
(defdecision method-post? (partial =method :post) post! put!)
(defdecision conflict? handle-conflict method-post?)
(defhandler handle-not-implemented 501 "Not implemented.")
(defdecision can-put-to-missing? conflict? handle-not-implemented)
(defdecision put-to-different-url? handle-moved-permanently can-put-to-missing?)
(defdecision method-put? (partial =method :put) put-to-different-url? existed?)
(defhandler handle-precondition-failed 412 "Precondition failed.")
(defdecision if-match-star-exists-for-missing?
if-match-star
handle-precondition-failed
method-put?)
(defhandler handle-not-modified 304 nil)
(defdecision if-none-match?
#(#{ :head :get} (get-in % [:request :request-method]))
handle-not-modified
handle-precondition-failed)
(defdecision put-to-existing? (partial =method :put)
conflict? multiple-representations?)
(defdecision post-to-existing? (partial =method :post)
conflict? put-to-existing?)
(defdecision delete-enacted? respond-with-entity? handle-accepted)
(defaction delete! delete-enacted?)
(defdecision method-patch? (partial =method :patch) patch! post-to-existing?)
(defdecision method-delete?
(partial =method :delete)
delete!
method-patch?)
(defdecision modified-since?
(fn [context]
(let [last-modified (gen-last-modified context)]
[(or (not last-modified) (.after last-modified (::if-modified-since-date context)))
{::last-modified last-modified}]))
method-delete?
handle-not-modified)
(defdecision if-modified-since-valid-date?
(fn [context]
(if-let [date (parse-http-date (get-in context [:request :headers "if-modified-since"]))]
{::if-modified-since-date date}))
modified-since?
method-delete?)
(defdecision if-modified-since-exists?
(partial header-exists? "if-modified-since")
if-modified-since-valid-date?
method-delete?)
(defdecision etag-matches-for-if-none?
(fn [context]
(let [etag (gen-etag context)]
[(= (get-in context [:request :headers "if-none-match"]) etag)
{::etag etag}]))
if-none-match?
if-modified-since-exists?)
(defdecision if-none-match-star?
#(= "*" (get-in % [:request :headers "if-none-match"]))
if-none-match?
etag-matches-for-if-none?)
(defdecision if-none-match-exists? (partial header-exists? "if-none-match")
if-none-match-star? if-modified-since-exists?)
(defdecision unmodified-since?
(fn [context]
(let [last-modified (gen-last-modified context)]
[(and last-modified
(.after last-modified
(::if-unmodified-since-date context)))
{::last-modified last-modified}]))
handle-precondition-failed
if-none-match-exists?)
(defdecision if-unmodified-since-valid-date?
(fn [context]
(when-let [date (parse-http-date (get-in context [:request :headers "if-unmodified-since"]))]
{::if-unmodified-since-date date}))
unmodified-since?
if-none-match-exists?)
(defdecision if-unmodified-since-exists? (partial header-exists? "if-unmodified-since")
if-unmodified-since-valid-date? if-none-match-exists?)
(defdecision etag-matches-for-if-match?
(fn [context]
(let [etag (gen-etag context)]
[(= etag (get-in context [:request :headers "if-match"]))
{::etag etag}]))
if-unmodified-since-exists?
handle-precondition-failed)
(defdecision if-match-star?
if-match-star if-unmodified-since-exists? etag-matches-for-if-match?)
(defdecision if-match-exists? (partial header-exists? "if-match")
if-match-star? if-unmodified-since-exists?)
(defdecision exists? if-match-exists? if-match-star-exists-for-missing?)
(defhandler handle-unprocessable-entity 422 "Unprocessable entity.")
(defdecision processable? exists? handle-unprocessable-entity)
(defhandler handle-not-acceptable 406 "No acceptable resource available.")
(defdecision encoding-available?
(fn [ctx]
(when-let [encoding (conneg/best-allowed-encoding
(get-in ctx [:request :headers "accept-encoding"])
((get-in ctx [:resource :available-encodings]) ctx))]
{:representation {:encoding encoding}}))
processable? handle-not-acceptable)
(defmacro try-header [header & body]
`(try ~@body
(catch ExceptionInfo e#
(if (is-protocol-exception? e#)
(throw (ex-info (format "Malformed %s header" ~header)
{:inner-exception e#}))
(throw e#)))))
(defdecision accept-encoding-exists? (partial header-exists? "accept-encoding")
encoding-available? processable?)
(defdecision charset-available?
#(when-let [charset (conneg/best-allowed-charset
(get-in % [:request :headers "accept-charset"])
((get-in context [:resource :available-charsets]) context))]
(if (= charset "*")
true
{:representation {:charset charset}}))
accept-encoding-exists? handle-not-acceptable)
(defdecision accept-charset-exists? (partial header-exists? "accept-charset")
charset-available? accept-encoding-exists?)
(defdecision language-available?
#(when-let [lang (conneg/best-allowed-language
(get-in % [:request :headers "accept-language"])
((get-in context [:resource :available-languages]) context))]
(if (= lang "*")
true
{:representation {:language lang}}))
accept-charset-exists? handle-not-acceptable)
(defdecision accept-language-exists? (partial header-exists? "accept-language")
language-available? accept-charset-exists?)
(defn negotiate-media-type [context]
(try-header "Accept"
(when-let [type (conneg/best-allowed-content-type
(get-in context [:request :headers "accept"])
((get-in context [:resource :available-media-types] (constantly "text/html")) context))]
{:representation {:media-type (conneg/stringify type)}})))
(defdecision media-type-available? negotiate-media-type
accept-language-exists? handle-not-acceptable)
(defdecision accept-exists?
#(if (header-exists? "accept" %)
true
(if-let [type (liberator.conneg/best-allowed-content-type
"*/*"
((get-in context [:resource :available-media-types]) context))]
[false {:representation {:media-type (liberator.conneg/stringify type)}}]
false))
media-type-available?
accept-language-exists?)
(defhandler handle-options 200 nil)
(defdecision is-options? #(= :options (:request-method (:request %))) handle-options accept-exists?)
(defhandler handle-request-entity-too-large 413 "Request entity too large.")
(defdecision valid-entity-length? is-options? handle-request-entity-too-large)
(defhandler handle-unsupported-media-type 415 "Unsupported media type.")
(defdecision known-content-type? valid-entity-length? handle-unsupported-media-type)
(defdecision valid-content-header? known-content-type? handle-not-implemented)
(defhandler handle-forbidden 403 "Forbidden.")
(defdecision allowed? valid-content-header? handle-forbidden)
(defhandler handle-unauthorized 401 "Not authorized.")
(defdecision authorized? allowed? handle-unauthorized)
(defhandler handle-malformed 400 "Bad request.")
(defdecision malformed? handle-malformed authorized?)
(defhandler handle-method-not-allowed 405 "Method not allowed.")
(defdecision method-allowed? coll-validator malformed? handle-method-not-allowed)
(defhandler handle-uri-too-long 414 "Request URI too long.")
(defdecision uri-too-long? handle-uri-too-long method-allowed?)
(defhandler handle-unknown-method 501 "Unknown method.")
(defdecision known-method? uri-too-long? handle-unknown-method)
(defhandler handle-service-not-available 503 "Service not available.")
(defdecision service-available? known-method? handle-service-not-available)
(defaction initialize-context service-available?)
(defhandler handle-exception 500 "Internal server error.")
(defn handle-exception-rethrow [{e :exception}]
(throw e))
(defn test-request-method [valid-methods-key]
(fn [{{m :request-method} :request
{vm valid-methods-key} :resource
:as ctx}]
(some #{m} (vm ctx))))
(def default-functions
{
:initialize-context {}
:service-available? true
:known-methods [:get :head :options :put :post :delete :trace :patch]
:known-method? (test-request-method :known-methods)
:uri-too-long? false
:allowed-methods [:get :head]
:method-allowed? (test-request-method :allowed-methods)
:malformed? false
:authorized? true
:allowed? true
:valid-content-header? true
:known-content-type? true
:valid-entity-length? true
:exists? true
:existed? false
:respond-with-entity? false
:new? true
:post-redirect? false
:put-to-different-url? false
:multiple-representations? false
:conflict? false
:can-post-to-missing? true
:can-put-to-missing? true
:moved-permanently? false
:moved-temporarily? false
:post-enacted? true
:put-enacted? true
:patch-enacted? true
:delete-enacted? true
:processable? true
:handle-ok "OK"
:handle-see-other handle-moved
:handle-moved-temporarily handle-moved
:handle-moved-permanently handle-moved
:handle-exception handle-exception-rethrow
:post! true
:put! true
:delete! true
:patch! true
To support , this is used for OPTIONS Accept - Patch
:patch-content-types []
:as-response (fn [data ctx]
(when data (as-response data ctx)))
:available-media-types []
:available-languages ["*"]
:available-charsets ["UTF-8"]
:available-encodings ["identity"]})
(defn run-resource [request kvs]
(try
(initialize-context {:request request
:resource (map-values make-function (merge default-functions kvs))
:representation {}})
(catch ExceptionInfo e
{:status 400
:headers {"Content-Type" "text/plain"}
:body (.getMessage e)
(throw e)))))
(defn get-options
[kvs]
(if (map? (first kvs))
(merge (first kvs) (apply hash-map (rest kvs)))
(apply hash-map kvs)))
(defn resource [& kvs]
(fn [request]
(run-resource request (get-options kvs))))
(defmacro defresource [name & resource-decl]
(let [[docstring resource-decl] (if (string? (first resource-decl))
[(first resource-decl) (rest resource-decl)]
[nil resource-decl])
[args kvs] (if (vector? (first resource-decl))
[(first resource-decl) (rest resource-decl)]
[nil resource-decl])
resource-fn `(fn [request#]
(run-resource request# (get-options (list ~@kvs))))]
(if args
(if docstring
`(defn ~name ~docstring [~@args] ~resource-fn)
`(defn ~name [~@args] ~resource-fn))
(if docstring
`(def ~name ~docstring ~resource-fn)
`(def ~name ~resource-fn)))))
(defn by-method
"returns a handler function that uses the request method to
lookup a function from the map and delegates to it.
Example:
(by-method {:get \"This is the entity\"
:delete \"Entity was deleted successfully.\"})"
[map]
(fn [ctx] ((make-function (get map (get-in ctx [:request :request-method]) ctx)) ctx)))
|
4ab88c8b82e3d3c4d1f3ff7a7c47b4105f47a9b45796e81b1f6b459dbb8f31c5 | rvantonder/CryptOSS | footer.ml | open Tyxml.Html
module B = Bootstrap
let copyright =
div ~a:[ a_class ["footer-copyright"] ] [
div ~a:[ a_class ["container-fluid"] ] [
pcdata "Copyright 2019 CryptoOSS"
]
]
let row_navigation =
B.row [
div ~a:[a_class [ "col-4"; ] ] []
; div ~a:[ a_class [ "col-2"; ] ] [
p [
a ~a:[ a_href (Xml.uri_of_string (Site_prefix.prefix ^ "/")) ] [
pcdata "HOME"
]
]
]
; div ~a:[ a_class [ "col-2" ] ] [
p [
a ~a:[ a_href (Xml.uri_of_string (Site_prefix.prefix ^ "/faq")) ] [
pcdata "FAQ"
]
]
]
; div ~a:[ a_class [ "col-2" ] ] [
p [
a ~a:[ a_href (Xml.uri_of_string (Site_prefix.prefix ^ "/disclaimer")) ] [
pcdata "DISCLAIMER"
]
]
]
]
let row_copyright =
B.row [
B.col_12 [
Unsafe.data "<small>© Copyright CryptoOSS 2019</small>"
]
]
let foot =
B.container [
row_navigation
; row_copyright
]
| null | https://raw.githubusercontent.com/rvantonder/CryptOSS/acd931433f70fd097930b2e62a294af6d31a2a77/site/footer.ml | ocaml | open Tyxml.Html
module B = Bootstrap
let copyright =
div ~a:[ a_class ["footer-copyright"] ] [
div ~a:[ a_class ["container-fluid"] ] [
pcdata "Copyright 2019 CryptoOSS"
]
]
let row_navigation =
B.row [
div ~a:[a_class [ "col-4"; ] ] []
; div ~a:[ a_class [ "col-2"; ] ] [
p [
a ~a:[ a_href (Xml.uri_of_string (Site_prefix.prefix ^ "/")) ] [
pcdata "HOME"
]
]
]
; div ~a:[ a_class [ "col-2" ] ] [
p [
a ~a:[ a_href (Xml.uri_of_string (Site_prefix.prefix ^ "/faq")) ] [
pcdata "FAQ"
]
]
]
; div ~a:[ a_class [ "col-2" ] ] [
p [
a ~a:[ a_href (Xml.uri_of_string (Site_prefix.prefix ^ "/disclaimer")) ] [
pcdata "DISCLAIMER"
]
]
]
]
let row_copyright =
B.row [
B.col_12 [
Unsafe.data "<small>© Copyright CryptoOSS 2019</small>"
]
]
let foot =
B.container [
row_navigation
; row_copyright
]
|
|
b989617fc4d2999e5f15a3f54bed46f6a0585b1bbff8ccabe931722fd413419f | chris-taylor/aima-haskell | Restaurant.hs | module AI.Learning.Example.Restaurant where
import Control.Monad
import Control.Monad.Random
import qualified Graphics.Gnuplot.Simple as G
import System.IO.Unsafe
import AI.Learning.Core
import AI.Learning.DecisionTree
import qualified AI.Learning.RandomForest as RF
import AI.Util.Util
data Patrons = Empty | Some | Full deriving (Show,Eq,Ord,Enum,Bounded)
data Price = Cheap | Medium | Expensive deriving (Show,Eq,Ord,Enum,Bounded)
data Type = French | Thai | Burger | Italian deriving (Show,Eq,Ord,Enum,Bounded)
data Wait = None | Short | Med | Long deriving (Show,Eq,Ord,Enum,Bounded)
data Restaurant = Restaurant {
alt :: Bool, -- is there an alternative?
bar :: Bool, -- is there a bar?
is it a friday ?
hun :: Bool, -- are you hungry?
pat :: Patrons, -- how many patrons are there?
price :: Price, -- how cheap is it?
rain :: Bool, -- is it raining?
res :: Bool, -- do you have a reservation?
food :: Type, -- what type of food is it?
wait :: Wait, -- what is the wait?
willWait :: Bool -- will you wait?
} deriving (Show,Eq,Ord)
atts :: [Att Restaurant]
atts = [ att alt "Alternative"
, att bar "Bar"
, att fri "Friday"
, att hun "Hungry"
, att pat "Patrons"
, att price "Price"
, att rain "Raining"
, att res "Reservation"
, att food "Food"
, att wait "Wait" ]
randomRestaurantNoisy :: RandomGen g => Float -> Rand g Restaurant
randomRestaurantNoisy noise = do
alt <- getRandom
bar <- getRandom
fri <- getRandom
hun <- getRandom
pat <- getRandomEnum 3
price <- getRandomEnum 3
rain <- getRandom
res <- getRandom
food <- getRandomEnum 4
wait <- getRandomEnum 4
let mkR ww = Restaurant alt bar fri hun pat price rain res food wait ww
willWait = decide actualTree (mkR False)
p <- getRandomR (0,1)
return $ if p > noise
then mkR willWait
else mkR (not willWait)
randomRestaurant :: RandomGen g => Rand g Restaurant
randomRestaurant = do
alt <- getRandom
bar <- getRandom
fri <- getRandom
hun <- getRandom
pat <- getRandomEnum 3
price <- getRandomEnum 3
rain <- getRandom
res <- getRandom
food <- getRandomEnum 4
wait <- getRandomEnum 4
let mkR ww = Restaurant alt bar fri hun pat price rain res food wait ww
willWait = decide actualTree (mkR False)
return (mkR willWait)
randomDataSetNoisy :: RandomGen g => Float -> Int -> Rand g [Restaurant]
randomDataSetNoisy noise n = replicateM n (randomRestaurantNoisy noise)
randomDataSet :: RandomGen g => Int -> Rand g [Restaurant]
randomDataSet n = replicateM n randomRestaurant
--------------------
-- Model builders --
--------------------
treeBuilder :: [Restaurant] -> [Bool] -> Restaurant -> Bool
treeBuilder as _ a =
let tree = fitTree willWait atts as
in decide tree a
forestBuilder :: Int -> Int -> [Restaurant] -> [Bool] -> Restaurant -> Bool
forestBuilder nTree nAtt as bs a = do
let forest = unsafePerformIO $ evalRandIO $
RF.randomForest nTree nAtt willWait atts as
in RF.decide forest a
---------------------------------------
-- Demo of the decision tree library --
---------------------------------------
--runWithNoise :: RandomGen g =>
-- Builder Restaurant Bool
-- -> Int
-- -> Int
-- -> Float
-- -> Rand g Float
--runWithNoise builder nTrain nTest noise = do
-- xTrain <- randomDataSetNoisy noise nTrain
xTest < - randomDataSetNoisy noise nTest
-- let yTrain = map willWait xTrain
-- yTest = map willWait xTest
-- return (crossValidate builder xTrain yTrain xTest yTest)
--runNoNoise :: RandomGen g =>
-- Int
-- -> Int
-- -> Rand g Float
runNoNoise = do
-- xTrain <- randomDataSet nTrain
xTest < - randomDataSet nTest
-- let yTrain = map willWait xTrain
-- yTest = map willWait xTest
return ( crossValidate treeBuilder xTrain yTest )
: : Float - > IO ( )
--demo2 noise = do
-- vals <- evalRandIO $ do
let ns = [ 1 .. 100 ]
do
-- sampleMcrs <- replicateM 100 $ runWithNoise treeBuilder n 100 noise
-- return (mean sampleMcrs)
return ( zip ns $ map ( * 100 ) mcrs )
let = " Size of test set "
ylabel = G.YLabel " Misclassification Rate ( % ) "
title = G.Title " Decision Tree Demo ( Restaurants ) "
G.plotList [ , ylabel , title ] vals
: : IO ( )
= do
-- vals <- evalRandIO $ do
let ns = [ 1 .. 100 ]
do
-- sampleMcrs <- replicateM 100 $ runNoNoise n 100
-- return (mean sampleMcrs)
return ( zip ns $ map ( * 100 ) mcrs )
let = " Size of test set "
ylabel = G.YLabel " Misclassification Rate ( % ) "
title = G.Title " Decision Tree Demo ( Restaurants ) "
G.plotList [ , ylabel , title ] vals
--------------------------------------
The decision tree in Figure 18.2 --
--------------------------------------
actualTree :: DTree Restaurant () Bool
actualTree = do
patrons <- attribute pat "Patrons"
case patrons of
Empty -> return False
Some -> return True
Full -> do
time <- attribute wait "WaitTime"
case time of
None -> return True
Short -> do
hungry <- attribute hun "Hungry"
if not hungry
then return True
else do
alternative <- attribute alt "Alternative"
if not alternative
then return True
else do
raining <- attribute rain "Rain"
return (if raining then True else False)
Med -> do
alternative <- attribute alt "Alternative"
if not alternative
then do
reservation <- attribute res "Reservation"
if reservation
then return True
else do
hasBar <- attribute bar "Bar"
return (if hasBar then True else False)
else do
friday <- attribute fri "Fri/Sat"
return (if friday then True else False)
Long -> return False
------------------------------------------
This is the example in AIMA Fig 18.3 --
------------------------------------------
restaurants =
[ Restaurant True False False True Some Expensive False True French None True
, Restaurant True False False True Full Cheap False False Thai Med False
, Restaurant False True False False Some Cheap False False Burger None True
, Restaurant True False True True Full Cheap True False Thai Short True
, Restaurant True False True False Full Expensive False True French Long False
, Restaurant False True False True Some Medium True True Italian None True
, Restaurant False True False False Empty Cheap True False Burger None False
, Restaurant False False False True Some Medium True True Thai None True
, Restaurant False True True False Full Cheap True False Burger Long False
, Restaurant True True True True Full Expensive False True Italian Short False
, Restaurant False False False False Empty Cheap False False Thai None False
, Restaurant True True True True Full Cheap False False Burger Med True ]
fittedTree = fitTree willWait atts restaurants
| null | https://raw.githubusercontent.com/chris-taylor/aima-haskell/538dcfe82a57a623e45174e911ce68974d8aa839/src/AI/Learning/Example/Restaurant.hs | haskell | is there an alternative?
is there a bar?
are you hungry?
how many patrons are there?
how cheap is it?
is it raining?
do you have a reservation?
what type of food is it?
what is the wait?
will you wait?
------------------
Model builders --
------------------
-------------------------------------
Demo of the decision tree library --
-------------------------------------
runWithNoise :: RandomGen g =>
Builder Restaurant Bool
-> Int
-> Int
-> Float
-> Rand g Float
runWithNoise builder nTrain nTest noise = do
xTrain <- randomDataSetNoisy noise nTrain
let yTrain = map willWait xTrain
yTest = map willWait xTest
return (crossValidate builder xTrain yTrain xTest yTest)
runNoNoise :: RandomGen g =>
Int
-> Int
-> Rand g Float
xTrain <- randomDataSet nTrain
let yTrain = map willWait xTrain
yTest = map willWait xTest
demo2 noise = do
vals <- evalRandIO $ do
sampleMcrs <- replicateM 100 $ runWithNoise treeBuilder n 100 noise
return (mean sampleMcrs)
vals <- evalRandIO $ do
sampleMcrs <- replicateM 100 $ runNoNoise n 100
return (mean sampleMcrs)
------------------------------------
------------------------------------
----------------------------------------
---------------------------------------- | module AI.Learning.Example.Restaurant where
import Control.Monad
import Control.Monad.Random
import qualified Graphics.Gnuplot.Simple as G
import System.IO.Unsafe
import AI.Learning.Core
import AI.Learning.DecisionTree
import qualified AI.Learning.RandomForest as RF
import AI.Util.Util
data Patrons = Empty | Some | Full deriving (Show,Eq,Ord,Enum,Bounded)
data Price = Cheap | Medium | Expensive deriving (Show,Eq,Ord,Enum,Bounded)
data Type = French | Thai | Burger | Italian deriving (Show,Eq,Ord,Enum,Bounded)
data Wait = None | Short | Med | Long deriving (Show,Eq,Ord,Enum,Bounded)
data Restaurant = Restaurant {
is it a friday ?
} deriving (Show,Eq,Ord)
atts :: [Att Restaurant]
atts = [ att alt "Alternative"
, att bar "Bar"
, att fri "Friday"
, att hun "Hungry"
, att pat "Patrons"
, att price "Price"
, att rain "Raining"
, att res "Reservation"
, att food "Food"
, att wait "Wait" ]
randomRestaurantNoisy :: RandomGen g => Float -> Rand g Restaurant
randomRestaurantNoisy noise = do
alt <- getRandom
bar <- getRandom
fri <- getRandom
hun <- getRandom
pat <- getRandomEnum 3
price <- getRandomEnum 3
rain <- getRandom
res <- getRandom
food <- getRandomEnum 4
wait <- getRandomEnum 4
let mkR ww = Restaurant alt bar fri hun pat price rain res food wait ww
willWait = decide actualTree (mkR False)
p <- getRandomR (0,1)
return $ if p > noise
then mkR willWait
else mkR (not willWait)
randomRestaurant :: RandomGen g => Rand g Restaurant
randomRestaurant = do
alt <- getRandom
bar <- getRandom
fri <- getRandom
hun <- getRandom
pat <- getRandomEnum 3
price <- getRandomEnum 3
rain <- getRandom
res <- getRandom
food <- getRandomEnum 4
wait <- getRandomEnum 4
let mkR ww = Restaurant alt bar fri hun pat price rain res food wait ww
willWait = decide actualTree (mkR False)
return (mkR willWait)
randomDataSetNoisy :: RandomGen g => Float -> Int -> Rand g [Restaurant]
randomDataSetNoisy noise n = replicateM n (randomRestaurantNoisy noise)
randomDataSet :: RandomGen g => Int -> Rand g [Restaurant]
randomDataSet n = replicateM n randomRestaurant
treeBuilder :: [Restaurant] -> [Bool] -> Restaurant -> Bool
treeBuilder as _ a =
let tree = fitTree willWait atts as
in decide tree a
forestBuilder :: Int -> Int -> [Restaurant] -> [Bool] -> Restaurant -> Bool
forestBuilder nTree nAtt as bs a = do
let forest = unsafePerformIO $ evalRandIO $
RF.randomForest nTree nAtt willWait atts as
in RF.decide forest a
xTest < - randomDataSetNoisy noise nTest
runNoNoise = do
xTest < - randomDataSet nTest
return ( crossValidate treeBuilder xTrain yTest )
: : Float - > IO ( )
let ns = [ 1 .. 100 ]
do
return ( zip ns $ map ( * 100 ) mcrs )
let = " Size of test set "
ylabel = G.YLabel " Misclassification Rate ( % ) "
title = G.Title " Decision Tree Demo ( Restaurants ) "
G.plotList [ , ylabel , title ] vals
: : IO ( )
= do
let ns = [ 1 .. 100 ]
do
return ( zip ns $ map ( * 100 ) mcrs )
let = " Size of test set "
ylabel = G.YLabel " Misclassification Rate ( % ) "
title = G.Title " Decision Tree Demo ( Restaurants ) "
G.plotList [ , ylabel , title ] vals
actualTree :: DTree Restaurant () Bool
actualTree = do
patrons <- attribute pat "Patrons"
case patrons of
Empty -> return False
Some -> return True
Full -> do
time <- attribute wait "WaitTime"
case time of
None -> return True
Short -> do
hungry <- attribute hun "Hungry"
if not hungry
then return True
else do
alternative <- attribute alt "Alternative"
if not alternative
then return True
else do
raining <- attribute rain "Rain"
return (if raining then True else False)
Med -> do
alternative <- attribute alt "Alternative"
if not alternative
then do
reservation <- attribute res "Reservation"
if reservation
then return True
else do
hasBar <- attribute bar "Bar"
return (if hasBar then True else False)
else do
friday <- attribute fri "Fri/Sat"
return (if friday then True else False)
Long -> return False
restaurants =
[ Restaurant True False False True Some Expensive False True French None True
, Restaurant True False False True Full Cheap False False Thai Med False
, Restaurant False True False False Some Cheap False False Burger None True
, Restaurant True False True True Full Cheap True False Thai Short True
, Restaurant True False True False Full Expensive False True French Long False
, Restaurant False True False True Some Medium True True Italian None True
, Restaurant False True False False Empty Cheap True False Burger None False
, Restaurant False False False True Some Medium True True Thai None True
, Restaurant False True True False Full Cheap True False Burger Long False
, Restaurant True True True True Full Expensive False True Italian Short False
, Restaurant False False False False Empty Cheap False False Thai None False
, Restaurant True True True True Full Cheap False False Burger Med True ]
fittedTree = fitTree willWait atts restaurants
|
8a956f7ffc50fe477c6c947b268dc356904fabc21ef5aa707d79ed233d00fe29 | hyperfiddle/electric | trace19.cljc | (ns dustin.trace19
(:require [missionary.core :as m]
[minitest :refer [tests]]
[dustin.trace17 :as trace]
[leo.extend-seq :refer [extend-seq]]))
;We could assume that extend-seq works, continue with tracing it, and
;then come back to the UI. This is because the submission fiddle UI is adding too much
;complexity. Even if we're wrong with extend-seq's implementation (diffing) we will
;still learn a lot by continuing with it. Lets do this
(defn init [inputs _!replayers tracef]
(let [>control (m/signal! (m/watch (get inputs '>control)))
>p (m/signal! (m/watch (get inputs '>p)))
>q (m/signal! (m/watch (get inputs '>q)))
>cross (m/signal! (m/relieve {} (m/ap (m/?! (case (m/?! >control)
:p >p
:q >q)))))
>z (m/signal! (m/latest range >cross))
>>z (m/signal! (extend-seq str >z))
>effects (m/stream! (m/relieve merge (m/ap
(trace/amb=
{'>control (m/?? >control)}
{'>p (m/?? >p)}
{'>q (m/?? >q)}
{'>cross (m/?? >cross)}
{'>z (m/?? >z)}
{'>>z (set (keys (m/?? >>z)))}
(let [[k v] (m/?= (m/enumerate (m/?? >>z)))]
{['>>z k] (m/?? v)})
))))]
(m/stream! (m/ap (tracef (m/?? >effects))))))
(tests
(def !control (atom :p))
(def !p (atom 0))
(def !q (atom 0))
(def r (trace/reactor! {'>control !control
'>p !p
'>q !q}
init))
(def !trace (trace/log! r))
(trace/directive! r '[>p 3])
@!trace := [{'>p 3
'>cross 3
'>z '(0 1 2)
['>>z "0"] 0
['>>z "1"] 1
['>>z "2"] 2
'>>z #{"0" "1" "2"}}])
;; We could work on:
;; - [X] ids (path, uuids, whatever)
;; - [ ] nested extend-seq (this example is top-level)
;; - [ ] replay dynamic trace
| null | https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2021/trace/trace19.cljc | clojure | We could assume that extend-seq works, continue with tracing it, and
then come back to the UI. This is because the submission fiddle UI is adding too much
complexity. Even if we're wrong with extend-seq's implementation (diffing) we will
still learn a lot by continuing with it. Lets do this
We could work on:
- [X] ids (path, uuids, whatever)
- [ ] nested extend-seq (this example is top-level)
- [ ] replay dynamic trace | (ns dustin.trace19
(:require [missionary.core :as m]
[minitest :refer [tests]]
[dustin.trace17 :as trace]
[leo.extend-seq :refer [extend-seq]]))
(defn init [inputs _!replayers tracef]
(let [>control (m/signal! (m/watch (get inputs '>control)))
>p (m/signal! (m/watch (get inputs '>p)))
>q (m/signal! (m/watch (get inputs '>q)))
>cross (m/signal! (m/relieve {} (m/ap (m/?! (case (m/?! >control)
:p >p
:q >q)))))
>z (m/signal! (m/latest range >cross))
>>z (m/signal! (extend-seq str >z))
>effects (m/stream! (m/relieve merge (m/ap
(trace/amb=
{'>control (m/?? >control)}
{'>p (m/?? >p)}
{'>q (m/?? >q)}
{'>cross (m/?? >cross)}
{'>z (m/?? >z)}
{'>>z (set (keys (m/?? >>z)))}
(let [[k v] (m/?= (m/enumerate (m/?? >>z)))]
{['>>z k] (m/?? v)})
))))]
(m/stream! (m/ap (tracef (m/?? >effects))))))
(tests
(def !control (atom :p))
(def !p (atom 0))
(def !q (atom 0))
(def r (trace/reactor! {'>control !control
'>p !p
'>q !q}
init))
(def !trace (trace/log! r))
(trace/directive! r '[>p 3])
@!trace := [{'>p 3
'>cross 3
'>z '(0 1 2)
['>>z "0"] 0
['>>z "1"] 1
['>>z "2"] 2
'>>z #{"0" "1" "2"}}])
|
9e6d7a5ae569767c4092e2f4ff76aefda9c76af79b7fcd507f56f42180ca8947 | mwand/eopl3 | tests.scm | (module tests mzscheme
(provide test-list)
;;;;;;;;;;;;;;;; tests ;;;;;;;;;;;;;;;;
(define test-list
'(
;; simple arithmetic
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
;; nested arithmetic
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
;; simple variables
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
;; simple unbound variables
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
;; simple conditionals
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
;; test dynamic typechecking
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
;; make sure that the test and both arms get evaluated
;; properly.
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
;; and make sure the other arm doesn't get evaluated.
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
;; simple let
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
;; check nested let and shadowing
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
;; simple applications
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
;; simple letrecs
(simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32)
(simple-letrec-2
"letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)"
8)
(simple-letrec-3
"let m = -5
in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)"
20)
; (fact-of-6 "letrec
fact(x ) = if ) then 1 else * ( x , ( fact ) ) )
in ( fact 6 ) "
720 )
(HO-nested-letrecs
"letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1))
in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)" 1)
(begin-test-1
"begin 1; 2; 3 end"
3)
(assignment-test-1 "let x = 17
in begin set x = 27; x end"
27)
(gensym-test
"let g = let count = 0 in proc(d)
let d = set count = -(count,-1)
in count
in -((g 11), (g 22))"
-1)
(even-odd-via-set "
let x = 0
in letrec even(d) = if zero?(x) then 1
else let d = set x = -(x,1)
in (odd d)
odd(d) = if zero?(x) then 0
else let d = set x = -(x,1)
in (even d)
in let d = set x = 13 in (odd -99)" 1)
(simple-mutpair-left-1 "let p = newpair(22,33) in left(p)" 22)
(simple-mutpair-right-1 "let p = newpair(22,33) in right(p)" 33)
(simple-mutpair-setleft-1 "
left(p ) end " 77 )
(simple-mutpair-setleft-2 "
right(p ) end " 33 )
(simple-mutpair-setright-1 "
right(p ) end " 77 )
(simple-mutpair-setright-2 "
left(p ) end " 22 )
(gensym-using-mutable-pair-left
"let g = let count = newpair(0,0)
in proc (dummy)
begin
setleft count = -(left(count), -1);
left(count)
end
in -((g 22), (g 22))"
-1)
(gensym-using-mutable-pair-right
"let g = let count = newpair(0,0)
in proc (dummy)
begin
setright count = -(right(count), -1);
right(count)
end
in -((g 22), (g 22))"
-1)
;; new for call-by-reference
(cbr-swap-1
"let swap = proc (x) proc (y)
let temp = x
in begin
set x = y;
set y = temp
end
in let a = 33
in let b = 44
in begin
((swap a) b);
-(a,b)
end"
11)
(cbr-global-aliasing-1
"let p = proc (z) set z = 44
in let x = 33
in begin (p x); x end"
44)
(cbr-direct-aliasing-1
"let p = proc (x) proc (y)
begin
set x = 44;
y
end
in let b = 33
in ((p b) b)"
44)
(cbr-indirect-aliasing-1
;; in this language, you can't return a reference.
"let p = proc (x) proc (y)
begin
set x = 44;
y
end
in let q = proc(z) z
in let b = 33
in ((p b) (q b))"
33)
(cbr-indirect-aliasing-2
;; in this language, you can't return a reference.
"let p = proc (x) proc (y)
begin
set x = 44;
y
end
in let q = proc(z) z
in let b = 33
in ((p (q b)) b)"
33)
(cbr-sideeffect-a-passed-structure-1
"let f = proc (x) setleft x = -(left(x),-1)
in let p = newpair (44,newpair(55,66))
in begin
(f right(p));
left(right(p))
end"
56)
(cbr-example-for-book "
let f = proc (x) set x = 44
in let g = proc (y) (f y)
in let z = 55
in begin
(g z);
z
end"
44)
))
) | null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter4/call-by-reference/tests.scm | scheme | tests ;;;;;;;;;;;;;;;;
simple arithmetic
nested arithmetic
simple variables
simple unbound variables
simple conditionals
test dynamic typechecking
make sure that the test and both arms get evaluated
properly.
and make sure the other arm doesn't get evaluated.
simple let
check nested let and shadowing
simple applications
simple letrecs
(fact-of-6 "letrec
x end"
new for call-by-reference
x end"
in this language, you can't return a reference.
in this language, you can't return a reference.
| (module tests mzscheme
(provide test-list)
(define test-list
'(
(positive-const "11" 11)
(negative-const "-33" -33)
(simple-arith-1 "-(44,33)" 11)
(nested-arith-left "-(-(44,33),22)" -11)
(nested-arith-right "-(55, -(22,11))" 44)
(test-var-1 "x" 10)
(test-var-2 "-(x,1)" 9)
(test-var-3 "-(1,x)" -9)
(test-unbound-var-1 "foo" error)
(test-unbound-var-2 "-(x,foo)" error)
(if-true "if zero?(0) then 3 else 4" 3)
(if-false "if zero?(1) then 3 else 4" 4)
(no-bool-to-diff-1 "-(zero?(0),1)" error)
(no-bool-to-diff-2 "-(1,zero?(0))" error)
(no-int-to-if "if 1 then 2 else 3" error)
(if-eval-test-true "if zero?(-(11,11)) then 3 else 4" 3)
(if-eval-test-false "if zero?(-(11, 12)) then 3 else 4" 4)
(if-eval-test-true-2 "if zero?(-(11, 11)) then 3 else foo" 3)
(if-eval-test-false-2 "if zero?(-(11,12)) then foo else 4" 4)
(simple-let-1 "let x = 3 in x" 3)
make sure the body and rhs get evaluated
(eval-let-body "let x = 3 in -(x,1)" 2)
(eval-let-rhs "let x = -(4,1) in -(x,1)" 2)
(simple-nested-let "let x = 3 in let y = 4 in -(x,y)" -1)
(check-shadowing-in-body "let x = 3 in let x = 4 in x" 4)
(check-shadowing-in-rhs "let x = 3 in let x = -(x,1) in x" 2)
(apply-proc-in-rator-pos "(proc(x) -(x,1) 30)" 29)
(apply-simple-proc "let f = proc (x) -(x,1) in (f 30)" 29)
(let-to-proc-1 "(proc(f)(f 30) proc(x)-(x,1))" 29)
(nested-procs "((proc (x) proc (y) -(x,y) 5) 6)" -1)
(nested-procs2 "let f = proc(x) proc (y) -(x,y) in ((f -(10,5)) 6)"
-1)
(y-combinator-1 "
let fix = proc (f)
let d = proc (x) proc (z) ((f (x x)) z)
in proc (n) ((f (d d)) n)
in let
t4m = proc (f) proc(x) if zero?(x) then 0 else -((f -(x,1)),-4)
in let times4 = (fix t4m)
in (times4 3)" 12)
(simple-letrec-1 "letrec f(x) = -(x,1) in (f 33)" 32)
(simple-letrec-2
"letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), -2) in (f 4)"
8)
(simple-letrec-3
"let m = -5
in letrec f(x) = if zero?(x) then 0 else -((f -(x,1)), m) in (f 4)"
20)
fact(x ) = if ) then 1 else * ( x , ( fact ) ) )
in ( fact 6 ) "
720 )
(HO-nested-letrecs
"letrec even(odd) = proc(x) if zero?(x) then 1 else (odd -(x,1))
in letrec odd(x) = if zero?(x) then 0 else ((even odd) -(x,1))
in (odd 13)" 1)
(begin-test-1
"begin 1; 2; 3 end"
3)
(assignment-test-1 "let x = 17
27)
(gensym-test
"let g = let count = 0 in proc(d)
let d = set count = -(count,-1)
in count
in -((g 11), (g 22))"
-1)
(even-odd-via-set "
let x = 0
in letrec even(d) = if zero?(x) then 1
else let d = set x = -(x,1)
in (odd d)
odd(d) = if zero?(x) then 0
else let d = set x = -(x,1)
in (even d)
in let d = set x = 13 in (odd -99)" 1)
(simple-mutpair-left-1 "let p = newpair(22,33) in left(p)" 22)
(simple-mutpair-right-1 "let p = newpair(22,33) in right(p)" 33)
(simple-mutpair-setleft-1 "
left(p ) end " 77 )
(simple-mutpair-setleft-2 "
right(p ) end " 33 )
(simple-mutpair-setright-1 "
right(p ) end " 77 )
(simple-mutpair-setright-2 "
left(p ) end " 22 )
(gensym-using-mutable-pair-left
"let g = let count = newpair(0,0)
in proc (dummy)
begin
left(count)
end
in -((g 22), (g 22))"
-1)
(gensym-using-mutable-pair-right
"let g = let count = newpair(0,0)
in proc (dummy)
begin
right(count)
end
in -((g 22), (g 22))"
-1)
(cbr-swap-1
"let swap = proc (x) proc (y)
let temp = x
in begin
set y = temp
end
in let a = 33
in let b = 44
in begin
-(a,b)
end"
11)
(cbr-global-aliasing-1
"let p = proc (z) set z = 44
in let x = 33
44)
(cbr-direct-aliasing-1
"let p = proc (x) proc (y)
begin
y
end
in let b = 33
in ((p b) b)"
44)
(cbr-indirect-aliasing-1
"let p = proc (x) proc (y)
begin
y
end
in let q = proc(z) z
in let b = 33
in ((p b) (q b))"
33)
(cbr-indirect-aliasing-2
"let p = proc (x) proc (y)
begin
y
end
in let q = proc(z) z
in let b = 33
in ((p (q b)) b)"
33)
(cbr-sideeffect-a-passed-structure-1
"let f = proc (x) setleft x = -(left(x),-1)
in let p = newpair (44,newpair(55,66))
in begin
left(right(p))
end"
56)
(cbr-example-for-book "
let f = proc (x) set x = 44
in let g = proc (y) (f y)
in let z = 55
in begin
z
end"
44)
))
) |
f75aded15f9f57196800589263809e6b94dfc7040e1cbb9b414f68e1b8a11594 | penpot/penpot | pages.cljs | 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) KALEIDOS INC
(ns frontend-tests.helpers.pages
(:require
[app.common.geom.point :as gpt]
[app.common.geom.shapes :as gsh]
[app.common.pages :as cp]
[app.common.pages.helpers :as cph]
[app.common.types.shape :as cts]
[app.common.uuid :as uuid]
[app.main.data.workspace :as dw]
[app.main.data.workspace.groups :as dwg]
[app.main.data.workspace.layout :as layout]
[app.main.data.workspace.libraries-helpers :as dwlh]
[app.main.data.workspace.state-helpers :as wsh]
[beicon.core :as rx]
[cljs.pprint :refer [pprint]]
[cljs.test :as t :include-macros true]
[potok.core :as ptk]))
;; ---- Helpers to manage pages and objects
(def current-file-id (uuid/next))
(def initial-state
{:current-file-id current-file-id
:current-page-id nil
:workspace-layout layout/default-layout
:workspace-global layout/default-global
:workspace-data {:id current-file-id
:components {}
:pages []
:pages-index {}}
:workspace-libraries {}})
(def ^:private idmap (atom {}))
(defn reset-idmap! []
(reset! idmap {}))
(defn current-page
[state]
(let [page-id (:current-page-id state)]
(get-in state [:workspace-data :pages-index page-id])))
(defn id
[label]
(get @idmap label))
(defn get-shape
[state label]
(let [page (current-page state)]
(get-in page [:objects (id label)])))
(defn sample-page
([state] (sample-page state {}))
([state {:keys [id name] :as props
:or {id (uuid/next)
name "page1"}}]
(swap! idmap assoc :page id)
(-> state
(assoc :current-page-id id)
(update :workspace-data
cp/process-changes
[{:type :add-page
:id id
:name name}]))))
(defn sample-shape
([state label type] (sample-shape state type {}))
([state label type props]
(let [page (current-page state)
frame (cph/get-frame (:objects page))
shape (cts/make-shape type {:x 0 :y 0 :width 1 :height 1} props)]
(swap! idmap assoc label (:id shape))
(update state :workspace-data
cp/process-changes
[{:type :add-obj
:id (:id shape)
:page-id (:id page)
:frame-id (:id frame)
:obj shape}]))))
(defn group-shapes
([state label ids] (group-shapes state label ids "Group"))
([state label ids prefix]
(let [page (current-page state)
shapes (dwg/shapes-for-grouping (:objects page) ids)]
(if (empty? shapes)
state
(let [[group changes]
(dwg/prepare-create-group nil (:objects page) (:id page) shapes prefix true)]
(swap! idmap assoc label (:id group))
(update state :workspace-data
cp/process-changes (:redo-changes changes)))))))
(defn make-component
[state instance-label component-label shape-ids]
(let [page (current-page state)
objects (wsh/lookup-page-objects state (:id page))
shapes (dwg/shapes-for-grouping objects shape-ids)
[group component-root changes]
(dwlh/generate-add-component nil
shapes
(:objects page)
(:id page)
current-file-id
true)]
(swap! idmap assoc instance-label (:id group)
component-label (:id component-root))
(update state :workspace-data
cp/process-changes (:redo-changes changes))))
(defn instantiate-component
([state label component-id]
(instantiate-component state label component-id current-file-id))
([state label component-id file-id]
(let [page (current-page state)
libraries (wsh/get-libraries state)
[new-shape changes]
(dwlh/generate-instantiate-component nil
file-id
component-id
(gpt/point 100 100)
page
libraries)]
(swap! idmap assoc label (:id new-shape))
(update state :workspace-data
cp/process-changes (:redo-changes changes)))))
(defn move-to-library
[state label name]
(let [library-id (uuid/next)
data (get state :workspace-data)]
(swap! idmap assoc label library-id)
(-> state
(update :workspace-libraries
assoc library-id {:id library-id
:name name
:data {:id library-id
:components (:components data)}})
(update :workspace-data
assoc :components {} :pages [] :pages-index {}))))
| null | https://raw.githubusercontent.com/penpot/penpot/62aa6569f258829d36bbdf7d43819fe876f6b8b2/frontend/test/frontend_tests/helpers/pages.cljs | clojure |
Copyright (c) KALEIDOS INC
---- Helpers to manage pages and objects | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns frontend-tests.helpers.pages
(:require
[app.common.geom.point :as gpt]
[app.common.geom.shapes :as gsh]
[app.common.pages :as cp]
[app.common.pages.helpers :as cph]
[app.common.types.shape :as cts]
[app.common.uuid :as uuid]
[app.main.data.workspace :as dw]
[app.main.data.workspace.groups :as dwg]
[app.main.data.workspace.layout :as layout]
[app.main.data.workspace.libraries-helpers :as dwlh]
[app.main.data.workspace.state-helpers :as wsh]
[beicon.core :as rx]
[cljs.pprint :refer [pprint]]
[cljs.test :as t :include-macros true]
[potok.core :as ptk]))
(def current-file-id (uuid/next))
(def initial-state
{:current-file-id current-file-id
:current-page-id nil
:workspace-layout layout/default-layout
:workspace-global layout/default-global
:workspace-data {:id current-file-id
:components {}
:pages []
:pages-index {}}
:workspace-libraries {}})
(def ^:private idmap (atom {}))
(defn reset-idmap! []
(reset! idmap {}))
(defn current-page
[state]
(let [page-id (:current-page-id state)]
(get-in state [:workspace-data :pages-index page-id])))
(defn id
[label]
(get @idmap label))
(defn get-shape
[state label]
(let [page (current-page state)]
(get-in page [:objects (id label)])))
(defn sample-page
([state] (sample-page state {}))
([state {:keys [id name] :as props
:or {id (uuid/next)
name "page1"}}]
(swap! idmap assoc :page id)
(-> state
(assoc :current-page-id id)
(update :workspace-data
cp/process-changes
[{:type :add-page
:id id
:name name}]))))
(defn sample-shape
([state label type] (sample-shape state type {}))
([state label type props]
(let [page (current-page state)
frame (cph/get-frame (:objects page))
shape (cts/make-shape type {:x 0 :y 0 :width 1 :height 1} props)]
(swap! idmap assoc label (:id shape))
(update state :workspace-data
cp/process-changes
[{:type :add-obj
:id (:id shape)
:page-id (:id page)
:frame-id (:id frame)
:obj shape}]))))
(defn group-shapes
([state label ids] (group-shapes state label ids "Group"))
([state label ids prefix]
(let [page (current-page state)
shapes (dwg/shapes-for-grouping (:objects page) ids)]
(if (empty? shapes)
state
(let [[group changes]
(dwg/prepare-create-group nil (:objects page) (:id page) shapes prefix true)]
(swap! idmap assoc label (:id group))
(update state :workspace-data
cp/process-changes (:redo-changes changes)))))))
(defn make-component
[state instance-label component-label shape-ids]
(let [page (current-page state)
objects (wsh/lookup-page-objects state (:id page))
shapes (dwg/shapes-for-grouping objects shape-ids)
[group component-root changes]
(dwlh/generate-add-component nil
shapes
(:objects page)
(:id page)
current-file-id
true)]
(swap! idmap assoc instance-label (:id group)
component-label (:id component-root))
(update state :workspace-data
cp/process-changes (:redo-changes changes))))
(defn instantiate-component
([state label component-id]
(instantiate-component state label component-id current-file-id))
([state label component-id file-id]
(let [page (current-page state)
libraries (wsh/get-libraries state)
[new-shape changes]
(dwlh/generate-instantiate-component nil
file-id
component-id
(gpt/point 100 100)
page
libraries)]
(swap! idmap assoc label (:id new-shape))
(update state :workspace-data
cp/process-changes (:redo-changes changes)))))
(defn move-to-library
[state label name]
(let [library-id (uuid/next)
data (get state :workspace-data)]
(swap! idmap assoc label library-id)
(-> state
(update :workspace-libraries
assoc library-id {:id library-id
:name name
:data {:id library-id
:components (:components data)}})
(update :workspace-data
assoc :components {} :pages [] :pages-index {}))))
|
4b905056d14ce413537fe1a67b2b45066bd75500f13e2a642c5e0fd92574617f | dongcarl/guix | rdf.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 , 2014 , 2015 < >
Copyright © 2015 , 2016 , 2018 < >
Copyright © 2018–2021 < >
Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 Pjotr Prins < >
Copyright © 2020 < >
Copyright © 2020 >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages rdf)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix download)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (guix build-system waf)
#:use-module (gnu packages)
#:use-module (gnu packages autotools)
#:use-module (gnu packages boost)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages curl)
#:use-module (gnu packages cyrus-sasl)
#:use-module (gnu packages documentation)
#:use-module (gnu packages dbm)
#:use-module (gnu packages gnupg)
#:use-module (gnu packages linux)
#:use-module (gnu packages multiprecision)
#:use-module (gnu packages pcre)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-web)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages qt)
#:use-module (gnu packages time)
#:use-module (gnu packages tls)
#:use-module (gnu packages xml))
(define-public raptor2
(package
(name "raptor2")
(version "2.0.15")
(source (origin
(method url-fetch)
(uri (string-append "/" name
"-" version ".tar.gz"))
(patches
(search-patches "raptor2-heap-overflow.patch"))
(sha256
(base32
"1vc02im4mpc28zxzgli68k6j0dakh0k3s389bm436yvqajxg19xd"))))
(build-system gnu-build-system)
(inputs
`(("curl" ,curl)
("libxml2" ,libxml2)
("libxslt" ,libxslt)
("zlib" ,zlib)))
(arguments
`(#:parallel-tests? #f))
(home-page "/")
(synopsis "RDF syntax library")
(description "Raptor is a C library providing a set of parsers and
serialisers that generate Resource Description Framework (RDF) triples
by parsing syntaxes or serialise the triples into a syntax. The supported
parsing syntaxes are RDF/XML, N-Quads, N-Triples 1.0 and 1.1, TRiG,
Turtle 2008 and 2013, RDFa 1.0 and 1.1, RSS tag soup including all versions
of RSS, Atom 1.0 and 0.3, GRDDL and microformats for HTML, XHTML and
XML. The serialising syntaxes are RDF/XML (regular, abbreviated, XMP),
Turtle 2013, N-Quads, N-Triples 1.1, Atom 1.0, RSS 1.0, GraphViz DOT,
HTML and JSON.")
(license license:lgpl2.1+))) ; or any choice of gpl2+ or asl2.0
(define-public clucene
(package
(name "clucene")
(version "2.3.3.4")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
"clucene-core-unstable/2.3/clucene-core-"
version ".tar.gz"))
(sha256
(base32
"1arffdwivig88kkx685pldr784njm0249k0rb1f1plwavlrw9zfx"))
(patches (search-patches "clucene-pkgconfig.patch"
"clucene-contribs-lib.patch"))))
(build-system cmake-build-system)
(inputs
`(("boost" ,boost) ; could also use bundled copy
("zlib" ,zlib)))
(arguments
`(#:test-target "cl_test"
#:configure-flags '("-DBUILD_CONTRIBS_LIB=ON")
Tests do not compile , as TestIndexSearcher.cpp uses
; undeclared usleep. After fixing this, one needs to run
; "make test" in addition to "make cl_test", then
SimpleTest fails .
; Notice that the library appears to be unmaintained
; with no reaction to bug reports.
(home-page "/")
(synopsis "C text indexing and searching library")
(description "CLucene is a high-performance, scalable, cross platform,
full-featured indexing and searching API. It is a port of the very popular
Java Lucene text search engine API to C++.")
(license license:lgpl2.1)))
(define-public lucene++
(package
(name "lucene++")
(version "3.0.7")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "rel_" version))))
(file-name (git-file-name name version))
(sha256
(base32
"06b37fly6l27zc6kbm93f6khfsv61w792j8xihfagpcm9cfz2zi1"))))
(build-system cmake-build-system)
(arguments
`(#:configure-flags
CXX_FLAGS suggested in a closed issue on github :
;;
(list "-Wno-dev" "-DCMAKE_CXX_FLAGS=-DBOOST_VARIANT_USE_RELAXED_GET_BY_DEFAULT"
;; Install in lib64 break rpath
"-DCMAKE_INSTALL_LIBDIR:PATH=lib")))
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("boost" ,boost)))
(home-page "")
(synopsis "Text search engine")
(description "Lucene++ is an up to date C++ port of the popular Java
Lucene library, a high-performance, full-featured text search engine.")
either asl or lgpl .
(define-public lrdf
(package
(name "lrdf")
(version "0.6.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"00wzkfb8y0aqd519ypz067cq099dpc89w69zw8ln39vl6f9x2pd4"))))
(build-system gnu-build-system)
(arguments
'(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'remove-out-of-tree-references
(lambda _
remove_test depends on an out - of - tree RDF file
(substitute* "examples/Makefile.am"
(("instances_test remove_test") "instances_test")
(("\\$\\(TESTS\\) remove_test") "$(TESTS)"))
#t))
The default bootstrap phase executes autogen.sh , which fails .
(replace 'bootstrap
(lambda _ (invoke "autoreconf" "-vif") #t)))))
(inputs
`(("raptor" ,raptor2)
("cyrus-sasl" ,cyrus-sasl)
("zlib" ,zlib)))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Lightweight RDF library for accessing LADSPA plugin metadata")
(description
"LRDF is a library to make it easy to manipulate RDF files describing
LADSPA plugins. It can also be used for general RDF manipulation. It can
read RDF/XLM and N3 files and export N3 files, and it also has a light
taxonomic inference capability.")
(license license:gpl2)))
(define-public rasqal
(package
(name "rasqal")
(version "0.9.33")
(source (origin
(method url-fetch)
(uri (string-append "/" name
"-" version ".tar.gz"))
(sha256
(base32
"0z6rrwn4jsagvarg8d5zf0j352kjgi33py39jqd29gbhcnncj939"))))
(build-system gnu-build-system)
(native-inputs
`(("perl" ,perl)
("perl-xml-dom" ,perl-xml-dom) ; for the tests
("pkg-config" ,pkg-config)))
(inputs
`(("libgcrypt" ,libgcrypt)
("libxml2" ,libxml2)
("mpfr" ,mpfr)
("pcre" ,pcre)
("util-linux" ,util-linux "lib")))
(propagated-inputs
`(("raptor2" ,raptor2))) ; stipulated by rasqal.pc
(arguments
`(#:parallel-tests? #f
; test failure reported upstream, see
;
#:tests? #f))
(home-page "/")
(synopsis "RDF query library")
(description "Rasqal is a C library that handles Resource Description
Framework (RDF) query language syntaxes, query construction and execution
of queries returning results as bindings, boolean, RDF graphs/triples or
syntaxes. The supported query languages are SPARQL Query 1.0,
SPARQL Query 1.1, SPARQL Update 1.1 (no executing) and the Experimental
SPARQL extensions (LAQRS). Rasqal can write binding query results in the
SPARQL XML, SPARQL JSON, CSV, TSV, HTML, ASCII tables, RDF/XML and
Turtle/N3 and read them in SPARQL XML, RDF/XML and Turtle/N3.")
(license license:lgpl2.1+))) ; or any choice of gpl2+ or asl2.0
(define-public redland
(package
(name "redland")
(version "1.0.17")
(source (origin
(method url-fetch)
(uri (string-append "/" name
"-" version ".tar.gz"))
(sha256
(base32
"109n0kp39p966dpiasad2bb7q66rwbcb9avjvimw28chnpvlf66y"))))
(build-system gnu-build-system)
(native-inputs
`(("perl" ,perl) ; needed for installation
("pkg-config" ,pkg-config)))
(propagated-inputs
in Requires.private field of .pc
(inputs
`(("bdb" ,bdb)))
(home-page "/")
(synopsis "RDF library")
(description "The Redland RDF Library (librdf) provides the RDF API
and triple stores.")
(license license:lgpl2.1+))) ; or any choice of gpl2+ or asl2.0
(define-public serd
(package
(name "serd")
(version "0.30.8")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"11zs53yx40mv62vxsl15mvdh7s17y5v6lgcgahdvzxgnan7w8bk7"))))
(build-system waf-build-system)
(arguments
`(#:tests? #f ; no check target
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-ldflags
(lambda* (#:key outputs #:allow-other-keys)
(setenv "LDFLAGS"
(string-append "-Wl,-rpath="
(assoc-ref outputs "out") "/lib"))
#t)))))
(home-page "/")
(synopsis "Library for RDF syntax supporting Turtle and NTriples")
(description
"Serd is a lightweight C library for RDF syntax which supports reading
and writing Turtle and NTriples. Serd is not intended to be a swiss-army
knife of RDF syntax, but rather is suited to resource limited or performance
critical applications (e.g. converting many gigabytes of NTriples to Turtle),
or situations where a simple reader/writer with minimal dependencies is
ideal (e.g. in LV2 implementations or embedded applications).")
(license license:isc)))
(define-public sord
(package
(name "sord")
(version "0.16.8")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"052y7zllrg0bzyky2rmrrwnnf16p6bk7q40rq9mgm0mzm8p9sa3w"))))
(build-system waf-build-system)
(arguments
`(#:tests? #f ; no check target
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-ldflags
(lambda* (#:key outputs #:allow-other-keys)
(setenv "LDFLAGS"
(string-append "-Wl,-rpath="
(assoc-ref outputs "out") "/lib"))
#t)))))
(inputs
`(("pcre" ,pcre)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(propagated-inputs
`(("serd" ,serd))) ; required by sord-0.pc
(home-page "/")
(synopsis "C library for storing RDF data in memory")
(description
"Sord is a lightweight C library for storing RDF data in memory.")
(license license:isc)))
(define-public python-rdflib
(package
(name "python-rdflib")
(version "4.2.2")
(source
(origin
(method url-fetch)
(uri (pypi-uri "rdflib" version))
(sha256
(base32
"0398c714znnhaa2x7v51b269hk20iz073knq2mvmqp2ma92z27fs"))))
(build-system python-build-system)
(arguments
FIXME : Three test failures . Should be fixed next release .
#:tests? #f))
;; #:phases
;; (modify-phases %standard-phases
;; (replace 'check
;; (lambda _
;; ;; Run tests from the build directory so python3 only
; ; sees the installed 2to3 version .
;; (invoke "nosetests" "--where=./build/src"))))))
(native-inputs
`(("python-nose" ,python-nose)))
(propagated-inputs
`(("python-html5lib" ,python-html5lib)
("python-isodate" ,python-isodate)
("python-pyparsing" ,python-pyparsing)))
(home-page "")
(synopsis "Python RDF library")
(description
"RDFLib is a Python library for working with RDF, a simple yet
powerful language for representing information.")
(license (license:non-copyleft "file"
"See LICENSE in the distribution."))))
(define-public python2-rdflib
(package-with-python2 python-rdflib))
(define-public python-rdflib-jsonld
(package
(name "python-rdflib-jsonld")
(version "0.5.0")
(source
(origin
(method url-fetch)
(uri (pypi-uri "rdflib-jsonld" version))
(sha256
(base32
"1v85f4hdlrrk0l1najmqmm79ijrvcj259kwsrrxiq1q5chr5azag"))))
(build-system python-build-system)
(native-inputs
`(("python-nose" ,python-nose)))
(propagated-inputs
`(("python-rdflib" ,python-rdflib)))
(home-page "-jsonld")
(synopsis "rdflib extension adding JSON-LD parser and serializer")
(description "This package provides an rdflib extension adding JSON-LD
parser and serializer.")
(license license:bsd-3)))
(define-public python-cfgraph
(package
(name "python-cfgraph")
(version "0.2.1")
(source
(origin
(method url-fetch)
(uri (pypi-uri "CFGraph" version))
(sha256
(base32
"0x7yz0lvqb6mkhl5fbml27sppmscgpf8v2ism9jzzf0h982ffzxm"))))
(build-system python-build-system)
(propagated-inputs
`(("python-rdflib" ,python-rdflib)))
(home-page "")
(synopsis "RDF Collections flattener for rdflib")
(description
"This package contains RDF Collections flattener for @code{rdflib}.")
(license license:asl2.0)))
(define-public hdt-cpp
(package
(name "hdt-cpp")
(version "1.3.3")
(source (origin
(method git-fetch)
(uri (git-reference
(url "-cpp")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1vsq80jnix6cy78ayag7v8ajyw7h8dqyad1q6xkf2hzz3skvr34z"))))
(build-system gnu-build-system)
(inputs
`(("serd" ,serd)
("zlib" ,zlib)))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(home-page "-cpp")
(synopsis "C++ implementation of the HDT compression format")
(description "Header Dictionary Triples (HDT) is a compression format for
RDF data that can also be queried for Triple Patterns. This package provides a
C++ library as well as various command-line tools to to work with HDT.")
(license license:lgpl2.1+)))
| null | https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/gnu/packages/rdf.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
or any choice of gpl2+ or asl2.0
could also use bundled copy
undeclared usleep. After fixing this, one needs to run
"make test" in addition to "make cl_test", then
Notice that the library appears to be unmaintained
with no reaction to bug reports.
Install in lib64 break rpath
for the tests
stipulated by rasqal.pc
test failure reported upstream, see
or any choice of gpl2+ or asl2.0
needed for installation
or any choice of gpl2+ or asl2.0
no check target
no check target
required by sord-0.pc
#:phases
(modify-phases %standard-phases
(replace 'check
(lambda _
;; Run tests from the build directory so python3 only
; sees the installed 2to3 version .
(invoke "nosetests" "--where=./build/src")))))) | Copyright © 2013 , 2014 , 2015 < >
Copyright © 2015 , 2016 , 2018 < >
Copyright © 2018–2021 < >
Copyright © 2019 < >
Copyright © 2020 < >
Copyright © 2020 Pjotr Prins < >
Copyright © 2020 < >
Copyright © 2020 >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages rdf)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix download)
#:use-module (guix build-system cmake)
#:use-module (guix build-system gnu)
#:use-module (guix build-system python)
#:use-module (guix build-system waf)
#:use-module (gnu packages)
#:use-module (gnu packages autotools)
#:use-module (gnu packages boost)
#:use-module (gnu packages check)
#:use-module (gnu packages compression)
#:use-module (gnu packages curl)
#:use-module (gnu packages cyrus-sasl)
#:use-module (gnu packages documentation)
#:use-module (gnu packages dbm)
#:use-module (gnu packages gnupg)
#:use-module (gnu packages linux)
#:use-module (gnu packages multiprecision)
#:use-module (gnu packages pcre)
#:use-module (gnu packages perl)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages python)
#:use-module (gnu packages python-web)
#:use-module (gnu packages python-xyz)
#:use-module (gnu packages qt)
#:use-module (gnu packages time)
#:use-module (gnu packages tls)
#:use-module (gnu packages xml))
(define-public raptor2
(package
(name "raptor2")
(version "2.0.15")
(source (origin
(method url-fetch)
(uri (string-append "/" name
"-" version ".tar.gz"))
(patches
(search-patches "raptor2-heap-overflow.patch"))
(sha256
(base32
"1vc02im4mpc28zxzgli68k6j0dakh0k3s389bm436yvqajxg19xd"))))
(build-system gnu-build-system)
(inputs
`(("curl" ,curl)
("libxml2" ,libxml2)
("libxslt" ,libxslt)
("zlib" ,zlib)))
(arguments
`(#:parallel-tests? #f))
(home-page "/")
(synopsis "RDF syntax library")
(description "Raptor is a C library providing a set of parsers and
serialisers that generate Resource Description Framework (RDF) triples
by parsing syntaxes or serialise the triples into a syntax. The supported
parsing syntaxes are RDF/XML, N-Quads, N-Triples 1.0 and 1.1, TRiG,
Turtle 2008 and 2013, RDFa 1.0 and 1.1, RSS tag soup including all versions
of RSS, Atom 1.0 and 0.3, GRDDL and microformats for HTML, XHTML and
XML. The serialising syntaxes are RDF/XML (regular, abbreviated, XMP),
Turtle 2013, N-Quads, N-Triples 1.1, Atom 1.0, RSS 1.0, GraphViz DOT,
HTML and JSON.")
(define-public clucene
(package
(name "clucene")
(version "2.3.3.4")
(source (origin
(method url-fetch)
(uri (string-append "mirror/"
"clucene-core-unstable/2.3/clucene-core-"
version ".tar.gz"))
(sha256
(base32
"1arffdwivig88kkx685pldr784njm0249k0rb1f1plwavlrw9zfx"))
(patches (search-patches "clucene-pkgconfig.patch"
"clucene-contribs-lib.patch"))))
(build-system cmake-build-system)
(inputs
("zlib" ,zlib)))
(arguments
`(#:test-target "cl_test"
#:configure-flags '("-DBUILD_CONTRIBS_LIB=ON")
Tests do not compile , as TestIndexSearcher.cpp uses
SimpleTest fails .
(home-page "/")
(synopsis "C text indexing and searching library")
(description "CLucene is a high-performance, scalable, cross platform,
full-featured indexing and searching API. It is a port of the very popular
Java Lucene text search engine API to C++.")
(license license:lgpl2.1)))
(define-public lucene++
(package
(name "lucene++")
(version "3.0.7")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "rel_" version))))
(file-name (git-file-name name version))
(sha256
(base32
"06b37fly6l27zc6kbm93f6khfsv61w792j8xihfagpcm9cfz2zi1"))))
(build-system cmake-build-system)
(arguments
`(#:configure-flags
CXX_FLAGS suggested in a closed issue on github :
(list "-Wno-dev" "-DCMAKE_CXX_FLAGS=-DBOOST_VARIANT_USE_RELAXED_GET_BY_DEFAULT"
"-DCMAKE_INSTALL_LIBDIR:PATH=lib")))
(native-inputs
`(("pkg-config" ,pkg-config)))
(inputs
`(("boost" ,boost)))
(home-page "")
(synopsis "Text search engine")
(description "Lucene++ is an up to date C++ port of the popular Java
Lucene library, a high-performance, full-featured text search engine.")
either asl or lgpl .
(define-public lrdf
(package
(name "lrdf")
(version "0.6.1")
(source (origin
(method git-fetch)
(uri (git-reference
(url "")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"00wzkfb8y0aqd519ypz067cq099dpc89w69zw8ln39vl6f9x2pd4"))))
(build-system gnu-build-system)
(arguments
'(#:phases
(modify-phases %standard-phases
(add-after 'unpack 'remove-out-of-tree-references
(lambda _
remove_test depends on an out - of - tree RDF file
(substitute* "examples/Makefile.am"
(("instances_test remove_test") "instances_test")
(("\\$\\(TESTS\\) remove_test") "$(TESTS)"))
#t))
The default bootstrap phase executes autogen.sh , which fails .
(replace 'bootstrap
(lambda _ (invoke "autoreconf" "-vif") #t)))))
(inputs
`(("raptor" ,raptor2)
("cyrus-sasl" ,cyrus-sasl)
("zlib" ,zlib)))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(home-page "")
(synopsis "Lightweight RDF library for accessing LADSPA plugin metadata")
(description
"LRDF is a library to make it easy to manipulate RDF files describing
LADSPA plugins. It can also be used for general RDF manipulation. It can
read RDF/XLM and N3 files and export N3 files, and it also has a light
taxonomic inference capability.")
(license license:gpl2)))
(define-public rasqal
(package
(name "rasqal")
(version "0.9.33")
(source (origin
(method url-fetch)
(uri (string-append "/" name
"-" version ".tar.gz"))
(sha256
(base32
"0z6rrwn4jsagvarg8d5zf0j352kjgi33py39jqd29gbhcnncj939"))))
(build-system gnu-build-system)
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)))
(inputs
`(("libgcrypt" ,libgcrypt)
("libxml2" ,libxml2)
("mpfr" ,mpfr)
("pcre" ,pcre)
("util-linux" ,util-linux "lib")))
(propagated-inputs
(arguments
`(#:parallel-tests? #f
#:tests? #f))
(home-page "/")
(synopsis "RDF query library")
(description "Rasqal is a C library that handles Resource Description
Framework (RDF) query language syntaxes, query construction and execution
of queries returning results as bindings, boolean, RDF graphs/triples or
syntaxes. The supported query languages are SPARQL Query 1.0,
SPARQL Query 1.1, SPARQL Update 1.1 (no executing) and the Experimental
SPARQL extensions (LAQRS). Rasqal can write binding query results in the
SPARQL XML, SPARQL JSON, CSV, TSV, HTML, ASCII tables, RDF/XML and
Turtle/N3 and read them in SPARQL XML, RDF/XML and Turtle/N3.")
(define-public redland
(package
(name "redland")
(version "1.0.17")
(source (origin
(method url-fetch)
(uri (string-append "/" name
"-" version ".tar.gz"))
(sha256
(base32
"109n0kp39p966dpiasad2bb7q66rwbcb9avjvimw28chnpvlf66y"))))
(build-system gnu-build-system)
(native-inputs
("pkg-config" ,pkg-config)))
(propagated-inputs
in Requires.private field of .pc
(inputs
`(("bdb" ,bdb)))
(home-page "/")
(synopsis "RDF library")
(description "The Redland RDF Library (librdf) provides the RDF API
and triple stores.")
(define-public serd
(package
(name "serd")
(version "0.30.8")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"11zs53yx40mv62vxsl15mvdh7s17y5v6lgcgahdvzxgnan7w8bk7"))))
(build-system waf-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-ldflags
(lambda* (#:key outputs #:allow-other-keys)
(setenv "LDFLAGS"
(string-append "-Wl,-rpath="
(assoc-ref outputs "out") "/lib"))
#t)))))
(home-page "/")
(synopsis "Library for RDF syntax supporting Turtle and NTriples")
(description
"Serd is a lightweight C library for RDF syntax which supports reading
and writing Turtle and NTriples. Serd is not intended to be a swiss-army
knife of RDF syntax, but rather is suited to resource limited or performance
critical applications (e.g. converting many gigabytes of NTriples to Turtle),
or situations where a simple reader/writer with minimal dependencies is
ideal (e.g. in LV2 implementations or embedded applications).")
(license license:isc)))
(define-public sord
(package
(name "sord")
(version "0.16.8")
(source (origin
(method url-fetch)
(uri (string-append "-"
version ".tar.bz2"))
(sha256
(base32
"052y7zllrg0bzyky2rmrrwnnf16p6bk7q40rq9mgm0mzm8p9sa3w"))))
(build-system waf-build-system)
(arguments
#:phases
(modify-phases %standard-phases
(add-before
'configure 'set-ldflags
(lambda* (#:key outputs #:allow-other-keys)
(setenv "LDFLAGS"
(string-append "-Wl,-rpath="
(assoc-ref outputs "out") "/lib"))
#t)))))
(inputs
`(("pcre" ,pcre)))
(native-inputs
`(("pkg-config" ,pkg-config)))
(propagated-inputs
(home-page "/")
(synopsis "C library for storing RDF data in memory")
(description
"Sord is a lightweight C library for storing RDF data in memory.")
(license license:isc)))
(define-public python-rdflib
(package
(name "python-rdflib")
(version "4.2.2")
(source
(origin
(method url-fetch)
(uri (pypi-uri "rdflib" version))
(sha256
(base32
"0398c714znnhaa2x7v51b269hk20iz073knq2mvmqp2ma92z27fs"))))
(build-system python-build-system)
(arguments
FIXME : Three test failures . Should be fixed next release .
#:tests? #f))
(native-inputs
`(("python-nose" ,python-nose)))
(propagated-inputs
`(("python-html5lib" ,python-html5lib)
("python-isodate" ,python-isodate)
("python-pyparsing" ,python-pyparsing)))
(home-page "")
(synopsis "Python RDF library")
(description
"RDFLib is a Python library for working with RDF, a simple yet
powerful language for representing information.")
(license (license:non-copyleft "file"
"See LICENSE in the distribution."))))
(define-public python2-rdflib
(package-with-python2 python-rdflib))
(define-public python-rdflib-jsonld
(package
(name "python-rdflib-jsonld")
(version "0.5.0")
(source
(origin
(method url-fetch)
(uri (pypi-uri "rdflib-jsonld" version))
(sha256
(base32
"1v85f4hdlrrk0l1najmqmm79ijrvcj259kwsrrxiq1q5chr5azag"))))
(build-system python-build-system)
(native-inputs
`(("python-nose" ,python-nose)))
(propagated-inputs
`(("python-rdflib" ,python-rdflib)))
(home-page "-jsonld")
(synopsis "rdflib extension adding JSON-LD parser and serializer")
(description "This package provides an rdflib extension adding JSON-LD
parser and serializer.")
(license license:bsd-3)))
(define-public python-cfgraph
(package
(name "python-cfgraph")
(version "0.2.1")
(source
(origin
(method url-fetch)
(uri (pypi-uri "CFGraph" version))
(sha256
(base32
"0x7yz0lvqb6mkhl5fbml27sppmscgpf8v2ism9jzzf0h982ffzxm"))))
(build-system python-build-system)
(propagated-inputs
`(("python-rdflib" ,python-rdflib)))
(home-page "")
(synopsis "RDF Collections flattener for rdflib")
(description
"This package contains RDF Collections flattener for @code{rdflib}.")
(license license:asl2.0)))
(define-public hdt-cpp
(package
(name "hdt-cpp")
(version "1.3.3")
(source (origin
(method git-fetch)
(uri (git-reference
(url "-cpp")
(commit (string-append "v" version))))
(file-name (git-file-name name version))
(sha256
(base32
"1vsq80jnix6cy78ayag7v8ajyw7h8dqyad1q6xkf2hzz3skvr34z"))))
(build-system gnu-build-system)
(inputs
`(("serd" ,serd)
("zlib" ,zlib)))
(native-inputs
`(("autoconf" ,autoconf)
("automake" ,automake)
("libtool" ,libtool)
("pkg-config" ,pkg-config)))
(home-page "-cpp")
(synopsis "C++ implementation of the HDT compression format")
(description "Header Dictionary Triples (HDT) is a compression format for
RDF data that can also be queried for Triple Patterns. This package provides a
C++ library as well as various command-line tools to to work with HDT.")
(license license:lgpl2.1+)))
|
166e62b2774881939d770784f3876c136ef9fc31f911f98602f67d8033ee8bce | haskell/haskell-language-server | PunShadowing.hs | data Bar = Bar { ax :: Int, bax :: Bool }
bar :: () -> Bar -> Int
bar ax x = _
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/PunShadowing.hs | haskell | data Bar = Bar { ax :: Int, bax :: Bool }
bar :: () -> Bar -> Int
bar ax x = _
|
|
4fdc39e3e6ca9da7168f4b02402758e7ac40bc5a763f7b16c8993487f961f282 | tschady/advent-of-code | d22_test.clj | (ns aoc.2021.d22-test
(:require [aoc.2021.d22 :as sut]
[clojure.test :refer :all]))
(deftest challenges
(is (= 527915 (sut/part-1 sut/input)))
(is (= 1218645427221987 (sut/part-2 sut/input))))
| null | https://raw.githubusercontent.com/tschady/advent-of-code/4928cfac176a76292ae8c5823205dc6cb028200e/test/aoc/2021/d22_test.clj | clojure | (ns aoc.2021.d22-test
(:require [aoc.2021.d22 :as sut]
[clojure.test :refer :all]))
(deftest challenges
(is (= 527915 (sut/part-1 sut/input)))
(is (= 1218645427221987 (sut/part-2 sut/input))))
|
|
c66f19516d6a9d081c8307b758c85aa2e5fd5979b53813d057b675754bc2bf07 | Technologicat/spicy | example_sexp.rkt | #lang spicy
(define (foldl f x lst)
(match lst
('() x)
((cons a l) (foldl f (f a x) l))))
(define (foldr f x lst)
(match lst
('() x)
((cons a l) (f a (foldr f x l)))))
(define reverse
(foldl cons empty))
(define (append a b)
(foldr cons b a))
(define (append* . lsts)
(foldr append empty lsts))
(define sum
(foldl + 0))
(define product
(foldl * 1))
(define (map f)
(foldr (compose cons f) empty))
(module+ main
(define a '(1 2))
(define b '(3 4))
(define c '(5 6 7))
(define (f x) (* x x))
(append a b)
(reverse c)
(sum a)
(product b)
(product (append a b))
(append* a b c)
(map f c))
| null | https://raw.githubusercontent.com/Technologicat/spicy/f0c8b44a5719fb7fffc63d25547e0cea35f2f0de/example_sexp.rkt | racket | #lang spicy
(define (foldl f x lst)
(match lst
('() x)
((cons a l) (foldl f (f a x) l))))
(define (foldr f x lst)
(match lst
('() x)
((cons a l) (f a (foldr f x l)))))
(define reverse
(foldl cons empty))
(define (append a b)
(foldr cons b a))
(define (append* . lsts)
(foldr append empty lsts))
(define sum
(foldl + 0))
(define product
(foldl * 1))
(define (map f)
(foldr (compose cons f) empty))
(module+ main
(define a '(1 2))
(define b '(3 4))
(define c '(5 6 7))
(define (f x) (* x x))
(append a b)
(reverse c)
(sum a)
(product b)
(product (append a b))
(append* a b c)
(map f c))
|
|
39afa5aaf40914afeda9e5ef83d091219495d77933ca8078f1ad463e35d5a68e | kitten/bs-flow-parser | loc.mli | *
* 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.
*)
type position = { line : int; column : int; } [@@deriving show]
type t = { source : File_key.t option; start : position; _end : position; } [@@deriving show]
val none : t
val btwn : t -> t -> t
val btwn_exclusive : t -> t -> t
val char_before : t -> t
val first_char: t -> t
val contains : t -> t -> bool
val lines_intersect : t -> t -> bool
val pos_cmp : position -> position -> int
val span_compare : t -> t -> int
val compare : t -> t -> int
val equal : t -> t -> bool
val to_string : ?include_source:bool -> t -> string
val source : t -> File_key.t option
(* filename, line, column. produces a Loc.t at the given location *)
val make: File_key.t -> int -> int -> t
(* Produces a location at the start of the input location *)
val start_loc : t -> t
(* Produces a location at the end of the input location *)
val end_loc : t -> t
| null | https://raw.githubusercontent.com/kitten/bs-flow-parser/00630c06016b51a7040ef4160ed2999cd208babd/src/loc.mli | ocaml | filename, line, column. produces a Loc.t at the given location
Produces a location at the start of the input location
Produces a location at the end of the input location | *
* 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.
*)
type position = { line : int; column : int; } [@@deriving show]
type t = { source : File_key.t option; start : position; _end : position; } [@@deriving show]
val none : t
val btwn : t -> t -> t
val btwn_exclusive : t -> t -> t
val char_before : t -> t
val first_char: t -> t
val contains : t -> t -> bool
val lines_intersect : t -> t -> bool
val pos_cmp : position -> position -> int
val span_compare : t -> t -> int
val compare : t -> t -> int
val equal : t -> t -> bool
val to_string : ?include_source:bool -> t -> string
val source : t -> File_key.t option
val make: File_key.t -> int -> int -> t
val start_loc : t -> t
val end_loc : t -> t
|
955a029f1fccf010a65934dd8be2af8e8c9c56304ddb0760b818936fecc85f3e | lilactown/punk | jvm.clj | (ns punk.adapter.jvm
(:require
[aleph.http :as ah]
[clojure.edn :as ce]
[compojure.core :as cc]
[compojure.route :as cr]
[frame.core :as fc]
[manifold.stream :as ms]
[manifold.deferred :as md]
[manifold.bus :as mb]
[punk.core :as pc]
[ring.middleware.params :as rmp]))
(def port
9876)
(defonce server
(atom nil))
(def default-script
["@v0.0.7/ui/dist/js/main.js"
"@v0.0.7/ui/dist/js/remote.js"]
;; ":8701/main.js"
)
(def default-css
["+Sans+Pro"
"@v0.0.7/ui/dist/css/grid-layout.css"
"@v0.0.7/ui/dist/css/resizable.css"
"@v0.0.7/ui/dist/css/punk.css"])
(defn css-tag [href]
(str "<link href=\"" href "\" rel=\"stylesheet\" />"))
(defn script-tag [src]
(str "<script src=\"" src "\" type=\"text/javascript\"></script>"))
(def page
(str "<html>"
" <head>"
"<style>body { margin: 0 }</style>"
(apply str
(map css-tag default-css))
" </head>"
"<body>"
(apply str (map script-tag default-script))
" <script>punk.ui.remote.start_BANG_()</script>"
"</body>"
"</html>"))
;; for alternative styles, see:
;; / \
;; src/aleph/examples/websocket.clj
(defn ws-handler
[req]
(if-let [socket (try
@(ah/websocket-connection req)
(catch Exception e
nil))]
(do
(fc/reg-fx
pc/frame :emit
(fn emit [v]
(ms/put! socket (pr-str v))))
(md/loop []
(let [msg @(ms/take! socket)
read-value (ce/read-string
{;; XXX: fill in and uncomment as desired
#_#_:readers {}
:default tagged-literal}
msg)]
(pc/dispatch read-value)
(md/recur))))
{:status 400
:headers {"Content-Type" "application/text"}
:body "Unexpected request"}))
(def handler
(rmp/wrap-params
(cc/routes
(cc/GET "/" [] page)
(cc/GET "/ws" [] ws-handler)
(cr/not-found "Not found"))))
(defn start
[]
(let [hs (ah/start-server handler
{:port port})]
(reset! server hs)
;;(pc/remove-taps!) ; XXX: called by add-taps!
(pc/add-taps!)))
(defn stop
[]
;; XXX: not working so well yet...
;;
#_(.close @server))
(comment
(defn send-msg
[msg]
(let [conn @(ah/websocket-client
(str "ws:" port "/ws"))]
(ms/put! conn msg)))
)
| null | https://raw.githubusercontent.com/lilactown/punk/0c6e529429837c00958d41e09fd672f49778dedf/adapter-jvm/src/punk/adapter/jvm.clj | clojure | ":8701/main.js"
for alternative styles, see:
/ \
src/aleph/examples/websocket.clj
XXX: fill in and uncomment as desired
(pc/remove-taps!) ; XXX: called by add-taps!
XXX: not working so well yet...
| (ns punk.adapter.jvm
(:require
[aleph.http :as ah]
[clojure.edn :as ce]
[compojure.core :as cc]
[compojure.route :as cr]
[frame.core :as fc]
[manifold.stream :as ms]
[manifold.deferred :as md]
[manifold.bus :as mb]
[punk.core :as pc]
[ring.middleware.params :as rmp]))
(def port
9876)
(defonce server
(atom nil))
(def default-script
["@v0.0.7/ui/dist/js/main.js"
"@v0.0.7/ui/dist/js/remote.js"]
)
(def default-css
["+Sans+Pro"
"@v0.0.7/ui/dist/css/grid-layout.css"
"@v0.0.7/ui/dist/css/resizable.css"
"@v0.0.7/ui/dist/css/punk.css"])
(defn css-tag [href]
(str "<link href=\"" href "\" rel=\"stylesheet\" />"))
(defn script-tag [src]
(str "<script src=\"" src "\" type=\"text/javascript\"></script>"))
(def page
(str "<html>"
" <head>"
"<style>body { margin: 0 }</style>"
(apply str
(map css-tag default-css))
" </head>"
"<body>"
(apply str (map script-tag default-script))
" <script>punk.ui.remote.start_BANG_()</script>"
"</body>"
"</html>"))
(defn ws-handler
[req]
(if-let [socket (try
@(ah/websocket-connection req)
(catch Exception e
nil))]
(do
(fc/reg-fx
pc/frame :emit
(fn emit [v]
(ms/put! socket (pr-str v))))
(md/loop []
(let [msg @(ms/take! socket)
read-value (ce/read-string
#_#_:readers {}
:default tagged-literal}
msg)]
(pc/dispatch read-value)
(md/recur))))
{:status 400
:headers {"Content-Type" "application/text"}
:body "Unexpected request"}))
(def handler
(rmp/wrap-params
(cc/routes
(cc/GET "/" [] page)
(cc/GET "/ws" [] ws-handler)
(cr/not-found "Not found"))))
(defn start
[]
(let [hs (ah/start-server handler
{:port port})]
(reset! server hs)
(pc/add-taps!)))
(defn stop
[]
#_(.close @server))
(comment
(defn send-msg
[msg]
(let [conn @(ah/websocket-client
(str "ws:" port "/ws"))]
(ms/put! conn msg)))
)
|
eab0d6dc4e52a0b7e769218948827cffc97f6d6cba15c608084a6d8d5672cdd5 | cl-axon/cl-aima | mdp.lisp | Definitions for Markov decision processes ( MDPs ) .
An MDP is defined by initial state , transition model , rewards , and
;;; distinguished terminal states. Model and rewards are hash tables
;;; index by state (after application of hash-key function).
;;; The entries in the model are alists keyed by action; each action is
;;; associated with an action model: basically a list of transitions.
Markov chains ( i.e. , stochastic processes with no distinct agent )
can be defined by allowing only a no - op action in the MDP .
(defstruct mdp
initial-state ;; The initial state for the problem
(model (make-hash-table :test #'equal)) ;; Describes transition probabilities
(rewards (make-hash-table :test #'equal)) ;; Rewards for each state
(terminal-states nil) ;; List of terminal states
(hash-key #'identity) ;; To convert states into hash keys
name) ;; String, identifies the problem
(defstruct (mdp-action-model (:type list))
(transitions nil)
(times-executed 0))
(defstruct (transition (:type list))
destination
probability
(times-achieved 0))
(defun action-model (a s M)
(cdr (assoc a (gethash s M) :test #'eq)))
(defun transitions (a s M)
"Returns the transitions resulting from executing
action a in state s according to model M."
(mdp-action-model-transitions (action-model a s M)))
(defun actions (s M)
"Returns the list of actions feasible in state s according to model M."
(mapcar #'car (gethash s M)))
| null | https://raw.githubusercontent.com/cl-axon/cl-aima/1e6915fa9f3e5f2c6fd75952d674ebec53558d04/uncertainty/domains/mdp.lisp | lisp | distinguished terminal states. Model and rewards are hash tables
index by state (after application of hash-key function).
The entries in the model are alists keyed by action; each action is
associated with an action model: basically a list of transitions.
The initial state for the problem
Describes transition probabilities
Rewards for each state
List of terminal states
To convert states into hash keys
String, identifies the problem | Definitions for Markov decision processes ( MDPs ) .
An MDP is defined by initial state , transition model , rewards , and
Markov chains ( i.e. , stochastic processes with no distinct agent )
can be defined by allowing only a no - op action in the MDP .
(defstruct mdp
(defstruct (mdp-action-model (:type list))
(transitions nil)
(times-executed 0))
(defstruct (transition (:type list))
destination
probability
(times-achieved 0))
(defun action-model (a s M)
(cdr (assoc a (gethash s M) :test #'eq)))
(defun transitions (a s M)
"Returns the transitions resulting from executing
action a in state s according to model M."
(mdp-action-model-transitions (action-model a s M)))
(defun actions (s M)
"Returns the list of actions feasible in state s according to model M."
(mapcar #'car (gethash s M)))
|
a15ba949f27d37f3ceda1983a1713ea3522dd5e5d7cebfff46b74725ff53b4dc | ChildsplayOSU/bogl | Syntax.hs | # LANGUAGE DeriveGeneric #
|
Module : Language . Syntax
Description : BoGL Syntax
Copyright : ( c )
License : BSD-3
BoGL language AST . This slightly deviates from the specified syntax in spots .
Module : Language.Syntax
Description : BoGL Syntax
Copyright : (c)
License : BSD-3
BoGL language AST. This slightly deviates from the specified syntax in spots.
-}
module Language.Syntax where
import Language.Types
import Data.List
import GHC.Generics
import Utils.String
-- | Names of games, signatures, etc.
type Name = String
-- | An unparsed expression
type ExprS = String
-- | A type definition or synonym
type TypeDef = (Name, Xtype)
-- | Game datatype
data Game a = Game
{
name :: Name -- ^ The name of the game
, board :: BoardDef -- ^ Size and type of the board
, input :: InputDef -- ^ Type of input
, defns :: [ValDef a] -- ^ List of value definitions
, tdefs :: [TypeDef] -- ^ Type definitions and type synonyms
}
deriving (Generic)
-- | Signatures are a product of name and type.
data Signature = Sig Name Type
deriving (Eq)
-- | Parameters are lists of 'Name'
data Parlist = Pars [Name]
deriving (Eq, Generic)
-- | Top level values are signatures paired with either an ordinary Equation or a list of Board Equations
data ValDef a = Val Signature (Equation a) a -- ^ Regular Value
| BVal Signature [BoardEq a] a -- ^ Board value
deriving (Eq, Generic)
instance Functor ValDef where
fmap f (Val s e a) = Val s (fmap f e) (f a)
fmap f (BVal s e a) = BVal s ((fmap . fmap) f e) (f a)
-- | Equations
^ Value equations ( a mapping from ' Name ' to )
| Feq Name Parlist (Expr a) -- ^ Function equations
deriving (Eq, Generic)
instance Functor Equation where
fmap f (Veq n e) = Veq n (fmap f e)
fmap f (Feq n ps e) = Feq n ps (fmap f e)
-- | Board equations are used to set positions on the board to an expression
data BoardEq a = PosDef
{
boardEqName :: Name,
xpos :: Pos,
ypos :: Pos,
boardExpr :: (Expr a)
}
deriving (Eq, Generic)
instance Functor BoardEq where
fmap f (PosDef n p1 p2 e) = PosDef n p1 p2 (fmap f e)
-- | Types of individual positions for the x and y in a board equation
data Pos = Index Int -- ^ Singular index as
| ForAll Name -- ^ All indices with a given name
deriving (Eq, Generic)
instance Ord Pos where
compare (Index i) (Index j) = compare i j
compare (ForAll _) (Index i) = if i <= 0 then GT else LT
compare ix@(Index _) f@(ForAll _) = compare f ix
compare (ForAll _) (ForAll _) = EQ
-- | Expressions
data Expr a = I Int -- ^ Integer
| S Name -- ^ Symbol
| B Bool -- ^ Boolean
| Ref Name -- ^ Reference to a variable
^ Tuple of ' '
| App Name (Expr a) -- ^ Function application with argument tuple
| Binop Op (Expr a) (Expr a) -- ^ Binary operation
| Let Name (Expr a) (Expr a) -- ^ Let binding
| While (Expr a) (Expr a) [Name] (Expr a) -- ^ While loop
| If (Expr a) (Expr a) (Expr a) -- ^ Conditional
| Annotation a (Expr a) -- ^ Parameterized by the type of an annotation
deriving (Eq, Generic)
-- Description of arguments to While:
-- condition, body, names of arguments from the wrapper function,
-- expressions which reference the names.
-- the last Expr can always be constructed from the [Name], but it makes the code cleaner to do that
-- only once while parsing
-- | this is just "deriving functor"
instance Functor Expr where
fmap _ (B x) = (B x)
fmap f (Annotation a e) = Annotation (f a) (fmap f e)
fmap f (While e1 e2 ns e3) = While (fmap f e1) (fmap f e2) ns (fmap f e3)
fmap f (If e1 e2 e3) = If (fmap f e1) (fmap f e2) (fmap f e3)
fmap f (Let n e1 e2) = Let n (fmap f e1) (fmap f e2)
fmap f (Binop o e1 e2) = Binop o (fmap f e1) (fmap f e2)
fmap f (App n es) = App n (fmap f es)
fmap f (Tuple xs) = Tuple (fmap (fmap f) xs)
fmap _ (Ref n) = (Ref n)
fmap _ (S n) = (S n)
fmap _ (I x) = (I x)
-- | Binary operations
data Op = Plus -- ^ Addition (+)
| Minus -- ^ Subtraction (-)
| Times -- ^ Multiplication (*)
| Div -- ^ Division (/)
| Mod -- ^ Modulus (%)
| Less -- ^ Less than comparison (<)
| Leq -- ^ Less than equal to comparison (<=)
| Equiv -- ^ Equivalent comparison (==)
| NotEquiv -- ^ Not equivalent comparison (/=)
| Geq -- ^ Greater than equal to comparison (>=)
| Greater -- ^ Greater than comparison (>)
| Get -- ^ Gets contents from a position on a board (!)
deriving (Eq, Generic)
Note : the three predicates below are used in the type checker
-- | Check if a binary operator is arithmetic
arithmetic :: Op -> Bool
arithmetic o = o `elem` [Plus, Minus, Times, Div, Mod]
-- | Check if a binary operator is relational (excluding == and /=)
relational :: Op -> Bool
relational o = o `elem` [Less, Leq, Geq, Greater]
-- | Check if a binary operator is == or /=
equiv :: Op -> Bool
equiv o = o `elem` [Equiv, NotEquiv]
| an expression
deAnnotate :: Expr a -> Expr a
deAnnotate (Annotation _ e) = e
deAnnotate x = x
-- | Clear the annotation from an expression
clearAnn :: Expr a -> Expr ()
clearAnn = (() <$)
-- | Clear the annotation from an equation
clearAnnEq :: Equation a -> Equation ()
clearAnnEq = (() <$)
| Get the identifier from a ValDef
ident :: (ValDef a) -> Name
ident (Val (Sig n _) _ _) = n
ident (BVal (Sig n _) _ _) = n
instance Show (BoardEq a) where
show (PosDef n x y e) = n ++ "(" ++ show x ++ ", " ++ show y ++ ")" ++ " = " ++ show e
instance Show Pos where
show (Index i) = show i
show (ForAll n) = n
instance Show (Equation a) where
show (Veq n e) = n ++ " = " ++ show e
show (Feq n pl e) = n ++ show pl ++ " = " ++ show e
instance Show (Expr a) where
show (Annotation _ e) = show e -- can refactor
show (I i) = show i
show (S s) = s
show (B b) = show b
show (Ref n) = n
show (Tuple e) = showAsTuple (map show e)
show (App n e@(Tuple _)) = n ++ show e
show (App n e) = n ++ parenthesize (show e)
show (Binop o e1 e2) = show e1 ++ show o ++ show e2
show (Let n e1 e2) = "let " ++ n ++ " = " ++ show e1 ++ " in " ++ show e2
show (If e1 e2 e3) = "if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show e3
show (While c b _ _) = "while " ++ show c ++ " do " ++ show b
instance Show (ValDef a) where
show (Val s e _) = show s ++ "\n" ++ show e
show (BVal s e _) = show s ++ "\n" ++ show e
instance Show Parlist where
show (Pars xs) = showAsTuple xs
instance Show Signature where
show (Sig n t) = n ++ " : " ++ show t
showDef :: TypeDef -> String
showDef (n, t) = "type " ++ n ++ " = " ++ show t
-- | TODO! show typedefs
instance Show (Game a) where
show (Game n b i vs ds) = "Game : " ++ n ++ "\n\n"
++ intercalate ("\n") (map showDef ds) ++ "\n"
++ show b ++ "\n"
++ show i ++ "\n\n"
++ intercalate ("\n\n") (map show vs)
instance Show Op where
show Plus = " + "
show Minus = " - "
show Times = " * "
show Div = " / "
show Mod = " % "
show Less = " < "
show Leq = " <= "
show Equiv = " == "
show NotEquiv = " /= "
show Geq = " >= "
show Greater = " > "
show Get = " ! "
| null | https://raw.githubusercontent.com/ChildsplayOSU/bogl/8c649689bf26543be1a7ec72787b9c013ecb754f/src/Language/Syntax.hs | haskell | | Names of games, signatures, etc.
| An unparsed expression
| A type definition or synonym
| Game datatype
^ The name of the game
^ Size and type of the board
^ Type of input
^ List of value definitions
^ Type definitions and type synonyms
| Signatures are a product of name and type.
| Parameters are lists of 'Name'
| Top level values are signatures paired with either an ordinary Equation or a list of Board Equations
^ Regular Value
^ Board value
| Equations
^ Function equations
| Board equations are used to set positions on the board to an expression
| Types of individual positions for the x and y in a board equation
^ Singular index as
^ All indices with a given name
| Expressions
^ Integer
^ Symbol
^ Boolean
^ Reference to a variable
^ Function application with argument tuple
^ Binary operation
^ Let binding
^ While loop
^ Conditional
^ Parameterized by the type of an annotation
Description of arguments to While:
condition, body, names of arguments from the wrapper function,
expressions which reference the names.
the last Expr can always be constructed from the [Name], but it makes the code cleaner to do that
only once while parsing
| this is just "deriving functor"
| Binary operations
^ Addition (+)
^ Subtraction (-)
^ Multiplication (*)
^ Division (/)
^ Modulus (%)
^ Less than comparison (<)
^ Less than equal to comparison (<=)
^ Equivalent comparison (==)
^ Not equivalent comparison (/=)
^ Greater than equal to comparison (>=)
^ Greater than comparison (>)
^ Gets contents from a position on a board (!)
| Check if a binary operator is arithmetic
| Check if a binary operator is relational (excluding == and /=)
| Check if a binary operator is == or /=
| Clear the annotation from an expression
| Clear the annotation from an equation
can refactor
| TODO! show typedefs | # LANGUAGE DeriveGeneric #
|
Module : Language . Syntax
Description : BoGL Syntax
Copyright : ( c )
License : BSD-3
BoGL language AST . This slightly deviates from the specified syntax in spots .
Module : Language.Syntax
Description : BoGL Syntax
Copyright : (c)
License : BSD-3
BoGL language AST. This slightly deviates from the specified syntax in spots.
-}
module Language.Syntax where
import Language.Types
import Data.List
import GHC.Generics
import Utils.String
type Name = String
type ExprS = String
type TypeDef = (Name, Xtype)
data Game a = Game
{
}
deriving (Generic)
data Signature = Sig Name Type
deriving (Eq)
data Parlist = Pars [Name]
deriving (Eq, Generic)
deriving (Eq, Generic)
instance Functor ValDef where
fmap f (Val s e a) = Val s (fmap f e) (f a)
fmap f (BVal s e a) = BVal s ((fmap . fmap) f e) (f a)
^ Value equations ( a mapping from ' Name ' to )
deriving (Eq, Generic)
instance Functor Equation where
fmap f (Veq n e) = Veq n (fmap f e)
fmap f (Feq n ps e) = Feq n ps (fmap f e)
data BoardEq a = PosDef
{
boardEqName :: Name,
xpos :: Pos,
ypos :: Pos,
boardExpr :: (Expr a)
}
deriving (Eq, Generic)
instance Functor BoardEq where
fmap f (PosDef n p1 p2 e) = PosDef n p1 p2 (fmap f e)
deriving (Eq, Generic)
instance Ord Pos where
compare (Index i) (Index j) = compare i j
compare (ForAll _) (Index i) = if i <= 0 then GT else LT
compare ix@(Index _) f@(ForAll _) = compare f ix
compare (ForAll _) (ForAll _) = EQ
^ Tuple of ' '
deriving (Eq, Generic)
instance Functor Expr where
fmap _ (B x) = (B x)
fmap f (Annotation a e) = Annotation (f a) (fmap f e)
fmap f (While e1 e2 ns e3) = While (fmap f e1) (fmap f e2) ns (fmap f e3)
fmap f (If e1 e2 e3) = If (fmap f e1) (fmap f e2) (fmap f e3)
fmap f (Let n e1 e2) = Let n (fmap f e1) (fmap f e2)
fmap f (Binop o e1 e2) = Binop o (fmap f e1) (fmap f e2)
fmap f (App n es) = App n (fmap f es)
fmap f (Tuple xs) = Tuple (fmap (fmap f) xs)
fmap _ (Ref n) = (Ref n)
fmap _ (S n) = (S n)
fmap _ (I x) = (I x)
deriving (Eq, Generic)
Note : the three predicates below are used in the type checker
arithmetic :: Op -> Bool
arithmetic o = o `elem` [Plus, Minus, Times, Div, Mod]
relational :: Op -> Bool
relational o = o `elem` [Less, Leq, Geq, Greater]
equiv :: Op -> Bool
equiv o = o `elem` [Equiv, NotEquiv]
| an expression
deAnnotate :: Expr a -> Expr a
deAnnotate (Annotation _ e) = e
deAnnotate x = x
clearAnn :: Expr a -> Expr ()
clearAnn = (() <$)
clearAnnEq :: Equation a -> Equation ()
clearAnnEq = (() <$)
| Get the identifier from a ValDef
ident :: (ValDef a) -> Name
ident (Val (Sig n _) _ _) = n
ident (BVal (Sig n _) _ _) = n
instance Show (BoardEq a) where
show (PosDef n x y e) = n ++ "(" ++ show x ++ ", " ++ show y ++ ")" ++ " = " ++ show e
instance Show Pos where
show (Index i) = show i
show (ForAll n) = n
instance Show (Equation a) where
show (Veq n e) = n ++ " = " ++ show e
show (Feq n pl e) = n ++ show pl ++ " = " ++ show e
instance Show (Expr a) where
show (I i) = show i
show (S s) = s
show (B b) = show b
show (Ref n) = n
show (Tuple e) = showAsTuple (map show e)
show (App n e@(Tuple _)) = n ++ show e
show (App n e) = n ++ parenthesize (show e)
show (Binop o e1 e2) = show e1 ++ show o ++ show e2
show (Let n e1 e2) = "let " ++ n ++ " = " ++ show e1 ++ " in " ++ show e2
show (If e1 e2 e3) = "if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show e3
show (While c b _ _) = "while " ++ show c ++ " do " ++ show b
instance Show (ValDef a) where
show (Val s e _) = show s ++ "\n" ++ show e
show (BVal s e _) = show s ++ "\n" ++ show e
instance Show Parlist where
show (Pars xs) = showAsTuple xs
instance Show Signature where
show (Sig n t) = n ++ " : " ++ show t
showDef :: TypeDef -> String
showDef (n, t) = "type " ++ n ++ " = " ++ show t
instance Show (Game a) where
show (Game n b i vs ds) = "Game : " ++ n ++ "\n\n"
++ intercalate ("\n") (map showDef ds) ++ "\n"
++ show b ++ "\n"
++ show i ++ "\n\n"
++ intercalate ("\n\n") (map show vs)
instance Show Op where
show Plus = " + "
show Minus = " - "
show Times = " * "
show Div = " / "
show Mod = " % "
show Less = " < "
show Leq = " <= "
show Equiv = " == "
show NotEquiv = " /= "
show Geq = " >= "
show Greater = " > "
show Get = " ! "
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.