_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 |
|---|---|---|---|---|---|---|---|---|
b8142cc06034b3795c0599b561b191d8c4ca80a3854d0dcccd846b033f69f39c | hamler-lang/hamler | RPC.erl | %%---------------------------------------------------------------------------
%% |
%% Module : RPC
Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd.
%% License : BSD-style (see the LICENSE file)
%%
Maintainer : ,
,
%% Stability : experimental
%% Portability : portable
%%
%% The RPC FFI module.
%%
%%---------------------------------------------------------------------------
-module('RPC').
-include("../../Foreign.hrl").
-export([ waitResponse/1
, waitResponseTimeout/2
]).
waitResponse(RequestId) ->
?IO(case erpc:wait_response(RequestId) of
{response, Result} -> ?Just(Result);
no_response -> ?Nothing
end).
waitResponseTimeout(RequestId, Timeout) ->
?IO(case erpc:wait_response(RequestId, Timeout) of
{response, Result} -> ?Just(Result);
no_response -> ?Nothing
end).
| null | https://raw.githubusercontent.com/hamler-lang/hamler/3ba89dde3067076e112c60351b019eeed6c97dd7/lib/Control/Distributed/RPC.erl | erlang | ---------------------------------------------------------------------------
|
Module : RPC
License : BSD-style (see the LICENSE file)
Stability : experimental
Portability : portable
The RPC FFI module.
--------------------------------------------------------------------------- | Copyright : ( c ) 2020 - 2021 EMQ Technologies Co. , Ltd.
Maintainer : ,
,
-module('RPC').
-include("../../Foreign.hrl").
-export([ waitResponse/1
, waitResponseTimeout/2
]).
waitResponse(RequestId) ->
?IO(case erpc:wait_response(RequestId) of
{response, Result} -> ?Just(Result);
no_response -> ?Nothing
end).
waitResponseTimeout(RequestId, Timeout) ->
?IO(case erpc:wait_response(RequestId, Timeout) of
{response, Result} -> ?Just(Result);
no_response -> ?Nothing
end).
|
94395a3bf1673fc881db77ed1135d810a72c2ae284ae24dc4a634e812a59f652 | mukul-rathi/bolt | desugar_overloading.mli | * overloaded functions and methods
open Ast.Ast_types
open Typing
val name_mangle_overloaded_method : Method_name.t -> type_expr list -> Method_name.t
val name_mangle_if_overloaded_function :
Typed_ast.function_defn list -> Function_name.t -> type_expr list -> Function_name.t
| null | https://raw.githubusercontent.com/mukul-rathi/bolt/1faf19d698852fdb6af2ee005a5f036ee1c76503/src/frontend/desugaring/desugar_overloading.mli | ocaml | * overloaded functions and methods
open Ast.Ast_types
open Typing
val name_mangle_overloaded_method : Method_name.t -> type_expr list -> Method_name.t
val name_mangle_if_overloaded_function :
Typed_ast.function_defn list -> Function_name.t -> type_expr list -> Function_name.t
| |
280ce6e11a2167319d368d76678d88a317ce23a86f1a6ee8ede4b59e5a9a7ec7 | mzp/coq-for-ipad | program_loading.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
Objective Caml port by and
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : program_loading.ml 9270 2009 - 05 - 20 11:52:42Z doligez $
Program loading
open Unix
open Debugger_config
open Parameters
open Input_handling
(*** Debugging. ***)
let debug_loading = ref false
(*** Load a program. ***)
(* Function used for launching the program. *)
let launching_func = ref (function () -> ())
let load_program () =
!launching_func ();
main_loop ()
(*** Launching functions. ***)
(* A generic function for launching the program *)
let generic_exec_unix cmdline = function () ->
if !debug_loading then
prerr_endline "Launching program...";
let child =
try
fork ()
with x ->
Unix_tools.report_error x;
raise Toplevel in
match child with
0 ->
begin try
match fork () with
0 -> (* Try to detach the process from the controlling terminal,
so that it does not receive SIGINT on ctrl-C. *)
begin try ignore(setsid()) with Invalid_argument _ -> () end;
execv shell [| shell; "-c"; cmdline() |]
| _ -> exit 0
with x ->
Unix_tools.report_error x;
exit 1
end
| _ ->
match wait () with
(_, WEXITED 0) -> ()
| _ -> raise Toplevel
let generic_exec_win cmdline = function () ->
if !debug_loading then
prerr_endline "Launching program...";
try ignore(create_process "cmd.exe" [| "/C"; cmdline() |] stdin stdout stderr)
with x ->
Unix_tools.report_error x;
raise Toplevel
let generic_exec =
match Sys.os_type with
"Win32" -> generic_exec_win
| _ -> generic_exec_unix
(* Execute the program by calling the runtime explicitely *)
let exec_with_runtime =
generic_exec
(function () ->
match Sys.os_type with
"Win32" ->
This fould fail on a file name with spaces
but quoting is even worse because
thinks each command line parameter is a file .
So no good solution so far
but quoting is even worse because Unix.create_process
thinks each command line parameter is a file.
So no good solution so far *)
Printf.sprintf "set CAML_DEBUG_SOCKET=%s && %s %s %s"
!socket_name
runtime_program
!program_name
!arguments
| _ ->
Printf.sprintf "CAML_DEBUG_SOCKET=%s %s %s %s"
!socket_name
(Filename.quote runtime_program)
(Filename.quote !program_name)
!arguments)
Excute the program directly
let exec_direct =
generic_exec
(function () ->
match Sys.os_type with
"Win32" ->
(* See the comment above *)
Printf.sprintf "set CAML_DEBUG_SOCKET=%s && %s %s"
!socket_name
!program_name
!arguments
| _ ->
Printf.sprintf "CAML_DEBUG_SOCKET=%s %s %s"
!socket_name
(Filename.quote !program_name)
!arguments)
(* Ask the user. *)
let exec_manual =
function () ->
print_newline ();
print_string "Waiting for connection...";
print_string ("(the socket is " ^ !socket_name ^ ")");
print_newline ()
(*** Selection of the launching function. ***)
type launching_function = (unit -> unit)
let loading_modes =
["direct", exec_direct;
"runtime", exec_with_runtime;
"manual", exec_manual]
let set_launching_function func =
launching_func := func
(* Initialization *)
let _ =
set_launching_function exec_direct
(*** Connection. ***)
let connection = ref Primitives.std_io
let connection_opened = ref false
| null | https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/debugger/program_loading.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
** Debugging. **
** Load a program. **
Function used for launching the program.
** Launching functions. **
A generic function for launching the program
Try to detach the process from the controlling terminal,
so that it does not receive SIGINT on ctrl-C.
Execute the program by calling the runtime explicitely
See the comment above
Ask the user.
** Selection of the launching function. **
Initialization
** Connection. ** | , projet Cristal , INRIA Rocquencourt
Objective Caml port by and
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : program_loading.ml 9270 2009 - 05 - 20 11:52:42Z doligez $
Program loading
open Unix
open Debugger_config
open Parameters
open Input_handling
let debug_loading = ref false
let launching_func = ref (function () -> ())
let load_program () =
!launching_func ();
main_loop ()
let generic_exec_unix cmdline = function () ->
if !debug_loading then
prerr_endline "Launching program...";
let child =
try
fork ()
with x ->
Unix_tools.report_error x;
raise Toplevel in
match child with
0 ->
begin try
match fork () with
begin try ignore(setsid()) with Invalid_argument _ -> () end;
execv shell [| shell; "-c"; cmdline() |]
| _ -> exit 0
with x ->
Unix_tools.report_error x;
exit 1
end
| _ ->
match wait () with
(_, WEXITED 0) -> ()
| _ -> raise Toplevel
let generic_exec_win cmdline = function () ->
if !debug_loading then
prerr_endline "Launching program...";
try ignore(create_process "cmd.exe" [| "/C"; cmdline() |] stdin stdout stderr)
with x ->
Unix_tools.report_error x;
raise Toplevel
let generic_exec =
match Sys.os_type with
"Win32" -> generic_exec_win
| _ -> generic_exec_unix
let exec_with_runtime =
generic_exec
(function () ->
match Sys.os_type with
"Win32" ->
This fould fail on a file name with spaces
but quoting is even worse because
thinks each command line parameter is a file .
So no good solution so far
but quoting is even worse because Unix.create_process
thinks each command line parameter is a file.
So no good solution so far *)
Printf.sprintf "set CAML_DEBUG_SOCKET=%s && %s %s %s"
!socket_name
runtime_program
!program_name
!arguments
| _ ->
Printf.sprintf "CAML_DEBUG_SOCKET=%s %s %s %s"
!socket_name
(Filename.quote runtime_program)
(Filename.quote !program_name)
!arguments)
Excute the program directly
let exec_direct =
generic_exec
(function () ->
match Sys.os_type with
"Win32" ->
Printf.sprintf "set CAML_DEBUG_SOCKET=%s && %s %s"
!socket_name
!program_name
!arguments
| _ ->
Printf.sprintf "CAML_DEBUG_SOCKET=%s %s %s"
!socket_name
(Filename.quote !program_name)
!arguments)
let exec_manual =
function () ->
print_newline ();
print_string "Waiting for connection...";
print_string ("(the socket is " ^ !socket_name ^ ")");
print_newline ()
type launching_function = (unit -> unit)
let loading_modes =
["direct", exec_direct;
"runtime", exec_with_runtime;
"manual", exec_manual]
let set_launching_function func =
launching_func := func
let _ =
set_launching_function exec_direct
let connection = ref Primitives.std_io
let connection_opened = ref false
|
88d791c09e04871a4080a9dd6cb9347e71ce7d8adf06cd643f454afb0d66f7ff | shortishly/haystack | haystack_docker_util.erl | Copyright ( c ) 2016 < >
%%
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(haystack_docker_util).
-export([container_id/1]).
-export([docker_id/1]).
-export([request/2]).
-export([ssl/2]).
-export([system_time/1]).
-export([ttl/0]).
request(Suffix, #{host := Host,
port := Port,
cert := Cert,
key := Key}) ->
httpc:request(get,
{iolist_to_list(["https://",
Host,
":",
integer_to_list(Port),
Suffix]), []},
[{ssl, ssl(Cert, Key)}],
[{body_format, binary}]);
request(Suffix, #{host := Host, port := Port}) ->
httpc:request(get,
{iolist_to_list(["http://",
Host,
":",
integer_to_list(Port),
Suffix]), []},
[],
[{body_format, binary}]).
iolist_to_list(IO) ->
binary_to_list(iolist_to_binary(IO)).
ssl(Cert, Key) ->
[{cert, Cert},
{key, Key}].
ttl() ->
100.
system_time(<<Year:4/bytes,
"-",
Month:2/bytes,
"-",
Date:2/bytes,
"T",
Hour:2/bytes,
":",
Minute:2/bytes,
":",
Second:2/bytes,
".",
_Remainder/binary>>) ->
{{binary_to_integer(Year),
binary_to_integer(Month),
binary_to_integer(Date)},
{binary_to_integer(Hour),
binary_to_integer(Minute),
binary_to_integer(Second)}}.
docker_id(<<_:59/bytes>> = Id) ->
id(<<"d">>, Id, dockers).
container_id(<<_:64/bytes>> = Id) ->
id(<<"c">>, Id, containers).
id(Prefix, Id, Origin) ->
dns_name:labels(<<
Prefix/binary,
(hash(Id))/binary,
".",
(haystack_config:origin(Origin))/binary
>>).
hash(Name) ->
list_to_binary(
string:to_lower(
integer_to_list(erlang:phash2(Name), 26))).
| null | https://raw.githubusercontent.com/shortishly/haystack/7ff0d737dcd90adf60c861b2cf755aee1355e555/src/haystack_docker_util.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. | Copyright ( c ) 2016 < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(haystack_docker_util).
-export([container_id/1]).
-export([docker_id/1]).
-export([request/2]).
-export([ssl/2]).
-export([system_time/1]).
-export([ttl/0]).
request(Suffix, #{host := Host,
port := Port,
cert := Cert,
key := Key}) ->
httpc:request(get,
{iolist_to_list(["https://",
Host,
":",
integer_to_list(Port),
Suffix]), []},
[{ssl, ssl(Cert, Key)}],
[{body_format, binary}]);
request(Suffix, #{host := Host, port := Port}) ->
httpc:request(get,
{iolist_to_list(["http://",
Host,
":",
integer_to_list(Port),
Suffix]), []},
[],
[{body_format, binary}]).
iolist_to_list(IO) ->
binary_to_list(iolist_to_binary(IO)).
ssl(Cert, Key) ->
[{cert, Cert},
{key, Key}].
ttl() ->
100.
system_time(<<Year:4/bytes,
"-",
Month:2/bytes,
"-",
Date:2/bytes,
"T",
Hour:2/bytes,
":",
Minute:2/bytes,
":",
Second:2/bytes,
".",
_Remainder/binary>>) ->
{{binary_to_integer(Year),
binary_to_integer(Month),
binary_to_integer(Date)},
{binary_to_integer(Hour),
binary_to_integer(Minute),
binary_to_integer(Second)}}.
docker_id(<<_:59/bytes>> = Id) ->
id(<<"d">>, Id, dockers).
container_id(<<_:64/bytes>> = Id) ->
id(<<"c">>, Id, containers).
id(Prefix, Id, Origin) ->
dns_name:labels(<<
Prefix/binary,
(hash(Id))/binary,
".",
(haystack_config:origin(Origin))/binary
>>).
hash(Name) ->
list_to_binary(
string:to_lower(
integer_to_list(erlang:phash2(Name), 26))).
|
2359825bd603277ae378128720624f3946c240129828ade81a5cd97d32c322ca | ekmett/ekmett.github.com | THash.hs | {-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
Module : Data .
Copyright : ( C ) 2006
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( requires STM )
--
A simple " STM " based transactional linear hash table based on Witold 1980 .
This wraps a " Data . THash . " in an simple container . It may be
more appropriate to use the underlying " " structure directly if you are
-- nesting these. The performance hit hasn't yet been measured.
----------------------------------------------------------------------------
module Data.THash (
THash,
( k - > Int ) - > STM ( THash k v )
newH, -- Hashable k => STM (THash k v)
Eq k = > ( k - > Int ) - > [ ( k , v ) ] - > STM ( THash k v )
Eq k = > THash k v - > k - > v - > STM ( Bool )
Eq k = > THash k v - > k - > v - > STM ( )
modify, -- Eq k => THash k v -> k -> (Maybe v -> v) -> STM ()
delete, -- Eq k => THash k v -> k -> STM (Bool)
lookup, -- Eq k => THash k v -> k -> STM (Maybe v)
mapH, -- ((k,v) -> r) -> THash k v -> STM [r]
each, -- THash k v -> STM [(k,v)]
keys, -- THash k v -> STM [k]
values, -- THash k v -> STM [v]
hashInt, -- Int -> Int
get,
-- hashString -- Int -> Int
) where
import qualified Data.THash.THT as THT hiding(THT)
import Data.Hashable
import Data.THash.THT (THT)
import Prelude hiding (lookup)
import Control.Monad (liftM)
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import Data.Bits
-- | A hash with keys of type k to values of type v
newtype THash k v = THash (TVar (THT k v))
# INLINE make #
make :: THT k v -> STM (THash k v)
make t = do x <- newTVar t; return $ THash x
{-# INLINE get #-}
get :: THash k v -> STM (THT k v)
get (THash h) = readTVar h
{-# INLINE set #-}
set :: THash k v -> THT k v -> STM ()
set (THash h) = writeTVar h
# INLINE setif #
setif :: THash k v -> (THT k v,Bool) -> STM (Bool)
setif (THash h) (t,b)
| b == True
= writeTVar h t >> return True
| otherwise
= return False
{-# INLINE new #-}
-- | Build an empty hash table
new :: (k -> Int) -> STM (THash k v)
new hash = make =<< THT.new hash
# INLINE newH #
-- | Build an empty hash table using the default hash function for the key type.
newH :: Hashable k => STM (THash k v)
newH = new hash
# INLINE fromList #
-- | Build a hash table from a list of @(key,value)@ pairs
fromList :: Eq k => (k -> Int) -> [(k,v)] -> STM (THash k v)
fromList hash list = make =<< THT.fromList hash list
# INLINE insert #
-- | Insert a value into the hash table. If a value with the key is present
-- then nothing is changed and 'False' is returned.
insert :: Eq k => THash k v -> k -> v -> STM (Bool)
insert hash key value = do x <- get hash; y <- THT.insert x key value; setif hash y
# INLINE update #
-- | Insert a value into the hash table, replacing any value with the same key that is present.
update :: Eq k => THash k v -> k -> v -> STM ()
update hash key value = do x <- get hash; y <- THT.update x key value; set hash y
# INLINE modify #
-- | Update a value in the hash table using the supplied function.
modify :: Eq k => THash k v -> k -> (Maybe v -> v) -> STM ()
modify hash key f = do x <- get hash; y <- THT.modify x key f ; set hash y
{-# INLINE delete #-}
-- | Remove a value from the hash table. Returns 'True' to indicate success.
delete :: Eq k => THash k v -> k -> STM (Bool)
delete hash key = do x <- get hash; y <- THT.delete x key; setif hash y
{-# INLINE lookup #-}
-- | Lookup a value in the hash table.
lookup :: Eq k => THash k v -> k -> STM (Maybe v)
lookup hash key = do x <- get hash; THT.lookup x key
{-# INLINE mapH #-}
-- | Map a function over all @(key,value)@ functions in the hash table.
mapH :: ((k,v) -> r) -> THash k v -> STM [r]
mapH f hash = do x <- get hash; THT.mapH f x
# INLINE each #
-- | @each = mapH id@ and returns all @(key,value)@ pairs in the hash.
each :: THash k v -> STM [(k,v)]
each = mapH id
# INLINE keys #
-- | @each = mapH fst@ and returns all keys in the hash.
keys :: THash k v -> STM [k]
keys = mapH fst
# INLINE values #
-- | @each = mapH snd@ and returns all values present in the hash.
values :: THash k v -> STM [v]
values = mapH snd
# INLINE hashInt #
| 32 bit mix function ; more effective than a prime modulus for
-- declustering a linear hash, but not good against an adversary, since its easily
-- reversed.
hashInt :: Int -> Int
hashInt = ap xor (`shiftR` 16)
. ap (+) (complement . (`shiftL` 11))
. ap xor (`shiftR` 6)
. ap (+) (`shiftL` 3)
. ap xor (`shiftR` 10)
. ap (+) (complement . (`shiftL` 15))
where ap x y z = x z $ y z
| null | https://raw.githubusercontent.com/ekmett/ekmett.github.com/8d3abab5b66db631e148e1d046d18909bece5893/haskell/thash/src/Data/THash.hs | haskell | # OPTIONS -fglasgow-exts #
---------------------------------------------------------------------------
|
License : BSD-style (see the file libraries/base/LICENSE)
Stability : experimental
nesting these. The performance hit hasn't yet been measured.
--------------------------------------------------------------------------
Hashable k => STM (THash k v)
Eq k => THash k v -> k -> (Maybe v -> v) -> STM ()
Eq k => THash k v -> k -> STM (Bool)
Eq k => THash k v -> k -> STM (Maybe v)
((k,v) -> r) -> THash k v -> STM [r]
THash k v -> STM [(k,v)]
THash k v -> STM [k]
THash k v -> STM [v]
Int -> Int
hashString -- Int -> Int
| A hash with keys of type k to values of type v
# INLINE get #
# INLINE set #
# INLINE new #
| Build an empty hash table
| Build an empty hash table using the default hash function for the key type.
| Build a hash table from a list of @(key,value)@ pairs
| Insert a value into the hash table. If a value with the key is present
then nothing is changed and 'False' is returned.
| Insert a value into the hash table, replacing any value with the same key that is present.
| Update a value in the hash table using the supplied function.
# INLINE delete #
| Remove a value from the hash table. Returns 'True' to indicate success.
# INLINE lookup #
| Lookup a value in the hash table.
# INLINE mapH #
| Map a function over all @(key,value)@ functions in the hash table.
| @each = mapH id@ and returns all @(key,value)@ pairs in the hash.
| @each = mapH fst@ and returns all keys in the hash.
| @each = mapH snd@ and returns all values present in the hash.
declustering a linear hash, but not good against an adversary, since its easily
reversed. | Module : Data .
Copyright : ( C ) 2006
Maintainer : < >
Portability : non - portable ( requires STM )
A simple " STM " based transactional linear hash table based on Witold 1980 .
This wraps a " Data . THash . " in an simple container . It may be
more appropriate to use the underlying " " structure directly if you are
module Data.THash (
THash,
( k - > Int ) - > STM ( THash k v )
Eq k = > ( k - > Int ) - > [ ( k , v ) ] - > STM ( THash k v )
Eq k = > THash k v - > k - > v - > STM ( Bool )
Eq k = > THash k v - > k - > v - > STM ( )
get,
) where
import qualified Data.THash.THT as THT hiding(THT)
import Data.Hashable
import Data.THash.THT (THT)
import Prelude hiding (lookup)
import Control.Monad (liftM)
import Control.Concurrent.STM
import Control.Concurrent.STM.TVar
import Data.Bits
newtype THash k v = THash (TVar (THT k v))
# INLINE make #
make :: THT k v -> STM (THash k v)
make t = do x <- newTVar t; return $ THash x
get :: THash k v -> STM (THT k v)
get (THash h) = readTVar h
set :: THash k v -> THT k v -> STM ()
set (THash h) = writeTVar h
# INLINE setif #
setif :: THash k v -> (THT k v,Bool) -> STM (Bool)
setif (THash h) (t,b)
| b == True
= writeTVar h t >> return True
| otherwise
= return False
new :: (k -> Int) -> STM (THash k v)
new hash = make =<< THT.new hash
# INLINE newH #
newH :: Hashable k => STM (THash k v)
newH = new hash
# INLINE fromList #
fromList :: Eq k => (k -> Int) -> [(k,v)] -> STM (THash k v)
fromList hash list = make =<< THT.fromList hash list
# INLINE insert #
insert :: Eq k => THash k v -> k -> v -> STM (Bool)
insert hash key value = do x <- get hash; y <- THT.insert x key value; setif hash y
# INLINE update #
update :: Eq k => THash k v -> k -> v -> STM ()
update hash key value = do x <- get hash; y <- THT.update x key value; set hash y
# INLINE modify #
modify :: Eq k => THash k v -> k -> (Maybe v -> v) -> STM ()
modify hash key f = do x <- get hash; y <- THT.modify x key f ; set hash y
delete :: Eq k => THash k v -> k -> STM (Bool)
delete hash key = do x <- get hash; y <- THT.delete x key; setif hash y
lookup :: Eq k => THash k v -> k -> STM (Maybe v)
lookup hash key = do x <- get hash; THT.lookup x key
mapH :: ((k,v) -> r) -> THash k v -> STM [r]
mapH f hash = do x <- get hash; THT.mapH f x
# INLINE each #
each :: THash k v -> STM [(k,v)]
each = mapH id
# INLINE keys #
keys :: THash k v -> STM [k]
keys = mapH fst
# INLINE values #
values :: THash k v -> STM [v]
values = mapH snd
# INLINE hashInt #
| 32 bit mix function ; more effective than a prime modulus for
hashInt :: Int -> Int
hashInt = ap xor (`shiftR` 16)
. ap (+) (complement . (`shiftL` 11))
. ap xor (`shiftR` 6)
. ap (+) (`shiftL` 3)
. ap xor (`shiftR` 10)
. ap (+) (complement . (`shiftL` 15))
where ap x y z = x z $ y z
|
27885192b6b5a32bf0adbc184a7ce44d9508b4a2f1eda59fea5d1fce204425a0 | yi-editor/yi | FriendlyPath.hs | module System.FriendlyPath
( userToCanonPath
, expandTilda
, isAbsolute'
) where
import System.CanonicalizePath (canonicalizePath)
import System.Directory (getHomeDirectory)
import System.FilePath (isAbsolute, normalise, pathSeparator)
import System.PosixCompat.User (getUserEntryForName, homeDirectory)
-- canonicalizePath follows symlinks, and does not work if the directory does not exist.
| a user - friendly path
userToCanonPath :: FilePath -> IO String
userToCanonPath f = canonicalizePath =<< expandTilda f
-- | Turn a user-friendly path into a computer-friendly path by expanding the leading tilda.
expandTilda :: String -> IO FilePath
expandTilda ('~':path)
| null path || (head path == pathSeparator) = (++ path) <$> getHomeDirectory
Home directory of another user , e.g. ~root/
| otherwise = let username = takeWhile (/= pathSeparator) path
dirname = drop (length username) path
in (normalise . (++ dirname) . homeDirectory) <$> getUserEntryForName username
expandTilda path = return path
-- | Is a user-friendly path absolute?
isAbsolute' :: String -> Bool
isAbsolute' ('~':_) = True
isAbsolute' p = isAbsolute p
| null | https://raw.githubusercontent.com/yi-editor/yi/58c239e3a77cef8f4f77e94677bd6a295f585f5f/yi-core/src/System/FriendlyPath.hs | haskell | canonicalizePath follows symlinks, and does not work if the directory does not exist.
| Turn a user-friendly path into a computer-friendly path by expanding the leading tilda.
| Is a user-friendly path absolute? | module System.FriendlyPath
( userToCanonPath
, expandTilda
, isAbsolute'
) where
import System.CanonicalizePath (canonicalizePath)
import System.Directory (getHomeDirectory)
import System.FilePath (isAbsolute, normalise, pathSeparator)
import System.PosixCompat.User (getUserEntryForName, homeDirectory)
| a user - friendly path
userToCanonPath :: FilePath -> IO String
userToCanonPath f = canonicalizePath =<< expandTilda f
expandTilda :: String -> IO FilePath
expandTilda ('~':path)
| null path || (head path == pathSeparator) = (++ path) <$> getHomeDirectory
Home directory of another user , e.g. ~root/
| otherwise = let username = takeWhile (/= pathSeparator) path
dirname = drop (length username) path
in (normalise . (++ dirname) . homeDirectory) <$> getUserEntryForName username
expandTilda path = return path
isAbsolute' :: String -> Bool
isAbsolute' ('~':_) = True
isAbsolute' p = isAbsolute p
|
a5d0f2a4c3a730a147e6f7068391569d0b9eb43ca9eefd26feec6c04c312da04 | marijnh/pcall | queue.lisp | (cl:defpackage :pcall-queue
(:use :cl :bordeaux-threads)
(:export #:make-queue
#:queue-push
#:queue-pop #:queue-wait
#:queue-length #:queue-empty-p))
(cl:in-package :pcall-queue)
;;; A thread-safe wait queue.
(defclass queue ()
((lock :initform (make-lock) :reader queue-lock)
(condition :initform (make-condition-variable) :reader queue-condition)
(front :initform nil :accessor queue-front)
(back :initform nil :accessor queue-back)))
(defstruct node val next prev)
(defun make-queue ()
"Create an empty queue."
(make-instance 'queue))
(defun queue-push (elt queue)
"Push an element onto the back of a queue."
(with-lock-held ((queue-lock queue))
(let* ((back (queue-back queue))
(node (make-node :val elt :prev back :next nil)))
(setf (queue-back queue) node)
(cond (back (setf (node-next back) node))
(t (setf (queue-front queue) node))))
(condition-notify (queue-condition queue)))
(values))
(defun queue-do-pop (queue)
(let ((node (queue-front queue)))
(if node
(progn
(setf (queue-front queue) (node-next node))
(unless (node-next node)
(setf (queue-back queue) nil))
(values (node-val node) t))
(values nil nil))))
(defun queue-pop (queue)
"Pop an element from the front of a queue. Returns immediately,
returning nil if the queue is empty, and a second value indicating
whether anything was popped."
(with-lock-held ((queue-lock queue))
(queue-do-pop queue)))
(defun queue-wait (queue)
"Pop an element from the front of a queue. Causes a blocking wait
when no elements are available."
(with-lock-held ((queue-lock queue))
(loop (multiple-value-bind (elt found) (queue-do-pop queue)
(when found (return elt)))
(condition-wait (queue-condition queue) (queue-lock queue)))))
(defun queue-length (queue)
"Find the length of a queue."
(with-lock-held ((queue-lock queue))
(loop :for node := (queue-front queue) :then (node-next node)
:for l :from 0
:while node
:finally (return l))))
(defun queue-empty-p (queue)
"Test whether a queue is empty."
(null (queue-front queue)))
| null | https://raw.githubusercontent.com/marijnh/pcall/0b4b98a45863b0f4437a8592c5630faa2d6437c5/queue.lisp | lisp | A thread-safe wait queue. | (cl:defpackage :pcall-queue
(:use :cl :bordeaux-threads)
(:export #:make-queue
#:queue-push
#:queue-pop #:queue-wait
#:queue-length #:queue-empty-p))
(cl:in-package :pcall-queue)
(defclass queue ()
((lock :initform (make-lock) :reader queue-lock)
(condition :initform (make-condition-variable) :reader queue-condition)
(front :initform nil :accessor queue-front)
(back :initform nil :accessor queue-back)))
(defstruct node val next prev)
(defun make-queue ()
"Create an empty queue."
(make-instance 'queue))
(defun queue-push (elt queue)
"Push an element onto the back of a queue."
(with-lock-held ((queue-lock queue))
(let* ((back (queue-back queue))
(node (make-node :val elt :prev back :next nil)))
(setf (queue-back queue) node)
(cond (back (setf (node-next back) node))
(t (setf (queue-front queue) node))))
(condition-notify (queue-condition queue)))
(values))
(defun queue-do-pop (queue)
(let ((node (queue-front queue)))
(if node
(progn
(setf (queue-front queue) (node-next node))
(unless (node-next node)
(setf (queue-back queue) nil))
(values (node-val node) t))
(values nil nil))))
(defun queue-pop (queue)
"Pop an element from the front of a queue. Returns immediately,
returning nil if the queue is empty, and a second value indicating
whether anything was popped."
(with-lock-held ((queue-lock queue))
(queue-do-pop queue)))
(defun queue-wait (queue)
"Pop an element from the front of a queue. Causes a blocking wait
when no elements are available."
(with-lock-held ((queue-lock queue))
(loop (multiple-value-bind (elt found) (queue-do-pop queue)
(when found (return elt)))
(condition-wait (queue-condition queue) (queue-lock queue)))))
(defun queue-length (queue)
"Find the length of a queue."
(with-lock-held ((queue-lock queue))
(loop :for node := (queue-front queue) :then (node-next node)
:for l :from 0
:while node
:finally (return l))))
(defun queue-empty-p (queue)
"Test whether a queue is empty."
(null (queue-front queue)))
|
10d22a880516e90d032bfcaaa2068844012a73c91543d597e3d1377c42b9549d | achirkin/qua-view | Scenario.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE Strict #-}
# OPTIONS_GHC -fno - warn - orphans #
-- | Geometry Scenario
--
-- The main structure in qua-view!
--
module Model.Scenario
( Scenario, Scenario' (..), getTransferables
, name, geoLoc, srid, properties, objects, objIdSeq, viewState, withoutObjects
, selectedDynamicColor, selectedStaticColor, selectedGroupColor
, defaultStaticColor
, defaultBlockColor, defaultLineColor, defaultPointColor
, defaultObjectHeight
, viewDistance, evaluationCellSize
, servicePluginsProp
, maxCameraDistance, minCameraDistance
, mapZoomLevel, mapOpacity, useMapLayer, mapUrl
, hiddenProperties
, resolvedObjectHeight, resolvedObjectColor
, resolvedObjectColorIgnoreVisible
, ScenarioState (..)
, cameraPos, cameraLoc, cameraLookAt, objectGroups, clippingDist, zoomLimits
, templates, forcedAreaObjId, groupIdSeq, creationPoint, servicePlugins
) where
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Control.Lens (set,(^.),non, _1, _2)
import Control.Applicative ((<|>))
import Numeric.DataFrame hiding (toList)
import Data.Foldable (toList)
import Data.Semigroup (stimesIdempotentMonoid)
import GHC.Generics
import Commons.NoReflex
import Model.Scenario.Properties
import Model.Scenario.ServicePlugin
import Model.Scenario.Object ( GroupId, ObjectId)
import qualified Model.Scenario.Object as Object
import qualified Model.Scenario.Object.Geometry as Geometry
type Scenario = Scenario' 'Object.Renderable
data Scenario' s
= Scenario
{ _name :: !(Maybe JSString)
-- ^ Friendly name for a scenario
, _geoLoc :: !(Maybe (Double, Double, Double))
-- ^ Longitude, Latitude, and Altitude of scenario reference point
, _srid :: !(Maybe Int)
-- ^ We can explicitly specify srid
, _properties :: !Properties
-- ^ key-value of arbitrary JSON properties
, _objects :: !(Object.Collection' s)
-- ^ Map with scenario content
, _objIdSeq :: !ObjectId
^ Keep track of highest to be able to generate more
, _viewState :: !ScenarioState
-- ^ Some necessary information for viewing and interacting with scenario
} deriving Generic
instance FromJSVal (Scenario' Object.Prepared)
instance ToJSVal (Scenario' Object.Prepared)
-- | Get transferable content of each scenario object
getTransferables :: Scenario' s -> IO [Transferable]
getTransferables = mapM Object.getTransferable . toList . _objects
-- | Get scenario with no Objects inside.
-- Used to send scenario information to a geometry loader,
-- so that geometry loader has scenario context.
withoutObjects :: Scenario' s -> Scenario' Object.Prepared
withoutObjects = set objects mempty
. set (viewState.objectGroups) mempty
-- * Lenses
name :: Functor f
=> (Maybe JSString -> f (Maybe JSString))
-> Scenario' s -> f (Scenario' s)
name f s = (\x -> s{_name = x}) <$> f (_name s)
geoLoc :: Functor f
=> (Maybe (Double, Double, Double) -> f (Maybe (Double, Double, Double)))
-> Scenario' s -> f (Scenario' s)
geoLoc f s = (\x -> s{_geoLoc = x}) <$> f (_geoLoc s)
srid :: Functor f
=> (Maybe Int -> f (Maybe Int))
-> Scenario' s -> f (Scenario' s)
srid f s = (\x -> s{_srid = x}) <$> f (_srid s)
properties :: Functor f
=> (Properties -> f Properties)
-> Scenario' s -> f (Scenario' s)
properties f s = (\x -> s{_properties = x}) <$> f (_properties s)
objects :: Functor f
=> (Object.Collection' s -> f (Object.Collection' t))
-> Scenario' s -> f (Scenario' t)
objects f s = (\x -> s{_objects = x}) <$> f (_objects s)
objIdSeq :: Functor f
=> (ObjectId -> f ObjectId)
-> Scenario' s -> f (Scenario' s)
objIdSeq f s = (\x -> s{_objIdSeq = x}) <$> f (_objIdSeq s)
viewState :: Functor f
=> (ScenarioState -> f ScenarioState)
-> Scenario' s -> f (Scenario' s)
viewState f s = (\x -> s{_viewState = x}) <$> f (_viewState s)
instance Semigroup (Scenario' s) where
scOld <> scNew = Scenario
{ -- trying to update scenario name if it has changed
_name = _name scNew <|> _name scOld
keeping GeoLocation from older version
, _geoLoc = _geoLoc scOld <|> _geoLoc scNew
keeping SRID from older version
, _srid = _srid scOld <|> _srid scNew
-- prefer duplicate properties from a new version
, _properties = _properties scNew <> _properties scOld
-- replace older objects with newer ones
, _objects = _objects scNew <> _objects scOld
-- get maximum of objId counters to make sure
-- no objects could have the same object Id
, _objIdSeq = max (_objIdSeq scOld) (_objIdSeq scNew)
-- just get a new view state
, _viewState = _viewState scNew
}
stimes = stimesIdempotentMonoid
instance Monoid (Scenario' s) where
mempty = Scenario
{ _name = Nothing
, _geoLoc = Nothing
, _srid = Nothing
, _properties = mempty
, _objects = mempty
, _objIdSeq = Object.ObjectId 0
, _viewState = def
}
mappend = (<>)
instance Default (Scenario' s) where
def = mempty
-- * Special properties
defaultObjectHeight :: Functor f
=> (Double -> f Double) -> Scenario' s -> f (Scenario' s)
defaultObjectHeight f = properties $ property "defaultObjectHeight" g
where
g Nothing = Just <$> f 3.5
g (Just c) = Just <$> f c
selectedDynamicColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
selectedDynamicColor f = properties $ property "selectedDynamicColor" g
where
g Nothing = Just <$> f "#FF6060FF"
g (Just c) = Just <$> f c
selectedGroupColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
selectedGroupColor f = properties $ property "selectedGroupColor" g
where
g Nothing = Just <$> f "#CC8888E0"
g (Just c) = Just <$> f c
selectedStaticColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
selectedStaticColor f = properties $ property "selectedStaticColor" g
where
g Nothing = Just <$> f "#BB8888FF"
g (Just c) = Just <$> f c
defaultStaticColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultStaticColor f = properties $ property "defaultStaticColor" g
where
g Nothing = Just <$> f "#808088E0"
g (Just c) = Just <$> f c
defaultBlockColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultBlockColor f = properties $ property "defaultBlockColor" g
where
g Nothing = Just <$> f "#C0C082FF"
g (Just c) = Just <$> f c
defaultLineColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultLineColor f = properties $ property "defaultLineColor" g
where
g Nothing = Just <$> f "#CC6666FF"
g (Just c) = Just <$> f c
defaultPointColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultPointColor f = properties $ property "defaultPointColor" g
where
g Nothing = Just <$> f "#006666FF"
g (Just c) = Just <$> f c
viewDistance :: Functor f
=> (Maybe Float -> f (Maybe Float)) -> Scenario' s -> f (Scenario' s)
viewDistance = properties . property "viewDistance"
maxCameraDistance :: Functor f
=> (Maybe Float -> f (Maybe Float)) -> Scenario' s -> f (Scenario' s)
maxCameraDistance = properties . property "maxCameraDistance"
minCameraDistance :: Functor f
=> (Maybe Float -> f (Maybe Float)) -> Scenario' s -> f (Scenario' s)
minCameraDistance = properties . property "minCameraDistance"
mapZoomLevel :: Functor f
=> (Int -> f Int) -> Scenario' s -> f (Scenario' s)
mapZoomLevel f = properties $ property "mapZoomLevel" g
where
g Nothing = Just <$> f 15
g (Just c) = Just <$> f c
mapOpacity :: Functor f
=> (Double -> f Double) -> Scenario' s -> f (Scenario' s)
mapOpacity f = properties $ property "mapOpacity" g
where
g Nothing = Just <$> f 0.8
g (Just c) = Just <$> f c
useMapLayer :: Functor f
=> (Bool -> f Bool) -> Scenario' s -> f (Scenario' s)
useMapLayer f = properties $ property "useMapLayer" g
where
g Nothing = Just <$> f False
g (Just c) = Just <$> f c
mapUrl :: Functor f
=> (JSString -> f JSString) -> Scenario' s -> f (Scenario' s)
mapUrl f = properties $ property "mapUrl" g
where
g Nothing = Just <$> f "/${z}/${x}/${y}.png"
g (Just c) = Just <$> f c
hiddenProperties :: Functor f
=> ([JSString] -> f [JSString]) -> Scenario' s -> f (Scenario' s)
hiddenProperties f = properties $ property "hiddenProperties" g
where
g Nothing = Just <$> f [ "geomID", "groupID"
, "hiddenProperties", "viewColor"
, "height", "static", "selectable"
, "visible", "special"]
g (Just c) = Just <$> f c
evaluationCellSize :: Functor f
=> (Double -> f Double) -> Scenario' s -> f (Scenario' s)
evaluationCellSize f = properties $ property "evaluationCellSize" g
where
g Nothing = Just <$> f 5.0
g (Just c) = Just <$> f c
servicePluginsProp :: Functor f
=> ([ServicePlugin] -> f [ServicePlugin])
-> Scenario' s -> f (Scenario' s)
servicePluginsProp f = properties $ property "servicePlugins" g
where
g Nothing = nonEmpty <$> f []
g (Just c) = nonEmpty <$> f c
nonEmpty [] = Nothing
nonEmpty xs = Just xs
-- * Resolved properties
resolvedObjectColorIgnoreVisible :: Scenario' s -> Object.Object' t -> HexColor
resolvedObjectColorIgnoreVisible s o = o^.Object.viewColor.non sdef
where
sdef = case o^.Object.geometry of
Geometry.Points _ -> s^.defaultPointColor
Geometry.Lines _ -> s^.defaultLineColor
Geometry.Polygons _ -> case o^.Object.objectBehavior of
Object.Static -> s^.defaultStaticColor
Object.Dynamic -> s^.defaultBlockColor
-- | Resolve view color of object based on object and scenario properties.
resolvedObjectColor :: Scenario' s -> Object.Object' t -> HexColor
resolvedObjectColor s o
= if o^.Object.visible
then resolvedObjectColorIgnoreVisible s o
else "#00000000"
-- | Resolve object height to extrude it if necessary
resolvedObjectHeight :: Scenario' s -> Object.Object' t -> Double
resolvedObjectHeight s o = o^.Object.height.non (s^.defaultObjectHeight)
-- * Computed and updateable attributes
| settings for qua - view
data ScenarioState
= ScenarioState
{ _cameraPos :: !(Vec3f, Vec3f)
, _objectGroups :: !(Map.Map GroupId [ObjectId])
, _clippingDist :: !Float
, _zoomLimits :: !(Float, Float)
, _templates :: !(Set.Set (Either ObjectId GroupId))
, _forcedAreaObjId :: !(Maybe ObjectId)
, _groupIdSeq :: !GroupId
, _creationPoint :: !(Maybe Vec3f)
, _servicePlugins :: ![ServicePlugin]
} deriving Generic
instance FromJSVal ScenarioState
instance ToJSVal ScenarioState
instance FromJSVal (Either ObjectId GroupId)
instance ToJSVal (Either ObjectId GroupId)
instance FromJSVal (Set.Set (Either ObjectId GroupId)) where
fromJSVal = fmap (fmap Set.fromDistinctAscList) . fromJSVal
instance ToJSVal (Set.Set (Either ObjectId GroupId)) where
toJSVal = toJSVal . Set.toAscList
instance Default ScenarioState where
def = ScenarioState
{ _cameraPos = (vec3 100 150 500, 0)
, _objectGroups = mempty
, _clippingDist = 2000
, _zoomLimits = (1, 1334)
, _templates = mempty
, _forcedAreaObjId = Nothing
, _groupIdSeq = 0
, _creationPoint = Nothing
, _servicePlugins = []
}
cameraPos :: Functor f
=> ((Vec3f, Vec3f) -> f (Vec3f, Vec3f))
-> ScenarioState -> f ScenarioState
cameraPos f s = (\x -> s{_cameraPos = x}) <$> f (_cameraPos s)
cameraLoc :: Functor f
=> (Vec3f -> f Vec3f)
-> ScenarioState -> f ScenarioState
cameraLoc = cameraPos . _1
cameraLookAt :: Functor f
=> (Vec3f -> f Vec3f)
-> ScenarioState -> f ScenarioState
cameraLookAt = cameraPos . _2
objectGroups :: Functor f
=> (Map.Map GroupId [ObjectId] -> f (Map.Map GroupId [ObjectId]))
-> ScenarioState -> f ScenarioState
objectGroups f s = (\x -> s{_objectGroups = x}) <$> f (_objectGroups s)
clippingDist :: Functor f
=> (Float -> f Float)
-> ScenarioState -> f ScenarioState
clippingDist f s = (\x -> s{_clippingDist = x}) <$> f (_clippingDist s)
zoomLimits :: Functor f
=> ((Float, Float) -> f (Float, Float))
-> ScenarioState -> f ScenarioState
zoomLimits f s = (\x -> s{_zoomLimits = x}) <$> f (_zoomLimits s)
templates :: Functor f
=> (Set.Set (Either ObjectId GroupId) -> f (Set.Set (Either ObjectId GroupId) ))
-> ScenarioState -> f ScenarioState
templates f s = (\x -> s{_templates = x}) <$> f (_templates s)
forcedAreaObjId :: Functor f
=> (Maybe ObjectId -> f (Maybe ObjectId))
-> ScenarioState -> f ScenarioState
forcedAreaObjId f s = (\x -> s{_forcedAreaObjId = x}) <$> f (_forcedAreaObjId s)
groupIdSeq :: Functor f
=> (GroupId -> f GroupId)
-> ScenarioState -> f ScenarioState
groupIdSeq f s = (\x -> s{_groupIdSeq = x}) <$> f (_groupIdSeq s)
creationPoint :: Functor f
=> (Maybe Vec3f -> f (Maybe Vec3f))
-> ScenarioState -> f ScenarioState
creationPoint f s = (\x -> s{_creationPoint = x}) <$> f (_creationPoint s)
servicePlugins :: Functor f
=> ([ServicePlugin] -> f [ServicePlugin])
-> ScenarioState -> f ScenarioState
servicePlugins f s = (\x -> s{_servicePlugins = x}) <$> f (_servicePlugins s)
| null | https://raw.githubusercontent.com/achirkin/qua-view/62626ead828889a1c7ef1fdba4d84324eb5420b3/src/Model/Scenario.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE DataKinds #
# LANGUAGE Strict #
| Geometry Scenario
The main structure in qua-view!
^ Friendly name for a scenario
^ Longitude, Latitude, and Altitude of scenario reference point
^ We can explicitly specify srid
^ key-value of arbitrary JSON properties
^ Map with scenario content
^ Some necessary information for viewing and interacting with scenario
| Get transferable content of each scenario object
| Get scenario with no Objects inside.
Used to send scenario information to a geometry loader,
so that geometry loader has scenario context.
* Lenses
trying to update scenario name if it has changed
prefer duplicate properties from a new version
replace older objects with newer ones
get maximum of objId counters to make sure
no objects could have the same object Id
just get a new view state
* Special properties
* Resolved properties
| Resolve view color of object based on object and scenario properties.
| Resolve object height to extrude it if necessary
* Computed and updateable attributes | # LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Model.Scenario
( Scenario, Scenario' (..), getTransferables
, name, geoLoc, srid, properties, objects, objIdSeq, viewState, withoutObjects
, selectedDynamicColor, selectedStaticColor, selectedGroupColor
, defaultStaticColor
, defaultBlockColor, defaultLineColor, defaultPointColor
, defaultObjectHeight
, viewDistance, evaluationCellSize
, servicePluginsProp
, maxCameraDistance, minCameraDistance
, mapZoomLevel, mapOpacity, useMapLayer, mapUrl
, hiddenProperties
, resolvedObjectHeight, resolvedObjectColor
, resolvedObjectColorIgnoreVisible
, ScenarioState (..)
, cameraPos, cameraLoc, cameraLookAt, objectGroups, clippingDist, zoomLimits
, templates, forcedAreaObjId, groupIdSeq, creationPoint, servicePlugins
) where
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Control.Lens (set,(^.),non, _1, _2)
import Control.Applicative ((<|>))
import Numeric.DataFrame hiding (toList)
import Data.Foldable (toList)
import Data.Semigroup (stimesIdempotentMonoid)
import GHC.Generics
import Commons.NoReflex
import Model.Scenario.Properties
import Model.Scenario.ServicePlugin
import Model.Scenario.Object ( GroupId, ObjectId)
import qualified Model.Scenario.Object as Object
import qualified Model.Scenario.Object.Geometry as Geometry
type Scenario = Scenario' 'Object.Renderable
data Scenario' s
= Scenario
{ _name :: !(Maybe JSString)
, _geoLoc :: !(Maybe (Double, Double, Double))
, _srid :: !(Maybe Int)
, _properties :: !Properties
, _objects :: !(Object.Collection' s)
, _objIdSeq :: !ObjectId
^ Keep track of highest to be able to generate more
, _viewState :: !ScenarioState
} deriving Generic
instance FromJSVal (Scenario' Object.Prepared)
instance ToJSVal (Scenario' Object.Prepared)
getTransferables :: Scenario' s -> IO [Transferable]
getTransferables = mapM Object.getTransferable . toList . _objects
withoutObjects :: Scenario' s -> Scenario' Object.Prepared
withoutObjects = set objects mempty
. set (viewState.objectGroups) mempty
name :: Functor f
=> (Maybe JSString -> f (Maybe JSString))
-> Scenario' s -> f (Scenario' s)
name f s = (\x -> s{_name = x}) <$> f (_name s)
geoLoc :: Functor f
=> (Maybe (Double, Double, Double) -> f (Maybe (Double, Double, Double)))
-> Scenario' s -> f (Scenario' s)
geoLoc f s = (\x -> s{_geoLoc = x}) <$> f (_geoLoc s)
srid :: Functor f
=> (Maybe Int -> f (Maybe Int))
-> Scenario' s -> f (Scenario' s)
srid f s = (\x -> s{_srid = x}) <$> f (_srid s)
properties :: Functor f
=> (Properties -> f Properties)
-> Scenario' s -> f (Scenario' s)
properties f s = (\x -> s{_properties = x}) <$> f (_properties s)
objects :: Functor f
=> (Object.Collection' s -> f (Object.Collection' t))
-> Scenario' s -> f (Scenario' t)
objects f s = (\x -> s{_objects = x}) <$> f (_objects s)
objIdSeq :: Functor f
=> (ObjectId -> f ObjectId)
-> Scenario' s -> f (Scenario' s)
objIdSeq f s = (\x -> s{_objIdSeq = x}) <$> f (_objIdSeq s)
viewState :: Functor f
=> (ScenarioState -> f ScenarioState)
-> Scenario' s -> f (Scenario' s)
viewState f s = (\x -> s{_viewState = x}) <$> f (_viewState s)
instance Semigroup (Scenario' s) where
scOld <> scNew = Scenario
_name = _name scNew <|> _name scOld
keeping GeoLocation from older version
, _geoLoc = _geoLoc scOld <|> _geoLoc scNew
keeping SRID from older version
, _srid = _srid scOld <|> _srid scNew
, _properties = _properties scNew <> _properties scOld
, _objects = _objects scNew <> _objects scOld
, _objIdSeq = max (_objIdSeq scOld) (_objIdSeq scNew)
, _viewState = _viewState scNew
}
stimes = stimesIdempotentMonoid
instance Monoid (Scenario' s) where
mempty = Scenario
{ _name = Nothing
, _geoLoc = Nothing
, _srid = Nothing
, _properties = mempty
, _objects = mempty
, _objIdSeq = Object.ObjectId 0
, _viewState = def
}
mappend = (<>)
instance Default (Scenario' s) where
def = mempty
defaultObjectHeight :: Functor f
=> (Double -> f Double) -> Scenario' s -> f (Scenario' s)
defaultObjectHeight f = properties $ property "defaultObjectHeight" g
where
g Nothing = Just <$> f 3.5
g (Just c) = Just <$> f c
selectedDynamicColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
selectedDynamicColor f = properties $ property "selectedDynamicColor" g
where
g Nothing = Just <$> f "#FF6060FF"
g (Just c) = Just <$> f c
selectedGroupColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
selectedGroupColor f = properties $ property "selectedGroupColor" g
where
g Nothing = Just <$> f "#CC8888E0"
g (Just c) = Just <$> f c
selectedStaticColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
selectedStaticColor f = properties $ property "selectedStaticColor" g
where
g Nothing = Just <$> f "#BB8888FF"
g (Just c) = Just <$> f c
defaultStaticColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultStaticColor f = properties $ property "defaultStaticColor" g
where
g Nothing = Just <$> f "#808088E0"
g (Just c) = Just <$> f c
defaultBlockColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultBlockColor f = properties $ property "defaultBlockColor" g
where
g Nothing = Just <$> f "#C0C082FF"
g (Just c) = Just <$> f c
defaultLineColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultLineColor f = properties $ property "defaultLineColor" g
where
g Nothing = Just <$> f "#CC6666FF"
g (Just c) = Just <$> f c
defaultPointColor :: Functor f
=> (HexColor -> f HexColor) -> Scenario' s -> f (Scenario' s)
defaultPointColor f = properties $ property "defaultPointColor" g
where
g Nothing = Just <$> f "#006666FF"
g (Just c) = Just <$> f c
viewDistance :: Functor f
=> (Maybe Float -> f (Maybe Float)) -> Scenario' s -> f (Scenario' s)
viewDistance = properties . property "viewDistance"
maxCameraDistance :: Functor f
=> (Maybe Float -> f (Maybe Float)) -> Scenario' s -> f (Scenario' s)
maxCameraDistance = properties . property "maxCameraDistance"
minCameraDistance :: Functor f
=> (Maybe Float -> f (Maybe Float)) -> Scenario' s -> f (Scenario' s)
minCameraDistance = properties . property "minCameraDistance"
mapZoomLevel :: Functor f
=> (Int -> f Int) -> Scenario' s -> f (Scenario' s)
mapZoomLevel f = properties $ property "mapZoomLevel" g
where
g Nothing = Just <$> f 15
g (Just c) = Just <$> f c
mapOpacity :: Functor f
=> (Double -> f Double) -> Scenario' s -> f (Scenario' s)
mapOpacity f = properties $ property "mapOpacity" g
where
g Nothing = Just <$> f 0.8
g (Just c) = Just <$> f c
useMapLayer :: Functor f
=> (Bool -> f Bool) -> Scenario' s -> f (Scenario' s)
useMapLayer f = properties $ property "useMapLayer" g
where
g Nothing = Just <$> f False
g (Just c) = Just <$> f c
mapUrl :: Functor f
=> (JSString -> f JSString) -> Scenario' s -> f (Scenario' s)
mapUrl f = properties $ property "mapUrl" g
where
g Nothing = Just <$> f "/${z}/${x}/${y}.png"
g (Just c) = Just <$> f c
hiddenProperties :: Functor f
=> ([JSString] -> f [JSString]) -> Scenario' s -> f (Scenario' s)
hiddenProperties f = properties $ property "hiddenProperties" g
where
g Nothing = Just <$> f [ "geomID", "groupID"
, "hiddenProperties", "viewColor"
, "height", "static", "selectable"
, "visible", "special"]
g (Just c) = Just <$> f c
evaluationCellSize :: Functor f
=> (Double -> f Double) -> Scenario' s -> f (Scenario' s)
evaluationCellSize f = properties $ property "evaluationCellSize" g
where
g Nothing = Just <$> f 5.0
g (Just c) = Just <$> f c
servicePluginsProp :: Functor f
=> ([ServicePlugin] -> f [ServicePlugin])
-> Scenario' s -> f (Scenario' s)
servicePluginsProp f = properties $ property "servicePlugins" g
where
g Nothing = nonEmpty <$> f []
g (Just c) = nonEmpty <$> f c
nonEmpty [] = Nothing
nonEmpty xs = Just xs
resolvedObjectColorIgnoreVisible :: Scenario' s -> Object.Object' t -> HexColor
resolvedObjectColorIgnoreVisible s o = o^.Object.viewColor.non sdef
where
sdef = case o^.Object.geometry of
Geometry.Points _ -> s^.defaultPointColor
Geometry.Lines _ -> s^.defaultLineColor
Geometry.Polygons _ -> case o^.Object.objectBehavior of
Object.Static -> s^.defaultStaticColor
Object.Dynamic -> s^.defaultBlockColor
resolvedObjectColor :: Scenario' s -> Object.Object' t -> HexColor
resolvedObjectColor s o
= if o^.Object.visible
then resolvedObjectColorIgnoreVisible s o
else "#00000000"
resolvedObjectHeight :: Scenario' s -> Object.Object' t -> Double
resolvedObjectHeight s o = o^.Object.height.non (s^.defaultObjectHeight)
| settings for qua - view
data ScenarioState
= ScenarioState
{ _cameraPos :: !(Vec3f, Vec3f)
, _objectGroups :: !(Map.Map GroupId [ObjectId])
, _clippingDist :: !Float
, _zoomLimits :: !(Float, Float)
, _templates :: !(Set.Set (Either ObjectId GroupId))
, _forcedAreaObjId :: !(Maybe ObjectId)
, _groupIdSeq :: !GroupId
, _creationPoint :: !(Maybe Vec3f)
, _servicePlugins :: ![ServicePlugin]
} deriving Generic
instance FromJSVal ScenarioState
instance ToJSVal ScenarioState
instance FromJSVal (Either ObjectId GroupId)
instance ToJSVal (Either ObjectId GroupId)
instance FromJSVal (Set.Set (Either ObjectId GroupId)) where
fromJSVal = fmap (fmap Set.fromDistinctAscList) . fromJSVal
instance ToJSVal (Set.Set (Either ObjectId GroupId)) where
toJSVal = toJSVal . Set.toAscList
instance Default ScenarioState where
def = ScenarioState
{ _cameraPos = (vec3 100 150 500, 0)
, _objectGroups = mempty
, _clippingDist = 2000
, _zoomLimits = (1, 1334)
, _templates = mempty
, _forcedAreaObjId = Nothing
, _groupIdSeq = 0
, _creationPoint = Nothing
, _servicePlugins = []
}
cameraPos :: Functor f
=> ((Vec3f, Vec3f) -> f (Vec3f, Vec3f))
-> ScenarioState -> f ScenarioState
cameraPos f s = (\x -> s{_cameraPos = x}) <$> f (_cameraPos s)
cameraLoc :: Functor f
=> (Vec3f -> f Vec3f)
-> ScenarioState -> f ScenarioState
cameraLoc = cameraPos . _1
cameraLookAt :: Functor f
=> (Vec3f -> f Vec3f)
-> ScenarioState -> f ScenarioState
cameraLookAt = cameraPos . _2
objectGroups :: Functor f
=> (Map.Map GroupId [ObjectId] -> f (Map.Map GroupId [ObjectId]))
-> ScenarioState -> f ScenarioState
objectGroups f s = (\x -> s{_objectGroups = x}) <$> f (_objectGroups s)
clippingDist :: Functor f
=> (Float -> f Float)
-> ScenarioState -> f ScenarioState
clippingDist f s = (\x -> s{_clippingDist = x}) <$> f (_clippingDist s)
zoomLimits :: Functor f
=> ((Float, Float) -> f (Float, Float))
-> ScenarioState -> f ScenarioState
zoomLimits f s = (\x -> s{_zoomLimits = x}) <$> f (_zoomLimits s)
templates :: Functor f
=> (Set.Set (Either ObjectId GroupId) -> f (Set.Set (Either ObjectId GroupId) ))
-> ScenarioState -> f ScenarioState
templates f s = (\x -> s{_templates = x}) <$> f (_templates s)
forcedAreaObjId :: Functor f
=> (Maybe ObjectId -> f (Maybe ObjectId))
-> ScenarioState -> f ScenarioState
forcedAreaObjId f s = (\x -> s{_forcedAreaObjId = x}) <$> f (_forcedAreaObjId s)
groupIdSeq :: Functor f
=> (GroupId -> f GroupId)
-> ScenarioState -> f ScenarioState
groupIdSeq f s = (\x -> s{_groupIdSeq = x}) <$> f (_groupIdSeq s)
creationPoint :: Functor f
=> (Maybe Vec3f -> f (Maybe Vec3f))
-> ScenarioState -> f ScenarioState
creationPoint f s = (\x -> s{_creationPoint = x}) <$> f (_creationPoint s)
servicePlugins :: Functor f
=> ([ServicePlugin] -> f [ServicePlugin])
-> ScenarioState -> f ScenarioState
servicePlugins f s = (\x -> s{_servicePlugins = x}) <$> f (_servicePlugins s)
|
2353f2334047f96eddc36d506e5cb5cb75f2b8e1d50bfdf620a7763cb1b6ae37 | naproche/naproche | Unify.hs | -- |
Authors : ( 2017 - 2018 )
--
-- Unification of literals.
module SAD.Prove.Unify (unify) where
import Control.Monad
import SAD.Data.Formula
given two literals we check whether they are eligible for unification
( sign and symbol are the same ) and then try to unify their arguments
(sign and symbol are the same) and then try to unify their arguments-}
unify :: MonadPlus m => Formula -> Formula -> m (Formula -> Formula)
unify (Not l) (Not r) = unify l r
unify l (Not r) = mzero
unify (Not l) r = mzero
unify Bot Bot = return id
unify Bot _ = mzero
unify _ Bot = mzero
unify Top Top = return id
unify Top _ = mzero
unify _ Top = mzero
unify l r = do
let la = ltAtomic l; ra = ltAtomic r
guard (isTrm la && isTrm ra && trmId la == trmId ra)
unif $ zip (trmArgs la) (trmArgs ra)
{- implementation of a standard unification algorithm -}
unif :: MonadPlus m => [(Formula, Formula)] -> m (Formula -> Formula)
unif = fmap (mkSubst . updateSubst) . dive [] -- we keep a list of already assigned variables
where
dive assigned (task@(l,r):rest)
| functionSymb l && functionSymb r -- if both sides have a function symbol
= if clash l r then mzero else dive assigned (newTasks l r ++ rest)
| functionSymb l = dive assigned $ (r, l) : rest
| otherwise
= if l `occursIn` r then mzero -- occurs check
-- save the assignment and unify the rest under this assignment
else dive (task:assigned) $ map (ufSub l r) rest
dive assigned _ = return assigned
--------------------- auxiliary functions
ufSub x t (l,r) = let sb = subst t (varName x) in (sb l, sb r)
newTasks Trm {trmArgs = tArgs} Trm {trmArgs = sArgs} = zip tArgs sArgs
newTasks _ _ = []
-- update earlier assignments with later ones
updateSubst ((x,t):rest) = (x,t) : updateSubst (map (fmap (subst t (varName x))) rest)
updateSubst [] = []
mkSubst assigned f = substs f (map (varName . fst) assigned) (map snd assigned)
clash Trm {trId = tId} Trm {trId = sId} = tId /= sId
clash Var {varName = x} Var {varName = y} = x /= y
clash _ _ = True
-- all other vars are treated as constants
functionSymb Var {varName = VarHole _ } = False
functionSymb Var {varName = VarU _ } = False
functionSymb _ = True
| null | https://raw.githubusercontent.com/naproche/naproche/6284a64b4b84eaa53dd0eb7ecb39737fb9135a0d/src/SAD/Prove/Unify.hs | haskell | |
Unification of literals.
implementation of a standard unification algorithm
we keep a list of already assigned variables
if both sides have a function symbol
occurs check
save the assignment and unify the rest under this assignment
------------------- auxiliary functions
update earlier assignments with later ones
all other vars are treated as constants | Authors : ( 2017 - 2018 )
module SAD.Prove.Unify (unify) where
import Control.Monad
import SAD.Data.Formula
given two literals we check whether they are eligible for unification
( sign and symbol are the same ) and then try to unify their arguments
(sign and symbol are the same) and then try to unify their arguments-}
unify :: MonadPlus m => Formula -> Formula -> m (Formula -> Formula)
unify (Not l) (Not r) = unify l r
unify l (Not r) = mzero
unify (Not l) r = mzero
unify Bot Bot = return id
unify Bot _ = mzero
unify _ Bot = mzero
unify Top Top = return id
unify Top _ = mzero
unify _ Top = mzero
unify l r = do
let la = ltAtomic l; ra = ltAtomic r
guard (isTrm la && isTrm ra && trmId la == trmId ra)
unif $ zip (trmArgs la) (trmArgs ra)
unif :: MonadPlus m => [(Formula, Formula)] -> m (Formula -> Formula)
where
dive assigned (task@(l,r):rest)
= if clash l r then mzero else dive assigned (newTasks l r ++ rest)
| functionSymb l = dive assigned $ (r, l) : rest
| otherwise
else dive (task:assigned) $ map (ufSub l r) rest
dive assigned _ = return assigned
ufSub x t (l,r) = let sb = subst t (varName x) in (sb l, sb r)
newTasks Trm {trmArgs = tArgs} Trm {trmArgs = sArgs} = zip tArgs sArgs
newTasks _ _ = []
updateSubst ((x,t):rest) = (x,t) : updateSubst (map (fmap (subst t (varName x))) rest)
updateSubst [] = []
mkSubst assigned f = substs f (map (varName . fst) assigned) (map snd assigned)
clash Trm {trId = tId} Trm {trId = sId} = tId /= sId
clash Var {varName = x} Var {varName = y} = x /= y
clash _ _ = True
functionSymb Var {varName = VarHole _ } = False
functionSymb Var {varName = VarU _ } = False
functionSymb _ = True
|
2251bec45530564332de21fbb992bc16893bc980f8269b5439e6e6b1b1e9543a | myaosato/clcm | tree.lisp | (defpackage :clcm/tree
(:use :cl
:clcm/utils
:clcm/line
:clcm/node
:clcm/nodes/document)
(:shadow :reverse-children)
(:export :make-tree
:tree->html))
(in-package :clcm/tree)
;; API
(defun make-tree (cm-string)
(-> cm-string
(cm->block-tree)
(reverse-children)))
(defun tree->html (tree)
(->html (root tree)))
;; tree
(defclass block-tree ()
((root :accessor root
:initform (make-instance 'document-node))))
;; cm -> block-tree
(defun cm->block-tree (input-string)
(let ((input-lines (string->lines input-string))
(tree (make-instance 'block-tree)))
(loop :for line :in input-lines
;; side effects !!
:do (setf tree (consumes-line tree line)))
tree))
(defun consumes-line (tree line)
(close!? (root tree) line 0) ;; side effects !!
(add!? (root tree) line 0) ;; side effects !!
tree)
parse inlines
(defun reverse-children (tree)
(clcm/node:reverse-children (root tree))
tree)
| null | https://raw.githubusercontent.com/myaosato/clcm/fd0390bedf00c5be3f5c2eb8176ff73bede797b0/src/tree.lisp | lisp | API
tree
cm -> block-tree
side effects !!
side effects !!
side effects !! | (defpackage :clcm/tree
(:use :cl
:clcm/utils
:clcm/line
:clcm/node
:clcm/nodes/document)
(:shadow :reverse-children)
(:export :make-tree
:tree->html))
(in-package :clcm/tree)
(defun make-tree (cm-string)
(-> cm-string
(cm->block-tree)
(reverse-children)))
(defun tree->html (tree)
(->html (root tree)))
(defclass block-tree ()
((root :accessor root
:initform (make-instance 'document-node))))
(defun cm->block-tree (input-string)
(let ((input-lines (string->lines input-string))
(tree (make-instance 'block-tree)))
(loop :for line :in input-lines
:do (setf tree (consumes-line tree line)))
tree))
(defun consumes-line (tree line)
tree)
parse inlines
(defun reverse-children (tree)
(clcm/node:reverse-children (root tree))
tree)
|
1b78e273defd44194752567c5f7541f7706a4d6ab1b7dbddda86abe9c180f3a0 | jwiegley/notes | Runner.hs | instance Typeable a => Typeable (Last a) where
typeOf (Last x) = typeOf x
instance (Data a, Typeable a) => Data (Last a) where
jww ( 2014 - 02 - 06 ): : Migrate : NYI
toConstr (Last x) = toConstr x
dataTypeOf (Last x) = dataTypeOf x
| null | https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/gists/8851173/Runner.hs | haskell | instance Typeable a => Typeable (Last a) where
typeOf (Last x) = typeOf x
instance (Data a, Typeable a) => Data (Last a) where
jww ( 2014 - 02 - 06 ): : Migrate : NYI
toConstr (Last x) = toConstr x
dataTypeOf (Last x) = dataTypeOf x
| |
8049527c07c34394c8de91744a940daea8bc63200dbb7e9ced11ceeec9f81a44 | plexus/chestnut | httpclient.clj | (ns chestnut.httpclient
(:require [clojure.java.io :as io]
[clojure.java.shell :as sh]
[clojure.string :as str])
(:import java.lang.System
[java.nio.file Files OpenOption Paths]
java.security.cert.CertificateFactory
java.security.KeyStore
[javax.net.ssl SSLContext TrustManagerFactory]))
;; Not actually working :(
#_
(defn letsencrypt-ssl-context
"Java before 8u101 does not recognize Let's Encrypt, so we do a bit of Java
dancing to load the certificate manually.
"
[]
(let [key-store (KeyStore/getInstance (KeyStore/getDefaultType))
key-store-path (Paths/get (System/getProperty "java.home") (into-array String ["lib" "security" "cacerts"]))
cert-factory (CertificateFactory/getInstance "X.509")
cert-file (io/input-stream (io/resource "DSTRootCAX3.crt"))
certificate (.generateCertificate cert-factory cert-file)
trust-manager (TrustManagerFactory/getInstance (TrustManagerFactory/getDefaultAlgorithm))
ssl-context (SSLContext/getInstance "TLS")]
(.load key-store (Files/newInputStream key-store-path (into-array OpenOption ())) (.toCharArray "changeit"))
(.setCertificateEntry key-store "DSTRootCAX3" certificate)
(.init trust-manager key-store)
(.init ssl-context nil (.getTrustManagers trust-manager) nil)
ssl-context
#_(SSLContext/setDefault ssl-context)))
;; borrowed from ring
(defn- double-escape [^String x]
(.replace (.replace x "\\" "\\\\") "$" "\\$"))
(defn percent-encode
"Percent-encode every character in the given string using either the specified
encoding, or UTF-8 by default."
[^String unencoded & [^String encoding]]
(->> (.getBytes unencoded (or encoding "UTF-8"))
(map (partial format "%%%02X"))
(str/join)))
(defn url-encode
"Returns the url-encoded version of the given string, using either a specified
encoding or UTF-8 by default."
[unencoded & [encoding]]
(str/replace
unencoded
#"[^A-Za-z0-9_~.+-]+"
#(double-escape (percent-encode % encoding))))
;;/borrowed from ring
#_(defn http-post!
"A very limited wrapper for doing a POST request, submits parameters in the
URL, rather than the body."
[url params]
(let [param-str (str/join "&" (map
(fn [[k v]]
(str (url-encode (name k)) "=" (url-encode v)))
params))
client (.. (HttpClients/custom)
(setSSLContext (letsencrypt-ssl-context))
build)
post (HttpPost. (str url "?" param-str))]
(.execute client post)))
(defn http-post!
"A very limited wrapper for doing a POST request, submits parameters in the
URL, rather than the body."
[url params]
(let [param-str (str/join "&" (map
(fn [[k v]]
(str (url-encode (name k)) "=" (url-encode v)))
params))
url (str url "?" param-str)]
(sh/sh "curl" "-X" "POST" url)))
| null | https://raw.githubusercontent.com/plexus/chestnut/684b668141586ed5ef4389f94a4dc7f4fde13112/src/chestnut/httpclient.clj | clojure | Not actually working :(
borrowed from ring
/borrowed from ring | (ns chestnut.httpclient
(:require [clojure.java.io :as io]
[clojure.java.shell :as sh]
[clojure.string :as str])
(:import java.lang.System
[java.nio.file Files OpenOption Paths]
java.security.cert.CertificateFactory
java.security.KeyStore
[javax.net.ssl SSLContext TrustManagerFactory]))
#_
(defn letsencrypt-ssl-context
"Java before 8u101 does not recognize Let's Encrypt, so we do a bit of Java
dancing to load the certificate manually.
"
[]
(let [key-store (KeyStore/getInstance (KeyStore/getDefaultType))
key-store-path (Paths/get (System/getProperty "java.home") (into-array String ["lib" "security" "cacerts"]))
cert-factory (CertificateFactory/getInstance "X.509")
cert-file (io/input-stream (io/resource "DSTRootCAX3.crt"))
certificate (.generateCertificate cert-factory cert-file)
trust-manager (TrustManagerFactory/getInstance (TrustManagerFactory/getDefaultAlgorithm))
ssl-context (SSLContext/getInstance "TLS")]
(.load key-store (Files/newInputStream key-store-path (into-array OpenOption ())) (.toCharArray "changeit"))
(.setCertificateEntry key-store "DSTRootCAX3" certificate)
(.init trust-manager key-store)
(.init ssl-context nil (.getTrustManagers trust-manager) nil)
ssl-context
#_(SSLContext/setDefault ssl-context)))
(defn- double-escape [^String x]
(.replace (.replace x "\\" "\\\\") "$" "\\$"))
(defn percent-encode
"Percent-encode every character in the given string using either the specified
encoding, or UTF-8 by default."
[^String unencoded & [^String encoding]]
(->> (.getBytes unencoded (or encoding "UTF-8"))
(map (partial format "%%%02X"))
(str/join)))
(defn url-encode
"Returns the url-encoded version of the given string, using either a specified
encoding or UTF-8 by default."
[unencoded & [encoding]]
(str/replace
unencoded
#"[^A-Za-z0-9_~.+-]+"
#(double-escape (percent-encode % encoding))))
#_(defn http-post!
"A very limited wrapper for doing a POST request, submits parameters in the
URL, rather than the body."
[url params]
(let [param-str (str/join "&" (map
(fn [[k v]]
(str (url-encode (name k)) "=" (url-encode v)))
params))
client (.. (HttpClients/custom)
(setSSLContext (letsencrypt-ssl-context))
build)
post (HttpPost. (str url "?" param-str))]
(.execute client post)))
(defn http-post!
"A very limited wrapper for doing a POST request, submits parameters in the
URL, rather than the body."
[url params]
(let [param-str (str/join "&" (map
(fn [[k v]]
(str (url-encode (name k)) "=" (url-encode v)))
params))
url (str url "?" param-str)]
(sh/sh "curl" "-X" "POST" url)))
|
6438ba90e838bef51d8f60bdeb084b0dfdefecfda5be7aee691fd17acdbe73ba | roburio/builder-web | m20210202.ml | let old_version = 1L and new_version = 1L
let identifier = "2021-02-02"
let migrate_doc = "add index job_build_idx on build"
let rollback_doc = "rollback index job_build_idx on build"
open Grej.Infix
let migrate _datadir (module Db : Caqti_blocking.CONNECTION) =
let job_build_idx =
Caqti_type.unit ->. Caqti_type.unit @@
"CREATE INDEX job_build_idx ON build(job)";
in
Grej.check_version ~user_version:1L (module Db) >>= fun () ->
Db.exec job_build_idx ()
let rollback _datadir (module Db : Caqti_blocking.CONNECTION) =
let q =
Caqti_type.unit ->. Caqti_type.unit @@
"DROP INDEX IF EXISTS job_build_idx"
in
Grej.check_version ~user_version:1L (module Db) >>= fun () ->
Db.exec q ()
| null | https://raw.githubusercontent.com/roburio/builder-web/a85be8730cece0bd78df580fb7d48aff94e060d2/bin/migrations/m20210202.ml | ocaml | let old_version = 1L and new_version = 1L
let identifier = "2021-02-02"
let migrate_doc = "add index job_build_idx on build"
let rollback_doc = "rollback index job_build_idx on build"
open Grej.Infix
let migrate _datadir (module Db : Caqti_blocking.CONNECTION) =
let job_build_idx =
Caqti_type.unit ->. Caqti_type.unit @@
"CREATE INDEX job_build_idx ON build(job)";
in
Grej.check_version ~user_version:1L (module Db) >>= fun () ->
Db.exec job_build_idx ()
let rollback _datadir (module Db : Caqti_blocking.CONNECTION) =
let q =
Caqti_type.unit ->. Caqti_type.unit @@
"DROP INDEX IF EXISTS job_build_idx"
in
Grej.check_version ~user_version:1L (module Db) >>= fun () ->
Db.exec q ()
| |
587ea74c07833f8132d4c844391238d6a582fd44e5238210f6efc2b1c93c7ac1 | petro-rudenko/cdr-analysis | project.clj | (defproject cdr-processing "0.1.0-SNAPSHOT"
:description "CDR data analysis on Storm, Hadoop, Spark and other clever words."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/data.json "0.2.2"]
[clj-time "0.5.1"]
For local mode since of ZK 3.4 problem
;; [org.apache.hadoop/hadoop-hdfs "2.0.6-alpha"] ; For deployment
[ org.apache.hadoop/hadoop-common " 2.0.6 - alpha " ] ]
:profiles {:dev {:dependencies [[storm "0.9.0-wip21"]]}})
| null | https://raw.githubusercontent.com/petro-rudenko/cdr-analysis/5e583b0cca30c4faf474507998bd7a9a0380f569/project.clj | clojure | [org.apache.hadoop/hadoop-hdfs "2.0.6-alpha"] ; For deployment | (defproject cdr-processing "0.1.0-SNAPSHOT"
:description "CDR data analysis on Storm, Hadoop, Spark and other clever words."
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[org.clojure/data.json "0.2.2"]
[clj-time "0.5.1"]
For local mode since of ZK 3.4 problem
[ org.apache.hadoop/hadoop-common " 2.0.6 - alpha " ] ]
:profiles {:dev {:dependencies [[storm "0.9.0-wip21"]]}})
|
ff79b8e7aeac3229294509d7a51bc2be46a36dba5f7beb5f6a015116ccbe4869 | Twinside/FontyFruity | Glyph.hs | # LANGUAGE TupleSections #
# LANGUAGE CPP #
module Graphics.Text.TrueType.Glyph
( GlyphHeader( .. )
, GlyphContour( .. )
, CompositeScaling( .. )
, GlyphComposition( .. )
, GlyphContent( .. )
, Glyph( .. )
, GlyphFlag( .. )
, extractFlatOutline
, emptyGlyph
) where
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid( mempty )
import Control.Applicative( (<*>), (<$>) )
#endif
import Control.DeepSeq
import Data.Bits( setBit, testBit, shiftL )
import Data.Int( Int16 )
import Data.List( mapAccumL, mapAccumR, zip4 )
import Data.Word( Word8, Word16 )
import Data.Binary( Binary( .. ) )
import Data.Binary.Get( Get
, getWord8
, getWord16be )
import Data.Binary.Put( putWord8, putWord16be )
import Data.Tuple( swap )
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
{-import Text.Printf-}
{-import Debug.Trace-}
data GlyphHeader = GlyphHeader
{ -- | If the number of contours is greater than or equal
to zero , this is a single glyph ; if negative , this is
-- a composite glyph.
_glfNumberOfContours :: {-# UNPACK #-} !Int16
-- | Minimum x for coordinate data.
, _glfXMin :: {-# UNPACK #-} !Int16
-- | Minimum y for coordinate data.
, _glfYMin :: {-# UNPACK #-} !Int16
-- | Maximum x for coordinate data.
, _glfXMax :: {-# UNPACK #-} !Int16
-- | Maximum y for coordinate data.
, _glfYMax :: {-# UNPACK #-} !Int16
}
deriving (Eq, Show)
instance NFData GlyphHeader where
rnf (GlyphHeader {}) = ()
emptyGlyphHeader :: GlyphHeader
emptyGlyphHeader = GlyphHeader 0 0 0 0 0
instance Binary GlyphHeader where
get = GlyphHeader <$> g16 <*> g16 <*> g16 <*> g16 <*> g16
where g16 = fromIntegral <$> getWord16be
put (GlyphHeader count xmini ymini xmaxi ymaxi) =
p16 count >> p16 xmini >> p16 ymini >> p16 xmaxi >> p16 ymaxi
where p16 = putWord16be . fromIntegral
data GlyphContour = GlyphContour
{ _glyphInstructions :: !(VU.Vector Word8)
, _glyphFlags :: ![GlyphFlag]
, _glyphPoints :: ![VU.Vector (Int16, Int16)]
}
deriving (Eq, Show)
instance NFData GlyphContour where
rnf (GlyphContour instr fl points) =
instr `seq` fl `seq` points `seq` ()
-- | Transformation matrix used to transform composite
-- glyph
--
-- @
-- | a b |
-- | c d |
-- @
--
data CompositeScaling = CompositeScaling
{ _a :: {-# UNPACK #-} !Int16 -- ^ a coeff.
, _b :: {-# UNPACK #-} !Int16 -- ^ b coeff.
, _c :: {-# UNPACK #-} !Int16 -- ^ c coeff.
, _d :: {-# UNPACK #-} !Int16 -- ^ d coeff.
}
deriving (Eq, Show)
data GlyphComposition = GlyphComposition
{ _glyphCompositeFlag :: {-# UNPACK #-} !Word16
, _glyphCompositeIndex :: {-# UNPACK #-} !Word16
, _glyphCompositionArg :: {-# UNPACK #-} !(Int16, Int16)
, _glyphCompositionOffsetArgs :: !Bool -- ^ True: args are offsets;
-- False: args are point indices
, _glyphCompositionScale :: !CompositeScaling
}
deriving (Eq, Show)
data GlyphContent
= GlyphEmpty
| GlyphSimple !GlyphContour
| GlyphComposite !(V.Vector GlyphComposition) !(VU.Vector Word8)
deriving (Eq, Show)
data Glyph = Glyph
{ _glyphHeader :: !GlyphHeader
, _glyphContent :: !GlyphContent
}
deriving (Eq, Show)
instance NFData Glyph where
rnf (Glyph hdr cont) =
rnf hdr `seq` cont `seq` ()
emptyGlyph :: Glyph
emptyGlyph = Glyph emptyGlyphHeader GlyphEmpty
getCompositeOutline :: Get GlyphContent
getCompositeOutline =
(\(instr, vals) -> GlyphComposite (V.fromList vals) instr) <$> go
where
go = do
flag <- getWord16be
index <- getWord16be
args <- fetchArguments flag
scaling <- fetchScaling flag
let value = GlyphComposition flag index args
(flag `testBit` aRGS_ARE_XY_VALUES) scaling
if flag `testBit` mORE_COMPONENTS then
(\(instr, acc) -> (instr, value : acc )) <$> go
else
if flag `testBit` wE_HAVE_INSTRUCTIONS then do
count <- fromIntegral <$> getWord16be
(, [value]) <$> VU.replicateM count getWord8
else
return (mempty, [value])
fetchArguments flag
| flag `testBit` aRG_1_AND_2_ARE_WORDS =
(,) <$> getInt16be <*> getInt16be
| otherwise =
(,) <$> getInt8 <*> getInt8
fetchScaling flag
| flag `testBit` wE_HAVE_A_SCALE =
(\v -> CompositeScaling v 0 0 v) <$> getF2Dot14
| flag `testBit` wE_HAVE_AN_X_AND_Y_SCALE =
(\x y -> CompositeScaling x 0 0 y) <$> getF2Dot14 <*> getF2Dot14
| flag `testBit` wE_HAVE_A_TWO_BY_TWO =
CompositeScaling <$> getF2Dot14 <*> getF2Dot14
<*> getF2Dot14 <*> getF2Dot14
| otherwise = return $ CompositeScaling one 0 0 one
where one = 1 `shiftL` 14
getInt16be = fromIntegral <$> getWord16be
getF2Dot14 = fromIntegral <$> getWord16be
getInt8 = fixByteSign . fromIntegral <$> getWord8
fixByteSign value = if value >= 0x80 then value - 0x100 else value
aRG_1_AND_2_ARE_WORDS = 0
aRGS_ARE_XY_VALUES = 1
2
wE_HAVE_A_SCALE = 3
rESERVED = 4
mORE_COMPONENTS = 5
wE_HAVE_AN_X_AND_Y_SCALE = 6
wE_HAVE_A_TWO_BY_TWO = 7
wE_HAVE_INSTRUCTIONS = 8
9
oVERLAP_COMPOUND = 10
11
uNSCALED_COMPONENT_OFFSET = 12
data GlyphFlag = GlyphFlag
{ -- | If set, the point is on the curve;
-- otherwise, it is off the curve.
_flagOnCurve :: !Bool
| If set , the corresponding x - coordinate is 1
byte long . If not set , 2 bytes .
, _flagXshort :: !Bool
| If set , the corresponding y - coordinate is 1
byte long . If not set , 2 bytes .
, _flagYShort :: !Bool
-- | If set, the next byte specifies the number of additional
-- times this set of flags is to be repeated. In this way, the
-- number of flags listed can be smaller than the number of
-- points in a character.
, _flagRepeat :: !Bool
| This flag has two meanings , depending on how the x - Short
-- Vector flag is set. If x-Short Vector is set, this bit
describes the sign of the value , with 1 equalling positive and
0 negative . If the x - Short Vector bit is not set and this bit is set ,
-- then the current x-coordinate is the same as the previous x-coordinate.
If the x - Short Vector bit is not set and this bit is also not set , the
current x - coordinate is a signed 16 - bit delta vector .
, _flagXSame :: !Bool
| This flag has two meanings , depending on how the y - Short Vector flag
-- is set. If y-Short Vector is set, this bit describes the sign of the
value , with 1 equalling positive and 0 negative . If the y - Short Vector
-- bit is not set and this bit is set, then the current y-coordinate is the
same as the previous y - coordinate . If the y - Short Vector bit is not set
-- and this bit is also not set, the current y-coordinate is a signed
16 - bit delta vector .
, _flagYSame :: !Bool
}
deriving (Eq, Show)
instance Binary GlyphFlag where
put (GlyphFlag a0 a1 a2 a3 a4 a5) =
putWord8 . foldl setter 0 $ zip [0..] [a0, a1, a2, a3, a4, a5]
where setter v ( _, False) = v
setter v (ix, True) = setBit v ix
get = do
tester <- testBit <$> getWord8
return GlyphFlag
{ _flagOnCurve = tester 0
, _flagXshort = tester 1
, _flagYShort = tester 2
, _flagRepeat = tester 3
, _flagXSame = tester 4
, _flagYSame = tester 5
}
getGlyphFlags :: Int -> Get [GlyphFlag]
getGlyphFlags count = go 0
where
go n | n >= count = return []
go n = do
flag <- get
if _flagRepeat flag
then do
repeatCount <- fromIntegral <$> getWord8
let real = min (count - n) (repeatCount + 1)
(replicate real flag ++) <$> go (n + real)
else (flag :) <$> go (n + 1)
getCoords :: [GlyphFlag] -> Get (VU.Vector (Int16, Int16))
getCoords flags =
VU.fromList <$> (zip <$> go (_flagXSame, _flagXshort) 0 flags
<*> go (_flagYSame, _flagYShort) 0 flags)
where
go _ _ [] = return []
go axx@(isSame, isShort) prevCoord (flag:flagRest) = do
let fetcher
| isShort flag && isSame flag =
(prevCoord +) . fromIntegral <$> getWord8
| isShort flag =
(prevCoord - ) . fromIntegral <$> getWord8
| isSame flag =
return prevCoord
| otherwise =
(prevCoord +) . fromIntegral <$> getWord16be
newCoord <- fetcher
(newCoord :) <$> go axx newCoord flagRest
extractFlatOutline :: GlyphContour
-> [VU.Vector (Int16, Int16)]
extractFlatOutline contour = zipWith (curry go) flagGroup coords
where
allFlags = _glyphFlags contour
coords = _glyphPoints contour
(_, flagGroup) =
mapAccumL (\acc v -> swap $ splitAt (VU.length v) acc) allFlags coords
go (flags, coord)
| VU.null coord = mempty
| otherwise = VU.fromList . (firstPoint :) $ expand mixed
where
isOnSide = map _flagOnCurve flags
firstOnCurve = head isOnSide
lst@(firstPoint:xs) = VU.toList coord
mixed = zip4 isOnSide (tail isOnSide) lst xs
midPoint (x1, y1) (x2, y2) =
((x1 + x2) `div` 2, (y1 + y2) `div` 2)
expand [] = []
expand [(onp, on, prevPoint, currPoint)]
| onp == on = (prevPoint `midPoint` currPoint) : endJunction
| otherwise = endJunction
where endJunction
| on && firstOnCurve =
[currPoint, currPoint `midPoint` firstPoint, firstPoint]
| otherwise = [currPoint, firstPoint]
expand ((onp, on, prevPoint, currPoint):rest)
| onp == on = prevPoint `midPoint` currPoint : currPoint : expand rest
| otherwise = currPoint : expand rest
getSimpleOutline :: Int16 -> Get GlyphContent
getSimpleOutline counterCount = do
endOfPoints <- VU.replicateM (fromIntegral counterCount) getWord16be
let pointCount = VU.last endOfPoints + 1
instructionCount <- fromIntegral <$> getWord16be
instructions <- VU.replicateM instructionCount getWord8
flags <- getGlyphFlags $ fromIntegral pointCount
GlyphSimple . GlyphContour instructions flags
. breakOutline endOfPoints <$> getCoords flags
where
prepender (v, lst) = v : lst
breakOutline endPoints coords =
prepender . mapAccumR breaker coords . VU.toList $ VU.init endPoints
where breaker array ix = VU.splitAt (fromIntegral ix + 1) array
instance Binary Glyph where
put _ = error "Glyph.put - unimplemented"
get = do
hdr <- get
case _glfNumberOfContours hdr of
-1 -> Glyph hdr <$> getCompositeOutline
n -> Glyph hdr <$> getSimpleOutline n
| null | https://raw.githubusercontent.com/Twinside/FontyFruity/636eeff6547478ba304cdd7b85ecaa24acc65062/src/Graphics/Text/TrueType/Glyph.hs | haskell | import Text.Printf
import Debug.Trace
| If the number of contours is greater than or equal
a composite glyph.
# UNPACK #
| Minimum x for coordinate data.
# UNPACK #
| Minimum y for coordinate data.
# UNPACK #
| Maximum x for coordinate data.
# UNPACK #
| Maximum y for coordinate data.
# UNPACK #
| Transformation matrix used to transform composite
glyph
@
| a b |
| c d |
@
# UNPACK #
^ a coeff.
# UNPACK #
^ b coeff.
# UNPACK #
^ c coeff.
# UNPACK #
^ d coeff.
# UNPACK #
# UNPACK #
# UNPACK #
^ True: args are offsets;
False: args are point indices
| If set, the point is on the curve;
otherwise, it is off the curve.
| If set, the next byte specifies the number of additional
times this set of flags is to be repeated. In this way, the
number of flags listed can be smaller than the number of
points in a character.
Vector flag is set. If x-Short Vector is set, this bit
then the current x-coordinate is the same as the previous x-coordinate.
is set. If y-Short Vector is set, this bit describes the sign of the
bit is not set and this bit is set, then the current y-coordinate is the
and this bit is also not set, the current y-coordinate is a signed | # LANGUAGE TupleSections #
# LANGUAGE CPP #
module Graphics.Text.TrueType.Glyph
( GlyphHeader( .. )
, GlyphContour( .. )
, CompositeScaling( .. )
, GlyphComposition( .. )
, GlyphContent( .. )
, Glyph( .. )
, GlyphFlag( .. )
, extractFlatOutline
, emptyGlyph
) where
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid( mempty )
import Control.Applicative( (<*>), (<$>) )
#endif
import Control.DeepSeq
import Data.Bits( setBit, testBit, shiftL )
import Data.Int( Int16 )
import Data.List( mapAccumL, mapAccumR, zip4 )
import Data.Word( Word8, Word16 )
import Data.Binary( Binary( .. ) )
import Data.Binary.Get( Get
, getWord8
, getWord16be )
import Data.Binary.Put( putWord8, putWord16be )
import Data.Tuple( swap )
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
data GlyphHeader = GlyphHeader
to zero , this is a single glyph ; if negative , this is
}
deriving (Eq, Show)
instance NFData GlyphHeader where
rnf (GlyphHeader {}) = ()
emptyGlyphHeader :: GlyphHeader
emptyGlyphHeader = GlyphHeader 0 0 0 0 0
instance Binary GlyphHeader where
get = GlyphHeader <$> g16 <*> g16 <*> g16 <*> g16 <*> g16
where g16 = fromIntegral <$> getWord16be
put (GlyphHeader count xmini ymini xmaxi ymaxi) =
p16 count >> p16 xmini >> p16 ymini >> p16 xmaxi >> p16 ymaxi
where p16 = putWord16be . fromIntegral
data GlyphContour = GlyphContour
{ _glyphInstructions :: !(VU.Vector Word8)
, _glyphFlags :: ![GlyphFlag]
, _glyphPoints :: ![VU.Vector (Int16, Int16)]
}
deriving (Eq, Show)
instance NFData GlyphContour where
rnf (GlyphContour instr fl points) =
instr `seq` fl `seq` points `seq` ()
data CompositeScaling = CompositeScaling
}
deriving (Eq, Show)
data GlyphComposition = GlyphComposition
, _glyphCompositionScale :: !CompositeScaling
}
deriving (Eq, Show)
data GlyphContent
= GlyphEmpty
| GlyphSimple !GlyphContour
| GlyphComposite !(V.Vector GlyphComposition) !(VU.Vector Word8)
deriving (Eq, Show)
data Glyph = Glyph
{ _glyphHeader :: !GlyphHeader
, _glyphContent :: !GlyphContent
}
deriving (Eq, Show)
instance NFData Glyph where
rnf (Glyph hdr cont) =
rnf hdr `seq` cont `seq` ()
emptyGlyph :: Glyph
emptyGlyph = Glyph emptyGlyphHeader GlyphEmpty
getCompositeOutline :: Get GlyphContent
getCompositeOutline =
(\(instr, vals) -> GlyphComposite (V.fromList vals) instr) <$> go
where
go = do
flag <- getWord16be
index <- getWord16be
args <- fetchArguments flag
scaling <- fetchScaling flag
let value = GlyphComposition flag index args
(flag `testBit` aRGS_ARE_XY_VALUES) scaling
if flag `testBit` mORE_COMPONENTS then
(\(instr, acc) -> (instr, value : acc )) <$> go
else
if flag `testBit` wE_HAVE_INSTRUCTIONS then do
count <- fromIntegral <$> getWord16be
(, [value]) <$> VU.replicateM count getWord8
else
return (mempty, [value])
fetchArguments flag
| flag `testBit` aRG_1_AND_2_ARE_WORDS =
(,) <$> getInt16be <*> getInt16be
| otherwise =
(,) <$> getInt8 <*> getInt8
fetchScaling flag
| flag `testBit` wE_HAVE_A_SCALE =
(\v -> CompositeScaling v 0 0 v) <$> getF2Dot14
| flag `testBit` wE_HAVE_AN_X_AND_Y_SCALE =
(\x y -> CompositeScaling x 0 0 y) <$> getF2Dot14 <*> getF2Dot14
| flag `testBit` wE_HAVE_A_TWO_BY_TWO =
CompositeScaling <$> getF2Dot14 <*> getF2Dot14
<*> getF2Dot14 <*> getF2Dot14
| otherwise = return $ CompositeScaling one 0 0 one
where one = 1 `shiftL` 14
getInt16be = fromIntegral <$> getWord16be
getF2Dot14 = fromIntegral <$> getWord16be
getInt8 = fixByteSign . fromIntegral <$> getWord8
fixByteSign value = if value >= 0x80 then value - 0x100 else value
aRG_1_AND_2_ARE_WORDS = 0
aRGS_ARE_XY_VALUES = 1
2
wE_HAVE_A_SCALE = 3
rESERVED = 4
mORE_COMPONENTS = 5
wE_HAVE_AN_X_AND_Y_SCALE = 6
wE_HAVE_A_TWO_BY_TWO = 7
wE_HAVE_INSTRUCTIONS = 8
9
oVERLAP_COMPOUND = 10
11
uNSCALED_COMPONENT_OFFSET = 12
data GlyphFlag = GlyphFlag
_flagOnCurve :: !Bool
| If set , the corresponding x - coordinate is 1
byte long . If not set , 2 bytes .
, _flagXshort :: !Bool
| If set , the corresponding y - coordinate is 1
byte long . If not set , 2 bytes .
, _flagYShort :: !Bool
, _flagRepeat :: !Bool
| This flag has two meanings , depending on how the x - Short
describes the sign of the value , with 1 equalling positive and
0 negative . If the x - Short Vector bit is not set and this bit is set ,
If the x - Short Vector bit is not set and this bit is also not set , the
current x - coordinate is a signed 16 - bit delta vector .
, _flagXSame :: !Bool
| This flag has two meanings , depending on how the y - Short Vector flag
value , with 1 equalling positive and 0 negative . If the y - Short Vector
same as the previous y - coordinate . If the y - Short Vector bit is not set
16 - bit delta vector .
, _flagYSame :: !Bool
}
deriving (Eq, Show)
instance Binary GlyphFlag where
put (GlyphFlag a0 a1 a2 a3 a4 a5) =
putWord8 . foldl setter 0 $ zip [0..] [a0, a1, a2, a3, a4, a5]
where setter v ( _, False) = v
setter v (ix, True) = setBit v ix
get = do
tester <- testBit <$> getWord8
return GlyphFlag
{ _flagOnCurve = tester 0
, _flagXshort = tester 1
, _flagYShort = tester 2
, _flagRepeat = tester 3
, _flagXSame = tester 4
, _flagYSame = tester 5
}
getGlyphFlags :: Int -> Get [GlyphFlag]
getGlyphFlags count = go 0
where
go n | n >= count = return []
go n = do
flag <- get
if _flagRepeat flag
then do
repeatCount <- fromIntegral <$> getWord8
let real = min (count - n) (repeatCount + 1)
(replicate real flag ++) <$> go (n + real)
else (flag :) <$> go (n + 1)
getCoords :: [GlyphFlag] -> Get (VU.Vector (Int16, Int16))
getCoords flags =
VU.fromList <$> (zip <$> go (_flagXSame, _flagXshort) 0 flags
<*> go (_flagYSame, _flagYShort) 0 flags)
where
go _ _ [] = return []
go axx@(isSame, isShort) prevCoord (flag:flagRest) = do
let fetcher
| isShort flag && isSame flag =
(prevCoord +) . fromIntegral <$> getWord8
| isShort flag =
(prevCoord - ) . fromIntegral <$> getWord8
| isSame flag =
return prevCoord
| otherwise =
(prevCoord +) . fromIntegral <$> getWord16be
newCoord <- fetcher
(newCoord :) <$> go axx newCoord flagRest
extractFlatOutline :: GlyphContour
-> [VU.Vector (Int16, Int16)]
extractFlatOutline contour = zipWith (curry go) flagGroup coords
where
allFlags = _glyphFlags contour
coords = _glyphPoints contour
(_, flagGroup) =
mapAccumL (\acc v -> swap $ splitAt (VU.length v) acc) allFlags coords
go (flags, coord)
| VU.null coord = mempty
| otherwise = VU.fromList . (firstPoint :) $ expand mixed
where
isOnSide = map _flagOnCurve flags
firstOnCurve = head isOnSide
lst@(firstPoint:xs) = VU.toList coord
mixed = zip4 isOnSide (tail isOnSide) lst xs
midPoint (x1, y1) (x2, y2) =
((x1 + x2) `div` 2, (y1 + y2) `div` 2)
expand [] = []
expand [(onp, on, prevPoint, currPoint)]
| onp == on = (prevPoint `midPoint` currPoint) : endJunction
| otherwise = endJunction
where endJunction
| on && firstOnCurve =
[currPoint, currPoint `midPoint` firstPoint, firstPoint]
| otherwise = [currPoint, firstPoint]
expand ((onp, on, prevPoint, currPoint):rest)
| onp == on = prevPoint `midPoint` currPoint : currPoint : expand rest
| otherwise = currPoint : expand rest
getSimpleOutline :: Int16 -> Get GlyphContent
getSimpleOutline counterCount = do
endOfPoints <- VU.replicateM (fromIntegral counterCount) getWord16be
let pointCount = VU.last endOfPoints + 1
instructionCount <- fromIntegral <$> getWord16be
instructions <- VU.replicateM instructionCount getWord8
flags <- getGlyphFlags $ fromIntegral pointCount
GlyphSimple . GlyphContour instructions flags
. breakOutline endOfPoints <$> getCoords flags
where
prepender (v, lst) = v : lst
breakOutline endPoints coords =
prepender . mapAccumR breaker coords . VU.toList $ VU.init endPoints
where breaker array ix = VU.splitAt (fromIntegral ix + 1) array
instance Binary Glyph where
put _ = error "Glyph.put - unimplemented"
get = do
hdr <- get
case _glfNumberOfContours hdr of
-1 -> Glyph hdr <$> getCompositeOutline
n -> Glyph hdr <$> getSimpleOutline n
|
040d1c0a361dd782f2d05271aadbcbe5709acd88651f651a15512c30be30251f | slipstream/SlipStreamServer | notification.clj | (ns com.sixsq.slipstream.ssclj.resources.notification
"
Notification resources provide a timestamp for the occurrence of some action. These
are used within the SlipStream server to mark changes in the lifecycle of a
cloud application and for other important actions.
"
(:require
[com.sixsq.slipstream.auth.acl :as a]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.schema :as c]
[com.sixsq.slipstream.ssclj.resources.common.std-crud :as std-crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.notification.utils :as notification-utils]
[com.sixsq.slipstream.ssclj.resources.spec.notification :as notification]))
(def ^:const resource-tag :notifications)
(def ^:const resource-name notification-utils/resource-name)
(def ^:const resource-url notification-utils/resource-url)
(def ^:const collection-name "NotificationCollection")
(def ^:const resource-uri notification-utils/resource-uri)
(def ^:const collection-uri (str c/cimi-schema-uri collection-name))
(def collection-acl notification-utils/collection-acl)
;;
" Implementations " of declared in crud namespace
;;
(def validate-fn (u/create-spec-validation-fn ::notification/notification))
(defmethod crud/validate
resource-uri
[resource]
(validate-fn resource))
(defmethod crud/add resource-name
[request]
(notification-utils/add-impl request))
(def retrieve-impl (std-crud/retrieve-fn resource-name))
(defmethod crud/retrieve resource-name
[request]
(retrieve-impl request))
(def delete-impl (std-crud/delete-fn resource-name))
(defmethod crud/delete resource-name
[request]
(delete-impl request))
;;
;; available operations
;;
(defmethod crud/set-operations resource-uri
[resource request]
(try
(a/can-modify? resource request)
(let [href (:id resource)
^String resourceURI (:resourceURI resource)
ops (if (.endsWith resourceURI "Collection")
[{:rel (:add c/action-uri) :href href}]
[{:rel (:delete c/action-uri) :href href}])]
(assoc resource :operations ops))
(catch Exception e
(dissoc resource :operations))))
;;
;; collection
;;
(def query-impl (std-crud/query-fn resource-name collection-acl collection-uri resource-tag))
(defmethod crud/query resource-name
[{{:keys [orderby]} :cimi-params :as request}]
(query-impl (assoc-in request [:cimi-params :orderby] (if (seq orderby) orderby [["timestamp" :desc]]))))
;;
;; initialization
;;
(defn initialize
[]
(std-crud/initialize resource-url ::notification/notification))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi-resources/src/com/sixsq/slipstream/ssclj/resources/notification.clj | clojure |
available operations
collection
initialization
| (ns com.sixsq.slipstream.ssclj.resources.notification
"
Notification resources provide a timestamp for the occurrence of some action. These
are used within the SlipStream server to mark changes in the lifecycle of a
cloud application and for other important actions.
"
(:require
[com.sixsq.slipstream.auth.acl :as a]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.schema :as c]
[com.sixsq.slipstream.ssclj.resources.common.std-crud :as std-crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.notification.utils :as notification-utils]
[com.sixsq.slipstream.ssclj.resources.spec.notification :as notification]))
(def ^:const resource-tag :notifications)
(def ^:const resource-name notification-utils/resource-name)
(def ^:const resource-url notification-utils/resource-url)
(def ^:const collection-name "NotificationCollection")
(def ^:const resource-uri notification-utils/resource-uri)
(def ^:const collection-uri (str c/cimi-schema-uri collection-name))
(def collection-acl notification-utils/collection-acl)
" Implementations " of declared in crud namespace
(def validate-fn (u/create-spec-validation-fn ::notification/notification))
(defmethod crud/validate
resource-uri
[resource]
(validate-fn resource))
(defmethod crud/add resource-name
[request]
(notification-utils/add-impl request))
(def retrieve-impl (std-crud/retrieve-fn resource-name))
(defmethod crud/retrieve resource-name
[request]
(retrieve-impl request))
(def delete-impl (std-crud/delete-fn resource-name))
(defmethod crud/delete resource-name
[request]
(delete-impl request))
(defmethod crud/set-operations resource-uri
[resource request]
(try
(a/can-modify? resource request)
(let [href (:id resource)
^String resourceURI (:resourceURI resource)
ops (if (.endsWith resourceURI "Collection")
[{:rel (:add c/action-uri) :href href}]
[{:rel (:delete c/action-uri) :href href}])]
(assoc resource :operations ops))
(catch Exception e
(dissoc resource :operations))))
(def query-impl (std-crud/query-fn resource-name collection-acl collection-uri resource-tag))
(defmethod crud/query resource-name
[{{:keys [orderby]} :cimi-params :as request}]
(query-impl (assoc-in request [:cimi-params :orderby] (if (seq orderby) orderby [["timestamp" :desc]]))))
(defn initialize
[]
(std-crud/initialize resource-url ::notification/notification))
|
0b86f3c605324b5b44e4593d8d43588597ad4f6ef0aa116c93b065b318cc2634 | deadcode/Learning-CL--David-Touretzky | 6.14.lisp | (format t "~s = ~s~%" '(INTERSECTION '(LET US SEE) '(LET US SEE)) (INTERSECTION '(LET US SEE) '(LET US SEE)))
| null | https://raw.githubusercontent.com/deadcode/Learning-CL--David-Touretzky/b4557c33f58e382f765369971e6a4747c27ca692/Chapter%206/6.14.lisp | lisp | (format t "~s = ~s~%" '(INTERSECTION '(LET US SEE) '(LET US SEE)) (INTERSECTION '(LET US SEE) '(LET US SEE)))
| |
3776c1e8c19e11f434d1da611148ba490fda96d2ee0a9420d54869d12b75f4b4 | droundy/iolaus-broken | Colors.hs | module Iolaus.Colors ( Color, colorCode, resetCode, spaceColor,
colorMeta, colorOld, colorNew,
colorPlain, rainbow ) where
import System.IO.Unsafe ( unsafePerformIO )
import Git.Plumbing ( getColorWithDefault )
data Color = Color String String
deriving ( Show, Eq )
colorCode :: Color -> String
colorCode (Color c d) = unsafePerformIO $ getColorWithDefault c d
resetCode :: String
resetCode = "\x1B[00m"
spaceColor :: Color -> Color
spaceColor (Color c d) = Color (c++".space") d'
where d' = case words d of [d0,"bold"] -> d0++" ul"
_ -> d++" ul"
colorMeta :: Color
colorMeta = Color "color.diff.meta" "blue bold"
colorOld :: Color
colorOld = Color "color.diff.old" "red bold"
colorNew :: Color
colorNew = Color "color.diff.new" "green bold"
colorPlain :: Color
colorPlain = Color "" ""
rainbow :: [Color]
rainbow = [colorPlain,
Color "c2" "blue",
Color "c2" "magenta",
Color "c3" "red",
Color "c3" "yellow",
Color "c3" "cyan",
Color "c3" "green",
Color "c3" "bold",
Color "c2" "blue bold",
Color "c2" "magenta bold",
Color "c3" "red bold",
Color "c3" "yellow bold",
Color "c3" "cyan bold",
Color "c3" "green bold"]
| null | https://raw.githubusercontent.com/droundy/iolaus-broken/e40c001f3c5a106bf39f437d6349858e7e9bf51e/Iolaus/Colors.hs | haskell | module Iolaus.Colors ( Color, colorCode, resetCode, spaceColor,
colorMeta, colorOld, colorNew,
colorPlain, rainbow ) where
import System.IO.Unsafe ( unsafePerformIO )
import Git.Plumbing ( getColorWithDefault )
data Color = Color String String
deriving ( Show, Eq )
colorCode :: Color -> String
colorCode (Color c d) = unsafePerformIO $ getColorWithDefault c d
resetCode :: String
resetCode = "\x1B[00m"
spaceColor :: Color -> Color
spaceColor (Color c d) = Color (c++".space") d'
where d' = case words d of [d0,"bold"] -> d0++" ul"
_ -> d++" ul"
colorMeta :: Color
colorMeta = Color "color.diff.meta" "blue bold"
colorOld :: Color
colorOld = Color "color.diff.old" "red bold"
colorNew :: Color
colorNew = Color "color.diff.new" "green bold"
colorPlain :: Color
colorPlain = Color "" ""
rainbow :: [Color]
rainbow = [colorPlain,
Color "c2" "blue",
Color "c2" "magenta",
Color "c3" "red",
Color "c3" "yellow",
Color "c3" "cyan",
Color "c3" "green",
Color "c3" "bold",
Color "c2" "blue bold",
Color "c2" "magenta bold",
Color "c3" "red bold",
Color "c3" "yellow bold",
Color "c3" "cyan bold",
Color "c3" "green bold"]
| |
8e989f5edb37bee55e51f6bd0620f37b2b56bd603bdcf835b61b6b90471c73c1 | contested-space/seer | seer_sup.erl | -module(seer_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
init([]) ->
SupFlags = #{strategy => one_for_all, intensity => 0, period => 1},
Poller = #{
id => seer_server,
start => {seer_server, start_link, []},
shutdown => 2000,
restart => permanent,
type => worker,
modules => [seer_server]
},
ChildSpecs = [Poller],
{ok, {SupFlags, ChildSpecs}}.
| null | https://raw.githubusercontent.com/contested-space/seer/f9879bce8632375d07b20443e8e3d7d88964b230/src/seer_sup.erl | erlang | -module(seer_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
init([]) ->
SupFlags = #{strategy => one_for_all, intensity => 0, period => 1},
Poller = #{
id => seer_server,
start => {seer_server, start_link, []},
shutdown => 2000,
restart => permanent,
type => worker,
modules => [seer_server]
},
ChildSpecs = [Poller],
{ok, {SupFlags, ChildSpecs}}.
| |
82b8422bb9b751003de9bda0dded152bf66f5af37b4fba1c619cff0ba365c893 | OctopiChalmers/haski | Vec.hs | # LANGUAGE KindSignatures #
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
{-# LANGUAGE GADTs #-}
-- needed for `++.`
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
module Haski.Vec where
import Prelude hiding (zipWith, (++), unzip)
import GHC.TypeLits
-- | Non-empty vector
data Vec (n :: Nat) a where
Last :: a -> Vec 1 a
Cons :: a -> Vec n a -> Vec (n + 1) a
Convert vector to list
toList :: Vec n a -> [ a ]
toList (Last x) = [ x ]
toList (Cons x v) = x : toList v
-- Append vectors
(++) :: Vec n a -> Vec m a -> Vec (n + m) a
v ++ (Last x) = Cons x v
v ++ (Cons x u) = Cons x (v ++ u)
First element of a vector
head :: Vec n a -> a
head (Last x) = x
head (Cons x _) = x
-- Apply
ap :: Vec n (a -> b) -> Vec n a -> Vec n b
ap f x = zipWith ($) f x
zipWith :: (a -> b -> c) -> Vec n a -> Vec n b -> Vec n c
zipWith f (Last x) (Last y) = Last (f x y)
zipWith f (Cons x xs) (Cons y ys) = Cons (f x y) (zipWith f xs ys)
zipWithM :: Applicative m => (a -> b -> m c) -> Vec n a -> Vec n b -> m (Vec n c)
zipWithM f x y = sequenceA (zipWith f x y)
unzipWith :: (c -> (a,b)) -> Vec n c -> (Vec n a, Vec n b)
unzipWith f (Last x) = let (p,q) = f x
in (Last p, Last q)
unzipWith f (Cons x xs) = let (p,q) = f x ; (ps,qs) = unzipWith f xs
in (Cons p ps, Cons q qs)
unzip :: Vec n (a, b) -> (Vec n a, Vec n b)
unzip = unzipWith id
instance Foldable (Vec n) where
foldr f b (Last x) = f x b
foldr f b (Cons x xs) = f x (foldr f b xs)
instance Traversable (Vec n) where
traverse f (Last x) = Last <$> (f x)
traverse f (Cons x xs) = Cons <$> (f x) <*> traverse f xs
-- gives definition for sequenceA
instance Functor (Vec n) where
fmap f (Last x) = Last (f x)
fmap f (Cons x v) = Cons (f x) (fmap f v)
| null | https://raw.githubusercontent.com/OctopiChalmers/haski/97835d6d90d0c82d29864db03955db0aaaf08c67/src/Haski/Vec.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE GADTs #
needed for `++.`
# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #
| Non-empty vector
Append vectors
Apply
gives definition for sequenceA | # LANGUAGE KindSignatures #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE UndecidableInstances #
# LANGUAGE DataKinds #
# LANGUAGE TypeOperators #
module Haski.Vec where
import Prelude hiding (zipWith, (++), unzip)
import GHC.TypeLits
data Vec (n :: Nat) a where
Last :: a -> Vec 1 a
Cons :: a -> Vec n a -> Vec (n + 1) a
Convert vector to list
toList :: Vec n a -> [ a ]
toList (Last x) = [ x ]
toList (Cons x v) = x : toList v
(++) :: Vec n a -> Vec m a -> Vec (n + m) a
v ++ (Last x) = Cons x v
v ++ (Cons x u) = Cons x (v ++ u)
First element of a vector
head :: Vec n a -> a
head (Last x) = x
head (Cons x _) = x
ap :: Vec n (a -> b) -> Vec n a -> Vec n b
ap f x = zipWith ($) f x
zipWith :: (a -> b -> c) -> Vec n a -> Vec n b -> Vec n c
zipWith f (Last x) (Last y) = Last (f x y)
zipWith f (Cons x xs) (Cons y ys) = Cons (f x y) (zipWith f xs ys)
zipWithM :: Applicative m => (a -> b -> m c) -> Vec n a -> Vec n b -> m (Vec n c)
zipWithM f x y = sequenceA (zipWith f x y)
unzipWith :: (c -> (a,b)) -> Vec n c -> (Vec n a, Vec n b)
unzipWith f (Last x) = let (p,q) = f x
in (Last p, Last q)
unzipWith f (Cons x xs) = let (p,q) = f x ; (ps,qs) = unzipWith f xs
in (Cons p ps, Cons q qs)
unzip :: Vec n (a, b) -> (Vec n a, Vec n b)
unzip = unzipWith id
instance Foldable (Vec n) where
foldr f b (Last x) = f x b
foldr f b (Cons x xs) = f x (foldr f b xs)
instance Traversable (Vec n) where
traverse f (Last x) = Last <$> (f x)
traverse f (Cons x xs) = Cons <$> (f x) <*> traverse f xs
instance Functor (Vec n) where
fmap f (Last x) = Last (f x)
fmap f (Cons x v) = Cons (f x) (fmap f v)
|
770dd1ba30420f5d88ab40279ee72172a0aad71c943af696ba53acbf701b331e | defaultxr/zoned | zoned-package.lisp | ;;;; zoned-package.lisp
(defpackage #:zoned
using alexandria causes a name conflict if we do n't do this ...
#:simple-parse-error)
(:shadow #:save-tileset)
(:use #:clim-lisp
#:clim
#:alexandria
#:mutility
#:zone)
(:import-from #:zone
#:with-swank-output
#:file-name-sans-suffix)
(:export #:zoned))
| null | https://raw.githubusercontent.com/defaultxr/zoned/869f456302912085f898be9f25991aae5c2a79f4/src/zoned-package.lisp | lisp | zoned-package.lisp |
(defpackage #:zoned
using alexandria causes a name conflict if we do n't do this ...
#:simple-parse-error)
(:shadow #:save-tileset)
(:use #:clim-lisp
#:clim
#:alexandria
#:mutility
#:zone)
(:import-from #:zone
#:with-swank-output
#:file-name-sans-suffix)
(:export #:zoned))
|
5d5643ea4a2ebed66ae8c818da1684fe2cf448fc62eee88bc39823fcc347b68e | clash-lang/clash-compiler | ReprCompact.hs | module ReprCompact
( testBench
, topEntity
) where
import Clash.Prelude
import Clash.Annotations.BitRepresentation
import RotateC (Color(..), MaybeColor(..), Top, tb)
import qualified RotateC
# ANN module (
DataReprAnn
$ ( liftQ [ t| Color | ] )
2
[ ConstrRepr
' Red
0b11
0b00
[ ]
, ConstrRepr
' Blue
0b11
0b10
[ ]
, ConstrRepr
' Green
0b11
0b01
[ ]
] ) #
DataReprAnn
$(liftQ [t| Color |])
2
[ ConstrRepr
'Red
0b11
0b00
[]
, ConstrRepr
'Blue
0b11
0b10
[]
, ConstrRepr
'Green
0b11
0b01
[]
]) #-}
# ANN module (
DataReprAnn
$ ( liftQ [ t| MaybeColor | ] )
2
[ ConstrRepr
' NothingC
0b11 -- Mask
0b11 -- Value
[ ]
, ConstrRepr
' JustC
0b00 -- Mask
0b00 -- Value
[ 0b11 ] -- Masks
] ) #
DataReprAnn
$(liftQ [t| MaybeColor |])
2
[ ConstrRepr
'NothingC
0b11 -- Mask
0b11 -- Value
[]
, ConstrRepr
'JustC
0b00 -- Mask
0b00 -- Value
[0b11] -- Masks
]) #-}
topEntity :: Top
topEntity = RotateC.topEntity
{-# NOINLINE topEntity #-}
testBench :: Signal System Bool
testBench = tb topEntity
# NOINLINE testBench #
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/b0e00ccb28f9a7c70e0ce1cfe3af5bb6ff88f93a/tests/shouldwork/CustomReprs/RotateC/ReprCompact.hs | haskell | Mask
Value
Mask
Value
Masks
Mask
Value
Mask
Value
Masks
# NOINLINE topEntity # | module ReprCompact
( testBench
, topEntity
) where
import Clash.Prelude
import Clash.Annotations.BitRepresentation
import RotateC (Color(..), MaybeColor(..), Top, tb)
import qualified RotateC
# ANN module (
DataReprAnn
$ ( liftQ [ t| Color | ] )
2
[ ConstrRepr
' Red
0b11
0b00
[ ]
, ConstrRepr
' Blue
0b11
0b10
[ ]
, ConstrRepr
' Green
0b11
0b01
[ ]
] ) #
DataReprAnn
$(liftQ [t| Color |])
2
[ ConstrRepr
'Red
0b11
0b00
[]
, ConstrRepr
'Blue
0b11
0b10
[]
, ConstrRepr
'Green
0b11
0b01
[]
]) #-}
# ANN module (
DataReprAnn
$ ( liftQ [ t| MaybeColor | ] )
2
[ ConstrRepr
' NothingC
[ ]
, ConstrRepr
' JustC
] ) #
DataReprAnn
$(liftQ [t| MaybeColor |])
2
[ ConstrRepr
'NothingC
[]
, ConstrRepr
'JustC
]) #-}
topEntity :: Top
topEntity = RotateC.topEntity
testBench :: Signal System Bool
testBench = tb topEntity
# NOINLINE testBench #
|
cf7584a4498aeb4c1c29720c099413e3f5b8ea6f712d6669de6b023ce298356c | nokijp/pietc | TestUtils.hs | module TestUtils
( toVector2D
, withTempFile
) where
import Control.Exception
import Data.Vector (Vector)
import qualified Data.Vector.Generic as V
import System.Directory
import System.IO
toVector2D :: [[a]] -> Vector (Vector a)
toVector2D = V.fromList . fmap V.fromList
withTempFile :: String -> (FilePath -> IO a) -> IO a
withTempFile template = bracket createTempFile removeTempFile where
createTempFile = do
tempDir <- getTemporaryDirectory
(path, fHandle) <- openTempFile tempDir template
hClose fHandle
return path
removeTempFile = removeFile
| null | https://raw.githubusercontent.com/nokijp/pietc/da6699c286a7b428b01211c8e467ce4ec1f7967e/test/TestUtils.hs | haskell | module TestUtils
( toVector2D
, withTempFile
) where
import Control.Exception
import Data.Vector (Vector)
import qualified Data.Vector.Generic as V
import System.Directory
import System.IO
toVector2D :: [[a]] -> Vector (Vector a)
toVector2D = V.fromList . fmap V.fromList
withTempFile :: String -> (FilePath -> IO a) -> IO a
withTempFile template = bracket createTempFile removeTempFile where
createTempFile = do
tempDir <- getTemporaryDirectory
(path, fHandle) <- openTempFile tempDir template
hClose fHandle
return path
removeTempFile = removeFile
| |
078f8a2f910e4ac9b708867fb497f443062ae58c7749fd7934283cc30336ac2c | ayazhafiz/plts | systemf.ml | open Format
open Util
open Util.Error
open Language
open Typecheck
open Eval
let searchpath = ref [ "" ]
let argDefs =
[
( "-I",
Arg.String (fun f -> searchpath := f :: !searchpath),
"Append a directory to the search path" );
]
let parseArgs () =
let inFile = ref (None : string option) in
Arg.parse argDefs
(fun s ->
match !inFile with
| Some _ -> error Unknown "You must specify at most one input file"
| None -> inFile := Some s)
"";
!inFile
let openfile infile =
let rec trynext l =
match l with
| [] -> error Unknown ("Could not find " ^ infile)
| d :: rest -> (
let name = if d = "" then infile else d ^ "/" ^ infile in
try open_in name with Sys_error _ -> trynext rest )
in
trynext !searchpath
let parse lexbuf =
let result =
try Some (Parser.toplevel Lexer.main lexbuf)
with Parsing.Parse_error -> None
in
Parsing.clear_parser ();
result
let parseFile inFile =
let pi = openfile inFile in
let lexbuf = Lexer.create inFile pi in
let result =
match parse lexbuf with
| Some res -> res
| _ -> error (Lexer.info lexbuf) "Parse error"
in
close_in pi;
result
let alreadyImported = ref ([] : string list)
let checkbinding fi ctx b =
match b with
| NameBinding -> NameBinding
| VarBinding tyT -> VarBinding tyT
| TmAbbBinding (t, None) -> TmAbbBinding (t, Some (typeof ctx t))
| TmAbbBinding (t, Some tyT) ->
let tyT' = typeof ctx t in
if tyeq ctx tyT' tyT then TmAbbBinding (t, Some tyT)
else error fi "Type of binding does not match declared type"
| TyVarBinding -> TyVarBinding
| TyAbbBinding tyT -> TyAbbBinding tyT
let prbindingty ctx b =
match b with
| NameBinding -> ()
| VarBinding tyT ->
pr ": ";
printty ctx tyT
| TmAbbBinding (t, tyT_opt) -> (
pr ": ";
match tyT_opt with
| None -> printty ctx (typeof ctx t)
| Some tyT -> printty ctx tyT )
| TyVarBinding -> ()
| TyAbbBinding ty ->
pr ":: ";
printty ctx ty
let process_command (ctx, store) cmd =
match cmd with
| Eval (_, t) ->
let tyT = typeof ctx t in
let t', store' = eval ctx store t in
printtm ctx t';
pr ": ";
printty ctx tyT;
force_newline ();
(ctx, store')
| Bind (fi, x, bind) ->
let bind = checkbinding fi ctx bind in
let bind', store' = evalbinding ctx store bind in
pr x;
pr " ";
prbindingty ctx bind';
force_newline ();
let ctx' = addbinding ctx x bind' in
(* Values in the store must be updated to reflect the insertion of the new binding.
This is not necessary during evaluation, as in that case there are no
free variables being added to the global scope, but there are during an
arbitrary bind command. *)
let store' = shift_store store' 1 in
(ctx', store')
let do_command (ctx, store) c =
open_hvbox 0;
let state = process_command (ctx, store) c in
print_flush ();
state
let process_file f (ctx, store) =
alreadyImported := f :: !alreadyImported;
let cmds, _ = parseFile f ctx in
List.fold_left do_command (ctx, store) cmds
let readin buf =
try
while true do
buf := read_line () :: !buf
done
with End_of_file -> pr "\n"
let rec repl (ctx, store) =
pr "> ";
let buf = ref [] in
readin buf;
let input = String.concat "\n" !buf in
match parse (Lexing.from_string input) with
| Some res ->
let newstate =
try
let cmds, _ = res ctx in
List.fold_left do_command (ctx, store) cmds
with Exit _ -> (ctx, store)
in
pr "\n";
repl newstate
| _ ->
pr "@@@ Could not parse input! @@@\n";
repl (ctx, store)
let main () =
match parseArgs () with
| Some inFile ->
let _ = process_file inFile (emptycontext, emptystore) in
()
| None -> repl (emptycontext, emptystore)
let () = set_max_boxes 1000
let () = set_margin 67
let res =
Printexc.catch
(fun () ->
try
main ();
0
with Exit x -> x)
()
let () = print_flush ()
let () = exit res
| null | https://raw.githubusercontent.com/ayazhafiz/plts/59b3996642f4fd5941c96a4987643303acc3dee6/tapl/25-systemf/systemf.ml | ocaml | Values in the store must be updated to reflect the insertion of the new binding.
This is not necessary during evaluation, as in that case there are no
free variables being added to the global scope, but there are during an
arbitrary bind command. | open Format
open Util
open Util.Error
open Language
open Typecheck
open Eval
let searchpath = ref [ "" ]
let argDefs =
[
( "-I",
Arg.String (fun f -> searchpath := f :: !searchpath),
"Append a directory to the search path" );
]
let parseArgs () =
let inFile = ref (None : string option) in
Arg.parse argDefs
(fun s ->
match !inFile with
| Some _ -> error Unknown "You must specify at most one input file"
| None -> inFile := Some s)
"";
!inFile
let openfile infile =
let rec trynext l =
match l with
| [] -> error Unknown ("Could not find " ^ infile)
| d :: rest -> (
let name = if d = "" then infile else d ^ "/" ^ infile in
try open_in name with Sys_error _ -> trynext rest )
in
trynext !searchpath
let parse lexbuf =
let result =
try Some (Parser.toplevel Lexer.main lexbuf)
with Parsing.Parse_error -> None
in
Parsing.clear_parser ();
result
let parseFile inFile =
let pi = openfile inFile in
let lexbuf = Lexer.create inFile pi in
let result =
match parse lexbuf with
| Some res -> res
| _ -> error (Lexer.info lexbuf) "Parse error"
in
close_in pi;
result
let alreadyImported = ref ([] : string list)
let checkbinding fi ctx b =
match b with
| NameBinding -> NameBinding
| VarBinding tyT -> VarBinding tyT
| TmAbbBinding (t, None) -> TmAbbBinding (t, Some (typeof ctx t))
| TmAbbBinding (t, Some tyT) ->
let tyT' = typeof ctx t in
if tyeq ctx tyT' tyT then TmAbbBinding (t, Some tyT)
else error fi "Type of binding does not match declared type"
| TyVarBinding -> TyVarBinding
| TyAbbBinding tyT -> TyAbbBinding tyT
let prbindingty ctx b =
match b with
| NameBinding -> ()
| VarBinding tyT ->
pr ": ";
printty ctx tyT
| TmAbbBinding (t, tyT_opt) -> (
pr ": ";
match tyT_opt with
| None -> printty ctx (typeof ctx t)
| Some tyT -> printty ctx tyT )
| TyVarBinding -> ()
| TyAbbBinding ty ->
pr ":: ";
printty ctx ty
let process_command (ctx, store) cmd =
match cmd with
| Eval (_, t) ->
let tyT = typeof ctx t in
let t', store' = eval ctx store t in
printtm ctx t';
pr ": ";
printty ctx tyT;
force_newline ();
(ctx, store')
| Bind (fi, x, bind) ->
let bind = checkbinding fi ctx bind in
let bind', store' = evalbinding ctx store bind in
pr x;
pr " ";
prbindingty ctx bind';
force_newline ();
let ctx' = addbinding ctx x bind' in
let store' = shift_store store' 1 in
(ctx', store')
let do_command (ctx, store) c =
open_hvbox 0;
let state = process_command (ctx, store) c in
print_flush ();
state
let process_file f (ctx, store) =
alreadyImported := f :: !alreadyImported;
let cmds, _ = parseFile f ctx in
List.fold_left do_command (ctx, store) cmds
let readin buf =
try
while true do
buf := read_line () :: !buf
done
with End_of_file -> pr "\n"
let rec repl (ctx, store) =
pr "> ";
let buf = ref [] in
readin buf;
let input = String.concat "\n" !buf in
match parse (Lexing.from_string input) with
| Some res ->
let newstate =
try
let cmds, _ = res ctx in
List.fold_left do_command (ctx, store) cmds
with Exit _ -> (ctx, store)
in
pr "\n";
repl newstate
| _ ->
pr "@@@ Could not parse input! @@@\n";
repl (ctx, store)
let main () =
match parseArgs () with
| Some inFile ->
let _ = process_file inFile (emptycontext, emptystore) in
()
| None -> repl (emptycontext, emptystore)
let () = set_max_boxes 1000
let () = set_margin 67
let res =
Printexc.catch
(fun () ->
try
main ();
0
with Exit x -> x)
()
let () = print_flush ()
let () = exit res
|
a7945daef8d49b147395061db52885efd866578a35d4497e48bae88d4b45e47e | ekmett/category-extras | Derivative.hs | -----------------------------------------------------------------------------
-- |
-- Module : Control.Functor.Derivative
Copyright : ( C ) 2008
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
----------------------------------------------------------------------------
module Control.Functor.Derivative where
| null | https://raw.githubusercontent.com/ekmett/category-extras/f0f3ca38a3dfcb49d39aa2bb5b31b719f2a5b1ae/Control/Functor/Derivative.hs | haskell | ---------------------------------------------------------------------------
|
Module : Control.Functor.Derivative
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : non-portable (rank-2 polymorphism)
-------------------------------------------------------------------------- | Copyright : ( C ) 2008
Maintainer : < >
module Control.Functor.Derivative where
|
af7a4657849a547c23e28bc5b45c42334dbc1d2275c21cda269fd835ad8bf218 | marigold-dev/chusai | chusai_tezos.mli | MIT License
Copyright ( c ) 2022 Marigold < >
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal in
the Software without restriction , including without limitation the rights to
use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of
the Software , and to permit persons to whom the Software is furnished to do so ,
subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, 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 .
Copyright (c) 2022 Marigold <>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. *)
module Environment = Tezos_protocol_013_PtJakart__Protocol.Environment
module Protocol = Tezos_protocol_013_PtJakart.Protocol
module Protocol_client_context = Tezos_client_013_PtJakart.Protocol_client_context
| null | https://raw.githubusercontent.com/marigold-dev/chusai/09f798c585121d3b02bf3fed0f52f15c3bdc79a1/layer2/lib/chusai_tezos/chusai_tezos.mli | ocaml | MIT License
Copyright ( c ) 2022 Marigold < >
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal in
the Software without restriction , including without limitation the rights to
use , copy , modify , merge , publish , distribute , sublicense , and/or sell copies of
the Software , and to permit persons to whom the Software is furnished to do so ,
subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, 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 .
Copyright (c) 2022 Marigold <>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. *)
module Environment = Tezos_protocol_013_PtJakart__Protocol.Environment
module Protocol = Tezos_protocol_013_PtJakart.Protocol
module Protocol_client_context = Tezos_client_013_PtJakart.Protocol_client_context
| |
0588ab0ef587a1ffe049c7a47dcda6f20792d686586297d28f68a9c637937f3b | stchang/macrotypes | turnstile-lang.rkt | #lang turnstile
(provide #%module-begin)
| null | https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-test/tests/turnstile/load-time-tests/turnstile-lang.rkt | racket | #lang turnstile
(provide #%module-begin)
| |
e8e275e8bf5e819dd7c3d1f6a92165c581810e7b464300320e6fea9f4a4ff74b | ghcjs/ghcjs-dom | StorageInfo.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.StorageInfo
(js_queryUsageAndQuota, queryUsageAndQuota, js_requestQuota,
requestQuota, pattern TEMPORARY, pattern PERSISTENT,
StorageInfo(..), gTypeStorageInfo)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"$1[\"queryUsageAndQuota\"]($2, $3,\n$4)" js_queryUsageAndQuota ::
StorageInfo ->
Word ->
Optional StorageUsageCallback ->
Optional StorageErrorCallback -> IO ()
| < -US/docs/Web/API/StorageInfo.queryUsageAndQuota Mozilla StorageInfo.queryUsageAndQuota documentation >
queryUsageAndQuota ::
(MonadIO m) =>
StorageInfo ->
Word ->
Maybe StorageUsageCallback -> Maybe StorageErrorCallback -> m ()
queryUsageAndQuota self storageType usageCallback errorCallback
= liftIO
(js_queryUsageAndQuota self storageType
(maybeToOptional usageCallback)
(maybeToOptional errorCallback))
foreign import javascript unsafe
"$1[\"requestQuota\"]($2, $3, $4,\n$5)" js_requestQuota ::
StorageInfo ->
Word ->
Double ->
Optional StorageQuotaCallback ->
Optional StorageErrorCallback -> IO ()
| < -US/docs/Web/API/StorageInfo.requestQuota Mozilla StorageInfo.requestQuota documentation >
requestQuota ::
(MonadIO m) =>
StorageInfo ->
Word ->
Word64 ->
Maybe StorageQuotaCallback -> Maybe StorageErrorCallback -> m ()
requestQuota self storageType newQuotaInBytes quotaCallback
errorCallback
= liftIO
(js_requestQuota self storageType (fromIntegral newQuotaInBytes)
(maybeToOptional quotaCallback)
(maybeToOptional errorCallback))
pattern TEMPORARY = 0
pattern PERSISTENT = 1 | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/StorageInfo.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.StorageInfo
(js_queryUsageAndQuota, queryUsageAndQuota, js_requestQuota,
requestQuota, pattern TEMPORARY, pattern PERSISTENT,
StorageInfo(..), gTypeStorageInfo)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import qualified Prelude (error)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull, jsUndefined)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad (void)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import Data.Maybe (fromJust)
import Data.Traversable (mapM)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"$1[\"queryUsageAndQuota\"]($2, $3,\n$4)" js_queryUsageAndQuota ::
StorageInfo ->
Word ->
Optional StorageUsageCallback ->
Optional StorageErrorCallback -> IO ()
| < -US/docs/Web/API/StorageInfo.queryUsageAndQuota Mozilla StorageInfo.queryUsageAndQuota documentation >
queryUsageAndQuota ::
(MonadIO m) =>
StorageInfo ->
Word ->
Maybe StorageUsageCallback -> Maybe StorageErrorCallback -> m ()
queryUsageAndQuota self storageType usageCallback errorCallback
= liftIO
(js_queryUsageAndQuota self storageType
(maybeToOptional usageCallback)
(maybeToOptional errorCallback))
foreign import javascript unsafe
"$1[\"requestQuota\"]($2, $3, $4,\n$5)" js_requestQuota ::
StorageInfo ->
Word ->
Double ->
Optional StorageQuotaCallback ->
Optional StorageErrorCallback -> IO ()
| < -US/docs/Web/API/StorageInfo.requestQuota Mozilla StorageInfo.requestQuota documentation >
requestQuota ::
(MonadIO m) =>
StorageInfo ->
Word ->
Word64 ->
Maybe StorageQuotaCallback -> Maybe StorageErrorCallback -> m ()
requestQuota self storageType newQuotaInBytes quotaCallback
errorCallback
= liftIO
(js_requestQuota self storageType (fromIntegral newQuotaInBytes)
(maybeToOptional quotaCallback)
(maybeToOptional errorCallback))
pattern TEMPORARY = 0
pattern PERSISTENT = 1 |
44fab6b3330f9a1714411f799f8bb895147e208b7ed337af298ff50ccc3ace9a | ds-wizard/engine-backend | Component.hs | module Shared.Model.Component.Component where
import Data.Time
import GHC.Generics
data Component = Component
{ name :: String
, version :: String
, builtAt :: UTCTime
, createdAt :: UTCTime
, updatedAt :: UTCTime
}
deriving (Generic, Eq, Show)
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/b87f6d481205dd7f0f00fd770145f8ee5c4be193/engine-shared/src/Shared/Model/Component/Component.hs | haskell | module Shared.Model.Component.Component where
import Data.Time
import GHC.Generics
data Component = Component
{ name :: String
, version :: String
, builtAt :: UTCTime
, createdAt :: UTCTime
, updatedAt :: UTCTime
}
deriving (Generic, Eq, Show)
| |
6dd4b60432043a635cafd7d32936db39b5e13cb19fe6fbcce4af3e6663628da6 | raviksharma/bartosz-basics-of-haskell | segment.hs | makeSegment p1 p2 = (p1, p2)
main = print $ makeSegment (1, 2) (3, 4)
| null | https://raw.githubusercontent.com/raviksharma/bartosz-basics-of-haskell/86d40d831f61415ef0022bff7fe7060ae6a23701/02-my-first-program/segment.hs | haskell | makeSegment p1 p2 = (p1, p2)
main = print $ makeSegment (1, 2) (3, 4)
| |
fbba81f8e73c4eeaca8c4532b0e75f4720d86304a846ebcf4af82d90c39004db | ta0kira/zeolite | TrackedErrors.hs | -----------------------------------------------------------------------------
Copyright 2020 - 2021 under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
-----------------------------------------------------------------------------
Copyright 2020-2021 Kevin P. Barry
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.
----------------------------------------------------------------------------- -}
Author : [ ]
{-# LANGUAGE Safe #-}
module Test.TrackedErrors (tests) where
import Control.Arrow (first)
import Control.Monad.Writer
import Base.CompilerError
import Base.TrackedErrors
tests :: [IO (TrackedErrors ())]
tests = [
checkSuccess 'a' (return 'a'),
checkError "error\n" (compilerErrorM "error" :: TrackedErrorsIO Char),
checkError "" (emptyErrorM :: TrackedErrorsIO Char),
checkSuccess ['a','b'] (collectAllM [return 'a',return 'b']),
checkSuccess [] (collectAllM [] :: TrackedErrorsIO [Char]),
checkError "error1\nerror2\n" (collectAllM [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccess "ab" (collectAnyM [return 'a',return 'b']),
checkSuccess "" (collectAnyM [] :: TrackedErrorsIO [Char]),
checkSuccess "b" (collectAnyM [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccess 'a' (collectFirstM [return 'a',return 'b']),
checkError "" (collectFirstM [] :: TrackedErrorsIO Char),
checkSuccess 'b' (collectFirstM [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccessAndWarnings "warning1\nwarning2\n" ()
(compilerWarningM "warning1" >> return () >> compilerWarningM "warning2"),
checkErrorAndWarnings "warning1\n" "error\n"
(compilerWarningM "warning1" >> compilerErrorM "error" >> compilerWarningM "warning2" :: TrackedErrorsIO ()),
checkSuccess ['a','b'] (sequence [return 'a',return 'b']),
checkSuccess [] (sequence [] :: TrackedErrorsIO [Char]),
checkError "error1\n" (sequence [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccess 'a' (return 'a' `withContextM` "message"),
checkError "message\n error\n" (compilerErrorM "error" `withContextM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "message\n warning\n" ()
(compilerWarningM "warning" `withContextM` "message" :: TrackedErrorsIO ()),
checkErrorAndWarnings "message\n warning\n" "message\n error\n"
((compilerWarningM "warning" >> compilerErrorM "error") `withContextM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "" () (return () `withContextM` "message"),
checkErrorAndWarnings "" "message\n" (emptyErrorM `withContextM` "message" :: TrackedErrorsIO ()),
checkSuccess 'a' (return 'a' `summarizeErrorsM` "message"),
checkError "message\n error\n" (compilerErrorM "error" `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "warning\n" ()
(compilerWarningM "warning" `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkErrorAndWarnings "warning\n" "message\n error\n"
((compilerWarningM "warning" >> compilerErrorM "error") `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "" () (return () `summarizeErrorsM` "message"),
checkErrorAndWarnings "" "message\n" (emptyErrorM `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "error\n" ()
(asCompilerWarnings $ compilerErrorM "error" :: TrackedErrorsIO ()),
checkErrorAndWarnings "" "warning\n"
(asCompilerError $ compilerWarningM "warning" :: TrackedErrorsIO ()),
checkSuccess 'a' (compilerBackgroundM "background" >> return 'a'),
checkError "error\n background\n"
(compilerBackgroundM "background" >> compilerErrorM "error" :: TrackedErrorsIO ()),
checkError "error\n background\n"
(collectAllM [compilerBackgroundM "background"] >> compilerErrorM "error" :: TrackedErrorsIO [()]),
checkError "error\n background\n"
(collectFirstM [compilerBackgroundM "background"] >> compilerErrorM "error" :: TrackedErrorsIO ()),
checkSuccess 'a' ((resetBackgroundM $ compilerBackgroundM "background") >> return 'a'),
checkError "error\n"
((resetBackgroundM $ compilerBackgroundM "background") >> compilerErrorM "error" :: TrackedErrorsIO ()),
checkWriterSuccess ('x',"ab") (ifElseSuccessT (lift (tell "a") >> return 'x') (tell "b") (tell "c")),
checkWriterFail ("failed\n","ac") (ifElseSuccessT (lift (tell "a") >> compilerErrorM "failed") (tell "b") (tell "c") :: TrackedErrorsT (Writer String) ())
]
checkWriterSuccess :: (Eq a, Show a) => (a,String) -> TrackedErrorsT (Writer String) a -> IO (TrackedErrors ())
checkWriterSuccess x y = do
let (failed,_) = runWriter $ isCompilerErrorT y
if failed
then return $ fst $ runWriter $ toTrackedErrors $ y >> return ()
else do
let y' = runWriter $ getCompilerSuccessT y
if y' == x
then return $ return ()
else return $ compilerErrorM $ "Expected value " ++ show x ++ " but got value " ++ show y'
checkWriterFail :: (Eq a, Show a) => (String,String) -> TrackedErrorsT (Writer String) a -> IO (TrackedErrors ())
checkWriterFail x y = do
let (failed,_) = runWriter $ isCompilerErrorT y
if failed
then do
let y' = first show $ runWriter $ getCompilerErrorT y
if y' == x
then return $ return ()
else return $ compilerErrorM $ "Expected error " ++ show x ++ " but got error " ++ show y'
else do
let y' = runWriter $ getCompilerSuccessT y
return $ compilerErrorM $ "Expected failure but got value " ++ show y'
checkSuccess :: (Eq a, Show a) => a -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkSuccess x y = do
y' <- toTrackedErrors y
if isCompilerError y' || getCompilerSuccess y' == x
then return $ y' >> return ()
else return $ compilerErrorM $ "Expected value " ++ show x ++ " but got value " ++ show (getCompilerSuccess y')
checkError :: (Eq a, Show a) => String -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkError e y = do
y' <- toTrackedErrors y
if not (isCompilerError y')
then return $ compilerErrorM $ "Expected error \"" ++ e ++ "\" but got value " ++ show (getCompilerSuccess y')
else if show (getCompilerError y') == e
then return $ return ()
else return $ compilerErrorM $ "Expected error \"" ++ e ++ "\" but got error \"" ++ show (getCompilerError y') ++ "\""
checkSuccessAndWarnings :: (Eq a, Show a) => String -> a -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkSuccessAndWarnings w x y = do
y' <- toTrackedErrors y
outcome <- checkSuccess x y
if show (getCompilerWarnings y') == w
then return $ outcome >> return ()
else return $ compilerErrorM $ "Expected warnings " ++ show w ++ " but got warnings \"" ++ show (getCompilerWarnings y') ++ "\""
checkErrorAndWarnings :: (Eq a, Show a) => String -> String -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkErrorAndWarnings w e y = do
y' <- toTrackedErrors y
outcome <- checkError e y
if show (getCompilerWarnings y') == w
then return $ outcome >> return ()
else return $ compilerErrorM $ "Expected warnings " ++ show w ++ " but got warnings \"" ++ show (getCompilerWarnings y') ++ "\""
| null | https://raw.githubusercontent.com/ta0kira/zeolite/6741e1fa38bdb7feaad10780290275cd5282fcbc/src/Test/TrackedErrors.hs | haskell | ---------------------------------------------------------------------------
---------------------------------------------------------------------------
--------------------------------------------------------------------------- -}
# LANGUAGE Safe # | Copyright 2020 - 2021 under the Apache License , Version 2.0 ( the " License " ) ;
you may not use this file except in compliance with the License .
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing , software
distributed under the License is distributed on an " AS IS " BASIS ,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
See the License for the specific language governing permissions and
limitations under the License .
Copyright 2020-2021 Kevin P. Barry
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.
Author : [ ]
module Test.TrackedErrors (tests) where
import Control.Arrow (first)
import Control.Monad.Writer
import Base.CompilerError
import Base.TrackedErrors
tests :: [IO (TrackedErrors ())]
tests = [
checkSuccess 'a' (return 'a'),
checkError "error\n" (compilerErrorM "error" :: TrackedErrorsIO Char),
checkError "" (emptyErrorM :: TrackedErrorsIO Char),
checkSuccess ['a','b'] (collectAllM [return 'a',return 'b']),
checkSuccess [] (collectAllM [] :: TrackedErrorsIO [Char]),
checkError "error1\nerror2\n" (collectAllM [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccess "ab" (collectAnyM [return 'a',return 'b']),
checkSuccess "" (collectAnyM [] :: TrackedErrorsIO [Char]),
checkSuccess "b" (collectAnyM [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccess 'a' (collectFirstM [return 'a',return 'b']),
checkError "" (collectFirstM [] :: TrackedErrorsIO Char),
checkSuccess 'b' (collectFirstM [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccessAndWarnings "warning1\nwarning2\n" ()
(compilerWarningM "warning1" >> return () >> compilerWarningM "warning2"),
checkErrorAndWarnings "warning1\n" "error\n"
(compilerWarningM "warning1" >> compilerErrorM "error" >> compilerWarningM "warning2" :: TrackedErrorsIO ()),
checkSuccess ['a','b'] (sequence [return 'a',return 'b']),
checkSuccess [] (sequence [] :: TrackedErrorsIO [Char]),
checkError "error1\n" (sequence [compilerErrorM "error1",return 'b',compilerErrorM "error2"]),
checkSuccess 'a' (return 'a' `withContextM` "message"),
checkError "message\n error\n" (compilerErrorM "error" `withContextM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "message\n warning\n" ()
(compilerWarningM "warning" `withContextM` "message" :: TrackedErrorsIO ()),
checkErrorAndWarnings "message\n warning\n" "message\n error\n"
((compilerWarningM "warning" >> compilerErrorM "error") `withContextM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "" () (return () `withContextM` "message"),
checkErrorAndWarnings "" "message\n" (emptyErrorM `withContextM` "message" :: TrackedErrorsIO ()),
checkSuccess 'a' (return 'a' `summarizeErrorsM` "message"),
checkError "message\n error\n" (compilerErrorM "error" `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "warning\n" ()
(compilerWarningM "warning" `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkErrorAndWarnings "warning\n" "message\n error\n"
((compilerWarningM "warning" >> compilerErrorM "error") `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "" () (return () `summarizeErrorsM` "message"),
checkErrorAndWarnings "" "message\n" (emptyErrorM `summarizeErrorsM` "message" :: TrackedErrorsIO ()),
checkSuccessAndWarnings "error\n" ()
(asCompilerWarnings $ compilerErrorM "error" :: TrackedErrorsIO ()),
checkErrorAndWarnings "" "warning\n"
(asCompilerError $ compilerWarningM "warning" :: TrackedErrorsIO ()),
checkSuccess 'a' (compilerBackgroundM "background" >> return 'a'),
checkError "error\n background\n"
(compilerBackgroundM "background" >> compilerErrorM "error" :: TrackedErrorsIO ()),
checkError "error\n background\n"
(collectAllM [compilerBackgroundM "background"] >> compilerErrorM "error" :: TrackedErrorsIO [()]),
checkError "error\n background\n"
(collectFirstM [compilerBackgroundM "background"] >> compilerErrorM "error" :: TrackedErrorsIO ()),
checkSuccess 'a' ((resetBackgroundM $ compilerBackgroundM "background") >> return 'a'),
checkError "error\n"
((resetBackgroundM $ compilerBackgroundM "background") >> compilerErrorM "error" :: TrackedErrorsIO ()),
checkWriterSuccess ('x',"ab") (ifElseSuccessT (lift (tell "a") >> return 'x') (tell "b") (tell "c")),
checkWriterFail ("failed\n","ac") (ifElseSuccessT (lift (tell "a") >> compilerErrorM "failed") (tell "b") (tell "c") :: TrackedErrorsT (Writer String) ())
]
checkWriterSuccess :: (Eq a, Show a) => (a,String) -> TrackedErrorsT (Writer String) a -> IO (TrackedErrors ())
checkWriterSuccess x y = do
let (failed,_) = runWriter $ isCompilerErrorT y
if failed
then return $ fst $ runWriter $ toTrackedErrors $ y >> return ()
else do
let y' = runWriter $ getCompilerSuccessT y
if y' == x
then return $ return ()
else return $ compilerErrorM $ "Expected value " ++ show x ++ " but got value " ++ show y'
checkWriterFail :: (Eq a, Show a) => (String,String) -> TrackedErrorsT (Writer String) a -> IO (TrackedErrors ())
checkWriterFail x y = do
let (failed,_) = runWriter $ isCompilerErrorT y
if failed
then do
let y' = first show $ runWriter $ getCompilerErrorT y
if y' == x
then return $ return ()
else return $ compilerErrorM $ "Expected error " ++ show x ++ " but got error " ++ show y'
else do
let y' = runWriter $ getCompilerSuccessT y
return $ compilerErrorM $ "Expected failure but got value " ++ show y'
checkSuccess :: (Eq a, Show a) => a -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkSuccess x y = do
y' <- toTrackedErrors y
if isCompilerError y' || getCompilerSuccess y' == x
then return $ y' >> return ()
else return $ compilerErrorM $ "Expected value " ++ show x ++ " but got value " ++ show (getCompilerSuccess y')
checkError :: (Eq a, Show a) => String -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkError e y = do
y' <- toTrackedErrors y
if not (isCompilerError y')
then return $ compilerErrorM $ "Expected error \"" ++ e ++ "\" but got value " ++ show (getCompilerSuccess y')
else if show (getCompilerError y') == e
then return $ return ()
else return $ compilerErrorM $ "Expected error \"" ++ e ++ "\" but got error \"" ++ show (getCompilerError y') ++ "\""
checkSuccessAndWarnings :: (Eq a, Show a) => String -> a -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkSuccessAndWarnings w x y = do
y' <- toTrackedErrors y
outcome <- checkSuccess x y
if show (getCompilerWarnings y') == w
then return $ outcome >> return ()
else return $ compilerErrorM $ "Expected warnings " ++ show w ++ " but got warnings \"" ++ show (getCompilerWarnings y') ++ "\""
checkErrorAndWarnings :: (Eq a, Show a) => String -> String -> TrackedErrorsIO a -> IO (TrackedErrors ())
checkErrorAndWarnings w e y = do
y' <- toTrackedErrors y
outcome <- checkError e y
if show (getCompilerWarnings y') == w
then return $ outcome >> return ()
else return $ compilerErrorM $ "Expected warnings " ++ show w ++ " but got warnings \"" ++ show (getCompilerWarnings y') ++ "\""
|
f5ba25e58239f069f10148c87d73b9da3c6dbac0ebcb3a11c85cd48eb84d2b6a | Kappa-Dev/KappaTools | eval.mli | (******************************************************************************)
(* _ __ * The Kappa Language *)
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
(* | ' / *********************************************************************)
(* | . \ * This file is distributed under the terms of the *)
(* |_|\_\ * GNU Lesser General Public License Version 3 *)
(******************************************************************************)
(** Main compilation functions *)
(*val init_kasa :
Remanent_parameters_sig.called_from -> Signature.s ->
(string Locality.annot * Ast.port list, Ast.mixture, string, Ast.rule)
Ast.compil ->
Primitives.contact_map * Export_to_KaSim.state
*)
val compile_bool:
debugMode:bool -> compileModeOn:bool -> ?origin:Operator.rev_dep ->
Contact_map.t -> Pattern.PreEnv.t ->
(LKappa.rule_mixture, int) Alg_expr.bool Locality.annot ->
Pattern.PreEnv.t *
(Pattern.id array list,int) Alg_expr.bool Locality.annot
val compile_modifications_no_track:
debugMode:bool -> warning:(pos:Locality.t -> (Format.formatter -> unit) -> unit) ->
compileModeOn:bool -> Contact_map.t -> Pattern.PreEnv.t ->
(LKappa.rule_mixture, Raw_mixture.t, int, LKappa.rule) Ast.modif_expr list ->
Pattern.PreEnv.t * Primitives.modification list
val compile_inits:
debugMode:bool ->
warning:(pos:Locality.t -> (Format.formatter -> unit) -> unit) ->
?rescale:float -> compileModeOn:bool -> Contact_map.t -> Model.t ->
(LKappa.rule_mixture, Raw_mixture.t, int) Ast.init_statment list ->
(Primitives.alg_expr * Primitives.elementary_rule) list
val compile :
outputs:(Data.t -> unit) -> pause:((unit -> 'b) -> 'b) ->
return:(Model.t * bool (*has_tracking*) *
(Primitives.alg_expr * Primitives.elementary_rule) list -> 'b) ->
sharing:Pattern.sharing_level -> debugMode:bool -> compileModeOn:bool ->
?overwrite_init:(LKappa.rule_mixture, Raw_mixture.t, int) Ast.init_statment list ->
?overwrite_t0: float ->
?rescale_init:float -> Signature.s -> unit NamedDecls.t -> Contact_map.t ->
('c, LKappa.rule_mixture, Raw_mixture.t, int, LKappa.rule) Ast.compil -> 'b
val build_initial_state :
bind:('a -> (bool * Rule_interpreter.t * State_interpreter.t -> 'a) -> 'a) ->
return:(bool * Rule_interpreter.t * State_interpreter.t -> 'a) ->
debugMode:bool -> outputs:(Data.t -> unit) -> Counter.t -> Model.t ->
with_trace:bool -> with_delta_activities:bool -> Random.State.t ->
(Primitives.alg_expr * Primitives.elementary_rule) list -> 'a
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/a7e166d671286d4fa951b07a60a1dd452d60e242/core/grammar/eval.mli | ocaml | ****************************************************************************
_ __ * The Kappa Language
| ' / ********************************************************************
| . \ * This file is distributed under the terms of the
|_|\_\ * GNU Lesser General Public License Version 3
****************************************************************************
* Main compilation functions
val init_kasa :
Remanent_parameters_sig.called_from -> Signature.s ->
(string Locality.annot * Ast.port list, Ast.mixture, string, Ast.rule)
Ast.compil ->
Primitives.contact_map * Export_to_KaSim.state
has_tracking | | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
val compile_bool:
debugMode:bool -> compileModeOn:bool -> ?origin:Operator.rev_dep ->
Contact_map.t -> Pattern.PreEnv.t ->
(LKappa.rule_mixture, int) Alg_expr.bool Locality.annot ->
Pattern.PreEnv.t *
(Pattern.id array list,int) Alg_expr.bool Locality.annot
val compile_modifications_no_track:
debugMode:bool -> warning:(pos:Locality.t -> (Format.formatter -> unit) -> unit) ->
compileModeOn:bool -> Contact_map.t -> Pattern.PreEnv.t ->
(LKappa.rule_mixture, Raw_mixture.t, int, LKappa.rule) Ast.modif_expr list ->
Pattern.PreEnv.t * Primitives.modification list
val compile_inits:
debugMode:bool ->
warning:(pos:Locality.t -> (Format.formatter -> unit) -> unit) ->
?rescale:float -> compileModeOn:bool -> Contact_map.t -> Model.t ->
(LKappa.rule_mixture, Raw_mixture.t, int) Ast.init_statment list ->
(Primitives.alg_expr * Primitives.elementary_rule) list
val compile :
outputs:(Data.t -> unit) -> pause:((unit -> 'b) -> 'b) ->
(Primitives.alg_expr * Primitives.elementary_rule) list -> 'b) ->
sharing:Pattern.sharing_level -> debugMode:bool -> compileModeOn:bool ->
?overwrite_init:(LKappa.rule_mixture, Raw_mixture.t, int) Ast.init_statment list ->
?overwrite_t0: float ->
?rescale_init:float -> Signature.s -> unit NamedDecls.t -> Contact_map.t ->
('c, LKappa.rule_mixture, Raw_mixture.t, int, LKappa.rule) Ast.compil -> 'b
val build_initial_state :
bind:('a -> (bool * Rule_interpreter.t * State_interpreter.t -> 'a) -> 'a) ->
return:(bool * Rule_interpreter.t * State_interpreter.t -> 'a) ->
debugMode:bool -> outputs:(Data.t -> unit) -> Counter.t -> Model.t ->
with_trace:bool -> with_delta_activities:bool -> Random.State.t ->
(Primitives.alg_expr * Primitives.elementary_rule) list -> 'a
|
1fb2483ba87352205cc8921cd631094485351121d5a5f81b2ea3e49eca26a8cb | TrustInSoft/tis-kernel | design.mli | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(** The extensible GUI.
@plugin development guide *)
open Cil_types
(** This is the type of source code buffers that can react to global
selections and highlighters.
@since Beryllium-20090901 *)
class type reactive_buffer = object
inherit Gtk_helper.error_manager
method buffer : GSourceView2.source_buffer
method locs : Pretty_source.Locs.state
method rehighlight : unit
method redisplay : unit
end
(** This class type lists all the methods available to navigate the
source code through the GUI *)
class type view_code = object
* { 3 Pretty - printed code }
method scroll : Pretty_source.localizable -> unit
* Move the pretty - printed source viewer to the given localizable
if possible . Return a boolean indicating whether the operation
succeeded
Now indicates whether the
operation succeeded .
if possible. Return a boolean indicating whether the operation
succeeded
@modify Nitrogen-20111001 Now indicates whether the
operation succeeded. *)
method display_globals : global list -> unit
(** Display the given globals in the pretty-printed source viewer. *)
* { 3 Original code }
method view_original_stmt : stmt -> location
(** Display the given [stmt] in the original source viewer *)
method view_original : location -> unit
(** Display the given location in the original_source_viewer *)
* { 3 Both pretty - printed and original code }
method view_stmt : stmt -> unit
* Display the given [ stmt ] in the [ source_viewer ] and in the
[ original_source_viewer ] . Equivalent to two successive
calls to [ scroll ] and [ view_original_stmt ]
@since Carbon-20101201
[original_source_viewer]. Equivalent to two successive
calls to [scroll] and [view_original_stmt]
@since Carbon-20101201 *)
method select_or_display_global : global -> unit
* This function tries to select the global in the treeview . If
this fails , for example because the global is not shown in the
treeview because of filters , it falls back to displaying the
global by hand .
@since
this fails, for example because the global is not shown in the
treeview because of filters, it falls back to displaying the
global by hand.
@since Nitrogen-20111001 *)
end
class protected_menu_factory:
Gtk_helper.host -> GMenu.menu -> [ GMenu.menu ] GMenu.factory
(** This is the type of extension points for the GUI.
@modify Boron-20100401 new way of handling the menu and the toolbar
@plugin development guide *)
class type main_window_extension_points = object
inherit view_code
(** {3 Main Components} *)
method toplevel : main_window_extension_points
(** The whole GUI aka self *)
method menu_manager: unit -> Menu_manager.menu_manager
* The object managing the menubar and the toolbar .
@since
@since Boron-20100401 *)
method file_tree : Filetree.t
(** The tree containing the list of files and functions *)
method file_tree_view : GTree.view
(** The tree view containing the list of files and functions *)
method main_window : GWindow.window
(** The main window *)
method annot_window : Wtext.text
(** The information panel.
The text is automatically cleared whenever the selection is changed.
You should not directly use the buffer contained in the annot_window
to add text. Use the method [pretty_information].
*)
method pretty_information : 'a. ?scroll:bool -> ('a, Format.formatter, unit) format -> 'a
(** Pretty print a message in the [annot_window],
optionally scrolling it to the beginning of the message. *)
method lower_notebook : GPack.notebook
(** The lower notebook with messages tabs *)
* { 4 Source viewers }
method source_viewer : GSourceView2.source_view
(** The [GText.view] showing the AST. *)
method source_viewer_scroll : GBin.scrolled_window
(** The scrolling of the [GText.view] showing the AST. *)
method reactive_buffer: reactive_buffer
* The buffer containing the AST .
@since Carbon-20101201
@since Carbon-20101201 *)
method original_source_viewer : Source_manager.t
(** The multi-tab source file display widget containing the
original source. *)
(** {3 Dialog Boxes} *)
method launcher : unit -> unit
(** Display the analysis configuration dialog and offer the
opportunity to launch to the user *)
method error :
'a. ?parent:GWindow.window_skel -> ?reset:bool ->
('a, Format.formatter, unit) format -> 'a
(** Popup a modal dialog displaying an error message. If [reset] is true
(default is false), the gui is reset after the dialog has been
displayed. *)
(** {3 Extension Points} *)
method register_source_selector :
(GMenu.menu GMenu.factory
-> main_window_extension_points
-> button:int -> Pretty_source.localizable -> unit) -> unit
* register an action to perform when button is released on a given
localizable .
If the button 3 is released , the first argument is popped as a
contextual menu .
@plugin development guide
localizable.
If the button 3 is released, the first argument is popped as a
contextual menu.
@plugin development guide *)
method register_source_highlighter :
(reactive_buffer -> Pretty_source.localizable ->
start:int -> stop:int -> unit)
-> unit
* register an highlighting function to run on a given localizable
between start and stop in the given buffer .
Priority of [ Gtext.tags ] is used to decide which tag is rendered on
top of the other .
Magnesium-20151001+dev : receives a { ! reactive_buffer } instead
of a { ! }
between start and stop in the given buffer.
Priority of [Gtext.tags] is used to decide which tag is rendered on
top of the other.
@modify Magnesium-20151001+dev: receives a {!reactive_buffer} instead
of a {!GSourceView2.source_buffer} *)
method register_panel :
(main_window_extension_points->(string*GObj.widget*(unit-> unit) option))
-> unit
(** [register_panel (name, widget, refresh)] registers a panel in GUI.
The arguments are the name of the panel to create,
the widget containing the panel and a function to be called on
refresh. *)
* { 3 General features }
method reset : unit -> unit
(** Reset the GUI and its extensions to its initial state *)
method rehighlight : unit -> unit
(** Force to rehilight the current displayed buffer.
Plugins should call this method whenever they have changed the states
on which the function given to [register_source_highlighter] have been
updated. *)
method redisplay : unit -> unit
* @since
Force to redisplay the current displayed buffer .
Plugins should call this method whenever they have changed the globals .
For example whenever a plugin adds an annotation , the buffers need
to be redisplayed .
Force to redisplay the current displayed buffer.
Plugins should call this method whenever they have changed the globals.
For example whenever a plugin adds an annotation, the buffers need
to be redisplayed. *)
method protect :
cancelable:bool -> ?parent:GWindow.window_skel -> (unit -> unit) -> unit
(** Lock the GUI ; run the funtion ; catch all exceptions ; Unlock GUI
The parent window must be set if this method is not called directly
by the main window: it will ensure that error dialogs are transient
for the right window.
Set cancelable to [true] if the protected action should be cancellable
by the user through button `Stop'. *)
method full_protect :
'a . cancelable:bool -> ?parent:GWindow.window_skel -> (unit -> 'a) ->
'a option
(** Lock the GUI ; run the funtion ; catch all exceptions ; Unlock GUI ;
returns [f ()].
The parent window must be set if this method is not called directly
by the main window: it will ensure that error dialogs are transient
for the right window.
Set cancelable to [true] if the protected action should be cancellable
by the user through button `Stop'. *)
method push_info : 'a. ('a, Format.formatter, unit) format -> 'a
(** Pretty print a temporary information in the status bar *)
method pop_info : unit -> unit
(** Remove last temporary information in the status bar *)
method show_ids : bool
* If [ true ] , the messages shown in the GUI can mention internal ids
( vid , , etc . ) . If [ false ] , other means of identification should
be used ( line numbers , etc . ) .
(vid, sid, etc.). If [false], other means of identification should
be used (line numbers, etc.). *)
method help_message : 'a 'b.
(<event : GObj.event_ops ; .. > as 'a) ->
('b, Format.formatter, unit) format ->
'b
(** Help message displayed when entering the widget *)
end
class main_window : unit -> main_window_extension_points
val register_extension : (main_window_extension_points -> unit) -> unit
(** Register an extension to the main GUI. It will be invoked at
initialization time.
@plugin development guide *)
val register_reset_extension : (main_window_extension_points -> unit) -> unit
(** Register a function to be called whenever the main GUI reset method is
called. *)
val reactive_buffer : main_window_extension_points ->
?parent_window:GWindow.window -> global list -> reactive_buffer
(** This function creates a reactive buffer for the given list of globals.
These buffers are cached and sensitive to selections and highlighters.
@since Beryllium-20090901 *)
* Bullets in left - margins
@since
@since Nitrogen-20111001 *)
module Feedback :
sig
val mark : GSourceView2.source_buffer
-> offset:int
-> Property_status.Feedback.t -> unit
(** [offset] is the offset of the character in the source buffer. The
mark is put in the left-margin of the line corresponding to said
character. *)
end
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/gui/design.mli | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* The extensible GUI.
@plugin development guide
* This is the type of source code buffers that can react to global
selections and highlighters.
@since Beryllium-20090901
* This class type lists all the methods available to navigate the
source code through the GUI
* Display the given globals in the pretty-printed source viewer.
* Display the given [stmt] in the original source viewer
* Display the given location in the original_source_viewer
* This is the type of extension points for the GUI.
@modify Boron-20100401 new way of handling the menu and the toolbar
@plugin development guide
* {3 Main Components}
* The whole GUI aka self
* The tree containing the list of files and functions
* The tree view containing the list of files and functions
* The main window
* The information panel.
The text is automatically cleared whenever the selection is changed.
You should not directly use the buffer contained in the annot_window
to add text. Use the method [pretty_information].
* Pretty print a message in the [annot_window],
optionally scrolling it to the beginning of the message.
* The lower notebook with messages tabs
* The [GText.view] showing the AST.
* The scrolling of the [GText.view] showing the AST.
* The multi-tab source file display widget containing the
original source.
* {3 Dialog Boxes}
* Display the analysis configuration dialog and offer the
opportunity to launch to the user
* Popup a modal dialog displaying an error message. If [reset] is true
(default is false), the gui is reset after the dialog has been
displayed.
* {3 Extension Points}
* [register_panel (name, widget, refresh)] registers a panel in GUI.
The arguments are the name of the panel to create,
the widget containing the panel and a function to be called on
refresh.
* Reset the GUI and its extensions to its initial state
* Force to rehilight the current displayed buffer.
Plugins should call this method whenever they have changed the states
on which the function given to [register_source_highlighter] have been
updated.
* Lock the GUI ; run the funtion ; catch all exceptions ; Unlock GUI
The parent window must be set if this method is not called directly
by the main window: it will ensure that error dialogs are transient
for the right window.
Set cancelable to [true] if the protected action should be cancellable
by the user through button `Stop'.
* Lock the GUI ; run the funtion ; catch all exceptions ; Unlock GUI ;
returns [f ()].
The parent window must be set if this method is not called directly
by the main window: it will ensure that error dialogs are transient
for the right window.
Set cancelable to [true] if the protected action should be cancellable
by the user through button `Stop'.
* Pretty print a temporary information in the status bar
* Remove last temporary information in the status bar
* Help message displayed when entering the widget
* Register an extension to the main GUI. It will be invoked at
initialization time.
@plugin development guide
* Register a function to be called whenever the main GUI reset method is
called.
* This function creates a reactive buffer for the given list of globals.
These buffers are cached and sensitive to selections and highlighters.
@since Beryllium-20090901
* [offset] is the offset of the character in the source buffer. The
mark is put in the left-margin of the line corresponding to said
character.
Local Variables:
compile-command: "make -C ../../.."
End:
| This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Cil_types
class type reactive_buffer = object
inherit Gtk_helper.error_manager
method buffer : GSourceView2.source_buffer
method locs : Pretty_source.Locs.state
method rehighlight : unit
method redisplay : unit
end
class type view_code = object
* { 3 Pretty - printed code }
method scroll : Pretty_source.localizable -> unit
* Move the pretty - printed source viewer to the given localizable
if possible . Return a boolean indicating whether the operation
succeeded
Now indicates whether the
operation succeeded .
if possible. Return a boolean indicating whether the operation
succeeded
@modify Nitrogen-20111001 Now indicates whether the
operation succeeded. *)
method display_globals : global list -> unit
* { 3 Original code }
method view_original_stmt : stmt -> location
method view_original : location -> unit
* { 3 Both pretty - printed and original code }
method view_stmt : stmt -> unit
* Display the given [ stmt ] in the [ source_viewer ] and in the
[ original_source_viewer ] . Equivalent to two successive
calls to [ scroll ] and [ view_original_stmt ]
@since Carbon-20101201
[original_source_viewer]. Equivalent to two successive
calls to [scroll] and [view_original_stmt]
@since Carbon-20101201 *)
method select_or_display_global : global -> unit
* This function tries to select the global in the treeview . If
this fails , for example because the global is not shown in the
treeview because of filters , it falls back to displaying the
global by hand .
@since
this fails, for example because the global is not shown in the
treeview because of filters, it falls back to displaying the
global by hand.
@since Nitrogen-20111001 *)
end
class protected_menu_factory:
Gtk_helper.host -> GMenu.menu -> [ GMenu.menu ] GMenu.factory
class type main_window_extension_points = object
inherit view_code
method toplevel : main_window_extension_points
method menu_manager: unit -> Menu_manager.menu_manager
* The object managing the menubar and the toolbar .
@since
@since Boron-20100401 *)
method file_tree : Filetree.t
method file_tree_view : GTree.view
method main_window : GWindow.window
method annot_window : Wtext.text
method pretty_information : 'a. ?scroll:bool -> ('a, Format.formatter, unit) format -> 'a
method lower_notebook : GPack.notebook
* { 4 Source viewers }
method source_viewer : GSourceView2.source_view
method source_viewer_scroll : GBin.scrolled_window
method reactive_buffer: reactive_buffer
* The buffer containing the AST .
@since Carbon-20101201
@since Carbon-20101201 *)
method original_source_viewer : Source_manager.t
method launcher : unit -> unit
method error :
'a. ?parent:GWindow.window_skel -> ?reset:bool ->
('a, Format.formatter, unit) format -> 'a
method register_source_selector :
(GMenu.menu GMenu.factory
-> main_window_extension_points
-> button:int -> Pretty_source.localizable -> unit) -> unit
* register an action to perform when button is released on a given
localizable .
If the button 3 is released , the first argument is popped as a
contextual menu .
@plugin development guide
localizable.
If the button 3 is released, the first argument is popped as a
contextual menu.
@plugin development guide *)
method register_source_highlighter :
(reactive_buffer -> Pretty_source.localizable ->
start:int -> stop:int -> unit)
-> unit
* register an highlighting function to run on a given localizable
between start and stop in the given buffer .
Priority of [ Gtext.tags ] is used to decide which tag is rendered on
top of the other .
Magnesium-20151001+dev : receives a { ! reactive_buffer } instead
of a { ! }
between start and stop in the given buffer.
Priority of [Gtext.tags] is used to decide which tag is rendered on
top of the other.
@modify Magnesium-20151001+dev: receives a {!reactive_buffer} instead
of a {!GSourceView2.source_buffer} *)
method register_panel :
(main_window_extension_points->(string*GObj.widget*(unit-> unit) option))
-> unit
* { 3 General features }
method reset : unit -> unit
method rehighlight : unit -> unit
method redisplay : unit -> unit
* @since
Force to redisplay the current displayed buffer .
Plugins should call this method whenever they have changed the globals .
For example whenever a plugin adds an annotation , the buffers need
to be redisplayed .
Force to redisplay the current displayed buffer.
Plugins should call this method whenever they have changed the globals.
For example whenever a plugin adds an annotation, the buffers need
to be redisplayed. *)
method protect :
cancelable:bool -> ?parent:GWindow.window_skel -> (unit -> unit) -> unit
method full_protect :
'a . cancelable:bool -> ?parent:GWindow.window_skel -> (unit -> 'a) ->
'a option
method push_info : 'a. ('a, Format.formatter, unit) format -> 'a
method pop_info : unit -> unit
method show_ids : bool
* If [ true ] , the messages shown in the GUI can mention internal ids
( vid , , etc . ) . If [ false ] , other means of identification should
be used ( line numbers , etc . ) .
(vid, sid, etc.). If [false], other means of identification should
be used (line numbers, etc.). *)
method help_message : 'a 'b.
(<event : GObj.event_ops ; .. > as 'a) ->
('b, Format.formatter, unit) format ->
'b
end
class main_window : unit -> main_window_extension_points
val register_extension : (main_window_extension_points -> unit) -> unit
val register_reset_extension : (main_window_extension_points -> unit) -> unit
val reactive_buffer : main_window_extension_points ->
?parent_window:GWindow.window -> global list -> reactive_buffer
* Bullets in left - margins
@since
@since Nitrogen-20111001 *)
module Feedback :
sig
val mark : GSourceView2.source_buffer
-> offset:int
-> Property_status.Feedback.t -> unit
end
|
d89dcefe3e7aa79a78acc74d76a638384f6c801406bdfd3785a2086222d4c05c | ptal/AbSolute | event_loop.ml | Copyright 2019
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. *)
module Schedulable_abstract_domain = Schedulable_abstract_domain
open Domains
open Domains.Abstract_domain
open Fixpoint
open Core
open Lang.Ast
open Bounds
open Schedulable_abstract_domain
open Typing.Ad_type
module type Event_combinator =
sig
type t
val name: string
val consume_task: t -> task -> (t * bool * event list)
val produce_events: t -> Pengine2D.t -> (t * Pengine2D.t)
val produce_tasks: t -> Pengine2D.t -> (t * Pengine2D.t)
end
module Event_atom(A: Schedulable_abstract_domain) =
struct
type t = A.t ref
let name = A.name
let consume_task a task =
let a', is_entailed = A.exec_task !a task in
let a', events = A.drain_events a' in
a := a';
a, is_entailed, events
let produce_tasks a pengine =
let a', tasks_events = A.drain_tasks !a in
a := a';
let pengine = List.fold_left (
fun p (task, events) -> Pengine2D.subscribe p task events) pengine tasks_events in
a, pengine
let produce_events a pengine =
let a', events = A.drain_events !a in
a := a';
Pengine2D.react pengine events;
a, pengine
end
module Event_cons(A: Schedulable_abstract_domain)(B: Event_combinator) =
struct
type t = (A.t ref * B.t)
module Atom = Event_atom(A)
let name = Atom.name ^ "," ^ B.name
let consume_task (a, b) ((uid, task_id) as task) =
if A.uid !a = uid then
let a, entailed, events = Atom.consume_task a task in
(a,b), entailed, events
else
let b, entailed, events = B.consume_task b (uid, task_id) in
(a,b), entailed, events
let produce_tasks (a, b) pengine =
let a, pengine = Atom.produce_tasks a pengine in
let b, pengine = B.produce_tasks b pengine in
(a,b), pengine
let produce_events (a, b) pengine =
let a, pengine = Atom.produce_events a pengine in
let b, pengine = B.produce_events b pengine in
(a,b), pengine
end
module Event_loop(L: Event_combinator) =
struct
module B = Bound_unit
module I = Unit_interpretation
type t = {
uid: ad_uid;
l: L.t;
pengine: Pengine2D.t;
has_changed: bool;
}
let init uid l = {
uid; l;
pengine=Pengine2D.empty ();
has_changed=false;
}
let uid p = p.uid
let name = "Event_loop(" ^ L.name ^ ")"
let type_of _ = None
let closure p =
let l, pengine = L.produce_tasks p.l p.pengine in
let l, pengine = L.produce_events l pengine in
Printf.printf " E.closure : num active tasks % d\n " ( Pengine2D.num_active_tasks pengine ) ;
let pengine, l, has_changed = Pengine2D.fixpoint pengine L.consume_task l in
(* if has_changed then Printf.printf "E.closure: has_changed\n" else Printf.printf "E.closure: NOT has_changed\n"; *)
{p with l; pengine; has_changed}
let has_changed p = p.has_changed
let state _ = Kleene.True
let split ?strategy:_ _ = []
let volume _ = 1.
let interpretation _ = Unit_interpretation.empty 0
let map_interpretation x f =
x, snd (f (Unit_interpretation.empty 0))
let print _ _ = ()
(* This abstract domain is totally functional. *)
type snapshot = t
let lazy_copy p n = List.init n (fun _ -> p)
let restore _ s = s
let meta_exn () = raise (Wrong_modelling ("[" ^ name ^ "] Event_loop is a meta abstract domain that does not represent any kind of variable or constraint."))
let empty _ = raise (Wrong_modelling "`Event_loop.empty` is not supported, you should first create the abstract domains and then pass their references to `Event_loop.init`.")
let project _ _ = meta_exn ()
let embed _ _ _ = meta_exn ()
let weak_incremental_closure _ _ = meta_exn ()
let entailment _ _ = meta_exn ()
let interpret _ _ _ = meta_exn ()
let drain_events _ = meta_exn ()
let events_of _ _ = meta_exn ()
let events_of_var _ _ = meta_exn ()
end
| null | https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/transformers/event_loop/event_loop.ml | ocaml | if has_changed then Printf.printf "E.closure: has_changed\n" else Printf.printf "E.closure: NOT has_changed\n";
This abstract domain is totally functional. | Copyright 2019
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 of the License , or ( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. *)
module Schedulable_abstract_domain = Schedulable_abstract_domain
open Domains
open Domains.Abstract_domain
open Fixpoint
open Core
open Lang.Ast
open Bounds
open Schedulable_abstract_domain
open Typing.Ad_type
module type Event_combinator =
sig
type t
val name: string
val consume_task: t -> task -> (t * bool * event list)
val produce_events: t -> Pengine2D.t -> (t * Pengine2D.t)
val produce_tasks: t -> Pengine2D.t -> (t * Pengine2D.t)
end
module Event_atom(A: Schedulable_abstract_domain) =
struct
type t = A.t ref
let name = A.name
let consume_task a task =
let a', is_entailed = A.exec_task !a task in
let a', events = A.drain_events a' in
a := a';
a, is_entailed, events
let produce_tasks a pengine =
let a', tasks_events = A.drain_tasks !a in
a := a';
let pengine = List.fold_left (
fun p (task, events) -> Pengine2D.subscribe p task events) pengine tasks_events in
a, pengine
let produce_events a pengine =
let a', events = A.drain_events !a in
a := a';
Pengine2D.react pengine events;
a, pengine
end
module Event_cons(A: Schedulable_abstract_domain)(B: Event_combinator) =
struct
type t = (A.t ref * B.t)
module Atom = Event_atom(A)
let name = Atom.name ^ "," ^ B.name
let consume_task (a, b) ((uid, task_id) as task) =
if A.uid !a = uid then
let a, entailed, events = Atom.consume_task a task in
(a,b), entailed, events
else
let b, entailed, events = B.consume_task b (uid, task_id) in
(a,b), entailed, events
let produce_tasks (a, b) pengine =
let a, pengine = Atom.produce_tasks a pengine in
let b, pengine = B.produce_tasks b pengine in
(a,b), pengine
let produce_events (a, b) pengine =
let a, pengine = Atom.produce_events a pengine in
let b, pengine = B.produce_events b pengine in
(a,b), pengine
end
module Event_loop(L: Event_combinator) =
struct
module B = Bound_unit
module I = Unit_interpretation
type t = {
uid: ad_uid;
l: L.t;
pengine: Pengine2D.t;
has_changed: bool;
}
let init uid l = {
uid; l;
pengine=Pengine2D.empty ();
has_changed=false;
}
let uid p = p.uid
let name = "Event_loop(" ^ L.name ^ ")"
let type_of _ = None
let closure p =
let l, pengine = L.produce_tasks p.l p.pengine in
let l, pengine = L.produce_events l pengine in
Printf.printf " E.closure : num active tasks % d\n " ( Pengine2D.num_active_tasks pengine ) ;
let pengine, l, has_changed = Pengine2D.fixpoint pengine L.consume_task l in
{p with l; pengine; has_changed}
let has_changed p = p.has_changed
let state _ = Kleene.True
let split ?strategy:_ _ = []
let volume _ = 1.
let interpretation _ = Unit_interpretation.empty 0
let map_interpretation x f =
x, snd (f (Unit_interpretation.empty 0))
let print _ _ = ()
type snapshot = t
let lazy_copy p n = List.init n (fun _ -> p)
let restore _ s = s
let meta_exn () = raise (Wrong_modelling ("[" ^ name ^ "] Event_loop is a meta abstract domain that does not represent any kind of variable or constraint."))
let empty _ = raise (Wrong_modelling "`Event_loop.empty` is not supported, you should first create the abstract domains and then pass their references to `Event_loop.init`.")
let project _ _ = meta_exn ()
let embed _ _ _ = meta_exn ()
let weak_incremental_closure _ _ = meta_exn ()
let entailment _ _ = meta_exn ()
let interpret _ _ _ = meta_exn ()
let drain_events _ = meta_exn ()
let events_of _ _ = meta_exn ()
let events_of_var _ _ = meta_exn ()
end
|
46e1ff1b65d4cff41fb77e939899d158acaad465443702e880251079ee0c1d87 | mirage/ocaml-rpc | markdowngen.ml | open Rpc.Types
open Idl
open Codegen
let get_description desc =
let escape =
let translate = function
(* Escape special XML (and HTML) chars that might become tags *)
| '<' -> Some "<"
| '>' -> Some ">"
| '&' -> Some "&"
(* Escape some special markdown chars - these are not part of ocamldoc markup language *)
| ('*' | '_' | '[' | ']' | '(' | ')' | '#' | '!') as c ->
Some ("\\" ^ String.make 1 c)
| _ -> None
in
Internals.encode translate
in
String.concat " " desc |> escape
let rec string_of_t : type a. a typ -> string list =
let of_basic : type b. b basic -> string = function
| Int -> "int"
| Int32 -> "int32"
| Int64 -> "int64"
| Bool -> "bool"
| Float -> "float"
| String -> "string"
| Char -> "char"
in
let print txt = [ txt ] in
function
| Basic b -> print (of_basic b)
| DateTime -> print (of_basic String)
| Base64 -> print (of_basic String)
| Struct { sname; _ } -> print sname
| Variant { vname; _ } -> print vname
| Array t -> string_of_t t @ print " list"
| List t -> string_of_t t @ print " list"
| Dict (key, v) ->
print (Printf.sprintf "(%s * " (of_basic key)) @ string_of_t v @ print ") list"
| Unit -> print "unit"
| Option x -> string_of_t x @ print " option"
| Tuple (a, b) -> string_of_t a @ print " * " @ string_of_t b
| Tuple3 (a, b, c) ->
string_of_t a @ print " * " @ string_of_t b @ print " * " @ string_of_t c
| Tuple4 (a, b, c, d) ->
string_of_t a
@ print " * "
@ string_of_t b
@ print " * "
@ string_of_t c
@ print " * "
@ string_of_t d
| Abstract _ -> print "<abstract>"
let definition_of_t : type a. a typ -> string list = function
| Struct _ -> [ "struct { ... }" ]
| Variant _ -> [ "variant { ... }" ]
| ty -> string_of_t ty
let rec ocaml_patt_of_t : type a. a typ -> string =
fun ty ->
let of_basic : type b. b basic -> string = function
| Int -> "int"
| Int32 -> "int32"
| Int64 -> "int64"
| Bool -> "bool"
| Float -> "float"
| String -> "str"
| Char -> "char"
in
match ty with
| Basic b -> of_basic b
| DateTime -> "datetime"
| Base64 -> "base64"
| Struct s -> s.Rpc.Types.sname
| Variant _ -> "v"
| Array t -> Printf.sprintf "%s_list" (ocaml_patt_of_t t)
| List t -> Printf.sprintf "%s_list" (ocaml_patt_of_t t)
| Dict _ -> "dict"
| Unit -> "()"
| Option x -> Printf.sprintf "%s_opt" (ocaml_patt_of_t x)
| Tuple (a, b) -> Printf.sprintf "(%s,%s)" (ocaml_patt_of_t a) (ocaml_patt_of_t b)
| Tuple3 (a, b, c) ->
Printf.sprintf
"(%s,%s,%s)"
(ocaml_patt_of_t a)
(ocaml_patt_of_t b)
(ocaml_patt_of_t c)
| Tuple4 (a, b, c, d) ->
Printf.sprintf
"(%s,%s,%s,%s)"
(ocaml_patt_of_t a)
(ocaml_patt_of_t b)
(ocaml_patt_of_t c)
(ocaml_patt_of_t d)
| Abstract _ -> "abstract"
let rpc_of : type a. a typ -> string -> Rpc.t =
fun ty hint -> Rpcmarshal.marshal ty (Rpc_genfake.gen_nice ty hint)
let table headings rows =
(* Slightly more convenient to have columns sometimes. This
also ensures each row has the correct number of entries. *)
let transpose mat =
let rec inner r =
let safe_hd = function
| hd :: _ -> hd
| _ -> ""
in
let safe_tl = function
| _ :: tl -> tl
| _ -> []
in
match r with
| [] :: _ -> []
| _ -> List.(map safe_hd r :: inner (map safe_tl r))
in
inner mat
in
let columns = transpose (headings :: rows) in
let all_rows = transpose columns in
let col_widths =
let col_width col = List.fold_left max 0 col in
let widths = List.map String.length in
List.map (fun col -> col_width (widths col)) columns
in
let pad c n s = Printf.sprintf "%s%s" s (String.make (n - String.length s) c) in
let padfns = List.map (pad ' ') col_widths in
let pad_row row = List.map2 (fun fn x -> fn x) padfns row in
let padded = List.map pad_row all_rows in
let row_to_string row = Printf.sprintf " %s " (String.concat " | " row) in
let separator =
Printf.sprintf
"-%s-"
(String.concat "-|-" (List.map (fun width -> pad '-' width "") col_widths))
in
row_to_string (List.hd padded) :: separator :: List.map row_to_string (List.tl padded)
let link uri text = Printf.sprintf "[%s](%s)" text uri
let h1 txt = [ Printf.sprintf "# %s" txt ]
txt ; String.make ( String.length txt ) ' = ' ]
let h2 txt = [ Printf.sprintf "## %s" txt ]
txt ; String.make ( String.length txt ) ' - ' ]
let h3 txt = [ Printf.sprintf "### %s" txt ]
let h4 txt = [ Printf.sprintf "#### %s" txt ]
let h5 txt = [ Printf.sprintf "##### %s" txt ]
let h6 txt = [ Printf.sprintf "###### %s" txt ]
let hrule = [ "---" ]
(* Function inputs and outputs in a table *)
let of_args args =
let row_of_arg (is_in, Param.Boxed arg) =
match is_in, arg.Param.typedef.ty with
| false, Unit -> []
| _ ->
let name =
match arg.Param.name with
| Some s -> s
| None -> "unnamed"
in
let direction = if is_in then "in" else "out" in
let ty = arg.Param.typedef.name in
let description = get_description arg.Param.description in
[ name; direction; ty; description ]
in
table
[ "Name"; "Direction"; "Type"; "Description" ]
(List.filter (fun l -> List.length l > 0) (List.map row_of_arg args))
let of_struct_fields : 'a boxed_field list -> string list =
fun all ->
let of_row (BoxedField f) =
let ty = string_of_t f.field in
[ f.fname; String.concat "" ty; get_description f.fdescription ]
in
table [ "Name"; "Type"; "Description" ] (List.map of_row all)
let of_variant_tags : 'a boxed_tag list -> string list =
fun all ->
let of_row (BoxedTag t) =
let ty = string_of_t t.tcontents in
[ t.tname; String.concat "" ty; get_description t.tdescription ]
in
table [ "Name"; "Type"; "Description" ] (List.map of_row all)
let of_type_decl _ (BoxedDef t as t') =
if List.mem t' default_types
then []
else (
let name = t.name in
let header = [ Printf.sprintf "### %s" name ] in
let example_tys = Rpc_genfake.genall 0 name t.ty in
let marshalled =
List.map (fun example -> Rpcmarshal.marshal t.ty example) example_tys
in
let example =
("```json"
:: List.map
(fun x ->
Jsonrpc.to_string x
|> Yojson.Basic.from_string
|> Yojson.Basic.pretty_to_string)
marshalled)
@ [ "```" ]
in
let definition =
let defn = String.concat "" (definition_of_t t.ty) in
let description = get_description t.description in
[ Printf.sprintf "type `%s` = `%s`" name defn; description ]
in
let rest =
match t.ty with
| Struct structure -> h4 "Members" @ of_struct_fields structure.fields
| Variant variant -> h4 "Constructors" @ of_variant_tags variant.variants
| _ -> []
in
header @ example @ definition @ rest)
let json_of_method namespace _ _ (Codegen.BoxedFunction m) =
let inputs = Codegen.Method.find_inputs m.Codegen.Method.ty in
let (Idl.Param.Boxed output) = Codegen.Method.find_output m.Codegen.Method.ty in
let named, unnamed =
List.fold_left
(fun (named, unnamed) bp ->
match bp with
| Idl.Param.Boxed p ->
let rpc =
rpc_of
p.Idl.Param.typedef.Rpc.Types.ty
(match p.Idl.Param.name with
| Some n -> n
| None -> p.Idl.Param.typedef.Rpc.Types.name)
in
(match p.Idl.Param.name with
| Some n -> (n, rpc) :: named, unnamed
| None -> named, rpc :: unnamed))
([], [])
inputs
in
let get_wire_name name =
match namespace with
| Some ns -> Printf.sprintf "%s.%s" ns name
| None -> name
in
let wire_name = get_wire_name m.Codegen.Method.name in
let args =
match named with
| [] -> List.rev unnamed
| _ -> Rpc.Dict named :: List.rev unnamed
in
let call = Rpc.call wire_name args in
let input =
Jsonrpc.string_of_call call
|> Yojson.Basic.from_string
|> Yojson.Basic.pretty_to_string
in
let example_ty =
Rpc_genfake.gen_nice
output.Idl.Param.typedef.Rpc.Types.ty
(match output.Idl.Param.name with
| Some n -> n
| None -> output.Idl.Param.typedef.Rpc.Types.name)
in
let marshalled = Rpcmarshal.marshal output.Idl.Param.typedef.Rpc.Types.ty example_ty in
let output =
Jsonrpc.to_string marshalled
|> Yojson.Basic.from_string
|> Yojson.Basic.pretty_to_string
in
input, output
let ocaml_of_method (Codegen.BoxedFunction m) =
let inputs = Codegen.Method.find_inputs m.Codegen.Method.ty in
let (Idl.Param.Boxed output) = Codegen.Method.find_output m.Codegen.Method.ty in
let (Rpc.Types.BoxedDef error) = Codegen.Method.find_errors m.Codegen.Method.ty in
let patt_of_var = function
| Rpc.Types.BoxedTag t ->
Printf.sprintf
"%s%s"
t.Rpc.Types.tname
(match t.Rpc.Types.tcontents with
| Unit -> ""
| t -> Printf.sprintf " %s" (ocaml_patt_of_t t))
in
let err_pre, err_post =
match error.Rpc.Types.ty with
| Variant v ->
let pre = "try\n " in
let post =
Printf.sprintf
"with %s"
(String.concat
"\n| "
(List.map
(fun v -> Printf.sprintf "Exn (%s) -> ..." (patt_of_var v))
v.Rpc.Types.variants))
in
pre, post
| _ ->
let pre = "try\n " in
let post = "with _ -> ..." in
pre, post
in
let gen_arg p =
match p with
| Idl.Param.Boxed p ->
(match p.Idl.Param.name with
| Some n -> n
| None -> p.Idl.Param.typedef.Rpc.Types.name)
in
let result_patt =
match output.Idl.Param.typedef.Rpc.Types.ty with
| Unit -> "()"
| _ ->
(match output.Idl.Param.name with
| Some n -> n
| None -> output.Idl.Param.typedef.Rpc.Types.name)
in
Printf.sprintf
"%slet %s = Client.%s %s in\n ...\n%s\n"
err_pre
result_patt
m.Codegen.Method.name
(String.concat " " (List.map gen_arg inputs))
err_post
let ocaml_server_of_method is i ( Codegen . BoxedFunction m ) = [
Printf.sprintf " module S=%s(Idl . GenServerExn ( ) ) " ( String.capitalize i.Interface.name ) ;
" " ;
Printf.sprintf " let % s_impl % s = " ( m.Method.name ) args ;
" let result = % s in " ;
" result " ;
" " ;
" let bind ( ) = " ;
" S.%s % s_impl "
]
Printf.sprintf "module S=%s(Idl.GenServerExn ())" (String.capitalize i.Interface.name);
"";
Printf.sprintf "let %s_impl %s =" (m.Method.name) args;
" let result = %s in";
" result";
"";
"let bind () =";
" S.%s %s_impl"
]*)
let tabs_of namespace is i m =
let json, json_response = json_of_method namespace is i m in
let ocaml = ocaml_of_method m in
let python = Pythongen.example_stub_user i m |> Pythongen.string_of_ts in
let python_server = Pythongen.example_skeleton_user i m |> Pythongen.string_of_ts in
[ "> Client"
; ""
; Printf.sprintf "```json\n%s\n```" json
; ""
; Printf.sprintf "```ocaml\n%s\n```" ocaml
; ""
; Printf.sprintf "```python\n%s\n```" python
; ""
; "> Server"
; ""
; Printf.sprintf "```json\n%s\n```" json_response
; ""
; Printf.sprintf "```ocaml\n%s\n```" ocaml
; ""
; Printf.sprintf "```python\n%s\n```" python_server
; ""
]
let of_method namespace is i (Codegen.BoxedFunction m) =
let name = m.Method.name in
let description = get_description m.Method.description in
h2 (Printf.sprintf "Method: `%s`" name)
@ [ description ]
@ [ "" ]
@ tabs_of namespace is i (Codegen.BoxedFunction m)
@ [ "" ]
@ of_args
(List.map (fun p -> true, p) Method.(find_inputs m.ty)
@ [ (false, Method.(find_output m.ty)) ])
let all_errors i =
let errors =
List.map
(function
| BoxedFunction m -> Codegen.Method.find_errors m.Codegen.Method.ty)
i.Interface.methods
in
let rec uniq acc errors =
match errors with
| e :: es -> if List.mem e acc then uniq acc es else uniq (e :: acc) es
| [] -> List.rev acc
in
uniq [] errors
(** We also document the nested types that contain useful documentation *)
let expand_types is =
(* These are the types that are helpful to document in the markdown *)
let doc = function
| Struct { sname; _ } as ty -> Some { name = sname; description = []; ty }
| Variant { vname; _ } as ty -> Some { name = vname; description = []; ty }
| _ -> None
in
let rec expand : type a. bool -> a typ -> boxed_def list =
fun documented ty ->
let expand ty = expand false ty in
let defs =
match ty with
| Array ty -> expand ty
| List ty -> expand ty
| Dict (_, ty) -> expand ty
| Option ty -> expand ty
| Tuple (ty1, ty2) -> expand ty1 @ expand ty2
| Tuple3 (ty1, ty2, ty3) -> expand ty1 @ expand ty2 @ expand ty3
| Tuple4 (ty1, ty2, ty3, ty4) -> expand ty1 @ expand ty2 @ expand ty3 @ expand ty4
| Struct { fields; _ } ->
List.map
(function
| BoxedField field -> expand field.field)
fields
|> List.flatten
| Variant { variants; _ } ->
List.map
(function
| BoxedTag tag -> expand tag.tcontents)
variants
|> List.flatten
| _ -> []
in
match documented, doc ty with
| false, Some def -> defs @ [ BoxedDef def ]
| _ -> defs
in
let same (BoxedDef def) (BoxedDef def') = def'.name = def.name in
(* The expanded types will be grouped together before the parameter they were
expanded from, with later ones referencing earlier ones. The ones
already documented earlier won't be repeated. *)
List.fold_left
(fun documented_defs (BoxedDef { ty; _ } as def) ->
let expanded =
(* Each function parameter we expand is already documented *)
expand true ty |> List.filter (fun d -> not (same d def))
in
let not_documented d = not (List.exists (same d) documented_defs) in
documented_defs @ List.filter not_documented (expanded @ [ def ]))
[]
is.Interfaces.type_decls
let of_interface is i =
let name = i.Interface.details.Idl.Interface.name in
let namespace = i.Interface.details.Idl.Interface.namespace in
let description = get_description i.Interface.details.Idl.Interface.description in
h2 (Printf.sprintf "Interface: `%s`" name)
@ [ description ]
@ List.concat (List.map (of_method namespace is i) i.Interface.methods)
let of_interfaces x =
let name = x.Interfaces.name in
let description = get_description x.Interfaces.description in
h1 name
@ [ description ]
@ h2 "Type definitions"
@ List.concat (List.map (of_type_decl None) (expand_types x))
@ List.concat (List.map (of_interface x) x.Interfaces.interfaces)
@ h2 "Errors"
@ List.concat
(List.map
(of_type_decl None)
(List.flatten (List.map all_errors x.Interfaces.interfaces)))
let to_string x = String.concat "\n" (of_interfaces x)
| null | https://raw.githubusercontent.com/mirage/ocaml-rpc/fdbf7f5c3e4f0c75837f0a96d5d4d6458805fd57/src/lib/markdowngen.ml | ocaml | Escape special XML (and HTML) chars that might become tags
Escape some special markdown chars - these are not part of ocamldoc markup language
Slightly more convenient to have columns sometimes. This
also ensures each row has the correct number of entries.
Function inputs and outputs in a table
* We also document the nested types that contain useful documentation
These are the types that are helpful to document in the markdown
The expanded types will be grouped together before the parameter they were
expanded from, with later ones referencing earlier ones. The ones
already documented earlier won't be repeated.
Each function parameter we expand is already documented | open Rpc.Types
open Idl
open Codegen
let get_description desc =
let escape =
let translate = function
| '<' -> Some "<"
| '>' -> Some ">"
| '&' -> Some "&"
| ('*' | '_' | '[' | ']' | '(' | ')' | '#' | '!') as c ->
Some ("\\" ^ String.make 1 c)
| _ -> None
in
Internals.encode translate
in
String.concat " " desc |> escape
let rec string_of_t : type a. a typ -> string list =
let of_basic : type b. b basic -> string = function
| Int -> "int"
| Int32 -> "int32"
| Int64 -> "int64"
| Bool -> "bool"
| Float -> "float"
| String -> "string"
| Char -> "char"
in
let print txt = [ txt ] in
function
| Basic b -> print (of_basic b)
| DateTime -> print (of_basic String)
| Base64 -> print (of_basic String)
| Struct { sname; _ } -> print sname
| Variant { vname; _ } -> print vname
| Array t -> string_of_t t @ print " list"
| List t -> string_of_t t @ print " list"
| Dict (key, v) ->
print (Printf.sprintf "(%s * " (of_basic key)) @ string_of_t v @ print ") list"
| Unit -> print "unit"
| Option x -> string_of_t x @ print " option"
| Tuple (a, b) -> string_of_t a @ print " * " @ string_of_t b
| Tuple3 (a, b, c) ->
string_of_t a @ print " * " @ string_of_t b @ print " * " @ string_of_t c
| Tuple4 (a, b, c, d) ->
string_of_t a
@ print " * "
@ string_of_t b
@ print " * "
@ string_of_t c
@ print " * "
@ string_of_t d
| Abstract _ -> print "<abstract>"
let definition_of_t : type a. a typ -> string list = function
| Struct _ -> [ "struct { ... }" ]
| Variant _ -> [ "variant { ... }" ]
| ty -> string_of_t ty
let rec ocaml_patt_of_t : type a. a typ -> string =
fun ty ->
let of_basic : type b. b basic -> string = function
| Int -> "int"
| Int32 -> "int32"
| Int64 -> "int64"
| Bool -> "bool"
| Float -> "float"
| String -> "str"
| Char -> "char"
in
match ty with
| Basic b -> of_basic b
| DateTime -> "datetime"
| Base64 -> "base64"
| Struct s -> s.Rpc.Types.sname
| Variant _ -> "v"
| Array t -> Printf.sprintf "%s_list" (ocaml_patt_of_t t)
| List t -> Printf.sprintf "%s_list" (ocaml_patt_of_t t)
| Dict _ -> "dict"
| Unit -> "()"
| Option x -> Printf.sprintf "%s_opt" (ocaml_patt_of_t x)
| Tuple (a, b) -> Printf.sprintf "(%s,%s)" (ocaml_patt_of_t a) (ocaml_patt_of_t b)
| Tuple3 (a, b, c) ->
Printf.sprintf
"(%s,%s,%s)"
(ocaml_patt_of_t a)
(ocaml_patt_of_t b)
(ocaml_patt_of_t c)
| Tuple4 (a, b, c, d) ->
Printf.sprintf
"(%s,%s,%s,%s)"
(ocaml_patt_of_t a)
(ocaml_patt_of_t b)
(ocaml_patt_of_t c)
(ocaml_patt_of_t d)
| Abstract _ -> "abstract"
let rpc_of : type a. a typ -> string -> Rpc.t =
fun ty hint -> Rpcmarshal.marshal ty (Rpc_genfake.gen_nice ty hint)
let table headings rows =
let transpose mat =
let rec inner r =
let safe_hd = function
| hd :: _ -> hd
| _ -> ""
in
let safe_tl = function
| _ :: tl -> tl
| _ -> []
in
match r with
| [] :: _ -> []
| _ -> List.(map safe_hd r :: inner (map safe_tl r))
in
inner mat
in
let columns = transpose (headings :: rows) in
let all_rows = transpose columns in
let col_widths =
let col_width col = List.fold_left max 0 col in
let widths = List.map String.length in
List.map (fun col -> col_width (widths col)) columns
in
let pad c n s = Printf.sprintf "%s%s" s (String.make (n - String.length s) c) in
let padfns = List.map (pad ' ') col_widths in
let pad_row row = List.map2 (fun fn x -> fn x) padfns row in
let padded = List.map pad_row all_rows in
let row_to_string row = Printf.sprintf " %s " (String.concat " | " row) in
let separator =
Printf.sprintf
"-%s-"
(String.concat "-|-" (List.map (fun width -> pad '-' width "") col_widths))
in
row_to_string (List.hd padded) :: separator :: List.map row_to_string (List.tl padded)
let link uri text = Printf.sprintf "[%s](%s)" text uri
let h1 txt = [ Printf.sprintf "# %s" txt ]
txt ; String.make ( String.length txt ) ' = ' ]
let h2 txt = [ Printf.sprintf "## %s" txt ]
txt ; String.make ( String.length txt ) ' - ' ]
let h3 txt = [ Printf.sprintf "### %s" txt ]
let h4 txt = [ Printf.sprintf "#### %s" txt ]
let h5 txt = [ Printf.sprintf "##### %s" txt ]
let h6 txt = [ Printf.sprintf "###### %s" txt ]
let hrule = [ "---" ]
let of_args args =
let row_of_arg (is_in, Param.Boxed arg) =
match is_in, arg.Param.typedef.ty with
| false, Unit -> []
| _ ->
let name =
match arg.Param.name with
| Some s -> s
| None -> "unnamed"
in
let direction = if is_in then "in" else "out" in
let ty = arg.Param.typedef.name in
let description = get_description arg.Param.description in
[ name; direction; ty; description ]
in
table
[ "Name"; "Direction"; "Type"; "Description" ]
(List.filter (fun l -> List.length l > 0) (List.map row_of_arg args))
let of_struct_fields : 'a boxed_field list -> string list =
fun all ->
let of_row (BoxedField f) =
let ty = string_of_t f.field in
[ f.fname; String.concat "" ty; get_description f.fdescription ]
in
table [ "Name"; "Type"; "Description" ] (List.map of_row all)
let of_variant_tags : 'a boxed_tag list -> string list =
fun all ->
let of_row (BoxedTag t) =
let ty = string_of_t t.tcontents in
[ t.tname; String.concat "" ty; get_description t.tdescription ]
in
table [ "Name"; "Type"; "Description" ] (List.map of_row all)
let of_type_decl _ (BoxedDef t as t') =
if List.mem t' default_types
then []
else (
let name = t.name in
let header = [ Printf.sprintf "### %s" name ] in
let example_tys = Rpc_genfake.genall 0 name t.ty in
let marshalled =
List.map (fun example -> Rpcmarshal.marshal t.ty example) example_tys
in
let example =
("```json"
:: List.map
(fun x ->
Jsonrpc.to_string x
|> Yojson.Basic.from_string
|> Yojson.Basic.pretty_to_string)
marshalled)
@ [ "```" ]
in
let definition =
let defn = String.concat "" (definition_of_t t.ty) in
let description = get_description t.description in
[ Printf.sprintf "type `%s` = `%s`" name defn; description ]
in
let rest =
match t.ty with
| Struct structure -> h4 "Members" @ of_struct_fields structure.fields
| Variant variant -> h4 "Constructors" @ of_variant_tags variant.variants
| _ -> []
in
header @ example @ definition @ rest)
let json_of_method namespace _ _ (Codegen.BoxedFunction m) =
let inputs = Codegen.Method.find_inputs m.Codegen.Method.ty in
let (Idl.Param.Boxed output) = Codegen.Method.find_output m.Codegen.Method.ty in
let named, unnamed =
List.fold_left
(fun (named, unnamed) bp ->
match bp with
| Idl.Param.Boxed p ->
let rpc =
rpc_of
p.Idl.Param.typedef.Rpc.Types.ty
(match p.Idl.Param.name with
| Some n -> n
| None -> p.Idl.Param.typedef.Rpc.Types.name)
in
(match p.Idl.Param.name with
| Some n -> (n, rpc) :: named, unnamed
| None -> named, rpc :: unnamed))
([], [])
inputs
in
let get_wire_name name =
match namespace with
| Some ns -> Printf.sprintf "%s.%s" ns name
| None -> name
in
let wire_name = get_wire_name m.Codegen.Method.name in
let args =
match named with
| [] -> List.rev unnamed
| _ -> Rpc.Dict named :: List.rev unnamed
in
let call = Rpc.call wire_name args in
let input =
Jsonrpc.string_of_call call
|> Yojson.Basic.from_string
|> Yojson.Basic.pretty_to_string
in
let example_ty =
Rpc_genfake.gen_nice
output.Idl.Param.typedef.Rpc.Types.ty
(match output.Idl.Param.name with
| Some n -> n
| None -> output.Idl.Param.typedef.Rpc.Types.name)
in
let marshalled = Rpcmarshal.marshal output.Idl.Param.typedef.Rpc.Types.ty example_ty in
let output =
Jsonrpc.to_string marshalled
|> Yojson.Basic.from_string
|> Yojson.Basic.pretty_to_string
in
input, output
let ocaml_of_method (Codegen.BoxedFunction m) =
let inputs = Codegen.Method.find_inputs m.Codegen.Method.ty in
let (Idl.Param.Boxed output) = Codegen.Method.find_output m.Codegen.Method.ty in
let (Rpc.Types.BoxedDef error) = Codegen.Method.find_errors m.Codegen.Method.ty in
let patt_of_var = function
| Rpc.Types.BoxedTag t ->
Printf.sprintf
"%s%s"
t.Rpc.Types.tname
(match t.Rpc.Types.tcontents with
| Unit -> ""
| t -> Printf.sprintf " %s" (ocaml_patt_of_t t))
in
let err_pre, err_post =
match error.Rpc.Types.ty with
| Variant v ->
let pre = "try\n " in
let post =
Printf.sprintf
"with %s"
(String.concat
"\n| "
(List.map
(fun v -> Printf.sprintf "Exn (%s) -> ..." (patt_of_var v))
v.Rpc.Types.variants))
in
pre, post
| _ ->
let pre = "try\n " in
let post = "with _ -> ..." in
pre, post
in
let gen_arg p =
match p with
| Idl.Param.Boxed p ->
(match p.Idl.Param.name with
| Some n -> n
| None -> p.Idl.Param.typedef.Rpc.Types.name)
in
let result_patt =
match output.Idl.Param.typedef.Rpc.Types.ty with
| Unit -> "()"
| _ ->
(match output.Idl.Param.name with
| Some n -> n
| None -> output.Idl.Param.typedef.Rpc.Types.name)
in
Printf.sprintf
"%slet %s = Client.%s %s in\n ...\n%s\n"
err_pre
result_patt
m.Codegen.Method.name
(String.concat " " (List.map gen_arg inputs))
err_post
let ocaml_server_of_method is i ( Codegen . BoxedFunction m ) = [
Printf.sprintf " module S=%s(Idl . GenServerExn ( ) ) " ( String.capitalize i.Interface.name ) ;
" " ;
Printf.sprintf " let % s_impl % s = " ( m.Method.name ) args ;
" let result = % s in " ;
" result " ;
" " ;
" let bind ( ) = " ;
" S.%s % s_impl "
]
Printf.sprintf "module S=%s(Idl.GenServerExn ())" (String.capitalize i.Interface.name);
"";
Printf.sprintf "let %s_impl %s =" (m.Method.name) args;
" let result = %s in";
" result";
"";
"let bind () =";
" S.%s %s_impl"
]*)
let tabs_of namespace is i m =
let json, json_response = json_of_method namespace is i m in
let ocaml = ocaml_of_method m in
let python = Pythongen.example_stub_user i m |> Pythongen.string_of_ts in
let python_server = Pythongen.example_skeleton_user i m |> Pythongen.string_of_ts in
[ "> Client"
; ""
; Printf.sprintf "```json\n%s\n```" json
; ""
; Printf.sprintf "```ocaml\n%s\n```" ocaml
; ""
; Printf.sprintf "```python\n%s\n```" python
; ""
; "> Server"
; ""
; Printf.sprintf "```json\n%s\n```" json_response
; ""
; Printf.sprintf "```ocaml\n%s\n```" ocaml
; ""
; Printf.sprintf "```python\n%s\n```" python_server
; ""
]
let of_method namespace is i (Codegen.BoxedFunction m) =
let name = m.Method.name in
let description = get_description m.Method.description in
h2 (Printf.sprintf "Method: `%s`" name)
@ [ description ]
@ [ "" ]
@ tabs_of namespace is i (Codegen.BoxedFunction m)
@ [ "" ]
@ of_args
(List.map (fun p -> true, p) Method.(find_inputs m.ty)
@ [ (false, Method.(find_output m.ty)) ])
let all_errors i =
let errors =
List.map
(function
| BoxedFunction m -> Codegen.Method.find_errors m.Codegen.Method.ty)
i.Interface.methods
in
let rec uniq acc errors =
match errors with
| e :: es -> if List.mem e acc then uniq acc es else uniq (e :: acc) es
| [] -> List.rev acc
in
uniq [] errors
let expand_types is =
let doc = function
| Struct { sname; _ } as ty -> Some { name = sname; description = []; ty }
| Variant { vname; _ } as ty -> Some { name = vname; description = []; ty }
| _ -> None
in
let rec expand : type a. bool -> a typ -> boxed_def list =
fun documented ty ->
let expand ty = expand false ty in
let defs =
match ty with
| Array ty -> expand ty
| List ty -> expand ty
| Dict (_, ty) -> expand ty
| Option ty -> expand ty
| Tuple (ty1, ty2) -> expand ty1 @ expand ty2
| Tuple3 (ty1, ty2, ty3) -> expand ty1 @ expand ty2 @ expand ty3
| Tuple4 (ty1, ty2, ty3, ty4) -> expand ty1 @ expand ty2 @ expand ty3 @ expand ty4
| Struct { fields; _ } ->
List.map
(function
| BoxedField field -> expand field.field)
fields
|> List.flatten
| Variant { variants; _ } ->
List.map
(function
| BoxedTag tag -> expand tag.tcontents)
variants
|> List.flatten
| _ -> []
in
match documented, doc ty with
| false, Some def -> defs @ [ BoxedDef def ]
| _ -> defs
in
let same (BoxedDef def) (BoxedDef def') = def'.name = def.name in
List.fold_left
(fun documented_defs (BoxedDef { ty; _ } as def) ->
let expanded =
expand true ty |> List.filter (fun d -> not (same d def))
in
let not_documented d = not (List.exists (same d) documented_defs) in
documented_defs @ List.filter not_documented (expanded @ [ def ]))
[]
is.Interfaces.type_decls
let of_interface is i =
let name = i.Interface.details.Idl.Interface.name in
let namespace = i.Interface.details.Idl.Interface.namespace in
let description = get_description i.Interface.details.Idl.Interface.description in
h2 (Printf.sprintf "Interface: `%s`" name)
@ [ description ]
@ List.concat (List.map (of_method namespace is i) i.Interface.methods)
let of_interfaces x =
let name = x.Interfaces.name in
let description = get_description x.Interfaces.description in
h1 name
@ [ description ]
@ h2 "Type definitions"
@ List.concat (List.map (of_type_decl None) (expand_types x))
@ List.concat (List.map (of_interface x) x.Interfaces.interfaces)
@ h2 "Errors"
@ List.concat
(List.map
(of_type_decl None)
(List.flatten (List.map all_errors x.Interfaces.interfaces)))
let to_string x = String.concat "\n" (of_interfaces x)
|
55764179d3a25209ca14c5adc11397b6c0f1301feff3d1453bfb8d1f9d59b1af | LexiFi/menhir | LALR.ml | (******************************************************************************)
(* *)
(* *)
, Paris
, PPS , Université Paris Diderot
(* *)
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
(* file LICENSE. *)
(* *)
(******************************************************************************)
This module constructs an LALR automaton for the grammar described by the
module [ Grammar ] .
module [Grammar]. *)
In LALR mode , two LR(1 ) states are merged as soon as they have the same
LR(0 ) core .
LR(0) core. *)
open Grammar
type lr1state =
Lr0.lr1state
module Run () = struct
let () = ()
(* -------------------------------------------------------------------------- *)
The LALR automaton has exactly the same states as the LR(0 ) automaton , up
to lookahead information . Therefore , we can use the same state numbers .
Thus , the states and the transitions of the LALR automaton are the same as
those of the LR(0 ) automaton !
to lookahead information. Therefore, we can use the same state numbers.
Thus, the states and the transitions of the LALR automaton are the same as
those of the LR(0) automaton! *)
This means that we have almost nothing to do : in fact , the only thing that
we have to do is compute a mapping of LR(0 ) nodes to LR(1 ) states .
we have to do is compute a mapping of LR(0) nodes to LR(1) states. *)
This computation can be viewed as a fixed point computation . In fact , it is
a special kind of fixed point computation : it can be viewed as a forward
data flow analysis where the graph is the LR(0 ) automaton and a property is
an LR(1 ) state .
a special kind of fixed point computation: it can be viewed as a forward
data flow analysis where the graph is the LR(0) automaton and a property is
an LR(1) state. *)
type node =
int
A property is an LR(1 ) state . The function [ leq_join ] is used to detect
stabilization and to merge the contribution of a predecessor state into a
successor state . We exploit the fact that [ Lr0.union s ' s ] is physically
equal to [ s ] if [ s ' ] is a subet of [ s ] . ( Yes , we live on the edge . )
stabilization and to merge the contribution of a predecessor state into a
successor state. We exploit the fact that [Lr0.union s' s] is physically
equal to [s] if [s'] is a subet of [s]. (Yes, we live on the edge.) *)
module P = struct
type property = lr1state
let leq_join = Lr0.union
end
(* The graph. *)
module G = struct
type variable = node
type property = P.property
(* The root nodes are the entry nodes of the LR(0) automaton. The properties
associated with these nodes are given by the function [Lr0.start]. *)
let foreach_root f =
ProductionMap.iter (fun _prod node ->
f node (Lr0.start node)
) Lr0.entry
(* The edges are the edges of the LR(0) automaton, and the manner in which
each edge contributes to the computation of a property is given by the
function [Lr0.transition]. *)
let foreach_successor node state f =
SymbolMap.iter (fun symbol (successor_node : node) ->
let successor_state : lr1state = Lr0.transition symbol state in
f successor_node successor_state
) (Lr0.outgoing_edges node)
end
(* Run the data flow computation. *)
module F = Fix.DataFlow.ForIntSegment(Lr0)(P)(G)
(* [solution : variable -> property option]. *)
(* Because every node is reachable, this function never returns [None]. *)
(* -------------------------------------------------------------------------- *)
Expose the mapping of nodes to LR(1 ) states .
let n =
Lr0.n
let states : lr1state array =
Array.init n (fun node -> Option.force (F.solution node))
let state : node -> lr1state =
Array.get states
(* -------------------------------------------------------------------------- *)
Expose the entry nodes and transitions of the LALR automaton .
(* Because we re-use LR(0) node numbers, these are exactly the same as those
of the LR(0) automaton! *)
let entry : node ProductionMap.t =
Lr0.entry
let transitions : node -> node SymbolMap.t =
Lr0.outgoing_edges
(* -------------------------------------------------------------------------- *)
(* Expose the bijection between nodes and numbers. *)
let number (i : node) : int =
i
let node (i : int) : node =
i
(* -------------------------------------------------------------------------- *)
end (* Run *)
| null | https://raw.githubusercontent.com/LexiFi/menhir/794e64e7997d4d3f91d36dd49aaecc942ea858b7/src/LALR.ml | ocaml | ****************************************************************************
file LICENSE.
****************************************************************************
--------------------------------------------------------------------------
The graph.
The root nodes are the entry nodes of the LR(0) automaton. The properties
associated with these nodes are given by the function [Lr0.start].
The edges are the edges of the LR(0) automaton, and the manner in which
each edge contributes to the computation of a property is given by the
function [Lr0.transition].
Run the data flow computation.
[solution : variable -> property option].
Because every node is reachable, this function never returns [None].
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Because we re-use LR(0) node numbers, these are exactly the same as those
of the LR(0) automaton!
--------------------------------------------------------------------------
Expose the bijection between nodes and numbers.
--------------------------------------------------------------------------
Run |
, Paris
, PPS , Université Paris Diderot
. All rights reserved . This file is distributed under the
terms of the GNU General Public License version 2 , as described in the
This module constructs an LALR automaton for the grammar described by the
module [ Grammar ] .
module [Grammar]. *)
In LALR mode , two LR(1 ) states are merged as soon as they have the same
LR(0 ) core .
LR(0) core. *)
open Grammar
type lr1state =
Lr0.lr1state
module Run () = struct
let () = ()
The LALR automaton has exactly the same states as the LR(0 ) automaton , up
to lookahead information . Therefore , we can use the same state numbers .
Thus , the states and the transitions of the LALR automaton are the same as
those of the LR(0 ) automaton !
to lookahead information. Therefore, we can use the same state numbers.
Thus, the states and the transitions of the LALR automaton are the same as
those of the LR(0) automaton! *)
This means that we have almost nothing to do : in fact , the only thing that
we have to do is compute a mapping of LR(0 ) nodes to LR(1 ) states .
we have to do is compute a mapping of LR(0) nodes to LR(1) states. *)
This computation can be viewed as a fixed point computation . In fact , it is
a special kind of fixed point computation : it can be viewed as a forward
data flow analysis where the graph is the LR(0 ) automaton and a property is
an LR(1 ) state .
a special kind of fixed point computation: it can be viewed as a forward
data flow analysis where the graph is the LR(0) automaton and a property is
an LR(1) state. *)
type node =
int
A property is an LR(1 ) state . The function [ leq_join ] is used to detect
stabilization and to merge the contribution of a predecessor state into a
successor state . We exploit the fact that [ Lr0.union s ' s ] is physically
equal to [ s ] if [ s ' ] is a subet of [ s ] . ( Yes , we live on the edge . )
stabilization and to merge the contribution of a predecessor state into a
successor state. We exploit the fact that [Lr0.union s' s] is physically
equal to [s] if [s'] is a subet of [s]. (Yes, we live on the edge.) *)
module P = struct
type property = lr1state
let leq_join = Lr0.union
end
module G = struct
type variable = node
type property = P.property
let foreach_root f =
ProductionMap.iter (fun _prod node ->
f node (Lr0.start node)
) Lr0.entry
let foreach_successor node state f =
SymbolMap.iter (fun symbol (successor_node : node) ->
let successor_state : lr1state = Lr0.transition symbol state in
f successor_node successor_state
) (Lr0.outgoing_edges node)
end
module F = Fix.DataFlow.ForIntSegment(Lr0)(P)(G)
Expose the mapping of nodes to LR(1 ) states .
let n =
Lr0.n
let states : lr1state array =
Array.init n (fun node -> Option.force (F.solution node))
let state : node -> lr1state =
Array.get states
Expose the entry nodes and transitions of the LALR automaton .
let entry : node ProductionMap.t =
Lr0.entry
let transitions : node -> node SymbolMap.t =
Lr0.outgoing_edges
let number (i : node) : int =
i
let node (i : int) : node =
i
|
cb41795bea41fb8bb15f6d87963915c2b297d1f9a5f894145c1b7a62b1b93576 | martijnbastiaan/doctest-parallel | Foo.hs | # LANGUAGE TemplateHaskell #
module Foo where
import Bar
-- | some documentation
foo :: Int
foo = $(bar)
| null | https://raw.githubusercontent.com/martijnbastiaan/doctest-parallel/f70d6a1c946cc0ada88571b90a39a7cd4d065452/test/extract/th/Foo.hs | haskell | | some documentation | # LANGUAGE TemplateHaskell #
module Foo where
import Bar
foo :: Int
foo = $(bar)
|
8f548596eb615ae62d9cc4a01ab0e185ac844a5c8d1d9d79463e792c7a7c1536 | korya/efuns | wX_port.ml | (***********************************************************************)
(* *)
(* ____ *)
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Xtypes
open WX_types
class t parent attributes =
object (self)
inherit WX_object.t parent attributes as super
val mutable widget = None
method container_add (o : contained) =
o#set_parent self#container;
widget <- Some o;
self#wait_resize
method size_request =
let sz = szhints in
if not w.w_size_modified || sz.comp_timestamp = s.s_timestamp then sz else
begin
sz.comp_timestamp <- s.s_timestamp;
match widget with None -> sz | Some o ->
let sz = o#size_request in
szhints <- { sz with
requested_width = sz.requested_width + 4;
requested_height = sz.requested_height + 4;
comp_timestamp = s.s_timestamp;
};
szhints
end
method size_allocate x y dx dy =
w.w_size_modified <- false;
let g = w.w_geometry in
let modified = not (g.width = dx && g.height = dy) in
super#size_allocate x y dx dy;
if modified then
match widget with None -> () | Some o ->
let g = w.w_geometry in
o#size_allocate 2 2 (g.width - 4) (g.height - 4)
method destroy =
(match widget with None -> () | Some o -> o#destroy);
super#destroy
method realize =
super#realize;
match widget with None -> () | Some o -> o#realize
method show =
super#show;
match widget with None -> () | Some o -> o#show
end
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/toolkit/wX_port.ml | ocaml | *********************************************************************
____
********************************************************************* | Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Xtypes
open WX_types
class t parent attributes =
object (self)
inherit WX_object.t parent attributes as super
val mutable widget = None
method container_add (o : contained) =
o#set_parent self#container;
widget <- Some o;
self#wait_resize
method size_request =
let sz = szhints in
if not w.w_size_modified || sz.comp_timestamp = s.s_timestamp then sz else
begin
sz.comp_timestamp <- s.s_timestamp;
match widget with None -> sz | Some o ->
let sz = o#size_request in
szhints <- { sz with
requested_width = sz.requested_width + 4;
requested_height = sz.requested_height + 4;
comp_timestamp = s.s_timestamp;
};
szhints
end
method size_allocate x y dx dy =
w.w_size_modified <- false;
let g = w.w_geometry in
let modified = not (g.width = dx && g.height = dy) in
super#size_allocate x y dx dy;
if modified then
match widget with None -> () | Some o ->
let g = w.w_geometry in
o#size_allocate 2 2 (g.width - 4) (g.height - 4)
method destroy =
(match widget with None -> () | Some o -> o#destroy);
super#destroy
method realize =
super#realize;
match widget with None -> () | Some o -> o#realize
method show =
super#show;
match widget with None -> () | Some o -> o#show
end
|
03607402d3d5c0570d029051b479bf0fec18bf4d46e1d552ff34f85c0338dd86 | vikram/lisplibraries | specials.lisp | -*- Mode : LISP ; Syntax : COMMON - LISP ; Package : TBNL ; Base : 10 -*-
$ Header : /usr / local / cvsrep / tbnl / specials.lisp , v 1.92 2006/09/30 13:20:25 edi Exp $
Copyright ( c ) 2004 - 2006 , Dr. . All rights reserved .
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:tbnl)
(eval-when (:compile-toplevel :execute :load-toplevel)
(defmacro defvar-unbound (name &optional (doc-string ""))
"Convenience macro to declare unbound special variables with a
documentation string."
`(progn
(defvar ,name)
(setf (documentation ',name 'variable) ,doc-string)))
(defmacro defconstant* (name value &optional doc)
"Make sure VALUE is evaluated only once \(to appease SBCL)."
`(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
,@(when doc (list doc)))))
;; common http return codes
(defconstant +http-continue+ 100)
(defconstant +http-switching-protocols+ 101)
(defconstant +http-ok+ 200)
(defconstant +http-created+ 201)
(defconstant +http-accepted+ 202)
(defconstant +http-non-authoritative-information+ 203)
(defconstant +http-no-content+ 204)
(defconstant +http-reset-content+ 205)
(defconstant +http-partial-content+ 206)
(defconstant +http-multiple-choices+ 300)
(defconstant +http-moved-permanently+ 301)
(defconstant +http-moved-temporarily+ 302)
(defconstant +http-see-other+ 303)
(defconstant +http-not-modified+ 304)
(defconstant +http-use-proxy+ 305)
(defconstant +http-temporary-redirect+ 307)
(defconstant +http-bad-request+ 400)
(defconstant +http-authorization-required+ 401)
(defconstant +http-payment-required+ 402)
(defconstant +http-forbidden+ 403)
(defconstant +http-not-found+ 404)
(defconstant +http-method-not-allowed+ 405)
(defconstant +http-not-acceptable+ 406)
(defconstant +http-proxy-authentication-required+ 407)
(defconstant +http-request-time-out+ 408)
(defconstant +http-conflict+ 409)
(defconstant +http-gone+ 410)
(defconstant +http-length-required+ 411)
(defconstant +http-precondition-failed+ 412)
(defconstant +http-request-entity-too-large+ 413)
(defconstant +http-request-uri-too-large+ 414)
(defconstant +http-unsupported-media-type+ 415)
(defconstant +http-requested-range-not-satisfiable+ 416)
(defconstant +http-expectation-failed+ 417)
(defconstant +http-internal-server-error+ 500)
(defconstant +http-not-implemented+ 501)
(defconstant +http-bad-gateway+ 502)
(defconstant +http-service-unavailable+ 503)
(defconstant +http-gateway-time-out+ 504)
(defconstant +http-version-not-supported+ 505)
(defconstant* +day-names+
#("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun")
"The three-character names of the seven days of the week - needed
for cookie date format.")
(defconstant* +month-names+
#("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")
"The three-character names of the twelve months - needed for cookie
date format.")
(defvar *session-cookie-name* "tbnl-session"
"The name of the cookie \(or the GET parameter) which is used to
store the session on the client side.")
(defvar *rewrite-for-session-urls* t
"Whether HTML pages should possibly be rewritten for cookie-less
session-management.")
(defvar *content-types-for-url-rewrite*
'("text/html" "application/xhtml+xml")
"The content types for which url-rewriting is OK. See
*REWRITE-FOR-SESSION-URLS*.")
(defparameter *the-random-state* (make-random-state t)
"A fresh random state.")
(defvar-unbound *session-secret*
"A random value that's used to encode the public session data.")
(defvar *tbnl-port* 3000
"The port TBNL is listening on.")
(defvar-unbound *tbnl-stream*
"The stream representing the socket TBNL is listening on.")
(defvar *close-tbnl-stream* nil
"Set this to T if you want to close the TBNL socket each time a
request has been handled.")
(defvar *tbnl-socket-usage-counter* 0
"The number of requests serviced with the current socket.")
(declaim (type fixnum *tbnl-socket-usage-counter*))
(defvar *headers-sent* nil
"Used internally to check whether the reply headers have
already been sent for this request.")
(defvar *file-upload-hook* nil
"If this is not NIL, it should be a unary function which will
be called with a pathname for each file which is uploaded to
TBNL. The pathname denotes the temporary file to which the
uploaded file is written. The hook is called directly before the
file is created.")
(defvar *session-data* nil
"All sessions of all users currently using TBNL. An alist where the
car is the session's ID and the cdr is the SESSION object itself.")
(defvar *session-max-time* #.(* 30 60)
"The default time \(in seconds) after which a session times out.")
(declaim (type fixnum *session-max-time*))
(defvar *session-gc-frequency* 50
"A session GC \(see function SESSION-GC) will happen every
*SESSION-GC-FREQUENCY* requests \(counting only requests which use a
session).")
(declaim (type fixnum *session-gc-frequency*))
(defvar *use-user-agent-for-sessions* t
"Whether the 'User-Agent' header should be encoded into the session
string. If this value is true a session will cease to be accessible if
the client sends a different 'User-Agent' header.")
(defvar *use-remote-addr-for-sessions* nil
"Whether the client's remote IP \(as returned by REAL-REMOTE-ADDR)
should be encoded into the session string. If this value is true a
session will cease to be accessible if the client's remote IP changes.
This might for example be an issue if the client uses a proxy server
which doesn't send correct 'X_FORWARDED_FOR' headers.")
(defvar *default-content-type* "text/html; charset=iso-8859-1"
"The default content-type header which is returned to the client.")
(defvar *show-lisp-errors-p* nil
"Whether Lisp errors should be shown in HTML output.")
(defvar *show-lisp-backtraces-p* nil
"Whether Lisp backtraces should be shown in HTML output when an
error occurs. Will only have effect of *SHOW-LISP-ERRORS-P* is
also true.")
(defvar *catch-errors-p* t
"Whether TBNL should catch and log errors \(or rather invoke
the debugger).")
(defvar *log-lisp-errors-p* t
"Whether Lisp errors should be logged.")
(defvar *lisp-errors-log-level* :error
"Log level for Lisp errors.")
(defvar *log-lisp-warnings-p* t
"Whether Lisp warnings should be logged.")
(defvar *lisp-warnings-log-level* :warning
"Log level for Lisp warnings.")
(defvar *log-lisp-backtraces-p* nil
"Whether Lisp backtraces should be logged when an error
occurs. Will only have effect of *LOG-LISP-ERRORS-P* or
*LOG-LISP-BACKTRACES* are also true.")
(defvar *use-apache-log* #+:araneida nil #-:araneida t
"Whether log messages should be sent as headers \(assuming that
mod_lisp hands them over to Apache).")
(defvar *show-access-log-messages* t
"Whether routine messages about each request should be logged. This
will only be done if *USE-APACHE-LOG* is NIL.")
(defvar *log-file*
(load-time-value
(let ((tmp-dir
#+:allegro (system:temporary-directory)
#+:lispworks (pathname (or (lw:environment-variable "TEMP")
(lw:environment-variable "TMP")
#+:win32 "C:/"
#-:win32 "/tmp/"))
#-(or :allegro :lispworks) #p"/tmp/"))
(merge-pathnames "tbnl.log" tmp-dir)))
"The log file to use if *USE-APACHE-LOG* is false.")
(defvar *log-file-stream* nil
"The stream corresponding to the log file.")
(defvar *log-file-lock*
#-:lispworks
(kmrcl::make-lock "log-file-lock")
#+:lispworks
(mp:make-lock :name "log-file-lock")
"A lock to prevent two threads from writing to the log file at same
time.")
(defvar-unbound *command*
"The current request as read from *TBNL-STREAM*, converted into an
alist.")
(defvar-unbound *error*
"The last error or warning handled by TBNL.")
(defvar-unbound *session*
"The current SESSION object.")
(defvar-unbound *request*
"The current REQUEST object.")
(defvar-unbound *reply*
"The current REPLY object.")
(defvar-unbound *body*
"The body which was sent to the front-end or to the browser.")
(defvar-unbound *backtrace*
"The backtrace \(as a string) of the last error.")
(defvar *log-prefix* t
"The prefix which is printed in front of Apache log messages. This
should be a string or T \(for \"TBNL\", the default) or NIL \(meaning
no prefix).")
(defvar-unbound *listener*
"The KMRCL:LISTENER object which currently listens on *TBNL-PORT*")
(defvar *debug-mode* nil
"Whether we're in debug mode.")
(defconstant* +implementation-link+
#+:cmu "/"
#+:sbcl "/"
#+:clisp "/"
#+:allegro "/"
#+:lispworks "/"
#+:scl "/"
#+:openmcl "/"
#+:digitool "/"
#+:cormanlisp "/"
#+:ecl "/"
#+:gcl "")
(defvar *dispatch-table* (list 'default-dispatcher)
"A list of dispatch functions - see function PROCESS-REQUEST.")
(defvar *default-handler* 'default-handler
"The name of the function which is always returned by DEFAULT-DISPATCHER.")
(defvar *easy-handler-alist* nil)
(defvar *http-error-handler* nil
"Contains NIL \(the default) or a function of one argument which is
called if the content handler has set a return code other than
+HTTP-OK+ or +HTTP-NOT-MODIFIED+.")
(defvar *default-log-level* nil
"The default log level for LOG-MESSAGE*")
(defvar *session-data-lock*
#-:lispworks
(kmrcl::make-lock "session-data-lock")
#+:lispworks
(mp:make-lock :name "session-data-lock")
"A lock to prevent two threads from modifying *SESSION-DATA* at the
same time.")
(defvar *session-removal-hook* (constantly nil)
"A function of one argument \(a session object) which is called
whenever a session is garbage-collected.")
(defvar *tmp-directory*
#+(or :win32 :mswindows) "c:\\tbnl-temp\\"
#-(or :win32 :mswindows) "/tmp/tbnl/"
"Directory for temporary files created by MAKE-TMP-FILE-NAME.")
(defvar *tmp-files* nil
"A list of temporary files created while a request was handled.")
(defvar *use-modlisp-headers* nil
"If this variable is true then outgoing headers are written in a
format mod_lisp can understand, otherwise they're written like plain
HTTP headers.")
(defconstant +latin-1+
#+:allegro :latin1
#+:lispworks :latin-1
#+:sb-unicode :latin-1
#-(or :allegro :lispworks :sb-unicode) nil)
(defconstant +utf-8+
#+:allegro :utf8
#+:lispworks :utf-8
#+:sb-unicode :utf-8
#-(or :allegro :lispworks :sb-unicode) nil)
(defvar *tbnl-default-external-format* +latin-1+)
(defconstant +buffer-length+ 8192
"Length of buffers used for internal purposes.")
(eval-when (:compile-toplevel :load-toplevel :execute)
#+(or (and :allegro :allegro-version>= (version>= 6 0))
:sb-unicode
:lispworks4.3
:lispworks4.4
:lispworks5.0)
(pushnew :tbnl-bivalent-streams *features*))
#+:sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (find-symbol "*DEBUG-PRINT-VARIABLE-ALIST*" :sb-debug)
(pushnew :tbnl-sbcl-debug-print-variable-alist *features*)))
#+:lispworks
(defvar *hunchentoot-p* t
"Whether we are in 'Hunchentoot mode' or just serving as
infrastructure for TBNL.")
(pushnew :tbnl *features*)
stuff for Nikodemus Siivola 's HYPERDOC
;; see <-lisp.net/project/hyperdoc/>
;; and <>
(defvar *hyperdoc-base-uri* "/")
(let ((exported-symbols-alist
(loop for symbol being the external-symbols of :tbnl
collect (cons symbol
(concatenate 'string
"#"
(string-downcase symbol))))))
(defun hyperdoc-lookup (symbol type)
(declare (ignore type))
(cdr (assoc symbol
exported-symbols-alist
:test #'eq))))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/tbnl-0.11.4/specials.lisp | lisp | Syntax : COMMON - LISP ; Package : TBNL ; Base : 10 -*-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
common http return codes
see <-lisp.net/project/hyperdoc/>
and <> | $ Header : /usr / local / cvsrep / tbnl / specials.lisp , v 1.92 2006/09/30 13:20:25 edi Exp $
Copyright ( c ) 2004 - 2006 , Dr. . All rights reserved .
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
(in-package #:tbnl)
(eval-when (:compile-toplevel :execute :load-toplevel)
(defmacro defvar-unbound (name &optional (doc-string ""))
"Convenience macro to declare unbound special variables with a
documentation string."
`(progn
(defvar ,name)
(setf (documentation ',name 'variable) ,doc-string)))
(defmacro defconstant* (name value &optional doc)
"Make sure VALUE is evaluated only once \(to appease SBCL)."
`(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
,@(when doc (list doc)))))
(defconstant +http-continue+ 100)
(defconstant +http-switching-protocols+ 101)
(defconstant +http-ok+ 200)
(defconstant +http-created+ 201)
(defconstant +http-accepted+ 202)
(defconstant +http-non-authoritative-information+ 203)
(defconstant +http-no-content+ 204)
(defconstant +http-reset-content+ 205)
(defconstant +http-partial-content+ 206)
(defconstant +http-multiple-choices+ 300)
(defconstant +http-moved-permanently+ 301)
(defconstant +http-moved-temporarily+ 302)
(defconstant +http-see-other+ 303)
(defconstant +http-not-modified+ 304)
(defconstant +http-use-proxy+ 305)
(defconstant +http-temporary-redirect+ 307)
(defconstant +http-bad-request+ 400)
(defconstant +http-authorization-required+ 401)
(defconstant +http-payment-required+ 402)
(defconstant +http-forbidden+ 403)
(defconstant +http-not-found+ 404)
(defconstant +http-method-not-allowed+ 405)
(defconstant +http-not-acceptable+ 406)
(defconstant +http-proxy-authentication-required+ 407)
(defconstant +http-request-time-out+ 408)
(defconstant +http-conflict+ 409)
(defconstant +http-gone+ 410)
(defconstant +http-length-required+ 411)
(defconstant +http-precondition-failed+ 412)
(defconstant +http-request-entity-too-large+ 413)
(defconstant +http-request-uri-too-large+ 414)
(defconstant +http-unsupported-media-type+ 415)
(defconstant +http-requested-range-not-satisfiable+ 416)
(defconstant +http-expectation-failed+ 417)
(defconstant +http-internal-server-error+ 500)
(defconstant +http-not-implemented+ 501)
(defconstant +http-bad-gateway+ 502)
(defconstant +http-service-unavailable+ 503)
(defconstant +http-gateway-time-out+ 504)
(defconstant +http-version-not-supported+ 505)
(defconstant* +day-names+
#("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun")
"The three-character names of the seven days of the week - needed
for cookie date format.")
(defconstant* +month-names+
#("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")
"The three-character names of the twelve months - needed for cookie
date format.")
(defvar *session-cookie-name* "tbnl-session"
"The name of the cookie \(or the GET parameter) which is used to
store the session on the client side.")
(defvar *rewrite-for-session-urls* t
"Whether HTML pages should possibly be rewritten for cookie-less
session-management.")
(defvar *content-types-for-url-rewrite*
'("text/html" "application/xhtml+xml")
"The content types for which url-rewriting is OK. See
*REWRITE-FOR-SESSION-URLS*.")
(defparameter *the-random-state* (make-random-state t)
"A fresh random state.")
(defvar-unbound *session-secret*
"A random value that's used to encode the public session data.")
(defvar *tbnl-port* 3000
"The port TBNL is listening on.")
(defvar-unbound *tbnl-stream*
"The stream representing the socket TBNL is listening on.")
(defvar *close-tbnl-stream* nil
"Set this to T if you want to close the TBNL socket each time a
request has been handled.")
(defvar *tbnl-socket-usage-counter* 0
"The number of requests serviced with the current socket.")
(declaim (type fixnum *tbnl-socket-usage-counter*))
(defvar *headers-sent* nil
"Used internally to check whether the reply headers have
already been sent for this request.")
(defvar *file-upload-hook* nil
"If this is not NIL, it should be a unary function which will
be called with a pathname for each file which is uploaded to
TBNL. The pathname denotes the temporary file to which the
uploaded file is written. The hook is called directly before the
file is created.")
(defvar *session-data* nil
"All sessions of all users currently using TBNL. An alist where the
car is the session's ID and the cdr is the SESSION object itself.")
(defvar *session-max-time* #.(* 30 60)
"The default time \(in seconds) after which a session times out.")
(declaim (type fixnum *session-max-time*))
(defvar *session-gc-frequency* 50
"A session GC \(see function SESSION-GC) will happen every
*SESSION-GC-FREQUENCY* requests \(counting only requests which use a
session).")
(declaim (type fixnum *session-gc-frequency*))
(defvar *use-user-agent-for-sessions* t
"Whether the 'User-Agent' header should be encoded into the session
string. If this value is true a session will cease to be accessible if
the client sends a different 'User-Agent' header.")
(defvar *use-remote-addr-for-sessions* nil
"Whether the client's remote IP \(as returned by REAL-REMOTE-ADDR)
should be encoded into the session string. If this value is true a
session will cease to be accessible if the client's remote IP changes.
This might for example be an issue if the client uses a proxy server
which doesn't send correct 'X_FORWARDED_FOR' headers.")
(defvar *default-content-type* "text/html; charset=iso-8859-1"
"The default content-type header which is returned to the client.")
(defvar *show-lisp-errors-p* nil
"Whether Lisp errors should be shown in HTML output.")
(defvar *show-lisp-backtraces-p* nil
"Whether Lisp backtraces should be shown in HTML output when an
error occurs. Will only have effect of *SHOW-LISP-ERRORS-P* is
also true.")
(defvar *catch-errors-p* t
"Whether TBNL should catch and log errors \(or rather invoke
the debugger).")
(defvar *log-lisp-errors-p* t
"Whether Lisp errors should be logged.")
(defvar *lisp-errors-log-level* :error
"Log level for Lisp errors.")
(defvar *log-lisp-warnings-p* t
"Whether Lisp warnings should be logged.")
(defvar *lisp-warnings-log-level* :warning
"Log level for Lisp warnings.")
(defvar *log-lisp-backtraces-p* nil
"Whether Lisp backtraces should be logged when an error
occurs. Will only have effect of *LOG-LISP-ERRORS-P* or
*LOG-LISP-BACKTRACES* are also true.")
(defvar *use-apache-log* #+:araneida nil #-:araneida t
"Whether log messages should be sent as headers \(assuming that
mod_lisp hands them over to Apache).")
(defvar *show-access-log-messages* t
"Whether routine messages about each request should be logged. This
will only be done if *USE-APACHE-LOG* is NIL.")
(defvar *log-file*
(load-time-value
(let ((tmp-dir
#+:allegro (system:temporary-directory)
#+:lispworks (pathname (or (lw:environment-variable "TEMP")
(lw:environment-variable "TMP")
#+:win32 "C:/"
#-:win32 "/tmp/"))
#-(or :allegro :lispworks) #p"/tmp/"))
(merge-pathnames "tbnl.log" tmp-dir)))
"The log file to use if *USE-APACHE-LOG* is false.")
(defvar *log-file-stream* nil
"The stream corresponding to the log file.")
(defvar *log-file-lock*
#-:lispworks
(kmrcl::make-lock "log-file-lock")
#+:lispworks
(mp:make-lock :name "log-file-lock")
"A lock to prevent two threads from writing to the log file at same
time.")
(defvar-unbound *command*
"The current request as read from *TBNL-STREAM*, converted into an
alist.")
(defvar-unbound *error*
"The last error or warning handled by TBNL.")
(defvar-unbound *session*
"The current SESSION object.")
(defvar-unbound *request*
"The current REQUEST object.")
(defvar-unbound *reply*
"The current REPLY object.")
(defvar-unbound *body*
"The body which was sent to the front-end or to the browser.")
(defvar-unbound *backtrace*
"The backtrace \(as a string) of the last error.")
(defvar *log-prefix* t
"The prefix which is printed in front of Apache log messages. This
should be a string or T \(for \"TBNL\", the default) or NIL \(meaning
no prefix).")
(defvar-unbound *listener*
"The KMRCL:LISTENER object which currently listens on *TBNL-PORT*")
(defvar *debug-mode* nil
"Whether we're in debug mode.")
(defconstant* +implementation-link+
#+:cmu "/"
#+:sbcl "/"
#+:clisp "/"
#+:allegro "/"
#+:lispworks "/"
#+:scl "/"
#+:openmcl "/"
#+:digitool "/"
#+:cormanlisp "/"
#+:ecl "/"
#+:gcl "")
(defvar *dispatch-table* (list 'default-dispatcher)
"A list of dispatch functions - see function PROCESS-REQUEST.")
(defvar *default-handler* 'default-handler
"The name of the function which is always returned by DEFAULT-DISPATCHER.")
(defvar *easy-handler-alist* nil)
(defvar *http-error-handler* nil
"Contains NIL \(the default) or a function of one argument which is
called if the content handler has set a return code other than
+HTTP-OK+ or +HTTP-NOT-MODIFIED+.")
(defvar *default-log-level* nil
"The default log level for LOG-MESSAGE*")
(defvar *session-data-lock*
#-:lispworks
(kmrcl::make-lock "session-data-lock")
#+:lispworks
(mp:make-lock :name "session-data-lock")
"A lock to prevent two threads from modifying *SESSION-DATA* at the
same time.")
(defvar *session-removal-hook* (constantly nil)
"A function of one argument \(a session object) which is called
whenever a session is garbage-collected.")
(defvar *tmp-directory*
#+(or :win32 :mswindows) "c:\\tbnl-temp\\"
#-(or :win32 :mswindows) "/tmp/tbnl/"
"Directory for temporary files created by MAKE-TMP-FILE-NAME.")
(defvar *tmp-files* nil
"A list of temporary files created while a request was handled.")
(defvar *use-modlisp-headers* nil
"If this variable is true then outgoing headers are written in a
format mod_lisp can understand, otherwise they're written like plain
HTTP headers.")
(defconstant +latin-1+
#+:allegro :latin1
#+:lispworks :latin-1
#+:sb-unicode :latin-1
#-(or :allegro :lispworks :sb-unicode) nil)
(defconstant +utf-8+
#+:allegro :utf8
#+:lispworks :utf-8
#+:sb-unicode :utf-8
#-(or :allegro :lispworks :sb-unicode) nil)
(defvar *tbnl-default-external-format* +latin-1+)
(defconstant +buffer-length+ 8192
"Length of buffers used for internal purposes.")
(eval-when (:compile-toplevel :load-toplevel :execute)
#+(or (and :allegro :allegro-version>= (version>= 6 0))
:sb-unicode
:lispworks4.3
:lispworks4.4
:lispworks5.0)
(pushnew :tbnl-bivalent-streams *features*))
#+:sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (find-symbol "*DEBUG-PRINT-VARIABLE-ALIST*" :sb-debug)
(pushnew :tbnl-sbcl-debug-print-variable-alist *features*)))
#+:lispworks
(defvar *hunchentoot-p* t
"Whether we are in 'Hunchentoot mode' or just serving as
infrastructure for TBNL.")
(pushnew :tbnl *features*)
stuff for Nikodemus Siivola 's HYPERDOC
(defvar *hyperdoc-base-uri* "/")
(let ((exported-symbols-alist
(loop for symbol being the external-symbols of :tbnl
collect (cons symbol
(concatenate 'string
"#"
(string-downcase symbol))))))
(defun hyperdoc-lookup (symbol type)
(declare (ignore type))
(cdr (assoc symbol
exported-symbols-alist
:test #'eq))))
|
ea1fca4699d1f066c0a46f4e6612241a42aa7ad218cc111bc92bed273a020832 | ryepup/cl-opencv | imgproc.lisp | ;;;; -*- mode: lisp; indent-tabs: nil -*-
;;;; imgproc.lisp
OpenCV bindings for SBCL
;;;; Image processing
(in-package :cl-opencv)
;;; Histograms
;;; Image Filtering
(cffi:defctype ipl-conv-kernel :pointer)
TODO test cvCopyMakeBorder
void cvCopyMakeBorder(const CvArr * src , CvArr * dst , ,
int bordertype , CvScalar value = cvScalarAll(0 ) )
(defanonenum
+ipl-border-constant+
+ipl-border-replicate+)
(cffi:defcfun ("cvCopyMakeBorder_glue" %copy-make-border) :void
(src cv-array)
(dest cv-array)
(offset :int64)
(border-type :int)
(s1 :double)
(s2 :double)
(s3 :double)
(s4 :double))
(defun copy-make-border (src dest offset border-type
&optional (value (make-cv-scalar)))
(apply #'%copy-make-border src dest offset border-type value))
;; IplConvKernel*
;; cvCreateStructuringElementEx(int cols, int rows, int anchorX, int anchorY,
;; int shape, int* values=NULL)
(defanonenum
+cv-shape-rect+
+cv-shape-cross+
+cv-shape-ellipse+
(+cv-shape-custom+ 100))
(cffi:defcfun ("cvCreateStructuringElementEx" %create-structuring-element-ex) :void
(cols :int)
(rows :int)
(anchor-x :int)
(anchor-y :int)
(shape :int)
(values :pointer))
TODO handle array of values in create - structuring - element - ex
(defun create-structuring-element-ex (cols rows anchor-x anchor-y shape
&optional (values (null-pointer)))
"Creates and fills an IplConvKernel structure. The structure will be
of dimensions COLSxROWS with the anchor at (ANCHOR-X, ANCHOR-Y) with
SHAPE filled with VALUES."
(%create-structuring-element-ex cols rows anchor-x anchor-y shape values))
;; void cvDilate(const CvArr* src, CvArr* dst, IplConvKernel* element = NULL,
int iterations = 1 )
(cffi:defcfun ("cvDilate" %dilate) :void
(src cv-array)
(dest cv-array)
(element ipl-conv-kernel)
(iterations :int))
(defun dilate (src dest &optional (element (null-pointer)) (iterations 1))
(%dilate src dest element iterations))
;; void cvErode(const CvArr* src, CvArr* dst, IplConvKernel* element=NULL,
;; int iterations=1)
(cffi:defcfun ("cvErode" %erode) :void
(src cv-array)
(dest cv-array)
(element ipl-conv-kernel)
(iterations :int))
(defun erode (src dest &optional (element (null-pointer)) (iterations 1))
(%erode src dest element iterations))
;; void cvLaplace(const CvArr* src, CvArr* dst, int apertureSize=3)
(cffi:defcfun ("cvLaplace" %laplace) :void
(src cv-array)
(dest cv-array)
(aperture-size :int))
(defun laplace (src dest &optional (aperture-size 3))
(%laplace src dest aperture-size))
void cvPyrDown(const CvArr * src , CvArr * dst , int filter = )
(defanonenum
(+gaussian-5x5+ 7))
(cffi:defcfun ("cvPyrDown" %pyr-down) :void
(src cv-array)
(dest cv-array)
(filter :int))
(defun pyr-down (src dest &optional (filter +gaussian-5x5+))
"Perform downsampling step of the Gaussian pyramid decomposition on
the image SRC and store it in DEST. Use the Gaussian filter type
FILTER for the convolution."
(%pyr-down src dest filter))
;; void cvReleaseStructuringElement(IplConvKernel** element)
(cffi:defcfun ("cvReleaseStructuringElement" %release-structuring-element) :void
(element-ptr :pointer))
(defun release-structuring-element (element)
(cffi:with-foreign-object (element-ptr :pointer)
(setf (cffi:mem-ref element-ptr :pointer) element)
(%release-structuring-element element-ptr)))
;;; Geometric Image Transformations
2
;;; Miscellaneous Image Transformations
void cvAdaptiveThreshold(const CvArr * src , CvArr * dst , double maxValue ,
int adaptive_method ,
int thresholdType = CV_THRESH_BINARY , int blockSize=3 ,
;; double param1=5)
;; Enumeration of threshold types for cvThreshold, cvAdaptiveThreshold
(defanonenum
+thresh-binary+
+thresh-binary-inv+
+thresh-trunc+
+thresh-tozero+
+thresh-tozero-inv+)
;; Adaptive threshold types
(defanonenum
+adaptive-thresh-mean-c+
+adaptive-thresh-gaussian-c+)
(cffi:defcfun ("cvAdaptiveThreshold" %adaptive-threshold) :void
(src cv-array) ; source image
(dest cv-array) ; destination image
(max-value :double) ; maximum value: binary and inverse binary
(adaptive-method :int) ; adaptive thresholding algorithm
(threshold-type :int) ; binary or inverse binary thresholding
(block-size :int) ; pixel neighborhood size for thresholding
(param-1 :double)) ; method-dependent parameter
(defun adaptive-threshold (src dest max-value &optional
(adaptive-method +adaptive-thresh-mean-c+)
(threshold-type +thresh-binary+) (block-size 3)
(param-1 5))
(%adaptive-threshold src dest (coerce max-value 'double-float) adaptive-method
threshold-type block-size
(coerce param-1 'double-float)))
;; double cvThreshold(const CvArr* src, CvArr* dst, double threshold,
double maxValue , int thresholdType )
(cffi:defcfun ("cvThreshold" %threshold) :double
(src cv-array)
(dest cv-array)
(threshold :double)
(max-value :double)
(threshold-type :int))
(defun threshold (src dest threshold max-value threshold-type)
"Applies a fixed-level threshold to array elements. SRC is the
source array and DEST is the target array. THRESHOLD is the threshold
value and MAX-VALUE is the 'on' value for binary
thresholding. THRESHOLD-TYPE is the type of thresholding to be done."
(%threshold src dest (coerce threshold 'double-float)
(coerce max-value 'double-float) threshold-type))
;;; Structural Analysis and Shape Descriptors
Planar Subdivisions
;;; Motion Analysis and Object Tracking
;;; Feature Detection
;;; Object Detection
| null | https://raw.githubusercontent.com/ryepup/cl-opencv/571215d60e963f53aaa87f3a5ee90f94176ddb00/imgproc.lisp | lisp | -*- mode: lisp; indent-tabs: nil -*-
imgproc.lisp
Image processing
Histograms
Image Filtering
IplConvKernel*
cvCreateStructuringElementEx(int cols, int rows, int anchorX, int anchorY,
int shape, int* values=NULL)
void cvDilate(const CvArr* src, CvArr* dst, IplConvKernel* element = NULL,
void cvErode(const CvArr* src, CvArr* dst, IplConvKernel* element=NULL,
int iterations=1)
void cvLaplace(const CvArr* src, CvArr* dst, int apertureSize=3)
void cvReleaseStructuringElement(IplConvKernel** element)
Geometric Image Transformations
Miscellaneous Image Transformations
double param1=5)
Enumeration of threshold types for cvThreshold, cvAdaptiveThreshold
Adaptive threshold types
source image
destination image
maximum value: binary and inverse binary
adaptive thresholding algorithm
binary or inverse binary thresholding
pixel neighborhood size for thresholding
method-dependent parameter
double cvThreshold(const CvArr* src, CvArr* dst, double threshold,
Structural Analysis and Shape Descriptors
Motion Analysis and Object Tracking
Feature Detection
Object Detection | OpenCV bindings for SBCL
(in-package :cl-opencv)
(cffi:defctype ipl-conv-kernel :pointer)
TODO test cvCopyMakeBorder
void cvCopyMakeBorder(const CvArr * src , CvArr * dst , ,
int bordertype , CvScalar value = cvScalarAll(0 ) )
(defanonenum
+ipl-border-constant+
+ipl-border-replicate+)
(cffi:defcfun ("cvCopyMakeBorder_glue" %copy-make-border) :void
(src cv-array)
(dest cv-array)
(offset :int64)
(border-type :int)
(s1 :double)
(s2 :double)
(s3 :double)
(s4 :double))
(defun copy-make-border (src dest offset border-type
&optional (value (make-cv-scalar)))
(apply #'%copy-make-border src dest offset border-type value))
(defanonenum
+cv-shape-rect+
+cv-shape-cross+
+cv-shape-ellipse+
(+cv-shape-custom+ 100))
(cffi:defcfun ("cvCreateStructuringElementEx" %create-structuring-element-ex) :void
(cols :int)
(rows :int)
(anchor-x :int)
(anchor-y :int)
(shape :int)
(values :pointer))
TODO handle array of values in create - structuring - element - ex
(defun create-structuring-element-ex (cols rows anchor-x anchor-y shape
&optional (values (null-pointer)))
"Creates and fills an IplConvKernel structure. The structure will be
of dimensions COLSxROWS with the anchor at (ANCHOR-X, ANCHOR-Y) with
SHAPE filled with VALUES."
(%create-structuring-element-ex cols rows anchor-x anchor-y shape values))
int iterations = 1 )
(cffi:defcfun ("cvDilate" %dilate) :void
(src cv-array)
(dest cv-array)
(element ipl-conv-kernel)
(iterations :int))
(defun dilate (src dest &optional (element (null-pointer)) (iterations 1))
(%dilate src dest element iterations))
(cffi:defcfun ("cvErode" %erode) :void
(src cv-array)
(dest cv-array)
(element ipl-conv-kernel)
(iterations :int))
(defun erode (src dest &optional (element (null-pointer)) (iterations 1))
(%erode src dest element iterations))
(cffi:defcfun ("cvLaplace" %laplace) :void
(src cv-array)
(dest cv-array)
(aperture-size :int))
(defun laplace (src dest &optional (aperture-size 3))
(%laplace src dest aperture-size))
void cvPyrDown(const CvArr * src , CvArr * dst , int filter = )
(defanonenum
(+gaussian-5x5+ 7))
(cffi:defcfun ("cvPyrDown" %pyr-down) :void
(src cv-array)
(dest cv-array)
(filter :int))
(defun pyr-down (src dest &optional (filter +gaussian-5x5+))
"Perform downsampling step of the Gaussian pyramid decomposition on
the image SRC and store it in DEST. Use the Gaussian filter type
FILTER for the convolution."
(%pyr-down src dest filter))
(cffi:defcfun ("cvReleaseStructuringElement" %release-structuring-element) :void
(element-ptr :pointer))
(defun release-structuring-element (element)
(cffi:with-foreign-object (element-ptr :pointer)
(setf (cffi:mem-ref element-ptr :pointer) element)
(%release-structuring-element element-ptr)))
2
void cvAdaptiveThreshold(const CvArr * src , CvArr * dst , double maxValue ,
int adaptive_method ,
int thresholdType = CV_THRESH_BINARY , int blockSize=3 ,
(defanonenum
+thresh-binary+
+thresh-binary-inv+
+thresh-trunc+
+thresh-tozero+
+thresh-tozero-inv+)
(defanonenum
+adaptive-thresh-mean-c+
+adaptive-thresh-gaussian-c+)
(cffi:defcfun ("cvAdaptiveThreshold" %adaptive-threshold) :void
(defun adaptive-threshold (src dest max-value &optional
(adaptive-method +adaptive-thresh-mean-c+)
(threshold-type +thresh-binary+) (block-size 3)
(param-1 5))
(%adaptive-threshold src dest (coerce max-value 'double-float) adaptive-method
threshold-type block-size
(coerce param-1 'double-float)))
double maxValue , int thresholdType )
(cffi:defcfun ("cvThreshold" %threshold) :double
(src cv-array)
(dest cv-array)
(threshold :double)
(max-value :double)
(threshold-type :int))
(defun threshold (src dest threshold max-value threshold-type)
"Applies a fixed-level threshold to array elements. SRC is the
source array and DEST is the target array. THRESHOLD is the threshold
value and MAX-VALUE is the 'on' value for binary
thresholding. THRESHOLD-TYPE is the type of thresholding to be done."
(%threshold src dest (coerce threshold 'double-float)
(coerce max-value 'double-float) threshold-type))
Planar Subdivisions
|
6ed0b6380e1923ad3b5d56cf09de14d2493a315a8807e5ec6c09ff324524b84a | cl-axon/shop2 | problem-converter.lisp | (in-package :common-lisp-user)
(defparameter *debug-mode* t)
(defun convert-problems (L)
(dolist (fn L)
(problem-converter fn (concatenate 'string fn ".lisp") fn)
)
)
(defun write-SHOP2-problem (shop2-problem-filename
problem-name
domain-name
objects-list
init-list
goal-list
metric-list)
(with-open-file (outfile shop2-problem-filename :direction :output
:if-exists :supersede)
(format outfile "(in-package :shop2-user)~%")
(format outfile "(defproblem ~A ~A~%" problem-name domain-name)
(format outfile " (~%")
(when *debug-mode*
(format outfile " ;;;~%")
(format outfile " ;;; facts~%")
(format outfile " ;;;~%")
(let* (objects
previous
object-type)
(dolist (ss objects-list)
(cond ((and (not (eql ss '-))
(eql previous nil))
(cond ((eql objects nil)
(setf objects (list ss)))
((not (eql objects nil))
(nconc objects (list ss)))))
((eql ss '-)
(setf previous t))
((and (not (eql ss '-))
(eql previous t))
(setf object-type ss)
(dolist (s objects)
(format outfile " (~A ~A)~%" object-type s))
(setf objects nil)
(setf previous nil)))
)))
; (do* ((ol objects-list (cdddr ol))
( obj ( first ol ) ( first ol ) )
( cls ( third ol ) ( third ol ) ) )
; ((null ol))
( format outfile " ( ~A ~A)~% " cls obj )
; ))
(format outfile " ;;;~%")
(format outfile " ;;; initial states~%")
(format outfile " ;;;~%")
(dolist (s init-list)
(if (eql (first s) '=)
(format outfile " ~A~%" (append (second s) (list (third s))))
(format outfile " ~A~%" s)
)
)
(format outfile " )~%")
(format outfile " ;;;~%")
(format outfile " ;;; goals~%")
(format outfile " ;;;~%")
(format outfile " ((achieve-goals (~%")
(dolist (s (cdr goal-list))
(format outfile " ~A~%" s))
(format outfile " )))~%")
(format outfile ")~%")
)
)
(defun problem-converter (pddl-problem-filename shop2-problem-filename problem-name)
(with-open-file (infile pddl-problem-filename :direction :input)
(let* ((pddl-problem (read infile))
; problem-name
domain-name
objects-list
init-list
goal-list
metric-list)
;;;
read the PDDL problem
;;;
(dolist (s pddl-problem)
( when ( and ( listp s ) ( eql ( first s ) ' problem ) )
( setf problem - name ( second s ) ) )
(when (and (listp s) (eql (first s) :domain))
(setf domain-name (second s)))
(when (and (listp s) (eql (first s) :objects))
(setf objects-list (cdr s)))
(when (and (listp s) (eql (first s) :init))
(setf init-list (cdr s)))
(when (and (listp s) (eql (first s) :goal))
(setf goal-list (second s)))
(when (and (listp s) (eql (first s) :metric))
(setf metric-list (second s)))
)
(write-SHOP2-problem shop2-problem-filename
problem-name
domain-name
objects-list
init-list
goal-list
metric-list)
)
)
)
(convert-problems '(
"pfile1"
"pfile2"
"pfile3"
"pfile4"
"pfile5"
"pfile6"
"pfile7"
"pfile8"
"pfile9"
"pfile10"
"pfile11"
"pfile12"
"pfile13"
"pfile14"
"pfile15"
"pfile16"
"pfile17"
"pfile18"
"pfile19"
"pfile20"
"pfile21"
"pfile22"))
| null | https://raw.githubusercontent.com/cl-axon/shop2/9136e51f7845b46232cc17ca3618f515ddcf2787/examples/IPC-2002/Depots/SimpleTime/easy_probs/problem-converter.lisp | lisp | (do* ((ol objects-list (cdddr ol))
((null ol))
))
problem-name
| (in-package :common-lisp-user)
(defparameter *debug-mode* t)
(defun convert-problems (L)
(dolist (fn L)
(problem-converter fn (concatenate 'string fn ".lisp") fn)
)
)
(defun write-SHOP2-problem (shop2-problem-filename
problem-name
domain-name
objects-list
init-list
goal-list
metric-list)
(with-open-file (outfile shop2-problem-filename :direction :output
:if-exists :supersede)
(format outfile "(in-package :shop2-user)~%")
(format outfile "(defproblem ~A ~A~%" problem-name domain-name)
(format outfile " (~%")
(when *debug-mode*
(format outfile " ;;;~%")
(format outfile " ;;; facts~%")
(format outfile " ;;;~%")
(let* (objects
previous
object-type)
(dolist (ss objects-list)
(cond ((and (not (eql ss '-))
(eql previous nil))
(cond ((eql objects nil)
(setf objects (list ss)))
((not (eql objects nil))
(nconc objects (list ss)))))
((eql ss '-)
(setf previous t))
((and (not (eql ss '-))
(eql previous t))
(setf object-type ss)
(dolist (s objects)
(format outfile " (~A ~A)~%" object-type s))
(setf objects nil)
(setf previous nil)))
)))
( obj ( first ol ) ( first ol ) )
( cls ( third ol ) ( third ol ) ) )
( format outfile " ( ~A ~A)~% " cls obj )
(format outfile " ;;;~%")
(format outfile " ;;; initial states~%")
(format outfile " ;;;~%")
(dolist (s init-list)
(if (eql (first s) '=)
(format outfile " ~A~%" (append (second s) (list (third s))))
(format outfile " ~A~%" s)
)
)
(format outfile " )~%")
(format outfile " ;;;~%")
(format outfile " ;;; goals~%")
(format outfile " ;;;~%")
(format outfile " ((achieve-goals (~%")
(dolist (s (cdr goal-list))
(format outfile " ~A~%" s))
(format outfile " )))~%")
(format outfile ")~%")
)
)
(defun problem-converter (pddl-problem-filename shop2-problem-filename problem-name)
(with-open-file (infile pddl-problem-filename :direction :input)
(let* ((pddl-problem (read infile))
domain-name
objects-list
init-list
goal-list
metric-list)
read the PDDL problem
(dolist (s pddl-problem)
( when ( and ( listp s ) ( eql ( first s ) ' problem ) )
( setf problem - name ( second s ) ) )
(when (and (listp s) (eql (first s) :domain))
(setf domain-name (second s)))
(when (and (listp s) (eql (first s) :objects))
(setf objects-list (cdr s)))
(when (and (listp s) (eql (first s) :init))
(setf init-list (cdr s)))
(when (and (listp s) (eql (first s) :goal))
(setf goal-list (second s)))
(when (and (listp s) (eql (first s) :metric))
(setf metric-list (second s)))
)
(write-SHOP2-problem shop2-problem-filename
problem-name
domain-name
objects-list
init-list
goal-list
metric-list)
)
)
)
(convert-problems '(
"pfile1"
"pfile2"
"pfile3"
"pfile4"
"pfile5"
"pfile6"
"pfile7"
"pfile8"
"pfile9"
"pfile10"
"pfile11"
"pfile12"
"pfile13"
"pfile14"
"pfile15"
"pfile16"
"pfile17"
"pfile18"
"pfile19"
"pfile20"
"pfile21"
"pfile22"))
|
7328f775cdd529402cc3a3868ab84793dbf8623522e99bc3c7dd579c8c805370 | ghc/packages-base | IO.hs | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude #
-----------------------------------------------------------------------------
-- |
-- Module : System.IO
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : stable
-- Portability : portable
--
The standard IO library .
--
-----------------------------------------------------------------------------
module System.IO (
* The IO monad
IO,
fixIO,
-- * Files and handles
FilePath,
Handle, -- abstract, instance of: Eq, Show.
| GHC note : a ' Handle ' will be automatically closed when the garbage
-- collector detects that it has become unreferenced by the program.
-- However, relying on this behaviour is not generally recommended:
-- the garbage collector is unpredictable. If possible, use
an explicit ' ' to close ' Handle 's when they are no longer
required . GHC does not currently attempt to free up file
-- descriptors when they have run out, it is your responsibility to
-- ensure that this doesn't happen.
-- ** Standard handles
-- | Three handles are allocated during program initialisation,
-- and are initially open.
stdin, stdout, stderr,
-- * Opening and closing files
-- ** Opening files
withFile,
openFile,
IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
-- ** Closing files
hClose,
-- ** Special cases
| These functions are also exported by the " Prelude " .
readFile,
writeFile,
appendFile,
-- ** File locking
-- $locking
-- * Operations on handles
-- ** Determining and changing the size of a file
hFileSize,
hSetFileSize,
-- ** Detecting the end of input
hIsEOF,
isEOF,
-- ** Buffering operations
BufferMode(NoBuffering,LineBuffering,BlockBuffering),
hSetBuffering,
hGetBuffering,
hFlush,
-- ** Repositioning handles
hGetPosn,
hSetPosn,
HandlePosn, -- abstract, instance of: Eq, Show.
hSeek,
SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
hTell,
-- ** Handle properties
hIsOpen, hIsClosed,
hIsReadable, hIsWritable,
hIsSeekable,
* * Terminal operations ( not portable : GHC only )
hIsTerminalDevice,
hSetEcho,
hGetEcho,
* * Showing handle state ( not portable : GHC only )
hShow,
-- * Text input and output
-- ** Text input
hWaitForInput,
hReady,
hGetChar,
hGetLine,
hLookAhead,
hGetContents,
-- ** Text output
hPutChar,
hPutStr,
hPutStrLn,
hPrint,
-- ** Special cases for standard input and output
| These functions are also exported by the " Prelude " .
interact,
putChar,
putStr,
putStrLn,
print,
getChar,
getLine,
getContents,
readIO,
readLn,
-- * Binary input and output
withBinaryFile,
openBinaryFile,
hSetBinaryMode,
hPutBuf,
hGetBuf,
hGetBufSome,
hPutBufNonBlocking,
hGetBufNonBlocking,
-- * Temporary files
openTempFile,
openBinaryTempFile,
openTempFileWithDefaultPermissions,
openBinaryTempFileWithDefaultPermissions,
-- * Unicode encoding\/decoding
-- | A text-mode 'Handle' has an associated 'TextEncoding', which
is used to decode bytes into Unicode characters when reading ,
and encode Unicode characters into bytes when writing .
--
-- The default 'TextEncoding' is the same as the default encoding
-- on your system, which is also available as 'localeEncoding'.
( GHC note : on Windows , we currently do not support double - byte
encodings ; if the console\ 's code page is unsupported , then
-- 'localeEncoding' will be 'latin1'.)
--
-- Encoding and decoding errors are always detected and reported,
except during lazy I / O ( ' hGetContents ' , ' ' , and
-- 'readFile'), where a decoding error merely results in
-- termination of the character stream, as with other I/O errors.
hSetEncoding,
hGetEncoding,
-- ** Unicode encodings
TextEncoding,
latin1,
utf8, utf8_bom,
utf16, utf16le, utf16be,
utf32, utf32le, utf32be,
localeEncoding,
char8,
mkTextEncoding,
-- * Newline conversion
| In Haskell , a newline is always represented by the character
-- '\n'. However, in files and external character streams, a
-- newline may be represented by another character sequence, such
-- as '\r\n'.
--
A text - mode ' Handle ' has an associated ' NewlineMode ' that
-- specifies how to transate newline characters. The
' NewlineMode ' specifies the input and output translation
-- separately, so that for instance you can translate '\r\n'
-- to '\n' on input, but leave newlines as '\n' on output.
--
The default ' NewlineMode ' for a ' Handle ' is
-- 'nativeNewlineMode', which does no translation on Unix systems,
but translates ' \r\n ' to ' \n ' and back on Windows .
--
-- Binary-mode 'Handle's do no newline translation at all.
--
hSetNewlineMode,
Newline(..), nativeNewline,
NewlineMode(..),
noNewlineTranslation, universalNewlineMode, nativeNewlineMode,
) where
import Control.Exception.Base
import Data.Bits
import Data.List
import Data.Maybe
import Foreign.C.Error
#ifdef mingw32_HOST_OS
import Foreign.C.String
#endif
import Foreign.C.Types
import System.Posix.Internals
import System.Posix.Types
import GHC.Base
import GHC.IO hiding ( bracket, onException )
import GHC.IO.IOMode
import GHC.IO.Handle.FD
import qualified GHC.IO.FD as FD
import GHC.IO.Handle
import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn )
import GHC.IO.Exception ( userError )
import GHC.IO.Encoding
import GHC.Num
import Text.Read
import GHC.Show
import GHC.MVar
-- -----------------------------------------------------------------------------
-- Standard IO
-- | Write a character to the standard output device
-- (same as 'hPutChar' 'stdout').
putChar :: Char -> IO ()
putChar c = hPutChar stdout c
-- | Write a string to the standard output device
-- (same as 'hPutStr' 'stdout').
putStr :: String -> IO ()
putStr s = hPutStr stdout s
-- | The same as 'putStr', but adds a newline character.
putStrLn :: String -> IO ()
putStrLn s = hPutStrLn stdout s
-- | The 'print' function outputs a value of any printable type to the
-- standard output device.
-- Printable types are those that are instances of class 'Show'; 'print'
-- converts values to strings for output using the 'show' operation and
-- adds a newline.
--
For example , a program to print the first 20 integers and their
powers of 2 could be written as :
--
> main = print ( [ ( n , 2^n ) | n < - [ 0 .. 19 ] ] )
print :: Show a => a -> IO ()
print x = putStrLn (show x)
-- | Read a character from the standard input device
( same as ' hGetChar ' ' stdin ' ) .
getChar :: IO Char
getChar = hGetChar stdin
-- | Read a line from the standard input device
( same as ' hGetLine ' ' stdin ' ) .
getLine :: IO String
getLine = hGetLine stdin
-- | The 'getContents' operation returns all user input as a single string,
-- which is read lazily as it is needed
( same as ' hGetContents ' ' stdin ' ) .
getContents :: IO String
getContents = hGetContents stdin
-- | The 'interact' function takes a function of type @String->String@
-- as its argument. The entire input from the standard input device is
-- passed to this function as its argument, and the resulting string is
-- output on the standard output device.
interact :: (String -> String) -> IO ()
interact f = do s <- getContents
putStr (f s)
-- | The 'readFile' function reads a file and
-- returns the contents of the file as a string.
The file is read lazily , on demand , as with ' ' .
readFile :: FilePath -> IO String
readFile name = openFile name ReadMode >>= hGetContents
-- | The computation 'writeFile' @file str@ function writes the string @str@,
-- to the file @file@.
writeFile :: FilePath -> String -> IO ()
writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
-- | The computation 'appendFile' @file str@ function appends the string @str@,
-- to the file @file@.
--
-- Note that 'writeFile' and 'appendFile' write a literal string
-- to a file. To write a value of any printable type, as with 'print',
use the ' show ' function to convert the value to a string first .
--
> main = appendFile " squares " ( show [ ( x , x*x ) | x < - [ 0,0.1 .. 2 ] ] )
appendFile :: FilePath -> String -> IO ()
appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
-- | The 'readLn' function combines 'getLine' and 'readIO'.
readLn :: Read a => IO a
readLn = do l <- getLine
r <- readIO l
return r
-- | The 'readIO' function is similar to 'read' except that it signals
-- parse failure to the 'IO' monad instead of terminating the program.
readIO :: Read a => String -> IO a
readIO s = case (do { (x,t) <- reads s ;
("","") <- lex t ;
return x }) of
[x] -> return x
[] -> ioError (userError "Prelude.readIO: no parse")
_ -> ioError (userError "Prelude.readIO: ambiguous parse")
| The Unicode encoding of the current locale
--
-- This is the initial locale encoding: if it has been subsequently changed by
-- 'GHC.IO.Encoding.setLocaleEncoding' this value will not reflect that change.
localeEncoding :: TextEncoding
localeEncoding = initLocaleEncoding
| Computation ' hReady ' @hdl@ indicates whether at least one item is
-- available for input from handle @hdl@.
--
-- This operation may fail with:
--
-- * 'System.IO.Error.isEOFError' if the end of file has been reached.
hReady :: Handle -> IO Bool
hReady h = hWaitForInput h 0
-- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
given by the ' shows ' function to the file or channel managed by @hdl@
-- and appends a newline.
--
-- This operation may fail with:
--
* ' System . ' if the device is full ; or
--
-- * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
hPrint :: Show a => Handle -> a -> IO ()
hPrint hdl = hPutStrLn hdl . show
-- | @'withFile' name mode act@ opens a file using 'openFile' and passes
the resulting handle to the computation @act@. The handle will be
-- closed on exit from 'withFile', whether by normal termination or by
-- raising an exception. If closing the handle raises an exception, then
-- this exception will be raised by 'withFile' rather than any exception
-- raised by 'act'.
withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withFile name mode = bracket (openFile name mode) hClose
-- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
and passes the resulting handle to the computation @act@. The handle
-- will be closed on exit from 'withBinaryFile', whether by normal
-- termination or by raising an exception.
withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
-- ---------------------------------------------------------------------------
-- fixIO
fixIO :: (a -> IO a) -> IO a
fixIO k = do
m <- newEmptyMVar
ans <- unsafeInterleaveIO (takeMVar m)
result <- k ans
putMVar m result
return result
NOTE : we do our own explicit black holing here , because GHC 's lazy
blackholing is n't enough . In an infinite loop , GHC may run the IO
-- computation a few times before it notices the loop, which is wrong.
--
NOTE2 : the explicit black - holing with an IORef ran into trouble
with multiple threads ( see # 5421 ) , so now we use an MVar . I 'm
-- actually wondering whether we should use readMVar rather than
-- takeMVar, just in case it ends up being executed multiple times,
-- but even then it would have to be masked to protect against async
exceptions . Ugh . What we really need here is an IVar , or an
atomic readMVar , or even STM . All these seem like overkill .
--
-- See also System.IO.Unsafe.unsafeFixIO.
--
| The function creates a temporary file in ReadWrite mode .
-- The created file isn\'t deleted automatically, so you need to delete it manually.
--
-- The file is creates with permissions such that only the current
user can it .
--
-- With some exceptions (see below), the file will be created securely
-- in the sense that an attacker should not be able to cause
-- openTempFile to overwrite another file on the filesystem using your
-- credentials, by putting symbolic links (on Unix) in the place where
the temporary file is to be created . On Unix the @O_CREAT@ and
@O_EXCL@ flags are used to prevent this attack , but note that
@O_EXCL@ is sometimes not supported on NFS filesystems , so if you
-- rely on this behaviour it is best to use local filesystems only.
--
openTempFile :: FilePath -- ^ Directory in which to create the file
-> String -- ^ File name template. If the template is \"foo.ext\" then
-- the created file will be \"fooXXX.ext\" where XXX is some
-- random number.
-> IO (FilePath, Handle)
openTempFile tmp_dir template
= openTempFile' "openTempFile" tmp_dir template False 0o600
-- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
openBinaryTempFile tmp_dir template
= openTempFile' "openBinaryTempFile" tmp_dir template True 0o600
-- | Like 'openTempFile', but uses the default file permissions
openTempFileWithDefaultPermissions :: FilePath -> String
-> IO (FilePath, Handle)
openTempFileWithDefaultPermissions tmp_dir template
= openTempFile' "openBinaryTempFile" tmp_dir template False 0o666
-- | Like 'openBinaryTempFile', but uses the default file permissions
openBinaryTempFileWithDefaultPermissions :: FilePath -> String
-> IO (FilePath, Handle)
openBinaryTempFileWithDefaultPermissions tmp_dir template
= openTempFile' "openBinaryTempFile" tmp_dir template True 0o666
openTempFile' :: String -> FilePath -> String -> Bool -> CMode
-> IO (FilePath, Handle)
openTempFile' loc tmp_dir template binary mode = do
pid <- c_getpid
findTempName pid
where
-- We split off the last extension, so we can use .foo.ext files
-- for temporary files (hidden on Unix OSes). Unfortunately we're
-- below filepath in the hierarchy here.
(prefix,suffix) =
case break (== '.') $ reverse template of
First case : template contains no ' . 's . Just re - reverse it .
(rev_suffix, "") -> (reverse rev_suffix, "")
Second case : template contains at least one ' . ' . Strip the
-- dot from the prefix and prepend it to the suffix (if we don't
-- do this, the unique number will get added after the '.' and
-- thus be part of the extension, which is wrong.)
(rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
-- Otherwise, something is wrong, because (break (== '.')) should
-- always return a pair with either the empty string or a string
beginning with ' . ' as the second component .
_ -> error "bug in System.IO.openTempFile"
findTempName x = do
r <- openNewFile filepath binary mode
case r of
FileExists -> findTempName (x + 1)
OpenNewError errno -> ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
NewFileCreated fd -> do
(fD,fd_type) <- FD.mkFD fd ReadWriteMode Nothing{-no stat-}
False{-is_socket-}
is_nonblock
enc <- getLocaleEncoding
h <- mkHandleFromFD fD fd_type filepath ReadWriteMode False{-set non-block-} (Just enc)
return (filepath, h)
where
filename = prefix ++ show x ++ suffix
filepath = tmp_dir `combine` filename
XXX bits copied from System . FilePath , since that 's not available here
combine a b
| null b = a
| null a = b
| last a == pathSeparator = a ++ b
| otherwise = a ++ [pathSeparator] ++ b
data OpenNewFileResult
= NewFileCreated CInt
| FileExists
| OpenNewError Errno
openNewFile :: FilePath -> Bool -> CMode -> IO OpenNewFileResult
openNewFile filepath binary mode = do
let oflags1 = rw_flags .|. o_EXCL
binary_flags
| binary = o_BINARY
| otherwise = 0
oflags = oflags1 .|. binary_flags
fd <- withFilePath filepath $ \ f ->
c_open f oflags mode
if fd < 0
then do
errno <- getErrno
case errno of
_ | errno == eEXIST -> return FileExists
#ifdef mingw32_HOST_OS
If c_open throws EACCES on windows , it could mean that filepath is a
directory . In this case , we want to return FileExists so that the
-- enclosing openTempFile can try again instead of failing outright.
See bug # 4968 .
_ | errno == eACCES -> do
withCString filepath $ \path -> do
-- There is a race here: the directory might have been moved or
-- deleted between the c_open call and the next line, but there
-- doesn't seem to be any direct way to detect that the c_open call
-- failed because of an existing directory.
exists <- c_fileExists path
return $ if exists
then FileExists
else OpenNewError errno
#endif
_ -> return (OpenNewError errno)
else return (NewFileCreated fd)
#ifdef mingw32_HOST_OS
foreign import ccall "file_exists" c_fileExists :: CString -> IO Bool
#endif
-- XXX Should use filepath library
pathSeparator :: Char
#ifdef mingw32_HOST_OS
pathSeparator = '\\'
#else
pathSeparator = '/'
#endif
XXX Copied from GHC.Handle
std_flags, output_flags, rw_flags :: CInt
std_flags = o_NONBLOCK .|. o_NOCTTY
output_flags = std_flags .|. o_CREAT
rw_flags = output_flags .|. o_RDWR
-- $locking
-- Implementations should enforce as far as possible, at least locally to the
Haskell process , multiple - reader single - writer locking on files .
-- That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/. If any
-- open or semi-closed handle is managing a file for output, no new
-- handle can be allocated for that file. If any open or semi-closed
-- handle is managing a file for input, new handles can only be allocated
if they do not manage output . Whether two files are the same is
-- implementation-dependent, but they should normally be the same if they
-- have the same absolute path name and neither has been renamed, for
-- example.
--
-- /Warning/: the 'readFile' operation holds a semi-closed handle on
-- the file until the entire contents of the file have been consumed.
-- It follows that an attempt to write to a file (using 'writeFile', for
-- example) that was earlier opened by 'readFile' will usually result in
failure with ' System . IO.Error.isAlreadyInUseError ' .
| null | https://raw.githubusercontent.com/ghc/packages-base/52c0b09036c36f1ed928663abb2f295fd36a88bb/System/IO.hs | haskell | ---------------------------------------------------------------------------
|
Module : System.IO
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : stable
Portability : portable
---------------------------------------------------------------------------
* Files and handles
abstract, instance of: Eq, Show.
collector detects that it has become unreferenced by the program.
However, relying on this behaviour is not generally recommended:
the garbage collector is unpredictable. If possible, use
descriptors when they have run out, it is your responsibility to
ensure that this doesn't happen.
** Standard handles
| Three handles are allocated during program initialisation,
and are initially open.
* Opening and closing files
** Opening files
** Closing files
** Special cases
** File locking
$locking
* Operations on handles
** Determining and changing the size of a file
** Detecting the end of input
** Buffering operations
** Repositioning handles
abstract, instance of: Eq, Show.
** Handle properties
* Text input and output
** Text input
** Text output
** Special cases for standard input and output
* Binary input and output
* Temporary files
* Unicode encoding\/decoding
| A text-mode 'Handle' has an associated 'TextEncoding', which
The default 'TextEncoding' is the same as the default encoding
on your system, which is also available as 'localeEncoding'.
'localeEncoding' will be 'latin1'.)
Encoding and decoding errors are always detected and reported,
'readFile'), where a decoding error merely results in
termination of the character stream, as with other I/O errors.
** Unicode encodings
* Newline conversion
'\n'. However, in files and external character streams, a
newline may be represented by another character sequence, such
as '\r\n'.
specifies how to transate newline characters. The
separately, so that for instance you can translate '\r\n'
to '\n' on input, but leave newlines as '\n' on output.
'nativeNewlineMode', which does no translation on Unix systems,
Binary-mode 'Handle's do no newline translation at all.
-----------------------------------------------------------------------------
Standard IO
| Write a character to the standard output device
(same as 'hPutChar' 'stdout').
| Write a string to the standard output device
(same as 'hPutStr' 'stdout').
| The same as 'putStr', but adds a newline character.
| The 'print' function outputs a value of any printable type to the
standard output device.
Printable types are those that are instances of class 'Show'; 'print'
converts values to strings for output using the 'show' operation and
adds a newline.
| Read a character from the standard input device
| Read a line from the standard input device
| The 'getContents' operation returns all user input as a single string,
which is read lazily as it is needed
| The 'interact' function takes a function of type @String->String@
as its argument. The entire input from the standard input device is
passed to this function as its argument, and the resulting string is
output on the standard output device.
| The 'readFile' function reads a file and
returns the contents of the file as a string.
| The computation 'writeFile' @file str@ function writes the string @str@,
to the file @file@.
| The computation 'appendFile' @file str@ function appends the string @str@,
to the file @file@.
Note that 'writeFile' and 'appendFile' write a literal string
to a file. To write a value of any printable type, as with 'print',
| The 'readLn' function combines 'getLine' and 'readIO'.
| The 'readIO' function is similar to 'read' except that it signals
parse failure to the 'IO' monad instead of terminating the program.
This is the initial locale encoding: if it has been subsequently changed by
'GHC.IO.Encoding.setLocaleEncoding' this value will not reflect that change.
available for input from handle @hdl@.
This operation may fail with:
* 'System.IO.Error.isEOFError' if the end of file has been reached.
| Computation 'hPrint' @hdl t@ writes the string representation of @t@
and appends a newline.
This operation may fail with:
* 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
| @'withFile' name mode act@ opens a file using 'openFile' and passes
closed on exit from 'withFile', whether by normal termination or by
raising an exception. If closing the handle raises an exception, then
this exception will be raised by 'withFile' rather than any exception
raised by 'act'.
| @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
will be closed on exit from 'withBinaryFile', whether by normal
termination or by raising an exception.
---------------------------------------------------------------------------
fixIO
computation a few times before it notices the loop, which is wrong.
actually wondering whether we should use readMVar rather than
takeMVar, just in case it ends up being executed multiple times,
but even then it would have to be masked to protect against async
See also System.IO.Unsafe.unsafeFixIO.
The created file isn\'t deleted automatically, so you need to delete it manually.
The file is creates with permissions such that only the current
With some exceptions (see below), the file will be created securely
in the sense that an attacker should not be able to cause
openTempFile to overwrite another file on the filesystem using your
credentials, by putting symbolic links (on Unix) in the place where
rely on this behaviour it is best to use local filesystems only.
^ Directory in which to create the file
^ File name template. If the template is \"foo.ext\" then
the created file will be \"fooXXX.ext\" where XXX is some
random number.
| Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
| Like 'openTempFile', but uses the default file permissions
| Like 'openBinaryTempFile', but uses the default file permissions
We split off the last extension, so we can use .foo.ext files
for temporary files (hidden on Unix OSes). Unfortunately we're
below filepath in the hierarchy here.
dot from the prefix and prepend it to the suffix (if we don't
do this, the unique number will get added after the '.' and
thus be part of the extension, which is wrong.)
Otherwise, something is wrong, because (break (== '.')) should
always return a pair with either the empty string or a string
no stat
is_socket
set non-block
enclosing openTempFile can try again instead of failing outright.
There is a race here: the directory might have been moved or
deleted between the c_open call and the next line, but there
doesn't seem to be any direct way to detect that the c_open call
failed because of an existing directory.
XXX Should use filepath library
$locking
Implementations should enforce as far as possible, at least locally to the
That is, /there may either be many handles on the same file which manage input, or just one handle on the file which manages output/. If any
open or semi-closed handle is managing a file for output, no new
handle can be allocated for that file. If any open or semi-closed
handle is managing a file for input, new handles can only be allocated
implementation-dependent, but they should normally be the same if they
have the same absolute path name and neither has been renamed, for
example.
/Warning/: the 'readFile' operation holds a semi-closed handle on
the file until the entire contents of the file have been consumed.
It follows that an attempt to write to a file (using 'writeFile', for
example) that was earlier opened by 'readFile' will usually result in | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude #
Copyright : ( c ) The University of Glasgow 2001
The standard IO library .
module System.IO (
* The IO monad
IO,
fixIO,
FilePath,
| GHC note : a ' Handle ' will be automatically closed when the garbage
an explicit ' ' to close ' Handle 's when they are no longer
required . GHC does not currently attempt to free up file
stdin, stdout, stderr,
withFile,
openFile,
IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
hClose,
| These functions are also exported by the " Prelude " .
readFile,
writeFile,
appendFile,
hFileSize,
hSetFileSize,
hIsEOF,
isEOF,
BufferMode(NoBuffering,LineBuffering,BlockBuffering),
hSetBuffering,
hGetBuffering,
hFlush,
hGetPosn,
hSetPosn,
hSeek,
SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
hTell,
hIsOpen, hIsClosed,
hIsReadable, hIsWritable,
hIsSeekable,
* * Terminal operations ( not portable : GHC only )
hIsTerminalDevice,
hSetEcho,
hGetEcho,
* * Showing handle state ( not portable : GHC only )
hShow,
hWaitForInput,
hReady,
hGetChar,
hGetLine,
hLookAhead,
hGetContents,
hPutChar,
hPutStr,
hPutStrLn,
hPrint,
| These functions are also exported by the " Prelude " .
interact,
putChar,
putStr,
putStrLn,
print,
getChar,
getLine,
getContents,
readIO,
readLn,
withBinaryFile,
openBinaryFile,
hSetBinaryMode,
hPutBuf,
hGetBuf,
hGetBufSome,
hPutBufNonBlocking,
hGetBufNonBlocking,
openTempFile,
openBinaryTempFile,
openTempFileWithDefaultPermissions,
openBinaryTempFileWithDefaultPermissions,
is used to decode bytes into Unicode characters when reading ,
and encode Unicode characters into bytes when writing .
( GHC note : on Windows , we currently do not support double - byte
encodings ; if the console\ 's code page is unsupported , then
except during lazy I / O ( ' hGetContents ' , ' ' , and
hSetEncoding,
hGetEncoding,
TextEncoding,
latin1,
utf8, utf8_bom,
utf16, utf16le, utf16be,
utf32, utf32le, utf32be,
localeEncoding,
char8,
mkTextEncoding,
| In Haskell , a newline is always represented by the character
A text - mode ' Handle ' has an associated ' NewlineMode ' that
' NewlineMode ' specifies the input and output translation
The default ' NewlineMode ' for a ' Handle ' is
but translates ' \r\n ' to ' \n ' and back on Windows .
hSetNewlineMode,
Newline(..), nativeNewline,
NewlineMode(..),
noNewlineTranslation, universalNewlineMode, nativeNewlineMode,
) where
import Control.Exception.Base
import Data.Bits
import Data.List
import Data.Maybe
import Foreign.C.Error
#ifdef mingw32_HOST_OS
import Foreign.C.String
#endif
import Foreign.C.Types
import System.Posix.Internals
import System.Posix.Types
import GHC.Base
import GHC.IO hiding ( bracket, onException )
import GHC.IO.IOMode
import GHC.IO.Handle.FD
import qualified GHC.IO.FD as FD
import GHC.IO.Handle
import GHC.IO.Handle.Text ( hGetBufSome, hPutStrLn )
import GHC.IO.Exception ( userError )
import GHC.IO.Encoding
import GHC.Num
import Text.Read
import GHC.Show
import GHC.MVar
putChar :: Char -> IO ()
putChar c = hPutChar stdout c
putStr :: String -> IO ()
putStr s = hPutStr stdout s
putStrLn :: String -> IO ()
putStrLn s = hPutStrLn stdout s
For example , a program to print the first 20 integers and their
powers of 2 could be written as :
> main = print ( [ ( n , 2^n ) | n < - [ 0 .. 19 ] ] )
print :: Show a => a -> IO ()
print x = putStrLn (show x)
( same as ' hGetChar ' ' stdin ' ) .
getChar :: IO Char
getChar = hGetChar stdin
( same as ' hGetLine ' ' stdin ' ) .
getLine :: IO String
getLine = hGetLine stdin
( same as ' hGetContents ' ' stdin ' ) .
getContents :: IO String
getContents = hGetContents stdin
interact :: (String -> String) -> IO ()
interact f = do s <- getContents
putStr (f s)
The file is read lazily , on demand , as with ' ' .
readFile :: FilePath -> IO String
readFile name = openFile name ReadMode >>= hGetContents
writeFile :: FilePath -> String -> IO ()
writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
use the ' show ' function to convert the value to a string first .
> main = appendFile " squares " ( show [ ( x , x*x ) | x < - [ 0,0.1 .. 2 ] ] )
appendFile :: FilePath -> String -> IO ()
appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
readLn :: Read a => IO a
readLn = do l <- getLine
r <- readIO l
return r
readIO :: Read a => String -> IO a
readIO s = case (do { (x,t) <- reads s ;
("","") <- lex t ;
return x }) of
[x] -> return x
[] -> ioError (userError "Prelude.readIO: no parse")
_ -> ioError (userError "Prelude.readIO: ambiguous parse")
| The Unicode encoding of the current locale
localeEncoding :: TextEncoding
localeEncoding = initLocaleEncoding
| Computation ' hReady ' @hdl@ indicates whether at least one item is
hReady :: Handle -> IO Bool
hReady h = hWaitForInput h 0
given by the ' shows ' function to the file or channel managed by @hdl@
* ' System . ' if the device is full ; or
hPrint :: Show a => Handle -> a -> IO ()
hPrint hdl = hPutStrLn hdl . show
the resulting handle to the computation @act@. The handle will be
withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withFile name mode = bracket (openFile name mode) hClose
and passes the resulting handle to the computation @act@. The handle
withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
fixIO :: (a -> IO a) -> IO a
fixIO k = do
m <- newEmptyMVar
ans <- unsafeInterleaveIO (takeMVar m)
result <- k ans
putMVar m result
return result
NOTE : we do our own explicit black holing here , because GHC 's lazy
blackholing is n't enough . In an infinite loop , GHC may run the IO
NOTE2 : the explicit black - holing with an IORef ran into trouble
with multiple threads ( see # 5421 ) , so now we use an MVar . I 'm
exceptions . Ugh . What we really need here is an IVar , or an
atomic readMVar , or even STM . All these seem like overkill .
| The function creates a temporary file in ReadWrite mode .
user can it .
the temporary file is to be created . On Unix the @O_CREAT@ and
@O_EXCL@ flags are used to prevent this attack , but note that
@O_EXCL@ is sometimes not supported on NFS filesystems , so if you
-> IO (FilePath, Handle)
openTempFile tmp_dir template
= openTempFile' "openTempFile" tmp_dir template False 0o600
openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
openBinaryTempFile tmp_dir template
= openTempFile' "openBinaryTempFile" tmp_dir template True 0o600
openTempFileWithDefaultPermissions :: FilePath -> String
-> IO (FilePath, Handle)
openTempFileWithDefaultPermissions tmp_dir template
= openTempFile' "openBinaryTempFile" tmp_dir template False 0o666
openBinaryTempFileWithDefaultPermissions :: FilePath -> String
-> IO (FilePath, Handle)
openBinaryTempFileWithDefaultPermissions tmp_dir template
= openTempFile' "openBinaryTempFile" tmp_dir template True 0o666
openTempFile' :: String -> FilePath -> String -> Bool -> CMode
-> IO (FilePath, Handle)
openTempFile' loc tmp_dir template binary mode = do
pid <- c_getpid
findTempName pid
where
(prefix,suffix) =
case break (== '.') $ reverse template of
First case : template contains no ' . 's . Just re - reverse it .
(rev_suffix, "") -> (reverse rev_suffix, "")
Second case : template contains at least one ' . ' . Strip the
(rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
beginning with ' . ' as the second component .
_ -> error "bug in System.IO.openTempFile"
findTempName x = do
r <- openNewFile filepath binary mode
case r of
FileExists -> findTempName (x + 1)
OpenNewError errno -> ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
NewFileCreated fd -> do
is_nonblock
enc <- getLocaleEncoding
return (filepath, h)
where
filename = prefix ++ show x ++ suffix
filepath = tmp_dir `combine` filename
XXX bits copied from System . FilePath , since that 's not available here
combine a b
| null b = a
| null a = b
| last a == pathSeparator = a ++ b
| otherwise = a ++ [pathSeparator] ++ b
data OpenNewFileResult
= NewFileCreated CInt
| FileExists
| OpenNewError Errno
openNewFile :: FilePath -> Bool -> CMode -> IO OpenNewFileResult
openNewFile filepath binary mode = do
let oflags1 = rw_flags .|. o_EXCL
binary_flags
| binary = o_BINARY
| otherwise = 0
oflags = oflags1 .|. binary_flags
fd <- withFilePath filepath $ \ f ->
c_open f oflags mode
if fd < 0
then do
errno <- getErrno
case errno of
_ | errno == eEXIST -> return FileExists
#ifdef mingw32_HOST_OS
If c_open throws EACCES on windows , it could mean that filepath is a
directory . In this case , we want to return FileExists so that the
See bug # 4968 .
_ | errno == eACCES -> do
withCString filepath $ \path -> do
exists <- c_fileExists path
return $ if exists
then FileExists
else OpenNewError errno
#endif
_ -> return (OpenNewError errno)
else return (NewFileCreated fd)
#ifdef mingw32_HOST_OS
foreign import ccall "file_exists" c_fileExists :: CString -> IO Bool
#endif
pathSeparator :: Char
#ifdef mingw32_HOST_OS
pathSeparator = '\\'
#else
pathSeparator = '/'
#endif
XXX Copied from GHC.Handle
std_flags, output_flags, rw_flags :: CInt
std_flags = o_NONBLOCK .|. o_NOCTTY
output_flags = std_flags .|. o_CREAT
rw_flags = output_flags .|. o_RDWR
Haskell process , multiple - reader single - writer locking on files .
if they do not manage output . Whether two files are the same is
failure with ' System . IO.Error.isAlreadyInUseError ' .
|
b73ff5786f25ad1a0426525f5358401e8f57c0c4c83a169cf9dc27192dba844c | comby-tools/comby | test_generic.ml | open Core
open Test_helpers
open Comby_kernel
open Matchers
let run
(module E : Engine.S)
?(configuration = configuration)
source
match_template
rewrite_template
=
E.Generic.first ~configuration match_template source
|> function
| Ok result ->
Rewrite.all ~source ~rewrite_template [ result ]
|> (fun x -> Option.value_exn x)
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string
| Error _ ->
(* this is too annoying to fix every time the grammar changes. *)
print_string ""
let run_all
(module M : Matchers.Matcher.S)
?(configuration = configuration)
source
match_template
rewrite_template
=
M.all ~configuration ~template:match_template ~source ()
|> function
| [] -> print_string "No matches."
| results ->
Option.value_exn (Rewrite.all ~source ~rewrite_template results)
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string
let run_match (module M : Matchers.Matcher.S) source match_template =
M.all ~configuration ~template:match_template ~source ()
|> function
| [] -> print_string "No matches."
| hd :: _ -> print_string (Yojson.Safe.to_string (Match.to_yojson hd))
let%expect_test "basic" =
let source = {|a b c d|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b c d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b c d|}];
let source = {|a b c d|} in
let match_template = {|a :[1] c d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b|}];
let source = {|a b c d|} in
let match_template = {|a :[1] d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b c|}];
let source = {|a b c d|} in
let match_template = {|a :[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b c d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b c d|}];
let source = {|a b c d|} in
let match_template = {|:[1] c d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b|}];
let source = {|a b c d|} in
let match_template = {|:[1] :[2]|} in
let rewrite_template = {|(:[1]) (:[2])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
let source = {|a b c d|} in
let match_template = {|:[2] :[1]|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
let source = {|a b c d|} in
let match_template = {|a :[2] :[1] d|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(b) (c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(b) (c)|}];
let source = {|a b c d|} in
let match_template = {|a :[2] :[1]|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(b) (c d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(b) (c d)|}];
let source = {|a b c d|} in
let match_template = {|a :[2] c :[1]|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(b) (d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(b) (d)|}];
let source = {|x:|} in
let match_template = {|:[1]:|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|x|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|x|}]
let%expect_test "basic_failures" =
let source = {|a x b bbq|} in
let match_template = {|a :[1] b c|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {||}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {||}];
let source = {|a b c d|} in
let match_template = {|a :[2] d :[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {||}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {||}];
let source = {|a b c d|} in
let match_template = {|a :[2] b :[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {||}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {||}]
let%expect_test "delimiter_matching" =
let source = {|foo(bar)|} in
let match_template = {|:[1](bar)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|foo|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|foo|}];
let source = {|(a b c) d|} in
let match_template = {|(:[1]) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b c|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b c|}];
let source = {|(a b c) d|} in
let match_template = {|(:[1] b :[2]) d|} in
let rewrite_template = {|(:[1]) (:[2])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
let source = {|q(a b c) d|} in
let match_template = {|q(:[1] b :[2]) d|} in
let rewrite_template = {|(:[1]) (:[2])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
let source = {|((a) b)|} in
let match_template = {|(:[1] b)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a)|}];
let source = {|((a b c)) d|} in
let match_template = {|(:[1]) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
let source = {|((a b c)) d|} in
let match_template = {|(:[1]) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
let source = {|((a b c) q) d|} in
let match_template = {|((:[1]) q) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b c|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b c|}];
let source = {|((a b c) q) d|} in
let match_template = {|((:[1] c) q) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b|}];
let source = {|((a b () c) q) d|} in
let match_template = {|((:[1] () c) q) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b|}];
let source = {|((a ((x) d) b c)) d|} in
let match_template = {|((a :[1] :[2] c)) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|((x) d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|((x) d)|}];
let source = {|((a ((x) d) b c)) d|} in
let match_template = {|((a (:[1]) :[2] c)) d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(x) d b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(x) d b|}];
let source = {|(b (c) d)|} in
let match_template = {|(:[1])|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
let source = {|(b (c) d.)|} in
let match_template = {|(:[1].)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
let source = {|(b (c.) d.)|} in
let match_template = {|(:[1].)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b (c.) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b (c.) d|}];
let source = {|(b. (c) d.)|} in
let match_template = {|(:[1].)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b. (c) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b. (c) d|}];
let source = {|(b (c) d.)|} in
let match_template = {|(b :[1] d.)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(c)|}];
let source = {|outer(inner(dst,src),src)|} in
let match_template = {|outer(:[1],src)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|inner(dst,src)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|inner(dst,src)|}];
let source = {|(b ((c)) d.)|} in
let match_template = {|(b :[1] d.)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|((c))|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|((c))|}];
let source = {|a b c|} in
let match_template = {|a :[1] c|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b|}];
let source = {|x = foo;|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|foo|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|foo|}];
let source = {|((a {{x} d} b c)) d|} in
let match_template = {|((a {:[1] d} :[2] c)) d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|{x} b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|{x} b|}];
let source = {|((a {([{x}]) d} b c)) d|} in
let match_template = {|((a {:[1] d} :[2] c)) d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|([{x}]) b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|([{x}]) b|}];
let source = {|(((((x)))))|} in
let match_template = {|(((:[1])))|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|((x))|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|((x))|}];
let source = {|((((y(x)z))))|} in
let match_template = {|(((:[1])))|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(y(x)z)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(y(x)z)|}];
let source = {|((((y(x)z))))|} in
let match_template = {|(((:[1]):[2]))|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(y(x)z) |}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(y(x)z) |}];
let source = {|(((x)z))|} in
let match_template = {|(((:[1]):[2]))|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|x z|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|x z|}];
let source = {|((((x))z))|} in
let match_template = {|(((:[1]):[2]))|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(x) z|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(x) z|}];
let source = {|lolwtfbbq|} in
let match_template = {|lol:[1]bbq|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|wtf|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|wtf|}];
let source = {|x = foo; x = bar;|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|foo x = bar;|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|foo x = bar;|}];
let source = {|[ no match prefix ] x = foo; [ no match suffix ]|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|[ no match prefix ] foo [ no match suffix ]|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|[ no match prefix ] foo [ no match suffix ]|}];
let source = {|x = a; x = b; x = c|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a x = b; x = c|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a x = b; x = c|}];
let source = {|x = ( x = x; );|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|( x = x; )|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|( x = x; )|}];
let source = {|( x = x = x; )|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|( x = x )|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|( x = x )|}];
let source = {|xxx a b d c 1 2 3 b d d blah|} in
let match_template = {|a :[1] c :[2] d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|xxx b d 1 2 3 b d blah|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|xxx b d 1 2 3 b d blah|}];
let source = {|howevenlolwtfbbqispossible|} in
let match_template = {|lol:[1]bbq|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|howevenwtfispossible|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|howevenwtfispossible|}];
let source = {|lolhowevenlolwtfbbqispossiblebbq|} in
let match_template = {|lol:[1]bbq|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|howevenlolwtfispossiblebbq|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|howevenlolwtfispossiblebbq|}];
let source = {|hello my name is bob the builder|} in
let match_template = {|:[alongidentifiername] :[2] :[3] :[xyz] :[5] :[6]|} in
let rewrite_template = {|:[alongidentifiername] :[2] :[3] :[xyz] :[5] :[6]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|hello my name is bob the builder|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|hello my name is bob the builder|}];
let source =
{|www.testdofooname.com/picsinsideit/stunningpictureofkays1381737242g8k4n-280x428.jpg|}
in
let match_template = {|www.:[1]-:[2].jpg|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|testdofooname.com/picsinsideit/stunningpictureofkays1381737242g8k4n 280x428|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|testdofooname.com/picsinsideit/stunningpictureofkays1381737242g8k4n 280x428|}];
let source =
{||}
in
let match_template = {|:[1]api.:[2]/repos/:[3]s/:[4]|} in
let rewrite_template = {|:[1] :[2] :[3] :[4]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact
{|https:// github.com dmjacobsen/slurm/commit 716c1499695c68afcab848a1b49653574b4fc167|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact
{|https:// github.com dmjacobsen/slurm/commit 716c1499695c68afcab848a1b49653574b4fc167|}];
let source =
{|
assert(stream->md_len + md_len -
si.foo_data_begin <= MAD_BUFFER_MDLEN);
stream->foo_data + stream->md_len ,
mad_bit_nextbyte(&stream->ptr ) ,
frame_used = md_len - si.foo_data_begin ) ;
stream->md_len + = frame_used ;
| }
| > format
in
let match_template = { |memcpy(:[1 ] , : [ 2 ] , : [ 3]);| } in
let rewrite_template = { |:[1 ] , : [ 2 ] , : [ 3]| } in
run ( module Alpha ) source match_template rewrite_template ;
[ % expect_exact
{ |assert(stream->md_len + md_len -
si.foo_data_begin < = MAD_BUFFER_MDLEN ) ;
* stream->foo_data + stream->md_len , mad_bit_nextbyte(&stream->ptr ) , frame_used = md_len - si.foo_data_begin
stream->md_len + = frame_used;| } ] ;
run ( module Omega ) source match_template rewrite_template ;
[ % expect_exact
{ |assert(stream->md_len + md_len -
si.foo_data_begin < = MAD_BUFFER_MDLEN ) ;
* stream->foo_data + stream->md_len , mad_bit_nextbyte(&stream->ptr ) , frame_used = md_len - si.foo_data_begin
stream->md_len + = frame_used;| } ]
let%expect_test " significant_whitespace " =
let configuration = Configuration.create ~match_kind : Fuzzy ~significant_whitespace : true ( ) in
let run = run ~configuration in
let source = { |two spaces| } in
let match_template = { |:[1 ] : [ 2]| } in
let rewrite_template = { |:[1 ] : [ 2]| } in
run ( module Alpha ) source match_template rewrite_template ;
[ % expect_exact { |two spaces| } ] ;
run ( module Omega ) source match_template rewrite_template ;
[ % expect_exact { |two spaces| } ] ;
( * FIXME : this should fail . also test case where separators do or do not need
whitespace . e.g. , strict about strcpy(src , dst ) matching a template
strcpy(:[1],:[2 ] ) versus strcpy(:[1 ] , : [ 2 ] )
mad_bit_nextbyte(&stream->ptr),
frame_used = md_len - si.foo_data_begin);
stream->md_len += frame_used;
|}
|> format
in
let match_template = {|memcpy(:[1], :[2], :[3]);|} in
let rewrite_template = {|:[1], :[2], :[3]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact
{|assert(stream->md_len + md_len -
si.foo_data_begin <= MAD_BUFFER_MDLEN);
*stream->foo_data + stream->md_len, mad_bit_nextbyte(&stream->ptr), frame_used = md_len - si.foo_data_begin
stream->md_len += frame_used;|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact
{|assert(stream->md_len + md_len -
si.foo_data_begin <= MAD_BUFFER_MDLEN);
*stream->foo_data + stream->md_len, mad_bit_nextbyte(&stream->ptr), frame_used = md_len - si.foo_data_begin
stream->md_len += frame_used;|}]
let%expect_test "significant_whitespace" =
let configuration = Configuration.create ~match_kind:Fuzzy ~significant_whitespace:true () in
let run = run ~configuration in
let source = {|two spaces|} in
let match_template = {|:[1] :[2]|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|two spaces|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|two spaces|}];
(* FIXME: this should fail. also test case where separators do or do not need
whitespace. e.g., strict about strcpy(src,dst) matching a template
strcpy(:[1],:[2]) versus strcpy(:[1], :[2]) *)
let source = {|two spaces|} in
let match_template = {|:[1] :[2]|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|two spaces|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|two spaces|}]
let%expect_test "contextual_matching" =
let source = {|memcpy(dst1, src1, 1); memcpy(dst2, src2, 2);|} in
let match_template = {|memcpy(:[1], :[2], :[3])|} in
let rewrite_template = {|:[1]|} in
run_all (module Alpha.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
run_all (module Omega.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
let source = {|memcpy(dst1, src1, 1); memcpy(dst2, src2, 2);|} in
let match_template = {|memcpy(:[1], :[2], :[3])|} in
let rewrite_template = {|:[1]|} in
run_all (module Alpha.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
run_all (module Omega.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}]
let%expect_test "contextual_matching_with_short_hole_syntax" =
let source = {|memcpy(dst1, src1, 1); memcpy(dst2, src2, 2);|} in
let match_template = {|memcpy(:[[1]], :[2], :[3])|} in
let rewrite_template = {|:[[1]]|} in
run_all (module Alpha.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
run_all (module Omega.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}]
let%expect_test "trivial_empty_case" =
let source = "" in
let match_template = "" in
run_match (module Alpha.Generic) source match_template;
[%expect_exact
{|{"range":{"start":{"offset":0,"line":1,"column":1},"end":{"offset":0,"line":1,"column":1}},"environment":[],"matched":""}|}];
run_match (module Omega.Generic) source match_template;
[%expect_exact
{|{"range":{"start":{"offset":0,"line":1,"column":1},"end":{"offset":0,"line":1,"column":1}},"environment":[],"matched":""}|}]
let%expect_test "test_top_level_hole_stops_at_newline_false_implies_default_generic" =
let source =
{|
a = b
c = d
(
e = f
(
g = h
i = j
)
k = l
m = n
)
o = p
|}
in
let match_template = ":[1] = :[2]" in
let rewrite_template = "line" in
let configuration = Configuration.create ~match_newline_toplevel:false () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact
{|
line
line
(
line
(
line
line
)
line
line
)
line
|}];
Unimplemented : Does not stop at newline
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|line|}]
let%expect_test "test_top_level_hole_stops_at_newline_for_example_generic_go_false" =
let source =
{|
for i, x := range derp {
do not match
}
for i, x := range derp {
do match
}
|}
in
let match_template = "for i, x := :[_] { do match }" in
let rewrite_template = "erased" in
let configuration = Configuration.create ~match_newline_toplevel:false () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact
{|
for i, x := range derp {
do not match
}
erased
|}];
Unimplemented : Does not stop at newline
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|
erased
|}]
let%expect_test "test_top_level_hole_stops_at_newline_for_example_generic_go_true" =
let source =
{|
for i, x := range derp {
do not match
}
for i, x := range derp {
do match
}
|}
in
let match_template = "for i, x := :[_] { do match }" in
let rewrite_template = "erased" in
let configuration = Configuration.create ~match_newline_toplevel:true () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|
erased
|}];
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|
erased
|}]
let%expect_test "test_top_level_hole_stops_at_newline_generic_true" =
let source =
{|
a = b
c = d
(
e = f
(
g = h
i = j
)
k = l
m = n
)
o = p
|}
in
let match_template = ":[1] = :[2]" in
let rewrite_template = "line" in
let configuration = Configuration.create ~match_newline_toplevel:true () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|line|}];
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|line|}]
let%expect_test "test_top_level_hole_crosses_newlines_for_html_by_default" =
let source = {|
<foo>
stuff
</foo>
|} in
let match_template = "<foo>:[x]</foo>" in
let rewrite_template = ":[x]" in
run_all (module Alpha.Html) ~configuration source match_template rewrite_template;
[%expect_exact {|
stuff
|}];
(* Unimplemented: Has no effect *)
run_all (module Omega.Html) ~configuration source match_template rewrite_template;
[%expect_exact {|
stuff
|}]
| null | https://raw.githubusercontent.com/comby-tools/comby/a36c63fb1e686adaff3e90aed00e88404f8cda78/test/common/test_generic.ml | ocaml | this is too annoying to fix every time the grammar changes.
FIXME: this should fail. also test case where separators do or do not need
whitespace. e.g., strict about strcpy(src,dst) matching a template
strcpy(:[1],:[2]) versus strcpy(:[1], :[2])
Unimplemented: Has no effect | open Core
open Test_helpers
open Comby_kernel
open Matchers
let run
(module E : Engine.S)
?(configuration = configuration)
source
match_template
rewrite_template
=
E.Generic.first ~configuration match_template source
|> function
| Ok result ->
Rewrite.all ~source ~rewrite_template [ result ]
|> (fun x -> Option.value_exn x)
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string
| Error _ ->
print_string ""
let run_all
(module M : Matchers.Matcher.S)
?(configuration = configuration)
source
match_template
rewrite_template
=
M.all ~configuration ~template:match_template ~source ()
|> function
| [] -> print_string "No matches."
| results ->
Option.value_exn (Rewrite.all ~source ~rewrite_template results)
|> (fun { rewritten_source; _ } -> rewritten_source)
|> print_string
let run_match (module M : Matchers.Matcher.S) source match_template =
M.all ~configuration ~template:match_template ~source ()
|> function
| [] -> print_string "No matches."
| hd :: _ -> print_string (Yojson.Safe.to_string (Match.to_yojson hd))
let%expect_test "basic" =
let source = {|a b c d|} in
let match_template = {|:[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b c d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b c d|}];
let source = {|a b c d|} in
let match_template = {|a :[1] c d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b|}];
let source = {|a b c d|} in
let match_template = {|a :[1] d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b c|}];
let source = {|a b c d|} in
let match_template = {|a :[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b c d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b c d|}];
let source = {|a b c d|} in
let match_template = {|:[1] c d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b|}];
let source = {|a b c d|} in
let match_template = {|:[1] :[2]|} in
let rewrite_template = {|(:[1]) (:[2])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
let source = {|a b c d|} in
let match_template = {|:[2] :[1]|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (b c d)|}];
let source = {|a b c d|} in
let match_template = {|a :[2] :[1] d|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(b) (c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(b) (c)|}];
let source = {|a b c d|} in
let match_template = {|a :[2] :[1]|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(b) (c d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(b) (c d)|}];
let source = {|a b c d|} in
let match_template = {|a :[2] c :[1]|} in
let rewrite_template = {|(:[2]) (:[1])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(b) (d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(b) (d)|}];
let source = {|x:|} in
let match_template = {|:[1]:|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|x|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|x|}]
let%expect_test "basic_failures" =
let source = {|a x b bbq|} in
let match_template = {|a :[1] b c|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {||}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {||}];
let source = {|a b c d|} in
let match_template = {|a :[2] d :[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {||}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {||}];
let source = {|a b c d|} in
let match_template = {|a :[2] b :[1]|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {||}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {||}]
let%expect_test "delimiter_matching" =
let source = {|foo(bar)|} in
let match_template = {|:[1](bar)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|foo|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|foo|}];
let source = {|(a b c) d|} in
let match_template = {|(:[1]) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b c|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b c|}];
let source = {|(a b c) d|} in
let match_template = {|(:[1] b :[2]) d|} in
let rewrite_template = {|(:[1]) (:[2])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
let source = {|q(a b c) d|} in
let match_template = {|q(:[1] b :[2]) d|} in
let rewrite_template = {|(:[1]) (:[2])|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a) (c)|}];
let source = {|((a) b)|} in
let match_template = {|(:[1] b)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a)|}];
let source = {|((a b c)) d|} in
let match_template = {|(:[1]) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
let source = {|((a b c)) d|} in
let match_template = {|(:[1]) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(a b c)|}];
let source = {|((a b c) q) d|} in
let match_template = {|((:[1]) q) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b c|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b c|}];
let source = {|((a b c) q) d|} in
let match_template = {|((:[1] c) q) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b|}];
let source = {|((a b () c) q) d|} in
let match_template = {|((:[1] () c) q) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a b|}];
let source = {|((a ((x) d) b c)) d|} in
let match_template = {|((a :[1] :[2] c)) d|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|((x) d)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|((x) d)|}];
let source = {|((a ((x) d) b c)) d|} in
let match_template = {|((a (:[1]) :[2] c)) d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(x) d b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(x) d b|}];
let source = {|(b (c) d)|} in
let match_template = {|(:[1])|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
let source = {|(b (c) d.)|} in
let match_template = {|(:[1].)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b (c) d|}];
let source = {|(b (c.) d.)|} in
let match_template = {|(:[1].)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b (c.) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b (c.) d|}];
let source = {|(b. (c) d.)|} in
let match_template = {|(:[1].)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b. (c) d|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b. (c) d|}];
let source = {|(b (c) d.)|} in
let match_template = {|(b :[1] d.)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(c)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(c)|}];
let source = {|outer(inner(dst,src),src)|} in
let match_template = {|outer(:[1],src)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|inner(dst,src)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|inner(dst,src)|}];
let source = {|(b ((c)) d.)|} in
let match_template = {|(b :[1] d.)|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|((c))|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|((c))|}];
let source = {|a b c|} in
let match_template = {|a :[1] c|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|b|}];
let source = {|x = foo;|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|foo|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|foo|}];
let source = {|((a {{x} d} b c)) d|} in
let match_template = {|((a {:[1] d} :[2] c)) d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|{x} b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|{x} b|}];
let source = {|((a {([{x}]) d} b c)) d|} in
let match_template = {|((a {:[1] d} :[2] c)) d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|([{x}]) b|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|([{x}]) b|}];
let source = {|(((((x)))))|} in
let match_template = {|(((:[1])))|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|((x))|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|((x))|}];
let source = {|((((y(x)z))))|} in
let match_template = {|(((:[1])))|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(y(x)z)|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(y(x)z)|}];
let source = {|((((y(x)z))))|} in
let match_template = {|(((:[1]):[2]))|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(y(x)z) |}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(y(x)z) |}];
let source = {|(((x)z))|} in
let match_template = {|(((:[1]):[2]))|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|x z|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|x z|}];
let source = {|((((x))z))|} in
let match_template = {|(((:[1]):[2]))|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|(x) z|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|(x) z|}];
let source = {|lolwtfbbq|} in
let match_template = {|lol:[1]bbq|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|wtf|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|wtf|}];
let source = {|x = foo; x = bar;|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|foo x = bar;|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|foo x = bar;|}];
let source = {|[ no match prefix ] x = foo; [ no match suffix ]|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|[ no match prefix ] foo [ no match suffix ]|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|[ no match prefix ] foo [ no match suffix ]|}];
let source = {|x = a; x = b; x = c|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|a x = b; x = c|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|a x = b; x = c|}];
let source = {|x = ( x = x; );|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|( x = x; )|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|( x = x; )|}];
let source = {|( x = x = x; )|} in
let match_template = {|x = :[1];|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|( x = x )|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|( x = x )|}];
let source = {|xxx a b d c 1 2 3 b d d blah|} in
let match_template = {|a :[1] c :[2] d|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|xxx b d 1 2 3 b d blah|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|xxx b d 1 2 3 b d blah|}];
let source = {|howevenlolwtfbbqispossible|} in
let match_template = {|lol:[1]bbq|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|howevenwtfispossible|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|howevenwtfispossible|}];
let source = {|lolhowevenlolwtfbbqispossiblebbq|} in
let match_template = {|lol:[1]bbq|} in
let rewrite_template = {|:[1]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|howevenlolwtfispossiblebbq|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|howevenlolwtfispossiblebbq|}];
let source = {|hello my name is bob the builder|} in
let match_template = {|:[alongidentifiername] :[2] :[3] :[xyz] :[5] :[6]|} in
let rewrite_template = {|:[alongidentifiername] :[2] :[3] :[xyz] :[5] :[6]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|hello my name is bob the builder|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|hello my name is bob the builder|}];
let source =
{|www.testdofooname.com/picsinsideit/stunningpictureofkays1381737242g8k4n-280x428.jpg|}
in
let match_template = {|www.:[1]-:[2].jpg|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|testdofooname.com/picsinsideit/stunningpictureofkays1381737242g8k4n 280x428|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|testdofooname.com/picsinsideit/stunningpictureofkays1381737242g8k4n 280x428|}];
let source =
{||}
in
let match_template = {|:[1]api.:[2]/repos/:[3]s/:[4]|} in
let rewrite_template = {|:[1] :[2] :[3] :[4]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact
{|https:// github.com dmjacobsen/slurm/commit 716c1499695c68afcab848a1b49653574b4fc167|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact
{|https:// github.com dmjacobsen/slurm/commit 716c1499695c68afcab848a1b49653574b4fc167|}];
let source =
{|
assert(stream->md_len + md_len -
si.foo_data_begin <= MAD_BUFFER_MDLEN);
stream->foo_data + stream->md_len ,
mad_bit_nextbyte(&stream->ptr ) ,
frame_used = md_len - si.foo_data_begin ) ;
stream->md_len + = frame_used ;
| }
| > format
in
let match_template = { |memcpy(:[1 ] , : [ 2 ] , : [ 3]);| } in
let rewrite_template = { |:[1 ] , : [ 2 ] , : [ 3]| } in
run ( module Alpha ) source match_template rewrite_template ;
[ % expect_exact
{ |assert(stream->md_len + md_len -
si.foo_data_begin < = MAD_BUFFER_MDLEN ) ;
* stream->foo_data + stream->md_len , mad_bit_nextbyte(&stream->ptr ) , frame_used = md_len - si.foo_data_begin
stream->md_len + = frame_used;| } ] ;
run ( module Omega ) source match_template rewrite_template ;
[ % expect_exact
{ |assert(stream->md_len + md_len -
si.foo_data_begin < = MAD_BUFFER_MDLEN ) ;
* stream->foo_data + stream->md_len , mad_bit_nextbyte(&stream->ptr ) , frame_used = md_len - si.foo_data_begin
stream->md_len + = frame_used;| } ]
let%expect_test " significant_whitespace " =
let configuration = Configuration.create ~match_kind : Fuzzy ~significant_whitespace : true ( ) in
let run = run ~configuration in
let source = { |two spaces| } in
let match_template = { |:[1 ] : [ 2]| } in
let rewrite_template = { |:[1 ] : [ 2]| } in
run ( module Alpha ) source match_template rewrite_template ;
[ % expect_exact { |two spaces| } ] ;
run ( module Omega ) source match_template rewrite_template ;
[ % expect_exact { |two spaces| } ] ;
( * FIXME : this should fail . also test case where separators do or do not need
whitespace . e.g. , strict about strcpy(src , dst ) matching a template
strcpy(:[1],:[2 ] ) versus strcpy(:[1 ] , : [ 2 ] )
mad_bit_nextbyte(&stream->ptr),
frame_used = md_len - si.foo_data_begin);
stream->md_len += frame_used;
|}
|> format
in
let match_template = {|memcpy(:[1], :[2], :[3]);|} in
let rewrite_template = {|:[1], :[2], :[3]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact
{|assert(stream->md_len + md_len -
si.foo_data_begin <= MAD_BUFFER_MDLEN);
*stream->foo_data + stream->md_len, mad_bit_nextbyte(&stream->ptr), frame_used = md_len - si.foo_data_begin
stream->md_len += frame_used;|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact
{|assert(stream->md_len + md_len -
si.foo_data_begin <= MAD_BUFFER_MDLEN);
*stream->foo_data + stream->md_len, mad_bit_nextbyte(&stream->ptr), frame_used = md_len - si.foo_data_begin
stream->md_len += frame_used;|}]
let%expect_test "significant_whitespace" =
let configuration = Configuration.create ~match_kind:Fuzzy ~significant_whitespace:true () in
let run = run ~configuration in
let source = {|two spaces|} in
let match_template = {|:[1] :[2]|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|two spaces|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|two spaces|}];
let source = {|two spaces|} in
let match_template = {|:[1] :[2]|} in
let rewrite_template = {|:[1] :[2]|} in
run (module Alpha) source match_template rewrite_template;
[%expect_exact {|two spaces|}];
run (module Omega) source match_template rewrite_template;
[%expect_exact {|two spaces|}]
let%expect_test "contextual_matching" =
let source = {|memcpy(dst1, src1, 1); memcpy(dst2, src2, 2);|} in
let match_template = {|memcpy(:[1], :[2], :[3])|} in
let rewrite_template = {|:[1]|} in
run_all (module Alpha.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
run_all (module Omega.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
let source = {|memcpy(dst1, src1, 1); memcpy(dst2, src2, 2);|} in
let match_template = {|memcpy(:[1], :[2], :[3])|} in
let rewrite_template = {|:[1]|} in
run_all (module Alpha.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
run_all (module Omega.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}]
let%expect_test "contextual_matching_with_short_hole_syntax" =
let source = {|memcpy(dst1, src1, 1); memcpy(dst2, src2, 2);|} in
let match_template = {|memcpy(:[[1]], :[2], :[3])|} in
let rewrite_template = {|:[[1]]|} in
run_all (module Alpha.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}];
run_all (module Omega.Generic) source match_template rewrite_template;
[%expect_exact {|dst1; dst2;|}]
let%expect_test "trivial_empty_case" =
let source = "" in
let match_template = "" in
run_match (module Alpha.Generic) source match_template;
[%expect_exact
{|{"range":{"start":{"offset":0,"line":1,"column":1},"end":{"offset":0,"line":1,"column":1}},"environment":[],"matched":""}|}];
run_match (module Omega.Generic) source match_template;
[%expect_exact
{|{"range":{"start":{"offset":0,"line":1,"column":1},"end":{"offset":0,"line":1,"column":1}},"environment":[],"matched":""}|}]
let%expect_test "test_top_level_hole_stops_at_newline_false_implies_default_generic" =
let source =
{|
a = b
c = d
(
e = f
(
g = h
i = j
)
k = l
m = n
)
o = p
|}
in
let match_template = ":[1] = :[2]" in
let rewrite_template = "line" in
let configuration = Configuration.create ~match_newline_toplevel:false () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact
{|
line
line
(
line
(
line
line
)
line
line
)
line
|}];
Unimplemented : Does not stop at newline
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|line|}]
let%expect_test "test_top_level_hole_stops_at_newline_for_example_generic_go_false" =
let source =
{|
for i, x := range derp {
do not match
}
for i, x := range derp {
do match
}
|}
in
let match_template = "for i, x := :[_] { do match }" in
let rewrite_template = "erased" in
let configuration = Configuration.create ~match_newline_toplevel:false () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact
{|
for i, x := range derp {
do not match
}
erased
|}];
Unimplemented : Does not stop at newline
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|
erased
|}]
let%expect_test "test_top_level_hole_stops_at_newline_for_example_generic_go_true" =
let source =
{|
for i, x := range derp {
do not match
}
for i, x := range derp {
do match
}
|}
in
let match_template = "for i, x := :[_] { do match }" in
let rewrite_template = "erased" in
let configuration = Configuration.create ~match_newline_toplevel:true () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|
erased
|}];
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|
erased
|}]
let%expect_test "test_top_level_hole_stops_at_newline_generic_true" =
let source =
{|
a = b
c = d
(
e = f
(
g = h
i = j
)
k = l
m = n
)
o = p
|}
in
let match_template = ":[1] = :[2]" in
let rewrite_template = "line" in
let configuration = Configuration.create ~match_newline_toplevel:true () in
run_all (module Alpha.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|line|}];
run_all (module Omega.Generic) ~configuration source match_template rewrite_template;
[%expect_exact {|line|}]
let%expect_test "test_top_level_hole_crosses_newlines_for_html_by_default" =
let source = {|
<foo>
stuff
</foo>
|} in
let match_template = "<foo>:[x]</foo>" in
let rewrite_template = ":[x]" in
run_all (module Alpha.Html) ~configuration source match_template rewrite_template;
[%expect_exact {|
stuff
|}];
run_all (module Omega.Html) ~configuration source match_template rewrite_template;
[%expect_exact {|
stuff
|}]
|
a6ff77f9cff563a809fa81f4a0695c9e71c9f2ac636b07fc7007bddb64701429 | haskell-tools/haskell-tools | B.hs | module B where
x = () | null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/daemon/examples/Project/multi-packages/package2/B.hs | haskell | module B where
x = () | |
42264ecb0862736a717a53dfcb6fb29edddefb607c74d0fa0d5e049368814119 | arrdem/shelving | common_test.clj | (ns shelving.common-test
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as sgen]
[clojure.string :as str]
[clojure.set :as set]
[clojure.test :as t]
[clojure.test.check :as tc]
[clojure.test.check.properties :as prop]
[shelving.core :as sh]))
(s/check-asserts true)
(s/def ::foo string?)
(s/def ::bar string?)
(s/def ::baz
(s/keys :req-un [::foo ::bar]))
(s/def ::qux pos-int?)
(def schema
(-> sh/empty-schema
(sh/value-spec ::foo)
(sh/record-spec ::baz)
(sh/spec-rel [::baz ::foo])
(sh/spec-rel [::baz ::bar])))
(defn schema-migrate-tests [->cfg]
(let [conn (sh/open (->cfg schema))
schema* (sh/schema conn)
_ (t/is (= schema schema*))
schema* (sh/alter-schema conn sh/record-spec ::qux)
_ (t/is (= (sh/schema conn) schema*))]
nil))
(defn check-forwards-backwards-rels [conn]
(doseq [rel-id (sh/enumerate-rels conn)]
(t/is (= (set (sh/enumerate-rel conn rel-id))
(set (->> (sh/enumerate-rel conn (reverse rel-id))
(map reverse))))
(format "Relation %s didn't forwards/backwards check!" rel-id))))
(defn put-get-enumerate-example-tests [->cfg]
(let [foo-gen (s/gen ::foo)
baz-gen (s/gen ::baz)]
(t/testing "Checking schema for errors"
(let [schema-errors (sh/check-schema schema)]
(t/is (not schema-errors)
(str/join "\n" schema-errors))))
(t/testing "Testing connection ops"
(let [cfg (->cfg schema)
conn (sh/open cfg)]
(t/testing "Conn has correct spec/schema information"
(t/is (set/subset? #{::foo ::bar ::baz}
(set (sh/enumerate-specs conn)))))
(t/testing "Testing put/get/has? on values"
(let [v1 (sgen/generate foo-gen)
r1 (sh/put-spec conn ::foo v1)
v2 (sgen/generate foo-gen)
r2 (sh/put-spec conn ::foo v2)]
(t/is (= v1 (sh/get-spec conn ::foo r1)))
(t/is (sh/has? conn ::foo r1))
(t/is (= v2 (sh/get-spec conn ::foo r2)))
(t/is (sh/has? conn ::foo r2))
(t/is (set/subset? #{r1 r2} (set (sh/enumerate-spec conn ::foo))))
(t/is (thrown? AssertionError
(sh/put-spec conn ::foo r1 (sgen/generate foo-gen))))
(t/is (>= 2 (sh/count-spec conn ::foo)))))
(t/testing "Testing put/get on records"
(let [b1 (sgen/generate baz-gen)
b2 (sgen/generate baz-gen)
bi1 (sh/put-spec conn ::baz b1)]
(t/is (= b1 (sh/get-spec conn ::baz bi1)))
(t/is (sh/has? conn ::baz bi1))
(t/is (some #{bi1} (sh/enumerate-spec conn ::baz)))
Upserts should work
(sh/put-spec conn ::baz bi1 b2)
(t/is (= b2 (sh/get-spec conn ::baz bi1)))
(t/is (some #{bi1} (sh/enumerate-spec conn ::baz)))))))))
(defn value-rel-tests [->cfg]
(let [foo-gen (s/gen ::foo)
baz-gen (s/gen ::baz)
conn (sh/open (->cfg schema))]
(tc/quick-check 2000
(prop/for-all [baz baz-gen]
(let [the-foo (:foo baz)
foo-id (sh/put-spec conn ::foo the-foo)
baz-id (sh/put-spec conn ::baz baz)]
(t/is foo-id)
(t/is baz-id)
;; Relations are bidirectional on read, unidirectional on write.
(t/is (some #{foo-id} (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (some #{baz-id} (sh/get-rel conn [::foo ::baz] foo-id)))
(check-forwards-backwards-rels conn))))))
(defn record-rel-tests [->cfg]
(let [foo-gen (s/gen ::foo)
baz-gen (s/gen ::baz)
conn (sh/open (->cfg schema))]
(tc/quick-check 2000
(prop/for-all [baz baz-gen
baz' baz-gen]
(let [the-foo (:foo baz)
the-foo' (:foo baz')
foo-id (sh/put-spec conn ::foo the-foo)
baz-id (sh/put-spec conn ::baz baz)
foo-id' (sh/put-spec conn ::foo the-foo')]
(t/is foo-id)
(t/is baz-id)
;; Relations are bidirectional on read, unidirectional on write.
(t/is (some #(= % foo-id) (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (some #(= % baz-id) (sh/get-rel conn [::foo ::baz] foo-id)))
;; Now perform a write which should invalidate the above properties
(sh/put-spec conn ::baz baz-id baz')
;; The old values should no longer be associated as baz has changed.
;; But only if foo and foo' are distinct.
(when (not= the-foo the-foo')
(t/is (not-any? #{foo-id} (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (not-any? #{baz-id} (sh/get-rel conn [::foo ::baz] foo-id))))
;; The new values should be in effect
(t/is (some #{foo-id'} (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (some #{baz-id} (sh/get-rel conn [::foo ::baz] foo-id')))
;; The rel should be counted, and equal in cardinality going either way
(t/is (= (sh/count-rel conn [::baz ::foo])
(sh/count-rel conn [::foo ::baz])))
(check-forwards-backwards-rels conn))))))
(defn rel-tests [->cfg]
(value-rel-tests ->cfg)
(record-rel-tests ->cfg))
(defn persistence-tests [->cfg]
(let [;; Test round-tripping
conn (sh/open (->cfg schema))
_ (sh/put-spec conn ::baz {:foo "hey" :bar "there"})
s1 (sh/enumerate-specs conn)
r1 (sh/enumerate-spec conn ::foo)
foo-id (last r1)
_ (sh/flush conn)
_ (sh/close conn)
conn (sh/open (->cfg schema))
_ (t/is (= s1 (sh/enumerate-specs conn)))
_ (t/is (= r1 (sh/enumerate-spec conn ::foo)))
_ (t/is (= "hey" (sh/get-spec conn ::foo foo-id)))]))
(defn common-tests
"Takes a ctor of fn [schema] -> cfg, applies it and opens the resulting config twice.
Runs the example usage session in the README against the computed config."
[->cfg]
(schema-migrate-tests ->cfg)
(put-get-enumerate-example-tests ->cfg)
(rel-tests ->cfg)
(persistence-tests ->cfg))
| null | https://raw.githubusercontent.com/arrdem/shelving/27439bfcb2f3438d5b23fcd468360bda491002f1/src/test/clj/shelving/common_test.clj | clojure | Relations are bidirectional on read, unidirectional on write.
Relations are bidirectional on read, unidirectional on write.
Now perform a write which should invalidate the above properties
The old values should no longer be associated as baz has changed.
But only if foo and foo' are distinct.
The new values should be in effect
The rel should be counted, and equal in cardinality going either way
Test round-tripping | (ns shelving.common-test
(:require [clojure.spec.alpha :as s]
[clojure.spec.gen.alpha :as sgen]
[clojure.string :as str]
[clojure.set :as set]
[clojure.test :as t]
[clojure.test.check :as tc]
[clojure.test.check.properties :as prop]
[shelving.core :as sh]))
(s/check-asserts true)
(s/def ::foo string?)
(s/def ::bar string?)
(s/def ::baz
(s/keys :req-un [::foo ::bar]))
(s/def ::qux pos-int?)
(def schema
(-> sh/empty-schema
(sh/value-spec ::foo)
(sh/record-spec ::baz)
(sh/spec-rel [::baz ::foo])
(sh/spec-rel [::baz ::bar])))
(defn schema-migrate-tests [->cfg]
(let [conn (sh/open (->cfg schema))
schema* (sh/schema conn)
_ (t/is (= schema schema*))
schema* (sh/alter-schema conn sh/record-spec ::qux)
_ (t/is (= (sh/schema conn) schema*))]
nil))
(defn check-forwards-backwards-rels [conn]
(doseq [rel-id (sh/enumerate-rels conn)]
(t/is (= (set (sh/enumerate-rel conn rel-id))
(set (->> (sh/enumerate-rel conn (reverse rel-id))
(map reverse))))
(format "Relation %s didn't forwards/backwards check!" rel-id))))
(defn put-get-enumerate-example-tests [->cfg]
(let [foo-gen (s/gen ::foo)
baz-gen (s/gen ::baz)]
(t/testing "Checking schema for errors"
(let [schema-errors (sh/check-schema schema)]
(t/is (not schema-errors)
(str/join "\n" schema-errors))))
(t/testing "Testing connection ops"
(let [cfg (->cfg schema)
conn (sh/open cfg)]
(t/testing "Conn has correct spec/schema information"
(t/is (set/subset? #{::foo ::bar ::baz}
(set (sh/enumerate-specs conn)))))
(t/testing "Testing put/get/has? on values"
(let [v1 (sgen/generate foo-gen)
r1 (sh/put-spec conn ::foo v1)
v2 (sgen/generate foo-gen)
r2 (sh/put-spec conn ::foo v2)]
(t/is (= v1 (sh/get-spec conn ::foo r1)))
(t/is (sh/has? conn ::foo r1))
(t/is (= v2 (sh/get-spec conn ::foo r2)))
(t/is (sh/has? conn ::foo r2))
(t/is (set/subset? #{r1 r2} (set (sh/enumerate-spec conn ::foo))))
(t/is (thrown? AssertionError
(sh/put-spec conn ::foo r1 (sgen/generate foo-gen))))
(t/is (>= 2 (sh/count-spec conn ::foo)))))
(t/testing "Testing put/get on records"
(let [b1 (sgen/generate baz-gen)
b2 (sgen/generate baz-gen)
bi1 (sh/put-spec conn ::baz b1)]
(t/is (= b1 (sh/get-spec conn ::baz bi1)))
(t/is (sh/has? conn ::baz bi1))
(t/is (some #{bi1} (sh/enumerate-spec conn ::baz)))
Upserts should work
(sh/put-spec conn ::baz bi1 b2)
(t/is (= b2 (sh/get-spec conn ::baz bi1)))
(t/is (some #{bi1} (sh/enumerate-spec conn ::baz)))))))))
(defn value-rel-tests [->cfg]
(let [foo-gen (s/gen ::foo)
baz-gen (s/gen ::baz)
conn (sh/open (->cfg schema))]
(tc/quick-check 2000
(prop/for-all [baz baz-gen]
(let [the-foo (:foo baz)
foo-id (sh/put-spec conn ::foo the-foo)
baz-id (sh/put-spec conn ::baz baz)]
(t/is foo-id)
(t/is baz-id)
(t/is (some #{foo-id} (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (some #{baz-id} (sh/get-rel conn [::foo ::baz] foo-id)))
(check-forwards-backwards-rels conn))))))
(defn record-rel-tests [->cfg]
(let [foo-gen (s/gen ::foo)
baz-gen (s/gen ::baz)
conn (sh/open (->cfg schema))]
(tc/quick-check 2000
(prop/for-all [baz baz-gen
baz' baz-gen]
(let [the-foo (:foo baz)
the-foo' (:foo baz')
foo-id (sh/put-spec conn ::foo the-foo)
baz-id (sh/put-spec conn ::baz baz)
foo-id' (sh/put-spec conn ::foo the-foo')]
(t/is foo-id)
(t/is baz-id)
(t/is (some #(= % foo-id) (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (some #(= % baz-id) (sh/get-rel conn [::foo ::baz] foo-id)))
(sh/put-spec conn ::baz baz-id baz')
(when (not= the-foo the-foo')
(t/is (not-any? #{foo-id} (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (not-any? #{baz-id} (sh/get-rel conn [::foo ::baz] foo-id))))
(t/is (some #{foo-id'} (sh/get-rel conn [::baz ::foo] baz-id)))
(t/is (some #{baz-id} (sh/get-rel conn [::foo ::baz] foo-id')))
(t/is (= (sh/count-rel conn [::baz ::foo])
(sh/count-rel conn [::foo ::baz])))
(check-forwards-backwards-rels conn))))))
(defn rel-tests [->cfg]
(value-rel-tests ->cfg)
(record-rel-tests ->cfg))
(defn persistence-tests [->cfg]
conn (sh/open (->cfg schema))
_ (sh/put-spec conn ::baz {:foo "hey" :bar "there"})
s1 (sh/enumerate-specs conn)
r1 (sh/enumerate-spec conn ::foo)
foo-id (last r1)
_ (sh/flush conn)
_ (sh/close conn)
conn (sh/open (->cfg schema))
_ (t/is (= s1 (sh/enumerate-specs conn)))
_ (t/is (= r1 (sh/enumerate-spec conn ::foo)))
_ (t/is (= "hey" (sh/get-spec conn ::foo foo-id)))]))
(defn common-tests
"Takes a ctor of fn [schema] -> cfg, applies it and opens the resulting config twice.
Runs the example usage session in the README against the computed config."
[->cfg]
(schema-migrate-tests ->cfg)
(put-get-enumerate-example-tests ->cfg)
(rel-tests ->cfg)
(persistence-tests ->cfg))
|
e18a1665d1fd76ea26c06020c6a1eacd363d9e6b3ae341774294e892b6d704f8 | maranget/hevea | simpleRope.ml | (***********************************************************************)
(* *)
(* HEVEA *)
(* *)
, , projet ,
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Printf
exception Out_of_bounds
module type Config = sig
val small_length : int
end
module Make(C:Config) = struct
open C
(**********)
(* Basics *)
(**********)
type t =
| Str of string
| App of t * t * int (* String length *)
let length = function
| Str s -> String.length s
| App (_,_,len) -> len
let of_string s = Str s
let singleton c = of_string (String.make 1 c)
let empty = of_string ""
(**********)
(* Append *)
(**********)
let app r1 r2 = match r1,r2 with
| Str "",t | t,Str "" -> t
| Str s1, Str s2
when String.length s1 < small_length && String.length s2 < small_length ->
Str (s1^s2)
| App (t1,Str s1,len), Str s2
when String.length s1 < small_length && String.length s2 < small_length ->
App (t1,Str (s1^s2),len+String.length s2)
| Str s1,App (Str s2,t2,len)
when String.length s1 < small_length && String.length s2 < small_length ->
App (Str (s1^s2),t2,len+String.length s1)
| _,_ ->
App (r1,r2,length r1+length r2)
let append r1 r2 = app r1 r2
let rec app_string r s slen = match r with
| Str rs ->
if String.length rs < small_length then Str (rs ^ s)
else raise Exit
| App (r1,r2,len) ->
let r2 = app_string r2 s slen in
App (r1,r2,len+slen)
let append_string r s =
let slen = String.length s in
if slen < small_length then
try app_string r s slen
with Exit -> App (r,Str s,length r+slen)
else App (r,Str s,length r+slen)
let sc2c s len c =
let b = Bytes.create (len+1) in
Bytes.blit_string s 0 b 0 len ;
Bytes.set b len c ;
Bytes.unsafe_to_string b
let rec app_char r c = match r with
| Str s ->
let len = String.length s in
if len < small_length then begin
Str (sc2c s len c)
end else
raise Exit
| App (r1,r2,len) ->
let r2 = app_char r2 c in
App (r1,r2,len+1)
let append_char r c =
try app_char r c
with Exit -> App (r,Str (String.make 1 c),length r+1)
(*************)
(* Substring *)
(*************)
assumption : 0 < = start < stop < = )
let rec mksub start stop t =
if start = 0 && stop = length t then t
else match t with
| Str s -> Str (String.sub s start (stop-start))
| App (t1, t2, _) ->
let n1 = length t1 in
if stop <= n1 then mksub start stop t1
else if start >= n1 then mksub (start-n1) (stop-n1) t2
else app (mksub start n1 t1) (mksub 0 (stop-n1) t2)
let sub t ofs len =
let stop = ofs + len in
if ofs < 0 || len < 0 || stop > length t then raise Out_of_bounds;
if len = 0 then empty else mksub ofs stop t
(***********************)
(* Get a char by index *)
(***********************)
let rec get_rec t i = match t with
| Str s -> String.unsafe_get s i
| App (t1, t2, _) ->
let n1 = length t1 in
if i < n1 then get_rec t1 i else get_rec t2 (i - n1)
let get t i =
if i < 0 || i >= length t then raise Out_of_bounds;
get_rec t i
(***********)
(* Iterate *)
(***********)
let iter_string f s =
for k=0 to String.length s-1 do
f (String.unsafe_get s k)
done
let rec iter_rec f = function
| Str s -> iter_string f s
| App (t1,t2,_) ->
iter_rec f t1 ;
iter_rec f t2
let iter f t = iter_rec f t
(**********)
(* Output *)
(**********)
let rec output chan = function
| Str s -> output_string chan s
| App (t1,t2,_) -> output chan t1 ; output chan t2
let rec debug_rec indent chan = function
| Str s ->
fprintf chan "%s\"%a\"\n" indent output_string s
| App (t1,t2,_) ->
let indent2 = indent ^ " " in
fprintf chan "%s[\n" indent ;
debug_rec indent2 chan t1 ;
debug_rec indent2 chan t2 ;
fprintf chan "%s]\n" indent ;
()
let debug = debug_rec ""
(*************)
(* To string *)
(*************)
let rec blit t buff pos = match t with
| Str s ->
Bytes.blit_string s 0 buff pos (String.length s)
| App (t1,t2,_) ->
blit t1 buff pos ;
blit t2 buff (pos+length t1)
let to_string t = match t with
| Str s -> s
| App (_,_,len) ->
let buff = Bytes.create len in
blit t buff 0 ;
Bytes.unsafe_to_string buff
(***********************)
(* To list (of string) *)
(***********************)
let rec do_to_list k = function
| Str s -> if String.length s > 0 then (s::k) else k
| App (t1,t2,_) ->
let k = do_to_list k t2 in
do_to_list k t1
let to_list t = do_to_list [] t
let to_list_append t k = do_to_list k t
(*******************)
(* Index functions *)
(*******************)
let rec index_from r i c = match r with
| Str s -> String.index_from s i c
| App (t1,t2,_) ->
let n1 = length t1 in
if i < n1 then
try index_from t1 i c
with Not_found -> index_from t2 0 c + n1
else index_from t2 (i-n1) c
let index r c =
try index_from r 0 c
with e ->
eprintf "SimpleRope.index failed c='%c'\n" c ;
debug stderr r ;
raise e
let rec rindex_from r i c = match r with
| Str s -> String.rindex_from s i c
| App (t1,t2,_) ->
let n1 = length t1 in
if i < n1 then rindex_from t1 i c
else
try rindex_from t2 (i-n1) c + n1
with Not_found -> rindex_from t1 (n1-1) c
let rindex r c = rindex_from r (length r-1) c
(* Erase end according to predicate *)
let erase t pred =
let rec do_rec t = match t with
| Str s ->
let len = String.length s in
let rec find_no k =
if k <= 0 then k
else
let c = String.unsafe_get s (k-1) in
if pred c then find_no (k-1)
else k in
let k_lst = find_no len in
if k_lst = len then t
else Str (String.sub s 0 len)
| App (t1,t2,_) ->
let t2 = do_rec t2 in
if t2 = empty then do_rec t1
else append t1 t2 in
do_rec t
end
| null | https://raw.githubusercontent.com/maranget/hevea/226eac8c506f82a600d453492fbc1b9784dd865f/simpleRope.ml | ocaml | *********************************************************************
HEVEA
*********************************************************************
********
Basics
********
String length
********
Append
********
***********
Substring
***********
*********************
Get a char by index
*********************
*********
Iterate
*********
********
Output
********
***********
To string
***********
*********************
To list (of string)
*********************
*****************
Index functions
*****************
Erase end according to predicate | , , projet ,
Copyright 2012 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Printf
exception Out_of_bounds
module type Config = sig
val small_length : int
end
module Make(C:Config) = struct
open C
type t =
| Str of string
let length = function
| Str s -> String.length s
| App (_,_,len) -> len
let of_string s = Str s
let singleton c = of_string (String.make 1 c)
let empty = of_string ""
let app r1 r2 = match r1,r2 with
| Str "",t | t,Str "" -> t
| Str s1, Str s2
when String.length s1 < small_length && String.length s2 < small_length ->
Str (s1^s2)
| App (t1,Str s1,len), Str s2
when String.length s1 < small_length && String.length s2 < small_length ->
App (t1,Str (s1^s2),len+String.length s2)
| Str s1,App (Str s2,t2,len)
when String.length s1 < small_length && String.length s2 < small_length ->
App (Str (s1^s2),t2,len+String.length s1)
| _,_ ->
App (r1,r2,length r1+length r2)
let append r1 r2 = app r1 r2
let rec app_string r s slen = match r with
| Str rs ->
if String.length rs < small_length then Str (rs ^ s)
else raise Exit
| App (r1,r2,len) ->
let r2 = app_string r2 s slen in
App (r1,r2,len+slen)
let append_string r s =
let slen = String.length s in
if slen < small_length then
try app_string r s slen
with Exit -> App (r,Str s,length r+slen)
else App (r,Str s,length r+slen)
let sc2c s len c =
let b = Bytes.create (len+1) in
Bytes.blit_string s 0 b 0 len ;
Bytes.set b len c ;
Bytes.unsafe_to_string b
let rec app_char r c = match r with
| Str s ->
let len = String.length s in
if len < small_length then begin
Str (sc2c s len c)
end else
raise Exit
| App (r1,r2,len) ->
let r2 = app_char r2 c in
App (r1,r2,len+1)
let append_char r c =
try app_char r c
with Exit -> App (r,Str (String.make 1 c),length r+1)
assumption : 0 < = start < stop < = )
let rec mksub start stop t =
if start = 0 && stop = length t then t
else match t with
| Str s -> Str (String.sub s start (stop-start))
| App (t1, t2, _) ->
let n1 = length t1 in
if stop <= n1 then mksub start stop t1
else if start >= n1 then mksub (start-n1) (stop-n1) t2
else app (mksub start n1 t1) (mksub 0 (stop-n1) t2)
let sub t ofs len =
let stop = ofs + len in
if ofs < 0 || len < 0 || stop > length t then raise Out_of_bounds;
if len = 0 then empty else mksub ofs stop t
let rec get_rec t i = match t with
| Str s -> String.unsafe_get s i
| App (t1, t2, _) ->
let n1 = length t1 in
if i < n1 then get_rec t1 i else get_rec t2 (i - n1)
let get t i =
if i < 0 || i >= length t then raise Out_of_bounds;
get_rec t i
let iter_string f s =
for k=0 to String.length s-1 do
f (String.unsafe_get s k)
done
let rec iter_rec f = function
| Str s -> iter_string f s
| App (t1,t2,_) ->
iter_rec f t1 ;
iter_rec f t2
let iter f t = iter_rec f t
let rec output chan = function
| Str s -> output_string chan s
| App (t1,t2,_) -> output chan t1 ; output chan t2
let rec debug_rec indent chan = function
| Str s ->
fprintf chan "%s\"%a\"\n" indent output_string s
| App (t1,t2,_) ->
let indent2 = indent ^ " " in
fprintf chan "%s[\n" indent ;
debug_rec indent2 chan t1 ;
debug_rec indent2 chan t2 ;
fprintf chan "%s]\n" indent ;
()
let debug = debug_rec ""
let rec blit t buff pos = match t with
| Str s ->
Bytes.blit_string s 0 buff pos (String.length s)
| App (t1,t2,_) ->
blit t1 buff pos ;
blit t2 buff (pos+length t1)
let to_string t = match t with
| Str s -> s
| App (_,_,len) ->
let buff = Bytes.create len in
blit t buff 0 ;
Bytes.unsafe_to_string buff
let rec do_to_list k = function
| Str s -> if String.length s > 0 then (s::k) else k
| App (t1,t2,_) ->
let k = do_to_list k t2 in
do_to_list k t1
let to_list t = do_to_list [] t
let to_list_append t k = do_to_list k t
let rec index_from r i c = match r with
| Str s -> String.index_from s i c
| App (t1,t2,_) ->
let n1 = length t1 in
if i < n1 then
try index_from t1 i c
with Not_found -> index_from t2 0 c + n1
else index_from t2 (i-n1) c
let index r c =
try index_from r 0 c
with e ->
eprintf "SimpleRope.index failed c='%c'\n" c ;
debug stderr r ;
raise e
let rec rindex_from r i c = match r with
| Str s -> String.rindex_from s i c
| App (t1,t2,_) ->
let n1 = length t1 in
if i < n1 then rindex_from t1 i c
else
try rindex_from t2 (i-n1) c + n1
with Not_found -> rindex_from t1 (n1-1) c
let rindex r c = rindex_from r (length r-1) c
let erase t pred =
let rec do_rec t = match t with
| Str s ->
let len = String.length s in
let rec find_no k =
if k <= 0 then k
else
let c = String.unsafe_get s (k-1) in
if pred c then find_no (k-1)
else k in
let k_lst = find_no len in
if k_lst = len then t
else Str (String.sub s 0 len)
| App (t1,t2,_) ->
let t2 = do_rec t2 in
if t2 = empty then do_rec t1
else append t1 t2 in
do_rec t
end
|
5ad7a8fc08e713626c9889e4fb4f16fd7475394773bb0b9ee53315e3cd786cb0 | input-output-hk/cardano-addresses | Utils.hs | # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
module Test.Utils
( cli
, describeCmd
, validateJSON
, SchemaRef
) where
import Prelude
import Data.String
( IsString )
import Data.Text
( Text )
#ifdef HJSONSCHEMA
import JSONSchema.Draft4
( Schema (..)
, SchemaWithURI (..)
, checkSchema
, emptySchema
, referencesViaFilesystem
)
#endif
import System.Environment
( lookupEnv )
import System.Process
( readProcess, readProcessWithExitCode )
import Test.Hspec
( Spec, SpecWith, describe, runIO )
import qualified Data.Aeson as Json
--
-- cli
--
class CommandLine output where
cli :: [String]
-- ^ arguments
-> String
^ stdin
-> IO output
-- ^ output, either stdout or (stdout, stderr)
instance CommandLine String where
cli args input = do
(exe', args') <- getWrappedCLI args
readProcess exe' args' input
instance CommandLine (String, String) where
cli args input = do
(exe', args') <- getWrappedCLI args
dropFirst <$> readProcessWithExitCode exe' args' input
where
dropFirst (_,b,c) = (b, c)
exe :: String
exe = "cardano-address"
-- | Return the exe name and args for a CLI invocation.
For , the cardano - address CLI must be executed under nodejs .
getWrappedCLI :: [String] -> IO (FilePath, [String])
getWrappedCLI args = maybe (exe, args) wrap <$> lookupJsExe
where
lookupJsExe = fmap allJs <$> lookupEnv "CARDANO_ADDRESSES_CLI"
allJs = (<> ("/" <> exe <> ".jsexe/all.js"))
wrap jsExe = ("node", (jsExe:args))
--
-- describeCmd
--
-- | Wrap HSpec 'describe' into a friendly command description. So that, we get
-- a very satisfying result visually from running the tests, and can inspect
-- what each command help text looks like.
describeCmd :: [String] -> SpecWith () -> Spec
describeCmd cmd spec = do
title <- runIO $ cli (cmd ++ ["--help"]) ""
describe title spec
--
-- JSON Schema Validation
--
newtype SchemaRef = SchemaRef
{ getSchemaRef :: Text
} deriving (Show, IsString)
validateJSON :: SchemaRef -> Json.Value -> IO [String]
#ifdef HJSONSCHEMA
validateJSON (SchemaRef ref) value = do
let schema = SchemaWithURI (emptySchema { _schemaRef = Just ref }) Nothing
refs <- unsafeIO =<< referencesViaFilesystem schema
validate <- unsafeIO (checkSchema refs schema)
pure $ map show $ validate value
where
unsafeIO :: Show e => Either e a -> IO a
unsafeIO = either (fail . show) pure
#else
validateJSON _ _ = pure []
#endif
| null | https://raw.githubusercontent.com/input-output-hk/cardano-addresses/d22a9aa986391642d4fc398c84305c42d3c77c34/command-line/test/Test/Utils.hs | haskell |
cli
^ arguments
^ output, either stdout or (stdout, stderr)
| Return the exe name and args for a CLI invocation.
describeCmd
| Wrap HSpec 'describe' into a friendly command description. So that, we get
a very satisfying result visually from running the tests, and can inspect
what each command help text looks like.
JSON Schema Validation
| # LANGUAGE CPP #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
module Test.Utils
( cli
, describeCmd
, validateJSON
, SchemaRef
) where
import Prelude
import Data.String
( IsString )
import Data.Text
( Text )
#ifdef HJSONSCHEMA
import JSONSchema.Draft4
( Schema (..)
, SchemaWithURI (..)
, checkSchema
, emptySchema
, referencesViaFilesystem
)
#endif
import System.Environment
( lookupEnv )
import System.Process
( readProcess, readProcessWithExitCode )
import Test.Hspec
( Spec, SpecWith, describe, runIO )
import qualified Data.Aeson as Json
class CommandLine output where
cli :: [String]
-> String
^ stdin
-> IO output
instance CommandLine String where
cli args input = do
(exe', args') <- getWrappedCLI args
readProcess exe' args' input
instance CommandLine (String, String) where
cli args input = do
(exe', args') <- getWrappedCLI args
dropFirst <$> readProcessWithExitCode exe' args' input
where
dropFirst (_,b,c) = (b, c)
exe :: String
exe = "cardano-address"
For , the cardano - address CLI must be executed under nodejs .
getWrappedCLI :: [String] -> IO (FilePath, [String])
getWrappedCLI args = maybe (exe, args) wrap <$> lookupJsExe
where
lookupJsExe = fmap allJs <$> lookupEnv "CARDANO_ADDRESSES_CLI"
allJs = (<> ("/" <> exe <> ".jsexe/all.js"))
wrap jsExe = ("node", (jsExe:args))
describeCmd :: [String] -> SpecWith () -> Spec
describeCmd cmd spec = do
title <- runIO $ cli (cmd ++ ["--help"]) ""
describe title spec
newtype SchemaRef = SchemaRef
{ getSchemaRef :: Text
} deriving (Show, IsString)
validateJSON :: SchemaRef -> Json.Value -> IO [String]
#ifdef HJSONSCHEMA
validateJSON (SchemaRef ref) value = do
let schema = SchemaWithURI (emptySchema { _schemaRef = Just ref }) Nothing
refs <- unsafeIO =<< referencesViaFilesystem schema
validate <- unsafeIO (checkSchema refs schema)
pure $ map show $ validate value
where
unsafeIO :: Show e => Either e a -> IO a
unsafeIO = either (fail . show) pure
#else
validateJSON _ _ = pure []
#endif
|
deff6be8455eb62c1bfe464a32a73ffaae4fd736f36e54de96cde15d169ccd14 | reactiveml/rml | lwt_js_events.mli | Js_of_ocaml library
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2010 Vincent Balat
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
(** Programming mouse or keyboard events handlers using Lwt *)
*
Reminder :
Event capturing starts with the outer most element in the DOM and
works inwards to the HTML element the event took place on ( capture phase )
and then out again ( bubbling phase ) .
Reminder:
Event capturing starts with the outer most element in the DOM and
works inwards to the HTML element the event took place on (capture phase)
and then out again (bubbling phase).
*)
* { 2 Create Lwt threads for events }
* [ make_event ev target ] creates a Lwt thread that waits
for the event [ ev ] to happen on [ target ] ( once ) .
This thread is cancellable using
{ % < < a_api project="lwt " | val Lwt.cancel > > % } .
If you set the optional parameter [ ~use_capture : true ] ,
the event will be caught during the capture phase ,
otherwise it is caught during the bubbling phase
( default ) .
for the event [ev] to happen on [target] (once).
This thread is cancellable using
{% <<a_api project="lwt" | val Lwt.cancel>> %}.
If you set the optional parameter [~use_capture:true],
the event will be caught during the capture phase,
otherwise it is caught during the bubbling phase
(default).
*)
val make_event :
(#Dom_html.event as 'a) Js.t Dom_html.Event.typ ->
?use_capture:bool -> #Dom_html.eventTarget Js.t -> 'a Js.t Lwt.t
* [ seq_loop ( make_event ev ) target handler ] creates a looping Lwt
thread that waits for the event [ ev ] to happen on [ target ] , then
execute handler , and start again waiting for the event . Events
happening during the execution of the handler are ignored . See
[ async_loop ] and [ buffered_loop ] for alternative semantics .
For example , the [ clicks ] function below is defined by :
[ let clicks ? use_capture t = seq_loop click ? use_capture t ]
The thread returned is cancellable using
{ % < < a_api project="lwt " | val Lwt.cancel > > % } .
In order for the loop thread to be canceled from within the handler ,
the latter receives the former as its second parameter .
By default , cancelling the loop will not cancel the potential
currently running handler . This behaviour can be changed by
setting the [ cancel_handler ] parameter to true .
thread that waits for the event [ev] to happen on [target], then
execute handler, and start again waiting for the event. Events
happening during the execution of the handler are ignored. See
[async_loop] and [buffered_loop] for alternative semantics.
For example, the [clicks] function below is defined by:
[let clicks ?use_capture t = seq_loop click ?use_capture t]
The thread returned is cancellable using
{% <<a_api project="lwt" | val Lwt.cancel>> %}.
In order for the loop thread to be canceled from within the handler,
the latter receives the former as its second parameter.
By default, cancelling the loop will not cancel the potential
currently running handler. This behaviour can be changed by
setting the [cancel_handler] parameter to true.
*)
val seq_loop :
(?use_capture:bool -> 'target -> 'event Lwt.t) ->
?cancel_handler:bool ->
?use_capture:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
(** [async_loop] is similar to [seq_loop], but each handler runs
independently. No event is thus missed, but since several
instances of the handler can be run concurrently, it is up to the
programmer to ensure that they interact correctly.
Cancelling the loop will not cancel the potential currently running
handlers.
*)
val async_loop :
(?use_capture:bool -> 'target -> 'event Lwt.t) ->
?use_capture:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
* [ buffered_loop ] is similar to [ seq_loop ] , but any event that
occurs during an execution of the handler is queued instead of
being ingnored .
No event is thus missed , but there can be a non predictible delay
between its trigger and its treatment . It is thus a good idea to
use this loop with handlers whose running time is short , so the
memorized event still makes sense when the handler is eventually
executed . It is also up to the programmer to ensure that event
handlers terminate so the queue will eventually be emptied .
By default , cancelling the loop will not cancel the ( potential )
currently running handler , but any other queued event will be
dropped . This behaviour can be customized using the two optional
parameters [ cancel_handler ] and [ cancel_queue ] .
occurs during an execution of the handler is queued instead of
being ingnored.
No event is thus missed, but there can be a non predictible delay
between its trigger and its treatment. It is thus a good idea to
use this loop with handlers whose running time is short, so the
memorized event still makes sense when the handler is eventually
executed. It is also up to the programmer to ensure that event
handlers terminate so the queue will eventually be emptied.
By default, cancelling the loop will not cancel the (potential)
currently running handler, but any other queued event will be
dropped. This behaviour can be customized using the two optional
parameters [cancel_handler] and [cancel_queue].
*)
val buffered_loop :
(?use_capture:bool -> 'target -> 'event Lwt.t) ->
?cancel_handler:bool -> ?cancel_queue:bool ->
?use_capture:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
(** [async t] records a thread to be executed later.
It is implemented by calling yield, then Lwt.async.
This is useful if you want to create a new event listener
when you are inside an event handler.
This avoids the current event to be catched by the new event handler
(if it propagates).
*)
val async : (unit -> 'a Lwt.t) -> unit
* { 2 Predefined functions for some types of events }
val click :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val dblclick :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mousedown :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mouseup :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mouseover :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mousemove :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mouseout :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val keypress :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t
val keydown :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t
val keyup :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t
val input :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val change :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val dragstart :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragend :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragenter :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragover :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragleave :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val drag :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val drop :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val focus :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val blur :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val scroll :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val submit :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val select :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
(** This function returns the event,
together with the numbers of ticks the mouse wheel moved.
Positive means down or right.
This interface is compatible with all (recent) browsers. *)
val mousewheel :
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t * (int * int)) Lwt.t
val touchstart :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
val touchmove :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
val touchend :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
val touchcancel :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
(** Returns when a CSS transition terminates on the element. *)
val transitionend : #Dom_html.eventTarget Js.t -> unit Lwt.t
val load : ?use_capture:bool ->
#Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t
val error : ?use_capture:bool ->
#Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t
val abort : ?use_capture:bool ->
#Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t
val clicks :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dblclicks :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mousedowns :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mouseups :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mouseovers :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mousemoves :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mouseouts :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val keypresses :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val keydowns :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val keyups :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val inputs :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val changes :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragstarts :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragends :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragenters :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragovers :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragleaves :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val drags :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val drops :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mousewheels :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
((Dom_html.mouseEvent Js.t * (int * int)) -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchstarts :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchmoves :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchends :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchcancels :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val focuses :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val blurs :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val scrolls :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val submits :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val selects :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
* Returns when a repaint of the window by the browser starts .
( see JS method [ window.requestAnimationFrame ] )
(see JS method [window.requestAnimationFrame]) *)
val request_animation_frame : unit -> unit Lwt.t
(** Returns when the page is loaded *)
val onload : unit -> Dom_html.event Js.t Lwt.t
val onbeforeunload : unit -> Dom_html.event Js.t Lwt.t
val onresize : unit -> Dom_html.event Js.t Lwt.t
val onpopstate : unit -> Dom_html.event Js.t Lwt.t
val onhashchange : unit -> Dom_html.event Js.t Lwt.t
val onresizes :
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val onpopstates :
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val onhashchanges :
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
| null | https://raw.githubusercontent.com/reactiveml/rml/d178d49ed923290fa7eee642541bdff3ee90b3b4/toplevel-alt/js/js-of-ocaml/lib/lwt_js_events.mli | ocaml | * Programming mouse or keyboard events handlers using Lwt
* [async_loop] is similar to [seq_loop], but each handler runs
independently. No event is thus missed, but since several
instances of the handler can be run concurrently, it is up to the
programmer to ensure that they interact correctly.
Cancelling the loop will not cancel the potential currently running
handlers.
* [async t] records a thread to be executed later.
It is implemented by calling yield, then Lwt.async.
This is useful if you want to create a new event listener
when you are inside an event handler.
This avoids the current event to be catched by the new event handler
(if it propagates).
* This function returns the event,
together with the numbers of ticks the mouse wheel moved.
Positive means down or right.
This interface is compatible with all (recent) browsers.
* Returns when a CSS transition terminates on the element.
* Returns when the page is loaded | Js_of_ocaml library
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* /
* Copyright (C) 2010 Vincent Balat
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
*
Reminder :
Event capturing starts with the outer most element in the DOM and
works inwards to the HTML element the event took place on ( capture phase )
and then out again ( bubbling phase ) .
Reminder:
Event capturing starts with the outer most element in the DOM and
works inwards to the HTML element the event took place on (capture phase)
and then out again (bubbling phase).
*)
* { 2 Create Lwt threads for events }
* [ make_event ev target ] creates a Lwt thread that waits
for the event [ ev ] to happen on [ target ] ( once ) .
This thread is cancellable using
{ % < < a_api project="lwt " | val Lwt.cancel > > % } .
If you set the optional parameter [ ~use_capture : true ] ,
the event will be caught during the capture phase ,
otherwise it is caught during the bubbling phase
( default ) .
for the event [ev] to happen on [target] (once).
This thread is cancellable using
{% <<a_api project="lwt" | val Lwt.cancel>> %}.
If you set the optional parameter [~use_capture:true],
the event will be caught during the capture phase,
otherwise it is caught during the bubbling phase
(default).
*)
val make_event :
(#Dom_html.event as 'a) Js.t Dom_html.Event.typ ->
?use_capture:bool -> #Dom_html.eventTarget Js.t -> 'a Js.t Lwt.t
* [ seq_loop ( make_event ev ) target handler ] creates a looping Lwt
thread that waits for the event [ ev ] to happen on [ target ] , then
execute handler , and start again waiting for the event . Events
happening during the execution of the handler are ignored . See
[ async_loop ] and [ buffered_loop ] for alternative semantics .
For example , the [ clicks ] function below is defined by :
[ let clicks ? use_capture t = seq_loop click ? use_capture t ]
The thread returned is cancellable using
{ % < < a_api project="lwt " | val Lwt.cancel > > % } .
In order for the loop thread to be canceled from within the handler ,
the latter receives the former as its second parameter .
By default , cancelling the loop will not cancel the potential
currently running handler . This behaviour can be changed by
setting the [ cancel_handler ] parameter to true .
thread that waits for the event [ev] to happen on [target], then
execute handler, and start again waiting for the event. Events
happening during the execution of the handler are ignored. See
[async_loop] and [buffered_loop] for alternative semantics.
For example, the [clicks] function below is defined by:
[let clicks ?use_capture t = seq_loop click ?use_capture t]
The thread returned is cancellable using
{% <<a_api project="lwt" | val Lwt.cancel>> %}.
In order for the loop thread to be canceled from within the handler,
the latter receives the former as its second parameter.
By default, cancelling the loop will not cancel the potential
currently running handler. This behaviour can be changed by
setting the [cancel_handler] parameter to true.
*)
val seq_loop :
(?use_capture:bool -> 'target -> 'event Lwt.t) ->
?cancel_handler:bool ->
?use_capture:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val async_loop :
(?use_capture:bool -> 'target -> 'event Lwt.t) ->
?use_capture:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
* [ buffered_loop ] is similar to [ seq_loop ] , but any event that
occurs during an execution of the handler is queued instead of
being ingnored .
No event is thus missed , but there can be a non predictible delay
between its trigger and its treatment . It is thus a good idea to
use this loop with handlers whose running time is short , so the
memorized event still makes sense when the handler is eventually
executed . It is also up to the programmer to ensure that event
handlers terminate so the queue will eventually be emptied .
By default , cancelling the loop will not cancel the ( potential )
currently running handler , but any other queued event will be
dropped . This behaviour can be customized using the two optional
parameters [ cancel_handler ] and [ cancel_queue ] .
occurs during an execution of the handler is queued instead of
being ingnored.
No event is thus missed, but there can be a non predictible delay
between its trigger and its treatment. It is thus a good idea to
use this loop with handlers whose running time is short, so the
memorized event still makes sense when the handler is eventually
executed. It is also up to the programmer to ensure that event
handlers terminate so the queue will eventually be emptied.
By default, cancelling the loop will not cancel the (potential)
currently running handler, but any other queued event will be
dropped. This behaviour can be customized using the two optional
parameters [cancel_handler] and [cancel_queue].
*)
val buffered_loop :
(?use_capture:bool -> 'target -> 'event Lwt.t) ->
?cancel_handler:bool -> ?cancel_queue:bool ->
?use_capture:bool -> 'target -> ('event -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val async : (unit -> 'a Lwt.t) -> unit
* { 2 Predefined functions for some types of events }
val click :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val dblclick :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mousedown :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mouseup :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mouseover :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mousemove :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val mouseout :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.mouseEvent Js.t Lwt.t
val keypress :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t
val keydown :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t
val keyup :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.keyboardEvent Js.t Lwt.t
val input :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val change :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val dragstart :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragend :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragenter :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragover :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val dragleave :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val drag :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val drop :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.dragEvent Js.t Lwt.t
val focus :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val blur :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val scroll :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val submit :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val select :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.event Js.t Lwt.t
val mousewheel :
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t * (int * int)) Lwt.t
val touchstart :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
val touchmove :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
val touchend :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
val touchcancel :
?use_capture:bool ->
#Dom_html.eventTarget Js.t -> Dom_html.touchEvent Js.t Lwt.t
val transitionend : #Dom_html.eventTarget Js.t -> unit Lwt.t
val load : ?use_capture:bool ->
#Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t
val error : ?use_capture:bool ->
#Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t
val abort : ?use_capture:bool ->
#Dom_html.imageElement Js.t -> Dom_html.event Js.t Lwt.t
val clicks :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dblclicks :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mousedowns :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mouseups :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mouseovers :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mousemoves :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mouseouts :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.mouseEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val keypresses :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val keydowns :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val keyups :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.keyboardEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val inputs :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val changes :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragstarts :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragends :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragenters :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragovers :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val dragleaves :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val drags :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val drops :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.dragEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val mousewheels :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
((Dom_html.mouseEvent Js.t * (int * int)) -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchstarts :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchmoves :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchends :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val touchcancels :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.touchEvent Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val focuses :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val blurs :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val scrolls :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val submits :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val selects :
?cancel_handler:bool ->
?use_capture:bool ->
#Dom_html.eventTarget Js.t ->
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
* Returns when a repaint of the window by the browser starts .
( see JS method [ window.requestAnimationFrame ] )
(see JS method [window.requestAnimationFrame]) *)
val request_animation_frame : unit -> unit Lwt.t
val onload : unit -> Dom_html.event Js.t Lwt.t
val onbeforeunload : unit -> Dom_html.event Js.t Lwt.t
val onresize : unit -> Dom_html.event Js.t Lwt.t
val onpopstate : unit -> Dom_html.event Js.t Lwt.t
val onhashchange : unit -> Dom_html.event Js.t Lwt.t
val onresizes :
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val onpopstates :
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
val onhashchanges :
(Dom_html.event Js.t -> unit Lwt.t -> unit Lwt.t) -> unit Lwt.t
|
f7baf3a5071f1335fa4b28f1066024af1aca6c5b9a66071b08d27ca88168d6fd | mzuther/MoccaFaux | tray.clj | ;; MoccaFaux
;; =========
;; Adapt power management to changes in the environment
;;
Copyright ( c ) 2020 - 2021 ( / ) and
;; contributors
;;
;; This program and the accompanying materials are made available under
the terms of the Eclipse Public License 2.0 which is available at
;; -2.0.
;;
This Source Code may also be made available under the following
;; Secondary Licenses when the conditions for such availability set forth
in the Eclipse Public License , v. 2.0 are satisfied : GNU General
Public License as published by the Free Software Foundation , either
version 2 of the License , or ( at your option ) any later version , with
the GNU Classpath Exception which is available at
;; .
(ns de.mzuther.moccafaux.tray
(:require [de.mzuther.moccafaux.helpers :as helpers]
[clojure.java.io :as io]
[clj-systemtray.core :as tray])
(:gen-class))
(def current-icon (ref nil))
(defn handle-menu-click
"Handle clicks in the menu of a tray bar icon and print name of
corresponding menu item."
[event]
(let [item-name (.getActionCommand ^java.awt.event.ActionEvent event)]
(io! (newline)
(helpers/printfln "%s Click: %s"
(helpers/get-timestamp)
item-name)
(newline)
(helpers/print-line \-))
(condp = item-name
"Quit" (System/exit 0)
nil)))
(defn add-to-traybar
"Create tray icon with an attached menu and add it to the system's
tray bar. Add current task-states to menu and use icon located at
icon-resource-path.
Return instance of created TrayIcon class."
[task-states icon-resource-path]
(when (tray/tray-supported?)
(dosync
(when @current-icon
(tray/remove-tray-icon! @current-icon)
(ref-set current-icon nil))
(let [icon-url (io/resource icon-resource-path)
states (for [task-state task-states]
(str (-> task-state first name)
" -> "
(-> task-state second name)))
menu-items (concat [(tray/menu-item (helpers/get-application-and-version) handle-menu-click)
(tray/separator)]
(for [state (sort states)]
(tray/menu-item state handle-menu-click))
[(tray/separator)
(tray/menu-item "Quit" handle-menu-click)])
menu (apply tray/popup-menu menu-items)]
(ref-set current-icon (tray/make-tray-icon! icon-url menu))))))
| null | https://raw.githubusercontent.com/mzuther/MoccaFaux/c0f4ed8538a08d460c039140c412ca535223a707/src/de/mzuther/moccafaux/tray.clj | clojure | MoccaFaux
=========
Adapt power management to changes in the environment
contributors
This program and the accompanying materials are made available under
-2.0.
Secondary Licenses when the conditions for such availability set forth
. | Copyright ( c ) 2020 - 2021 ( / ) and
the terms of the Eclipse Public License 2.0 which is available at
This Source Code may also be made available under the following
in the Eclipse Public License , v. 2.0 are satisfied : GNU General
Public License as published by the Free Software Foundation , either
version 2 of the License , or ( at your option ) any later version , with
the GNU Classpath Exception which is available at
(ns de.mzuther.moccafaux.tray
(:require [de.mzuther.moccafaux.helpers :as helpers]
[clojure.java.io :as io]
[clj-systemtray.core :as tray])
(:gen-class))
(def current-icon (ref nil))
(defn handle-menu-click
"Handle clicks in the menu of a tray bar icon and print name of
corresponding menu item."
[event]
(let [item-name (.getActionCommand ^java.awt.event.ActionEvent event)]
(io! (newline)
(helpers/printfln "%s Click: %s"
(helpers/get-timestamp)
item-name)
(newline)
(helpers/print-line \-))
(condp = item-name
"Quit" (System/exit 0)
nil)))
(defn add-to-traybar
"Create tray icon with an attached menu and add it to the system's
tray bar. Add current task-states to menu and use icon located at
icon-resource-path.
Return instance of created TrayIcon class."
[task-states icon-resource-path]
(when (tray/tray-supported?)
(dosync
(when @current-icon
(tray/remove-tray-icon! @current-icon)
(ref-set current-icon nil))
(let [icon-url (io/resource icon-resource-path)
states (for [task-state task-states]
(str (-> task-state first name)
" -> "
(-> task-state second name)))
menu-items (concat [(tray/menu-item (helpers/get-application-and-version) handle-menu-click)
(tray/separator)]
(for [state (sort states)]
(tray/menu-item state handle-menu-click))
[(tray/separator)
(tray/menu-item "Quit" handle-menu-click)])
menu (apply tray/popup-menu menu-items)]
(ref-set current-icon (tray/make-tray-icon! icon-url menu))))))
|
592e95df724c9d73aa13bae51ebd58b61bcc701202de9c5db557dd7dfa9f33d0 | ocaml-multicore/ocaml-tsan | nativeint.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 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. *)
(* *)
(**************************************************************************)
* Processor - native integers .
This module provides operations on the type [ nativeint ] of
signed 32 - bit integers ( on 32 - bit platforms ) or
signed 64 - bit integers ( on 64 - bit platforms ) .
This integer type has exactly the same width as that of a
pointer type in the C compiler . All arithmetic operations over
[ nativeint ] are taken modulo 2{^32 } or 2{^64 } depending
on the word size of the architecture .
Performance notice : values of type [ nativeint ] occupy more memory
space than values of type [ int ] , and arithmetic operations on
[ nativeint ] are generally slower than those on [ int ] . Use [ nativeint ]
only when the application requires the extra bit of precision
over the [ int ] type .
Literals for native integers are suffixed by n :
{ [
let zero : nativeint = 0n
let one : nativeint = 1n
let m_one : nativeint = -1n
] }
This module provides operations on the type [nativeint] of
signed 32-bit integers (on 32-bit platforms) or
signed 64-bit integers (on 64-bit platforms).
This integer type has exactly the same width as that of a
pointer type in the C compiler. All arithmetic operations over
[nativeint] are taken modulo 2{^32} or 2{^64} depending
on the word size of the architecture.
Performance notice: values of type [nativeint] occupy more memory
space than values of type [int], and arithmetic operations on
[nativeint] are generally slower than those on [int]. Use [nativeint]
only when the application requires the extra bit of precision
over the [int] type.
Literals for native integers are suffixed by n:
{[
let zero: nativeint = 0n
let one: nativeint = 1n
let m_one: nativeint = -1n
]}
*)
val zero : nativeint
(** The native integer 0.*)
val one : nativeint
* The native integer 1 .
val minus_one : nativeint
(** The native integer -1.*)
external neg : nativeint -> nativeint = "%nativeint_neg"
(** Unary negation. *)
external add : nativeint -> nativeint -> nativeint = "%nativeint_add"
(** Addition. *)
external sub : nativeint -> nativeint -> nativeint = "%nativeint_sub"
(** Subtraction. *)
external mul : nativeint -> nativeint -> nativeint = "%nativeint_mul"
(** Multiplication. *)
external div : nativeint -> nativeint -> nativeint = "%nativeint_div"
* Integer division . This division rounds the real quotient of
its arguments towards zero , as specified for { ! Stdlib.(/ ) } .
@raise Division_by_zero if the second
argument is zero .
its arguments towards zero, as specified for {!Stdlib.(/)}.
@raise Division_by_zero if the second
argument is zero. *)
val unsigned_div : nativeint -> nativeint -> nativeint
* Same as { ! div } , except that arguments and result are interpreted as { e
unsigned } native integers .
@since 4.08
unsigned} native integers.
@since 4.08 *)
external rem : nativeint -> nativeint -> nativeint = "%nativeint_mod"
* Integer remainder . If [ y ] is not zero , the result
of [ x y ] satisfies the following properties :
[ Nativeint.zero < = x y < Nativeint.abs y ] and
[ x = Nativeint.add ( Nativeint.mul ( Nativeint.div x y ) y )
( x y ) ] .
If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] .
of [Nativeint.rem x y] satisfies the following properties:
[Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y] and
[x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y)
(Nativeint.rem x y)].
If [y = 0], [Nativeint.rem x y] raises [Division_by_zero]. *)
val unsigned_rem : nativeint -> nativeint -> nativeint
* Same as { ! rem } , except that arguments and result are interpreted as { e
unsigned } native integers .
@since 4.08
unsigned} native integers.
@since 4.08 *)
val succ : nativeint -> nativeint
(** Successor.
[Nativeint.succ x] is [Nativeint.add x Nativeint.one]. *)
val pred : nativeint -> nativeint
* Predecessor .
[ Nativeint.pred x ] is [ Nativeint.sub x Nativeint.one ] .
[Nativeint.pred x] is [Nativeint.sub x Nativeint.one]. *)
val abs : nativeint -> nativeint
(** [abs x] is the absolute value of [x]. On [min_int] this
is [min_int] itself and thus remains negative. *)
val size : int
* The size in bits of a native integer . This is equal to [ 32 ]
on a 32 - bit platform and to [ 64 ] on a 64 - bit platform .
on a 32-bit platform and to [64] on a 64-bit platform. *)
val max_int : nativeint
* The greatest representable native integer ,
either 2{^31 } - 1 on a 32 - bit platform ,
or 2{^63 } - 1 on a 64 - bit platform .
either 2{^31} - 1 on a 32-bit platform,
or 2{^63} - 1 on a 64-bit platform. *)
val min_int : nativeint
* The smallest representable native integer ,
either -2{^31 } on a 32 - bit platform ,
or -2{^63 } on a 64 - bit platform .
either -2{^31} on a 32-bit platform,
or -2{^63} on a 64-bit platform. *)
external logand : nativeint -> nativeint -> nativeint = "%nativeint_and"
(** Bitwise logical and. *)
external logor : nativeint -> nativeint -> nativeint = "%nativeint_or"
(** Bitwise logical or. *)
external logxor : nativeint -> nativeint -> nativeint = "%nativeint_xor"
(** Bitwise logical exclusive or. *)
val lognot : nativeint -> nativeint
(** Bitwise logical negation. *)
external shift_left : nativeint -> int -> nativeint = "%nativeint_lsl"
* [ Nativeint.shift_left x y ] shifts [ x ] to the left by [ y ] bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] ,
where [ bitsize ] is [ 32 ] on a 32 - bit platform and
[ 64 ] on a 64 - bit platform .
The result is unspecified if [y < 0] or [y >= bitsize],
where [bitsize] is [32] on a 32-bit platform and
[64] on a 64-bit platform. *)
external shift_right : nativeint -> int -> nativeint = "%nativeint_asr"
* [ Nativeint.shift_right x y ] shifts [ x ] to the right by [ y ] bits .
This is an arithmetic shift : the sign bit of [ x ] is replicated
and inserted in the vacated bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
This is an arithmetic shift: the sign bit of [x] is replicated
and inserted in the vacated bits.
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external shift_right_logical :
nativeint -> int -> nativeint = "%nativeint_lsr"
* [ Nativeint.shift_right_logical x y ] shifts [ x ] to the right
by [ y ] bits .
This is a logical shift : zeroes are inserted in the vacated bits
regardless of the sign of [ x ] .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
by [y] bits.
This is a logical shift: zeroes are inserted in the vacated bits
regardless of the sign of [x].
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external of_int : int -> nativeint = "%nativeint_of_int"
(** Convert the given integer (type [int]) to a native integer
(type [nativeint]). *)
external to_int : nativeint -> int = "%nativeint_to_int"
(** Convert the given native integer (type [nativeint]) to an
integer (type [int]). The high-order bit is lost during
the conversion. *)
val unsigned_to_int : nativeint -> int option
* Same as { ! to_int } , but interprets the argument as an { e unsigned } integer .
Returns [ None ] if the unsigned value of the argument can not fit into an
[ int ] .
@since 4.08
Returns [None] if the unsigned value of the argument cannot fit into an
[int].
@since 4.08 *)
external of_float : float -> nativeint
= "caml_nativeint_of_float" "caml_nativeint_of_float_unboxed"
[@@unboxed] [@@noalloc]
(** Convert the given floating-point number to a native integer,
discarding the fractional part (truncate towards 0).
If the truncated floating-point number is outside the range
\[{!Nativeint.min_int}, {!Nativeint.max_int}\], no exception is raised,
and an unspecified, platform-dependent integer is returned. *)
external to_float : nativeint -> float
= "caml_nativeint_to_float" "caml_nativeint_to_float_unboxed"
[@@unboxed] [@@noalloc]
(** Convert the given native integer to a floating-point number. *)
external of_int32 : int32 -> nativeint = "%nativeint_of_int32"
* Convert the given 32 - bit integer ( type [ int32 ] )
to a native integer .
to a native integer. *)
external to_int32 : nativeint -> int32 = "%nativeint_to_int32"
* Convert the given native integer to a
32 - bit integer ( type [ int32 ] ) . On 64 - bit platforms ,
the 64 - bit native integer is taken modulo 2{^32 } ,
i.e. the top 32 bits are lost . On 32 - bit platforms ,
the conversion is exact .
32-bit integer (type [int32]). On 64-bit platforms,
the 64-bit native integer is taken modulo 2{^32},
i.e. the top 32 bits are lost. On 32-bit platforms,
the conversion is exact. *)
external of_string : string -> nativeint = "caml_nativeint_of_string"
* Convert the given string to a native integer .
The string is read in decimal ( by default , or if the string
begins with [ 0u ] ) or in hexadecimal , octal or binary if the
string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively .
The [ 0u ] prefix reads the input as an unsigned integer in the range
[ [ 0 , 2*Nativeint.max_int+1 ] ] . If the input exceeds { ! Nativeint.max_int }
it is converted to the signed integer
[ + input - Nativeint.max_int - 1 ] .
@raise Failure if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ nativeint ] .
The string is read in decimal (by default, or if the string
begins with [0u]) or in hexadecimal, octal or binary if the
string begins with [0x], [0o] or [0b] respectively.
The [0u] prefix reads the input as an unsigned integer in the range
[[0, 2*Nativeint.max_int+1]]. If the input exceeds {!Nativeint.max_int}
it is converted to the signed integer
[Int64.min_int + input - Nativeint.max_int - 1].
@raise Failure if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [nativeint]. *)
val of_string_opt: string -> nativeint option
* Same as [ of_string ] , but return [ None ] instead of raising .
@since 4.05
@since 4.05 *)
val to_string : nativeint -> string
(** Return the string representation of its argument, in decimal. *)
type t = nativeint
(** An alias for the type of native integers. *)
val compare: t -> t -> int
* The comparison function for native integers , with the same specification as
{ ! Stdlib.compare } . Along with the type [ t ] , this function [ compare ]
allows the module [ Nativeint ] to be passed as argument to the functors
{ ! Set . Make } and { ! Map . Make } .
{!Stdlib.compare}. Along with the type [t], this function [compare]
allows the module [Nativeint] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
val unsigned_compare: t -> t -> int
* Same as { ! compare } , except that arguments are interpreted as { e unsigned }
native integers .
@since 4.08
native integers.
@since 4.08 *)
val equal: t -> t -> bool
* The equal function for native ints .
@since 4.03
@since 4.03 *)
val min: t -> t -> t
* Return the smaller of the two arguments .
@since 4.13
@since 4.13
*)
val max: t -> t -> t
* Return the greater of the two arguments .
@since 4.13
@since 4.13
*)
val seeded_hash : int -> t -> int
* A seeded hash function for native ints , with the same output value as
{ ! Hashtbl.seeded_hash } . This function allows this module to be passed as
argument to the functor { ! . MakeSeeded } .
@since 5.1
{!Hashtbl.seeded_hash}. This function allows this module to be passed as
argument to the functor {!Hashtbl.MakeSeeded}.
@since 5.1 *)
val hash : t -> int
* An unseeded hash function for native ints , with the same output value as
{ ! Hashtbl.hash } . This function allows this module to be passed as argument
to the functor { ! . Make } .
@since 5.1
{!Hashtbl.hash}. This function allows this module to be passed as argument
to the functor {!Hashtbl.Make}.
@since 5.1 *)
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/stdlib/nativeint.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* The native integer 0.
* The native integer -1.
* Unary negation.
* Addition.
* Subtraction.
* Multiplication.
* Successor.
[Nativeint.succ x] is [Nativeint.add x Nativeint.one].
* [abs x] is the absolute value of [x]. On [min_int] this
is [min_int] itself and thus remains negative.
* Bitwise logical and.
* Bitwise logical or.
* Bitwise logical exclusive or.
* Bitwise logical negation.
* Convert the given integer (type [int]) to a native integer
(type [nativeint]).
* Convert the given native integer (type [nativeint]) to an
integer (type [int]). The high-order bit is lost during
the conversion.
* Convert the given floating-point number to a native integer,
discarding the fractional part (truncate towards 0).
If the truncated floating-point number is outside the range
\[{!Nativeint.min_int}, {!Nativeint.max_int}\], no exception is raised,
and an unspecified, platform-dependent integer is returned.
* Convert the given native integer to a floating-point number.
* Return the string representation of its argument, in decimal.
* An alias for the type of native integers. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* Processor - native integers .
This module provides operations on the type [ nativeint ] of
signed 32 - bit integers ( on 32 - bit platforms ) or
signed 64 - bit integers ( on 64 - bit platforms ) .
This integer type has exactly the same width as that of a
pointer type in the C compiler . All arithmetic operations over
[ nativeint ] are taken modulo 2{^32 } or 2{^64 } depending
on the word size of the architecture .
Performance notice : values of type [ nativeint ] occupy more memory
space than values of type [ int ] , and arithmetic operations on
[ nativeint ] are generally slower than those on [ int ] . Use [ nativeint ]
only when the application requires the extra bit of precision
over the [ int ] type .
Literals for native integers are suffixed by n :
{ [
let zero : nativeint = 0n
let one : nativeint = 1n
let m_one : nativeint = -1n
] }
This module provides operations on the type [nativeint] of
signed 32-bit integers (on 32-bit platforms) or
signed 64-bit integers (on 64-bit platforms).
This integer type has exactly the same width as that of a
pointer type in the C compiler. All arithmetic operations over
[nativeint] are taken modulo 2{^32} or 2{^64} depending
on the word size of the architecture.
Performance notice: values of type [nativeint] occupy more memory
space than values of type [int], and arithmetic operations on
[nativeint] are generally slower than those on [int]. Use [nativeint]
only when the application requires the extra bit of precision
over the [int] type.
Literals for native integers are suffixed by n:
{[
let zero: nativeint = 0n
let one: nativeint = 1n
let m_one: nativeint = -1n
]}
*)
val zero : nativeint
val one : nativeint
* The native integer 1 .
val minus_one : nativeint
external neg : nativeint -> nativeint = "%nativeint_neg"
external add : nativeint -> nativeint -> nativeint = "%nativeint_add"
external sub : nativeint -> nativeint -> nativeint = "%nativeint_sub"
external mul : nativeint -> nativeint -> nativeint = "%nativeint_mul"
external div : nativeint -> nativeint -> nativeint = "%nativeint_div"
* Integer division . This division rounds the real quotient of
its arguments towards zero , as specified for { ! Stdlib.(/ ) } .
@raise Division_by_zero if the second
argument is zero .
its arguments towards zero, as specified for {!Stdlib.(/)}.
@raise Division_by_zero if the second
argument is zero. *)
val unsigned_div : nativeint -> nativeint -> nativeint
* Same as { ! div } , except that arguments and result are interpreted as { e
unsigned } native integers .
@since 4.08
unsigned} native integers.
@since 4.08 *)
external rem : nativeint -> nativeint -> nativeint = "%nativeint_mod"
* Integer remainder . If [ y ] is not zero , the result
of [ x y ] satisfies the following properties :
[ Nativeint.zero < = x y < Nativeint.abs y ] and
[ x = Nativeint.add ( Nativeint.mul ( Nativeint.div x y ) y )
( x y ) ] .
If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] .
of [Nativeint.rem x y] satisfies the following properties:
[Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y] and
[x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y)
(Nativeint.rem x y)].
If [y = 0], [Nativeint.rem x y] raises [Division_by_zero]. *)
val unsigned_rem : nativeint -> nativeint -> nativeint
* Same as { ! rem } , except that arguments and result are interpreted as { e
unsigned } native integers .
@since 4.08
unsigned} native integers.
@since 4.08 *)
val succ : nativeint -> nativeint
val pred : nativeint -> nativeint
* Predecessor .
[ Nativeint.pred x ] is [ Nativeint.sub x Nativeint.one ] .
[Nativeint.pred x] is [Nativeint.sub x Nativeint.one]. *)
val abs : nativeint -> nativeint
val size : int
* The size in bits of a native integer . This is equal to [ 32 ]
on a 32 - bit platform and to [ 64 ] on a 64 - bit platform .
on a 32-bit platform and to [64] on a 64-bit platform. *)
val max_int : nativeint
* The greatest representable native integer ,
either 2{^31 } - 1 on a 32 - bit platform ,
or 2{^63 } - 1 on a 64 - bit platform .
either 2{^31} - 1 on a 32-bit platform,
or 2{^63} - 1 on a 64-bit platform. *)
val min_int : nativeint
* The smallest representable native integer ,
either -2{^31 } on a 32 - bit platform ,
or -2{^63 } on a 64 - bit platform .
either -2{^31} on a 32-bit platform,
or -2{^63} on a 64-bit platform. *)
external logand : nativeint -> nativeint -> nativeint = "%nativeint_and"
external logor : nativeint -> nativeint -> nativeint = "%nativeint_or"
external logxor : nativeint -> nativeint -> nativeint = "%nativeint_xor"
val lognot : nativeint -> nativeint
external shift_left : nativeint -> int -> nativeint = "%nativeint_lsl"
* [ Nativeint.shift_left x y ] shifts [ x ] to the left by [ y ] bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] ,
where [ bitsize ] is [ 32 ] on a 32 - bit platform and
[ 64 ] on a 64 - bit platform .
The result is unspecified if [y < 0] or [y >= bitsize],
where [bitsize] is [32] on a 32-bit platform and
[64] on a 64-bit platform. *)
external shift_right : nativeint -> int -> nativeint = "%nativeint_asr"
* [ Nativeint.shift_right x y ] shifts [ x ] to the right by [ y ] bits .
This is an arithmetic shift : the sign bit of [ x ] is replicated
and inserted in the vacated bits .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
This is an arithmetic shift: the sign bit of [x] is replicated
and inserted in the vacated bits.
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external shift_right_logical :
nativeint -> int -> nativeint = "%nativeint_lsr"
* [ Nativeint.shift_right_logical x y ] shifts [ x ] to the right
by [ y ] bits .
This is a logical shift : zeroes are inserted in the vacated bits
regardless of the sign of [ x ] .
The result is unspecified if [ y < 0 ] or [ y > = bitsize ] .
by [y] bits.
This is a logical shift: zeroes are inserted in the vacated bits
regardless of the sign of [x].
The result is unspecified if [y < 0] or [y >= bitsize]. *)
external of_int : int -> nativeint = "%nativeint_of_int"
external to_int : nativeint -> int = "%nativeint_to_int"
val unsigned_to_int : nativeint -> int option
* Same as { ! to_int } , but interprets the argument as an { e unsigned } integer .
Returns [ None ] if the unsigned value of the argument can not fit into an
[ int ] .
@since 4.08
Returns [None] if the unsigned value of the argument cannot fit into an
[int].
@since 4.08 *)
external of_float : float -> nativeint
= "caml_nativeint_of_float" "caml_nativeint_of_float_unboxed"
[@@unboxed] [@@noalloc]
external to_float : nativeint -> float
= "caml_nativeint_to_float" "caml_nativeint_to_float_unboxed"
[@@unboxed] [@@noalloc]
external of_int32 : int32 -> nativeint = "%nativeint_of_int32"
* Convert the given 32 - bit integer ( type [ int32 ] )
to a native integer .
to a native integer. *)
external to_int32 : nativeint -> int32 = "%nativeint_to_int32"
* Convert the given native integer to a
32 - bit integer ( type [ int32 ] ) . On 64 - bit platforms ,
the 64 - bit native integer is taken modulo 2{^32 } ,
i.e. the top 32 bits are lost . On 32 - bit platforms ,
the conversion is exact .
32-bit integer (type [int32]). On 64-bit platforms,
the 64-bit native integer is taken modulo 2{^32},
i.e. the top 32 bits are lost. On 32-bit platforms,
the conversion is exact. *)
external of_string : string -> nativeint = "caml_nativeint_of_string"
* Convert the given string to a native integer .
The string is read in decimal ( by default , or if the string
begins with [ 0u ] ) or in hexadecimal , octal or binary if the
string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively .
The [ 0u ] prefix reads the input as an unsigned integer in the range
[ [ 0 , 2*Nativeint.max_int+1 ] ] . If the input exceeds { ! Nativeint.max_int }
it is converted to the signed integer
[ + input - Nativeint.max_int - 1 ] .
@raise Failure if the given string is not
a valid representation of an integer , or if the integer represented
exceeds the range of integers representable in type [ nativeint ] .
The string is read in decimal (by default, or if the string
begins with [0u]) or in hexadecimal, octal or binary if the
string begins with [0x], [0o] or [0b] respectively.
The [0u] prefix reads the input as an unsigned integer in the range
[[0, 2*Nativeint.max_int+1]]. If the input exceeds {!Nativeint.max_int}
it is converted to the signed integer
[Int64.min_int + input - Nativeint.max_int - 1].
@raise Failure if the given string is not
a valid representation of an integer, or if the integer represented
exceeds the range of integers representable in type [nativeint]. *)
val of_string_opt: string -> nativeint option
* Same as [ of_string ] , but return [ None ] instead of raising .
@since 4.05
@since 4.05 *)
val to_string : nativeint -> string
type t = nativeint
val compare: t -> t -> int
* The comparison function for native integers , with the same specification as
{ ! Stdlib.compare } . Along with the type [ t ] , this function [ compare ]
allows the module [ Nativeint ] to be passed as argument to the functors
{ ! Set . Make } and { ! Map . Make } .
{!Stdlib.compare}. Along with the type [t], this function [compare]
allows the module [Nativeint] to be passed as argument to the functors
{!Set.Make} and {!Map.Make}. *)
val unsigned_compare: t -> t -> int
* Same as { ! compare } , except that arguments are interpreted as { e unsigned }
native integers .
@since 4.08
native integers.
@since 4.08 *)
val equal: t -> t -> bool
* The equal function for native ints .
@since 4.03
@since 4.03 *)
val min: t -> t -> t
* Return the smaller of the two arguments .
@since 4.13
@since 4.13
*)
val max: t -> t -> t
* Return the greater of the two arguments .
@since 4.13
@since 4.13
*)
val seeded_hash : int -> t -> int
* A seeded hash function for native ints , with the same output value as
{ ! Hashtbl.seeded_hash } . This function allows this module to be passed as
argument to the functor { ! . MakeSeeded } .
@since 5.1
{!Hashtbl.seeded_hash}. This function allows this module to be passed as
argument to the functor {!Hashtbl.MakeSeeded}.
@since 5.1 *)
val hash : t -> int
* An unseeded hash function for native ints , with the same output value as
{ ! Hashtbl.hash } . This function allows this module to be passed as argument
to the functor { ! . Make } .
@since 5.1
{!Hashtbl.hash}. This function allows this module to be passed as argument
to the functor {!Hashtbl.Make}.
@since 5.1 *)
|
79d7861f4e10caa50756c850a701bedb0f694f60b52df1dfeca47e4cbd293fcf | mbj/stratosphere | UriPathRouteInputProperty.hs | module Stratosphere.RefactorSpaces.Route.UriPathRouteInputProperty (
UriPathRouteInputProperty(..), mkUriPathRouteInputProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data UriPathRouteInputProperty
= UriPathRouteInputProperty {activationState :: (Value Prelude.Text),
includeChildPaths :: (Prelude.Maybe (Value Prelude.Bool)),
methods :: (Prelude.Maybe (ValueList Prelude.Text)),
sourcePath :: (Prelude.Maybe (Value Prelude.Text))}
mkUriPathRouteInputProperty ::
Value Prelude.Text -> UriPathRouteInputProperty
mkUriPathRouteInputProperty activationState
= UriPathRouteInputProperty
{activationState = activationState,
includeChildPaths = Prelude.Nothing, methods = Prelude.Nothing,
sourcePath = Prelude.Nothing}
instance ToResourceProperties UriPathRouteInputProperty where
toResourceProperties UriPathRouteInputProperty {..}
= ResourceProperties
{awsType = "AWS::RefactorSpaces::Route.UriPathRouteInput",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["ActivationState" JSON..= activationState]
(Prelude.catMaybes
[(JSON..=) "IncludeChildPaths" Prelude.<$> includeChildPaths,
(JSON..=) "Methods" Prelude.<$> methods,
(JSON..=) "SourcePath" Prelude.<$> sourcePath]))}
instance JSON.ToJSON UriPathRouteInputProperty where
toJSON UriPathRouteInputProperty {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["ActivationState" JSON..= activationState]
(Prelude.catMaybes
[(JSON..=) "IncludeChildPaths" Prelude.<$> includeChildPaths,
(JSON..=) "Methods" Prelude.<$> methods,
(JSON..=) "SourcePath" Prelude.<$> sourcePath])))
instance Property "ActivationState" UriPathRouteInputProperty where
type PropertyType "ActivationState" UriPathRouteInputProperty = Value Prelude.Text
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty {activationState = newValue, ..}
instance Property "IncludeChildPaths" UriPathRouteInputProperty where
type PropertyType "IncludeChildPaths" UriPathRouteInputProperty = Value Prelude.Bool
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty
{includeChildPaths = Prelude.pure newValue, ..}
instance Property "Methods" UriPathRouteInputProperty where
type PropertyType "Methods" UriPathRouteInputProperty = ValueList Prelude.Text
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty {methods = Prelude.pure newValue, ..}
instance Property "SourcePath" UriPathRouteInputProperty where
type PropertyType "SourcePath" UriPathRouteInputProperty = Value Prelude.Text
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty
{sourcePath = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/refactorspaces/gen/Stratosphere/RefactorSpaces/Route/UriPathRouteInputProperty.hs | haskell | module Stratosphere.RefactorSpaces.Route.UriPathRouteInputProperty (
UriPathRouteInputProperty(..), mkUriPathRouteInputProperty
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data UriPathRouteInputProperty
= UriPathRouteInputProperty {activationState :: (Value Prelude.Text),
includeChildPaths :: (Prelude.Maybe (Value Prelude.Bool)),
methods :: (Prelude.Maybe (ValueList Prelude.Text)),
sourcePath :: (Prelude.Maybe (Value Prelude.Text))}
mkUriPathRouteInputProperty ::
Value Prelude.Text -> UriPathRouteInputProperty
mkUriPathRouteInputProperty activationState
= UriPathRouteInputProperty
{activationState = activationState,
includeChildPaths = Prelude.Nothing, methods = Prelude.Nothing,
sourcePath = Prelude.Nothing}
instance ToResourceProperties UriPathRouteInputProperty where
toResourceProperties UriPathRouteInputProperty {..}
= ResourceProperties
{awsType = "AWS::RefactorSpaces::Route.UriPathRouteInput",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["ActivationState" JSON..= activationState]
(Prelude.catMaybes
[(JSON..=) "IncludeChildPaths" Prelude.<$> includeChildPaths,
(JSON..=) "Methods" Prelude.<$> methods,
(JSON..=) "SourcePath" Prelude.<$> sourcePath]))}
instance JSON.ToJSON UriPathRouteInputProperty where
toJSON UriPathRouteInputProperty {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["ActivationState" JSON..= activationState]
(Prelude.catMaybes
[(JSON..=) "IncludeChildPaths" Prelude.<$> includeChildPaths,
(JSON..=) "Methods" Prelude.<$> methods,
(JSON..=) "SourcePath" Prelude.<$> sourcePath])))
instance Property "ActivationState" UriPathRouteInputProperty where
type PropertyType "ActivationState" UriPathRouteInputProperty = Value Prelude.Text
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty {activationState = newValue, ..}
instance Property "IncludeChildPaths" UriPathRouteInputProperty where
type PropertyType "IncludeChildPaths" UriPathRouteInputProperty = Value Prelude.Bool
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty
{includeChildPaths = Prelude.pure newValue, ..}
instance Property "Methods" UriPathRouteInputProperty where
type PropertyType "Methods" UriPathRouteInputProperty = ValueList Prelude.Text
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty {methods = Prelude.pure newValue, ..}
instance Property "SourcePath" UriPathRouteInputProperty where
type PropertyType "SourcePath" UriPathRouteInputProperty = Value Prelude.Text
set newValue UriPathRouteInputProperty {..}
= UriPathRouteInputProperty
{sourcePath = Prelude.pure newValue, ..} | |
52678767847224b8184dc5bda8c4a1696f718c586ba3021658444c50a764a705 | brendanhay/gogol | Product.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 : . File . Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Gogol.File.Internal.Product
( -- * Backup
Backup (..),
newBackup,
-- * Backup_Labels
Backup_Labels (..),
newBackup_Labels,
-- * CancelOperationRequest
CancelOperationRequest (..),
newCancelOperationRequest,
*
DailyCycle (..),
newDailyCycle,
-- * Date
Date (..),
newDate,
-- * DenyMaintenancePeriod
DenyMaintenancePeriod (..),
newDenyMaintenancePeriod,
-- * Empty
Empty (..),
newEmpty,
-- * FileShareConfig
FileShareConfig (..),
newFileShareConfig,
-- * GoogleCloudSaasacceleratorManagementProvidersV1Instance
GoogleCloudSaasacceleratorManagementProvidersV1Instance (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance,
-- * GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels,
-- * GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames,
-- * GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules,
-- * GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters,
-- * GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata,
-- * GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions,
-- * GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule (..),
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule,
-- * GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings (..),
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings,
-- * GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies (..),
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies,
-- * GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata (..),
newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata,
-- * GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility (..),
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility,
-- * GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities (..),
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities,
-- * GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource (..),
newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource,
-- * GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility (..),
newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility,
-- * GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata (..),
newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata,
-- * Instance
Instance (..),
newInstance,
-- * Instance_Labels
Instance_Labels (..),
newInstance_Labels,
* ListBackupsResponse
ListBackupsResponse (..),
newListBackupsResponse,
* ListInstancesResponse
ListInstancesResponse (..),
newListInstancesResponse,
* ListLocationsResponse
ListLocationsResponse (..),
newListLocationsResponse,
-- * ListOperationsResponse
ListOperationsResponse (..),
newListOperationsResponse,
*
ListSnapshotsResponse (..),
newListSnapshotsResponse,
-- * Location
Location (..),
newLocation,
-- * Location_Labels
Location_Labels (..),
newLocation_Labels,
-- * Location_Metadata
Location_Metadata (..),
newLocation_Metadata,
* MaintenancePolicy
MaintenancePolicy (..),
newMaintenancePolicy,
*
MaintenancePolicy_Labels (..),
newMaintenancePolicy_Labels,
-- * MaintenanceWindow
MaintenanceWindow (..),
newMaintenanceWindow,
* NetworkConfig
NetworkConfig (..),
newNetworkConfig,
* NfsExportOptions
NfsExportOptions (..),
newNfsExportOptions,
-- * Operation
Operation (..),
newOperation,
-- * Operation_Metadata
Operation_Metadata (..),
newOperation_Metadata,
-- * Operation_Response
Operation_Response (..),
newOperation_Response,
-- * OperationMetadata
OperationMetadata (..),
newOperationMetadata,
-- * RestoreInstanceRequest
RestoreInstanceRequest (..),
newRestoreInstanceRequest,
-- * Schedule
Schedule (..),
newSchedule,
-- * Snapshot
Snapshot (..),
newSnapshot,
-- * Snapshot_Labels
Snapshot_Labels (..),
newSnapshot_Labels,
-- * Status
Status (..),
newStatus,
-- * Status_DetailsItem
Status_DetailsItem (..),
newStatus_DetailsItem,
* '
TimeOfDay' (..),
newTimeOfDay,
* UpdatePolicy
UpdatePolicy (..),
newUpdatePolicy,
-- * WeeklyCycle
WeeklyCycle (..),
newWeeklyCycle,
)
where
import Gogol.File.Internal.Sum
import qualified Gogol.Prelude as Core
-- | A Cloud Filestore backup.
--
/See:/ ' ' smart constructor .
data Backup = Backup
{ -- | Output only. Capacity of the source file share when the backup was created.
capacityGb :: (Core.Maybe Core.Int64),
-- | Output only. The time when the backup was created.
createTime :: (Core.Maybe Core.DateTime),
| A description of the backup with 2048 characters or less . Requests with longer descriptions will be rejected .
description :: (Core.Maybe Core.Text),
-- | Output only. Amount of bytes that will be downloaded if the backup is restored. This may be different than storage bytes, since sequential backups of the same disk will share storage.
downloadBytes :: (Core.Maybe Core.Int64),
-- | Resource labels to represent user provided metadata.
labels :: (Core.Maybe Backup_Labels),
-- | Output only. The resource name of the backup, in the format @projects\/{project_number}\/locations\/{location_id}\/backups\/{backup_id}@.
name :: (Core.Maybe Core.Text),
-- | Output only. Reserved for future use.
satisfiesPzs :: (Core.Maybe Core.Bool),
| Name of the file share in the source Cloud Filestore instance that the backup is created from .
sourceFileShare :: (Core.Maybe Core.Text),
| The resource name of the source Cloud Filestore instance , in the format @projects\/{project_number}\/locations\/{location_id}\/instances\/{instance_id}@ , used to create this backup .
sourceInstance :: (Core.Maybe Core.Text),
| Output only . The service tier of the source Cloud Filestore instance that this backup is created from .
sourceInstanceTier :: (Core.Maybe Backup_SourceInstanceTier),
-- | Output only. The backup state.
state :: (Core.Maybe Backup_State),
-- | Output only. The size of the storage used by the backup. As backups share storage, this number is expected to change with backup creation\/deletion.
storageBytes :: (Core.Maybe Core.Int64)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Backup' with the minimum fields required to make a request.
newBackup ::
Backup
newBackup =
Backup
{ capacityGb = Core.Nothing,
createTime = Core.Nothing,
description = Core.Nothing,
downloadBytes = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
satisfiesPzs = Core.Nothing,
sourceFileShare = Core.Nothing,
sourceInstance = Core.Nothing,
sourceInstanceTier = Core.Nothing,
state = Core.Nothing,
storageBytes = Core.Nothing
}
instance Core.FromJSON Backup where
parseJSON =
Core.withObject
"Backup"
( \o ->
Backup
Core.<$> ( o Core..:? "capacityGb"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> ( o Core..:? "downloadBytes"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "satisfiesPzs")
Core.<*> (o Core..:? "sourceFileShare")
Core.<*> (o Core..:? "sourceInstance")
Core.<*> (o Core..:? "sourceInstanceTier")
Core.<*> (o Core..:? "state")
Core.<*> ( o Core..:? "storageBytes"
Core.<&> Core.fmap Core.fromAsText
)
)
instance Core.ToJSON Backup where
toJSON Backup {..} =
Core.object
( Core.catMaybes
[ ("capacityGb" Core..=) Core.. Core.AsText
Core.<$> capacityGb,
("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("downloadBytes" Core..=) Core.. Core.AsText
Core.<$> downloadBytes,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("satisfiesPzs" Core..=) Core.<$> satisfiesPzs,
("sourceFileShare" Core..=) Core.<$> sourceFileShare,
("sourceInstance" Core..=) Core.<$> sourceInstance,
("sourceInstanceTier" Core..=)
Core.<$> sourceInstanceTier,
("state" Core..=) Core.<$> state,
("storageBytes" Core..=) Core.. Core.AsText
Core.<$> storageBytes
]
)
-- | Resource labels to represent user provided metadata.
--
-- /See:/ 'newBackup_Labels' smart constructor.
newtype Backup_Labels = Backup_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Backup_Labels' with the minimum fields required to make a request.
newBackup_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
Backup_Labels
newBackup_Labels additional = Backup_Labels {additional = additional}
instance Core.FromJSON Backup_Labels where
parseJSON =
Core.withObject
"Backup_Labels"
( \o ->
Backup_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Backup_Labels where
toJSON Backup_Labels {..} = Core.toJSON additional
| The request message for Operations . CancelOperation .
--
/See:/ ' newCancelOperationRequest ' smart constructor .
data CancelOperationRequest = CancelOperationRequest
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'CancelOperationRequest' with the minimum fields required to make a request.
newCancelOperationRequest ::
CancelOperationRequest
newCancelOperationRequest = CancelOperationRequest
instance Core.FromJSON CancelOperationRequest where
parseJSON =
Core.withObject
"CancelOperationRequest"
(\o -> Core.pure CancelOperationRequest)
instance Core.ToJSON CancelOperationRequest where
toJSON = Core.const Core.emptyObject
| Time window specified for daily operations .
--
-- /See:/ 'newDailyCycle' smart constructor.
data DailyCycle = DailyCycle
{ -- | Output only. Duration of the time window, set by service producer.
duration :: (Core.Maybe Core.Duration),
| Time within the day to start the operations .
startTime :: (Core.Maybe TimeOfDay')
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' DailyCycle ' with the minimum fields required to make a request .
newDailyCycle ::
DailyCycle
newDailyCycle = DailyCycle {duration = Core.Nothing, startTime = Core.Nothing}
instance Core.FromJSON DailyCycle where
parseJSON =
Core.withObject
"DailyCycle"
( \o ->
DailyCycle
Core.<$> (o Core..:? "duration")
Core.<*> (o Core..:? "startTime")
)
instance Core.ToJSON DailyCycle where
toJSON DailyCycle {..} =
Core.object
( Core.catMaybes
[ ("duration" Core..=) Core.<$> duration,
("startTime" Core..=) Core.<$> startTime
]
)
| Represents a whole or partial calendar date , such as a birthday . The time of day and time zone are either specified elsewhere or are insignificant . The date is relative to the Gregorian Calendar . This can represent one of the following : * A full date , with non - zero year , month , and day values * A month and day , with a zero year ( e.g. , an anniversary ) * A year on its own , with a zero month and a zero day * A year and month , with a zero day ( e.g. , a credit card expiration date ) Related types : * google.type . * google.type . DateTime * google.protobuf . Timestamp
--
-- /See:/ 'newDate' smart constructor.
data Date = Date
| Day of a month . Must be from 1 to 31 and valid for the year and month , or 0 to specify a year by itself or a year and month where the day isn\'t significant .
day :: (Core.Maybe Core.Int32),
| Month of a year . Must be from 1 to 12 , or 0 to specify a year without a month and day .
month :: (Core.Maybe Core.Int32),
| Year of the date . Must be from 1 to 9999 , or 0 to specify a date without a year .
year :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Date' with the minimum fields required to make a request.
newDate ::
Date
newDate = Date {day = Core.Nothing, month = Core.Nothing, year = Core.Nothing}
instance Core.FromJSON Date where
parseJSON =
Core.withObject
"Date"
( \o ->
Date
Core.<$> (o Core..:? "day")
Core.<*> (o Core..:? "month")
Core.<*> (o Core..:? "year")
)
instance Core.ToJSON Date where
toJSON Date {..} =
Core.object
( Core.catMaybes
[ ("day" Core..=) Core.<$> day,
("month" Core..=) Core.<$> month,
("year" Core..=) Core.<$> year
]
)
-- | DenyMaintenancePeriod definition. Maintenance is forbidden within the deny period. The start/date must be less than the end/date.
--
-- /See:/ 'newDenyMaintenancePeriod' smart constructor.
data DenyMaintenancePeriod = DenyMaintenancePeriod
| Deny period end date . This can be : * A full date , with non - zero year , month and day values . * A month and day value , with a zero year . Allows recurring deny periods each year . Date matching this period will have to be before the end .
endDate :: (Core.Maybe Date),
| Deny period start date . This can be : * A full date , with non - zero year , month and day values . * A month and day value , with a zero year . Allows recurring deny periods each year . Date matching this period will have to be the same or after the start .
startDate :: (Core.Maybe Date),
| Time in UTC when the Blackout period starts on start / date and ends on end / date . This can be : * Full time . * All zeros for 00:00:00 UTC
time :: (Core.Maybe TimeOfDay')
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'DenyMaintenancePeriod' with the minimum fields required to make a request.
newDenyMaintenancePeriod ::
DenyMaintenancePeriod
newDenyMaintenancePeriod =
DenyMaintenancePeriod
{ endDate = Core.Nothing,
startDate = Core.Nothing,
time = Core.Nothing
}
instance Core.FromJSON DenyMaintenancePeriod where
parseJSON =
Core.withObject
"DenyMaintenancePeriod"
( \o ->
DenyMaintenancePeriod
Core.<$> (o Core..:? "endDate")
Core.<*> (o Core..:? "startDate")
Core.<*> (o Core..:? "time")
)
instance Core.ToJSON DenyMaintenancePeriod where
toJSON DenyMaintenancePeriod {..} =
Core.object
( Core.catMaybes
[ ("endDate" Core..=) Core.<$> endDate,
("startDate" Core..=) Core.<$> startDate,
("time" Core..=) Core.<$> time
]
)
| A generic empty message that you can re - use to avoid defining duplicated empty messages in your APIs . A typical example is to use it as the request or the response type of an API method . For instance : service Foo { rpc Bar(google.protobuf . Empty ) returns ( google.protobuf . Empty ) ; } The JSON representation for @Empty@ is empty JSON object @{}@.
--
/See:/ ' ' smart constructor .
data Empty = Empty
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Empty' with the minimum fields required to make a request.
newEmpty ::
Empty
newEmpty = Empty
instance Core.FromJSON Empty where
parseJSON =
Core.withObject "Empty" (\o -> Core.pure Empty)
instance Core.ToJSON Empty where
toJSON = Core.const Core.emptyObject
-- | File share configuration for the instance.
--
-- /See:/ 'newFileShareConfig' smart constructor.
data FileShareConfig = FileShareConfig
| File share capacity in gigabytes ( GB ) . defines 1 GB as 1024 ^ 3 bytes .
capacityGb :: (Core.Maybe Core.Int64),
| The name of the file share ( must be 16 characters or less ) .
name :: (Core.Maybe Core.Text),
| Nfs Export Options . There is a limit of 10 export options per file share .
nfsExportOptions :: (Core.Maybe [NfsExportOptions]),
-- | The resource name of the backup, in the format @projects\/{project_number}\/locations\/{location_id}\/backups\/{backup_id}@, that this file share has been restored from.
sourceBackup :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'FileShareConfig' with the minimum fields required to make a request.
newFileShareConfig ::
FileShareConfig
newFileShareConfig =
FileShareConfig
{ capacityGb = Core.Nothing,
name = Core.Nothing,
nfsExportOptions = Core.Nothing,
sourceBackup = Core.Nothing
}
instance Core.FromJSON FileShareConfig where
parseJSON =
Core.withObject
"FileShareConfig"
( \o ->
FileShareConfig
Core.<$> ( o Core..:? "capacityGb"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "nfsExportOptions")
Core.<*> (o Core..:? "sourceBackup")
)
instance Core.ToJSON FileShareConfig where
toJSON FileShareConfig {..} =
Core.object
( Core.catMaybes
[ ("capacityGb" Core..=) Core.. Core.AsText
Core.<$> capacityGb,
("name" Core..=) Core.<$> name,
("nfsExportOptions" Core..=)
Core.<$> nfsExportOptions,
("sourceBackup" Core..=) Core.<$> sourceBackup
]
)
--
/See:/ ' newGoogleCloudSaasacceleratorManagementProvidersV1Instance ' smart constructor .
data GoogleCloudSaasacceleratorManagementProvidersV1Instance = GoogleCloudSaasacceleratorManagementProvidersV1Instance
| consumer / defined / name is the name that is set by the consumer . On the other hand Name field represents system - assigned i d of an instance so consumers are not necessarily aware of it . consumer / defined / name is used for notification\/UI purposes for consumer to recognize their instances .
consumerDefinedName :: (Core.Maybe Core.Text),
-- | Output only. Timestamp when the resource was created.
createTime :: (Core.Maybe Core.DateTime),
| Optional . The instance / type of this instance of format : projects\/{project / id}\/locations\/{location / id}\/instanceTypes\/{instance / type / id } . Instance Type represents a high - level tier or SKU of the service that this instance belong to . When enabled(eg : Maintenance Rollout ) , Rollout uses \'instance / type\ ' along with \'software_versions\ ' to determine whether instance needs an update or not .
instanceType :: (Core.Maybe Core.Text),
-- | Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
labels ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
),
| Deprecated . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the referenced policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug .
maintenancePolicyNames ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
),
-- | The MaintenanceSchedule contains the scheduling information of published maintenance schedule with same key as software_versions.
maintenanceSchedules ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
),
| Optional . The MaintenanceSettings associated with instance .
maintenanceSettings ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
),
| Unique name of the resource . It uses the form : @projects\/{project_id|project_number}\/locations\/{location_id}\/instances\/{instance_id}@ Note : Either project / id or project / number can be used , but keep it consistent with other APIs ( e.g. RescheduleUpdate )
name :: (Core.Maybe Core.Text),
| Optional . notification_parameters are information that service producers may like to include that is not relevant to Rollout . This parameter will only be passed to Gamma and Cloud Logging for notification\/logging purpose .
notificationParameters ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
),
-- | Output only. Custom string attributes used primarily to expose producer-specific information in monitoring dashboards. See go\/get-instance-metadata.
producerMetadata ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
),
| Output only . The list of data plane resources provisioned for this instance , e.g. compute VMs . See go\/get - instance - metadata .
provisionedResources ::
( Core.Maybe
[GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource]
),
| Link to the SLM instance template . Only populated when updating SLM instances via SSA\ 's Actuation service adaptor . Service producers with custom control plane ( e.g. Cloud SQL ) doesn\'t need to populate this field . Instead they should use software_versions .
slmInstanceTemplate :: (Core.Maybe Core.Text),
| Output only . SLO metadata for instance classification in the Standardized dataplane SLO platform . See go\/cloud - ssa - standard - slo for feature description .
sloMetadata ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
),
-- | Software versions that are used to deploy this instance. This can be mutated by rollout services.
softwareVersions ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
),
| Output only . Current lifecycle state of the resource ( e.g. if it\ 's being created or ready to use ) .
state ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_State
),
| Output only . ID of the associated GCP tenant project . See go\/get - instance - metadata .
tenantProjectId :: (Core.Maybe Core.Text),
-- | Output only. Timestamp when the resource was last modified.
updateTime :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1Instance ::
GoogleCloudSaasacceleratorManagementProvidersV1Instance
newGoogleCloudSaasacceleratorManagementProvidersV1Instance =
GoogleCloudSaasacceleratorManagementProvidersV1Instance
{ consumerDefinedName = Core.Nothing,
createTime = Core.Nothing,
instanceType = Core.Nothing,
labels = Core.Nothing,
maintenancePolicyNames = Core.Nothing,
maintenanceSchedules = Core.Nothing,
maintenanceSettings = Core.Nothing,
name = Core.Nothing,
notificationParameters = Core.Nothing,
producerMetadata = Core.Nothing,
provisionedResources = Core.Nothing,
slmInstanceTemplate = Core.Nothing,
sloMetadata = Core.Nothing,
softwareVersions = Core.Nothing,
state = Core.Nothing,
tenantProjectId = Core.Nothing,
updateTime = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance
Core.<$> (o Core..:? "consumerDefinedName")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "instanceType")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "maintenancePolicyNames")
Core.<*> (o Core..:? "maintenanceSchedules")
Core.<*> (o Core..:? "maintenanceSettings")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "notificationParameters")
Core.<*> (o Core..:? "producerMetadata")
Core.<*> (o Core..:? "provisionedResources")
Core.<*> (o Core..:? "slmInstanceTemplate")
Core.<*> (o Core..:? "sloMetadata")
Core.<*> (o Core..:? "softwareVersions")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "tenantProjectId")
Core.<*> (o Core..:? "updateTime")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance {..} =
Core.object
( Core.catMaybes
[ ("consumerDefinedName" Core..=)
Core.<$> consumerDefinedName,
("createTime" Core..=) Core.<$> createTime,
("instanceType" Core..=) Core.<$> instanceType,
("labels" Core..=) Core.<$> labels,
("maintenancePolicyNames" Core..=)
Core.<$> maintenancePolicyNames,
("maintenanceSchedules" Core..=)
Core.<$> maintenanceSchedules,
("maintenanceSettings" Core..=)
Core.<$> maintenanceSettings,
("name" Core..=) Core.<$> name,
("notificationParameters" Core..=)
Core.<$> notificationParameters,
("producerMetadata" Core..=)
Core.<$> producerMetadata,
("provisionedResources" Core..=)
Core.<$> provisionedResources,
("slmInstanceTemplate" Core..=)
Core.<$> slmInstanceTemplate,
("sloMetadata" Core..=) Core.<$> sloMetadata,
("softwareVersions" Core..=)
Core.<$> softwareVersions,
("state" Core..=) Core.<$> state,
("tenantProjectId" Core..=) Core.<$> tenantProjectId,
("updateTime" Core..=) Core.<$> updateTime
]
)
-- | Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels = GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels ' with the minimum fields required to make a request .
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels {..} =
Core.toJSON additional
| Deprecated . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the referenced policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug .
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames = GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames {..} =
Core.toJSON additional
-- | The MaintenanceSchedule contains the scheduling information of published maintenance schedule with same key as software_versions.
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules = GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
{ -- |
additional ::
( Core.HashMap
Core.Text
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules ::
-- | See 'additional'.
Core.HashMap Core.Text GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules {..} =
Core.toJSON additional
| Optional . notification_parameters are information that service producers may like to include that is not relevant to Rollout . This parameter will only be passed to Gamma and Cloud Logging for notification\/logging purpose .
--
/See:/ ' newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters ' smart constructor .
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters = GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters {..} =
Core.toJSON additional
-- | Output only. Custom string attributes used primarily to expose producer-specific information in monitoring dashboards. See go\/get-instance-metadata.
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata = GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata {..} =
Core.toJSON additional
-- | Software versions that are used to deploy this instance. This can be mutated by rollout services.
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions = GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions {..} =
Core.toJSON additional
-- | Maintenance schedule which is exposed to customer and potentially end user, indicating published upcoming future maintenance schedule
--
/See:/ ' newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule ' smart constructor .
data GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule = GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
{ -- | This field is deprecated, and will be always set to true since reschedule can happen multiple times now. This field should not be removed until all service producers remove this for their customers.
canReschedule :: (Core.Maybe Core.Bool),
-- | The scheduled end time for the maintenance.
endTime :: (Core.Maybe Core.DateTime),
-- | The rollout management policy this maintenance schedule is associated with. When doing reschedule update request, the reschedule should be against this given policy.
rolloutManagementPolicy :: (Core.Maybe Core.Text),
| schedule / deadline / time is the time deadline any schedule start time can not go beyond , including reschedule . It\ 's normally the initial schedule start time plus maintenance window length ( 1 day or 1 week ) . Maintenance can not be scheduled to start beyond this deadline .
scheduleDeadlineTime :: (Core.Maybe Core.DateTime),
-- | The scheduled start time for the maintenance.
startTime :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule ::
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule =
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
{ canReschedule = Core.Nothing,
endTime = Core.Nothing,
rolloutManagementPolicy = Core.Nothing,
scheduleDeadlineTime = Core.Nothing,
startTime = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
Core.<$> (o Core..:? "canReschedule")
Core.<*> (o Core..:? "endTime")
Core.<*> (o Core..:? "rolloutManagementPolicy")
Core.<*> (o Core..:? "scheduleDeadlineTime")
Core.<*> (o Core..:? "startTime")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule {..} =
Core.object
( Core.catMaybes
[ ("canReschedule" Core..=) Core.<$> canReschedule,
("endTime" Core..=) Core.<$> endTime,
("rolloutManagementPolicy" Core..=)
Core.<$> rolloutManagementPolicy,
("scheduleDeadlineTime" Core..=)
Core.<$> scheduleDeadlineTime,
("startTime" Core..=) Core.<$> startTime
]
)
-- | Maintenance settings associated with instance. Allows service producers and end users to assign settings that controls maintenance on this instance.
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings' smart constructor.
data GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings = GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
{ -- | Optional. Exclude instance from maintenance. When true, rollout service will not attempt maintenance on the instance. Rollout service will include the instance in reported rollout progress as not attempted.
exclude :: (Core.Maybe Core.Bool),
-- | Optional. If the update call is triggered from rollback, set the value as true.
isRollback :: (Core.Maybe Core.Bool),
| Optional . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the embedded policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug . If only the name is needed ( like in the deprecated Instance.maintenance/policy/names field ) then only populate MaintenancePolicy.name .
maintenancePolicies ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings ::
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings =
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
{ exclude = Core.Nothing,
isRollback = Core.Nothing,
maintenancePolicies = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
Core.<$> (o Core..:? "exclude")
Core.<*> (o Core..:? "isRollback")
Core.<*> (o Core..:? "maintenancePolicies")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings {..} =
Core.object
( Core.catMaybes
[ ("exclude" Core..=) Core.<$> exclude,
("isRollback" Core..=) Core.<$> isRollback,
("maintenancePolicies" Core..=)
Core.<$> maintenancePolicies
]
)
| Optional . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the embedded policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug . If only the name is needed ( like in the deprecated Instance.maintenance/policy/names field ) then only populate MaintenancePolicy.name .
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies = GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
{ -- |
additional :: (Core.HashMap Core.Text MaintenancePolicy)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies ' with the minimum fields required to make a request .
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies ::
-- | See 'additional'.
Core.HashMap Core.Text MaintenancePolicy ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies additional =
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies {..} =
Core.toJSON additional
| Node information for custom per - node SLO implementations . SSA does not support per - node SLO , but producers can populate per - node information in SloMetadata for custom precomputations . SSA Eligibility Exporter will emit per - node metric based on this information .
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata' smart constructor.
data GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata = GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
{ -- | The location of the node, if different from instance location.
location :: (Core.Maybe Core.Text),
-- | The id of the node. This should be equal to SaasInstanceNode.node_id.
nodeId :: (Core.Maybe Core.Text),
-- | If present, this will override eligibility for the node coming from instance or exclusions for specified SLIs.
perSliEligibility ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata ' with the minimum fields required to make a request .
newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata ::
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata =
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
{ location = Core.Nothing,
nodeId = Core.Nothing,
perSliEligibility = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
Core.<$> (o Core..:? "location")
Core.<*> (o Core..:? "nodeId")
Core.<*> (o Core..:? "perSliEligibility")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata {..} =
Core.object
( Core.catMaybes
[ ("location" Core..=) Core.<$> location,
("nodeId" Core..=) Core.<$> nodeId,
("perSliEligibility" Core..=)
Core.<$> perSliEligibility
]
)
| PerSliSloEligibility is a mapping from an SLI name to eligibility .
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility = GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
| An entry in the eligibilities map specifies an eligibility for a particular SLI for the given instance . The SLI key in the name must be a valid SLI name specified in the Eligibility Exporter binary flags otherwise an error will be emitted by Eligibility Exporter and the oncaller will be alerted . If an SLI has been defined in the binary flags but the eligibilities map does not contain it , the corresponding SLI time series will not be emitted by the Eligibility Exporter . This ensures a smooth rollout and compatibility between the data produced by different versions of the Eligibility Exporters . If eligibilities map contains a key for an SLI which has not been declared in the binary flags , there will be an error message emitted in the Eligibility Exporter log and the metric for the SLI in question will not be emitted .
eligibilities ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility ::
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility =
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
{ eligibilities = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
Core.<$> (o Core..:? "eligibilities")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility {..} =
Core.object
( Core.catMaybes
[("eligibilities" Core..=) Core.<$> eligibilities]
)
| An entry in the eligibilities map specifies an eligibility for a particular SLI for the given instance . The SLI key in the name must be a valid SLI name specified in the Eligibility Exporter binary flags otherwise an error will be emitted by Eligibility Exporter and the oncaller will be alerted . If an SLI has been defined in the binary flags but the eligibilities map does not contain it , the corresponding SLI time series will not be emitted by the Eligibility Exporter . This ensures a smooth rollout and compatibility between the data produced by different versions of the Eligibility Exporters . If eligibilities map contains a key for an SLI which has not been declared in the binary flags , there will be an error message emitted in the Eligibility Exporter log and the metric for the SLI in question will not be emitted .
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities' smart constructor.
newtype GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities = GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
{ -- |
additional ::
( Core.HashMap
Core.Text
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities ::
-- | See 'additional'.
Core.HashMap Core.Text GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility ->
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities additional =
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities {..} =
Core.toJSON additional
-- | Describes provisioned dataplane resources.
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource' smart constructor.
data GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource = GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
| Type of the resource . This can be either a GCP resource or a custom one ( e.g. another cloud provider\ 's VM ) . For GCP compute resources use singular form of the names listed in GCP compute API documentation ( https:\/\/cloud.google.com\/compute\/docs\/reference\/rest\/v1\/ ) , prefixed with \'compute-\ ' , for example : \'compute - instance\ ' , \'compute - disk\ ' , \'compute - autoscaler\ ' .
resourceType :: (Core.Maybe Core.Text),
| URL identifying the resource , e.g. ... )\ " .
resourceUrl :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource ::
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource =
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
{ resourceType = Core.Nothing,
resourceUrl = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
Core.<$> (o Core..:? "resourceType")
Core.<*> (o Core..:? "resourceUrl")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource {..} =
Core.object
( Core.catMaybes
[ ("resourceType" Core..=) Core.<$> resourceType,
("resourceUrl" Core..=) Core.<$> resourceUrl
]
)
| SloEligibility is a tuple containing eligibility value : true if an instance is eligible for SLO calculation or false if it should be excluded from all SLO - related calculations along with a user - defined reason .
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility' smart constructor.
data GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility = GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
{ -- | Whether an instance is eligible or ineligible.
eligible :: (Core.Maybe Core.Bool),
-- | User-defined reason for the current value of instance eligibility. Usually, this can be directly mapped to the internal state. An empty reason is allowed.
reason :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility ::
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility =
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
{ eligible = Core.Nothing,
reason = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
Core.<$> (o Core..:? "eligible")
Core.<*> (o Core..:? "reason")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility {..} =
Core.object
( Core.catMaybes
[ ("eligible" Core..=) Core.<$> eligible,
("reason" Core..=) Core.<$> reason
]
)
| SloMetadata contains resources required for proper SLO classification of the instance .
--
-- /See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata' smart constructor.
data GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata = GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
| Optional . List of nodes . Some producers need to use per - node metadata to calculate SLO . This field allows such producers to publish per - node SLO meta data , which will be consumed by SSA Eligibility Exporter and published in the form of per node metric to Monarch .
nodes ::
( Core.Maybe
[GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata]
),
| Optional . Multiple per - instance SLI eligibilities which apply for individual SLIs .
perSliEligibility ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
),
| Name of the SLO tier the Instance belongs to . This name will be expected to match the tiers specified in the service SLO configuration . Field is mandatory and must not be empty .
tier :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata' with the minimum fields required to make a request.
newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata ::
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata =
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
{ nodes = Core.Nothing,
perSliEligibility = Core.Nothing,
tier = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
Core.<$> (o Core..:? "nodes")
Core.<*> (o Core..:? "perSliEligibility")
Core.<*> (o Core..:? "tier")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata {..} =
Core.object
( Core.catMaybes
[ ("nodes" Core..=) Core.<$> nodes,
("perSliEligibility" Core..=)
Core.<$> perSliEligibility,
("tier" Core..=) Core.<$> tier
]
)
-- | A Cloud Filestore instance.
--
/See:/ ' newInstance ' smart constructor .
data Instance = Instance
{ -- | Output only. The time when the instance was created.
createTime :: (Core.Maybe Core.DateTime),
| The description of the instance ( 2048 characters or less ) .
description :: (Core.Maybe Core.Text),
-- | Server-specified ETag for the instance resource to prevent simultaneous updates from overwriting each other.
etag :: (Core.Maybe Core.Text),
-- | File system shares on the instance. For this version, only a single file share is supported.
fileShares :: (Core.Maybe [FileShareConfig]),
| KMS key name used for data encryption .
kmsKeyName :: (Core.Maybe Core.Text),
-- | Resource labels to represent user provided metadata.
labels :: (Core.Maybe Instance_Labels),
-- | Output only. The resource name of the instance, in the format @projects\/{project}\/locations\/{location}\/instances\/{instance}@.
name :: (Core.Maybe Core.Text),
-- | VPC networks to which the instance is connected. For this version, only a single network is supported.
networks :: (Core.Maybe [NetworkConfig]),
-- | Output only. Reserved for future use.
satisfiesPzs :: (Core.Maybe Core.Bool),
-- | Output only. The instance state.
state :: (Core.Maybe Instance_State),
-- | Output only. Additional information about the instance state, if available.
statusMessage :: (Core.Maybe Core.Text),
| Output only . field indicates all the reasons the instance is in \"SUSPENDED\ " state .
suspensionReasons :: (Core.Maybe [Instance_SuspensionReasonsItem]),
-- | The service tier of the instance.
tier :: (Core.Maybe Instance_Tier)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Instance' with the minimum fields required to make a request.
newInstance ::
Instance
newInstance =
Instance
{ createTime = Core.Nothing,
description = Core.Nothing,
etag = Core.Nothing,
fileShares = Core.Nothing,
kmsKeyName = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
networks = Core.Nothing,
satisfiesPzs = Core.Nothing,
state = Core.Nothing,
statusMessage = Core.Nothing,
suspensionReasons = Core.Nothing,
tier = Core.Nothing
}
instance Core.FromJSON Instance where
parseJSON =
Core.withObject
"Instance"
( \o ->
Instance
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "fileShares")
Core.<*> (o Core..:? "kmsKeyName")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "networks")
Core.<*> (o Core..:? "satisfiesPzs")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "statusMessage")
Core.<*> (o Core..:? "suspensionReasons")
Core.<*> (o Core..:? "tier")
)
instance Core.ToJSON Instance where
toJSON Instance {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("fileShares" Core..=) Core.<$> fileShares,
("kmsKeyName" Core..=) Core.<$> kmsKeyName,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("networks" Core..=) Core.<$> networks,
("satisfiesPzs" Core..=) Core.<$> satisfiesPzs,
("state" Core..=) Core.<$> state,
("statusMessage" Core..=) Core.<$> statusMessage,
("suspensionReasons" Core..=)
Core.<$> suspensionReasons,
("tier" Core..=) Core.<$> tier
]
)
-- | Resource labels to represent user provided metadata.
--
-- /See:/ 'newInstance_Labels' smart constructor.
newtype Instance_Labels = Instance_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Instance_Labels ' with the minimum fields required to make a request .
newInstance_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
Instance_Labels
newInstance_Labels additional = Instance_Labels {additional = additional}
instance Core.FromJSON Instance_Labels where
parseJSON =
Core.withObject
"Instance_Labels"
( \o ->
Instance_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Instance_Labels where
toJSON Instance_Labels {..} = Core.toJSON additional
| ListBackupsResponse is the result of ListBackupsRequest .
--
-- /See:/ 'newListBackupsResponse' smart constructor.
data ListBackupsResponse = ListBackupsResponse
| A list of backups in the project for the specified location . If the @{location}@ value in the request is \"-\ " , the response contains a list of backups from all locations . If any location is unreachable , the response will only return backups in reachable locations and the \"unreachable\ " field will be populated with a list of unreachable locations .
backups :: (Core.Maybe [Backup]),
-- | The token you can use to retrieve the next page of results. Not returned if there are no more results in the list.
nextPageToken :: (Core.Maybe Core.Text),
-- | Locations that could not be reached.
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ListBackupsResponse' with the minimum fields required to make a request.
newListBackupsResponse ::
ListBackupsResponse
newListBackupsResponse =
ListBackupsResponse
{ backups = Core.Nothing,
nextPageToken = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListBackupsResponse where
parseJSON =
Core.withObject
"ListBackupsResponse"
( \o ->
ListBackupsResponse
Core.<$> (o Core..:? "backups")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListBackupsResponse where
toJSON ListBackupsResponse {..} =
Core.object
( Core.catMaybes
[ ("backups" Core..=) Core.<$> backups,
("nextPageToken" Core..=) Core.<$> nextPageToken,
("unreachable" Core..=) Core.<$> unreachable
]
)
| ListInstancesResponse is the result of ListInstancesRequest .
--
-- /See:/ 'newListInstancesResponse' smart constructor.
data ListInstancesResponse = ListInstancesResponse
| A list of instances in the project for the specified location . If the @{location}@ value in the request is \"-\ " , the response contains a list of instances from all locations . If any location is unreachable , the response will only return instances in reachable locations and the \"unreachable\ " field will be populated with a list of unreachable locations .
instances :: (Core.Maybe [Instance]),
-- | The token you can use to retrieve the next page of results. Not returned if there are no more results in the list.
nextPageToken :: (Core.Maybe Core.Text),
-- | Locations that could not be reached.
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ListInstancesResponse' with the minimum fields required to make a request.
newListInstancesResponse ::
ListInstancesResponse
newListInstancesResponse =
ListInstancesResponse
{ instances = Core.Nothing,
nextPageToken = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListInstancesResponse where
parseJSON =
Core.withObject
"ListInstancesResponse"
( \o ->
ListInstancesResponse
Core.<$> (o Core..:? "instances")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListInstancesResponse where
toJSON ListInstancesResponse {..} =
Core.object
( Core.catMaybes
[ ("instances" Core..=) Core.<$> instances,
("nextPageToken" Core..=) Core.<$> nextPageToken,
("unreachable" Core..=) Core.<$> unreachable
]
)
-- | The response message for Locations.ListLocations.
--
-- /See:/ 'newListLocationsResponse' smart constructor.
data ListLocationsResponse = ListLocationsResponse
{ -- | A list of locations that matches the specified filter in the request.
locations :: (Core.Maybe [Location]),
-- | The standard List next-page token.
nextPageToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListLocationsResponse ' with the minimum fields required to make a request .
newListLocationsResponse ::
ListLocationsResponse
newListLocationsResponse =
ListLocationsResponse {locations = Core.Nothing, nextPageToken = Core.Nothing}
instance Core.FromJSON ListLocationsResponse where
parseJSON =
Core.withObject
"ListLocationsResponse"
( \o ->
ListLocationsResponse
Core.<$> (o Core..:? "locations")
Core.<*> (o Core..:? "nextPageToken")
)
instance Core.ToJSON ListLocationsResponse where
toJSON ListLocationsResponse {..} =
Core.object
( Core.catMaybes
[ ("locations" Core..=) Core.<$> locations,
("nextPageToken" Core..=) Core.<$> nextPageToken
]
)
| The response message for Operations . ListOperations .
--
-- /See:/ 'newListOperationsResponse' smart constructor.
data ListOperationsResponse = ListOperationsResponse
{ -- | The standard List next-page token.
nextPageToken :: (Core.Maybe Core.Text),
-- | A list of operations that matches the specified filter in the request.
operations :: (Core.Maybe [Operation])
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request.
newListOperationsResponse ::
ListOperationsResponse
newListOperationsResponse =
ListOperationsResponse
{ nextPageToken = Core.Nothing,
operations = Core.Nothing
}
instance Core.FromJSON ListOperationsResponse where
parseJSON =
Core.withObject
"ListOperationsResponse"
( \o ->
ListOperationsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "operations")
)
instance Core.ToJSON ListOperationsResponse where
toJSON ListOperationsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("operations" Core..=) Core.<$> operations
]
)
| is the result of ListSnapshotsRequest .
--
-- /See:/ 'newListSnapshotsResponse' smart constructor.
data ListSnapshotsResponse = ListSnapshotsResponse
{ -- | The token you can use to retrieve the next page of results. Not returned if there are no more results in the list.
nextPageToken :: (Core.Maybe Core.Text),
-- | A list of snapshots in the project for the specified instance.
snapshots :: (Core.Maybe [Snapshot])
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListSnapshotsResponse ' with the minimum fields required to make a request .
newListSnapshotsResponse ::
ListSnapshotsResponse
newListSnapshotsResponse =
ListSnapshotsResponse {nextPageToken = Core.Nothing, snapshots = Core.Nothing}
instance Core.FromJSON ListSnapshotsResponse where
parseJSON =
Core.withObject
"ListSnapshotsResponse"
( \o ->
ListSnapshotsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "snapshots")
)
instance Core.ToJSON ListSnapshotsResponse where
toJSON ListSnapshotsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("snapshots" Core..=) Core.<$> snapshots
]
)
| A resource that represents Google Cloud Platform location .
--
/See:/ ' newLocation ' smart constructor .
data Location = Location
{ -- | The friendly name for this location, typically a nearby city name. For example, \"Tokyo\".
displayName :: (Core.Maybe Core.Text),
-- | Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
labels :: (Core.Maybe Location_Labels),
| The canonical i d for this location . For example : @\"us - east1\"@.
locationId :: (Core.Maybe Core.Text),
-- | Service-specific metadata. For example the available capacity at the given location.
metadata :: (Core.Maybe Location_Metadata),
-- | Resource name for the location, which may vary between implementations. For example: @\"projects\/example-project\/locations\/us-east1\"@
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Location' with the minimum fields required to make a request.
newLocation ::
Location
newLocation =
Location
{ displayName = Core.Nothing,
labels = Core.Nothing,
locationId = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON Location where
parseJSON =
Core.withObject
"Location"
( \o ->
Location
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "locationId")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON Location where
toJSON Location {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("labels" Core..=) Core.<$> labels,
("locationId" Core..=) Core.<$> locationId,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name
]
)
-- | Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
--
-- /See:/ 'newLocation_Labels' smart constructor.
newtype Location_Labels = Location_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Location_Labels' with the minimum fields required to make a request.
newLocation_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
Location_Labels
newLocation_Labels additional = Location_Labels {additional = additional}
instance Core.FromJSON Location_Labels where
parseJSON =
Core.withObject
"Location_Labels"
( \o ->
Location_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Labels where
toJSON Location_Labels {..} = Core.toJSON additional
-- | Service-specific metadata. For example the available capacity at the given location.
--
-- /See:/ 'newLocation_Metadata' smart constructor.
newtype Location_Metadata = Location_Metadata
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Location_Metadata' with the minimum fields required to make a request.
newLocation_Metadata ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Location_Metadata
newLocation_Metadata additional = Location_Metadata {additional = additional}
instance Core.FromJSON Location_Metadata where
parseJSON =
Core.withObject
"Location_Metadata"
( \o ->
Location_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Metadata where
toJSON Location_Metadata {..} = Core.toJSON additional
-- | Defines policies to service maintenance events.
--
-- /See:/ 'newMaintenancePolicy' smart constructor.
data MaintenancePolicy = MaintenancePolicy
{ -- | Output only. The time when the resource was created.
createTime :: (Core.Maybe Core.DateTime),
| Optional . Description of what this policy is for . Create\/Update methods return if the length is greater than 512 .
description :: (Core.Maybe Core.Text),
-- | Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
labels :: (Core.Maybe MaintenancePolicy_Labels),
| Required . MaintenancePolicy name using the form : @projects\/{project_id}\/locations\/{location_id}\/maintenancePolicies\/{maintenance_policy_id}@ where { project / id } refers to a GCP consumer project ID , { location / id } refers to a GCP region\/zone , { maintenance / policy / id } must be 1 - 63 characters long and match the regular expression @[a - z0 - 9]([-a - z0 - 9]*[a - z0 - 9])?@.
name :: (Core.Maybe Core.Text),
-- | Optional. The state of the policy.
state :: (Core.Maybe MaintenancePolicy_State),
-- | Maintenance policy applicable to instance update.
updatePolicy :: (Core.Maybe UpdatePolicy),
-- | Output only. The time when the resource was updated.
updateTime :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' MaintenancePolicy ' with the minimum fields required to make a request .
newMaintenancePolicy ::
MaintenancePolicy
newMaintenancePolicy =
MaintenancePolicy
{ createTime = Core.Nothing,
description = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
state = Core.Nothing,
updatePolicy = Core.Nothing,
updateTime = Core.Nothing
}
instance Core.FromJSON MaintenancePolicy where
parseJSON =
Core.withObject
"MaintenancePolicy"
( \o ->
MaintenancePolicy
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "updatePolicy")
Core.<*> (o Core..:? "updateTime")
)
instance Core.ToJSON MaintenancePolicy where
toJSON MaintenancePolicy {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("state" Core..=) Core.<$> state,
("updatePolicy" Core..=) Core.<$> updatePolicy,
("updateTime" Core..=) Core.<$> updateTime
]
)
-- | Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
--
-- /See:/ 'newMaintenancePolicy_Labels' smart constructor.
newtype MaintenancePolicy_Labels = MaintenancePolicy_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' MaintenancePolicy_Labels ' with the minimum fields required to make a request .
newMaintenancePolicy_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
MaintenancePolicy_Labels
newMaintenancePolicy_Labels additional =
MaintenancePolicy_Labels {additional = additional}
instance Core.FromJSON MaintenancePolicy_Labels where
parseJSON =
Core.withObject
"MaintenancePolicy_Labels"
( \o ->
MaintenancePolicy_Labels
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON MaintenancePolicy_Labels where
toJSON MaintenancePolicy_Labels {..} =
Core.toJSON additional
-- | MaintenanceWindow definition.
--
-- /See:/ 'newMaintenanceWindow' smart constructor.
data MaintenanceWindow = MaintenanceWindow
{ -- | Daily cycle.
dailyCycle :: (Core.Maybe DailyCycle),
-- | Weekly cycle.
weeklyCycle :: (Core.Maybe WeeklyCycle)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'MaintenanceWindow' with the minimum fields required to make a request.
newMaintenanceWindow ::
MaintenanceWindow
newMaintenanceWindow =
MaintenanceWindow {dailyCycle = Core.Nothing, weeklyCycle = Core.Nothing}
instance Core.FromJSON MaintenanceWindow where
parseJSON =
Core.withObject
"MaintenanceWindow"
( \o ->
MaintenanceWindow
Core.<$> (o Core..:? "dailyCycle")
Core.<*> (o Core..:? "weeklyCycle")
)
instance Core.ToJSON MaintenanceWindow where
toJSON MaintenanceWindow {..} =
Core.object
( Core.catMaybes
[ ("dailyCycle" Core..=) Core.<$> dailyCycle,
("weeklyCycle" Core..=) Core.<$> weeklyCycle
]
)
-- | Network configuration for the instance.
--
-- /See:/ 'newNetworkConfig' smart constructor.
data NetworkConfig = NetworkConfig
| The network connect mode of the instance . If not provided , the connect mode defaults to DIRECT_PEERING .
connectMode :: (Core.Maybe NetworkConfig_ConnectMode),
| Output only . IPv4 addresses in the format @{octet1}.{octet2}.{octet3}.{octet4}@ or IPv6 addresses in the format @{block1}:{block2}:{block3}:{block4}:{block5}:{block6}:{block7}:{block8}@.
ipAddresses :: (Core.Maybe [Core.Text]),
-- | Internet protocol versions for which the instance has IP addresses assigned. For this version, only MODE_IPV4 is supported.
modes :: (Core.Maybe [NetworkConfig_ModesItem]),
| The name of the Google Compute Engine < VPC network > to which the instance is connected .
network :: (Core.Maybe Core.Text),
| Optional , reserved / ip / range can have one of the following two types of values . * CIDR range value when using DIRECT / PEERING connect mode . * < -addresses/reserve-static-internal-ip-address Allocated IP address range > when using PRIVATE / SERVICE_ACCESS connect mode . When the name of an allocated IP address range is specified , it must be one of the ranges associated with the private service access connection . When specified as a direct CIDR value , it must be a \/29 CIDR block for Basic tier or a \/24 CIDR block for High Scale or Enterprise tier in one of the < / internal IP address ranges > that identifies the range of IP addresses reserved for this instance . For example , 10.0.0.0\/29 or 192.168.0.0\/24 . The range you specify can\'t overlap with either existing subnets or assigned IP address ranges for other Cloud Filestore instances in the selected VPC network .
reservedIpRange :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NetworkConfig ' with the minimum fields required to make a request .
newNetworkConfig ::
NetworkConfig
newNetworkConfig =
NetworkConfig
{ connectMode = Core.Nothing,
ipAddresses = Core.Nothing,
modes = Core.Nothing,
network = Core.Nothing,
reservedIpRange = Core.Nothing
}
instance Core.FromJSON NetworkConfig where
parseJSON =
Core.withObject
"NetworkConfig"
( \o ->
NetworkConfig
Core.<$> (o Core..:? "connectMode")
Core.<*> (o Core..:? "ipAddresses")
Core.<*> (o Core..:? "modes")
Core.<*> (o Core..:? "network")
Core.<*> (o Core..:? "reservedIpRange")
)
instance Core.ToJSON NetworkConfig where
toJSON NetworkConfig {..} =
Core.object
( Core.catMaybes
[ ("connectMode" Core..=) Core.<$> connectMode,
("ipAddresses" Core..=) Core.<$> ipAddresses,
("modes" Core..=) Core.<$> modes,
("network" Core..=) Core.<$> network,
("reservedIpRange" Core..=)
Core.<$> reservedIpRange
]
)
-- | NFS export options specifications.
--
-- /See:/ 'newNfsExportOptions' smart constructor.
data NfsExportOptions = NfsExportOptions
{ -- | Either READ/ONLY, for allowing only read requests on the exported directory, or READ/WRITE, for allowing both read and write requests. The default is READ_WRITE.
accessMode :: (Core.Maybe NfsExportOptions_AccessMode),
| An integer representing the anonymous group i d with a default value of 65534 . Anon / gid may only be set with squash / mode of ROOT / SQUASH . An error will be returned if this field is specified for other squash / mode settings .
anonGid :: (Core.Maybe Core.Int64),
| An integer representing the anonymous user i d with a default value of 65534 . Anon / uid may only be set with squash / mode of ROOT / SQUASH . An error will be returned if this field is specified for other squash / mode settings .
anonUid :: (Core.Maybe Core.Int64),
| List of either an IPv4 addresses in the format @{octet1}.{octet2}.{octet3}.{octet4}@ or CIDR ranges in the format @{octet1}.{octet2}.{octet3}.{octet4}\/{mask size}@ which may mount the file share . Overlapping IP ranges are not allowed , both within and across NfsExportOptions . An error will be returned . The limit is 64 IP ranges\/addresses for each FileShareConfig among all NfsExportOptions .
ipRanges :: (Core.Maybe [Core.Text]),
| Either NO / ROOT / SQUASH , for allowing root access on the exported directory , or ROOT / SQUASH , for not allowing root access . The default is NO / ROOT_SQUASH .
squashMode :: (Core.Maybe NfsExportOptions_SquashMode)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NfsExportOptions ' with the minimum fields required to make a request .
newNfsExportOptions ::
NfsExportOptions
newNfsExportOptions =
NfsExportOptions
{ accessMode = Core.Nothing,
anonGid = Core.Nothing,
anonUid = Core.Nothing,
ipRanges = Core.Nothing,
squashMode = Core.Nothing
}
instance Core.FromJSON NfsExportOptions where
parseJSON =
Core.withObject
"NfsExportOptions"
( \o ->
NfsExportOptions
Core.<$> (o Core..:? "accessMode")
Core.<*> ( o Core..:? "anonGid"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> ( o Core..:? "anonUid"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "ipRanges")
Core.<*> (o Core..:? "squashMode")
)
instance Core.ToJSON NfsExportOptions where
toJSON NfsExportOptions {..} =
Core.object
( Core.catMaybes
[ ("accessMode" Core..=) Core.<$> accessMode,
("anonGid" Core..=) Core.. Core.AsText
Core.<$> anonGid,
("anonUid" Core..=) Core.. Core.AsText
Core.<$> anonUid,
("ipRanges" Core..=) Core.<$> ipRanges,
("squashMode" Core..=) Core.<$> squashMode
]
)
-- | This resource represents a long-running operation that is the result of a network API call.
--
-- /See:/ 'newOperation' smart constructor.
data Operation = Operation
| If the value is @false@ , it means the operation is still in progress . If @true@ , the operation is completed , and either @error@ or @response@ is available .
done :: (Core.Maybe Core.Bool),
-- | The error result of the operation in case of failure or cancellation.
error :: (Core.Maybe Status),
-- | Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
metadata :: (Core.Maybe Operation_Metadata),
| The server - assigned name , which is only unique within the same service that originally returns it . If you use the default HTTP mapping , the @name@ should be a resource name ending with
name :: (Core.Maybe Core.Text),
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
response :: (Core.Maybe Operation_Response)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Operation' with the minimum fields required to make a request.
newOperation ::
Operation
newOperation =
Operation
{ done = Core.Nothing,
error = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing,
response = Core.Nothing
}
instance Core.FromJSON Operation where
parseJSON =
Core.withObject
"Operation"
( \o ->
Operation
Core.<$> (o Core..:? "done")
Core.<*> (o Core..:? "error")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "response")
)
instance Core.ToJSON Operation where
toJSON Operation {..} =
Core.object
( Core.catMaybes
[ ("done" Core..=) Core.<$> done,
("error" Core..=) Core.<$> error,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name,
("response" Core..=) Core.<$> response
]
)
-- | Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
--
-- /See:/ 'newOperation_Metadata' smart constructor.
newtype Operation_Metadata = Operation_Metadata
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Operation_Metadata' with the minimum fields required to make a request.
newOperation_Metadata ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Operation_Metadata
newOperation_Metadata additional = Operation_Metadata {additional = additional}
instance Core.FromJSON Operation_Metadata where
parseJSON =
Core.withObject
"Operation_Metadata"
( \o ->
Operation_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Metadata where
toJSON Operation_Metadata {..} =
Core.toJSON additional
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
--
-- /See:/ 'newOperation_Response' smart constructor.
newtype Operation_Response = Operation_Response
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Operation_Response' with the minimum fields required to make a request.
newOperation_Response ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Operation_Response
newOperation_Response additional = Operation_Response {additional = additional}
instance Core.FromJSON Operation_Response where
parseJSON =
Core.withObject
"Operation_Response"
( \o ->
Operation_Response Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Response where
toJSON Operation_Response {..} =
Core.toJSON additional
-- | Represents the metadata of the long-running operation.
--
/See:/ ' newOperationMetadata ' smart constructor .
data OperationMetadata = OperationMetadata
{ -- | Output only. API version used to start the operation.
apiVersion :: (Core.Maybe Core.Text),
| Output only . Identifies whether the user has requested cancellation of the operation . Operations that have been cancelled successfully have Operation.error value with a google.rpc.Status.code of 1 , corresponding to @Code . CANCELLED@.
cancelRequested :: (Core.Maybe Core.Bool),
-- | Output only. The time the operation was created.
createTime :: (Core.Maybe Core.DateTime),
-- | Output only. The time the operation finished running.
endTime :: (Core.Maybe Core.DateTime),
-- | Output only. Human-readable status of the operation, if any.
statusDetail :: (Core.Maybe Core.Text),
-- | Output only. Server-defined resource path for the target of the operation.
target :: (Core.Maybe Core.Text),
-- | Output only. Name of the verb executed by the operation.
verb :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' OperationMetadata ' with the minimum fields required to make a request .
newOperationMetadata ::
OperationMetadata
newOperationMetadata =
OperationMetadata
{ apiVersion = Core.Nothing,
cancelRequested = Core.Nothing,
createTime = Core.Nothing,
endTime = Core.Nothing,
statusDetail = Core.Nothing,
target = Core.Nothing,
verb = Core.Nothing
}
instance Core.FromJSON OperationMetadata where
parseJSON =
Core.withObject
"OperationMetadata"
( \o ->
OperationMetadata
Core.<$> (o Core..:? "apiVersion")
Core.<*> (o Core..:? "cancelRequested")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "endTime")
Core.<*> (o Core..:? "statusDetail")
Core.<*> (o Core..:? "target")
Core.<*> (o Core..:? "verb")
)
instance Core.ToJSON OperationMetadata where
toJSON OperationMetadata {..} =
Core.object
( Core.catMaybes
[ ("apiVersion" Core..=) Core.<$> apiVersion,
("cancelRequested" Core..=) Core.<$> cancelRequested,
("createTime" Core..=) Core.<$> createTime,
("endTime" Core..=) Core.<$> endTime,
("statusDetail" Core..=) Core.<$> statusDetail,
("target" Core..=) Core.<$> target,
("verb" Core..=) Core.<$> verb
]
)
| RestoreInstanceRequest restores an existing instance\ 's file share from a backup .
--
-- /See:/ 'newRestoreInstanceRequest' smart constructor.
data RestoreInstanceRequest = RestoreInstanceRequest
{ -- | Required. Name of the file share in the Cloud Filestore instance that the backup is being restored to.
fileShare :: (Core.Maybe Core.Text),
-- | The resource name of the backup, in the format @projects\/{project_number}\/locations\/{location_id}\/backups\/{backup_id}@.
sourceBackup :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' RestoreInstanceRequest ' with the minimum fields required to make a request .
newRestoreInstanceRequest ::
RestoreInstanceRequest
newRestoreInstanceRequest =
RestoreInstanceRequest {fileShare = Core.Nothing, sourceBackup = Core.Nothing}
instance Core.FromJSON RestoreInstanceRequest where
parseJSON =
Core.withObject
"RestoreInstanceRequest"
( \o ->
RestoreInstanceRequest
Core.<$> (o Core..:? "fileShare")
Core.<*> (o Core..:? "sourceBackup")
)
instance Core.ToJSON RestoreInstanceRequest where
toJSON RestoreInstanceRequest {..} =
Core.object
( Core.catMaybes
[ ("fileShare" Core..=) Core.<$> fileShare,
("sourceBackup" Core..=) Core.<$> sourceBackup
]
)
-- | Configure the schedule.
--
/See:/ ' ' smart constructor .
data Schedule = Schedule
| Allows to define schedule that runs specified day of the week .
day :: (Core.Maybe Schedule_Day),
-- | Output only. Duration of the time window, set by service producer.
duration :: (Core.Maybe Core.Duration),
-- | Time within the window to start the operations.
startTime :: (Core.Maybe TimeOfDay')
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Schedule' with the minimum fields required to make a request.
newSchedule ::
Schedule
newSchedule =
Schedule
{ day = Core.Nothing,
duration = Core.Nothing,
startTime = Core.Nothing
}
instance Core.FromJSON Schedule where
parseJSON =
Core.withObject
"Schedule"
( \o ->
Schedule
Core.<$> (o Core..:? "day")
Core.<*> (o Core..:? "duration")
Core.<*> (o Core..:? "startTime")
)
instance Core.ToJSON Schedule where
toJSON Schedule {..} =
Core.object
( Core.catMaybes
[ ("day" Core..=) Core.<$> day,
("duration" Core..=) Core.<$> duration,
("startTime" Core..=) Core.<$> startTime
]
)
| A snapshot .
--
-- /See:/ 'newSnapshot' smart constructor.
data Snapshot = Snapshot
{ -- | Output only. The time when the snapshot was created.
createTime :: (Core.Maybe Core.DateTime),
| A description of the snapshot with 2048 characters or less . Requests with longer descriptions will be rejected .
description :: (Core.Maybe Core.Text),
-- | Output only. The amount of bytes needed to allocate a full copy of the snapshot content
filesystemUsedBytes :: (Core.Maybe Core.Int64),
-- | Resource labels to represent user provided metadata.
labels :: (Core.Maybe Snapshot_Labels),
-- | Output only. The resource name of the snapshot, in the format @projects\/{project_id}\/locations\/{location_id}\/instances\/{instance_id}\/snapshots\/{snapshot_id}@.
name :: (Core.Maybe Core.Text),
-- | Output only. The snapshot state.
state :: (Core.Maybe Snapshot_State)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Snapshot ' with the minimum fields required to make a request .
newSnapshot ::
Snapshot
newSnapshot =
Snapshot
{ createTime = Core.Nothing,
description = Core.Nothing,
filesystemUsedBytes = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
state = Core.Nothing
}
instance Core.FromJSON Snapshot where
parseJSON =
Core.withObject
"Snapshot"
( \o ->
Snapshot
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> ( o Core..:? "filesystemUsedBytes"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "state")
)
instance Core.ToJSON Snapshot where
toJSON Snapshot {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("filesystemUsedBytes" Core..=) Core.. Core.AsText
Core.<$> filesystemUsedBytes,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("state" Core..=) Core.<$> state
]
)
-- | Resource labels to represent user provided metadata.
--
-- /See:/ 'newSnapshot_Labels' smart constructor.
newtype Snapshot_Labels = Snapshot_Labels
{ -- |
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Snapshot_Labels' with the minimum fields required to make a request.
newSnapshot_Labels ::
-- | See 'additional'.
Core.HashMap Core.Text Core.Text ->
Snapshot_Labels
newSnapshot_Labels additional = Snapshot_Labels {additional = additional}
instance Core.FromJSON Snapshot_Labels where
parseJSON =
Core.withObject
"Snapshot_Labels"
( \o ->
Snapshot_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Snapshot_Labels where
toJSON Snapshot_Labels {..} = Core.toJSON additional
| The @Status@ type defines a logical error model that is suitable for different programming environments , including REST APIs and RPC APIs . It is used by < > . Each @Status@ message contains three pieces of data : error code , error message , and error details . You can find out more about this error model and how to work with it in the < API Design Guide > .
--
/See:/ ' newStatus ' smart constructor .
data Status = Status
{ -- | The status code, which should be an enum value of google.rpc.Code.
code :: (Core.Maybe Core.Int32),
-- | A list of messages that carry the error details. There is a common set of message types for APIs to use.
details :: (Core.Maybe [Status_DetailsItem]),
| A developer - facing error message , which should be in English . Any user - facing error message should be localized and sent in the google.rpc.Status.details field , or localized by the client .
message :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Status' with the minimum fields required to make a request.
newStatus ::
Status
newStatus =
Status {code = Core.Nothing, details = Core.Nothing, message = Core.Nothing}
instance Core.FromJSON Status where
parseJSON =
Core.withObject
"Status"
( \o ->
Status
Core.<$> (o Core..:? "code")
Core.<*> (o Core..:? "details")
Core.<*> (o Core..:? "message")
)
instance Core.ToJSON Status where
toJSON Status {..} =
Core.object
( Core.catMaybes
[ ("code" Core..=) Core.<$> code,
("details" Core..=) Core.<$> details,
("message" Core..=) Core.<$> message
]
)
--
-- /See:/ 'newStatus_DetailsItem' smart constructor.
newtype Status_DetailsItem = Status_DetailsItem
{ -- | Properties of the object. Contains field \@type with type URL.
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Status_DetailsItem' with the minimum fields required to make a request.
newStatus_DetailsItem ::
-- | Properties of the object. Contains field \@type with type URL. See 'additional'.
Core.HashMap Core.Text Core.Value ->
Status_DetailsItem
newStatus_DetailsItem additional = Status_DetailsItem {additional = additional}
instance Core.FromJSON Status_DetailsItem where
parseJSON =
Core.withObject
"Status_DetailsItem"
( \o ->
Status_DetailsItem Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Status_DetailsItem where
toJSON Status_DetailsItem {..} =
Core.toJSON additional
| Represents a time of day . The date and time zone are either not significant or are specified elsewhere . An API may choose to allow leap seconds . Related types are google.type . Date and @google.protobuf . Timestamp@.
--
-- /See:/ 'newTimeOfDay' smart constructor.
data TimeOfDay' = TimeOfDay'
| Hours of day in 24 hour format . Should be from 0 to 23 . An API may choose to allow the value \"24:00:00\ " for scenarios like business closing time .
hours :: (Core.Maybe Core.Int32),
| Minutes of hour of day . Must be from 0 to 59 .
minutes :: (Core.Maybe Core.Int32),
| Fractions of seconds in nanoseconds . Must be from 0 to 999,999,999 .
nanos :: (Core.Maybe Core.Int32),
| Seconds of minutes of the time . Must normally be from 0 to 59 . An API may allow the value 60 if it allows leap - seconds .
seconds :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newTimeOfDay ::
TimeOfDay'
newTimeOfDay =
TimeOfDay'
{ hours = Core.Nothing,
minutes = Core.Nothing,
nanos = Core.Nothing,
seconds = Core.Nothing
}
instance Core.FromJSON TimeOfDay' where
parseJSON =
Core.withObject
"TimeOfDay'"
( \o ->
TimeOfDay'
Core.<$> (o Core..:? "hours")
Core.<*> (o Core..:? "minutes")
Core.<*> (o Core..:? "nanos")
Core.<*> (o Core..:? "seconds")
)
instance Core.ToJSON TimeOfDay' where
toJSON TimeOfDay' {..} =
Core.object
( Core.catMaybes
[ ("hours" Core..=) Core.<$> hours,
("minutes" Core..=) Core.<$> minutes,
("nanos" Core..=) Core.<$> nanos,
("seconds" Core..=) Core.<$> seconds
]
)
-- | Maintenance policy applicable to instance updates.
--
-- /See:/ 'newUpdatePolicy' smart constructor.
data UpdatePolicy = UpdatePolicy
{ -- | Optional. Relative scheduling channel applied to resource.
channel :: (Core.Maybe UpdatePolicy_Channel),
| Deny Maintenance Period that is applied to resource to indicate when maintenance is forbidden . User can specify zero or more non - overlapping deny periods . Maximum number of deny / maintenance / periods expected is one .
denyMaintenancePeriods :: (Core.Maybe [DenyMaintenancePeriod]),
-- | Optional. Maintenance window that is applied to resources covered by this policy.
window :: (Core.Maybe MaintenanceWindow)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' UpdatePolicy ' with the minimum fields required to make a request .
newUpdatePolicy ::
UpdatePolicy
newUpdatePolicy =
UpdatePolicy
{ channel = Core.Nothing,
denyMaintenancePeriods = Core.Nothing,
window = Core.Nothing
}
instance Core.FromJSON UpdatePolicy where
parseJSON =
Core.withObject
"UpdatePolicy"
( \o ->
UpdatePolicy
Core.<$> (o Core..:? "channel")
Core.<*> (o Core..:? "denyMaintenancePeriods")
Core.<*> (o Core..:? "window")
)
instance Core.ToJSON UpdatePolicy where
toJSON UpdatePolicy {..} =
Core.object
( Core.catMaybes
[ ("channel" Core..=) Core.<$> channel,
("denyMaintenancePeriods" Core..=)
Core.<$> denyMaintenancePeriods,
("window" Core..=) Core.<$> window
]
)
| Time window specified for weekly operations .
--
-- /See:/ 'newWeeklyCycle' smart constructor.
newtype WeeklyCycle = WeeklyCycle
| User can specify multiple windows in a week . Minimum of 1 window .
schedule :: (Core.Maybe [Schedule])
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' WeeklyCycle ' with the minimum fields required to make a request .
newWeeklyCycle ::
WeeklyCycle
newWeeklyCycle = WeeklyCycle {schedule = Core.Nothing}
instance Core.FromJSON WeeklyCycle where
parseJSON =
Core.withObject
"WeeklyCycle"
(\o -> WeeklyCycle Core.<$> (o Core..:? "schedule"))
instance Core.ToJSON WeeklyCycle where
toJSON WeeklyCycle {..} =
Core.object
( Core.catMaybes
[("schedule" Core..=) Core.<$> schedule]
)
| null | https://raw.githubusercontent.com/brendanhay/gogol/8cbceeaaba36a3c08712b2e272606161500fbe91/lib/services/gogol-file/gen/Gogol/File/Internal/Product.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* Backup
* Backup_Labels
* CancelOperationRequest
* Date
* DenyMaintenancePeriod
* Empty
* FileShareConfig
* GoogleCloudSaasacceleratorManagementProvidersV1Instance
* GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
* GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
* GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
* GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
* GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
* GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
* GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
* GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
* GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
* GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
* GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
* GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
* GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
* GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
* GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
* Instance
* Instance_Labels
* ListOperationsResponse
* Location
* Location_Labels
* Location_Metadata
* MaintenanceWindow
* Operation
* Operation_Metadata
* Operation_Response
* OperationMetadata
* RestoreInstanceRequest
* Schedule
* Snapshot
* Snapshot_Labels
* Status
* Status_DetailsItem
* WeeklyCycle
| A Cloud Filestore backup.
| Output only. Capacity of the source file share when the backup was created.
| Output only. The time when the backup was created.
| Output only. Amount of bytes that will be downloaded if the backup is restored. This may be different than storage bytes, since sequential backups of the same disk will share storage.
| Resource labels to represent user provided metadata.
| Output only. The resource name of the backup, in the format @projects\/{project_number}\/locations\/{location_id}\/backups\/{backup_id}@.
| Output only. Reserved for future use.
| Output only. The backup state.
| Output only. The size of the storage used by the backup. As backups share storage, this number is expected to change with backup creation\/deletion.
| Creates a value of 'Backup' with the minimum fields required to make a request.
| Resource labels to represent user provided metadata.
/See:/ 'newBackup_Labels' smart constructor.
|
| Creates a value of 'Backup_Labels' with the minimum fields required to make a request.
| See 'additional'.
| Creates a value of 'CancelOperationRequest' with the minimum fields required to make a request.
/See:/ 'newDailyCycle' smart constructor.
| Output only. Duration of the time window, set by service producer.
/See:/ 'newDate' smart constructor.
| Creates a value of 'Date' with the minimum fields required to make a request.
| DenyMaintenancePeriod definition. Maintenance is forbidden within the deny period. The start/date must be less than the end/date.
/See:/ 'newDenyMaintenancePeriod' smart constructor.
| Creates a value of 'DenyMaintenancePeriod' with the minimum fields required to make a request.
| Creates a value of 'Empty' with the minimum fields required to make a request.
| File share configuration for the instance.
/See:/ 'newFileShareConfig' smart constructor.
| The resource name of the backup, in the format @projects\/{project_number}\/locations\/{location_id}\/backups\/{backup_id}@, that this file share has been restored from.
| Creates a value of 'FileShareConfig' with the minimum fields required to make a request.
| Output only. Timestamp when the resource was created.
| Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
| The MaintenanceSchedule contains the scheduling information of published maintenance schedule with same key as software_versions.
| Output only. Custom string attributes used primarily to expose producer-specific information in monitoring dashboards. See go\/get-instance-metadata.
| Software versions that are used to deploy this instance. This can be mutated by rollout services.
| Output only. Timestamp when the resource was last modified.
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance' with the minimum fields required to make a request.
| Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels' smart constructor.
|
| See 'additional'.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames' smart constructor.
|
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames' with the minimum fields required to make a request.
| See 'additional'.
| The MaintenanceSchedule contains the scheduling information of published maintenance schedule with same key as software_versions.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules' smart constructor.
|
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules' with the minimum fields required to make a request.
| See 'additional'.
|
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters' with the minimum fields required to make a request.
| See 'additional'.
| Output only. Custom string attributes used primarily to expose producer-specific information in monitoring dashboards. See go\/get-instance-metadata.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata' smart constructor.
|
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata' with the minimum fields required to make a request.
| See 'additional'.
| Software versions that are used to deploy this instance. This can be mutated by rollout services.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions' smart constructor.
|
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions' with the minimum fields required to make a request.
| See 'additional'.
| Maintenance schedule which is exposed to customer and potentially end user, indicating published upcoming future maintenance schedule
| This field is deprecated, and will be always set to true since reschedule can happen multiple times now. This field should not be removed until all service producers remove this for their customers.
| The scheduled end time for the maintenance.
| The rollout management policy this maintenance schedule is associated with. When doing reschedule update request, the reschedule should be against this given policy.
| The scheduled start time for the maintenance.
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule' with the minimum fields required to make a request.
| Maintenance settings associated with instance. Allows service producers and end users to assign settings that controls maintenance on this instance.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings' smart constructor.
| Optional. Exclude instance from maintenance. When true, rollout service will not attempt maintenance on the instance. Rollout service will include the instance in reported rollout progress as not attempted.
| Optional. If the update call is triggered from rollback, set the value as true.
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings' with the minimum fields required to make a request.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies' smart constructor.
|
| See 'additional'.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata' smart constructor.
| The location of the node, if different from instance location.
| The id of the node. This should be equal to SaasInstanceNode.node_id.
| If present, this will override eligibility for the node coming from instance or exclusions for specified SLIs.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility' smart constructor.
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility' with the minimum fields required to make a request.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities' smart constructor.
|
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities' with the minimum fields required to make a request.
| See 'additional'.
| Describes provisioned dataplane resources.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource' smart constructor.
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource' with the minimum fields required to make a request.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility' smart constructor.
| Whether an instance is eligible or ineligible.
| User-defined reason for the current value of instance eligibility. Usually, this can be directly mapped to the internal state. An empty reason is allowed.
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility' with the minimum fields required to make a request.
/See:/ 'newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata' smart constructor.
| Creates a value of 'GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata' with the minimum fields required to make a request.
| A Cloud Filestore instance.
| Output only. The time when the instance was created.
| Server-specified ETag for the instance resource to prevent simultaneous updates from overwriting each other.
| File system shares on the instance. For this version, only a single file share is supported.
| Resource labels to represent user provided metadata.
| Output only. The resource name of the instance, in the format @projects\/{project}\/locations\/{location}\/instances\/{instance}@.
| VPC networks to which the instance is connected. For this version, only a single network is supported.
| Output only. Reserved for future use.
| Output only. The instance state.
| Output only. Additional information about the instance state, if available.
| The service tier of the instance.
| Creates a value of 'Instance' with the minimum fields required to make a request.
| Resource labels to represent user provided metadata.
/See:/ 'newInstance_Labels' smart constructor.
|
| See 'additional'.
/See:/ 'newListBackupsResponse' smart constructor.
| The token you can use to retrieve the next page of results. Not returned if there are no more results in the list.
| Locations that could not be reached.
| Creates a value of 'ListBackupsResponse' with the minimum fields required to make a request.
/See:/ 'newListInstancesResponse' smart constructor.
| The token you can use to retrieve the next page of results. Not returned if there are no more results in the list.
| Locations that could not be reached.
| Creates a value of 'ListInstancesResponse' with the minimum fields required to make a request.
| The response message for Locations.ListLocations.
/See:/ 'newListLocationsResponse' smart constructor.
| A list of locations that matches the specified filter in the request.
| The standard List next-page token.
/See:/ 'newListOperationsResponse' smart constructor.
| The standard List next-page token.
| A list of operations that matches the specified filter in the request.
| Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request.
/See:/ 'newListSnapshotsResponse' smart constructor.
| The token you can use to retrieve the next page of results. Not returned if there are no more results in the list.
| A list of snapshots in the project for the specified instance.
| The friendly name for this location, typically a nearby city name. For example, \"Tokyo\".
| Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
| Service-specific metadata. For example the available capacity at the given location.
| Resource name for the location, which may vary between implementations. For example: @\"projects\/example-project\/locations\/us-east1\"@
| Creates a value of 'Location' with the minimum fields required to make a request.
| Cross-service attributes for the location. For example {\"cloud.googleapis.com\/region\": \"us-east1\"}
/See:/ 'newLocation_Labels' smart constructor.
|
| Creates a value of 'Location_Labels' with the minimum fields required to make a request.
| See 'additional'.
| Service-specific metadata. For example the available capacity at the given location.
/See:/ 'newLocation_Metadata' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Location_Metadata' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
| Defines policies to service maintenance events.
/See:/ 'newMaintenancePolicy' smart constructor.
| Output only. The time when the resource was created.
| Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
| Optional. The state of the policy.
| Maintenance policy applicable to instance update.
| Output only. The time when the resource was updated.
| Optional. Resource labels to represent user provided metadata. Each label is a key-value pair, where both the key and the value are arbitrary strings provided by the user.
/See:/ 'newMaintenancePolicy_Labels' smart constructor.
|
| See 'additional'.
| MaintenanceWindow definition.
/See:/ 'newMaintenanceWindow' smart constructor.
| Daily cycle.
| Weekly cycle.
| Creates a value of 'MaintenanceWindow' with the minimum fields required to make a request.
| Network configuration for the instance.
/See:/ 'newNetworkConfig' smart constructor.
| Internet protocol versions for which the instance has IP addresses assigned. For this version, only MODE_IPV4 is supported.
| NFS export options specifications.
/See:/ 'newNfsExportOptions' smart constructor.
| Either READ/ONLY, for allowing only read requests on the exported directory, or READ/WRITE, for allowing both read and write requests. The default is READ_WRITE.
| This resource represents a long-running operation that is the result of a network API call.
/See:/ 'newOperation' smart constructor.
| The error result of the operation in case of failure or cancellation.
| Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
| Creates a value of 'Operation' with the minimum fields required to make a request.
| Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
/See:/ 'newOperation_Metadata' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Operation_Metadata' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
/See:/ 'newOperation_Response' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Operation_Response' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
| Represents the metadata of the long-running operation.
| Output only. API version used to start the operation.
| Output only. The time the operation was created.
| Output only. The time the operation finished running.
| Output only. Human-readable status of the operation, if any.
| Output only. Server-defined resource path for the target of the operation.
| Output only. Name of the verb executed by the operation.
/See:/ 'newRestoreInstanceRequest' smart constructor.
| Required. Name of the file share in the Cloud Filestore instance that the backup is being restored to.
| The resource name of the backup, in the format @projects\/{project_number}\/locations\/{location_id}\/backups\/{backup_id}@.
| Configure the schedule.
| Output only. Duration of the time window, set by service producer.
| Time within the window to start the operations.
| Creates a value of 'Schedule' with the minimum fields required to make a request.
/See:/ 'newSnapshot' smart constructor.
| Output only. The time when the snapshot was created.
| Output only. The amount of bytes needed to allocate a full copy of the snapshot content
| Resource labels to represent user provided metadata.
| Output only. The resource name of the snapshot, in the format @projects\/{project_id}\/locations\/{location_id}\/instances\/{instance_id}\/snapshots\/{snapshot_id}@.
| Output only. The snapshot state.
| Resource labels to represent user provided metadata.
/See:/ 'newSnapshot_Labels' smart constructor.
|
| Creates a value of 'Snapshot_Labels' with the minimum fields required to make a request.
| See 'additional'.
| The status code, which should be an enum value of google.rpc.Code.
| A list of messages that carry the error details. There is a common set of message types for APIs to use.
| Creates a value of 'Status' with the minimum fields required to make a request.
/See:/ 'newStatus_DetailsItem' smart constructor.
| Properties of the object. Contains field \@type with type URL.
| Creates a value of 'Status_DetailsItem' with the minimum fields required to make a request.
| Properties of the object. Contains field \@type with type URL. See 'additional'.
/See:/ 'newTimeOfDay' smart constructor.
| Maintenance policy applicable to instance updates.
/See:/ 'newUpdatePolicy' smart constructor.
| Optional. Relative scheduling channel applied to resource.
| Optional. Maintenance window that is applied to resources covered by this policy.
/See:/ 'newWeeklyCycle' smart constructor. | # 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 : . File . Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.File.Internal.Product
Backup (..),
newBackup,
Backup_Labels (..),
newBackup_Labels,
CancelOperationRequest (..),
newCancelOperationRequest,
*
DailyCycle (..),
newDailyCycle,
Date (..),
newDate,
DenyMaintenancePeriod (..),
newDenyMaintenancePeriod,
Empty (..),
newEmpty,
FileShareConfig (..),
newFileShareConfig,
GoogleCloudSaasacceleratorManagementProvidersV1Instance (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance,
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels,
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames,
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules,
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters,
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata,
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions (..),
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions,
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule (..),
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule,
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings (..),
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings,
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies (..),
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies,
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata (..),
newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata,
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility (..),
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility,
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities (..),
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities,
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource (..),
newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource,
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility (..),
newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility,
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata (..),
newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata,
Instance (..),
newInstance,
Instance_Labels (..),
newInstance_Labels,
* ListBackupsResponse
ListBackupsResponse (..),
newListBackupsResponse,
* ListInstancesResponse
ListInstancesResponse (..),
newListInstancesResponse,
* ListLocationsResponse
ListLocationsResponse (..),
newListLocationsResponse,
ListOperationsResponse (..),
newListOperationsResponse,
*
ListSnapshotsResponse (..),
newListSnapshotsResponse,
Location (..),
newLocation,
Location_Labels (..),
newLocation_Labels,
Location_Metadata (..),
newLocation_Metadata,
* MaintenancePolicy
MaintenancePolicy (..),
newMaintenancePolicy,
*
MaintenancePolicy_Labels (..),
newMaintenancePolicy_Labels,
MaintenanceWindow (..),
newMaintenanceWindow,
* NetworkConfig
NetworkConfig (..),
newNetworkConfig,
* NfsExportOptions
NfsExportOptions (..),
newNfsExportOptions,
Operation (..),
newOperation,
Operation_Metadata (..),
newOperation_Metadata,
Operation_Response (..),
newOperation_Response,
OperationMetadata (..),
newOperationMetadata,
RestoreInstanceRequest (..),
newRestoreInstanceRequest,
Schedule (..),
newSchedule,
Snapshot (..),
newSnapshot,
Snapshot_Labels (..),
newSnapshot_Labels,
Status (..),
newStatus,
Status_DetailsItem (..),
newStatus_DetailsItem,
* '
TimeOfDay' (..),
newTimeOfDay,
* UpdatePolicy
UpdatePolicy (..),
newUpdatePolicy,
WeeklyCycle (..),
newWeeklyCycle,
)
where
import Gogol.File.Internal.Sum
import qualified Gogol.Prelude as Core
/See:/ ' ' smart constructor .
data Backup = Backup
capacityGb :: (Core.Maybe Core.Int64),
createTime :: (Core.Maybe Core.DateTime),
| A description of the backup with 2048 characters or less . Requests with longer descriptions will be rejected .
description :: (Core.Maybe Core.Text),
downloadBytes :: (Core.Maybe Core.Int64),
labels :: (Core.Maybe Backup_Labels),
name :: (Core.Maybe Core.Text),
satisfiesPzs :: (Core.Maybe Core.Bool),
| Name of the file share in the source Cloud Filestore instance that the backup is created from .
sourceFileShare :: (Core.Maybe Core.Text),
| The resource name of the source Cloud Filestore instance , in the format @projects\/{project_number}\/locations\/{location_id}\/instances\/{instance_id}@ , used to create this backup .
sourceInstance :: (Core.Maybe Core.Text),
| Output only . The service tier of the source Cloud Filestore instance that this backup is created from .
sourceInstanceTier :: (Core.Maybe Backup_SourceInstanceTier),
state :: (Core.Maybe Backup_State),
storageBytes :: (Core.Maybe Core.Int64)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newBackup ::
Backup
newBackup =
Backup
{ capacityGb = Core.Nothing,
createTime = Core.Nothing,
description = Core.Nothing,
downloadBytes = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
satisfiesPzs = Core.Nothing,
sourceFileShare = Core.Nothing,
sourceInstance = Core.Nothing,
sourceInstanceTier = Core.Nothing,
state = Core.Nothing,
storageBytes = Core.Nothing
}
instance Core.FromJSON Backup where
parseJSON =
Core.withObject
"Backup"
( \o ->
Backup
Core.<$> ( o Core..:? "capacityGb"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> ( o Core..:? "downloadBytes"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "satisfiesPzs")
Core.<*> (o Core..:? "sourceFileShare")
Core.<*> (o Core..:? "sourceInstance")
Core.<*> (o Core..:? "sourceInstanceTier")
Core.<*> (o Core..:? "state")
Core.<*> ( o Core..:? "storageBytes"
Core.<&> Core.fmap Core.fromAsText
)
)
instance Core.ToJSON Backup where
toJSON Backup {..} =
Core.object
( Core.catMaybes
[ ("capacityGb" Core..=) Core.. Core.AsText
Core.<$> capacityGb,
("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("downloadBytes" Core..=) Core.. Core.AsText
Core.<$> downloadBytes,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("satisfiesPzs" Core..=) Core.<$> satisfiesPzs,
("sourceFileShare" Core..=) Core.<$> sourceFileShare,
("sourceInstance" Core..=) Core.<$> sourceInstance,
("sourceInstanceTier" Core..=)
Core.<$> sourceInstanceTier,
("state" Core..=) Core.<$> state,
("storageBytes" Core..=) Core.. Core.AsText
Core.<$> storageBytes
]
)
newtype Backup_Labels = Backup_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newBackup_Labels ::
Core.HashMap Core.Text Core.Text ->
Backup_Labels
newBackup_Labels additional = Backup_Labels {additional = additional}
instance Core.FromJSON Backup_Labels where
parseJSON =
Core.withObject
"Backup_Labels"
( \o ->
Backup_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Backup_Labels where
toJSON Backup_Labels {..} = Core.toJSON additional
| The request message for Operations . CancelOperation .
/See:/ ' newCancelOperationRequest ' smart constructor .
data CancelOperationRequest = CancelOperationRequest
deriving (Core.Eq, Core.Show, Core.Generic)
newCancelOperationRequest ::
CancelOperationRequest
newCancelOperationRequest = CancelOperationRequest
instance Core.FromJSON CancelOperationRequest where
parseJSON =
Core.withObject
"CancelOperationRequest"
(\o -> Core.pure CancelOperationRequest)
instance Core.ToJSON CancelOperationRequest where
toJSON = Core.const Core.emptyObject
| Time window specified for daily operations .
data DailyCycle = DailyCycle
duration :: (Core.Maybe Core.Duration),
| Time within the day to start the operations .
startTime :: (Core.Maybe TimeOfDay')
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' DailyCycle ' with the minimum fields required to make a request .
newDailyCycle ::
DailyCycle
newDailyCycle = DailyCycle {duration = Core.Nothing, startTime = Core.Nothing}
instance Core.FromJSON DailyCycle where
parseJSON =
Core.withObject
"DailyCycle"
( \o ->
DailyCycle
Core.<$> (o Core..:? "duration")
Core.<*> (o Core..:? "startTime")
)
instance Core.ToJSON DailyCycle where
toJSON DailyCycle {..} =
Core.object
( Core.catMaybes
[ ("duration" Core..=) Core.<$> duration,
("startTime" Core..=) Core.<$> startTime
]
)
| Represents a whole or partial calendar date , such as a birthday . The time of day and time zone are either specified elsewhere or are insignificant . The date is relative to the Gregorian Calendar . This can represent one of the following : * A full date , with non - zero year , month , and day values * A month and day , with a zero year ( e.g. , an anniversary ) * A year on its own , with a zero month and a zero day * A year and month , with a zero day ( e.g. , a credit card expiration date ) Related types : * google.type . * google.type . DateTime * google.protobuf . Timestamp
data Date = Date
| Day of a month . Must be from 1 to 31 and valid for the year and month , or 0 to specify a year by itself or a year and month where the day isn\'t significant .
day :: (Core.Maybe Core.Int32),
| Month of a year . Must be from 1 to 12 , or 0 to specify a year without a month and day .
month :: (Core.Maybe Core.Int32),
| Year of the date . Must be from 1 to 9999 , or 0 to specify a date without a year .
year :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newDate ::
Date
newDate = Date {day = Core.Nothing, month = Core.Nothing, year = Core.Nothing}
instance Core.FromJSON Date where
parseJSON =
Core.withObject
"Date"
( \o ->
Date
Core.<$> (o Core..:? "day")
Core.<*> (o Core..:? "month")
Core.<*> (o Core..:? "year")
)
instance Core.ToJSON Date where
toJSON Date {..} =
Core.object
( Core.catMaybes
[ ("day" Core..=) Core.<$> day,
("month" Core..=) Core.<$> month,
("year" Core..=) Core.<$> year
]
)
data DenyMaintenancePeriod = DenyMaintenancePeriod
| Deny period end date . This can be : * A full date , with non - zero year , month and day values . * A month and day value , with a zero year . Allows recurring deny periods each year . Date matching this period will have to be before the end .
endDate :: (Core.Maybe Date),
| Deny period start date . This can be : * A full date , with non - zero year , month and day values . * A month and day value , with a zero year . Allows recurring deny periods each year . Date matching this period will have to be the same or after the start .
startDate :: (Core.Maybe Date),
| Time in UTC when the Blackout period starts on start / date and ends on end / date . This can be : * Full time . * All zeros for 00:00:00 UTC
time :: (Core.Maybe TimeOfDay')
}
deriving (Core.Eq, Core.Show, Core.Generic)
newDenyMaintenancePeriod ::
DenyMaintenancePeriod
newDenyMaintenancePeriod =
DenyMaintenancePeriod
{ endDate = Core.Nothing,
startDate = Core.Nothing,
time = Core.Nothing
}
instance Core.FromJSON DenyMaintenancePeriod where
parseJSON =
Core.withObject
"DenyMaintenancePeriod"
( \o ->
DenyMaintenancePeriod
Core.<$> (o Core..:? "endDate")
Core.<*> (o Core..:? "startDate")
Core.<*> (o Core..:? "time")
)
instance Core.ToJSON DenyMaintenancePeriod where
toJSON DenyMaintenancePeriod {..} =
Core.object
( Core.catMaybes
[ ("endDate" Core..=) Core.<$> endDate,
("startDate" Core..=) Core.<$> startDate,
("time" Core..=) Core.<$> time
]
)
| A generic empty message that you can re - use to avoid defining duplicated empty messages in your APIs . A typical example is to use it as the request or the response type of an API method . For instance : service Foo { rpc Bar(google.protobuf . Empty ) returns ( google.protobuf . Empty ) ; } The JSON representation for @Empty@ is empty JSON object @{}@.
/See:/ ' ' smart constructor .
data Empty = Empty
deriving (Core.Eq, Core.Show, Core.Generic)
newEmpty ::
Empty
newEmpty = Empty
instance Core.FromJSON Empty where
parseJSON =
Core.withObject "Empty" (\o -> Core.pure Empty)
instance Core.ToJSON Empty where
toJSON = Core.const Core.emptyObject
data FileShareConfig = FileShareConfig
| File share capacity in gigabytes ( GB ) . defines 1 GB as 1024 ^ 3 bytes .
capacityGb :: (Core.Maybe Core.Int64),
| The name of the file share ( must be 16 characters or less ) .
name :: (Core.Maybe Core.Text),
| Nfs Export Options . There is a limit of 10 export options per file share .
nfsExportOptions :: (Core.Maybe [NfsExportOptions]),
sourceBackup :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newFileShareConfig ::
FileShareConfig
newFileShareConfig =
FileShareConfig
{ capacityGb = Core.Nothing,
name = Core.Nothing,
nfsExportOptions = Core.Nothing,
sourceBackup = Core.Nothing
}
instance Core.FromJSON FileShareConfig where
parseJSON =
Core.withObject
"FileShareConfig"
( \o ->
FileShareConfig
Core.<$> ( o Core..:? "capacityGb"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "nfsExportOptions")
Core.<*> (o Core..:? "sourceBackup")
)
instance Core.ToJSON FileShareConfig where
toJSON FileShareConfig {..} =
Core.object
( Core.catMaybes
[ ("capacityGb" Core..=) Core.. Core.AsText
Core.<$> capacityGb,
("name" Core..=) Core.<$> name,
("nfsExportOptions" Core..=)
Core.<$> nfsExportOptions,
("sourceBackup" Core..=) Core.<$> sourceBackup
]
)
/See:/ ' newGoogleCloudSaasacceleratorManagementProvidersV1Instance ' smart constructor .
data GoogleCloudSaasacceleratorManagementProvidersV1Instance = GoogleCloudSaasacceleratorManagementProvidersV1Instance
| consumer / defined / name is the name that is set by the consumer . On the other hand Name field represents system - assigned i d of an instance so consumers are not necessarily aware of it . consumer / defined / name is used for notification\/UI purposes for consumer to recognize their instances .
consumerDefinedName :: (Core.Maybe Core.Text),
createTime :: (Core.Maybe Core.DateTime),
| Optional . The instance / type of this instance of format : projects\/{project / id}\/locations\/{location / id}\/instanceTypes\/{instance / type / id } . Instance Type represents a high - level tier or SKU of the service that this instance belong to . When enabled(eg : Maintenance Rollout ) , Rollout uses \'instance / type\ ' along with \'software_versions\ ' to determine whether instance needs an update or not .
instanceType :: (Core.Maybe Core.Text),
labels ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
),
| Deprecated . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the referenced policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug .
maintenancePolicyNames ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
),
maintenanceSchedules ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
),
| Optional . The MaintenanceSettings associated with instance .
maintenanceSettings ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
),
| Unique name of the resource . It uses the form : @projects\/{project_id|project_number}\/locations\/{location_id}\/instances\/{instance_id}@ Note : Either project / id or project / number can be used , but keep it consistent with other APIs ( e.g. RescheduleUpdate )
name :: (Core.Maybe Core.Text),
| Optional . notification_parameters are information that service producers may like to include that is not relevant to Rollout . This parameter will only be passed to Gamma and Cloud Logging for notification\/logging purpose .
notificationParameters ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
),
producerMetadata ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
),
| Output only . The list of data plane resources provisioned for this instance , e.g. compute VMs . See go\/get - instance - metadata .
provisionedResources ::
( Core.Maybe
[GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource]
),
| Link to the SLM instance template . Only populated when updating SLM instances via SSA\ 's Actuation service adaptor . Service producers with custom control plane ( e.g. Cloud SQL ) doesn\'t need to populate this field . Instead they should use software_versions .
slmInstanceTemplate :: (Core.Maybe Core.Text),
| Output only . SLO metadata for instance classification in the Standardized dataplane SLO platform . See go\/cloud - ssa - standard - slo for feature description .
sloMetadata ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
),
softwareVersions ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
),
| Output only . Current lifecycle state of the resource ( e.g. if it\ 's being created or ready to use ) .
state ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1Instance_State
),
| Output only . ID of the associated GCP tenant project . See go\/get - instance - metadata .
tenantProjectId :: (Core.Maybe Core.Text),
updateTime :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1Instance ::
GoogleCloudSaasacceleratorManagementProvidersV1Instance
newGoogleCloudSaasacceleratorManagementProvidersV1Instance =
GoogleCloudSaasacceleratorManagementProvidersV1Instance
{ consumerDefinedName = Core.Nothing,
createTime = Core.Nothing,
instanceType = Core.Nothing,
labels = Core.Nothing,
maintenancePolicyNames = Core.Nothing,
maintenanceSchedules = Core.Nothing,
maintenanceSettings = Core.Nothing,
name = Core.Nothing,
notificationParameters = Core.Nothing,
producerMetadata = Core.Nothing,
provisionedResources = Core.Nothing,
slmInstanceTemplate = Core.Nothing,
sloMetadata = Core.Nothing,
softwareVersions = Core.Nothing,
state = Core.Nothing,
tenantProjectId = Core.Nothing,
updateTime = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance
Core.<$> (o Core..:? "consumerDefinedName")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "instanceType")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "maintenancePolicyNames")
Core.<*> (o Core..:? "maintenanceSchedules")
Core.<*> (o Core..:? "maintenanceSettings")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "notificationParameters")
Core.<*> (o Core..:? "producerMetadata")
Core.<*> (o Core..:? "provisionedResources")
Core.<*> (o Core..:? "slmInstanceTemplate")
Core.<*> (o Core..:? "sloMetadata")
Core.<*> (o Core..:? "softwareVersions")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "tenantProjectId")
Core.<*> (o Core..:? "updateTime")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance {..} =
Core.object
( Core.catMaybes
[ ("consumerDefinedName" Core..=)
Core.<$> consumerDefinedName,
("createTime" Core..=) Core.<$> createTime,
("instanceType" Core..=) Core.<$> instanceType,
("labels" Core..=) Core.<$> labels,
("maintenancePolicyNames" Core..=)
Core.<$> maintenancePolicyNames,
("maintenanceSchedules" Core..=)
Core.<$> maintenanceSchedules,
("maintenanceSettings" Core..=)
Core.<$> maintenanceSettings,
("name" Core..=) Core.<$> name,
("notificationParameters" Core..=)
Core.<$> notificationParameters,
("producerMetadata" Core..=)
Core.<$> producerMetadata,
("provisionedResources" Core..=)
Core.<$> provisionedResources,
("slmInstanceTemplate" Core..=)
Core.<$> slmInstanceTemplate,
("sloMetadata" Core..=) Core.<$> sloMetadata,
("softwareVersions" Core..=)
Core.<$> softwareVersions,
("state" Core..=) Core.<$> state,
("tenantProjectId" Core..=) Core.<$> tenantProjectId,
("updateTime" Core..=) Core.<$> updateTime
]
)
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels = GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels ' with the minimum fields required to make a request .
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels ::
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_Labels {..} =
Core.toJSON additional
| Deprecated . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the referenced policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug .
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames = GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames ::
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenancePolicyNames {..} =
Core.toJSON additional
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules = GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
additional ::
( Core.HashMap
Core.Text
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules ::
Core.HashMap Core.Text GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_MaintenanceSchedules {..} =
Core.toJSON additional
| Optional . notification_parameters are information that service producers may like to include that is not relevant to Rollout . This parameter will only be passed to Gamma and Cloud Logging for notification\/logging purpose .
/See:/ ' newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters ' smart constructor .
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters = GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters ::
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_NotificationParameters {..} =
Core.toJSON additional
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata = GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata ::
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_ProducerMetadata {..} =
Core.toJSON additional
newtype GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions = GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions ::
Core.HashMap Core.Text Core.Text ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
newGoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions additional =
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1Instance_SoftwareVersions {..} =
Core.toJSON additional
/See:/ ' newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule ' smart constructor .
data GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule = GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
canReschedule :: (Core.Maybe Core.Bool),
endTime :: (Core.Maybe Core.DateTime),
rolloutManagementPolicy :: (Core.Maybe Core.Text),
| schedule / deadline / time is the time deadline any schedule start time can not go beyond , including reschedule . It\ 's normally the initial schedule start time plus maintenance window length ( 1 day or 1 week ) . Maintenance can not be scheduled to start beyond this deadline .
scheduleDeadlineTime :: (Core.Maybe Core.DateTime),
startTime :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule ::
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule =
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
{ canReschedule = Core.Nothing,
endTime = Core.Nothing,
rolloutManagementPolicy = Core.Nothing,
scheduleDeadlineTime = Core.Nothing,
startTime = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
Core.<$> (o Core..:? "canReschedule")
Core.<*> (o Core..:? "endTime")
Core.<*> (o Core..:? "rolloutManagementPolicy")
Core.<*> (o Core..:? "scheduleDeadlineTime")
Core.<*> (o Core..:? "startTime")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule {..} =
Core.object
( Core.catMaybes
[ ("canReschedule" Core..=) Core.<$> canReschedule,
("endTime" Core..=) Core.<$> endTime,
("rolloutManagementPolicy" Core..=)
Core.<$> rolloutManagementPolicy,
("scheduleDeadlineTime" Core..=)
Core.<$> scheduleDeadlineTime,
("startTime" Core..=) Core.<$> startTime
]
)
data GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings = GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
exclude :: (Core.Maybe Core.Bool),
isRollback :: (Core.Maybe Core.Bool),
| Optional . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the embedded policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug . If only the name is needed ( like in the deprecated Instance.maintenance/policy/names field ) then only populate MaintenancePolicy.name .
maintenancePolicies ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings ::
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings =
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
{ exclude = Core.Nothing,
isRollback = Core.Nothing,
maintenancePolicies = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
Core.<$> (o Core..:? "exclude")
Core.<*> (o Core..:? "isRollback")
Core.<*> (o Core..:? "maintenancePolicies")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings {..} =
Core.object
( Core.catMaybes
[ ("exclude" Core..=) Core.<$> exclude,
("isRollback" Core..=) Core.<$> isRollback,
("maintenancePolicies" Core..=)
Core.<$> maintenancePolicies
]
)
| Optional . The MaintenancePolicies that have been attached to the instance . The key must be of the type name of the oneof policy name defined in MaintenancePolicy , and the embedded policy must define the same policy type . For complete details of MaintenancePolicy , please refer to go\/cloud - saas - mw - ug . If only the name is needed ( like in the deprecated Instance.maintenance/policy/names field ) then only populate MaintenancePolicy.name .
newtype GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies = GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
additional :: (Core.HashMap Core.Text MaintenancePolicy)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies ' with the minimum fields required to make a request .
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies ::
Core.HashMap Core.Text MaintenancePolicy ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
newGoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies additional =
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings_MaintenancePolicies {..} =
Core.toJSON additional
| Node information for custom per - node SLO implementations . SSA does not support per - node SLO , but producers can populate per - node information in SloMetadata for custom precomputations . SSA Eligibility Exporter will emit per - node metric based on this information .
data GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata = GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
location :: (Core.Maybe Core.Text),
nodeId :: (Core.Maybe Core.Text),
perSliEligibility ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata ' with the minimum fields required to make a request .
newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata ::
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
newGoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata =
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
{ location = Core.Nothing,
nodeId = Core.Nothing,
perSliEligibility = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
Core.<$> (o Core..:? "location")
Core.<*> (o Core..:? "nodeId")
Core.<*> (o Core..:? "perSliEligibility")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata {..} =
Core.object
( Core.catMaybes
[ ("location" Core..=) Core.<$> location,
("nodeId" Core..=) Core.<$> nodeId,
("perSliEligibility" Core..=)
Core.<$> perSliEligibility
]
)
| PerSliSloEligibility is a mapping from an SLI name to eligibility .
newtype GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility = GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
| An entry in the eligibilities map specifies an eligibility for a particular SLI for the given instance . The SLI key in the name must be a valid SLI name specified in the Eligibility Exporter binary flags otherwise an error will be emitted by Eligibility Exporter and the oncaller will be alerted . If an SLI has been defined in the binary flags but the eligibilities map does not contain it , the corresponding SLI time series will not be emitted by the Eligibility Exporter . This ensures a smooth rollout and compatibility between the data produced by different versions of the Eligibility Exporters . If eligibilities map contains a key for an SLI which has not been declared in the binary flags , there will be an error message emitted in the Eligibility Exporter log and the metric for the SLI in question will not be emitted .
eligibilities ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility ::
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility =
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
{ eligibilities = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
Core.<$> (o Core..:? "eligibilities")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility {..} =
Core.object
( Core.catMaybes
[("eligibilities" Core..=) Core.<$> eligibilities]
)
| An entry in the eligibilities map specifies an eligibility for a particular SLI for the given instance . The SLI key in the name must be a valid SLI name specified in the Eligibility Exporter binary flags otherwise an error will be emitted by Eligibility Exporter and the oncaller will be alerted . If an SLI has been defined in the binary flags but the eligibilities map does not contain it , the corresponding SLI time series will not be emitted by the Eligibility Exporter . This ensures a smooth rollout and compatibility between the data produced by different versions of the Eligibility Exporters . If eligibilities map contains a key for an SLI which has not been declared in the binary flags , there will be an error message emitted in the Eligibility Exporter log and the metric for the SLI in question will not be emitted .
newtype GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities = GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
additional ::
( Core.HashMap
Core.Text
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities ::
Core.HashMap Core.Text GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility ->
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
newGoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities additional =
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
{ additional = additional
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
Core.<$> (Core.parseJSONObject o)
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility_Eligibilities {..} =
Core.toJSON additional
data GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource = GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
| Type of the resource . This can be either a GCP resource or a custom one ( e.g. another cloud provider\ 's VM ) . For GCP compute resources use singular form of the names listed in GCP compute API documentation ( https:\/\/cloud.google.com\/compute\/docs\/reference\/rest\/v1\/ ) , prefixed with \'compute-\ ' , for example : \'compute - instance\ ' , \'compute - disk\ ' , \'compute - autoscaler\ ' .
resourceType :: (Core.Maybe Core.Text),
| URL identifying the resource , e.g. ... )\ " .
resourceUrl :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource ::
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
newGoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource =
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
{ resourceType = Core.Nothing,
resourceUrl = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
Core.<$> (o Core..:? "resourceType")
Core.<*> (o Core..:? "resourceUrl")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource {..} =
Core.object
( Core.catMaybes
[ ("resourceType" Core..=) Core.<$> resourceType,
("resourceUrl" Core..=) Core.<$> resourceUrl
]
)
| SloEligibility is a tuple containing eligibility value : true if an instance is eligible for SLO calculation or false if it should be excluded from all SLO - related calculations along with a user - defined reason .
data GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility = GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
eligible :: (Core.Maybe Core.Bool),
reason :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility ::
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
newGoogleCloudSaasacceleratorManagementProvidersV1SloEligibility =
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
{ eligible = Core.Nothing,
reason = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
Core.<$> (o Core..:? "eligible")
Core.<*> (o Core..:? "reason")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility {..} =
Core.object
( Core.catMaybes
[ ("eligible" Core..=) Core.<$> eligible,
("reason" Core..=) Core.<$> reason
]
)
| SloMetadata contains resources required for proper SLO classification of the instance .
data GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata = GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
| Optional . List of nodes . Some producers need to use per - node metadata to calculate SLO . This field allows such producers to publish per - node SLO meta data , which will be consumed by SSA Eligibility Exporter and published in the form of per node metric to Monarch .
nodes ::
( Core.Maybe
[GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata]
),
| Optional . Multiple per - instance SLI eligibilities which apply for individual SLIs .
perSliEligibility ::
( Core.Maybe
GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility
),
| Name of the SLO tier the Instance belongs to . This name will be expected to match the tiers specified in the service SLO configuration . Field is mandatory and must not be empty .
tier :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata ::
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
newGoogleCloudSaasacceleratorManagementProvidersV1SloMetadata =
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
{ nodes = Core.Nothing,
perSliEligibility = Core.Nothing,
tier = Core.Nothing
}
instance
Core.FromJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
where
parseJSON =
Core.withObject
"GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata"
( \o ->
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
Core.<$> (o Core..:? "nodes")
Core.<*> (o Core..:? "perSliEligibility")
Core.<*> (o Core..:? "tier")
)
instance
Core.ToJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata
where
toJSON
GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata {..} =
Core.object
( Core.catMaybes
[ ("nodes" Core..=) Core.<$> nodes,
("perSliEligibility" Core..=)
Core.<$> perSliEligibility,
("tier" Core..=) Core.<$> tier
]
)
/See:/ ' newInstance ' smart constructor .
data Instance = Instance
createTime :: (Core.Maybe Core.DateTime),
| The description of the instance ( 2048 characters or less ) .
description :: (Core.Maybe Core.Text),
etag :: (Core.Maybe Core.Text),
fileShares :: (Core.Maybe [FileShareConfig]),
| KMS key name used for data encryption .
kmsKeyName :: (Core.Maybe Core.Text),
labels :: (Core.Maybe Instance_Labels),
name :: (Core.Maybe Core.Text),
networks :: (Core.Maybe [NetworkConfig]),
satisfiesPzs :: (Core.Maybe Core.Bool),
state :: (Core.Maybe Instance_State),
statusMessage :: (Core.Maybe Core.Text),
| Output only . field indicates all the reasons the instance is in \"SUSPENDED\ " state .
suspensionReasons :: (Core.Maybe [Instance_SuspensionReasonsItem]),
tier :: (Core.Maybe Instance_Tier)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newInstance ::
Instance
newInstance =
Instance
{ createTime = Core.Nothing,
description = Core.Nothing,
etag = Core.Nothing,
fileShares = Core.Nothing,
kmsKeyName = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
networks = Core.Nothing,
satisfiesPzs = Core.Nothing,
state = Core.Nothing,
statusMessage = Core.Nothing,
suspensionReasons = Core.Nothing,
tier = Core.Nothing
}
instance Core.FromJSON Instance where
parseJSON =
Core.withObject
"Instance"
( \o ->
Instance
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "etag")
Core.<*> (o Core..:? "fileShares")
Core.<*> (o Core..:? "kmsKeyName")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "networks")
Core.<*> (o Core..:? "satisfiesPzs")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "statusMessage")
Core.<*> (o Core..:? "suspensionReasons")
Core.<*> (o Core..:? "tier")
)
instance Core.ToJSON Instance where
toJSON Instance {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("etag" Core..=) Core.<$> etag,
("fileShares" Core..=) Core.<$> fileShares,
("kmsKeyName" Core..=) Core.<$> kmsKeyName,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("networks" Core..=) Core.<$> networks,
("satisfiesPzs" Core..=) Core.<$> satisfiesPzs,
("state" Core..=) Core.<$> state,
("statusMessage" Core..=) Core.<$> statusMessage,
("suspensionReasons" Core..=)
Core.<$> suspensionReasons,
("tier" Core..=) Core.<$> tier
]
)
newtype Instance_Labels = Instance_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Instance_Labels ' with the minimum fields required to make a request .
newInstance_Labels ::
Core.HashMap Core.Text Core.Text ->
Instance_Labels
newInstance_Labels additional = Instance_Labels {additional = additional}
instance Core.FromJSON Instance_Labels where
parseJSON =
Core.withObject
"Instance_Labels"
( \o ->
Instance_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Instance_Labels where
toJSON Instance_Labels {..} = Core.toJSON additional
| ListBackupsResponse is the result of ListBackupsRequest .
data ListBackupsResponse = ListBackupsResponse
| A list of backups in the project for the specified location . If the @{location}@ value in the request is \"-\ " , the response contains a list of backups from all locations . If any location is unreachable , the response will only return backups in reachable locations and the \"unreachable\ " field will be populated with a list of unreachable locations .
backups :: (Core.Maybe [Backup]),
nextPageToken :: (Core.Maybe Core.Text),
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newListBackupsResponse ::
ListBackupsResponse
newListBackupsResponse =
ListBackupsResponse
{ backups = Core.Nothing,
nextPageToken = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListBackupsResponse where
parseJSON =
Core.withObject
"ListBackupsResponse"
( \o ->
ListBackupsResponse
Core.<$> (o Core..:? "backups")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListBackupsResponse where
toJSON ListBackupsResponse {..} =
Core.object
( Core.catMaybes
[ ("backups" Core..=) Core.<$> backups,
("nextPageToken" Core..=) Core.<$> nextPageToken,
("unreachable" Core..=) Core.<$> unreachable
]
)
| ListInstancesResponse is the result of ListInstancesRequest .
data ListInstancesResponse = ListInstancesResponse
| A list of instances in the project for the specified location . If the @{location}@ value in the request is \"-\ " , the response contains a list of instances from all locations . If any location is unreachable , the response will only return instances in reachable locations and the \"unreachable\ " field will be populated with a list of unreachable locations .
instances :: (Core.Maybe [Instance]),
nextPageToken :: (Core.Maybe Core.Text),
unreachable :: (Core.Maybe [Core.Text])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newListInstancesResponse ::
ListInstancesResponse
newListInstancesResponse =
ListInstancesResponse
{ instances = Core.Nothing,
nextPageToken = Core.Nothing,
unreachable = Core.Nothing
}
instance Core.FromJSON ListInstancesResponse where
parseJSON =
Core.withObject
"ListInstancesResponse"
( \o ->
ListInstancesResponse
Core.<$> (o Core..:? "instances")
Core.<*> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "unreachable")
)
instance Core.ToJSON ListInstancesResponse where
toJSON ListInstancesResponse {..} =
Core.object
( Core.catMaybes
[ ("instances" Core..=) Core.<$> instances,
("nextPageToken" Core..=) Core.<$> nextPageToken,
("unreachable" Core..=) Core.<$> unreachable
]
)
data ListLocationsResponse = ListLocationsResponse
locations :: (Core.Maybe [Location]),
nextPageToken :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListLocationsResponse ' with the minimum fields required to make a request .
newListLocationsResponse ::
ListLocationsResponse
newListLocationsResponse =
ListLocationsResponse {locations = Core.Nothing, nextPageToken = Core.Nothing}
instance Core.FromJSON ListLocationsResponse where
parseJSON =
Core.withObject
"ListLocationsResponse"
( \o ->
ListLocationsResponse
Core.<$> (o Core..:? "locations")
Core.<*> (o Core..:? "nextPageToken")
)
instance Core.ToJSON ListLocationsResponse where
toJSON ListLocationsResponse {..} =
Core.object
( Core.catMaybes
[ ("locations" Core..=) Core.<$> locations,
("nextPageToken" Core..=) Core.<$> nextPageToken
]
)
| The response message for Operations . ListOperations .
data ListOperationsResponse = ListOperationsResponse
nextPageToken :: (Core.Maybe Core.Text),
operations :: (Core.Maybe [Operation])
}
deriving (Core.Eq, Core.Show, Core.Generic)
newListOperationsResponse ::
ListOperationsResponse
newListOperationsResponse =
ListOperationsResponse
{ nextPageToken = Core.Nothing,
operations = Core.Nothing
}
instance Core.FromJSON ListOperationsResponse where
parseJSON =
Core.withObject
"ListOperationsResponse"
( \o ->
ListOperationsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "operations")
)
instance Core.ToJSON ListOperationsResponse where
toJSON ListOperationsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("operations" Core..=) Core.<$> operations
]
)
| is the result of ListSnapshotsRequest .
data ListSnapshotsResponse = ListSnapshotsResponse
nextPageToken :: (Core.Maybe Core.Text),
snapshots :: (Core.Maybe [Snapshot])
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ListSnapshotsResponse ' with the minimum fields required to make a request .
newListSnapshotsResponse ::
ListSnapshotsResponse
newListSnapshotsResponse =
ListSnapshotsResponse {nextPageToken = Core.Nothing, snapshots = Core.Nothing}
instance Core.FromJSON ListSnapshotsResponse where
parseJSON =
Core.withObject
"ListSnapshotsResponse"
( \o ->
ListSnapshotsResponse
Core.<$> (o Core..:? "nextPageToken")
Core.<*> (o Core..:? "snapshots")
)
instance Core.ToJSON ListSnapshotsResponse where
toJSON ListSnapshotsResponse {..} =
Core.object
( Core.catMaybes
[ ("nextPageToken" Core..=) Core.<$> nextPageToken,
("snapshots" Core..=) Core.<$> snapshots
]
)
| A resource that represents Google Cloud Platform location .
/See:/ ' newLocation ' smart constructor .
data Location = Location
displayName :: (Core.Maybe Core.Text),
labels :: (Core.Maybe Location_Labels),
| The canonical i d for this location . For example : @\"us - east1\"@.
locationId :: (Core.Maybe Core.Text),
metadata :: (Core.Maybe Location_Metadata),
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLocation ::
Location
newLocation =
Location
{ displayName = Core.Nothing,
labels = Core.Nothing,
locationId = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON Location where
parseJSON =
Core.withObject
"Location"
( \o ->
Location
Core.<$> (o Core..:? "displayName")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "locationId")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON Location where
toJSON Location {..} =
Core.object
( Core.catMaybes
[ ("displayName" Core..=) Core.<$> displayName,
("labels" Core..=) Core.<$> labels,
("locationId" Core..=) Core.<$> locationId,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name
]
)
newtype Location_Labels = Location_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLocation_Labels ::
Core.HashMap Core.Text Core.Text ->
Location_Labels
newLocation_Labels additional = Location_Labels {additional = additional}
instance Core.FromJSON Location_Labels where
parseJSON =
Core.withObject
"Location_Labels"
( \o ->
Location_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Labels where
toJSON Location_Labels {..} = Core.toJSON additional
newtype Location_Metadata = Location_Metadata
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLocation_Metadata ::
Core.HashMap Core.Text Core.Value ->
Location_Metadata
newLocation_Metadata additional = Location_Metadata {additional = additional}
instance Core.FromJSON Location_Metadata where
parseJSON =
Core.withObject
"Location_Metadata"
( \o ->
Location_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Location_Metadata where
toJSON Location_Metadata {..} = Core.toJSON additional
data MaintenancePolicy = MaintenancePolicy
createTime :: (Core.Maybe Core.DateTime),
| Optional . Description of what this policy is for . Create\/Update methods return if the length is greater than 512 .
description :: (Core.Maybe Core.Text),
labels :: (Core.Maybe MaintenancePolicy_Labels),
| Required . MaintenancePolicy name using the form : @projects\/{project_id}\/locations\/{location_id}\/maintenancePolicies\/{maintenance_policy_id}@ where { project / id } refers to a GCP consumer project ID , { location / id } refers to a GCP region\/zone , { maintenance / policy / id } must be 1 - 63 characters long and match the regular expression @[a - z0 - 9]([-a - z0 - 9]*[a - z0 - 9])?@.
name :: (Core.Maybe Core.Text),
state :: (Core.Maybe MaintenancePolicy_State),
updatePolicy :: (Core.Maybe UpdatePolicy),
updateTime :: (Core.Maybe Core.DateTime)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' MaintenancePolicy ' with the minimum fields required to make a request .
newMaintenancePolicy ::
MaintenancePolicy
newMaintenancePolicy =
MaintenancePolicy
{ createTime = Core.Nothing,
description = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
state = Core.Nothing,
updatePolicy = Core.Nothing,
updateTime = Core.Nothing
}
instance Core.FromJSON MaintenancePolicy where
parseJSON =
Core.withObject
"MaintenancePolicy"
( \o ->
MaintenancePolicy
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "state")
Core.<*> (o Core..:? "updatePolicy")
Core.<*> (o Core..:? "updateTime")
)
instance Core.ToJSON MaintenancePolicy where
toJSON MaintenancePolicy {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("state" Core..=) Core.<$> state,
("updatePolicy" Core..=) Core.<$> updatePolicy,
("updateTime" Core..=) Core.<$> updateTime
]
)
newtype MaintenancePolicy_Labels = MaintenancePolicy_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' MaintenancePolicy_Labels ' with the minimum fields required to make a request .
newMaintenancePolicy_Labels ::
Core.HashMap Core.Text Core.Text ->
MaintenancePolicy_Labels
newMaintenancePolicy_Labels additional =
MaintenancePolicy_Labels {additional = additional}
instance Core.FromJSON MaintenancePolicy_Labels where
parseJSON =
Core.withObject
"MaintenancePolicy_Labels"
( \o ->
MaintenancePolicy_Labels
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON MaintenancePolicy_Labels where
toJSON MaintenancePolicy_Labels {..} =
Core.toJSON additional
data MaintenanceWindow = MaintenanceWindow
dailyCycle :: (Core.Maybe DailyCycle),
weeklyCycle :: (Core.Maybe WeeklyCycle)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newMaintenanceWindow ::
MaintenanceWindow
newMaintenanceWindow =
MaintenanceWindow {dailyCycle = Core.Nothing, weeklyCycle = Core.Nothing}
instance Core.FromJSON MaintenanceWindow where
parseJSON =
Core.withObject
"MaintenanceWindow"
( \o ->
MaintenanceWindow
Core.<$> (o Core..:? "dailyCycle")
Core.<*> (o Core..:? "weeklyCycle")
)
instance Core.ToJSON MaintenanceWindow where
toJSON MaintenanceWindow {..} =
Core.object
( Core.catMaybes
[ ("dailyCycle" Core..=) Core.<$> dailyCycle,
("weeklyCycle" Core..=) Core.<$> weeklyCycle
]
)
data NetworkConfig = NetworkConfig
| The network connect mode of the instance . If not provided , the connect mode defaults to DIRECT_PEERING .
connectMode :: (Core.Maybe NetworkConfig_ConnectMode),
| Output only . IPv4 addresses in the format @{octet1}.{octet2}.{octet3}.{octet4}@ or IPv6 addresses in the format @{block1}:{block2}:{block3}:{block4}:{block5}:{block6}:{block7}:{block8}@.
ipAddresses :: (Core.Maybe [Core.Text]),
modes :: (Core.Maybe [NetworkConfig_ModesItem]),
| The name of the Google Compute Engine < VPC network > to which the instance is connected .
network :: (Core.Maybe Core.Text),
| Optional , reserved / ip / range can have one of the following two types of values . * CIDR range value when using DIRECT / PEERING connect mode . * < -addresses/reserve-static-internal-ip-address Allocated IP address range > when using PRIVATE / SERVICE_ACCESS connect mode . When the name of an allocated IP address range is specified , it must be one of the ranges associated with the private service access connection . When specified as a direct CIDR value , it must be a \/29 CIDR block for Basic tier or a \/24 CIDR block for High Scale or Enterprise tier in one of the < / internal IP address ranges > that identifies the range of IP addresses reserved for this instance . For example , 10.0.0.0\/29 or 192.168.0.0\/24 . The range you specify can\'t overlap with either existing subnets or assigned IP address ranges for other Cloud Filestore instances in the selected VPC network .
reservedIpRange :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NetworkConfig ' with the minimum fields required to make a request .
newNetworkConfig ::
NetworkConfig
newNetworkConfig =
NetworkConfig
{ connectMode = Core.Nothing,
ipAddresses = Core.Nothing,
modes = Core.Nothing,
network = Core.Nothing,
reservedIpRange = Core.Nothing
}
instance Core.FromJSON NetworkConfig where
parseJSON =
Core.withObject
"NetworkConfig"
( \o ->
NetworkConfig
Core.<$> (o Core..:? "connectMode")
Core.<*> (o Core..:? "ipAddresses")
Core.<*> (o Core..:? "modes")
Core.<*> (o Core..:? "network")
Core.<*> (o Core..:? "reservedIpRange")
)
instance Core.ToJSON NetworkConfig where
toJSON NetworkConfig {..} =
Core.object
( Core.catMaybes
[ ("connectMode" Core..=) Core.<$> connectMode,
("ipAddresses" Core..=) Core.<$> ipAddresses,
("modes" Core..=) Core.<$> modes,
("network" Core..=) Core.<$> network,
("reservedIpRange" Core..=)
Core.<$> reservedIpRange
]
)
data NfsExportOptions = NfsExportOptions
accessMode :: (Core.Maybe NfsExportOptions_AccessMode),
| An integer representing the anonymous group i d with a default value of 65534 . Anon / gid may only be set with squash / mode of ROOT / SQUASH . An error will be returned if this field is specified for other squash / mode settings .
anonGid :: (Core.Maybe Core.Int64),
| An integer representing the anonymous user i d with a default value of 65534 . Anon / uid may only be set with squash / mode of ROOT / SQUASH . An error will be returned if this field is specified for other squash / mode settings .
anonUid :: (Core.Maybe Core.Int64),
| List of either an IPv4 addresses in the format @{octet1}.{octet2}.{octet3}.{octet4}@ or CIDR ranges in the format @{octet1}.{octet2}.{octet3}.{octet4}\/{mask size}@ which may mount the file share . Overlapping IP ranges are not allowed , both within and across NfsExportOptions . An error will be returned . The limit is 64 IP ranges\/addresses for each FileShareConfig among all NfsExportOptions .
ipRanges :: (Core.Maybe [Core.Text]),
| Either NO / ROOT / SQUASH , for allowing root access on the exported directory , or ROOT / SQUASH , for not allowing root access . The default is NO / ROOT_SQUASH .
squashMode :: (Core.Maybe NfsExportOptions_SquashMode)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' NfsExportOptions ' with the minimum fields required to make a request .
newNfsExportOptions ::
NfsExportOptions
newNfsExportOptions =
NfsExportOptions
{ accessMode = Core.Nothing,
anonGid = Core.Nothing,
anonUid = Core.Nothing,
ipRanges = Core.Nothing,
squashMode = Core.Nothing
}
instance Core.FromJSON NfsExportOptions where
parseJSON =
Core.withObject
"NfsExportOptions"
( \o ->
NfsExportOptions
Core.<$> (o Core..:? "accessMode")
Core.<*> ( o Core..:? "anonGid"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> ( o Core..:? "anonUid"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "ipRanges")
Core.<*> (o Core..:? "squashMode")
)
instance Core.ToJSON NfsExportOptions where
toJSON NfsExportOptions {..} =
Core.object
( Core.catMaybes
[ ("accessMode" Core..=) Core.<$> accessMode,
("anonGid" Core..=) Core.. Core.AsText
Core.<$> anonGid,
("anonUid" Core..=) Core.. Core.AsText
Core.<$> anonUid,
("ipRanges" Core..=) Core.<$> ipRanges,
("squashMode" Core..=) Core.<$> squashMode
]
)
data Operation = Operation
| If the value is @false@ , it means the operation is still in progress . If @true@ , the operation is completed , and either @error@ or @response@ is available .
done :: (Core.Maybe Core.Bool),
error :: (Core.Maybe Status),
metadata :: (Core.Maybe Operation_Metadata),
| The server - assigned name , which is only unique within the same service that originally returns it . If you use the default HTTP mapping , the @name@ should be a resource name ending with
name :: (Core.Maybe Core.Text),
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
response :: (Core.Maybe Operation_Response)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newOperation ::
Operation
newOperation =
Operation
{ done = Core.Nothing,
error = Core.Nothing,
metadata = Core.Nothing,
name = Core.Nothing,
response = Core.Nothing
}
instance Core.FromJSON Operation where
parseJSON =
Core.withObject
"Operation"
( \o ->
Operation
Core.<$> (o Core..:? "done")
Core.<*> (o Core..:? "error")
Core.<*> (o Core..:? "metadata")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "response")
)
instance Core.ToJSON Operation where
toJSON Operation {..} =
Core.object
( Core.catMaybes
[ ("done" Core..=) Core.<$> done,
("error" Core..=) Core.<$> error,
("metadata" Core..=) Core.<$> metadata,
("name" Core..=) Core.<$> name,
("response" Core..=) Core.<$> response
]
)
newtype Operation_Metadata = Operation_Metadata
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newOperation_Metadata ::
Core.HashMap Core.Text Core.Value ->
Operation_Metadata
newOperation_Metadata additional = Operation_Metadata {additional = additional}
instance Core.FromJSON Operation_Metadata where
parseJSON =
Core.withObject
"Operation_Metadata"
( \o ->
Operation_Metadata Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Metadata where
toJSON Operation_Metadata {..} =
Core.toJSON additional
| The normal response of the operation in case of success . If the original method returns no data on success , such as @Delete@ , the response is @google.protobuf . Empty@. If the original method is standard @Get@\/@Create@\/@Update@ , the response should be the resource . For other methods , the response should have the type @XxxResponse@ , where @Xxx@ is the original method name . For example , if the original method name is , the inferred response type is @TakeSnapshotResponse@.
newtype Operation_Response = Operation_Response
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newOperation_Response ::
Core.HashMap Core.Text Core.Value ->
Operation_Response
newOperation_Response additional = Operation_Response {additional = additional}
instance Core.FromJSON Operation_Response where
parseJSON =
Core.withObject
"Operation_Response"
( \o ->
Operation_Response Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Operation_Response where
toJSON Operation_Response {..} =
Core.toJSON additional
/See:/ ' newOperationMetadata ' smart constructor .
data OperationMetadata = OperationMetadata
apiVersion :: (Core.Maybe Core.Text),
| Output only . Identifies whether the user has requested cancellation of the operation . Operations that have been cancelled successfully have Operation.error value with a google.rpc.Status.code of 1 , corresponding to @Code . CANCELLED@.
cancelRequested :: (Core.Maybe Core.Bool),
createTime :: (Core.Maybe Core.DateTime),
endTime :: (Core.Maybe Core.DateTime),
statusDetail :: (Core.Maybe Core.Text),
target :: (Core.Maybe Core.Text),
verb :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' OperationMetadata ' with the minimum fields required to make a request .
newOperationMetadata ::
OperationMetadata
newOperationMetadata =
OperationMetadata
{ apiVersion = Core.Nothing,
cancelRequested = Core.Nothing,
createTime = Core.Nothing,
endTime = Core.Nothing,
statusDetail = Core.Nothing,
target = Core.Nothing,
verb = Core.Nothing
}
instance Core.FromJSON OperationMetadata where
parseJSON =
Core.withObject
"OperationMetadata"
( \o ->
OperationMetadata
Core.<$> (o Core..:? "apiVersion")
Core.<*> (o Core..:? "cancelRequested")
Core.<*> (o Core..:? "createTime")
Core.<*> (o Core..:? "endTime")
Core.<*> (o Core..:? "statusDetail")
Core.<*> (o Core..:? "target")
Core.<*> (o Core..:? "verb")
)
instance Core.ToJSON OperationMetadata where
toJSON OperationMetadata {..} =
Core.object
( Core.catMaybes
[ ("apiVersion" Core..=) Core.<$> apiVersion,
("cancelRequested" Core..=) Core.<$> cancelRequested,
("createTime" Core..=) Core.<$> createTime,
("endTime" Core..=) Core.<$> endTime,
("statusDetail" Core..=) Core.<$> statusDetail,
("target" Core..=) Core.<$> target,
("verb" Core..=) Core.<$> verb
]
)
| RestoreInstanceRequest restores an existing instance\ 's file share from a backup .
data RestoreInstanceRequest = RestoreInstanceRequest
fileShare :: (Core.Maybe Core.Text),
sourceBackup :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' RestoreInstanceRequest ' with the minimum fields required to make a request .
newRestoreInstanceRequest ::
RestoreInstanceRequest
newRestoreInstanceRequest =
RestoreInstanceRequest {fileShare = Core.Nothing, sourceBackup = Core.Nothing}
instance Core.FromJSON RestoreInstanceRequest where
parseJSON =
Core.withObject
"RestoreInstanceRequest"
( \o ->
RestoreInstanceRequest
Core.<$> (o Core..:? "fileShare")
Core.<*> (o Core..:? "sourceBackup")
)
instance Core.ToJSON RestoreInstanceRequest where
toJSON RestoreInstanceRequest {..} =
Core.object
( Core.catMaybes
[ ("fileShare" Core..=) Core.<$> fileShare,
("sourceBackup" Core..=) Core.<$> sourceBackup
]
)
/See:/ ' ' smart constructor .
data Schedule = Schedule
| Allows to define schedule that runs specified day of the week .
day :: (Core.Maybe Schedule_Day),
duration :: (Core.Maybe Core.Duration),
startTime :: (Core.Maybe TimeOfDay')
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSchedule ::
Schedule
newSchedule =
Schedule
{ day = Core.Nothing,
duration = Core.Nothing,
startTime = Core.Nothing
}
instance Core.FromJSON Schedule where
parseJSON =
Core.withObject
"Schedule"
( \o ->
Schedule
Core.<$> (o Core..:? "day")
Core.<*> (o Core..:? "duration")
Core.<*> (o Core..:? "startTime")
)
instance Core.ToJSON Schedule where
toJSON Schedule {..} =
Core.object
( Core.catMaybes
[ ("day" Core..=) Core.<$> day,
("duration" Core..=) Core.<$> duration,
("startTime" Core..=) Core.<$> startTime
]
)
| A snapshot .
data Snapshot = Snapshot
createTime :: (Core.Maybe Core.DateTime),
| A description of the snapshot with 2048 characters or less . Requests with longer descriptions will be rejected .
description :: (Core.Maybe Core.Text),
filesystemUsedBytes :: (Core.Maybe Core.Int64),
labels :: (Core.Maybe Snapshot_Labels),
name :: (Core.Maybe Core.Text),
state :: (Core.Maybe Snapshot_State)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' Snapshot ' with the minimum fields required to make a request .
newSnapshot ::
Snapshot
newSnapshot =
Snapshot
{ createTime = Core.Nothing,
description = Core.Nothing,
filesystemUsedBytes = Core.Nothing,
labels = Core.Nothing,
name = Core.Nothing,
state = Core.Nothing
}
instance Core.FromJSON Snapshot where
parseJSON =
Core.withObject
"Snapshot"
( \o ->
Snapshot
Core.<$> (o Core..:? "createTime")
Core.<*> (o Core..:? "description")
Core.<*> ( o Core..:? "filesystemUsedBytes"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "labels")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "state")
)
instance Core.ToJSON Snapshot where
toJSON Snapshot {..} =
Core.object
( Core.catMaybes
[ ("createTime" Core..=) Core.<$> createTime,
("description" Core..=) Core.<$> description,
("filesystemUsedBytes" Core..=) Core.. Core.AsText
Core.<$> filesystemUsedBytes,
("labels" Core..=) Core.<$> labels,
("name" Core..=) Core.<$> name,
("state" Core..=) Core.<$> state
]
)
newtype Snapshot_Labels = Snapshot_Labels
additional :: (Core.HashMap Core.Text Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSnapshot_Labels ::
Core.HashMap Core.Text Core.Text ->
Snapshot_Labels
newSnapshot_Labels additional = Snapshot_Labels {additional = additional}
instance Core.FromJSON Snapshot_Labels where
parseJSON =
Core.withObject
"Snapshot_Labels"
( \o ->
Snapshot_Labels Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Snapshot_Labels where
toJSON Snapshot_Labels {..} = Core.toJSON additional
| The @Status@ type defines a logical error model that is suitable for different programming environments , including REST APIs and RPC APIs . It is used by < > . Each @Status@ message contains three pieces of data : error code , error message , and error details . You can find out more about this error model and how to work with it in the < API Design Guide > .
/See:/ ' newStatus ' smart constructor .
data Status = Status
code :: (Core.Maybe Core.Int32),
details :: (Core.Maybe [Status_DetailsItem]),
| A developer - facing error message , which should be in English . Any user - facing error message should be localized and sent in the google.rpc.Status.details field , or localized by the client .
message :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newStatus ::
Status
newStatus =
Status {code = Core.Nothing, details = Core.Nothing, message = Core.Nothing}
instance Core.FromJSON Status where
parseJSON =
Core.withObject
"Status"
( \o ->
Status
Core.<$> (o Core..:? "code")
Core.<*> (o Core..:? "details")
Core.<*> (o Core..:? "message")
)
instance Core.ToJSON Status where
toJSON Status {..} =
Core.object
( Core.catMaybes
[ ("code" Core..=) Core.<$> code,
("details" Core..=) Core.<$> details,
("message" Core..=) Core.<$> message
]
)
newtype Status_DetailsItem = Status_DetailsItem
additional :: (Core.HashMap Core.Text Core.Value)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newStatus_DetailsItem ::
Core.HashMap Core.Text Core.Value ->
Status_DetailsItem
newStatus_DetailsItem additional = Status_DetailsItem {additional = additional}
instance Core.FromJSON Status_DetailsItem where
parseJSON =
Core.withObject
"Status_DetailsItem"
( \o ->
Status_DetailsItem Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON Status_DetailsItem where
toJSON Status_DetailsItem {..} =
Core.toJSON additional
| Represents a time of day . The date and time zone are either not significant or are specified elsewhere . An API may choose to allow leap seconds . Related types are google.type . Date and @google.protobuf . Timestamp@.
data TimeOfDay' = TimeOfDay'
| Hours of day in 24 hour format . Should be from 0 to 23 . An API may choose to allow the value \"24:00:00\ " for scenarios like business closing time .
hours :: (Core.Maybe Core.Int32),
| Minutes of hour of day . Must be from 0 to 59 .
minutes :: (Core.Maybe Core.Int32),
| Fractions of seconds in nanoseconds . Must be from 0 to 999,999,999 .
nanos :: (Core.Maybe Core.Int32),
| Seconds of minutes of the time . Must normally be from 0 to 59 . An API may allow the value 60 if it allows leap - seconds .
seconds :: (Core.Maybe Core.Int32)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ' with the minimum fields required to make a request .
newTimeOfDay ::
TimeOfDay'
newTimeOfDay =
TimeOfDay'
{ hours = Core.Nothing,
minutes = Core.Nothing,
nanos = Core.Nothing,
seconds = Core.Nothing
}
instance Core.FromJSON TimeOfDay' where
parseJSON =
Core.withObject
"TimeOfDay'"
( \o ->
TimeOfDay'
Core.<$> (o Core..:? "hours")
Core.<*> (o Core..:? "minutes")
Core.<*> (o Core..:? "nanos")
Core.<*> (o Core..:? "seconds")
)
instance Core.ToJSON TimeOfDay' where
toJSON TimeOfDay' {..} =
Core.object
( Core.catMaybes
[ ("hours" Core..=) Core.<$> hours,
("minutes" Core..=) Core.<$> minutes,
("nanos" Core..=) Core.<$> nanos,
("seconds" Core..=) Core.<$> seconds
]
)
data UpdatePolicy = UpdatePolicy
channel :: (Core.Maybe UpdatePolicy_Channel),
| Deny Maintenance Period that is applied to resource to indicate when maintenance is forbidden . User can specify zero or more non - overlapping deny periods . Maximum number of deny / maintenance / periods expected is one .
denyMaintenancePeriods :: (Core.Maybe [DenyMaintenancePeriod]),
window :: (Core.Maybe MaintenanceWindow)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' UpdatePolicy ' with the minimum fields required to make a request .
newUpdatePolicy ::
UpdatePolicy
newUpdatePolicy =
UpdatePolicy
{ channel = Core.Nothing,
denyMaintenancePeriods = Core.Nothing,
window = Core.Nothing
}
instance Core.FromJSON UpdatePolicy where
parseJSON =
Core.withObject
"UpdatePolicy"
( \o ->
UpdatePolicy
Core.<$> (o Core..:? "channel")
Core.<*> (o Core..:? "denyMaintenancePeriods")
Core.<*> (o Core..:? "window")
)
instance Core.ToJSON UpdatePolicy where
toJSON UpdatePolicy {..} =
Core.object
( Core.catMaybes
[ ("channel" Core..=) Core.<$> channel,
("denyMaintenancePeriods" Core..=)
Core.<$> denyMaintenancePeriods,
("window" Core..=) Core.<$> window
]
)
| Time window specified for weekly operations .
newtype WeeklyCycle = WeeklyCycle
| User can specify multiple windows in a week . Minimum of 1 window .
schedule :: (Core.Maybe [Schedule])
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' WeeklyCycle ' with the minimum fields required to make a request .
newWeeklyCycle ::
WeeklyCycle
newWeeklyCycle = WeeklyCycle {schedule = Core.Nothing}
instance Core.FromJSON WeeklyCycle where
parseJSON =
Core.withObject
"WeeklyCycle"
(\o -> WeeklyCycle Core.<$> (o Core..:? "schedule"))
instance Core.ToJSON WeeklyCycle where
toJSON WeeklyCycle {..} =
Core.object
( Core.catMaybes
[("schedule" Core..=) Core.<$> schedule]
)
|
7836e83611b5d74d9bdf27e170fb33ba2efabd4e76c2f4add0204faeadc1f5f7 | jumarko/clojure-experiments | logging.clj | (ns clojure-experiments.logging
(:require [clojure.spec.alpha :as s]
[clojure.tools.logging :as log]
[clojure.tools.logging.impl :as log-impl]
[taoensso.timbre :as log-timbre])
(:import (org.apache.logging.log4j Level LogManager)
(org.apache.logging.log4j.core.config Configurator)))
;;;; clojure.tools.logging and dynamic log level setting
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn log-levels []
(->> (Level/values)
seq
(map (fn [log-level]
[(-> log-level str clojure.string/lower-case keyword)
log-level]))
(into {}))
#_{:fatal Level/FATAL
:error Level/ERROR
:warn Level/WARN
:info Level/INFO
:debug Level/DEBUG
:trace Level/TRACE
:off Level/OFF
:all Level/ALL}
)
(defn to-log4j-level [level-keyword]
(get (log-levels) level-keyword))
;; copied from `clojure.tools.logging.impl/find-factory` and making `log4j2-factory
highest priority ( rather than cl - factory and slf4j - factory - commons - logging e.g. is included in apache http client )
(defn find-factory
"Returns the first non-nil value from slf4j-factory, cl-factory,
log4j2-factory, log4j-factory, and jul-factory."
[]
(or (log-impl/log4j2-factory)
(log-impl/slf4j-factory)
(log-impl/cl-factory)
(log-impl/log4j-factory)
(log-impl/jul-factory)
this should never happen in 1.5 +
(RuntimeException.
"Valid logging implementation could not be found."))))
(s/def ::log-level (set (keys (log-levels))))
(s/fdef set-level!
:args (s/cat :level ::log-level)
:ret nil?)
(defn set-level!
"Sets new log level for the Root logger. "
[level]
(if-let [log-level (to-log4j-level level)]
;; How do I set a logger's level programmaticaly? -2.4/faq.html#reconfig_level_from_code
(do
(Configurator/setRootLevel log-level)
;; finally, we need to update logger-factory used internally by clojure.tools.logging
;; otherwise it would cache the log level set when it was initialized
(alter-var-root #'log/*logger-factory* (constantly (find-factory))))
(throw (IllegalArgumentException. (str "Invalid log level: " level)))))
(comment
(Configurator/setRootLevel (to-log4j-level :debug))
;; alternatively you can try `setAllLevels`
;; (Configurator/setAllLevels LogManager/ROOT_LOGGER_NAME (to-log4j-level :info))
(do
(set-level! :info)
(log/info "PRINTED.")
(log/debug "NOT PRINTED")
(set-level! :debug)
(log/debug "PRINTED?")
(set-level! :info)
(log/debug "NOT PRINTED")
(set-level! :warn)
(log/info "INFO NOT PRINTED"))
;; check
(log-impl/get-logger log/*logger-factory* *ns*)
(log-impl/get-logger (find-factory) *ns*)
;;
)
Timbre
;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Masking secrets in logs
;;;
(def secrets-log-patterns
"All patterns matching potentially sensitive data in logs that should be replaced by `secret-replacement-str`.
These patterns should always follow the format '(Whatever is the matching prefix) MYSCRET'.
- note that the parens are required!
This will match the log message 'Whatever is the matching prefix MYSCRET'
and that message will be replaced with 'Whatever is the matching prefix ***'"
OAuth access tokens sent in the Authorization header
OAuth access / refresh tokens as used internally in Clojure maps or returned by OAuth provider " access_token " API
OAuth app client secret sent in the request form body param
OAuth app client secret as stored in a Clojure map
])
(def secret-replacement "***")
(defn- mask-secrets [secrets-patterns replacement log-message]
((reduce
(fn mask-pattern [msg pattern]
the original prefix ( $ 1 ) plus the secret replaced with ' * * * '
(clojure.string/replace msg pattern (str "$1" secret-replacement)))
log-message
secrets-patterns)))
(def mask-secrets-in-log (partial mask-secrets secrets-log-patterns secret-replacement))
(comment
(def my-msg
"2019-06-12 08:41:34.115 Jurajs-MacBook-Pro-2.local DEBUG [org.apache.http.wire:73] - http-outgoing-30 >> \"Authorization: Bearer 882a64a1234567890abcdefghij1234567890dcb[\r][\n]\"")
(mask-secrets-in-log my-msg)
;; criterium reports ~5 microseconds per `mask-secrets` call
(crit/quick-bench (mask-secrets-in-log my-msg))
)
(defn mask-secrets-log-config
"Mask sensitive data in the logs - e.g. OAuth client secrets and access tokens.
See for an old example of masking middleware.
However that is complex and not easy to do (one would have to 'mask' everything in the `:vargs` vector)
so the easier option using the `:output-fn` was chosen."
[]
(log-timbre/merge-config!
{:output-fn (comp
mask-secrets-in-log
log-timbre/default-output-fn)}))
(comment
;; Compare
(log-timbre/info "Bearer XYZ")
(mask-secrets-log-config)
(log-timbre/info "Bearer XYZ")
)
Timbre does n't work with internal exception classes like ` SunCertPathBuilderException `
;;;
;;; NOTE: clojure.tools.logging works just fine
(comment
;; This throws
1 . Unhandled java.lang . IllegalAccessException
class clojure.core$bean$fn__7278$fn__7279 can not access class
;; sun.security.validator.ValidatorException (in module java.base) because module java.base does not
;; export sun.security.validator to unnamed module @ac279a9
(try
(slurp "-root.badssl.com/")
(catch Exception e
(taoensso.timbre/error e "ssl error")))
;; clojure.tools.logging works
(try
(slurp "-root.badssl.com/")
(catch Exception e
(log/error e "ssl error")))
)
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/0ba4f8da824da2da59e88cf0157239ead88744df/src/clojure_experiments/logging.clj | clojure | clojure.tools.logging and dynamic log level setting
copied from `clojure.tools.logging.impl/find-factory` and making `log4j2-factory
How do I set a logger's level programmaticaly? -2.4/faq.html#reconfig_level_from_code
finally, we need to update logger-factory used internally by clojure.tools.logging
otherwise it would cache the log level set when it was initialized
alternatively you can try `setAllLevels`
(Configurator/setAllLevels LogManager/ROOT_LOGGER_NAME (to-log4j-level :info))
check
Masking secrets in logs
criterium reports ~5 microseconds per `mask-secrets` call
Compare
NOTE: clojure.tools.logging works just fine
This throws
sun.security.validator.ValidatorException (in module java.base) because module java.base does not
export sun.security.validator to unnamed module @ac279a9
clojure.tools.logging works | (ns clojure-experiments.logging
(:require [clojure.spec.alpha :as s]
[clojure.tools.logging :as log]
[clojure.tools.logging.impl :as log-impl]
[taoensso.timbre :as log-timbre])
(:import (org.apache.logging.log4j Level LogManager)
(org.apache.logging.log4j.core.config Configurator)))
(defn log-levels []
(->> (Level/values)
seq
(map (fn [log-level]
[(-> log-level str clojure.string/lower-case keyword)
log-level]))
(into {}))
#_{:fatal Level/FATAL
:error Level/ERROR
:warn Level/WARN
:info Level/INFO
:debug Level/DEBUG
:trace Level/TRACE
:off Level/OFF
:all Level/ALL}
)
(defn to-log4j-level [level-keyword]
(get (log-levels) level-keyword))
highest priority ( rather than cl - factory and slf4j - factory - commons - logging e.g. is included in apache http client )
(defn find-factory
"Returns the first non-nil value from slf4j-factory, cl-factory,
log4j2-factory, log4j-factory, and jul-factory."
[]
(or (log-impl/log4j2-factory)
(log-impl/slf4j-factory)
(log-impl/cl-factory)
(log-impl/log4j-factory)
(log-impl/jul-factory)
this should never happen in 1.5 +
(RuntimeException.
"Valid logging implementation could not be found."))))
(s/def ::log-level (set (keys (log-levels))))
(s/fdef set-level!
:args (s/cat :level ::log-level)
:ret nil?)
(defn set-level!
"Sets new log level for the Root logger. "
[level]
(if-let [log-level (to-log4j-level level)]
(do
(Configurator/setRootLevel log-level)
(alter-var-root #'log/*logger-factory* (constantly (find-factory))))
(throw (IllegalArgumentException. (str "Invalid log level: " level)))))
(comment
(Configurator/setRootLevel (to-log4j-level :debug))
(do
(set-level! :info)
(log/info "PRINTED.")
(log/debug "NOT PRINTED")
(set-level! :debug)
(log/debug "PRINTED?")
(set-level! :info)
(log/debug "NOT PRINTED")
(set-level! :warn)
(log/info "INFO NOT PRINTED"))
(log-impl/get-logger log/*logger-factory* *ns*)
(log-impl/get-logger (find-factory) *ns*)
)
Timbre
(def secrets-log-patterns
"All patterns matching potentially sensitive data in logs that should be replaced by `secret-replacement-str`.
These patterns should always follow the format '(Whatever is the matching prefix) MYSCRET'.
- note that the parens are required!
This will match the log message 'Whatever is the matching prefix MYSCRET'
and that message will be replaced with 'Whatever is the matching prefix ***'"
OAuth access tokens sent in the Authorization header
OAuth access / refresh tokens as used internally in Clojure maps or returned by OAuth provider " access_token " API
OAuth app client secret sent in the request form body param
OAuth app client secret as stored in a Clojure map
])
(def secret-replacement "***")
(defn- mask-secrets [secrets-patterns replacement log-message]
((reduce
(fn mask-pattern [msg pattern]
the original prefix ( $ 1 ) plus the secret replaced with ' * * * '
(clojure.string/replace msg pattern (str "$1" secret-replacement)))
log-message
secrets-patterns)))
(def mask-secrets-in-log (partial mask-secrets secrets-log-patterns secret-replacement))
(comment
(def my-msg
"2019-06-12 08:41:34.115 Jurajs-MacBook-Pro-2.local DEBUG [org.apache.http.wire:73] - http-outgoing-30 >> \"Authorization: Bearer 882a64a1234567890abcdefghij1234567890dcb[\r][\n]\"")
(mask-secrets-in-log my-msg)
(crit/quick-bench (mask-secrets-in-log my-msg))
)
(defn mask-secrets-log-config
"Mask sensitive data in the logs - e.g. OAuth client secrets and access tokens.
See for an old example of masking middleware.
However that is complex and not easy to do (one would have to 'mask' everything in the `:vargs` vector)
so the easier option using the `:output-fn` was chosen."
[]
(log-timbre/merge-config!
{:output-fn (comp
mask-secrets-in-log
log-timbre/default-output-fn)}))
(comment
(log-timbre/info "Bearer XYZ")
(mask-secrets-log-config)
(log-timbre/info "Bearer XYZ")
)
Timbre does n't work with internal exception classes like ` SunCertPathBuilderException `
(comment
1 . Unhandled java.lang . IllegalAccessException
class clojure.core$bean$fn__7278$fn__7279 can not access class
(try
(slurp "-root.badssl.com/")
(catch Exception e
(taoensso.timbre/error e "ssl error")))
(try
(slurp "-root.badssl.com/")
(catch Exception e
(log/error e "ssl error")))
)
|
7be7ae27e6d668ed00b7ec08b4e147065ddaacb0be6287f2e8ed34ea883a528f | meain/evil-textobj-tree-sitter | textobjects.scm | inherits :
| null | https://raw.githubusercontent.com/meain/evil-textobj-tree-sitter/d67bdd55ae0d70978232e952020f6e8300b5c7bb/queries/cuda/textobjects.scm | scheme | inherits :
| |
440a702b527f8b7d101c81d3b79468d567eddf707eccbf592b60b4910f17e5eb | muqiuhan/MLisp | mlisp.ml | (****************************************************************************)
(* MLisp *)
Copyright ( C ) 2022 Muqiu Han
(* *)
(* This program is free software: you can redistribute it and/or modify *)
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation , either version 3 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Affero General Public License for more details. *)
(* *)
You should have received a copy of the GNU Affero General Public License
(* along with this program. If not, see </>. *)
(****************************************************************************)
let exec_path = "../bin/main.exe"
let test_path = "../../../test/"
let is_mlisp_file file_name =
match String.split_on_char '.' file_name with
| _ :: [ "mlisp" ] -> true
| _ -> false
;;
let test_mlisp_file file_name =
Sys.command (exec_path ^ " " ^ test_path ^ file_name) |> ignore
;;
let test_files =
test_path
|> Sys.readdir
|> Array.iter (fun file_name ->
if is_mlisp_file file_name
then (
flush_all ();
Printf.printf "Test %s ..." file_name;
test_mlisp_file file_name;
print_endline "done!")
else ())
;;
| null | https://raw.githubusercontent.com/muqiuhan/MLisp/5d79cf6731910d77cde674fb77d71d3ddad38e3c/test/mlisp.ml | ocaml | **************************************************************************
MLisp
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
along with this program. If not, see </>.
************************************************************************** | Copyright ( C ) 2022 Muqiu Han
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU Affero General Public License
let exec_path = "../bin/main.exe"
let test_path = "../../../test/"
let is_mlisp_file file_name =
match String.split_on_char '.' file_name with
| _ :: [ "mlisp" ] -> true
| _ -> false
;;
let test_mlisp_file file_name =
Sys.command (exec_path ^ " " ^ test_path ^ file_name) |> ignore
;;
let test_files =
test_path
|> Sys.readdir
|> Array.iter (fun file_name ->
if is_mlisp_file file_name
then (
flush_all ();
Printf.printf "Test %s ..." file_name;
test_mlisp_file file_name;
print_endline "done!")
else ())
;;
|
304a14a31b4b158353811dac81e9a42389cd7a74b7586dc0f7ad02fe662aeaf3 | RefactoringTools/HaRe | Dd1.hs | module DeleteDef.Dd1 where
--simple bind
c :: Integer
c = 5
remove5s :: [Integer] -> [Integer]
remove5s [] = []
remove5s (5:xs) = remove5s xs
remove5s (x:xs) = x: (remove5s xs)
funcWithLet :: (Num a) => a -> a
funcWithLet x = let c = 12 in
c * x
funcWithWhere :: (Num a) => a -> a
funcWithWhere x = x + c
where c = 12
fact :: Integer -> Integer
fact 0 = 1
fact n = n * fact (n - 1)
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/DeleteDef/Dd1.hs | haskell | simple bind | module DeleteDef.Dd1 where
c :: Integer
c = 5
remove5s :: [Integer] -> [Integer]
remove5s [] = []
remove5s (5:xs) = remove5s xs
remove5s (x:xs) = x: (remove5s xs)
funcWithLet :: (Num a) => a -> a
funcWithLet x = let c = 12 in
c * x
funcWithWhere :: (Num a) => a -> a
funcWithWhere x = x + c
where c = 12
fact :: Integer -> Integer
fact 0 = 1
fact n = n * fact (n - 1)
|
c342145aa09afb19bc3a735dc8da8ec35380f7bd94117259c5f186417f9e5f07 | xvw/muhokama | lib_test.mli | * { 1 Test definition }
open Lib_common
(** An helper for test definition.*)
val test
: ?speed:Alcotest.speed_level
-> about:string
-> desc:string
-> ('a -> unit)
-> 'a Alcotest.test_case
val integration_test
: ?migrations_path:string
-> ?speed:Alcotest.speed_level
-> about:string
-> desc:string
-> (Env.t -> Caqti_lwt.connection -> 'a Try.t Lwt.t)
-> ('a Try.t -> unit)
-> unit Alcotest.test_case
(** An helper for checking equalities.*)
val same : 'a Alcotest.testable -> expected:'a -> computed:'a -> unit
(** [delayed ~time f] will perform [f] after awaiting [time]. *)
val delayed : ?time:float -> (unit -> 'a Lwt.t) -> 'a Lwt.t
(** {1 Testables} *)
module Testable = Testable
* { 1 diverses Helpers }
val nel : 'a -> 'a list -> 'a Preface.Nonempty_list.t
* { 1 model helpers }
val user_for_registration
: string
-> string
-> string
-> string
-> Models.User.registration_form Try.t
val category_for_creation
: string
-> string
-> Models.Category.creation_form Try.t
val user_for_connection : string -> string -> Models.User.connection_form Try.t
val shared_link_for_creation
: string
-> string
-> Models.Shared_link.creation_form Try.t
val user_for_update_preferences
: string
-> string
-> Models.User.t
-> Models.User.update_preference_form Try.t
val user_for_update_password
: string
-> string
-> Models.User.t
-> Models.User.update_password_form Try.t
val make_user
: ?state:Models.User.State.t
-> string
-> string
-> string
-> Caqti_lwt.connection
-> Models.User.t Try.t Lwt.t
val create_category
: string
-> string
-> Caqti_lwt.connection
-> unit Try.t Lwt.t
val create_categories
: Caqti_lwt.connection
-> (Models.Category.t * Models.Category.t * Models.Category.t) Try.t Lwt.t
val create_users
: Caqti_lwt.connection
-> (Models.User.t * Models.User.t * Models.User.t * Models.User.t) Try.t Lwt.t
val create_topic
: string
-> Models.User.t
-> string
-> string
-> Caqti_lwt.connection
-> string Try.t Lwt.t
val update_topic
: string
-> string
-> string
-> string
-> Caqti_lwt.connection
-> unit Try.t Lwt.t
val create_message
: Models.User.t
-> string
-> string
-> Caqti_lwt.connection
-> string Try.t Lwt.t
val create_shared_link
: Models.User.t
-> string
-> string
-> Caqti_lwt.connection
-> unit Try.t Lwt.t
* { 1 Some data }
module Individual : sig
type t =
{ id : string
; age : int option
; name : string option
; email : string
}
val pp : t Fmt.t
val equal : t -> t -> bool
val testable : t Alcotest.testable
val make : string -> int option -> string option -> string -> t
end
| null | https://raw.githubusercontent.com/xvw/muhokama/fc0879ec44e7bbb99f140950191e2a883fe60597/test/util/lib_test.mli | ocaml | * An helper for test definition.
* An helper for checking equalities.
* [delayed ~time f] will perform [f] after awaiting [time].
* {1 Testables} | * { 1 Test definition }
open Lib_common
val test
: ?speed:Alcotest.speed_level
-> about:string
-> desc:string
-> ('a -> unit)
-> 'a Alcotest.test_case
val integration_test
: ?migrations_path:string
-> ?speed:Alcotest.speed_level
-> about:string
-> desc:string
-> (Env.t -> Caqti_lwt.connection -> 'a Try.t Lwt.t)
-> ('a Try.t -> unit)
-> unit Alcotest.test_case
val same : 'a Alcotest.testable -> expected:'a -> computed:'a -> unit
val delayed : ?time:float -> (unit -> 'a Lwt.t) -> 'a Lwt.t
module Testable = Testable
* { 1 diverses Helpers }
val nel : 'a -> 'a list -> 'a Preface.Nonempty_list.t
* { 1 model helpers }
val user_for_registration
: string
-> string
-> string
-> string
-> Models.User.registration_form Try.t
val category_for_creation
: string
-> string
-> Models.Category.creation_form Try.t
val user_for_connection : string -> string -> Models.User.connection_form Try.t
val shared_link_for_creation
: string
-> string
-> Models.Shared_link.creation_form Try.t
val user_for_update_preferences
: string
-> string
-> Models.User.t
-> Models.User.update_preference_form Try.t
val user_for_update_password
: string
-> string
-> Models.User.t
-> Models.User.update_password_form Try.t
val make_user
: ?state:Models.User.State.t
-> string
-> string
-> string
-> Caqti_lwt.connection
-> Models.User.t Try.t Lwt.t
val create_category
: string
-> string
-> Caqti_lwt.connection
-> unit Try.t Lwt.t
val create_categories
: Caqti_lwt.connection
-> (Models.Category.t * Models.Category.t * Models.Category.t) Try.t Lwt.t
val create_users
: Caqti_lwt.connection
-> (Models.User.t * Models.User.t * Models.User.t * Models.User.t) Try.t Lwt.t
val create_topic
: string
-> Models.User.t
-> string
-> string
-> Caqti_lwt.connection
-> string Try.t Lwt.t
val update_topic
: string
-> string
-> string
-> string
-> Caqti_lwt.connection
-> unit Try.t Lwt.t
val create_message
: Models.User.t
-> string
-> string
-> Caqti_lwt.connection
-> string Try.t Lwt.t
val create_shared_link
: Models.User.t
-> string
-> string
-> Caqti_lwt.connection
-> unit Try.t Lwt.t
* { 1 Some data }
module Individual : sig
type t =
{ id : string
; age : int option
; name : string option
; email : string
}
val pp : t Fmt.t
val equal : t -> t -> bool
val testable : t Alcotest.testable
val make : string -> int option -> string option -> string -> t
end
|
9c7c2dcc20f6e65479bdc8abe4729b24a98e33d05d76d5c51aeb484391ec16a2 | dmitryvk/sbcl-win32-threads | mop-9.impure-cload.lisp | miscellaneous side - effectful tests of the MOP
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
While most of SBCL is derived from the CMU CL system , the test
;;;; files (like this one) were written from scratch after the fork
from CMU CL .
;;;;
;;;; This software is in the public domain and is provided with
;;;; absolutely no warranty. See the COPYING and CREDITS files for
;;;; more information.
this file contains tests of ( SETF CLASS - NAME ) and ( SETF
;;; GENERIC-FUNCTION-NAME)
(defpackage "MOP-9"
(:use "CL" "SB-MOP" "TEST-UTIL"))
(in-package "MOP-9")
(defclass metaclass/ri (standard-class)
())
(defmethod validate-superclass ((c metaclass/ri) (s standard-class))
t)
(defclass class/ri ()
()
(:metaclass metaclass/ri))
(defvar *class/ri-args* nil)
(defmethod reinitialize-instance :after ((o metaclass/ri) &rest initargs)
(setf *class/ri-args* initargs))
(with-test (:name ((setf class-name) reinitialize-instance))
(let ((class (find-class 'class/ri)))
(setf (class-name class) 'name)
(assert (equal *class/ri-args* '(:name name)))
(setf (class-name class) 'class/ri)
(assert (equal *class/ri-args* '(:name class/ri)))))
(defclass dependent ()
((slot :initform nil :accessor dependent-slot)))
(defclass class/dependent ()
())
(defvar *dependent* (make-instance 'dependent))
(defmethod update-dependent ((object standard-class) (dependent dependent)
&rest args)
(setf (dependent-slot dependent) args))
(with-test (:name ((setf class-name) update-dependent))
(let ((class (find-class 'class/dependent)))
(add-dependent class *dependent*)
(setf (class-name class) 'name)
(assert (equal (dependent-slot *dependent*) '(:name name)))
(remove-dependent class *dependent*)
(setf (class-name class) 'name)
(assert (equal (dependent-slot *dependent*) '(:name name)))))
(defclass gfc/ri (standard-generic-function)
()
(:metaclass funcallable-standard-class))
(defgeneric gf/ri ()
(:generic-function-class gfc/ri))
(defvar *gf/ri-args* nil)
(defmethod reinitialize-instance :after ((o gfc/ri) &rest initargs)
(setf *gf/ri-args* initargs))
(with-test (:name ((setf generic-function-name) reinitialize-instance))
(let ((gf #'gf/ri))
(setf (generic-function-name gf) 'name)
(assert (equal *gf/ri-args* '(:name name)))
(setf (generic-function-name gf) 'gf/ri)
(assert (equal *gf/ri-args* '(:name gf/ri)))))
(defgeneric gf/dependent ())
(defmethod update-dependent ((object standard-generic-function)
(dependent dependent)
&rest args)
(setf (dependent-slot dependent) args))
(with-test (:name ((setf generic-function-name) update-dependent))
(let ((gf (find-class 'class/dependent)))
(add-dependent gf *dependent*)
(setf (generic-function-name gf) 'gf/name)
(assert (equal (dependent-slot *dependent*) '(:name gf/name)))
(remove-dependent gf *dependent*)
(setf (generic-function-name gf) 'gf/dependent)
(assert (equal (dependent-slot *dependent*) '(:name gf/name)))))
| null | https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/tests/mop-9.impure-cload.lisp | lisp | more information.
files (like this one) were written from scratch after the fork
This software is in the public domain and is provided with
absolutely no warranty. See the COPYING and CREDITS files for
more information.
GENERIC-FUNCTION-NAME) | miscellaneous side - effectful tests of the MOP
This software is part of the SBCL system . See the README file for
While most of SBCL is derived from the CMU CL system , the test
from CMU CL .
this file contains tests of ( SETF CLASS - NAME ) and ( SETF
(defpackage "MOP-9"
(:use "CL" "SB-MOP" "TEST-UTIL"))
(in-package "MOP-9")
(defclass metaclass/ri (standard-class)
())
(defmethod validate-superclass ((c metaclass/ri) (s standard-class))
t)
(defclass class/ri ()
()
(:metaclass metaclass/ri))
(defvar *class/ri-args* nil)
(defmethod reinitialize-instance :after ((o metaclass/ri) &rest initargs)
(setf *class/ri-args* initargs))
(with-test (:name ((setf class-name) reinitialize-instance))
(let ((class (find-class 'class/ri)))
(setf (class-name class) 'name)
(assert (equal *class/ri-args* '(:name name)))
(setf (class-name class) 'class/ri)
(assert (equal *class/ri-args* '(:name class/ri)))))
(defclass dependent ()
((slot :initform nil :accessor dependent-slot)))
(defclass class/dependent ()
())
(defvar *dependent* (make-instance 'dependent))
(defmethod update-dependent ((object standard-class) (dependent dependent)
&rest args)
(setf (dependent-slot dependent) args))
(with-test (:name ((setf class-name) update-dependent))
(let ((class (find-class 'class/dependent)))
(add-dependent class *dependent*)
(setf (class-name class) 'name)
(assert (equal (dependent-slot *dependent*) '(:name name)))
(remove-dependent class *dependent*)
(setf (class-name class) 'name)
(assert (equal (dependent-slot *dependent*) '(:name name)))))
(defclass gfc/ri (standard-generic-function)
()
(:metaclass funcallable-standard-class))
(defgeneric gf/ri ()
(:generic-function-class gfc/ri))
(defvar *gf/ri-args* nil)
(defmethod reinitialize-instance :after ((o gfc/ri) &rest initargs)
(setf *gf/ri-args* initargs))
(with-test (:name ((setf generic-function-name) reinitialize-instance))
(let ((gf #'gf/ri))
(setf (generic-function-name gf) 'name)
(assert (equal *gf/ri-args* '(:name name)))
(setf (generic-function-name gf) 'gf/ri)
(assert (equal *gf/ri-args* '(:name gf/ri)))))
(defgeneric gf/dependent ())
(defmethod update-dependent ((object standard-generic-function)
(dependent dependent)
&rest args)
(setf (dependent-slot dependent) args))
(with-test (:name ((setf generic-function-name) update-dependent))
(let ((gf (find-class 'class/dependent)))
(add-dependent gf *dependent*)
(setf (generic-function-name gf) 'gf/name)
(assert (equal (dependent-slot *dependent*) '(:name gf/name)))
(remove-dependent gf *dependent*)
(setf (generic-function-name gf) 'gf/dependent)
(assert (equal (dependent-slot *dependent*) '(:name gf/name)))))
|
4cb38d3b48197ae52baa9a784c2ada6abae98f50afc440de9e33bd131cb0b50d | steshaw/PLAR | intro.ml | (* ========================================================================= *)
(* Simple algebraic expression example from the introductory chapter. *)
(* *)
Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . )
(* ========================================================================= *)
type expression =
Var of string
| Const of int
| Add of expression * expression
| Mul of expression * expression;;
(* ------------------------------------------------------------------------- *)
(* Trivial example of using the type constructors. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
Add(Mul(Const 2,Var "x"),Var "y");;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Simplification example. *)
(* ------------------------------------------------------------------------- *)
let simplify1 expr =
match expr with
Add(Const(m),Const(n)) -> Const(m + n)
| Mul(Const(m),Const(n)) -> Const(m * n)
| Add(Const(0),x) -> x
| Add(x,Const(0)) -> x
| Mul(Const(0),x) -> Const(0)
| Mul(x,Const(0)) -> Const(0)
| Mul(Const(1),x) -> x
| Mul(x,Const(1)) -> x
| _ -> expr;;
let rec simplify expr =
match expr with
Add(e1,e2) -> simplify1(Add(simplify e1,simplify e2))
| Mul(e1,e2) -> simplify1(Mul(simplify e1,simplify e2))
| _ -> simplify1 expr;;
(* ------------------------------------------------------------------------- *)
(* Example. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
let e = Add(Mul(Add(Mul(Const(0),Var "x"),Const(1)),Const(3)),
Const(12));;
simplify e;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Lexical analysis. *)
(* ------------------------------------------------------------------------- *)
let matches s = let chars = explode s in fun c -> mem c chars;;
let space = matches " \t\n\r"
and punctuation = matches "()[]{},"
and symbolic = matches "~`!@#$%^&*-+=|\\:;<>.?/"
and numeric = matches "0123456789"
and alphanumeric = matches
"abcdefghijklmnopqrstuvwxyz_'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";;
let rec lexwhile prop inp =
match inp with
c::cs when prop c -> let tok,rest = lexwhile prop cs in c^tok,rest
| _ -> "",inp;;
let rec lex inp =
match snd(lexwhile space inp) with
[] -> []
| c::cs -> let prop = if alphanumeric(c) then alphanumeric
else if symbolic(c) then symbolic
else fun c -> false in
let toktl,rest = lexwhile prop cs in
(c^toktl)::lex rest;;
START_INTERACTIVE;;
lex(explode "2*((var_1 + x') + 11)");;
lex(explode "if (*p1-- == *p2++) then f() else g()");;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Parsing. *)
(* ------------------------------------------------------------------------- *)
let rec parse_expression i =
match parse_product i with
e1,"+"::i1 -> let e2,i2 = parse_expression i1 in Add(e1,e2),i2
| e1,i1 -> e1,i1
and parse_product i =
match parse_atom i with
e1,"*"::i1 -> let e2,i2 = parse_product i1 in Mul(e1,e2),i2
| e1,i1 -> e1,i1
and parse_atom i =
match i with
[] -> failwith "Expected an expression at end of input"
| "("::i1 -> (match parse_expression i1 with
e2,")"::i2 -> e2,i2
| _ -> failwith "Expected closing bracket")
| tok::i1 -> if forall numeric (explode tok)
then Const(int_of_string tok),i1
else Var(tok),i1;;
(* ------------------------------------------------------------------------- *)
Generic function to impose lexing and exhaustion checking on a parser .
(* ------------------------------------------------------------------------- *)
let make_parser pfn s =
let expr,rest = pfn (lex(explode s)) in
if rest = [] then expr else failwith "Unparsed input";;
(* ------------------------------------------------------------------------- *)
(* Our parser. *)
(* ------------------------------------------------------------------------- *)
let default_parser = make_parser parse_expression;;
START_INTERACTIVE;;
default_parser "x + 1";;
(* ------------------------------------------------------------------------- *)
Demonstrate automatic installation .
(* ------------------------------------------------------------------------- *)
<<(x1 + x2 + x3) * (1 + 2 + 3 * x + y)>>;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
Conservatively bracketing first attempt at printer .
(* ------------------------------------------------------------------------- *)
let rec string_of_exp e =
match e with
Var s -> s
| Const n -> string_of_int n
| Add(e1,e2) -> "("^(string_of_exp e1)^" + "^(string_of_exp e2)^")"
| Mul(e1,e2) -> "("^(string_of_exp e1)^" * "^(string_of_exp e2)^")";;
(* ------------------------------------------------------------------------- *)
(* Examples. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
string_of_exp <<x + 3 * y>>;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Somewhat better attempt. *)
(* ------------------------------------------------------------------------- *)
let rec string_of_exp pr e =
match e with
Var s -> s
| Const n -> string_of_int n
| Add(e1,e2) ->
let s = (string_of_exp 3 e1)^" + "^(string_of_exp 2 e2) in
if 2 < pr then "("^s^")" else s
| Mul(e1,e2) ->
let s = (string_of_exp 5 e1)^" * "^(string_of_exp 4 e2) in
if 4 < pr then "("^s^")" else s;;
(* ------------------------------------------------------------------------- *)
(* Install it. *)
(* ------------------------------------------------------------------------- *)
let print_exp e = Format.print_string ("<<"^string_of_exp 0 e^">>");;
#install_printer print_exp;;
(* ------------------------------------------------------------------------- *)
(* Examples. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
<<x + 3 * y>>;;
<<(x + 3) * y>>;;
<<1 + 2 + 3>>;;
<<((1 + 2) + 3) + 4>>;;
END_INTERACTIVE;;
(* ------------------------------------------------------------------------- *)
(* Example shows the problem. *)
(* ------------------------------------------------------------------------- *)
START_INTERACTIVE;;
<<(x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10) *
(y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10)>>;;
END_INTERACTIVE;;
| null | https://raw.githubusercontent.com/steshaw/PLAR/c143b097d1028963f4c1d24f45a1a56c8b65b838/intro.ml | ocaml | =========================================================================
Simple algebraic expression example from the introductory chapter.
=========================================================================
-------------------------------------------------------------------------
Trivial example of using the type constructors.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Simplification example.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Example.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Lexical analysis.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Parsing.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Our parser.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Examples.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Somewhat better attempt.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Install it.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Examples.
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Example shows the problem.
------------------------------------------------------------------------- | Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . )
type expression =
Var of string
| Const of int
| Add of expression * expression
| Mul of expression * expression;;
START_INTERACTIVE;;
Add(Mul(Const 2,Var "x"),Var "y");;
END_INTERACTIVE;;
let simplify1 expr =
match expr with
Add(Const(m),Const(n)) -> Const(m + n)
| Mul(Const(m),Const(n)) -> Const(m * n)
| Add(Const(0),x) -> x
| Add(x,Const(0)) -> x
| Mul(Const(0),x) -> Const(0)
| Mul(x,Const(0)) -> Const(0)
| Mul(Const(1),x) -> x
| Mul(x,Const(1)) -> x
| _ -> expr;;
let rec simplify expr =
match expr with
Add(e1,e2) -> simplify1(Add(simplify e1,simplify e2))
| Mul(e1,e2) -> simplify1(Mul(simplify e1,simplify e2))
| _ -> simplify1 expr;;
START_INTERACTIVE;;
let e = Add(Mul(Add(Mul(Const(0),Var "x"),Const(1)),Const(3)),
Const(12));;
simplify e;;
END_INTERACTIVE;;
let matches s = let chars = explode s in fun c -> mem c chars;;
let space = matches " \t\n\r"
and punctuation = matches "()[]{},"
and symbolic = matches "~`!@#$%^&*-+=|\\:;<>.?/"
and numeric = matches "0123456789"
and alphanumeric = matches
"abcdefghijklmnopqrstuvwxyz_'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";;
let rec lexwhile prop inp =
match inp with
c::cs when prop c -> let tok,rest = lexwhile prop cs in c^tok,rest
| _ -> "",inp;;
let rec lex inp =
match snd(lexwhile space inp) with
[] -> []
| c::cs -> let prop = if alphanumeric(c) then alphanumeric
else if symbolic(c) then symbolic
else fun c -> false in
let toktl,rest = lexwhile prop cs in
(c^toktl)::lex rest;;
START_INTERACTIVE;;
lex(explode "2*((var_1 + x') + 11)");;
lex(explode "if (*p1-- == *p2++) then f() else g()");;
END_INTERACTIVE;;
let rec parse_expression i =
match parse_product i with
e1,"+"::i1 -> let e2,i2 = parse_expression i1 in Add(e1,e2),i2
| e1,i1 -> e1,i1
and parse_product i =
match parse_atom i with
e1,"*"::i1 -> let e2,i2 = parse_product i1 in Mul(e1,e2),i2
| e1,i1 -> e1,i1
and parse_atom i =
match i with
[] -> failwith "Expected an expression at end of input"
| "("::i1 -> (match parse_expression i1 with
e2,")"::i2 -> e2,i2
| _ -> failwith "Expected closing bracket")
| tok::i1 -> if forall numeric (explode tok)
then Const(int_of_string tok),i1
else Var(tok),i1;;
Generic function to impose lexing and exhaustion checking on a parser .
let make_parser pfn s =
let expr,rest = pfn (lex(explode s)) in
if rest = [] then expr else failwith "Unparsed input";;
let default_parser = make_parser parse_expression;;
START_INTERACTIVE;;
default_parser "x + 1";;
Demonstrate automatic installation .
<<(x1 + x2 + x3) * (1 + 2 + 3 * x + y)>>;;
END_INTERACTIVE;;
Conservatively bracketing first attempt at printer .
let rec string_of_exp e =
match e with
Var s -> s
| Const n -> string_of_int n
| Add(e1,e2) -> "("^(string_of_exp e1)^" + "^(string_of_exp e2)^")"
| Mul(e1,e2) -> "("^(string_of_exp e1)^" * "^(string_of_exp e2)^")";;
START_INTERACTIVE;;
string_of_exp <<x + 3 * y>>;;
END_INTERACTIVE;;
let rec string_of_exp pr e =
match e with
Var s -> s
| Const n -> string_of_int n
| Add(e1,e2) ->
let s = (string_of_exp 3 e1)^" + "^(string_of_exp 2 e2) in
if 2 < pr then "("^s^")" else s
| Mul(e1,e2) ->
let s = (string_of_exp 5 e1)^" * "^(string_of_exp 4 e2) in
if 4 < pr then "("^s^")" else s;;
let print_exp e = Format.print_string ("<<"^string_of_exp 0 e^">>");;
#install_printer print_exp;;
START_INTERACTIVE;;
<<x + 3 * y>>;;
<<(x + 3) * y>>;;
<<1 + 2 + 3>>;;
<<((1 + 2) + 3) + 4>>;;
END_INTERACTIVE;;
START_INTERACTIVE;;
<<(x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10) *
(y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10)>>;;
END_INTERACTIVE;;
|
987a8c790dc3ba4cf9d93c6364c182d82d4a628f06f246e0e9ca1cae25df3a55 | well-typed/large-records | R070.hs | #if PROFILE_CORESIZE
{-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-}
#endif
#if PROFILE_TIMING
{-# OPTIONS_GHC -ddump-to-file -ddump-timings #-}
#endif
module Experiment.Generics_LR.Sized.R070 where
import Data.Aeson (Value)
import Bench.HList
import Experiment.Generics_LR
import Common.HListOfSize.HL070
hlistToJSON :: HList ExampleFields -> Value
hlistToJSON = gtoJSON | null | https://raw.githubusercontent.com/well-typed/large-records/551f265845fbe56346988a6b484dca40ef380609/large-records-benchmarks/bench/experiments/Experiment/Generics_LR/Sized/R070.hs | haskell | # OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #
# OPTIONS_GHC -ddump-to-file -ddump-timings # | #if PROFILE_CORESIZE
#endif
#if PROFILE_TIMING
#endif
module Experiment.Generics_LR.Sized.R070 where
import Data.Aeson (Value)
import Bench.HList
import Experiment.Generics_LR
import Common.HListOfSize.HL070
hlistToJSON :: HList ExampleFields -> Value
hlistToJSON = gtoJSON |
c0d3fbf64efea713a826fd34da20be0c9a68daba146b618fe84fba14c5e6b945 | fakedata-haskell/fakedata | Food.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Faker.Provider.Food where
import Config
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Map.Strict (Map)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseFood :: FromJSON a => FakerSettings -> Value -> Parser a
parseFood settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
food <- faker .: "food"
pure food
parseFood settings val = fail $ "expected Object, but got " <> (show val)
parseFoodField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseFoodField settings txt val = do
food <- parseFood settings val
field <- food .:? txt .!= mempty
pure field
parseFoodFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseFoodFields settings txts val = do
food <- parseFood settings val
helper food txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
$(genParser "food" "dish")
$(genProvider "food" "dish")
$(genParser "food" "descriptions")
$(genProvider "food" "descriptions")
$(genParser "food" "ingredients")
$(genProvider "food" "ingredients")
$(genParser "food" "fruits")
$(genProvider "food" "fruits")
$(genParser "food" "vegetables")
$(genProvider "food" "vegetables")
$(genParser "food" "spices")
$(genProvider "food" "spices")
$(genParser "food" "measurements")
$(genProvider "food" "measurements")
$(genParser "food" "measurement_sizes")
$(genProvider "food" "measurement_sizes")
$(genParser "food" "metric_measurements")
$(genProvider "food" "metric_measurements")
$(genParser "food" "sushi")
$(genProvider "food" "sushi")
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/Food.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.Provider.Food where
import Config
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Map.Strict (Map)
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseFood :: FromJSON a => FakerSettings -> Value -> Parser a
parseFood settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
food <- faker .: "food"
pure food
parseFood settings val = fail $ "expected Object, but got " <> (show val)
parseFoodField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseFoodField settings txt val = do
food <- parseFood settings val
field <- food .:? txt .!= mempty
pure field
parseFoodFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseFoodFields settings txts val = do
food <- parseFood settings val
helper food txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
$(genParser "food" "dish")
$(genProvider "food" "dish")
$(genParser "food" "descriptions")
$(genProvider "food" "descriptions")
$(genParser "food" "ingredients")
$(genProvider "food" "ingredients")
$(genParser "food" "fruits")
$(genProvider "food" "fruits")
$(genParser "food" "vegetables")
$(genProvider "food" "vegetables")
$(genParser "food" "spices")
$(genProvider "food" "spices")
$(genParser "food" "measurements")
$(genProvider "food" "measurements")
$(genParser "food" "measurement_sizes")
$(genProvider "food" "measurement_sizes")
$(genParser "food" "metric_measurements")
$(genProvider "food" "metric_measurements")
$(genParser "food" "sushi")
$(genProvider "food" "sushi")
|
ce3a500f8cc5a530f45451ce3165d82bc2c7d2674d255e6e316b7810f63f8bae | ghc/nofib | nbody.hs |
- Intel Concurrent Collections for ( c ) 2010 , Intel Corporation .
-
- This program is free software ; you can redistribute it and/or modify it
- under the terms and conditions of the GNU Lesser General Public License ,
- version 2.1 , as published by the Free Software Foundation .
-
- This program is distributed in the hope it will be useful , but WITHOUT
- ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
- FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for
- more details .
-
- You should have received a copy of the GNU Lesser General Public License along with
- this program ; if not , write to the Free Software Foundation , Inc. ,
- 51 Franklin St - Fifth Floor , Boston , USA .
-
- Intel Concurrent Collections for Haskell
- Copyright (c) 2010, Intel Corporation.
-
- This program is free software; you can redistribute it and/or modify it
- under the terms and conditions of the GNU Lesser General Public License,
- version 2.1, as published by the Free Software Foundation.
-
- This program is distributed in the hope it will be useful, but WITHOUT
- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
- more details.
-
- You should have received a copy of the GNU Lesser General Public License along with
- this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
-
-}
# LANGUAGE CPP , MagicHash , UnboxedTuples , BangPatterns #
Author :
This program uses CnC to calculate the accelerations of the bodies in a 3D system .
import System.Environment
import Data.Int
import Control.Monad hiding (join)
import GHC.Exts
import GHC.Conc (numCapabilities)
import Control.Seq as Seq
import qualified Data.List as List
import qualified Data.Array as Array
import Future
type Float3D = (Float, Float, Float)
type UFloat3D = (# Float#, Float#, Float# #)
-- This step generates the bodies in the system.
genVector tag = (tag' * 1.0, tag' * 0.2, tag' * 30.0)
where tag' = fromIntegral tag
-- Only doing the O(N^2) part in parallel:
-- This step computes the accelerations of the bodies.
compute vecList tag =
let myvector = vecList Array.! (tag-1) in
accel myvector vecList
vecList = elems vecArr
g = 9.8
: : Float # - > UFloat3D - > UFloat3D
( # x , y , z # ) = ( # c*x , c*y , c*z # )
multTriple :: Float -> Float3D -> Float3D
multTriple c ( x,y,z ) = ( c*x,c*y,c*z )
# define OLD_VER
#ifdef OLD_VER
pairWiseAccel :: Float3D -> Float3D -> Float3D
pairWiseAccel (x,y,z) (x',y',z') = let dx = x'-x
dy = y'-y
dz = z'-z
eps = 0.005
distanceSq = dx^2 + dy^2 + dz^2 + eps
factor = 1/sqrt(distanceSq ^ 3)
in multTriple factor ( dx , dy , dz )
in multTriple factor (dx,dy,dz)
sumTriples = foldr (\(x,y,z) (x',y',z') -> (x+x',y+y',z+z')) (0,0,0)
accel vector vecList = multTriple g $ sumTriples $ List.map (pairWiseAccel vector) vecList
#else
-- Making this much leCss haskell like to avoid allocation:
(strt,end) = Array.bounds vecList
accel :: Float3D -> (Array.Array Int Float3D) -> Float3D
accel vector vecList =
-- Manually inlining to see if the tuples unbox:
let (# sx,sy,sz #) = loop strt 0 0 0
loop !i !ax !ay !az
| i == end = (# ax,ay,az #)
| otherwise =
let ( x,y,z ) = vector
( x',y',z' ) = vecList Array.! i
(# dx,dy,dz #) = (# x'-x, y'-y, z'-z #)
eps = 0.005
#if 1
distanceSq = dx^2 + dy^2 + dz^2 + eps
factor = 1/sqrt(distanceSq ^ 3)
#else
distanceSq = dx*dx + dy*dy + dz*dz + eps
factor = 1/sqrt(distanceSq * distanceSq * distanceSq)
#endif
(# px,py,pz #) = (# factor * dx, factor * dy, factor *dz #)
in loop (i+1) (ax+px) (ay+py) (az+pz)
in ( g*sx, g*sy, g*sz )
#endif
This describes the graph-- The same tag collection prescribes the two step collections .
--run :: Int -> (b, c)
--run :: Int -> ([(Int, (Float, Float, Float))], [(Int, (Float, Float, Float))])
run : : Int - > ( [ Float3D ] , [ Float3D ] )
run :: Int -> [Float3D]
run n = runEval $ do
let initVecs = Array.array (0,n-1) [ (i, genVector i) | i <- [0..n-1] ]
10 chunks per Capability
let chunk = n `quot` (numCapabilities * 10)
fs <- forM [1, 1+chunk .. n] $ \t -> do
let t1 = min (t + chunk - 1) n
fork (return (Seq.withStrategy (Seq.seqList Seq.rseq) $
map (compute initVecs) [t .. t1]))
ls <- mapM join fs
return (concat ls)
main =
do args <- getArgs
let accList = case args of
[] -> run (3::Int)
[s] -> run (read s)
--putStrLn $ show accList;
-- Do a meaningless sum to generate a small output:
putStrLn $ show ( foldl ( \sum ( _ , ( x , y , z ) ) - > sum + x+y+z ) 0 accList )
putStrLn $ show (foldl (\sum (x,y,z) -> if x>0 then sum+1 else sum) 0 accList)
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/parallel/nbody/nbody.hs | haskell | This step generates the bodies in the system.
Only doing the O(N^2) part in parallel:
This step computes the accelerations of the bodies.
Making this much leCss haskell like to avoid allocation:
Manually inlining to see if the tuples unbox:
The same tag collection prescribes the two step collections .
run :: Int -> (b, c)
run :: Int -> ([(Int, (Float, Float, Float))], [(Int, (Float, Float, Float))])
putStrLn $ show accList;
Do a meaningless sum to generate a small output: |
- Intel Concurrent Collections for ( c ) 2010 , Intel Corporation .
-
- This program is free software ; you can redistribute it and/or modify it
- under the terms and conditions of the GNU Lesser General Public License ,
- version 2.1 , as published by the Free Software Foundation .
-
- This program is distributed in the hope it will be useful , but WITHOUT
- ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
- FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public License for
- more details .
-
- You should have received a copy of the GNU Lesser General Public License along with
- this program ; if not , write to the Free Software Foundation , Inc. ,
- 51 Franklin St - Fifth Floor , Boston , USA .
-
- Intel Concurrent Collections for Haskell
- Copyright (c) 2010, Intel Corporation.
-
- This program is free software; you can redistribute it and/or modify it
- under the terms and conditions of the GNU Lesser General Public License,
- version 2.1, as published by the Free Software Foundation.
-
- This program is distributed in the hope it will be useful, but WITHOUT
- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
- more details.
-
- You should have received a copy of the GNU Lesser General Public License along with
- this program; if not, write to the Free Software Foundation, Inc.,
- 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
-
-}
# LANGUAGE CPP , MagicHash , UnboxedTuples , BangPatterns #
Author :
This program uses CnC to calculate the accelerations of the bodies in a 3D system .
import System.Environment
import Data.Int
import Control.Monad hiding (join)
import GHC.Exts
import GHC.Conc (numCapabilities)
import Control.Seq as Seq
import qualified Data.List as List
import qualified Data.Array as Array
import Future
type Float3D = (Float, Float, Float)
type UFloat3D = (# Float#, Float#, Float# #)
genVector tag = (tag' * 1.0, tag' * 0.2, tag' * 30.0)
where tag' = fromIntegral tag
compute vecList tag =
let myvector = vecList Array.! (tag-1) in
accel myvector vecList
vecList = elems vecArr
g = 9.8
: : Float # - > UFloat3D - > UFloat3D
( # x , y , z # ) = ( # c*x , c*y , c*z # )
multTriple :: Float -> Float3D -> Float3D
multTriple c ( x,y,z ) = ( c*x,c*y,c*z )
# define OLD_VER
#ifdef OLD_VER
pairWiseAccel :: Float3D -> Float3D -> Float3D
pairWiseAccel (x,y,z) (x',y',z') = let dx = x'-x
dy = y'-y
dz = z'-z
eps = 0.005
distanceSq = dx^2 + dy^2 + dz^2 + eps
factor = 1/sqrt(distanceSq ^ 3)
in multTriple factor ( dx , dy , dz )
in multTriple factor (dx,dy,dz)
sumTriples = foldr (\(x,y,z) (x',y',z') -> (x+x',y+y',z+z')) (0,0,0)
accel vector vecList = multTriple g $ sumTriples $ List.map (pairWiseAccel vector) vecList
#else
(strt,end) = Array.bounds vecList
accel :: Float3D -> (Array.Array Int Float3D) -> Float3D
accel vector vecList =
let (# sx,sy,sz #) = loop strt 0 0 0
loop !i !ax !ay !az
| i == end = (# ax,ay,az #)
| otherwise =
let ( x,y,z ) = vector
( x',y',z' ) = vecList Array.! i
(# dx,dy,dz #) = (# x'-x, y'-y, z'-z #)
eps = 0.005
#if 1
distanceSq = dx^2 + dy^2 + dz^2 + eps
factor = 1/sqrt(distanceSq ^ 3)
#else
distanceSq = dx*dx + dy*dy + dz*dz + eps
factor = 1/sqrt(distanceSq * distanceSq * distanceSq)
#endif
(# px,py,pz #) = (# factor * dx, factor * dy, factor *dz #)
in loop (i+1) (ax+px) (ay+py) (az+pz)
in ( g*sx, g*sy, g*sz )
#endif
run : : Int - > ( [ Float3D ] , [ Float3D ] )
run :: Int -> [Float3D]
run n = runEval $ do
let initVecs = Array.array (0,n-1) [ (i, genVector i) | i <- [0..n-1] ]
10 chunks per Capability
let chunk = n `quot` (numCapabilities * 10)
fs <- forM [1, 1+chunk .. n] $ \t -> do
let t1 = min (t + chunk - 1) n
fork (return (Seq.withStrategy (Seq.seqList Seq.rseq) $
map (compute initVecs) [t .. t1]))
ls <- mapM join fs
return (concat ls)
main =
do args <- getArgs
let accList = case args of
[] -> run (3::Int)
[s] -> run (read s)
putStrLn $ show ( foldl ( \sum ( _ , ( x , y , z ) ) - > sum + x+y+z ) 0 accList )
putStrLn $ show (foldl (\sum (x,y,z) -> if x>0 then sum+1 else sum) 0 accList)
|
13b5bea705ad47a46437dfb488b2ad060f2571e76ce7b9326610c9fb5de184e0 | Bodigrim/arithmoi | Primes.hs | -- |
Module : Math . . Primes
Copyright : ( c ) 2016 - 2018 Andrew . Lelechenko
Licence : MIT
Maintainer : < >
--
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# OPTIONS_GHC -fno - warn - orphans #
module Math.NumberTheory.Primes
( Prime
, unPrime
, toPrimeIntegral
, nextPrime
, precPrime
, UniqueFactorisation(..)
, factorBack
, -- * Old interface
primes
) where
import Data.Bits
import Data.Coerce
import Data.Maybe
import Data.Word
import Numeric.Natural
import Math.NumberTheory.Primes.Counting (nthPrime, primeCount)
import qualified Math.NumberTheory.Primes.Factorisation.Montgomery as F (factorise)
import qualified Math.NumberTheory.Primes.Testing.Probabilistic as T (isPrime)
import Math.NumberTheory.Primes.Sieve.Eratosthenes (primes, sieveRange, primeList, psieveFrom, primeSieve)
import Math.NumberTheory.Primes.Small
import Math.NumberTheory.Primes.Types
import Math.NumberTheory.Utils (toWheel30, fromWheel30)
import Math.NumberTheory.Utils.FromIntegral
-- | A class for unique factorisation domains.
class Num a => UniqueFactorisation a where
| Factorise a number into a product of prime powers .
Factorisation of 0 is an undefined behaviour . Otherwise
-- following invariants hold:
--
> abs n = = abs ( product ( map ( \(p , k ) - > unPrime p ^ k ) ( factorise n ) ) )
> all ( ( > 0 ) . snd ) ( factorise n )
--
> > > factorise ( 1 : : Integer )
-- []
> > > factorise ( -1 : : Integer )
-- []
> > > factorise ( 6 : : Integer )
[ ( Prime 2,1),(Prime 3,1 ) ]
> > > factorise ( -108 : : Integer )
[ ( Prime 2,2),(Prime 3,3 ) ]
--
-- This function is a replacement
for ' Math.NumberTheory.Primes.Factorisation.factorise ' .
-- If you were looking for the latter, please import
" Math . . Primes . Factorisation " instead of this module .
--
-- __Warning:__ there are no guarantees of any particular
order of prime factors , do not expect them to be ascending . ,
--
> > > factorise 10251562501
-- [(Prime 101701,1),(Prime 100801,1)]
factorise :: a -> [(Prime a, Word)]
-- | Check whether an argument is prime.
-- If it is then return an associated prime.
--
> > > isPrime ( 3 : : Integer )
Just ( Prime 3 )
> > > isPrime ( 4 : : Integer )
-- Nothing
-- >>> isPrime (-5 :: Integer)
Just ( Prime 5 )
--
-- This function is a replacement
for ' Math . . Primes . Testing.isPrime ' .
-- If you were looking for the latter, please import
" Math . . Primes . Testing " instead of this module .
isPrime :: a -> Maybe (Prime a)
instance UniqueFactorisation Int where
factorise = coerce . F.factorise
isPrime n = if T.isPrime (toInteger n) then Just (Prime $ abs n) else Nothing
instance UniqueFactorisation Word where
factorise = coerce . F.factorise
isPrime n = if T.isPrime (toInteger n) then Just (Prime n) else Nothing
instance UniqueFactorisation Integer where
factorise = coerce . F.factorise
isPrime n = if T.isPrime n then Just (Prime $ abs n) else Nothing
instance UniqueFactorisation Natural where
factorise = coerce . F.factorise
isPrime n = if T.isPrime (toInteger n) then Just (Prime n) else Nothing
-- | Restore a number from its factorisation.
factorBack :: Num a => [(Prime a, Word)] -> a
factorBack = product . map (\(p, k) -> unPrime p ^ k)
-- | Smallest prime, greater or equal to argument.
--
> nextPrime ( -100 ) = = 2
> nextPrime 1000 = = 1009
> nextPrime 1009 = = 1009
nextPrime :: (Bits a, Integral a, UniqueFactorisation a) => a -> Prime a
nextPrime n
| n <= 2 = Prime 2
| n <= 3 = Prime 3
| n <= 5 = Prime 5
| otherwise = head $ mapMaybe isPrime $
dropWhile (< n) $ map fromWheel30 [toWheel30 n ..]
-- dropWhile is important, because fromWheel30 (toWheel30 n) may appear to be < n.
, fromWheel30 ( toWheel30 94 ) = = 97
| Largest prime , less or equal to argument . Undefined , when argument < 2 .
--
> 100 = = 97
> 97 = = 97
precPrime :: (Bits a, Integral a, UniqueFactorisation a) => a -> Prime a
precPrime n
| n < 2 = error "precPrime: tried to take `precPrime` of an argument less than 2"
| n < 3 = Prime 2
| n < 5 = Prime 3
| n < 7 = Prime 5
| otherwise = head $ mapMaybe isPrime $
dropWhile (> n) $ map fromWheel30 [toWheel30 n, toWheel30 n - 1 ..]
-- dropWhile is important, because fromWheel30 (toWheel30 n) may appear to be > n.
, fromWheel30 ( toWheel30 100 ) = = 101
-------------------------------------------------------------------------------
-- Prime sequences
data Algorithm = IsPrime | Sieve
chooseAlgorithm :: Integral a => a -> a -> Algorithm
chooseAlgorithm from to
| to <= fromIntegral sieveRange
&& to < from + truncate (sqrt (fromIntegral from) :: Double)
= IsPrime
| to > fromIntegral sieveRange
&& to < from + truncate (0.036 * sqrt (fromIntegral from) + 40000 :: Double)
= IsPrime
| otherwise
= Sieve
succGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a
succGeneric = \case
Prime 2 -> Prime 3
Prime 3 -> Prime 5
Prime 5 -> Prime 7
Prime p -> head $ mapMaybe (isPrime . fromWheel30) [toWheel30 p + 1 ..]
succGenericBounded
:: (Bits a, Integral a, UniqueFactorisation a, Bounded a)
=> Prime a
-> Prime a
succGenericBounded = \case
Prime 2 -> Prime 3
Prime 3 -> Prime 5
Prime 5 -> Prime 7
Prime p -> case mapMaybe (isPrime . fromWheel30) [toWheel30 p + 1 .. toWheel30 maxBound] of
[] -> error "Enum.succ{Prime}: tried to take `succ' near `maxBound'"
q : _ -> q
predGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a
predGeneric = \case
Prime 2 -> error "Enum.pred{Prime}: tried to take `pred' of 2"
Prime 3 -> Prime 2
Prime 5 -> Prime 3
Prime 7 -> Prime 5
Prime p -> head $ mapMaybe (isPrime . fromWheel30) [toWheel30 p - 1, toWheel30 p - 2 ..]
-- 'dropWhile' is important, because 'psieveFrom' can actually contain primes less than p.
enumFromGeneric :: Integral a => Prime a -> [Prime a]
enumFromGeneric p@(Prime p')
= coerce
$ dropWhile (< p)
$ concat
$ takeWhile (not . null)
$ map primeList
$ psieveFrom
$ toInteger p'
smallPrimesLimit :: Integral a => a
smallPrimesLimit = fromIntegral (maxBound :: Word16)
enumFromToGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a -> [Prime a]
enumFromToGeneric p@(Prime p') q@(Prime q')
| p' <= smallPrimesLimit, q' <= smallPrimesLimit
= map (Prime . fromIntegral) $ smallPrimesFromTo (fromIntegral p') (fromIntegral q')
| p' <= smallPrimesLimit
= map (Prime . fromIntegral) (smallPrimesFromTo (fromIntegral p') smallPrimesLimit)
++ enumFromToGeneric' (nextPrime smallPrimesLimit) q
| otherwise
= enumFromToGeneric' p q
enumFromToGeneric'
:: (Bits a, Integral a, UniqueFactorisation a)
=> Prime a
-> Prime a
-> [Prime a]
enumFromToGeneric' p@(Prime p') q@(Prime q') = takeWhile (<= q) $ dropWhile (< p) $
case chooseAlgorithm p' q' of
IsPrime -> Prime 2 : Prime 3 : Prime 5 : mapMaybe (isPrime . fromWheel30) [toWheel30 p' .. toWheel30 q']
Sieve ->
if q' < fromIntegral sieveRange
then primeList $ primeSieve $ toInteger q'
else concatMap primeList $ psieveFrom $ toInteger p'
enumFromThenGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a -> [Prime a]
enumFromThenGeneric p@(Prime p') (Prime q') = case p' `compare` q' of
LT -> filter (\(Prime r') -> (r' - p') `rem` delta == 0) $ enumFromGeneric p
where
delta = q' - p'
EQ -> repeat p
GT -> filter (\(Prime r') -> (p' - r') `rem` delta == 0) $ reverse $ enumFromToGeneric (Prime 2) p
where
delta = p' - q'
enumFromThenToGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a -> Prime a -> [Prime a]
enumFromThenToGeneric p@(Prime p') (Prime q') r@(Prime r') = case p' `compare` q' of
LT -> filter (\(Prime t') -> (t' - p') `rem` delta == 0) $ enumFromToGeneric p r
where
delta = q' - p'
EQ -> if p' <= r' then repeat p else []
GT -> filter (\(Prime t') -> (p' - t') `rem` delta == 0) $ reverse $ enumFromToGeneric r p
where
delta = p' - q'
instance Enum (Prime Integer) where
toEnum = nthPrime
fromEnum = integerToInt . primeCount . unPrime
succ = succGeneric
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Enum (Prime Natural) where
toEnum = Prime . integerToNatural . unPrime . nthPrime
fromEnum = integerToInt . primeCount . naturalToInteger . unPrime
succ = succGeneric
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Enum (Prime Int) where
toEnum n = if p > intToInteger maxBound
then error $ "Enum.toEnum{Prime}: " ++ show n ++ "th prime = " ++ show p ++ " is out of bounds of Int"
else Prime (integerToInt p)
where
Prime p = nthPrime n
fromEnum = integerToInt . primeCount . intToInteger . unPrime
succ = succGenericBounded
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Bounded (Prime Int) where
minBound = Prime 2
maxBound = precPrime maxBound
instance Enum (Prime Word) where
toEnum n = if p > wordToInteger maxBound
then error $ "Enum.toEnum{Prime}: " ++ show n ++ "th prime = " ++ show p ++ " is out of bounds of Word"
else Prime (integerToWord p)
where
Prime p = nthPrime n
fromEnum = integerToInt . primeCount . wordToInteger . unPrime
succ = succGenericBounded
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Bounded (Prime Word) where
minBound = Prime 2
maxBound = precPrime maxBound
| null | https://raw.githubusercontent.com/Bodigrim/arithmoi/df789d23341247e9cdb4f690595ea99c89836d09/Math/NumberTheory/Primes.hs | haskell | |
* Old interface
| A class for unique factorisation domains.
following invariants hold:
[]
[]
This function is a replacement
If you were looking for the latter, please import
__Warning:__ there are no guarantees of any particular
[(Prime 101701,1),(Prime 100801,1)]
| Check whether an argument is prime.
If it is then return an associated prime.
Nothing
>>> isPrime (-5 :: Integer)
This function is a replacement
If you were looking for the latter, please import
| Restore a number from its factorisation.
| Smallest prime, greater or equal to argument.
dropWhile is important, because fromWheel30 (toWheel30 n) may appear to be < n.
dropWhile is important, because fromWheel30 (toWheel30 n) may appear to be > n.
-----------------------------------------------------------------------------
Prime sequences
'dropWhile' is important, because 'psieveFrom' can actually contain primes less than p. | Module : Math . . Primes
Copyright : ( c ) 2016 - 2018 Andrew . Lelechenko
Licence : MIT
Maintainer : < >
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# OPTIONS_GHC -fno - warn - orphans #
module Math.NumberTheory.Primes
( Prime
, unPrime
, toPrimeIntegral
, nextPrime
, precPrime
, UniqueFactorisation(..)
, factorBack
primes
) where
import Data.Bits
import Data.Coerce
import Data.Maybe
import Data.Word
import Numeric.Natural
import Math.NumberTheory.Primes.Counting (nthPrime, primeCount)
import qualified Math.NumberTheory.Primes.Factorisation.Montgomery as F (factorise)
import qualified Math.NumberTheory.Primes.Testing.Probabilistic as T (isPrime)
import Math.NumberTheory.Primes.Sieve.Eratosthenes (primes, sieveRange, primeList, psieveFrom, primeSieve)
import Math.NumberTheory.Primes.Small
import Math.NumberTheory.Primes.Types
import Math.NumberTheory.Utils (toWheel30, fromWheel30)
import Math.NumberTheory.Utils.FromIntegral
class Num a => UniqueFactorisation a where
| Factorise a number into a product of prime powers .
Factorisation of 0 is an undefined behaviour . Otherwise
> abs n = = abs ( product ( map ( \(p , k ) - > unPrime p ^ k ) ( factorise n ) ) )
> all ( ( > 0 ) . snd ) ( factorise n )
> > > factorise ( 1 : : Integer )
> > > factorise ( -1 : : Integer )
> > > factorise ( 6 : : Integer )
[ ( Prime 2,1),(Prime 3,1 ) ]
> > > factorise ( -108 : : Integer )
[ ( Prime 2,2),(Prime 3,3 ) ]
for ' Math.NumberTheory.Primes.Factorisation.factorise ' .
" Math . . Primes . Factorisation " instead of this module .
order of prime factors , do not expect them to be ascending . ,
> > > factorise 10251562501
factorise :: a -> [(Prime a, Word)]
> > > isPrime ( 3 : : Integer )
Just ( Prime 3 )
> > > isPrime ( 4 : : Integer )
Just ( Prime 5 )
for ' Math . . Primes . Testing.isPrime ' .
" Math . . Primes . Testing " instead of this module .
isPrime :: a -> Maybe (Prime a)
instance UniqueFactorisation Int where
factorise = coerce . F.factorise
isPrime n = if T.isPrime (toInteger n) then Just (Prime $ abs n) else Nothing
instance UniqueFactorisation Word where
factorise = coerce . F.factorise
isPrime n = if T.isPrime (toInteger n) then Just (Prime n) else Nothing
instance UniqueFactorisation Integer where
factorise = coerce . F.factorise
isPrime n = if T.isPrime n then Just (Prime $ abs n) else Nothing
instance UniqueFactorisation Natural where
factorise = coerce . F.factorise
isPrime n = if T.isPrime (toInteger n) then Just (Prime n) else Nothing
factorBack :: Num a => [(Prime a, Word)] -> a
factorBack = product . map (\(p, k) -> unPrime p ^ k)
> nextPrime ( -100 ) = = 2
> nextPrime 1000 = = 1009
> nextPrime 1009 = = 1009
nextPrime :: (Bits a, Integral a, UniqueFactorisation a) => a -> Prime a
nextPrime n
| n <= 2 = Prime 2
| n <= 3 = Prime 3
| n <= 5 = Prime 5
| otherwise = head $ mapMaybe isPrime $
dropWhile (< n) $ map fromWheel30 [toWheel30 n ..]
, fromWheel30 ( toWheel30 94 ) = = 97
| Largest prime , less or equal to argument . Undefined , when argument < 2 .
> 100 = = 97
> 97 = = 97
precPrime :: (Bits a, Integral a, UniqueFactorisation a) => a -> Prime a
precPrime n
| n < 2 = error "precPrime: tried to take `precPrime` of an argument less than 2"
| n < 3 = Prime 2
| n < 5 = Prime 3
| n < 7 = Prime 5
| otherwise = head $ mapMaybe isPrime $
dropWhile (> n) $ map fromWheel30 [toWheel30 n, toWheel30 n - 1 ..]
, fromWheel30 ( toWheel30 100 ) = = 101
data Algorithm = IsPrime | Sieve
chooseAlgorithm :: Integral a => a -> a -> Algorithm
chooseAlgorithm from to
| to <= fromIntegral sieveRange
&& to < from + truncate (sqrt (fromIntegral from) :: Double)
= IsPrime
| to > fromIntegral sieveRange
&& to < from + truncate (0.036 * sqrt (fromIntegral from) + 40000 :: Double)
= IsPrime
| otherwise
= Sieve
succGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a
succGeneric = \case
Prime 2 -> Prime 3
Prime 3 -> Prime 5
Prime 5 -> Prime 7
Prime p -> head $ mapMaybe (isPrime . fromWheel30) [toWheel30 p + 1 ..]
succGenericBounded
:: (Bits a, Integral a, UniqueFactorisation a, Bounded a)
=> Prime a
-> Prime a
succGenericBounded = \case
Prime 2 -> Prime 3
Prime 3 -> Prime 5
Prime 5 -> Prime 7
Prime p -> case mapMaybe (isPrime . fromWheel30) [toWheel30 p + 1 .. toWheel30 maxBound] of
[] -> error "Enum.succ{Prime}: tried to take `succ' near `maxBound'"
q : _ -> q
predGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a
predGeneric = \case
Prime 2 -> error "Enum.pred{Prime}: tried to take `pred' of 2"
Prime 3 -> Prime 2
Prime 5 -> Prime 3
Prime 7 -> Prime 5
Prime p -> head $ mapMaybe (isPrime . fromWheel30) [toWheel30 p - 1, toWheel30 p - 2 ..]
enumFromGeneric :: Integral a => Prime a -> [Prime a]
enumFromGeneric p@(Prime p')
= coerce
$ dropWhile (< p)
$ concat
$ takeWhile (not . null)
$ map primeList
$ psieveFrom
$ toInteger p'
smallPrimesLimit :: Integral a => a
smallPrimesLimit = fromIntegral (maxBound :: Word16)
enumFromToGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a -> [Prime a]
enumFromToGeneric p@(Prime p') q@(Prime q')
| p' <= smallPrimesLimit, q' <= smallPrimesLimit
= map (Prime . fromIntegral) $ smallPrimesFromTo (fromIntegral p') (fromIntegral q')
| p' <= smallPrimesLimit
= map (Prime . fromIntegral) (smallPrimesFromTo (fromIntegral p') smallPrimesLimit)
++ enumFromToGeneric' (nextPrime smallPrimesLimit) q
| otherwise
= enumFromToGeneric' p q
enumFromToGeneric'
:: (Bits a, Integral a, UniqueFactorisation a)
=> Prime a
-> Prime a
-> [Prime a]
enumFromToGeneric' p@(Prime p') q@(Prime q') = takeWhile (<= q) $ dropWhile (< p) $
case chooseAlgorithm p' q' of
IsPrime -> Prime 2 : Prime 3 : Prime 5 : mapMaybe (isPrime . fromWheel30) [toWheel30 p' .. toWheel30 q']
Sieve ->
if q' < fromIntegral sieveRange
then primeList $ primeSieve $ toInteger q'
else concatMap primeList $ psieveFrom $ toInteger p'
enumFromThenGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a -> [Prime a]
enumFromThenGeneric p@(Prime p') (Prime q') = case p' `compare` q' of
LT -> filter (\(Prime r') -> (r' - p') `rem` delta == 0) $ enumFromGeneric p
where
delta = q' - p'
EQ -> repeat p
GT -> filter (\(Prime r') -> (p' - r') `rem` delta == 0) $ reverse $ enumFromToGeneric (Prime 2) p
where
delta = p' - q'
enumFromThenToGeneric :: (Bits a, Integral a, UniqueFactorisation a) => Prime a -> Prime a -> Prime a -> [Prime a]
enumFromThenToGeneric p@(Prime p') (Prime q') r@(Prime r') = case p' `compare` q' of
LT -> filter (\(Prime t') -> (t' - p') `rem` delta == 0) $ enumFromToGeneric p r
where
delta = q' - p'
EQ -> if p' <= r' then repeat p else []
GT -> filter (\(Prime t') -> (p' - t') `rem` delta == 0) $ reverse $ enumFromToGeneric r p
where
delta = p' - q'
instance Enum (Prime Integer) where
toEnum = nthPrime
fromEnum = integerToInt . primeCount . unPrime
succ = succGeneric
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Enum (Prime Natural) where
toEnum = Prime . integerToNatural . unPrime . nthPrime
fromEnum = integerToInt . primeCount . naturalToInteger . unPrime
succ = succGeneric
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Enum (Prime Int) where
toEnum n = if p > intToInteger maxBound
then error $ "Enum.toEnum{Prime}: " ++ show n ++ "th prime = " ++ show p ++ " is out of bounds of Int"
else Prime (integerToInt p)
where
Prime p = nthPrime n
fromEnum = integerToInt . primeCount . intToInteger . unPrime
succ = succGenericBounded
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Bounded (Prime Int) where
minBound = Prime 2
maxBound = precPrime maxBound
instance Enum (Prime Word) where
toEnum n = if p > wordToInteger maxBound
then error $ "Enum.toEnum{Prime}: " ++ show n ++ "th prime = " ++ show p ++ " is out of bounds of Word"
else Prime (integerToWord p)
where
Prime p = nthPrime n
fromEnum = integerToInt . primeCount . wordToInteger . unPrime
succ = succGenericBounded
pred = predGeneric
enumFrom = enumFromGeneric
enumFromTo = enumFromToGeneric
enumFromThen = enumFromThenGeneric
enumFromThenTo = enumFromThenToGeneric
instance Bounded (Prime Word) where
minBound = Prime 2
maxBound = precPrime maxBound
|
47478e997f6c62486c64c42c4ee5f259306112b0a04b31cbff7318ab08163386 | modular-macros/ocaml-macros | pr6899_first_bad.ml | let should_reject =
let table = Hashtbl.create 1 in
fun x y -> Hashtbl.add table x y
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/typing-modules-bugs/pr6899_first_bad.ml | ocaml | let should_reject =
let table = Hashtbl.create 1 in
fun x y -> Hashtbl.add table x y
| |
3e6dd4809b48a209bfe35481b5680b89c0d611fe7db3dd72a096a1521738e858 | freizl/dive-into-haskell | nimgame.hs | module Main where
import Control.Monad
type Board = [Int]
main :: IO ()
main = do showBoard (reverse [1..5])
showBoard :: Board -> IO ()
showBoard b = forM_ (map wrapRow b) (\x -> putStrLn x)
wrapRow :: Int -> String
wrapRow n = [ '*' | x <- [1..n] ]
| null | https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/codes/sandbox/nimgame.hs | haskell | module Main where
import Control.Monad
type Board = [Int]
main :: IO ()
main = do showBoard (reverse [1..5])
showBoard :: Board -> IO ()
showBoard b = forM_ (map wrapRow b) (\x -> putStrLn x)
wrapRow :: Int -> String
wrapRow n = [ '*' | x <- [1..n] ]
| |
65604f8a503281f20f16813262ce86077a2d7acf4c71a17cd6792c92b3eb81a2 | falsetru/htdp | 37.1.5.scm | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-advanced-reader.ss" "lang")((modname 37.1.5) (read-case-sensitive #t) (teachpacks ((lib "gui.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "gui.ss" "teachpack" "htdp")))))
(define COLORS
'(black white red blue green gold pink orange purple navy))
(define COL# (length COLORS))
(define target1 (first COLORS))
(define target2 (first COLORS))
(define guess1 (first COLORS))
(define guess2 (first COLORS))
(define guess-count 0)
(define (random-pick xs)
(list-ref xs (random (length xs))))
(define (master)
(begin (set! target1 (random-pick COLORS))
(set! target2 (random-pick COLORS))
(set! guess-count 0)))
(define (check-color guess1 guess2 target1 target2)
(cond [(and (symbol=? guess1 target1) (symbol=? guess2 target2)) 'Perfect!]
[(or (symbol=? guess1 target1) (symbol=? guess2 target2)) 'OneColorAtCorrectPosition]
[(or (symbol=? guess1 target2) (symbol=? guess2 target1)) 'OneColorOccurs]
[else 'NothingCorrect]))
(define (master-check)
(local ((define result (check-color guess1 guess2 target1 target2)))
(begin
(if (symbol=? result 'Perfect)
(master)
(void))
result))
)
(define color-buttons
(map (lambda (c)
(make-button
(symbol->string c)
(lambda (e)
(begin
(set! guess-count (add1 guess-count))
(if (= (remainder guess-count 2) 1)
(begin
(set! guess1 c)
(draw-message (first choice-texts) (symbol->string c))
(draw-message result "Select another color"))
(begin
(set! guess2 c)
(draw-message (second choice-texts) (symbol->string c))
(draw-message result (symbol->string (master-check)))
))
true))))
COLORS))
(define choice-texts
(list (make-message "UNSELECTED")
(make-message "UNSELECTED")))
(define result (make-message ""))
(create-window
(list color-buttons
choice-texts
(list result))) | null | https://raw.githubusercontent.com/falsetru/htdp/4cdad3b999f19b89ff4fa7561839cbcbaad274df/37/37.1.5.scm | scheme | about the language level of this file in a form that our tools can easily process. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-advanced-reader.ss" "lang")((modname 37.1.5) (read-case-sensitive #t) (teachpacks ((lib "gui.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #t #t none #f ((lib "gui.ss" "teachpack" "htdp")))))
(define COLORS
'(black white red blue green gold pink orange purple navy))
(define COL# (length COLORS))
(define target1 (first COLORS))
(define target2 (first COLORS))
(define guess1 (first COLORS))
(define guess2 (first COLORS))
(define guess-count 0)
(define (random-pick xs)
(list-ref xs (random (length xs))))
(define (master)
(begin (set! target1 (random-pick COLORS))
(set! target2 (random-pick COLORS))
(set! guess-count 0)))
(define (check-color guess1 guess2 target1 target2)
(cond [(and (symbol=? guess1 target1) (symbol=? guess2 target2)) 'Perfect!]
[(or (symbol=? guess1 target1) (symbol=? guess2 target2)) 'OneColorAtCorrectPosition]
[(or (symbol=? guess1 target2) (symbol=? guess2 target1)) 'OneColorOccurs]
[else 'NothingCorrect]))
(define (master-check)
(local ((define result (check-color guess1 guess2 target1 target2)))
(begin
(if (symbol=? result 'Perfect)
(master)
(void))
result))
)
(define color-buttons
(map (lambda (c)
(make-button
(symbol->string c)
(lambda (e)
(begin
(set! guess-count (add1 guess-count))
(if (= (remainder guess-count 2) 1)
(begin
(set! guess1 c)
(draw-message (first choice-texts) (symbol->string c))
(draw-message result "Select another color"))
(begin
(set! guess2 c)
(draw-message (second choice-texts) (symbol->string c))
(draw-message result (symbol->string (master-check)))
))
true))))
COLORS))
(define choice-texts
(list (make-message "UNSELECTED")
(make-message "UNSELECTED")))
(define result (make-message ""))
(create-window
(list color-buttons
choice-texts
(list result))) |
331267f4a08c571793191ef0cfe9b0b1cb8c56c2ffd0c6dba491f4ab5193353b | Ptival/chick | Instantiable.hs | # LANGUAGE FlexibleInstances #
module Instantiable where
import Control.Monad.Reader.Class (MonadReader)
import Control.Monad.State.Class (MonadState)
import Inductive.Inductive (Constructor (..))
import qualified Term.TypeChecked as C
import Term.Variable (Variable)
import Typing.GlobalEnvironment (GlobalEnvironment)
import Typing.LocalContext (LocalContext)
class Instantiable t where
instantiate ::
( MonadReader (GlobalEnvironment ξ (C.Checked Variable)) m,
MonadState (LocalContext ξ (C.Checked Variable)) m
) =>
t ->
m (C.Term Variable)
instance Instantiable (C.Term Variable) where
instantiate t = return t
instance Instantiable (Constructor α (C.Checked Variable)) where
instantiate Constructor {..} = _
| null | https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/lib/Instantiable.hs | haskell | # LANGUAGE FlexibleInstances #
module Instantiable where
import Control.Monad.Reader.Class (MonadReader)
import Control.Monad.State.Class (MonadState)
import Inductive.Inductive (Constructor (..))
import qualified Term.TypeChecked as C
import Term.Variable (Variable)
import Typing.GlobalEnvironment (GlobalEnvironment)
import Typing.LocalContext (LocalContext)
class Instantiable t where
instantiate ::
( MonadReader (GlobalEnvironment ξ (C.Checked Variable)) m,
MonadState (LocalContext ξ (C.Checked Variable)) m
) =>
t ->
m (C.Term Variable)
instance Instantiable (C.Term Variable) where
instantiate t = return t
instance Instantiable (Constructor α (C.Checked Variable)) where
instantiate Constructor {..} = _
| |
0ba48b40ee4ed19ba5988593506b25128c463356facfd80195dda725c8df7551 | ocaml/opam | opamPath.ml | (**************************************************************************)
(* *)
Copyright 2012 - 2020 OCamlPro
Copyright 2012 INRIA
(* *)
(* 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. *)
(* *)
(**************************************************************************)
open OpamTypes
open OpamFilename.Op
type t = dirname
(* Returns a generic file, coerced by the .mli *)
let ( /- ) dir f = OpamFile.make (dir // f)
let config t = t /- "config"
let init_config_files () =
List.map OpamFile.make [
OpamFilename.Dir.of_string (OpamStd.Sys.etc ()) // "opamrc";
OpamFilename.Dir.of_string (OpamStd.Sys.home ()) // ".opamrc";
]
let state_cache_dir t = t / "repo"
let state_cache t = state_cache_dir t // Printf.sprintf "state-%s.cache" (OpamVersion.magic ())
let lock t = t // "lock"
let config_lock t = t // "config.lock"
(*
let archives_dir t = t / "archives"
let archive t nv = archives_dir t // (OpamPackage.to_string nv ^ "+opam.tar.gz")
*)
let repos_lock t = t / "repo" // "lock"
let repos_config t = t / "repo" /- "repos-config"
let init t = t / "opam-init"
let hooks_dir t = init t / "hooks"
let log t = t / "log"
let backup_file =
let file = lazy Unix.(
let tm = gmtime (Unix.gettimeofday ()) in
Printf.sprintf "state-%04d%02d%02d%02d%02d%02d.export"
(tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec
) in
fun () -> Lazy.force file
let backup_dir t = t / "backup"
let backup t = backup_dir t /- backup_file ()
let plugin_prefix = "opam-"
let plugins t = t / "plugins"
let plugins_bin t = plugins t / "bin"
let plugin_bin t name =
let sname = OpamPackage.Name.to_string name ^ OpamStd.Sys.executable_name "" in
let basename =
if OpamStd.String.starts_with ~prefix:plugin_prefix sname then sname
else plugin_prefix ^ sname
in
plugins_bin t // basename
let plugin t name =
let sname = OpamPackage.Name.to_string name in
assert (sname <> "bin");
plugins t / sname
module type LAYOUT = sig
type ctx
val root : dirname -> ctx -> dirname
val lib_dir : dirname -> ctx -> dirname
end
module Switch = struct
let root t a = OpamSwitch.get_root t a
* Internal files and dirs with static location
let meta_dirname = ".opam-switch"
let meta t a = root t a / meta_dirname
let lock t a = meta t a // "lock"
let backup_dir t a = meta t a / "backup"
let backup t a = backup_dir t a /- backup_file ()
let selections t a = meta t a /- "switch-state"
let build_dir t a = meta t a / "build"
let build t a nv = build_dir t a / OpamPackage.to_string nv
let remove_dir t a = meta t a / "remove"
let remove t a nv = remove_dir t a / OpamPackage.to_string nv
let install_dir t a = meta t a / "install"
let install t a n = install_dir t a /- (OpamPackage.Name.to_string n ^ ".install")
let changes t a n = install_dir t a /- (OpamPackage.Name.to_string n ^ ".changes")
let reinstall t a = meta t a /- "reinstall"
let switch_config t a = meta t a /- "switch-config"
let config_dir t a = meta t a / "config"
let config t a n =
config_dir t a /- (OpamPackage.Name.to_string n ^ ".config")
let sources_dir t a = meta t a / "sources"
let extra_files_dir t a = meta t a / "extra-files-cache"
let extra_file t a h = extra_files_dir t a // OpamHash.contents h
let sources t a nv = sources_dir t a / OpamPackage.to_string nv
let pinned_package t a name = sources_dir t a / OpamPackage.Name.to_string name
let env_filename = "environment"
let environment t a = meta t a /- env_filename
let env_relative_to_prefix pfx = pfx / meta_dirname /- env_filename
let installed_opams t a = meta t a / "packages"
let installed_opams_cache t a = meta t a / "packages" // "cache"
let installed_package_dir t a nv =
installed_opams t a / OpamPackage.to_string nv
let installed_opam t a nv =
installed_package_dir t a nv /- "opam"
let installed_opam_files_dir t a nv =
installed_package_dir t a nv / "files"
let mans = ["1";"1M";"2";"3";"4";"5";"6";"7";"9"]
module DefaultF(L:LAYOUT) = struct
let lib_dir = L.lib_dir
let lib t a n = L.lib_dir t a / OpamPackage.Name.to_string n
let stublibs t a = L.lib_dir t a / "stublibs"
let toplevel t a = L.lib_dir t a / "toplevel"
let doc_dir t a = L.root t a / "doc"
let man_dir ?num t a =
match num with
| None -> L.root t a / "man"
| Some n -> L.root t a / "man" / ("man" ^ n)
let man_dirs t a = List.map (fun num -> man_dir ~num t a) mans
let share_dir t a = L.root t a / "share"
let share t a n = share_dir t a / OpamPackage.Name.to_string n
let etc_dir t a = L.root t a / "etc"
let etc t a n = etc_dir t a / OpamPackage.Name.to_string n
let doc t a n = doc_dir t a / OpamPackage.Name.to_string n
let bin t a = L.root t a / "bin"
let sbin t a = L.root t a / "sbin"
end
(** Visible files that can be redirected using
[config/global-config.config] *)
module Default = struct
include DefaultF(struct
type ctx = switch
let root = root
let lib_dir t a = root t a / "lib"
end)
end
let lookup stdpath relative_to default config =
let dir =
OpamStd.Option.default default
(OpamFile.Switch_config.path config stdpath)
in
if Filename.is_relative dir then
if dir = "" then relative_to else relative_to / dir
else OpamFilename.Dir.of_string dir
let prefix t a c = lookup Prefix (root t a) "" c
let lib_dir t a c = lookup Lib (prefix t a c) "lib" c
let lib t a c n = lib_dir t a c / OpamPackage.Name.to_string n
let stublibs t a c = lookup Stublibs (lib_dir t a c) "stublibs" c
let toplevel t a c = lookup Toplevel (lib_dir t a c) "toplevel" c
let doc_dir t a c = lookup Doc (prefix t a c) "doc" c
let doc t a c n = doc_dir t a c / OpamPackage.Name.to_string n
let man_dir ?num t a c =
let base = lookup Man (prefix t a c) "man" c in
match num with
| None -> base
| Some n -> base / ("man" ^ n)
let man_dirs t a c = List.map (fun num -> man_dir ~num t a c) mans
let share_dir t a c = lookup Share (prefix t a c) "share" c
let share t a c n = share_dir t a c / OpamPackage.Name.to_string n
let etc_dir t a c = lookup Etc (prefix t a c) "etc" c
let etc t a c n = etc_dir t a c / OpamPackage.Name.to_string n
let bin t a c = lookup Bin (prefix t a c) "bin" c
let sbin t a c = lookup Sbin (prefix t a c) "sbin" c
let get_stdpath t a c = function
| Prefix -> prefix t a c
| Lib -> lib_dir t a c
| Bin -> bin t a c
| Sbin -> sbin t a c
| Share -> share_dir t a c
| Doc -> doc_dir t a c
| Etc -> etc_dir t a c
| Man -> man_dir t a c
| Toplevel -> toplevel t a c
| Stublibs -> stublibs t a c
module Overlay = struct
let dir t a = meta t a / "overlay"
let package t a n = dir t a / OpamPackage.Name.to_string n
let opam t a n = package t a n /- "opam"
let tmp_opam t a n = package t a n /- "opam_"
let url t a n = package t a n /- "url"
let descr t a n = package t a n /- "descr"
let files t a n = package t a n / "files"
end
end
module Builddir = struct
let install builddir nv =
builddir /- (OpamPackage.Name.to_string nv.name ^ ".install")
let config builddir nv =
builddir /- (OpamPackage.Name.to_string nv.name ^ ".config")
end
| null | https://raw.githubusercontent.com/ocaml/opam/9e287777ebd14fb52130aa945f792861ec034cd5/src/format/opamPath.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************
Returns a generic file, coerced by the .mli
let archives_dir t = t / "archives"
let archive t nv = archives_dir t // (OpamPackage.to_string nv ^ "+opam.tar.gz")
* Visible files that can be redirected using
[config/global-config.config] | Copyright 2012 - 2020 OCamlPro
Copyright 2012 INRIA
GNU Lesser General Public License version 2.1 , with the special
open OpamTypes
open OpamFilename.Op
type t = dirname
let ( /- ) dir f = OpamFile.make (dir // f)
let config t = t /- "config"
let init_config_files () =
List.map OpamFile.make [
OpamFilename.Dir.of_string (OpamStd.Sys.etc ()) // "opamrc";
OpamFilename.Dir.of_string (OpamStd.Sys.home ()) // ".opamrc";
]
let state_cache_dir t = t / "repo"
let state_cache t = state_cache_dir t // Printf.sprintf "state-%s.cache" (OpamVersion.magic ())
let lock t = t // "lock"
let config_lock t = t // "config.lock"
let repos_lock t = t / "repo" // "lock"
let repos_config t = t / "repo" /- "repos-config"
let init t = t / "opam-init"
let hooks_dir t = init t / "hooks"
let log t = t / "log"
let backup_file =
let file = lazy Unix.(
let tm = gmtime (Unix.gettimeofday ()) in
Printf.sprintf "state-%04d%02d%02d%02d%02d%02d.export"
(tm.tm_year+1900) (tm.tm_mon+1) tm.tm_mday tm.tm_hour tm.tm_min tm.tm_sec
) in
fun () -> Lazy.force file
let backup_dir t = t / "backup"
let backup t = backup_dir t /- backup_file ()
let plugin_prefix = "opam-"
let plugins t = t / "plugins"
let plugins_bin t = plugins t / "bin"
let plugin_bin t name =
let sname = OpamPackage.Name.to_string name ^ OpamStd.Sys.executable_name "" in
let basename =
if OpamStd.String.starts_with ~prefix:plugin_prefix sname then sname
else plugin_prefix ^ sname
in
plugins_bin t // basename
let plugin t name =
let sname = OpamPackage.Name.to_string name in
assert (sname <> "bin");
plugins t / sname
module type LAYOUT = sig
type ctx
val root : dirname -> ctx -> dirname
val lib_dir : dirname -> ctx -> dirname
end
module Switch = struct
let root t a = OpamSwitch.get_root t a
* Internal files and dirs with static location
let meta_dirname = ".opam-switch"
let meta t a = root t a / meta_dirname
let lock t a = meta t a // "lock"
let backup_dir t a = meta t a / "backup"
let backup t a = backup_dir t a /- backup_file ()
let selections t a = meta t a /- "switch-state"
let build_dir t a = meta t a / "build"
let build t a nv = build_dir t a / OpamPackage.to_string nv
let remove_dir t a = meta t a / "remove"
let remove t a nv = remove_dir t a / OpamPackage.to_string nv
let install_dir t a = meta t a / "install"
let install t a n = install_dir t a /- (OpamPackage.Name.to_string n ^ ".install")
let changes t a n = install_dir t a /- (OpamPackage.Name.to_string n ^ ".changes")
let reinstall t a = meta t a /- "reinstall"
let switch_config t a = meta t a /- "switch-config"
let config_dir t a = meta t a / "config"
let config t a n =
config_dir t a /- (OpamPackage.Name.to_string n ^ ".config")
let sources_dir t a = meta t a / "sources"
let extra_files_dir t a = meta t a / "extra-files-cache"
let extra_file t a h = extra_files_dir t a // OpamHash.contents h
let sources t a nv = sources_dir t a / OpamPackage.to_string nv
let pinned_package t a name = sources_dir t a / OpamPackage.Name.to_string name
let env_filename = "environment"
let environment t a = meta t a /- env_filename
let env_relative_to_prefix pfx = pfx / meta_dirname /- env_filename
let installed_opams t a = meta t a / "packages"
let installed_opams_cache t a = meta t a / "packages" // "cache"
let installed_package_dir t a nv =
installed_opams t a / OpamPackage.to_string nv
let installed_opam t a nv =
installed_package_dir t a nv /- "opam"
let installed_opam_files_dir t a nv =
installed_package_dir t a nv / "files"
let mans = ["1";"1M";"2";"3";"4";"5";"6";"7";"9"]
module DefaultF(L:LAYOUT) = struct
let lib_dir = L.lib_dir
let lib t a n = L.lib_dir t a / OpamPackage.Name.to_string n
let stublibs t a = L.lib_dir t a / "stublibs"
let toplevel t a = L.lib_dir t a / "toplevel"
let doc_dir t a = L.root t a / "doc"
let man_dir ?num t a =
match num with
| None -> L.root t a / "man"
| Some n -> L.root t a / "man" / ("man" ^ n)
let man_dirs t a = List.map (fun num -> man_dir ~num t a) mans
let share_dir t a = L.root t a / "share"
let share t a n = share_dir t a / OpamPackage.Name.to_string n
let etc_dir t a = L.root t a / "etc"
let etc t a n = etc_dir t a / OpamPackage.Name.to_string n
let doc t a n = doc_dir t a / OpamPackage.Name.to_string n
let bin t a = L.root t a / "bin"
let sbin t a = L.root t a / "sbin"
end
module Default = struct
include DefaultF(struct
type ctx = switch
let root = root
let lib_dir t a = root t a / "lib"
end)
end
let lookup stdpath relative_to default config =
let dir =
OpamStd.Option.default default
(OpamFile.Switch_config.path config stdpath)
in
if Filename.is_relative dir then
if dir = "" then relative_to else relative_to / dir
else OpamFilename.Dir.of_string dir
let prefix t a c = lookup Prefix (root t a) "" c
let lib_dir t a c = lookup Lib (prefix t a c) "lib" c
let lib t a c n = lib_dir t a c / OpamPackage.Name.to_string n
let stublibs t a c = lookup Stublibs (lib_dir t a c) "stublibs" c
let toplevel t a c = lookup Toplevel (lib_dir t a c) "toplevel" c
let doc_dir t a c = lookup Doc (prefix t a c) "doc" c
let doc t a c n = doc_dir t a c / OpamPackage.Name.to_string n
let man_dir ?num t a c =
let base = lookup Man (prefix t a c) "man" c in
match num with
| None -> base
| Some n -> base / ("man" ^ n)
let man_dirs t a c = List.map (fun num -> man_dir ~num t a c) mans
let share_dir t a c = lookup Share (prefix t a c) "share" c
let share t a c n = share_dir t a c / OpamPackage.Name.to_string n
let etc_dir t a c = lookup Etc (prefix t a c) "etc" c
let etc t a c n = etc_dir t a c / OpamPackage.Name.to_string n
let bin t a c = lookup Bin (prefix t a c) "bin" c
let sbin t a c = lookup Sbin (prefix t a c) "sbin" c
let get_stdpath t a c = function
| Prefix -> prefix t a c
| Lib -> lib_dir t a c
| Bin -> bin t a c
| Sbin -> sbin t a c
| Share -> share_dir t a c
| Doc -> doc_dir t a c
| Etc -> etc_dir t a c
| Man -> man_dir t a c
| Toplevel -> toplevel t a c
| Stublibs -> stublibs t a c
module Overlay = struct
let dir t a = meta t a / "overlay"
let package t a n = dir t a / OpamPackage.Name.to_string n
let opam t a n = package t a n /- "opam"
let tmp_opam t a n = package t a n /- "opam_"
let url t a n = package t a n /- "url"
let descr t a n = package t a n /- "descr"
let files t a n = package t a n / "files"
end
end
module Builddir = struct
let install builddir nv =
builddir /- (OpamPackage.Name.to_string nv.name ^ ".install")
let config builddir nv =
builddir /- (OpamPackage.Name.to_string nv.name ^ ".config")
end
|
d6e20bf5ca93a10fedb808b3604b52949ca8314809bfb008808bc2370178d3d1 | mfoemmel/erlang-otp | xmerl_xpath_parse.erl | -module(xmerl_xpath_parse).
-export([parse/1, parse_and_scan/1, format_error/1]).
-file("xmerl_xpath_parse.yrl", 301).
% token({Token, _Line}) ->
% Token;
% token({Token, _Line, _Value}) ->
% Token.
value({Token, _Line}) ->
Token;
value({_Token, _Line, Value}) ->
Value.
-file("/net/isildur/ldisk/daily_build/otp_prebuild_r13b02.2009-09-21_11/otp_src_R13B02/bootstrap/lib/parsetools/include/yeccpre.hrl", 0).
%%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The parser generator will insert appropriate declarations before this line.%
-type(yecc_ret() :: {'error', _} | {'ok', _}).
-spec parse(Tokens :: list()) -> yecc_ret().
parse(Tokens) ->
yeccpars0(Tokens, {no_func, no_line}, 0, [], []).
-spec(parse_and_scan/1 ::
({function() | {atom(), atom()}, [_]} | {atom(), atom(), [_]}) ->
yecc_ret()).
parse_and_scan({F, A}) -> % Fun or {M, F}
yeccpars0([], {{F, A}, no_line}, 0, [], []);
parse_and_scan({M, F, A}) ->
yeccpars0([], {{{M, F}, A}, no_line}, 0, [], []).
-spec(format_error/1 :: (any()) -> [char() | list()]).
format_error(Message) ->
case io_lib:deep_char_list(Message) of
true ->
Message;
_ ->
io_lib:write(Message)
end.
% To be used in grammar files to throw an error message to the parser
% toplevel. Doesn't have to be exported!
-compile({nowarn_unused_function, return_error/2}).
-spec(return_error/2 :: (integer(), any()) -> no_return()).
return_error(Line, Message) ->
throw({error, {Line, ?MODULE, Message}}).
-define(CODE_VERSION, "1.4").
yeccpars0(Tokens, Tzr, State, States, Vstack) ->
try yeccpars1(Tokens, Tzr, State, States, Vstack)
catch
error: Error ->
Stacktrace = erlang:get_stacktrace(),
try yecc_error_type(Error, Stacktrace) of
{syntax_error, Token} ->
yeccerror(Token);
{missing_in_goto_table=Tag, Symbol, State} ->
Desc = {Symbol, State, Tag},
erlang:raise(error, {yecc_bug, ?CODE_VERSION, Desc},
Stacktrace)
catch _:_ -> erlang:raise(error, Error, Stacktrace)
end;
%% Probably thrown from return_error/2:
throw: {error, {_Line, ?MODULE, _M}} = Error ->
Error
end.
yecc_error_type(function_clause, [{?MODULE,F,[State,_,_,_,Token,_,_]} | _]) ->
case atom_to_list(F) of
"yeccpars2" ++ _ ->
{syntax_error, Token};
"yeccgoto_" ++ SymbolL ->
{ok,[{atom,_,Symbol}],_} = erl_scan:string(SymbolL),
{missing_in_goto_table, Symbol, State}
end.
yeccpars1([Token | Tokens], Tzr, State, States, Vstack) ->
yeccpars2(State, element(1, Token), States, Vstack, Token, Tokens, Tzr);
yeccpars1([], {{F, A},_Line}, State, States, Vstack) ->
case apply(F, A) of
{ok, Tokens, Endline} ->
yeccpars1(Tokens, {{F, A}, Endline}, State, States, Vstack);
{eof, Endline} ->
yeccpars1([], {no_func, Endline}, State, States, Vstack);
{error, Descriptor, _Endline} ->
{error, Descriptor}
end;
yeccpars1([], {no_func, no_line}, State, States, Vstack) ->
Line = 999999,
yeccpars2(State, '$end', States, Vstack, yecc_end(Line), [],
{no_func, Line});
yeccpars1([], {no_func, Endline}, State, States, Vstack) ->
yeccpars2(State, '$end', States, Vstack, yecc_end(Endline), [],
{no_func, Endline}).
%% yeccpars1/7 is called from generated code.
%%
%% When using the {includefile, Includefile} option, make sure that
%% yeccpars1/7 can be found by parsing the file without following
%% include directives. yecc will otherwise assume that an old
yeccpre.hrl is included ( one which defines yeccpars1/5 ) .
yeccpars1(State1, State, States, Vstack, Token0, [Token | Tokens], Tzr) ->
yeccpars2(State, element(1, Token), [State1 | States],
[Token0 | Vstack], Token, Tokens, Tzr);
yeccpars1(State1, State, States, Vstack, Token0, [], {{_F,_A}, _Line}=Tzr) ->
yeccpars1([], Tzr, State, [State1 | States], [Token0 | Vstack]);
yeccpars1(State1, State, States, Vstack, Token0, [], {no_func, no_line}) ->
Line = yecctoken_end_location(Token0),
yeccpars2(State, '$end', [State1 | States], [Token0 | Vstack],
yecc_end(Line), [], {no_func, Line});
yeccpars1(State1, State, States, Vstack, Token0, [], {no_func, Line}) ->
yeccpars2(State, '$end', [State1 | States], [Token0 | Vstack],
yecc_end(Line), [], {no_func, Line}).
% For internal use only.
yecc_end({Line,_Column}) ->
{'$end', Line};
yecc_end(Line) ->
{'$end', Line}.
yecctoken_end_location(Token) ->
try
{text, Str} = erl_scan:token_info(Token, text),
{line, Line} = erl_scan:token_info(Token, line),
Parts = re:split(Str, "\n"),
Dline = length(Parts) - 1,
Yline = Line + Dline,
case erl_scan:token_info(Token, column) of
{column, Column} ->
Col = byte_size(lists:last(Parts)),
{Yline, Col + if Dline =:= 0 -> Column; true -> 1 end};
undefined ->
Yline
end
catch _:_ ->
yecctoken_location(Token)
end.
yeccerror(Token) ->
Text = yecctoken_to_string(Token),
Location = yecctoken_location(Token),
{error, {Location, ?MODULE, ["syntax error before: ", Text]}}.
yecctoken_to_string(Token) ->
case catch erl_scan:token_info(Token, text) of
{text, Txt} -> Txt;
_ -> yecctoken2string(Token)
end.
yecctoken_location(Token) ->
case catch erl_scan:token_info(Token, location) of
{location, Loc} -> Loc;
_ -> element(2, Token)
end.
yecctoken2string({atom, _, A}) -> io_lib:write(A);
yecctoken2string({integer,_,N}) -> io_lib:write(N);
yecctoken2string({float,_,F}) -> io_lib:write(F);
yecctoken2string({char,_,C}) -> io_lib:write_char(C);
yecctoken2string({var,_,V}) -> io_lib:format("~s", [V]);
yecctoken2string({string,_,S}) -> io_lib:write_unicode_string(S);
yecctoken2string({reserved_symbol, _, A}) -> io_lib:write(A);
yecctoken2string({_Cat, _, Val}) -> io_lib:write(Val);
yecctoken2string({dot, _}) -> "'.'";
yecctoken2string({'$end', _}) ->
[];
yecctoken2string({Other, _}) when is_atom(Other) ->
io_lib:write(Other);
yecctoken2string(Other) ->
io_lib:write(Other).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-file("./xmerl_xpath_parse.erl", 197).
yeccpars2(0=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(1=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(2=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_2(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(3 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_3(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(4=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(5=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(6=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(7=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(8=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_8(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(9=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(10=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(11=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(12=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(13=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(14=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_14(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(15=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_15(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(16=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(17=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(18=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(19=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(20=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(21=S, Cat, Ss, Stack, T, Ts, Tzr) ->
, Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(22 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_22(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(23=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(24=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(25=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_25(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(26=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_26(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(27=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_27(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(28=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(29=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_29(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(30=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_30(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(31=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_31(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(32=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_32(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(33=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_33(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(34=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_34(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(35=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_35(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(36=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_36(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(37=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_37(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(38=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_38(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(39=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_39(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(40=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_40(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(41=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_41(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(42=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_42(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(43=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_43(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(44=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_44(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(45=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_45(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(46=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_46(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(47=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_47(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(48=S, Cat, Ss, Stack, T, Ts, Tzr) ->
, Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(49=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_49(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(50=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_50(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(51=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_51(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(52=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(53=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_53(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(54=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(55=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_55(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(56=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_56(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(57=S, Cat, Ss, Stack, T, Ts, Tzr) ->
, Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(58=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_58(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(59=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(60=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_60(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(61=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_61(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(62=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_62(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(63=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_63(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(64=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_64(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(65=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_65(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(66=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_66(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(67=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_67(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(68=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_67(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(69=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_69(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(70=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_70(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(71 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
, Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(72=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_72(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(73 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_73(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(74=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_74(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(75=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(76=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(77 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
%% yeccpars2_77(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(78 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_0(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(79=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_79(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(80=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(81=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(82=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_82(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(83 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
, Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(84=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_84(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(85=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_85(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(86=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(87=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_87(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(88=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(89=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(90=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_90(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(91=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(92=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(93=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(94=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(95=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_95(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(96=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_96(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(97=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_97(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(98=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_98(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(99=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_99(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(100=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_100(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(101=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(102=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(103=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_103(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(104=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_104(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
%% yeccpars2(105=S, Cat, Ss, Stack, T, Ts, Tzr) ->
%% yeccpars2_105(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(106=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(107=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_107(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(108=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_108(S, Cat, Ss, Stack, T, Ts, Tzr);
%% yeccpars2(109=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_109(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(Other, _, _, _, _, _, _) ->
erlang:error({yecc_bug,"1.3",{missing_state_in_action_table, Other}}).
yeccpars2_0(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 23, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 24, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 27, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, function_name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 31, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 32, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, number, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, var_reference, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 38, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_1(S, '|', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 108, Ss, Stack, T, Ts, Tzr);
yeccpars2_1(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'UnaryExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'MultiplicativeExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelativeLocationPath\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_4(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_4(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_4(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_4_(Stack),
'yeccgoto_\'LocationPath\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_5(S, '<', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 91, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(S, '<=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 92, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(S, '>', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 93, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(S, '>=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 94, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'EqualityExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'FilterExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'UnionExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_8(S, 'or', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 106, Ss, Stack, T, Ts, Tzr);
yeccpars2_8(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'Expr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_9(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_9(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_9_(Stack),
'yeccgoto_\'Step\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'NodeTest\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_11(S, '*', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 79, Ss, Stack, T, Ts, Tzr);
yeccpars2_11(S, 'div', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 80, Ss, Stack, T, Ts, Tzr);
yeccpars2_11(S, mod, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 81, Ss, Stack, T, Ts, Tzr);
yeccpars2_11(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AdditiveExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PathExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_14(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 101, Ss, Stack, T, Ts, Tzr);
yeccpars2_14(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 102, Ss, Stack, T, Ts, Tzr);
yeccpars2_14(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_14(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PathExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_15(_S, '$end', _Ss, Stack, _T, _Ts, _Tzr) ->
{ok, hd(Stack)}.
yeccpars2_16(S, '!=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 88, Ss, Stack, T, Ts, Tzr);
yeccpars2_16(S, '=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 89, Ss, Stack, T, Ts, Tzr);
yeccpars2_16(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AndExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_17(S, 'and', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 86, Ss, Stack, T, Ts, Tzr);
yeccpars2_17(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'OrExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_18(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_18(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_18(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelationalExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_19_(Stack),
'yeccgoto_\'LocationPath\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_20_(Stack),
'yeccgoto_\'Step\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelativeLocationPath\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelativeLocationPath\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
%% yeccpars2_23: see yeccpars2_0
%% yeccpars2_24: see yeccpars2_0
yeccpars2_25(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AbbreviatedStep\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_26(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AbbreviatedStep\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_27(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 33, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, node_type, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 34, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, prefix_test, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 36, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, 'processing-instruction', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 37, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, wildcard, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 39, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_27_(Stack),
'yeccgoto_\'AbsoluteLocationPath\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_28(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_29(S, name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 64, Ss, Stack, T, Ts, Tzr).
yeccpars2_30(S, '::', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 54, Ss, Stack, T, Ts, Tzr).
yeccpars2_31(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 45, Ss, Stack, T, Ts, Tzr).
yeccpars2_32(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_32_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_33(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_33_(Stack),
'yeccgoto_\'NameTest\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_34(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 43, Ss, Stack, T, Ts, Tzr).
yeccpars2_35(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_35_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_36(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_36_(Stack),
'yeccgoto_\'NameTest\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_37(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 40, Ss, Stack, T, Ts, Tzr).
yeccpars2_38(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_38_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_39(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_39_(Stack),
'yeccgoto_\'NameTest\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_40(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 41, Ss, Stack, T, Ts, Tzr).
yeccpars2_41(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 42, Ss, Stack, T, Ts, Tzr).
yeccpars2_42(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_,_|Nss] = Ss,
NewStack = yeccpars2_42_(Stack),
'yeccgoto_\'NodeTest\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_43(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 44, Ss, Stack, T, Ts, Tzr).
yeccpars2_44(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_44_(Stack),
'yeccgoto_\'NodeTest\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_45(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 23, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 50, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 24, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 27, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, function_name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 31, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 32, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, number, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, var_reference, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 38, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_46(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'Argument\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_47(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_47_(Stack),
'yeccgoto_\'<ArgumentMember>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_48(S, ',', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 52, Ss, Stack, T, Ts, Tzr);
yeccpars2_48(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_48_(Stack),
'yeccgoto_\'<ArgumentList>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_49(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 51, Ss, Stack, T, Ts, Tzr).
yeccpars2_50(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_50_(Stack),
'yeccgoto_\'FunctionCall\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_51(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_,_|Nss] = Ss,
NewStack = yeccpars2_51_(Stack),
'yeccgoto_\'FunctionCall\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_52: see yeccpars2_0
yeccpars2_53(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_53_(Stack),
'yeccgoto_\'<ArgumentMember>\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_54(S, name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 33, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, node_type, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 34, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, prefix_test, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 36, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, 'processing-instruction', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 37, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, wildcard, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 39, Ss, Stack, T, Ts, Tzr).
yeccpars2_55(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_55(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_55_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_56_(Stack),
'yeccgoto_\'<PredicateMember>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_57(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_57(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_57_(Stack),
'yeccgoto_\'<PredicateList>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_58(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_,_|Nss] = Ss,
NewStack = yeccpars2_58_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_59: see yeccpars2_0
yeccpars2_60(S, ']', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 62, Ss, Stack, T, Ts, Tzr).
yeccpars2_61(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PredicateExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_62(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_62_(Stack),
'yeccgoto_\'Predicate\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_63(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_63_(Stack),
'yeccgoto_\'<PredicateMember>\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_64(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_64(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_64_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_65(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_65_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_66(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_66(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_66(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_66_(Stack),
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_67(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
%% yeccpars2_68: see yeccpars2_67
yeccpars2_69(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_69_(Stack),
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_70(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_70_(Stack),
'yeccgoto_\'RelativeLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_71(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_71(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_71(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_71_(Stack),
'yeccgoto_\'AbsoluteLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_72(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_72_(Stack),
'yeccgoto_\'UnaryExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_73(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 74, Ss, Stack, T, Ts, Tzr).
yeccpars2_74(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_74_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_75: see yeccpars2_0
%% yeccpars2_76: see yeccpars2_0
yeccpars2_77(S, '*', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 79, Ss, Stack, T, Ts, Tzr);
yeccpars2_77(S, 'div', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 80, Ss, Stack, T, Ts, Tzr);
yeccpars2_77(S, mod, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 81, Ss, Stack, T, Ts, Tzr);
yeccpars2_77(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_77_(Stack),
'yeccgoto_\'AdditiveExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_78: see yeccpars2_0
yeccpars2_79(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_79_(Stack),
'yeccgoto_\'MultiplyOperator\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
%% yeccpars2_80: see yeccpars2_0
%% yeccpars2_81: see yeccpars2_0
yeccpars2_82(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_82_(Stack),
'yeccgoto_\'MultiplicativeExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_83(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_83_(Stack),
'yeccgoto_\'MultiplicativeExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_84(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_84_(Stack),
'yeccgoto_\'MultiplicativeExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_85(S, '*', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 79, Ss, Stack, T, Ts, Tzr);
yeccpars2_85(S, 'div', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 80, Ss, Stack, T, Ts, Tzr);
yeccpars2_85(S, mod, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 81, Ss, Stack, T, Ts, Tzr);
yeccpars2_85(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_85_(Stack),
'yeccgoto_\'AdditiveExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_86: see yeccpars2_0
yeccpars2_87(S, '!=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 88, Ss, Stack, T, Ts, Tzr);
yeccpars2_87(S, '=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 89, Ss, Stack, T, Ts, Tzr);
yeccpars2_87(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_87_(Stack),
'yeccgoto_\'AndExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_88: see yeccpars2_0
%% yeccpars2_89: see yeccpars2_0
yeccpars2_90(S, '<', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 91, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(S, '<=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 92, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(S, '>', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 93, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(S, '>=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 94, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_90_(Stack),
'yeccgoto_\'EqualityExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_91: see yeccpars2_0
%% yeccpars2_92: see yeccpars2_0
%% yeccpars2_93: see yeccpars2_0
%% yeccpars2_94: see yeccpars2_0
yeccpars2_95(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_95(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_95(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_95_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_96(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_96(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_96(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_96_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_97(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_97(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_97(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_97_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_98(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_98(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_98(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_98_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_99(S, '<', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 91, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(S, '<=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 92, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(S, '>', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 93, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(S, '>=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 94, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_99_(Stack),
'yeccgoto_\'EqualityExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_100(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_100_(Stack),
'yeccgoto_\'FilterExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_101: see yeccpars2_28
%% yeccpars2_102: see yeccpars2_28
yeccpars2_103(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_103(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_103(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_103_(Stack),
'yeccgoto_\'PathExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_104(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_104(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_104(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_104_(Stack),
'yeccgoto_\'PathExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_105(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_105_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
%% yeccpars2_106: see yeccpars2_0
yeccpars2_107(S, 'and', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 86, Ss, Stack, T, Ts, Tzr);
yeccpars2_107(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_107_(Stack),
'yeccgoto_\'OrExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_108(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 23, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 27, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, function_name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 31, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 32, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, number, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, var_reference, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 38, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_109(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_109_(Stack),
'yeccgoto_\'UnionExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
'yeccgoto_\'<ArgumentList>\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_49(49, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'<ArgumentMember>\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_48(48, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'<PredicateList>\''(9=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_105(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateList>\''(55=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_58(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateList>\''(64=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_65(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'<PredicateMember>\''(9, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_57(57, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateMember>\''(55, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_57(57, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateMember>\''(64, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_57(57, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbbreviatedStep\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(67=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(68=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbsoluteLocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AdditiveExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_98(98, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_97(97, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_96(96, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_95(95, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AndExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_107(107, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Argument\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_47(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Argument\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_53(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'EqualityExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_87(87, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Expr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_15(15, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_73(73, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_46(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_46(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_61(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'FilterExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(108, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'FunctionCall\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'LocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'MultiplicativeExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_85(85, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_77(77, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'MultiplyOperator\''(11, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(78, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplyOperator\''(77, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(78, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplyOperator\''(85, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(78, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'NameTest\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(54=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(67=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(68=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'NodeTest\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(27, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(28, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(54, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_55(55, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(67, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(68, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(101, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(102, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(108, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'OrExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'PathExpr\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_109(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Predicate\''(9=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(14=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_100(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(55=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(57=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_63(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(64=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'PredicateExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_60(60, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'PrimaryExpr\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'RelationalExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_99(99, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_90(90, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'RelativeLocationPath\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(27, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_71(71, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(28, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_66(66, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(101, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_104(104, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(102, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_103(103, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(108, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Step\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(67=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_70(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(68=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_69(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'UnaryExpr\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_72(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_84(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_83(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_82(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'UnionExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr).
-compile({inline,yeccpars2_4_/1}).
-file("xmerl_xpath_parse.yrl", 96).
yeccpars2_4_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ path , rel , __1 }
end | __Stack].
-compile({inline,yeccpars2_9_/1}).
-file("xmerl_xpath_parse.yrl", 122).
yeccpars2_9_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ step , { child , __1 , [ ] } }
end | __Stack].
-compile({inline,yeccpars2_19_/1}).
-file("xmerl_xpath_parse.yrl", 97).
yeccpars2_19_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ path , abs , __1 }
end | __Stack].
-compile({inline,yeccpars2_20_/1}).
-file("xmerl_xpath_parse.yrl", 124).
yeccpars2_20_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ abbrev_step , __1 }
end | __Stack].
-compile({inline,yeccpars2_27_/1}).
-file("xmerl_xpath_parse.yrl", 101).
yeccpars2_27_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
'/'
end | __Stack].
-compile({inline,yeccpars2_32_/1}).
-file("xmerl_xpath_parse.yrl", 175).
yeccpars2_32_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ literal , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_33_/1}).
-file("xmerl_xpath_parse.yrl", 293).
yeccpars2_33_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ name , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_35_/1}).
-file("xmerl_xpath_parse.yrl", 176).
yeccpars2_35_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ number , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_36_/1}).
-file("xmerl_xpath_parse.yrl", 292).
yeccpars2_36_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ prefix_test , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_38_/1}).
-file("xmerl_xpath_parse.yrl", 173).
yeccpars2_38_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ variable_reference , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_39_/1}).
-file("xmerl_xpath_parse.yrl", 291).
yeccpars2_39_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ wildcard , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_42_/1}).
-file("xmerl_xpath_parse.yrl", 144).
yeccpars2_42_(__Stack0) ->
[__4,__3,__2,__1 | __Stack] = __Stack0,
[begin
{ processing_instruction , value ( __3 ) }
end | __Stack].
-compile({inline,yeccpars2_44_/1}).
-file("xmerl_xpath_parse.yrl", 142).
yeccpars2_44_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ node_type , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_47_/1}).
-file("xmerl_xpath_parse.yrl", 189).
yeccpars2_47_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
[ __1 ]
end | __Stack].
-compile({inline,yeccpars2_48_/1}).
-file("xmerl_xpath_parse.yrl", 185).
yeccpars2_48_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
lists : reverse ( __1 )
end | __Stack].
-compile({inline,yeccpars2_50_/1}).
-file("xmerl_xpath_parse.yrl", 181).
yeccpars2_50_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ function_call , value ( __1 ) , [ ] }
end | __Stack].
-compile({inline,yeccpars2_51_/1}).
-file("xmerl_xpath_parse.yrl", 183).
yeccpars2_51_(__Stack0) ->
[__4,__3,__2,__1 | __Stack] = __Stack0,
[begin
{ function_call , value ( __1 ) , __3 }
end | __Stack].
-compile({inline,yeccpars2_53_/1}).
-file("xmerl_xpath_parse.yrl", 188).
yeccpars2_53_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
[ __3 | __1 ]
end | __Stack].
-compile({inline,yeccpars2_55_/1}).
-file("xmerl_xpath_parse.yrl", 114).
yeccpars2_55_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ step , { value ( __1 ) , __3 , [ ] } }
end | __Stack].
-compile({inline,yeccpars2_56_/1}).
-file("xmerl_xpath_parse.yrl", 132).
yeccpars2_56_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
[ __1 ]
end | __Stack].
-compile({inline,yeccpars2_57_/1}).
-file("xmerl_xpath_parse.yrl", 127).
yeccpars2_57_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
lists : reverse ( __1 )
end | __Stack].
-compile({inline,yeccpars2_58_/1}).
-file("xmerl_xpath_parse.yrl", 112).
yeccpars2_58_(__Stack0) ->
[__4,__3,__2,__1 | __Stack] = __Stack0,
[begin
{ step , { value ( __1 ) , __3 , __4 } }
end | __Stack].
-compile({inline,yeccpars2_62_/1}).
-file("xmerl_xpath_parse.yrl", 148).
yeccpars2_62_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ pred , __2 }
end | __Stack].
-compile({inline,yeccpars2_63_/1}).
-file("xmerl_xpath_parse.yrl", 131).
yeccpars2_63_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
[ __2 | __1 ]
end | __Stack].
-compile({inline,yeccpars2_64_/1}).
-file("xmerl_xpath_parse.yrl", 118).
yeccpars2_64_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ step , { attribute , __2 , [ ] } }
end | __Stack].
-compile({inline,yeccpars2_65_/1}).
-file("xmerl_xpath_parse.yrl", 116).
yeccpars2_65_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ step , { value ( __1 ) , __2 , __3 } }
end | __Stack].
-compile({inline,yeccpars2_66_/1}).
-file("xmerl_xpath_parse.yrl", 155).
yeccpars2_66_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ '//' , __2 }
end | __Stack].
-compile({inline,yeccpars2_69_/1}).
-file("xmerl_xpath_parse.yrl", 159).
yeccpars2_69_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ __1 , '//' , __3 }
end | __Stack].
-compile({inline,yeccpars2_70_/1}).
-file("xmerl_xpath_parse.yrl", 107).
yeccpars2_70_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ refine , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_71_/1}).
-file("xmerl_xpath_parse.yrl", 100).
yeccpars2_71_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
__2
end | __Stack].
-compile({inline,yeccpars2_72_/1}).
-file("xmerl_xpath_parse.yrl", 262).
yeccpars2_72_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ negative , __2 }
end | __Stack].
-compile({inline,yeccpars2_74_/1}).
-file("xmerl_xpath_parse.yrl", 174).
yeccpars2_74_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
__2
end | __Stack].
-compile({inline,yeccpars2_77_/1}).
-file("xmerl_xpath_parse.yrl", 247).
yeccpars2_77_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , '-' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_79_/1}).
-file("xmerl_xpath_parse.yrl", 287).
yeccpars2_79_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
'*'
end | __Stack].
-compile({inline,yeccpars2_82_/1}).
-file("xmerl_xpath_parse.yrl", 257).
yeccpars2_82_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , mod , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_83_/1}).
-file("xmerl_xpath_parse.yrl", 255).
yeccpars2_83_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , 'div' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_84_/1}).
-file("xmerl_xpath_parse.yrl", 253).
yeccpars2_84_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , __2 , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_85_/1}).
-file("xmerl_xpath_parse.yrl", 245).
yeccpars2_85_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , '+' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_87_/1}).
-file("xmerl_xpath_parse.yrl", 221).
yeccpars2_87_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ bool , 'and' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_90_/1}).
-file("xmerl_xpath_parse.yrl", 226).
yeccpars2_90_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_95_/1}).
-file("xmerl_xpath_parse.yrl", 239).
yeccpars2_95_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '>=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_96_/1}).
-file("xmerl_xpath_parse.yrl", 235).
yeccpars2_96_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '>' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_97_/1}).
-file("xmerl_xpath_parse.yrl", 237).
yeccpars2_97_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '<=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_98_/1}).
-file("xmerl_xpath_parse.yrl", 233).
yeccpars2_98_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '<' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_99_/1}).
-file("xmerl_xpath_parse.yrl", 228).
yeccpars2_99_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '!=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_100_/1}).
-file("xmerl_xpath_parse.yrl", 209).
yeccpars2_100_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ path , filter , { __1 , __2 } }
end | __Stack].
-compile({inline,yeccpars2_103_/1}).
-file("xmerl_xpath_parse.yrl", 205).
yeccpars2_103_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ __1 , '//' , __3 }
end | __Stack].
-compile({inline,yeccpars2_104_/1}).
-file("xmerl_xpath_parse.yrl", 204).
yeccpars2_104_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ refine , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_105_/1}).
-file("xmerl_xpath_parse.yrl", 120).
yeccpars2_105_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ step , { child , __1 , __2 } }
end | __Stack].
-compile({inline,yeccpars2_107_/1}).
-file("xmerl_xpath_parse.yrl", 215).
yeccpars2_107_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ bool , 'or' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_109_/1}).
-file("xmerl_xpath_parse.yrl", 198).
yeccpars2_109_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ path , union , { __1 , __3 } }
end | __Stack].
-file("xmerl_xpath_parse.yrl", 312).
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/xmerl/src/xmerl_xpath_parse.erl | erlang | token({Token, _Line}) ->
Token;
token({Token, _Line, _Value}) ->
Token.
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
The parser generator will insert appropriate declarations before this line.%
Fun or {M, F}
To be used in grammar files to throw an error message to the parser
toplevel. Doesn't have to be exported!
Probably thrown from return_error/2:
yeccpars1/7 is called from generated code.
When using the {includefile, Includefile} option, make sure that
yeccpars1/7 can be found by parsing the file without following
include directives. yecc will otherwise assume that an old
For internal use only.
yeccpars2(1=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(2=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(4=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(5=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(6=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(7=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(8=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(9=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(10=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(11=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(12=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(13=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(14=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(15=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(16=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(17=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(18=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(19=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(20=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(21=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(46=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(47=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(48=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(49=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(53=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(55=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_55(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(56=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(57=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(58=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(60=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(61=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(63=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(65=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(66=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(69=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_69(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(70=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(72=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_77(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(82=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(84=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(85=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(87=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_87(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(90=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_90(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(95=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(96=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(97=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(98=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(99=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_99(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(100=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(103=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(104=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(105=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_105(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(107=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2(109=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_23: see yeccpars2_0
yeccpars2_24: see yeccpars2_0
yeccpars2_52: see yeccpars2_0
yeccpars2_59: see yeccpars2_0
yeccpars2_68: see yeccpars2_67
yeccpars2_75: see yeccpars2_0
yeccpars2_76: see yeccpars2_0
yeccpars2_78: see yeccpars2_0
yeccpars2_80: see yeccpars2_0
yeccpars2_81: see yeccpars2_0
yeccpars2_86: see yeccpars2_0
yeccpars2_88: see yeccpars2_0
yeccpars2_89: see yeccpars2_0
yeccpars2_91: see yeccpars2_0
yeccpars2_92: see yeccpars2_0
yeccpars2_93: see yeccpars2_0
yeccpars2_94: see yeccpars2_0
yeccpars2_101: see yeccpars2_28
yeccpars2_102: see yeccpars2_28
yeccpars2_106: see yeccpars2_0 | -module(xmerl_xpath_parse).
-export([parse/1, parse_and_scan/1, format_error/1]).
-file("xmerl_xpath_parse.yrl", 301).
value({Token, _Line}) ->
Token;
value({_Token, _Line, Value}) ->
Value.
-file("/net/isildur/ldisk/daily_build/otp_prebuild_r13b02.2009-09-21_11/otp_src_R13B02/bootstrap/lib/parsetools/include/yeccpre.hrl", 0).
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-type(yecc_ret() :: {'error', _} | {'ok', _}).
-spec parse(Tokens :: list()) -> yecc_ret().
parse(Tokens) ->
yeccpars0(Tokens, {no_func, no_line}, 0, [], []).
-spec(parse_and_scan/1 ::
({function() | {atom(), atom()}, [_]} | {atom(), atom(), [_]}) ->
yecc_ret()).
yeccpars0([], {{F, A}, no_line}, 0, [], []);
parse_and_scan({M, F, A}) ->
yeccpars0([], {{{M, F}, A}, no_line}, 0, [], []).
-spec(format_error/1 :: (any()) -> [char() | list()]).
format_error(Message) ->
case io_lib:deep_char_list(Message) of
true ->
Message;
_ ->
io_lib:write(Message)
end.
-compile({nowarn_unused_function, return_error/2}).
-spec(return_error/2 :: (integer(), any()) -> no_return()).
return_error(Line, Message) ->
throw({error, {Line, ?MODULE, Message}}).
-define(CODE_VERSION, "1.4").
yeccpars0(Tokens, Tzr, State, States, Vstack) ->
try yeccpars1(Tokens, Tzr, State, States, Vstack)
catch
error: Error ->
Stacktrace = erlang:get_stacktrace(),
try yecc_error_type(Error, Stacktrace) of
{syntax_error, Token} ->
yeccerror(Token);
{missing_in_goto_table=Tag, Symbol, State} ->
Desc = {Symbol, State, Tag},
erlang:raise(error, {yecc_bug, ?CODE_VERSION, Desc},
Stacktrace)
catch _:_ -> erlang:raise(error, Error, Stacktrace)
end;
throw: {error, {_Line, ?MODULE, _M}} = Error ->
Error
end.
yecc_error_type(function_clause, [{?MODULE,F,[State,_,_,_,Token,_,_]} | _]) ->
case atom_to_list(F) of
"yeccpars2" ++ _ ->
{syntax_error, Token};
"yeccgoto_" ++ SymbolL ->
{ok,[{atom,_,Symbol}],_} = erl_scan:string(SymbolL),
{missing_in_goto_table, Symbol, State}
end.
yeccpars1([Token | Tokens], Tzr, State, States, Vstack) ->
yeccpars2(State, element(1, Token), States, Vstack, Token, Tokens, Tzr);
yeccpars1([], {{F, A},_Line}, State, States, Vstack) ->
case apply(F, A) of
{ok, Tokens, Endline} ->
yeccpars1(Tokens, {{F, A}, Endline}, State, States, Vstack);
{eof, Endline} ->
yeccpars1([], {no_func, Endline}, State, States, Vstack);
{error, Descriptor, _Endline} ->
{error, Descriptor}
end;
yeccpars1([], {no_func, no_line}, State, States, Vstack) ->
Line = 999999,
yeccpars2(State, '$end', States, Vstack, yecc_end(Line), [],
{no_func, Line});
yeccpars1([], {no_func, Endline}, State, States, Vstack) ->
yeccpars2(State, '$end', States, Vstack, yecc_end(Endline), [],
{no_func, Endline}).
yeccpre.hrl is included ( one which defines yeccpars1/5 ) .
yeccpars1(State1, State, States, Vstack, Token0, [Token | Tokens], Tzr) ->
yeccpars2(State, element(1, Token), [State1 | States],
[Token0 | Vstack], Token, Tokens, Tzr);
yeccpars1(State1, State, States, Vstack, Token0, [], {{_F,_A}, _Line}=Tzr) ->
yeccpars1([], Tzr, State, [State1 | States], [Token0 | Vstack]);
yeccpars1(State1, State, States, Vstack, Token0, [], {no_func, no_line}) ->
Line = yecctoken_end_location(Token0),
yeccpars2(State, '$end', [State1 | States], [Token0 | Vstack],
yecc_end(Line), [], {no_func, Line});
yeccpars1(State1, State, States, Vstack, Token0, [], {no_func, Line}) ->
yeccpars2(State, '$end', [State1 | States], [Token0 | Vstack],
yecc_end(Line), [], {no_func, Line}).
yecc_end({Line,_Column}) ->
{'$end', Line};
yecc_end(Line) ->
{'$end', Line}.
yecctoken_end_location(Token) ->
try
{text, Str} = erl_scan:token_info(Token, text),
{line, Line} = erl_scan:token_info(Token, line),
Parts = re:split(Str, "\n"),
Dline = length(Parts) - 1,
Yline = Line + Dline,
case erl_scan:token_info(Token, column) of
{column, Column} ->
Col = byte_size(lists:last(Parts)),
{Yline, Col + if Dline =:= 0 -> Column; true -> 1 end};
undefined ->
Yline
end
catch _:_ ->
yecctoken_location(Token)
end.
yeccerror(Token) ->
Text = yecctoken_to_string(Token),
Location = yecctoken_location(Token),
{error, {Location, ?MODULE, ["syntax error before: ", Text]}}.
yecctoken_to_string(Token) ->
case catch erl_scan:token_info(Token, text) of
{text, Txt} -> Txt;
_ -> yecctoken2string(Token)
end.
yecctoken_location(Token) ->
case catch erl_scan:token_info(Token, location) of
{location, Loc} -> Loc;
_ -> element(2, Token)
end.
yecctoken2string({atom, _, A}) -> io_lib:write(A);
yecctoken2string({integer,_,N}) -> io_lib:write(N);
yecctoken2string({float,_,F}) -> io_lib:write(F);
yecctoken2string({char,_,C}) -> io_lib:write_char(C);
yecctoken2string({var,_,V}) -> io_lib:format("~s", [V]);
yecctoken2string({string,_,S}) -> io_lib:write_unicode_string(S);
yecctoken2string({reserved_symbol, _, A}) -> io_lib:write(A);
yecctoken2string({_Cat, _, Val}) -> io_lib:write(Val);
yecctoken2string({dot, _}) -> "'.'";
yecctoken2string({'$end', _}) ->
[];
yecctoken2string({Other, _}) when is_atom(Other) ->
io_lib:write(Other);
yecctoken2string(Other) ->
io_lib:write(Other).
-file("./xmerl_xpath_parse.erl", 197).
yeccpars2(0=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_1(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(3 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_3(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_4(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_5(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_6(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_7(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_9(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_10(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_11(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_12(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_13(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_15(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_16(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_17(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_18(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_19(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_20(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
, Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(22 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_22(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(23=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(24=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(25=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_25(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(26=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_26(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(27=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_27(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(28=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(29=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_29(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(30=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_30(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(31=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_31(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(32=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_32(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(33=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_33(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(34=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_34(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(35=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_35(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(36=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_36(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(37=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_37(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(38=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_38(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(39=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_39(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(40=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_40(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(41=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_41(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(42=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_42(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(43=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_43(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(44=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_44(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(45=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_45(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_46(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_47(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
, Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_49(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(50=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_50(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(51=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_51(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(52=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_53(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(54=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_56(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
, Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_58(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(59=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_60(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_61(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(62=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_62(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_63(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(64=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_64(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_65(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_66(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(67=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_67(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(68=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_67(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_70(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(71 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
, Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_72(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(73 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_73(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(74=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_74(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(75=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(76=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(77 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2(78 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
yeccpars2_0(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(79=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_79(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(80=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(81=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_82(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(83 = S , Cat , Ss , Stack , T , Ts , Tzr ) - >
, Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_84(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_85(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(86=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(88=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(89=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(91=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(92=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(93=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(94=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_95(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_96(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_97(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_98(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_100(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(101=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2(102=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_103(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2_104(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(106=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_107(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(108=S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_108(S, Cat, Ss, Stack, T, Ts, Tzr);
yeccpars2_109(S , Cat , Ss , Stack , T , Ts , Tzr ) ;
yeccpars2(Other, _, _, _, _, _, _) ->
erlang:error({yecc_bug,"1.3",{missing_state_in_action_table, Other}}).
yeccpars2_0(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 23, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 24, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 27, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, function_name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 31, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 32, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, number, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, var_reference, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 38, Ss, Stack, T, Ts, Tzr);
yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_1(S, '|', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 108, Ss, Stack, T, Ts, Tzr);
yeccpars2_1(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'UnaryExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'MultiplicativeExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelativeLocationPath\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_4(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_4(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_4(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_4_(Stack),
'yeccgoto_\'LocationPath\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_5(S, '<', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 91, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(S, '<=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 92, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(S, '>', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 93, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(S, '>=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 94, Ss, Stack, T, Ts, Tzr);
yeccpars2_5(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'EqualityExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'FilterExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'UnionExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_8(S, 'or', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 106, Ss, Stack, T, Ts, Tzr);
yeccpars2_8(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'Expr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_9(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_9(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_9_(Stack),
'yeccgoto_\'Step\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'NodeTest\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_11(S, '*', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 79, Ss, Stack, T, Ts, Tzr);
yeccpars2_11(S, 'div', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 80, Ss, Stack, T, Ts, Tzr);
yeccpars2_11(S, mod, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 81, Ss, Stack, T, Ts, Tzr);
yeccpars2_11(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AdditiveExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PathExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_14(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 101, Ss, Stack, T, Ts, Tzr);
yeccpars2_14(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 102, Ss, Stack, T, Ts, Tzr);
yeccpars2_14(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_14(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PathExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_15(_S, '$end', _Ss, Stack, _T, _Ts, _Tzr) ->
{ok, hd(Stack)}.
yeccpars2_16(S, '!=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 88, Ss, Stack, T, Ts, Tzr);
yeccpars2_16(S, '=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 89, Ss, Stack, T, Ts, Tzr);
yeccpars2_16(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AndExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_17(S, 'and', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 86, Ss, Stack, T, Ts, Tzr);
yeccpars2_17(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'OrExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_18(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_18(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_18(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelationalExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_19_(Stack),
'yeccgoto_\'LocationPath\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_20_(Stack),
'yeccgoto_\'Step\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelativeLocationPath\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'RelativeLocationPath\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_25(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AbbreviatedStep\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_26(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'AbbreviatedStep\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_27(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 33, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, node_type, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 34, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, prefix_test, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 36, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, 'processing-instruction', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 37, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(S, wildcard, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 39, Ss, Stack, T, Ts, Tzr);
yeccpars2_27(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_27_(Stack),
'yeccgoto_\'AbsoluteLocationPath\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_28(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_29(S, name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 64, Ss, Stack, T, Ts, Tzr).
yeccpars2_30(S, '::', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 54, Ss, Stack, T, Ts, Tzr).
yeccpars2_31(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 45, Ss, Stack, T, Ts, Tzr).
yeccpars2_32(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_32_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_33(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_33_(Stack),
'yeccgoto_\'NameTest\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_34(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 43, Ss, Stack, T, Ts, Tzr).
yeccpars2_35(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_35_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_36(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_36_(Stack),
'yeccgoto_\'NameTest\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_37(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 40, Ss, Stack, T, Ts, Tzr).
yeccpars2_38(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_38_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_39(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_39_(Stack),
'yeccgoto_\'NameTest\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_40(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 41, Ss, Stack, T, Ts, Tzr).
yeccpars2_41(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 42, Ss, Stack, T, Ts, Tzr).
yeccpars2_42(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_,_|Nss] = Ss,
NewStack = yeccpars2_42_(Stack),
'yeccgoto_\'NodeTest\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_43(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 44, Ss, Stack, T, Ts, Tzr).
yeccpars2_44(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_44_(Stack),
'yeccgoto_\'NodeTest\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_45(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 23, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 50, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 24, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 27, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, function_name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 31, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 32, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, number, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, var_reference, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 38, Ss, Stack, T, Ts, Tzr);
yeccpars2_45(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_46(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'Argument\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_47(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_47_(Stack),
'yeccgoto_\'<ArgumentMember>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_48(S, ',', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 52, Ss, Stack, T, Ts, Tzr);
yeccpars2_48(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_48_(Stack),
'yeccgoto_\'<ArgumentList>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_49(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 51, Ss, Stack, T, Ts, Tzr).
yeccpars2_50(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_50_(Stack),
'yeccgoto_\'FunctionCall\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_51(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_,_|Nss] = Ss,
NewStack = yeccpars2_51_(Stack),
'yeccgoto_\'FunctionCall\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_53(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_53_(Stack),
'yeccgoto_\'<ArgumentMember>\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_54(S, name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 33, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, node_type, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 34, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, prefix_test, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 36, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, 'processing-instruction', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 37, Ss, Stack, T, Ts, Tzr);
yeccpars2_54(S, wildcard, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 39, Ss, Stack, T, Ts, Tzr).
yeccpars2_55(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_55(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_55_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_56_(Stack),
'yeccgoto_\'<PredicateMember>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_57(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_57(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_57_(Stack),
'yeccgoto_\'<PredicateList>\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_58(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_,_|Nss] = Ss,
NewStack = yeccpars2_58_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_60(S, ']', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 62, Ss, Stack, T, Ts, Tzr).
yeccpars2_61(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
'yeccgoto_\'PredicateExpr\''(hd(Ss), Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_62(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_62_(Stack),
'yeccgoto_\'Predicate\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_63(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_63_(Stack),
'yeccgoto_\'<PredicateMember>\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_64(S, '[', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 59, Ss, Stack, T, Ts, Tzr);
yeccpars2_64(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_64_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_65(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_65_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_66(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_66(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_66(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_66_(Stack),
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_67(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_67(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_69(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_69_(Stack),
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_70(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_70_(Stack),
'yeccgoto_\'RelativeLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_71(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_71(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_71(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_71_(Stack),
'yeccgoto_\'AbsoluteLocationPath\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_72(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_72_(Stack),
'yeccgoto_\'UnaryExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_73(S, ')', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 74, Ss, Stack, T, Ts, Tzr).
yeccpars2_74(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_74_(Stack),
'yeccgoto_\'PrimaryExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_77(S, '*', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 79, Ss, Stack, T, Ts, Tzr);
yeccpars2_77(S, 'div', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 80, Ss, Stack, T, Ts, Tzr);
yeccpars2_77(S, mod, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 81, Ss, Stack, T, Ts, Tzr);
yeccpars2_77(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_77_(Stack),
'yeccgoto_\'AdditiveExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_79(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
NewStack = yeccpars2_79_(Stack),
'yeccgoto_\'MultiplyOperator\''(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr).
yeccpars2_82(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_82_(Stack),
'yeccgoto_\'MultiplicativeExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_83(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_83_(Stack),
'yeccgoto_\'MultiplicativeExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_84(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_84_(Stack),
'yeccgoto_\'MultiplicativeExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_85(S, '*', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 79, Ss, Stack, T, Ts, Tzr);
yeccpars2_85(S, 'div', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 80, Ss, Stack, T, Ts, Tzr);
yeccpars2_85(S, mod, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 81, Ss, Stack, T, Ts, Tzr);
yeccpars2_85(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_85_(Stack),
'yeccgoto_\'AdditiveExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_87(S, '!=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 88, Ss, Stack, T, Ts, Tzr);
yeccpars2_87(S, '=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 89, Ss, Stack, T, Ts, Tzr);
yeccpars2_87(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_87_(Stack),
'yeccgoto_\'AndExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_90(S, '<', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 91, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(S, '<=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 92, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(S, '>', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 93, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(S, '>=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 94, Ss, Stack, T, Ts, Tzr);
yeccpars2_90(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_90_(Stack),
'yeccgoto_\'EqualityExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_95(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_95(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_95(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_95_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_96(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_96(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_96(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_96_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_97(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_97(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_97(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_97_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_98(S, '+', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 75, Ss, Stack, T, Ts, Tzr);
yeccpars2_98(S, '-', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 76, Ss, Stack, T, Ts, Tzr);
yeccpars2_98(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_98_(Stack),
'yeccgoto_\'RelationalExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_99(S, '<', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 91, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(S, '<=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 92, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(S, '>', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 93, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(S, '>=', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 94, Ss, Stack, T, Ts, Tzr);
yeccpars2_99(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_99_(Stack),
'yeccgoto_\'EqualityExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_100(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_100_(Stack),
'yeccgoto_\'FilterExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_103(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_103(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_103(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_103_(Stack),
'yeccgoto_\'PathExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_104(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 67, Ss, Stack, T, Ts, Tzr);
yeccpars2_104(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 68, Ss, Stack, T, Ts, Tzr);
yeccpars2_104(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_104_(Stack),
'yeccgoto_\'PathExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_105(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_|Nss] = Ss,
NewStack = yeccpars2_105_(Stack),
'yeccgoto_\'Step\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_107(S, 'and', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 86, Ss, Stack, T, Ts, Tzr);
yeccpars2_107(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_107_(Stack),
'yeccgoto_\'OrExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
yeccpars2_108(S, '(', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 23, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '.', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '..', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '/', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 27, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '//', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, '@', Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 29, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, axis, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 30, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, function_name, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 31, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, literal, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 32, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, number, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, var_reference, Ss, Stack, T, Ts, Tzr) ->
yeccpars1(S, 38, Ss, Stack, T, Ts, Tzr);
yeccpars2_108(S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_54(S, Cat, Ss, Stack, T, Ts, Tzr).
yeccpars2_109(_S, Cat, Ss, Stack, T, Ts, Tzr) ->
[_,_|Nss] = Ss,
NewStack = yeccpars2_109_(Stack),
'yeccgoto_\'UnionExpr\''(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr).
'yeccgoto_\'<ArgumentList>\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_49(49, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'<ArgumentMember>\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_48(48, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'<PredicateList>\''(9=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_105(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateList>\''(55=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_58(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateList>\''(64=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_65(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'<PredicateMember>\''(9, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_57(57, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateMember>\''(55, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_57(57, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'<PredicateMember>\''(64, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_57(57, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedAbsoluteLocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedRelativeLocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbbreviatedStep\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(67=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(68=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbbreviatedStep\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AbsoluteLocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AbsoluteLocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AdditiveExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_98(98, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_97(97, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_96(96, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_95(95, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AdditiveExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_18(18, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'AndExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_17(17, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'AndExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_107(107, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Argument\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_47(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Argument\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_53(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'EqualityExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_87(87, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'EqualityExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Expr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_15(15, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_73(73, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_46(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_46(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Expr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_61(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'FilterExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FilterExpr\''(108, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_14(14, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'FunctionCall\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'FunctionCall\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'LocationPath\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'LocationPath\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_12(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'MultiplicativeExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_85(85, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_77(77, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplicativeExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_11(11, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'MultiplyOperator\''(11, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(78, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplyOperator\''(77, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(78, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'MultiplyOperator\''(85, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_0(78, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'NameTest\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(54=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(67=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(68=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NameTest\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_10(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'NodeTest\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(27, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(28, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(54, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_55(55, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(67, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(68, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(101, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(102, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'NodeTest\''(108, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'OrExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'OrExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'PathExpr\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PathExpr\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_109(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Predicate\''(9=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(14=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_100(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(55=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(57=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_63(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Predicate\''(64=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_56(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'PredicateExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_60(60, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'PrimaryExpr\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'PrimaryExpr\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'RelationalExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_99(99, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_90(90, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelationalExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_5(5, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'RelativeLocationPath\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(27, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_71(71, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(28, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_66(66, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(101, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_104(104, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(102, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_103(103, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'RelativeLocationPath\''(108, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'Step\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(27=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(28=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(67=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_70(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(68=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_69(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(101=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(102=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'Step\''(108=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_3(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'UnaryExpr\''(0=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(23=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(24=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_72(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(45=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(52=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(59=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(75=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(76=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(78=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_84(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(80=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_83(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(81=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_82(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(86=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(88=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(89=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(91=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(92=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(93=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(94=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnaryExpr\''(106=_S, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr).
'yeccgoto_\'UnionExpr\''(0, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(23, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(24, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(45, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(52, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(59, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(75, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(76, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(78, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(80, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(81, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(86, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(88, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(89, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(91, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(92, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(93, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(94, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr);
'yeccgoto_\'UnionExpr\''(106, Cat, Ss, Stack, T, Ts, Tzr) ->
yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr).
-compile({inline,yeccpars2_4_/1}).
-file("xmerl_xpath_parse.yrl", 96).
yeccpars2_4_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ path , rel , __1 }
end | __Stack].
-compile({inline,yeccpars2_9_/1}).
-file("xmerl_xpath_parse.yrl", 122).
yeccpars2_9_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ step , { child , __1 , [ ] } }
end | __Stack].
-compile({inline,yeccpars2_19_/1}).
-file("xmerl_xpath_parse.yrl", 97).
yeccpars2_19_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ path , abs , __1 }
end | __Stack].
-compile({inline,yeccpars2_20_/1}).
-file("xmerl_xpath_parse.yrl", 124).
yeccpars2_20_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ abbrev_step , __1 }
end | __Stack].
-compile({inline,yeccpars2_27_/1}).
-file("xmerl_xpath_parse.yrl", 101).
yeccpars2_27_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
'/'
end | __Stack].
-compile({inline,yeccpars2_32_/1}).
-file("xmerl_xpath_parse.yrl", 175).
yeccpars2_32_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ literal , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_33_/1}).
-file("xmerl_xpath_parse.yrl", 293).
yeccpars2_33_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ name , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_35_/1}).
-file("xmerl_xpath_parse.yrl", 176).
yeccpars2_35_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ number , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_36_/1}).
-file("xmerl_xpath_parse.yrl", 292).
yeccpars2_36_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ prefix_test , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_38_/1}).
-file("xmerl_xpath_parse.yrl", 173).
yeccpars2_38_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ variable_reference , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_39_/1}).
-file("xmerl_xpath_parse.yrl", 291).
yeccpars2_39_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
{ wildcard , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_42_/1}).
-file("xmerl_xpath_parse.yrl", 144).
yeccpars2_42_(__Stack0) ->
[__4,__3,__2,__1 | __Stack] = __Stack0,
[begin
{ processing_instruction , value ( __3 ) }
end | __Stack].
-compile({inline,yeccpars2_44_/1}).
-file("xmerl_xpath_parse.yrl", 142).
yeccpars2_44_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ node_type , value ( __1 ) }
end | __Stack].
-compile({inline,yeccpars2_47_/1}).
-file("xmerl_xpath_parse.yrl", 189).
yeccpars2_47_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
[ __1 ]
end | __Stack].
-compile({inline,yeccpars2_48_/1}).
-file("xmerl_xpath_parse.yrl", 185).
yeccpars2_48_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
lists : reverse ( __1 )
end | __Stack].
-compile({inline,yeccpars2_50_/1}).
-file("xmerl_xpath_parse.yrl", 181).
yeccpars2_50_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ function_call , value ( __1 ) , [ ] }
end | __Stack].
-compile({inline,yeccpars2_51_/1}).
-file("xmerl_xpath_parse.yrl", 183).
yeccpars2_51_(__Stack0) ->
[__4,__3,__2,__1 | __Stack] = __Stack0,
[begin
{ function_call , value ( __1 ) , __3 }
end | __Stack].
-compile({inline,yeccpars2_53_/1}).
-file("xmerl_xpath_parse.yrl", 188).
yeccpars2_53_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
[ __3 | __1 ]
end | __Stack].
-compile({inline,yeccpars2_55_/1}).
-file("xmerl_xpath_parse.yrl", 114).
yeccpars2_55_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ step , { value ( __1 ) , __3 , [ ] } }
end | __Stack].
-compile({inline,yeccpars2_56_/1}).
-file("xmerl_xpath_parse.yrl", 132).
yeccpars2_56_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
[ __1 ]
end | __Stack].
-compile({inline,yeccpars2_57_/1}).
-file("xmerl_xpath_parse.yrl", 127).
yeccpars2_57_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
lists : reverse ( __1 )
end | __Stack].
-compile({inline,yeccpars2_58_/1}).
-file("xmerl_xpath_parse.yrl", 112).
yeccpars2_58_(__Stack0) ->
[__4,__3,__2,__1 | __Stack] = __Stack0,
[begin
{ step , { value ( __1 ) , __3 , __4 } }
end | __Stack].
-compile({inline,yeccpars2_62_/1}).
-file("xmerl_xpath_parse.yrl", 148).
yeccpars2_62_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ pred , __2 }
end | __Stack].
-compile({inline,yeccpars2_63_/1}).
-file("xmerl_xpath_parse.yrl", 131).
yeccpars2_63_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
[ __2 | __1 ]
end | __Stack].
-compile({inline,yeccpars2_64_/1}).
-file("xmerl_xpath_parse.yrl", 118).
yeccpars2_64_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ step , { attribute , __2 , [ ] } }
end | __Stack].
-compile({inline,yeccpars2_65_/1}).
-file("xmerl_xpath_parse.yrl", 116).
yeccpars2_65_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ step , { value ( __1 ) , __2 , __3 } }
end | __Stack].
-compile({inline,yeccpars2_66_/1}).
-file("xmerl_xpath_parse.yrl", 155).
yeccpars2_66_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ '//' , __2 }
end | __Stack].
-compile({inline,yeccpars2_69_/1}).
-file("xmerl_xpath_parse.yrl", 159).
yeccpars2_69_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ __1 , '//' , __3 }
end | __Stack].
-compile({inline,yeccpars2_70_/1}).
-file("xmerl_xpath_parse.yrl", 107).
yeccpars2_70_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ refine , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_71_/1}).
-file("xmerl_xpath_parse.yrl", 100).
yeccpars2_71_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
__2
end | __Stack].
-compile({inline,yeccpars2_72_/1}).
-file("xmerl_xpath_parse.yrl", 262).
yeccpars2_72_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ negative , __2 }
end | __Stack].
-compile({inline,yeccpars2_74_/1}).
-file("xmerl_xpath_parse.yrl", 174).
yeccpars2_74_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
__2
end | __Stack].
-compile({inline,yeccpars2_77_/1}).
-file("xmerl_xpath_parse.yrl", 247).
yeccpars2_77_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , '-' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_79_/1}).
-file("xmerl_xpath_parse.yrl", 287).
yeccpars2_79_(__Stack0) ->
[__1 | __Stack] = __Stack0,
[begin
'*'
end | __Stack].
-compile({inline,yeccpars2_82_/1}).
-file("xmerl_xpath_parse.yrl", 257).
yeccpars2_82_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , mod , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_83_/1}).
-file("xmerl_xpath_parse.yrl", 255).
yeccpars2_83_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , 'div' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_84_/1}).
-file("xmerl_xpath_parse.yrl", 253).
yeccpars2_84_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , __2 , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_85_/1}).
-file("xmerl_xpath_parse.yrl", 245).
yeccpars2_85_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ arith , '+' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_87_/1}).
-file("xmerl_xpath_parse.yrl", 221).
yeccpars2_87_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ bool , 'and' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_90_/1}).
-file("xmerl_xpath_parse.yrl", 226).
yeccpars2_90_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_95_/1}).
-file("xmerl_xpath_parse.yrl", 239).
yeccpars2_95_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '>=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_96_/1}).
-file("xmerl_xpath_parse.yrl", 235).
yeccpars2_96_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '>' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_97_/1}).
-file("xmerl_xpath_parse.yrl", 237).
yeccpars2_97_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '<=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_98_/1}).
-file("xmerl_xpath_parse.yrl", 233).
yeccpars2_98_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '<' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_99_/1}).
-file("xmerl_xpath_parse.yrl", 228).
yeccpars2_99_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ comp , '!=' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_100_/1}).
-file("xmerl_xpath_parse.yrl", 209).
yeccpars2_100_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ path , filter , { __1 , __2 } }
end | __Stack].
-compile({inline,yeccpars2_103_/1}).
-file("xmerl_xpath_parse.yrl", 205).
yeccpars2_103_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ __1 , '//' , __3 }
end | __Stack].
-compile({inline,yeccpars2_104_/1}).
-file("xmerl_xpath_parse.yrl", 204).
yeccpars2_104_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ refine , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_105_/1}).
-file("xmerl_xpath_parse.yrl", 120).
yeccpars2_105_(__Stack0) ->
[__2,__1 | __Stack] = __Stack0,
[begin
{ step , { child , __1 , __2 } }
end | __Stack].
-compile({inline,yeccpars2_107_/1}).
-file("xmerl_xpath_parse.yrl", 215).
yeccpars2_107_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ bool , 'or' , __1 , __3 }
end | __Stack].
-compile({inline,yeccpars2_109_/1}).
-file("xmerl_xpath_parse.yrl", 198).
yeccpars2_109_(__Stack0) ->
[__3,__2,__1 | __Stack] = __Stack0,
[begin
{ path , union , { __1 , __3 } }
end | __Stack].
-file("xmerl_xpath_parse.yrl", 312).
|
ed7bcfdda95257a369cc34dc633fd8fea11152203d5e27d1b07eca9fe01de2e4 | samsergey/formica | formal.rkt | #lang racket/base
;;______________________________________________________________
;; ______
;; ( // _____ ____ . __ __
;; ~//~ ((_)// // / / // ((_ ((_/_
;; (_//
;;..............................................................
; Provides formal functions.
;;;=============================================================
(require racket/match
racket/contract
racket/syntax
racket/provide-syntax
racket/require-syntax
(for-syntax racket/base
racket/match
racket/list
racket/syntax
"../tools/tags.rkt"
"hold.rkt")
(for-syntax (for-syntax racket/base racket/syntax))
(prefix-in part: "../syntax/partial-app.rkt")
"../tools/tags.rkt"
"hold.rkt"
"../types/infix-arrow.rkt"
"../types/type-checking.rkt")
(provide
(contract-out
(formals (parameter/c (listof predicate/c)))
(formal? predicate/c)
(n/f-list? predicate/c)
(n/f-pair? predicate/c))
define-formal
formal
formal-out
#;formal-in)
;;--------------------------------------------------------------------------------
;; The parameter which keeps track of functions declared to be formal
;;--------------------------------------------------------------------------------
(define formals (make-parameter '()))
(define (add-to-formals p)
(define (include x s)
(match s
['() (list x)]
[(and s (cons h t)) (if (equal? (object-name x)
(object-name h))
s
(cons h (include x t)))]))
(formals (include p (formals))))
;;--------------------------------------------------------------------------------
;; Helper function which creates a list of rules for match expander f:
;;--------------------------------------------------------------------------------
(define-for-syntax (make-match-rules id id: n)
(with-syntax ([id* id]
[id:* id:])
(match n
[(? integer? n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list n 'x))])
(list #'[(id:* tmp ...) (list (quote id*) tmp ...)]))]
[(list 'arity-at-least n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list (add1 n) 'x))])
(list #'[(id:* tmp ... (... ...)) (list (quote id*) tmp ... (... ...))]))]
[(cons n m) (append (make-match-rules id id: n) (make-match-rules id id: m))]
[else '()])))
;;--------------------------------------------------------------------------------
;; Helper function which creates a list of rules for the predicate f?
;;--------------------------------------------------------------------------------
(define-for-syntax (make-predicate-rules id n)
(with-syntax ([id* id])
(match n
[(? integer? n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list n 'x))])
(list #'[(id* tmp ...) #t]))]
[(list 'arity-at-least n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list (add1 n) 'x))])
(list #'[(id* tmp ... (... ...)) #t]))]
[(cons n m) (append (make-predicate-rules id n) (make-predicate-rules id m))]
[else '()])))
;;--------------------------------------------------------------------------------
;; The definition of formal functions
;;--------------------------------------------------------------------------------
(define-syntax (define-formal stx)
(syntax-case stx (.. ?)
[(_ (id n))
; compile-time syntax check
(unless (symbol? (syntax-e #'id))
(raise-syntax-error 'define-formal
"expected a symbol as a formal function name"
#'(id n)))
(let* ([str (symbol->string (syntax-e #'id))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))]
[dn (syntax->datum #'n)])
(with-syntax*
([id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)]
[(match-rules ...) (make-match-rules #'id #'id dn)]
[(predicate-rules ...) (make-predicate-rules #'id dn)])
#'(begin
; declaration-time syntax check
(unless (procedure-arity? n)
(raise-syntax-error 'define-formal
"invalid arity specification"
#'(id n)))
(define-match-expander id
; the match expander (f: ...)
(syntax-rules ()
match-rules ...
[(id x (... ...)) (list (quote id) x (... ...))])
; formal function outside the match form
(syntax-id-rules ()
[(id x (... ...)) (part:#%app (hold 'id n) x (... ...))]
[id (hold 'id n)]))
(define-syntax (id: stx)
; the contracts for formal applications
(syntax-case stx (.. ?)
[(id: c (... ...) (? x (... ...)))
(with-syntax ([((oc (... ...)) (... ...))
(add-optional (syntax->list #'(c (... ...)))
(syntax->list #'(x (... ...))))])
#'(procedure-rename
(or/c (id: oc (... ...)) (... ...))
(string->symbol (format "~a" '(id: c (... ...) (? x (... ...)))))))]
[(id: c ..) #'(procedure-rename
(cons/c 'id (listof c))
(string->symbol (format "~a" '(id: c ..) )))]
[(id: c (... ...) x ..) #'(procedure-rename
(foldr cons/c (listof x) (list 'id c (... ...)))
(string->symbol (format "~a" '(id: c (... ...) x ..))))]
[(id: c (... ...)) #'(procedure-rename
(list/c 'id c (... ...))
(string->symbol (format "~a" '(id: c (... ...)))))]))
; the predicate for formal applications
(define id?
(match-lambda predicate-rules ... (_ #f)))
; new predicate in the list of functions declared to be formal
(add-to-formals id?))))]
[(_ (id #:contract (cntr ...)))
; compile-time syntax check
(unless (symbol? (syntax-e #'id))
(raise-syntax-error 'define-formal
"expected a symbol as a formal function name"
(syntax-e #'id)))
(let* ([str (symbol->string (syntax-e #'id))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax*
([id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)]
[f #'(contract (.->. cntr ... id?) (hold 'id) 'id 'id 'id #f)])
#'(begin
(define-syntax (id: stx)
; the contracts for formal applications
(syntax-case stx (.. ?)
[(id: c (... ...) (? x (... ...)))
(with-syntax ([((oc (... ...)) (... ...))
(add-optional (syntax->list #'(c (... ...)))
(syntax->list #'(x (... ...))))])
#'(procedure-rename
(or/c (id: oc (... ...)) (... ...))
(string->symbol (format "~a" '(id: c (... ...) (? x (... ...)))))))]
[(id: c ..) #'(procedure-rename
(cons/c 'id (listof c))
(string->symbol (format "~a" '(id: c ..) )))]
[(id: c (... ...) x ..) #'(procedure-rename
(foldr cons/c (listof x) (list 'id c (... ...)))
(string->symbol (format "~a" '(id: c (... ...) x ..))))]
[(id: c (... ...)) #'(procedure-rename
(list/c 'id c (... ...))
(string->symbol (format "~a" '(id: c (... ...)))))]))
(define (id? x)
; the predicate for formal applications
(is x (id: cntr ...)))
(define-match-expander id
; the match expander (f: ...)
(syntax-rules ()
[(id x (... ...)) (list (quote id) x (... ...))])
; formal function outside the match form
(syntax-id-rules ()
[(id x (... ...)) (part:#%app f x (... ...))]
[id f]))
; new predicate in the list of functions declared to be formal
(add-to-formals id?))))]
[(_ id)
; compile-time syntax check
(unless (symbol? (syntax-e #'id))
(raise-syntax-error 'define-formal
"expected a symbol as a formal function name"
(syntax-e #'id)))
(let* ([str (symbol->string (syntax-e #'id))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax ([id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)])
#'(begin
(define-match-expander id
; the match expander (f: ...)
(syntax-rules ()
[(id x (... ...)) (list (quote id) x (... ...))])
; formal function outside the match form
(syntax-id-rules ()
[(id x (... ...)) (part:#%app (hold 'id) x (... ...))]
[id (hold 'id)]))
(define-syntax (id: stx)
; the contracts for formal applications
(syntax-case stx (.. ?)
[(id: c (... ...) (? x (... ...)))
(with-syntax ([((oc (... ...)) (... ...))
(add-optional (syntax->list #'(c (... ...)))
(syntax->list #'(x (... ...))))])
#'(procedure-rename
(or/c (id: oc (... ...)) (... ...))
(string->symbol (format "~a" '(id: c (... ...) (? x (... ...)))))))]
[(id: c ..) #'(procedure-rename
(cons/c 'id (listof c))
(string->symbol (format "~a" '(id: c ..) )))]
[(id: c (... ...) x ..) #'(procedure-rename
(foldr cons/c (listof x) (list 'id c (... ...)))
(string->symbol (format "~a" '(id: c (... ...) x ..))))]
[(id: c (... ...)) #'(procedure-rename
(list/c 'id c (... ...))
(string->symbol (format "~a" '(id: c (... ...)))))]))
; the predicate for formal applications
(define id?
(match-lambda
[(cons 'id _) #t]
[_ #f]))
; new predicate in the list of functions declared to be formal
(add-to-formals id?))))]
[(_ ids ...) #'(begin (define-formal ids) ...)]))
(define-for-syntax (add-optional s xlist)
(reverse
(for/fold ([res (list s)]) ([x (in-list xlist)])
(cons (append (car res) (list x)) res))))
;;--------------------------------------------------------------------------------
;; The predicate that returns #t for the formal applications
;;--------------------------------------------------------------------------------
(define (formal? x)
(ormap (λ(f)(f x)) (formals)))
;;--------------------------------------------------------------------------------
;; The match expander for general formal application
;; This expander may return the head of the formal application
;;--------------------------------------------------------------------------------
(define-match-expander formal
(syntax-rules ()
[(formal (h x ...)) (? formal? (list h x ...))]))
;;--------------------------------------------------------------------------------
;; The predicate that returns #t for lists which are not formal applications
;;--------------------------------------------------------------------------------
(define (n/f-list? x)
(and (list? x)
(not (formal? x))))
;;--------------------------------------------------------------------------------
;; The predicate that returns #t for pairs which are not formal applications
;;--------------------------------------------------------------------------------
(define (n/f-pair? x)
(and (pair? x)
(not (formal? x))))
;;--------------------------------------------------------------------------------
;; The formal-out form
;;--------------------------------------------------------------------------------
(require (for-syntax racket/provide-transform
racket/require-transform))
(define-for-syntax (make-out-combination stx)
(let* ([str (symbol->string (syntax-e stx))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax ([id stx]
[id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)])
#'(combine-out id id? id:))))
(define-provide-syntax (formal-out stx)
(syntax-case stx ()
[(_ id) (with-syntax ([o (make-out-combination #'id)]
[frm #'formals])
#'(combine-out o frm))]
[(_ ids ...) (with-syntax ([(o ...) (map make-out-combination (syntax->list #'(ids ...)))]
[frm #'formals])
#'(combine-out o ... frm))]))
;;--------------------------------------------------------------------------------
;; The formal-in form
;; To be done
;;--------------------------------------------------------------------------------
( define - for - syntax ( ( make - in - combination m ) stx )
(let* ([str (symbol->string (syntax-e stx))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax ([mod m] [id stx]
[id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)])
#'(only-in mod id id? id:))))
( define - require - syntax ( formal - in stx )
(syntax-case stx ()
[(_ m id) ((make-in-combination #'m) #'id)]
[(_ m ids ...) (with-syntax ([(i ...)
(map (make-in-combination #'m)
(syntax->list #'(ids ...)))])
#'(combine-in i ...))]))
| null | https://raw.githubusercontent.com/samsergey/formica/b4410b4b6da63ecb15b4c25080951a7ba4d90d2c/private/formal/formal.rkt | racket | ______________________________________________________________
______
( // _____ ____ . __ __
~//~ ((_)// // / / // ((_ ((_/_
(_//
..............................................................
Provides formal functions.
=============================================================
formal-in)
--------------------------------------------------------------------------------
The parameter which keeps track of functions declared to be formal
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Helper function which creates a list of rules for match expander f:
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Helper function which creates a list of rules for the predicate f?
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
The definition of formal functions
--------------------------------------------------------------------------------
compile-time syntax check
declaration-time syntax check
the match expander (f: ...)
formal function outside the match form
the contracts for formal applications
the predicate for formal applications
new predicate in the list of functions declared to be formal
compile-time syntax check
the contracts for formal applications
the predicate for formal applications
the match expander (f: ...)
formal function outside the match form
new predicate in the list of functions declared to be formal
compile-time syntax check
the match expander (f: ...)
formal function outside the match form
the contracts for formal applications
the predicate for formal applications
new predicate in the list of functions declared to be formal
--------------------------------------------------------------------------------
The predicate that returns #t for the formal applications
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
The match expander for general formal application
This expander may return the head of the formal application
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
The predicate that returns #t for lists which are not formal applications
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
The predicate that returns #t for pairs which are not formal applications
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
The formal-out form
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
The formal-in form
To be done
-------------------------------------------------------------------------------- | #lang racket/base
(require racket/match
racket/contract
racket/syntax
racket/provide-syntax
racket/require-syntax
(for-syntax racket/base
racket/match
racket/list
racket/syntax
"../tools/tags.rkt"
"hold.rkt")
(for-syntax (for-syntax racket/base racket/syntax))
(prefix-in part: "../syntax/partial-app.rkt")
"../tools/tags.rkt"
"hold.rkt"
"../types/infix-arrow.rkt"
"../types/type-checking.rkt")
(provide
(contract-out
(formals (parameter/c (listof predicate/c)))
(formal? predicate/c)
(n/f-list? predicate/c)
(n/f-pair? predicate/c))
define-formal
formal
formal-out
(define formals (make-parameter '()))
(define (add-to-formals p)
(define (include x s)
(match s
['() (list x)]
[(and s (cons h t)) (if (equal? (object-name x)
(object-name h))
s
(cons h (include x t)))]))
(formals (include p (formals))))
(define-for-syntax (make-match-rules id id: n)
(with-syntax ([id* id]
[id:* id:])
(match n
[(? integer? n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list n 'x))])
(list #'[(id:* tmp ...) (list (quote id*) tmp ...)]))]
[(list 'arity-at-least n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list (add1 n) 'x))])
(list #'[(id:* tmp ... (... ...)) (list (quote id*) tmp ... (... ...))]))]
[(cons n m) (append (make-match-rules id id: n) (make-match-rules id id: m))]
[else '()])))
(define-for-syntax (make-predicate-rules id n)
(with-syntax ([id* id])
(match n
[(? integer? n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list n 'x))])
(list #'[(id* tmp ...) #t]))]
[(list 'arity-at-least n)
(with-syntax ([(tmp ...) (generate-temporaries (make-list (add1 n) 'x))])
(list #'[(id* tmp ... (... ...)) #t]))]
[(cons n m) (append (make-predicate-rules id n) (make-predicate-rules id m))]
[else '()])))
(define-syntax (define-formal stx)
(syntax-case stx (.. ?)
[(_ (id n))
(unless (symbol? (syntax-e #'id))
(raise-syntax-error 'define-formal
"expected a symbol as a formal function name"
#'(id n)))
(let* ([str (symbol->string (syntax-e #'id))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))]
[dn (syntax->datum #'n)])
(with-syntax*
([id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)]
[(match-rules ...) (make-match-rules #'id #'id dn)]
[(predicate-rules ...) (make-predicate-rules #'id dn)])
#'(begin
(unless (procedure-arity? n)
(raise-syntax-error 'define-formal
"invalid arity specification"
#'(id n)))
(define-match-expander id
(syntax-rules ()
match-rules ...
[(id x (... ...)) (list (quote id) x (... ...))])
(syntax-id-rules ()
[(id x (... ...)) (part:#%app (hold 'id n) x (... ...))]
[id (hold 'id n)]))
(define-syntax (id: stx)
(syntax-case stx (.. ?)
[(id: c (... ...) (? x (... ...)))
(with-syntax ([((oc (... ...)) (... ...))
(add-optional (syntax->list #'(c (... ...)))
(syntax->list #'(x (... ...))))])
#'(procedure-rename
(or/c (id: oc (... ...)) (... ...))
(string->symbol (format "~a" '(id: c (... ...) (? x (... ...)))))))]
[(id: c ..) #'(procedure-rename
(cons/c 'id (listof c))
(string->symbol (format "~a" '(id: c ..) )))]
[(id: c (... ...) x ..) #'(procedure-rename
(foldr cons/c (listof x) (list 'id c (... ...)))
(string->symbol (format "~a" '(id: c (... ...) x ..))))]
[(id: c (... ...)) #'(procedure-rename
(list/c 'id c (... ...))
(string->symbol (format "~a" '(id: c (... ...)))))]))
(define id?
(match-lambda predicate-rules ... (_ #f)))
(add-to-formals id?))))]
[(_ (id #:contract (cntr ...)))
(unless (symbol? (syntax-e #'id))
(raise-syntax-error 'define-formal
"expected a symbol as a formal function name"
(syntax-e #'id)))
(let* ([str (symbol->string (syntax-e #'id))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax*
([id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)]
[f #'(contract (.->. cntr ... id?) (hold 'id) 'id 'id 'id #f)])
#'(begin
(define-syntax (id: stx)
(syntax-case stx (.. ?)
[(id: c (... ...) (? x (... ...)))
(with-syntax ([((oc (... ...)) (... ...))
(add-optional (syntax->list #'(c (... ...)))
(syntax->list #'(x (... ...))))])
#'(procedure-rename
(or/c (id: oc (... ...)) (... ...))
(string->symbol (format "~a" '(id: c (... ...) (? x (... ...)))))))]
[(id: c ..) #'(procedure-rename
(cons/c 'id (listof c))
(string->symbol (format "~a" '(id: c ..) )))]
[(id: c (... ...) x ..) #'(procedure-rename
(foldr cons/c (listof x) (list 'id c (... ...)))
(string->symbol (format "~a" '(id: c (... ...) x ..))))]
[(id: c (... ...)) #'(procedure-rename
(list/c 'id c (... ...))
(string->symbol (format "~a" '(id: c (... ...)))))]))
(define (id? x)
(is x (id: cntr ...)))
(define-match-expander id
(syntax-rules ()
[(id x (... ...)) (list (quote id) x (... ...))])
(syntax-id-rules ()
[(id x (... ...)) (part:#%app f x (... ...))]
[id f]))
(add-to-formals id?))))]
[(_ id)
(unless (symbol? (syntax-e #'id))
(raise-syntax-error 'define-formal
"expected a symbol as a formal function name"
(syntax-e #'id)))
(let* ([str (symbol->string (syntax-e #'id))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax ([id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)])
#'(begin
(define-match-expander id
(syntax-rules ()
[(id x (... ...)) (list (quote id) x (... ...))])
(syntax-id-rules ()
[(id x (... ...)) (part:#%app (hold 'id) x (... ...))]
[id (hold 'id)]))
(define-syntax (id: stx)
(syntax-case stx (.. ?)
[(id: c (... ...) (? x (... ...)))
(with-syntax ([((oc (... ...)) (... ...))
(add-optional (syntax->list #'(c (... ...)))
(syntax->list #'(x (... ...))))])
#'(procedure-rename
(or/c (id: oc (... ...)) (... ...))
(string->symbol (format "~a" '(id: c (... ...) (? x (... ...)))))))]
[(id: c ..) #'(procedure-rename
(cons/c 'id (listof c))
(string->symbol (format "~a" '(id: c ..) )))]
[(id: c (... ...) x ..) #'(procedure-rename
(foldr cons/c (listof x) (list 'id c (... ...)))
(string->symbol (format "~a" '(id: c (... ...) x ..))))]
[(id: c (... ...)) #'(procedure-rename
(list/c 'id c (... ...))
(string->symbol (format "~a" '(id: c (... ...)))))]))
(define id?
(match-lambda
[(cons 'id _) #t]
[_ #f]))
(add-to-formals id?))))]
[(_ ids ...) #'(begin (define-formal ids) ...)]))
(define-for-syntax (add-optional s xlist)
(reverse
(for/fold ([res (list s)]) ([x (in-list xlist)])
(cons (append (car res) (list x)) res))))
(define (formal? x)
(ormap (λ(f)(f x)) (formals)))
(define-match-expander formal
(syntax-rules ()
[(formal (h x ...)) (? formal? (list h x ...))]))
(define (n/f-list? x)
(and (list? x)
(not (formal? x))))
(define (n/f-pair? x)
(and (pair? x)
(not (formal? x))))
(require (for-syntax racket/provide-transform
racket/require-transform))
(define-for-syntax (make-out-combination stx)
(let* ([str (symbol->string (syntax-e stx))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax ([id stx]
[id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)])
#'(combine-out id id? id:))))
(define-provide-syntax (formal-out stx)
(syntax-case stx ()
[(_ id) (with-syntax ([o (make-out-combination #'id)]
[frm #'formals])
#'(combine-out o frm))]
[(_ ids ...) (with-syntax ([(o ...) (map make-out-combination (syntax->list #'(ids ...)))]
[frm #'formals])
#'(combine-out o ... frm))]))
( define - for - syntax ( ( make - in - combination m ) stx )
(let* ([str (symbol->string (syntax-e stx))]
[str? (string->symbol (string-append str "?"))]
[str: (string->symbol (string-append str ":"))])
(with-syntax ([mod m] [id stx]
[id? (datum->syntax #'id str? #'id)]
[id: (datum->syntax #'id str: #'id)])
#'(only-in mod id id? id:))))
( define - require - syntax ( formal - in stx )
(syntax-case stx ()
[(_ m id) ((make-in-combination #'m) #'id)]
[(_ m ids ...) (with-syntax ([(i ...)
(map (make-in-combination #'m)
(syntax->list #'(ids ...)))])
#'(combine-in i ...))]))
|
f117cabc19f93a10e5b64cbc24d079971fc97c913a2afbacbe7c9e2147b69dd1 | unnohideyuki/bunny | sample151.hs | main = do
print $ LT == LT
print $ LT == EQ
print $ LT == GT
print $ EQ == LT
print $ EQ == EQ
print $ EQ == GT
print $ GT == LT
print $ GT == EQ
print $ GT == GT
print $ LT /= LT
print $ LT /= EQ
print $ LT /= GT
print $ EQ /= LT
print $ EQ /= EQ
print $ EQ /= GT
print $ GT /= LT
print $ GT /= EQ
print $ GT /= GT
| null | https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample151.hs | haskell | main = do
print $ LT == LT
print $ LT == EQ
print $ LT == GT
print $ EQ == LT
print $ EQ == EQ
print $ EQ == GT
print $ GT == LT
print $ GT == EQ
print $ GT == GT
print $ LT /= LT
print $ LT /= EQ
print $ LT /= GT
print $ EQ /= LT
print $ EQ /= EQ
print $ EQ /= GT
print $ GT /= LT
print $ GT /= EQ
print $ GT /= GT
| |
0fce6d1960d8317eadff49b13665d3b7f24853ae8cc6df8afdc5f5e97dc91ced | meain/evil-textobj-tree-sitter | textobjects.scm | (class_declaration
body: (class_body . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(class_declaration
body: (enum_class_body . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(function_declaration
body: (function_body . "{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
(lambda_literal
("{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
(call_suffix
(value_arguments . "(" . (_) @call.inner._start (_)? @call.inner._end . ")"
)) @call.outer
(value_argument
value: ((_) @parameter.inner)) @parameter.outer
(comment) @comment.outer
(multiline_comment) @comment.outer
| null | https://raw.githubusercontent.com/meain/evil-textobj-tree-sitter/866928d3ee6b4623addc2324f2eebe55e95dd778/queries/swift/textobjects.scm | scheme | (class_declaration
body: (class_body . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(class_declaration
body: (enum_class_body . "{" . (_) @class.inner._start @class.inner._end (_)? @class.inner._end . "}"
)) @class.outer
(function_declaration
body: (function_body . "{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
(lambda_literal
("{" . (_) @function.inner._start @function.inner._end (_)? @function.inner._end . "}"
)) @function.outer
(call_suffix
(value_arguments . "(" . (_) @call.inner._start (_)? @call.inner._end . ")"
)) @call.outer
(value_argument
value: ((_) @parameter.inner)) @parameter.outer
(comment) @comment.outer
(multiline_comment) @comment.outer
| |
72087b1da32a4694a9831d3fd3394a3fde7af9444773abf3bd6d12875531d200 | mzp/scheme-abc | codegen.ml | open Base
open Ast
open Node
open Swflib
open MethodType
module QName = struct
let join xs =
String.concat "." xs
let of_stmt_name =
function
`Public {Node.value=(ns,name)} ->
`QName (`Namespace (join ns),name)
| `Internal {Node.value=(ns,name)} ->
`QName (`PackageInternalNamespace (join ns),name)
let make ns x =
`QName ((`Namespace (join ns)),x)
let of_node {Node.value=(ns,name)} =
make ns name
let make_global name =
make [] name
end
* { 6 Builtin operator }
let builtin = [
"+" , ([`Add_i],2);
"-" , ([`Subtract_i],2);
"*" , ([`Multiply_i],2);
"/" , ([`Divide;`Convert_i],2);
"+.", ([`Add],2);
"-.", ([`Subtract],2);
"*.", ([`Multiply],2);
"/." , ([`Divide],2);
"remainder", ([`Modulo],2);
"=" , ([`Equals],2);
">" , ([`GreaterThan],2);
">=" , ([`GreaterEquals],2);
"<" , ([`LessThan],2);
"<=" , ([`LessEquals],2)
]
let is_builtin name args =
try
let _,n =
List.assoc name builtin in
n = List.length args
with Not_found ->
false
let rec generate_expr expr =
let gen e =
generate_expr e in
match expr with
`Bool {value = true} ->
[`PushTrue]
| `Bool {value = false} ->
[`PushFalse]
| `Float {value = v} ->
[`PushDouble v]
| `String {value = str} ->
[`PushString str]
| `Int {value = n} when 0 <= n && n <= 0x7F ->
[`PushByte n]
| `Int {value = n} ->
[`PushInt n]
| `Block [] ->
[`PushUndefined]
| `Array xs ->
List.concat [
HList.concat_map gen xs;
[`NewArray (List.length xs)]
]
| `Block xs ->
List.concat @@ interperse [`Pop] @@ (List.map gen xs)
| `New (name,args) ->
let qname =
QName.of_node name in
List.concat [
[`FindPropStrict qname];
HList.concat_map gen args;
[`ConstructProp (qname, List.length args)]]
| `Lambda (args,body) ->
let body' =
generate_expr body in
let m = {
MethodType.empty with
method_name = QName.make_global "";
params = List.map (const 0) args;
code = body' @ [`ReturnValue] } in
[`NewFunction m]
| `Var name ->
[`GetLex (QName.of_node name)]
| `BindVar {value=Binding.Member (Binding.Scope scope,(ns,name)) } ->
[`GetScopeObject scope;
`GetProperty (QName.make ns name)]
| `BindVar {value=Binding.Member (Binding.Global,(ns,name)) } ->
[`GetGlobalScope;
`GetProperty (QName.make ns name)]
| `BindVar {value=Binding.Register n } ->
[`GetLocal n]
| `BindVar {value=Binding.Slot (Binding.Global,id) } ->
[`GetGlobalScope;
`GetSlot id]
| `BindVar {value=Binding.Slot (Binding.Scope scope,id) } ->
[`GetScopeObject scope;
`GetSlot id]
| `Let (vars,body) ->
let inits =
vars +> HList.concat_map
(fun ({value = var},init)->
[`PushString var] @
generate_expr init) in
List.concat [inits;
[`NewObject (List.length vars);
`PushWith];
generate_expr body;
[`PopScope]]
| `LetRec (vars,body) ->
let inits =
vars +> HList.concat_map
(fun ({value = var},init)->
List.concat [
[`Dup];
generate_expr init;
[`SetProperty (QName.make_global var)] ]) in
List.concat [[`NewObject 0;`Dup;`PushWith];
inits;
[`Pop];
generate_expr body;
[`PopScope]]
| `Invoke (obj,{value = name},args)->
List.concat [
gen obj;
HList.concat_map gen args;
[`CallProperty (QName.make_global name,List.length args)]]
| `SlotRef (obj,{value = name}) ->
List.concat [
gen obj;
[`GetProperty (QName.make_global name)]]
| `SlotSet (obj,{value = name},value) ->
List.concat [
gen value;
gen obj;
[`Swap;
`SetProperty (QName.make_global name);
`PushUndefined]]
| `Call (`Var {value = ([],name)}::args) when is_builtin name args ->
let inst,_ =
List.assoc name builtin in
List.concat [
HList.concat_map gen args;
inst]
| `Call (`Var {value = (ns,name)}::args) ->
let qname =
QName.make ns name in
List.concat [[`FindPropStrict qname];
HList.concat_map generate_expr args;
[`CallPropLex (qname,List.length args)]]
| `Call (`BindVar {value =
Binding.Member (Binding.Scope scope,(ns,name))}::args) ->
List.concat [[`GetScopeObject scope];
HList.concat_map generate_expr args;
[`CallPropLex (QName.make ns name,
List.length args)]]
| `Call (`BindVar {value =
Binding.Member (Binding.Global,(ns,name))}::args) ->
List.concat [[`GetGlobalScope];
HList.concat_map generate_expr args;
[`CallPropLex (QName.make ns name,
List.length args)]]
| `Call (`BindVar {value = Binding.Register n}::args) ->
List.concat [[`GetLocal n;
`GetGlobalScope];
HList.concat_map generate_expr args;
[`Call (List.length args)]]
| `Call (name::args) ->
let nargs =
List.length args in
List.concat [gen name;
[`GetGlobalScope];
HList.concat_map gen args;
[`Call nargs]]
| `Call [] ->
failwith "must not happen"
| `If (cond,cons,alt) ->
let l_alt =
Label.make () in
let l_if =
Label.make () in
let prefix = List.concat @@ match cond with
`Call [`Var {value = (_var,"=")};a;b] ->
[gen a;gen b;[`IfNe l_alt]]
| `Call [`Var {value = (_,">")};a;b] ->
[gen a;gen b;[`IfNgt l_alt]]
| `Call [`Var {value = (_,">=")};a;b] ->
[gen a;gen b;[`IfNge l_alt]]
| `Call [`Var {value = (_,"<=")};a;b] ->
[gen a;gen b;[`IfNle l_alt]]
| _ ->
IfNlt maybe does not work on FlashPlayer10 on
[gen cond;[`IfFalse l_alt]] in
List.concat [prefix;
gen cons;
[`Coerce_a];
[`Jump l_if;`Label l_alt];
gen alt;
[`Coerce_a];
[`Label l_if]]
(* class *)
let init_prefix =
[ `GetLocal_0;
`ConstructSuper 0 ]
let generate_method scope ctx ({Ast.method_name = name;
args = args;
body = body},attrs) =
let {code = inst} as m =
{MethodType.empty with
fun_scope = scope;
code = generate_expr body} in
match name with
`Public {Node.value="init"} ->
{ctx with
iinit =
{m with
method_name = QName.make_global "init";
params = List.map (const 0) @@ List.tl args;
code = init_prefix @ inst @ [`Pop; `ReturnVoid]}}
| `Public {Node.value=name} ->
{ctx with
instance_methods =
{m with
method_name = QName.make_global name;
params = List.map (const 0) @@ List.tl args;
method_attrs = (attrs :> [`Final | `Override] list);
code = inst @ [`ReturnValue] } :: ctx.instance_methods}
| `Static {Node.value="init"} ->
{ctx with
cinit =
{m with
method_name = QName.make_global "init";
params = List.map (const 0) args;
code = inst @ [`Pop; `ReturnVoid]}}
| `Static {Node.value=name} ->
{ctx with
static_methods =
{m with
method_name = QName.make_global name;
params = List.map (const 0) args;
method_attrs = (attrs :> [`Final | `Override] list);
code = inst @ [`ReturnValue] } :: ctx.static_methods}
let generate_class name {value = (ns,sname)} attrs methods =
let qname =
QName.of_stmt_name name in
let super =
QName.make ns sname in
let init =
{ MethodType.empty with
method_name = QName.make_global "init";
fun_scope = `Class qname;
code = init_prefix @ [`ReturnVoid] } in
let cinit =
{ MethodType.empty with
method_name = QName.make_global "cinit";
fun_scope = `Class qname;
code = [`ReturnVoid] } in
let empty = {
class_name = qname;
super = super;
class_flags = [`Sealed];
cinit = cinit;
iinit = init;
interface = [];
instance_methods = [];
static_methods = [];
attrs = attrs
} in
let klass =
List.fold_left (generate_method @@ `Class qname)
empty methods in
[
(* init class *)
`GetLex super;
`PushScope;
`GetLex super;
`NewClass klass;
`PopScope;
(* add to scope *)
`GetGlobalScope;
`Swap;
`InitProperty qname
]
let generate_stmt stmt =
match stmt with
`Expr expr ->
(generate_expr expr) @ [`Pop]
| `Define (name,body) ->
let qname =
QName.of_stmt_name name in
List.concat [
generate_expr body;
[`GetGlobalScope;
`Swap;
`SetProperty qname]
]
| `Class {Ast.class_name=name;
super=super;
attrs=attrs;
methods=methods} ->
generate_class
name super
(List.map (QName.make_global $ Node.value) attrs)
methods
let generate_program xs =
HList.concat_map generate_stmt xs
let generate_scope_class slots =
let attrs =
List.map (fun ((ns,name),_)-> QName.make ns name)
slots in
generate_class
(`Public (Node.ghost ([],"$Scope")))
(Node.ghost ([],"Object"))
attrs
[]
let generate program =
let program' =
generate_program program in
{MethodType.empty with
method_name =
QName.make_global "";
code =
List.concat [
[ `GetLocal_0; `PushScope ];
program';
[`ReturnVoid]
] }
| null | https://raw.githubusercontent.com/mzp/scheme-abc/2cb541159bcc32ae4d033793dea6e6828566d503/scm/codegen/codegen.ml | ocaml | class
init class
add to scope | open Base
open Ast
open Node
open Swflib
open MethodType
module QName = struct
let join xs =
String.concat "." xs
let of_stmt_name =
function
`Public {Node.value=(ns,name)} ->
`QName (`Namespace (join ns),name)
| `Internal {Node.value=(ns,name)} ->
`QName (`PackageInternalNamespace (join ns),name)
let make ns x =
`QName ((`Namespace (join ns)),x)
let of_node {Node.value=(ns,name)} =
make ns name
let make_global name =
make [] name
end
* { 6 Builtin operator }
let builtin = [
"+" , ([`Add_i],2);
"-" , ([`Subtract_i],2);
"*" , ([`Multiply_i],2);
"/" , ([`Divide;`Convert_i],2);
"+.", ([`Add],2);
"-.", ([`Subtract],2);
"*.", ([`Multiply],2);
"/." , ([`Divide],2);
"remainder", ([`Modulo],2);
"=" , ([`Equals],2);
">" , ([`GreaterThan],2);
">=" , ([`GreaterEquals],2);
"<" , ([`LessThan],2);
"<=" , ([`LessEquals],2)
]
let is_builtin name args =
try
let _,n =
List.assoc name builtin in
n = List.length args
with Not_found ->
false
let rec generate_expr expr =
let gen e =
generate_expr e in
match expr with
`Bool {value = true} ->
[`PushTrue]
| `Bool {value = false} ->
[`PushFalse]
| `Float {value = v} ->
[`PushDouble v]
| `String {value = str} ->
[`PushString str]
| `Int {value = n} when 0 <= n && n <= 0x7F ->
[`PushByte n]
| `Int {value = n} ->
[`PushInt n]
| `Block [] ->
[`PushUndefined]
| `Array xs ->
List.concat [
HList.concat_map gen xs;
[`NewArray (List.length xs)]
]
| `Block xs ->
List.concat @@ interperse [`Pop] @@ (List.map gen xs)
| `New (name,args) ->
let qname =
QName.of_node name in
List.concat [
[`FindPropStrict qname];
HList.concat_map gen args;
[`ConstructProp (qname, List.length args)]]
| `Lambda (args,body) ->
let body' =
generate_expr body in
let m = {
MethodType.empty with
method_name = QName.make_global "";
params = List.map (const 0) args;
code = body' @ [`ReturnValue] } in
[`NewFunction m]
| `Var name ->
[`GetLex (QName.of_node name)]
| `BindVar {value=Binding.Member (Binding.Scope scope,(ns,name)) } ->
[`GetScopeObject scope;
`GetProperty (QName.make ns name)]
| `BindVar {value=Binding.Member (Binding.Global,(ns,name)) } ->
[`GetGlobalScope;
`GetProperty (QName.make ns name)]
| `BindVar {value=Binding.Register n } ->
[`GetLocal n]
| `BindVar {value=Binding.Slot (Binding.Global,id) } ->
[`GetGlobalScope;
`GetSlot id]
| `BindVar {value=Binding.Slot (Binding.Scope scope,id) } ->
[`GetScopeObject scope;
`GetSlot id]
| `Let (vars,body) ->
let inits =
vars +> HList.concat_map
(fun ({value = var},init)->
[`PushString var] @
generate_expr init) in
List.concat [inits;
[`NewObject (List.length vars);
`PushWith];
generate_expr body;
[`PopScope]]
| `LetRec (vars,body) ->
let inits =
vars +> HList.concat_map
(fun ({value = var},init)->
List.concat [
[`Dup];
generate_expr init;
[`SetProperty (QName.make_global var)] ]) in
List.concat [[`NewObject 0;`Dup;`PushWith];
inits;
[`Pop];
generate_expr body;
[`PopScope]]
| `Invoke (obj,{value = name},args)->
List.concat [
gen obj;
HList.concat_map gen args;
[`CallProperty (QName.make_global name,List.length args)]]
| `SlotRef (obj,{value = name}) ->
List.concat [
gen obj;
[`GetProperty (QName.make_global name)]]
| `SlotSet (obj,{value = name},value) ->
List.concat [
gen value;
gen obj;
[`Swap;
`SetProperty (QName.make_global name);
`PushUndefined]]
| `Call (`Var {value = ([],name)}::args) when is_builtin name args ->
let inst,_ =
List.assoc name builtin in
List.concat [
HList.concat_map gen args;
inst]
| `Call (`Var {value = (ns,name)}::args) ->
let qname =
QName.make ns name in
List.concat [[`FindPropStrict qname];
HList.concat_map generate_expr args;
[`CallPropLex (qname,List.length args)]]
| `Call (`BindVar {value =
Binding.Member (Binding.Scope scope,(ns,name))}::args) ->
List.concat [[`GetScopeObject scope];
HList.concat_map generate_expr args;
[`CallPropLex (QName.make ns name,
List.length args)]]
| `Call (`BindVar {value =
Binding.Member (Binding.Global,(ns,name))}::args) ->
List.concat [[`GetGlobalScope];
HList.concat_map generate_expr args;
[`CallPropLex (QName.make ns name,
List.length args)]]
| `Call (`BindVar {value = Binding.Register n}::args) ->
List.concat [[`GetLocal n;
`GetGlobalScope];
HList.concat_map generate_expr args;
[`Call (List.length args)]]
| `Call (name::args) ->
let nargs =
List.length args in
List.concat [gen name;
[`GetGlobalScope];
HList.concat_map gen args;
[`Call nargs]]
| `Call [] ->
failwith "must not happen"
| `If (cond,cons,alt) ->
let l_alt =
Label.make () in
let l_if =
Label.make () in
let prefix = List.concat @@ match cond with
`Call [`Var {value = (_var,"=")};a;b] ->
[gen a;gen b;[`IfNe l_alt]]
| `Call [`Var {value = (_,">")};a;b] ->
[gen a;gen b;[`IfNgt l_alt]]
| `Call [`Var {value = (_,">=")};a;b] ->
[gen a;gen b;[`IfNge l_alt]]
| `Call [`Var {value = (_,"<=")};a;b] ->
[gen a;gen b;[`IfNle l_alt]]
| _ ->
IfNlt maybe does not work on FlashPlayer10 on
[gen cond;[`IfFalse l_alt]] in
List.concat [prefix;
gen cons;
[`Coerce_a];
[`Jump l_if;`Label l_alt];
gen alt;
[`Coerce_a];
[`Label l_if]]
let init_prefix =
[ `GetLocal_0;
`ConstructSuper 0 ]
let generate_method scope ctx ({Ast.method_name = name;
args = args;
body = body},attrs) =
let {code = inst} as m =
{MethodType.empty with
fun_scope = scope;
code = generate_expr body} in
match name with
`Public {Node.value="init"} ->
{ctx with
iinit =
{m with
method_name = QName.make_global "init";
params = List.map (const 0) @@ List.tl args;
code = init_prefix @ inst @ [`Pop; `ReturnVoid]}}
| `Public {Node.value=name} ->
{ctx with
instance_methods =
{m with
method_name = QName.make_global name;
params = List.map (const 0) @@ List.tl args;
method_attrs = (attrs :> [`Final | `Override] list);
code = inst @ [`ReturnValue] } :: ctx.instance_methods}
| `Static {Node.value="init"} ->
{ctx with
cinit =
{m with
method_name = QName.make_global "init";
params = List.map (const 0) args;
code = inst @ [`Pop; `ReturnVoid]}}
| `Static {Node.value=name} ->
{ctx with
static_methods =
{m with
method_name = QName.make_global name;
params = List.map (const 0) args;
method_attrs = (attrs :> [`Final | `Override] list);
code = inst @ [`ReturnValue] } :: ctx.static_methods}
let generate_class name {value = (ns,sname)} attrs methods =
let qname =
QName.of_stmt_name name in
let super =
QName.make ns sname in
let init =
{ MethodType.empty with
method_name = QName.make_global "init";
fun_scope = `Class qname;
code = init_prefix @ [`ReturnVoid] } in
let cinit =
{ MethodType.empty with
method_name = QName.make_global "cinit";
fun_scope = `Class qname;
code = [`ReturnVoid] } in
let empty = {
class_name = qname;
super = super;
class_flags = [`Sealed];
cinit = cinit;
iinit = init;
interface = [];
instance_methods = [];
static_methods = [];
attrs = attrs
} in
let klass =
List.fold_left (generate_method @@ `Class qname)
empty methods in
[
`GetLex super;
`PushScope;
`GetLex super;
`NewClass klass;
`PopScope;
`GetGlobalScope;
`Swap;
`InitProperty qname
]
let generate_stmt stmt =
match stmt with
`Expr expr ->
(generate_expr expr) @ [`Pop]
| `Define (name,body) ->
let qname =
QName.of_stmt_name name in
List.concat [
generate_expr body;
[`GetGlobalScope;
`Swap;
`SetProperty qname]
]
| `Class {Ast.class_name=name;
super=super;
attrs=attrs;
methods=methods} ->
generate_class
name super
(List.map (QName.make_global $ Node.value) attrs)
methods
let generate_program xs =
HList.concat_map generate_stmt xs
let generate_scope_class slots =
let attrs =
List.map (fun ((ns,name),_)-> QName.make ns name)
slots in
generate_class
(`Public (Node.ghost ([],"$Scope")))
(Node.ghost ([],"Object"))
attrs
[]
let generate program =
let program' =
generate_program program in
{MethodType.empty with
method_name =
QName.make_global "";
code =
List.concat [
[ `GetLocal_0; `PushScope ];
program';
[`ReturnVoid]
] }
|
5033448e972ecc81b6d10c524a5f90abdca2a7decf11ab64a1d1823b06f31835 | haskell/ghcup-hs | Config.hs | # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
# LANGUAGE FlexibleContexts #
# LANGUAGE TemplateHaskell #
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE DuplicateRecordFields #
{-# LANGUAGE RankNTypes #-}
module GHCup.OptParse.Config where
import GHCup.Errors
import GHCup.Types
import GHCup.Utils
import GHCup.Prelude
import GHCup.Prelude.Logger
import GHCup.Prelude.String.QQ
import GHCup.OptParse.Common
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail ( MonadFail )
#endif
import Control.Exception ( displayException )
import Control.Monad.Reader
import Control.Monad.Trans.Resource
import Data.Functor
import Data.Maybe
import Haskus.Utils.Variant.Excepts
import Options.Applicative hiding ( style, ParseError )
import Options.Applicative.Help.Pretty ( text )
import Prelude hiding ( appendFile )
import System.Exit
import URI.ByteString hiding ( uriParser )
import qualified Data.Text as T
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.Yaml.Aeson as Y
import Control.Exception.Safe (MonadMask)
----------------
--[ Commands ]--
----------------
data ConfigCommand
= ShowConfig
| SetConfig String (Maybe String)
| InitConfig
| AddReleaseChannel Bool URI
---------------
[ Parsers ] --
---------------
configP :: Parser ConfigCommand
configP = subparser
( command "init" initP
[ set ] KEY VALUE at help lhs
<> command "show" showP
<> command "add-release-channel" addP
)
<|> argsP -- add show for a single option
<|> pure ShowConfig
where
initP = info (pure InitConfig) (progDesc "Write default config to ~/.ghcup/config.yaml")
showP = info (pure ShowConfig) (progDesc "Show current config (default)")
setP = info argsP (progDesc "Set config KEY to VALUE (or specify as single json value)" <> footerDoc (Just $ text configSetFooter))
argsP = SetConfig <$> argument str (metavar "<JSON_VALUE | YAML_KEY>") <*> optional (argument str (metavar "YAML_VALUE"))
addP = info (AddReleaseChannel <$> switch (long "force" <> help "Delete existing entry (if any) and append instead of failing") <*> argument (eitherReader uriParser) (metavar "URI" <> completer fileUri))
(progDesc "Add a release channel from a URI")
--------------
--[ Footer ]--
--------------
configFooter :: String
configFooter = [s|Examples:
# show current config
ghcup config
# initialize config
ghcup config init
# set <key> <value> configuration pair
ghcup config set <key> <value>|]
configSetFooter :: String
configSetFooter = [s|Examples:
# disable caching
ghcup config set cache false
# switch downloader to wget
ghcup config set downloader Wget
# set mirror for ghcup metadata
ghcup config set '{url-source: { OwnSource: "<url>"}}'|]
-----------------
--[ Utilities ]--
-----------------
formatConfig :: UserSettings -> String
formatConfig = UTF8.toString . Y.encode
updateSettings :: UserSettings -> UserSettings -> UserSettings
updateSettings usl usr =
let cache' = uCache usl <|> uCache usr
metaCache' = uMetaCache usl <|> uMetaCache usr
metaMode' = uMetaMode usl <|> uMetaMode usr
noVerify' = uNoVerify usl <|> uNoVerify usr
verbose' = uVerbose usl <|> uVerbose usr
keepDirs' = uKeepDirs usl <|> uKeepDirs usr
downloader' = uDownloader usl <|> uDownloader usr
urlSource' = uUrlSource usl <|> uUrlSource usr
noNetwork' = uNoNetwork usl <|> uNoNetwork usr
gpgSetting' = uGPGSetting usl <|> uGPGSetting usr
platformOverride' = uPlatformOverride usl <|> uPlatformOverride usr
mirrors' = uMirrors usl <|> uMirrors usr
in UserSettings cache' metaCache' metaMode' noVerify' verbose' keepDirs' downloader' (updateKeyBindings (uKeyBindings usl) (uKeyBindings usr)) urlSource' noNetwork' gpgSetting' platformOverride' mirrors'
where
updateKeyBindings :: Maybe UserKeyBindings -> Maybe UserKeyBindings -> Maybe UserKeyBindings
updateKeyBindings Nothing Nothing = Nothing
updateKeyBindings (Just kbl) Nothing = Just kbl
updateKeyBindings Nothing (Just kbr) = Just kbr
updateKeyBindings (Just kbl) (Just kbr) =
Just $ UserKeyBindings {
kUp = kUp kbl <|> kUp kbr
, kDown = kDown kbl <|> kDown kbr
, kQuit = kQuit kbl <|> kQuit kbr
, kInstall = kInstall kbl <|> kInstall kbr
, kUninstall = kUninstall kbl <|> kUninstall kbr
, kSet = kSet kbl <|> kSet kbr
, kChangelog = kChangelog kbl <|> kChangelog kbr
, kShowAll = kShowAll kbl <|> kShowAll kbr
, kShowAllTools = kShowAllTools kbl <|> kShowAllTools kbr
}
------------------
--[ Entrypoint ]--
------------------
data Duplicate = Duplicate -- ^ there is a duplicate somewhere in the middle
| NoDuplicate -- ^ there is no duplicate
| DuplicateLast -- ^ there's a duplicate, but it's the last element
config :: forall m. ( Monad m
, MonadMask m
, MonadUnliftIO m
, MonadFail m
)
=> ConfigCommand
-> Settings
-> UserSettings
-> KeyBindings
-> (ReaderT LeanAppState m () -> m ())
-> m ExitCode
config configCommand settings userConf keybindings runLogger = case configCommand of
InitConfig -> do
path <- getConfigFilePath
liftIO $ writeFile path $ formatConfig $ fromSettings settings (Just keybindings)
runLogger $ logDebug $ "config.yaml initialized at " <> T.pack path
pure ExitSuccess
ShowConfig -> do
liftIO $ putStrLn $ formatConfig $ fromSettings settings (Just keybindings)
pure ExitSuccess
(SetConfig k mv) -> do
r <- runE @'[JSONError, ParseError] $ do
case mv of
Just "" ->
throwE $ ParseError "Empty values are not allowed"
Nothing -> do
usersettings <- decodeSettings k
lift $ doConfig usersettings
pure ()
Just v -> do
usersettings <- decodeSettings (k <> ": " <> v <> "\n")
lift $ doConfig usersettings
pure ()
case r of
VRight _ -> pure ExitSuccess
VLeft (V (JSONDecodeError e)) -> do
runLogger $ logError $ "Error decoding config: " <> T.pack e
pure $ ExitFailure 65
VLeft _ -> pure $ ExitFailure 65
AddReleaseChannel force uri -> do
r <- runE @'[DuplicateReleaseChannel] $ do
case urlSource settings of
AddSource xs -> do
case checkDuplicate xs (Right uri) of
Duplicate
| not force -> throwE (DuplicateReleaseChannel uri)
DuplicateLast -> pure ()
_ -> lift $ doConfig (defaultUserSettings { uUrlSource = Just $ AddSource (appendUnique xs (Right uri)) })
GHCupURL -> do
lift $ doConfig (defaultUserSettings { uUrlSource = Just $ AddSource [Right uri] })
pure ()
OwnSource xs -> do
case checkDuplicate xs (Right uri) of
Duplicate
| not force -> throwE (DuplicateReleaseChannel uri)
DuplicateLast -> pure ()
_ -> lift $ doConfig (defaultUserSettings { uUrlSource = Just $ OwnSource (appendUnique xs (Right uri)) })
OwnSpec spec -> do
lift $ doConfig (defaultUserSettings { uUrlSource = Just $ OwnSource [Left spec, Right uri] })
pure ()
case r of
VRight _ -> do
pure ExitSuccess
VLeft e -> do
runLogger $ logError $ T.pack $ prettyHFError e
pure $ ExitFailure 15
where
checkDuplicate :: Eq a => [a] -> a -> Duplicate
checkDuplicate xs a
| last xs == a = DuplicateLast
| a `elem` xs = Duplicate
| otherwise = NoDuplicate
-- appends the element to the end of the list, but also removes it from the existing list
appendUnique :: Eq a => [a] -> a -> [a]
appendUnique xs' e = go xs'
where
go [] = [e]
go (x:xs)
| x == e = go xs -- skip
| otherwise = x : go xs
doConfig :: MonadIO m => UserSettings -> m ()
doConfig usersettings = do
let settings' = updateSettings usersettings userConf
path <- liftIO getConfigFilePath
liftIO $ writeFile path $ formatConfig $ settings'
runLogger $ logDebug $ T.pack $ show settings'
pure ()
decodeSettings = lE' (JSONDecodeError . displayException) . Y.decodeEither' . UTF8.fromString
| null | https://raw.githubusercontent.com/haskell/ghcup-hs/e57a8abd3ddebffe08bb05d9cd92589cca216a61/app/ghcup/GHCup/OptParse/Config.hs | haskell | # LANGUAGE QuasiQuotes #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
--------------
[ Commands ]--
--------------
-------------
-------------
add show for a single option
------------
[ Footer ]--
------------
---------------
[ Utilities ]--
---------------
----------------
[ Entrypoint ]--
----------------
^ there is a duplicate somewhere in the middle
^ there is no duplicate
^ there's a duplicate, but it's the last element
appends the element to the end of the list, but also removes it from the existing list
skip | # LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE TypeApplications #
# LANGUAGE FlexibleContexts #
# LANGUAGE TemplateHaskell #
# LANGUAGE DuplicateRecordFields #
module GHCup.OptParse.Config where
import GHCup.Errors
import GHCup.Types
import GHCup.Utils
import GHCup.Prelude
import GHCup.Prelude.Logger
import GHCup.Prelude.String.QQ
import GHCup.OptParse.Common
#if !MIN_VERSION_base(4,13,0)
import Control.Monad.Fail ( MonadFail )
#endif
import Control.Exception ( displayException )
import Control.Monad.Reader
import Control.Monad.Trans.Resource
import Data.Functor
import Data.Maybe
import Haskus.Utils.Variant.Excepts
import Options.Applicative hiding ( style, ParseError )
import Options.Applicative.Help.Pretty ( text )
import Prelude hiding ( appendFile )
import System.Exit
import URI.ByteString hiding ( uriParser )
import qualified Data.Text as T
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.Yaml.Aeson as Y
import Control.Exception.Safe (MonadMask)
data ConfigCommand
= ShowConfig
| SetConfig String (Maybe String)
| InitConfig
| AddReleaseChannel Bool URI
configP :: Parser ConfigCommand
configP = subparser
( command "init" initP
[ set ] KEY VALUE at help lhs
<> command "show" showP
<> command "add-release-channel" addP
)
<|> pure ShowConfig
where
initP = info (pure InitConfig) (progDesc "Write default config to ~/.ghcup/config.yaml")
showP = info (pure ShowConfig) (progDesc "Show current config (default)")
setP = info argsP (progDesc "Set config KEY to VALUE (or specify as single json value)" <> footerDoc (Just $ text configSetFooter))
argsP = SetConfig <$> argument str (metavar "<JSON_VALUE | YAML_KEY>") <*> optional (argument str (metavar "YAML_VALUE"))
addP = info (AddReleaseChannel <$> switch (long "force" <> help "Delete existing entry (if any) and append instead of failing") <*> argument (eitherReader uriParser) (metavar "URI" <> completer fileUri))
(progDesc "Add a release channel from a URI")
configFooter :: String
configFooter = [s|Examples:
# show current config
ghcup config
# initialize config
ghcup config init
# set <key> <value> configuration pair
ghcup config set <key> <value>|]
configSetFooter :: String
configSetFooter = [s|Examples:
# disable caching
ghcup config set cache false
# switch downloader to wget
ghcup config set downloader Wget
# set mirror for ghcup metadata
ghcup config set '{url-source: { OwnSource: "<url>"}}'|]
formatConfig :: UserSettings -> String
formatConfig = UTF8.toString . Y.encode
updateSettings :: UserSettings -> UserSettings -> UserSettings
updateSettings usl usr =
let cache' = uCache usl <|> uCache usr
metaCache' = uMetaCache usl <|> uMetaCache usr
metaMode' = uMetaMode usl <|> uMetaMode usr
noVerify' = uNoVerify usl <|> uNoVerify usr
verbose' = uVerbose usl <|> uVerbose usr
keepDirs' = uKeepDirs usl <|> uKeepDirs usr
downloader' = uDownloader usl <|> uDownloader usr
urlSource' = uUrlSource usl <|> uUrlSource usr
noNetwork' = uNoNetwork usl <|> uNoNetwork usr
gpgSetting' = uGPGSetting usl <|> uGPGSetting usr
platformOverride' = uPlatformOverride usl <|> uPlatformOverride usr
mirrors' = uMirrors usl <|> uMirrors usr
in UserSettings cache' metaCache' metaMode' noVerify' verbose' keepDirs' downloader' (updateKeyBindings (uKeyBindings usl) (uKeyBindings usr)) urlSource' noNetwork' gpgSetting' platformOverride' mirrors'
where
updateKeyBindings :: Maybe UserKeyBindings -> Maybe UserKeyBindings -> Maybe UserKeyBindings
updateKeyBindings Nothing Nothing = Nothing
updateKeyBindings (Just kbl) Nothing = Just kbl
updateKeyBindings Nothing (Just kbr) = Just kbr
updateKeyBindings (Just kbl) (Just kbr) =
Just $ UserKeyBindings {
kUp = kUp kbl <|> kUp kbr
, kDown = kDown kbl <|> kDown kbr
, kQuit = kQuit kbl <|> kQuit kbr
, kInstall = kInstall kbl <|> kInstall kbr
, kUninstall = kUninstall kbl <|> kUninstall kbr
, kSet = kSet kbl <|> kSet kbr
, kChangelog = kChangelog kbl <|> kChangelog kbr
, kShowAll = kShowAll kbl <|> kShowAll kbr
, kShowAllTools = kShowAllTools kbl <|> kShowAllTools kbr
}
config :: forall m. ( Monad m
, MonadMask m
, MonadUnliftIO m
, MonadFail m
)
=> ConfigCommand
-> Settings
-> UserSettings
-> KeyBindings
-> (ReaderT LeanAppState m () -> m ())
-> m ExitCode
config configCommand settings userConf keybindings runLogger = case configCommand of
InitConfig -> do
path <- getConfigFilePath
liftIO $ writeFile path $ formatConfig $ fromSettings settings (Just keybindings)
runLogger $ logDebug $ "config.yaml initialized at " <> T.pack path
pure ExitSuccess
ShowConfig -> do
liftIO $ putStrLn $ formatConfig $ fromSettings settings (Just keybindings)
pure ExitSuccess
(SetConfig k mv) -> do
r <- runE @'[JSONError, ParseError] $ do
case mv of
Just "" ->
throwE $ ParseError "Empty values are not allowed"
Nothing -> do
usersettings <- decodeSettings k
lift $ doConfig usersettings
pure ()
Just v -> do
usersettings <- decodeSettings (k <> ": " <> v <> "\n")
lift $ doConfig usersettings
pure ()
case r of
VRight _ -> pure ExitSuccess
VLeft (V (JSONDecodeError e)) -> do
runLogger $ logError $ "Error decoding config: " <> T.pack e
pure $ ExitFailure 65
VLeft _ -> pure $ ExitFailure 65
AddReleaseChannel force uri -> do
r <- runE @'[DuplicateReleaseChannel] $ do
case urlSource settings of
AddSource xs -> do
case checkDuplicate xs (Right uri) of
Duplicate
| not force -> throwE (DuplicateReleaseChannel uri)
DuplicateLast -> pure ()
_ -> lift $ doConfig (defaultUserSettings { uUrlSource = Just $ AddSource (appendUnique xs (Right uri)) })
GHCupURL -> do
lift $ doConfig (defaultUserSettings { uUrlSource = Just $ AddSource [Right uri] })
pure ()
OwnSource xs -> do
case checkDuplicate xs (Right uri) of
Duplicate
| not force -> throwE (DuplicateReleaseChannel uri)
DuplicateLast -> pure ()
_ -> lift $ doConfig (defaultUserSettings { uUrlSource = Just $ OwnSource (appendUnique xs (Right uri)) })
OwnSpec spec -> do
lift $ doConfig (defaultUserSettings { uUrlSource = Just $ OwnSource [Left spec, Right uri] })
pure ()
case r of
VRight _ -> do
pure ExitSuccess
VLeft e -> do
runLogger $ logError $ T.pack $ prettyHFError e
pure $ ExitFailure 15
where
checkDuplicate :: Eq a => [a] -> a -> Duplicate
checkDuplicate xs a
| last xs == a = DuplicateLast
| a `elem` xs = Duplicate
| otherwise = NoDuplicate
appendUnique :: Eq a => [a] -> a -> [a]
appendUnique xs' e = go xs'
where
go [] = [e]
go (x:xs)
| otherwise = x : go xs
doConfig :: MonadIO m => UserSettings -> m ()
doConfig usersettings = do
let settings' = updateSettings usersettings userConf
path <- liftIO getConfigFilePath
liftIO $ writeFile path $ formatConfig $ settings'
runLogger $ logDebug $ T.pack $ show settings'
pure ()
decodeSettings = lE' (JSONDecodeError . displayException) . Y.decodeEither' . UTF8.fromString
|
c3e6572e66b4a56856e8b7b46e53bfc2a16a39aa92e6e20bb242aa4fd296deb7 | well-typed-lightbulbs/ocaml-esp32 | harness.ml | external reset_instrumentation : bool -> unit = "caml_reset_afl_instrumentation"
external sys_exit : int -> 'a = "caml_sys_exit"
let name n =
fst (Test.tests.(int_of_string n - 1))
let run n =
snd (Test.tests.(int_of_string n - 1)) ()
let orig_random = Random.get_state ()
let () =
(* Random.set_state orig_random; *)
reset_instrumentation true;
begin
match Sys.argv with
| [| _; "len" |] ->
print_int (Array.length Test.tests); print_newline (); flush stdout
| [| _; "name"; n |] -> print_string (name n); flush stdout
| [| _; "1"; n |] -> run n
| [| _; "2"; n |] ->
run n;
(* Random.set_state orig_random; *)
reset_instrumentation false;
run n
| _ -> failwith "error"
end;
sys_exit 0
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/afl-instrumentation/harness.ml | ocaml | Random.set_state orig_random;
Random.set_state orig_random; | external reset_instrumentation : bool -> unit = "caml_reset_afl_instrumentation"
external sys_exit : int -> 'a = "caml_sys_exit"
let name n =
fst (Test.tests.(int_of_string n - 1))
let run n =
snd (Test.tests.(int_of_string n - 1)) ()
let orig_random = Random.get_state ()
let () =
reset_instrumentation true;
begin
match Sys.argv with
| [| _; "len" |] ->
print_int (Array.length Test.tests); print_newline (); flush stdout
| [| _; "name"; n |] -> print_string (name n); flush stdout
| [| _; "1"; n |] -> run n
| [| _; "2"; n |] ->
run n;
reset_instrumentation false;
run n
| _ -> failwith "error"
end;
sys_exit 0
|
4ecce258b47d3f2c9618a2bdee4eb83c1845485aae4d7269838c99b9979cacb6 | anmonteiro/websocket-httpaf | websocket_lwt_io.ml | { { { Copyright ( c ) 2012 - 2014 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
(*
* Adapted from:
* -cohttp/blob/master/cohttp-lwt-unix/src/io.ml
*)
let () =
if Sys.os_type <> "Win32" then
Sys.(set_signal sigpipe Signal_ignore);
type 'a t = 'a Lwt.t
type 'a u = 'a Lwt.u
let (>>=) = Lwt.bind
let return = Lwt.return
let wait = Lwt.wait
let join = Lwt.join
let wakeup_later = Lwt.wakeup_later
type ic = Lwt_io.input_channel
type oc = Lwt_io.output_channel
type conn = unit
let src = Logs.Src.create "websocket-httpaf.lwt.io" ~doc:"Websocket-httpaf Lwt IO module"
module Log = (val Logs.src_log src : Logs.LOG)
let read_line ic =
Lwt_io.read_line_opt ic >>= function
| None ->
Log.debug (fun f -> f "<<< EOF");
Lwt.return_none
| Some l as x ->
Log.debug (fun f -> f "<<< %s" l);
Lwt.return x
let read ic count =
let count = min count Sys.max_string_length in
Lwt_io.read ~count ic >>= fun buf ->
Log.debug (fun f -> f "<<<[%d] %s" count buf);
Lwt.return buf
let write oc buf =
Log.debug (fun f -> f ">>> %s" (String.trim buf));
Lwt_io.write oc buf
let flush oc =
Lwt_io.flush oc
| null | https://raw.githubusercontent.com/anmonteiro/websocket-httpaf/3308726f81dbf204657c225b29e88c642b0706d2/lwt/websocket_lwt_io.ml | ocaml |
* Adapted from:
* -cohttp/blob/master/cohttp-lwt-unix/src/io.ml
| { { { Copyright ( c ) 2012 - 2014 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
} } }
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
}}}*)
let () =
if Sys.os_type <> "Win32" then
Sys.(set_signal sigpipe Signal_ignore);
type 'a t = 'a Lwt.t
type 'a u = 'a Lwt.u
let (>>=) = Lwt.bind
let return = Lwt.return
let wait = Lwt.wait
let join = Lwt.join
let wakeup_later = Lwt.wakeup_later
type ic = Lwt_io.input_channel
type oc = Lwt_io.output_channel
type conn = unit
let src = Logs.Src.create "websocket-httpaf.lwt.io" ~doc:"Websocket-httpaf Lwt IO module"
module Log = (val Logs.src_log src : Logs.LOG)
let read_line ic =
Lwt_io.read_line_opt ic >>= function
| None ->
Log.debug (fun f -> f "<<< EOF");
Lwt.return_none
| Some l as x ->
Log.debug (fun f -> f "<<< %s" l);
Lwt.return x
let read ic count =
let count = min count Sys.max_string_length in
Lwt_io.read ~count ic >>= fun buf ->
Log.debug (fun f -> f "<<<[%d] %s" count buf);
Lwt.return buf
let write oc buf =
Log.debug (fun f -> f ">>> %s" (String.trim buf));
Lwt_io.write oc buf
let flush oc =
Lwt_io.flush oc
|
65a1147de5b4b1a31dbc3bb58e82a5e7414dcc36d3e362be3a258ce4e5578afa | cj1128/sicp-review | queue.scm | ;; Implements queue abstract data structure
(define (front-ptr queue) (car queue))
(define (rear-ptr queue) (cdr queue))
(define (set-front-ptr! queue item)
(set-car! queue item))
(define (set-rear-ptr! queue item)
(set-cdr! queue item))
(define (empty-queue? queue)
(null? (front-ptr? queue)))
(define (make-queue)
(cons '() '()))
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(car (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr queue new-pair)
queue))))
(define (delete-queue! queue)
(cond
((empty-queue? queue)
(error "DELETE called with an empty queue" queue))
(else
(let ((item (car (front-ptr queue))))
(set-front-ptr! queue (cdr item))
item))))
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-3/queue.scm | scheme | Implements queue abstract data structure |
(define (front-ptr queue) (car queue))
(define (rear-ptr queue) (cdr queue))
(define (set-front-ptr! queue item)
(set-car! queue item))
(define (set-rear-ptr! queue item)
(set-cdr! queue item))
(define (empty-queue? queue)
(null? (front-ptr? queue)))
(define (make-queue)
(cons '() '()))
(define (front-queue queue)
(if (empty-queue? queue)
(error "FRONT called with an empty queue" queue)
(car (front-ptr queue))))
(define (insert-queue! queue item)
(let ((new-pair (cons item '())))
(cond ((empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue)
(else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr queue new-pair)
queue))))
(define (delete-queue! queue)
(cond
((empty-queue? queue)
(error "DELETE called with an empty queue" queue))
(else
(let ((item (car (front-ptr queue))))
(set-front-ptr! queue (cdr item))
item))))
|
08b57cac8b67d5ae0799286fa3893660487543db293083d15f980614a564e2c4 | rabbitmq/rabbitmq-common | worker_pool.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(worker_pool).
Generic worker pool manager .
%%
%% Submitted jobs are functions. They can be executed synchronously
( using worker_pool : submit/1 , worker_pool : submit/2 ) or asynchronously
( using worker_pool : submit_async/1 ) .
%%
%% We typically use the worker pool if we want to limit the maximum
%% parallelism of some job. We are not trying to dodge the cost of
creating Erlang processes .
%%
Supports nested submission of jobs and two execution modes :
%% 'single' and 'reuse'. Jobs executed in 'single' mode are invoked in
a one - off process . Those executed in ' reuse ' mode are invoked in a
%% worker process out of the pool. Nested jobs are always executed
%% immediately in current worker process.
%%
' single ' mode is offered to work around a bug in : after
%% network partitions reply messages for prior failed requests can be
sent to clients - a reused worker pool process can crash on
%% receiving one.
%%
Caller submissions are enqueued internally . When the next worker
%% process is available, it communicates it to the pool and is
%% assigned a job to execute. If job execution fails with an error, no
%% response is returned to the caller.
%%
%% Worker processes prioritise certain command-and-control messages
%% from the pool.
%%
%% Future improvement points: job prioritisation.
-behaviour(gen_server2).
-export([start_link/1,
submit/1, submit/2, submit/3,
submit_async/1, submit_async/2,
dispatch_sync/1, dispatch_sync/2,
ready/2,
idle/2,
default_pool/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
%%----------------------------------------------------------------------------
-type mfargs() :: {atom(), atom(), [any()]}.
-spec start_link(atom()) -> {'ok', pid()} | {'error', any()}.
-spec submit(fun (() -> A) | mfargs()) -> A.
-spec submit(fun (() -> A) | mfargs(), 'reuse' | 'single') -> A.
-spec submit(atom(), fun (() -> A) | mfargs(), 'reuse' | 'single') -> A.
-spec submit_async(fun (() -> any()) | mfargs()) -> 'ok'.
-spec dispatch_sync(fun(() -> any()) | mfargs()) -> 'ok'.
-spec ready(atom(), pid()) -> 'ok'.
-spec idle(atom(), pid()) -> 'ok'.
-spec default_pool() -> atom().
%%----------------------------------------------------------------------------
-define(DEFAULT_POOL, ?MODULE).
-define(HIBERNATE_AFTER_MIN, 1000).
-define(DESIRED_HIBERNATE, 10000).
-record(state, { available, pending }).
%%----------------------------------------------------------------------------
start_link(Name) -> gen_server2:start_link({local, Name}, ?MODULE, [],
[{timeout, infinity}]).
submit(Fun) ->
submit(?DEFAULT_POOL, Fun, reuse).
ProcessModel = : = single is for working around the mnesia_locker bug .
submit(Fun, ProcessModel) ->
submit(?DEFAULT_POOL, Fun, ProcessModel).
submit(Server, Fun, ProcessModel) ->
case get(worker_pool_worker) of
true -> worker_pool_worker:run(Fun);
_ -> Pid = gen_server2:call(Server, {next_free, self()}, infinity),
worker_pool_worker:submit(Pid, Fun, ProcessModel)
end.
submit_async(Fun) -> submit_async(?DEFAULT_POOL, Fun).
submit_async(Server, Fun) -> gen_server2:cast(Server, {run_async, Fun}).
dispatch_sync(Fun) ->
dispatch_sync(?DEFAULT_POOL, Fun).
dispatch_sync(Server, Fun) ->
Pid = gen_server2:call(Server, {next_free, self()}, infinity),
worker_pool_worker:submit_async(Pid, Fun).
ready(Server, WPid) -> gen_server2:cast(Server, {ready, WPid}).
idle(Server, WPid) -> gen_server2:cast(Server, {idle, WPid}).
default_pool() -> ?DEFAULT_POOL.
%%----------------------------------------------------------------------------
init([]) ->
{ok, #state { pending = queue:new(), available = ordsets:new() }, hibernate,
{backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN, ?DESIRED_HIBERNATE}}.
handle_call({next_free, CPid}, From, State = #state { available = [],
pending = Pending }) ->
{noreply, State#state{pending = queue:in({next_free, From, CPid}, Pending)},
hibernate};
handle_call({next_free, CPid}, _From, State = #state { available =
[WPid | Avail1] }) ->
worker_pool_worker:next_job_from(WPid, CPid),
{reply, WPid, State #state { available = Avail1 }, hibernate};
handle_call(Msg, _From, State) ->
{stop, {unexpected_call, Msg}, State}.
handle_cast({ready, WPid}, State) ->
erlang:monitor(process, WPid),
handle_cast({idle, WPid}, State);
handle_cast({idle, WPid}, State = #state { available = Avail,
pending = Pending }) ->
{noreply,
case queue:out(Pending) of
{empty, _Pending} ->
State #state { available = ordsets:add_element(WPid, Avail) };
{{value, {next_free, From, CPid}}, Pending1} ->
worker_pool_worker:next_job_from(WPid, CPid),
gen_server2:reply(From, WPid),
State #state { pending = Pending1 };
{{value, {run_async, Fun}}, Pending1} ->
worker_pool_worker:submit_async(WPid, Fun),
State #state { pending = Pending1 }
end, hibernate};
handle_cast({run_async, Fun}, State = #state { available = [],
pending = Pending }) ->
{noreply, State #state { pending = queue:in({run_async, Fun}, Pending)},
hibernate};
handle_cast({run_async, Fun}, State = #state { available = [WPid | Avail1] }) ->
worker_pool_worker:submit_async(WPid, Fun),
{noreply, State #state { available = Avail1 }, hibernate};
handle_cast(Msg, State) ->
{stop, {unexpected_cast, Msg}, State}.
handle_info({'DOWN', _MRef, process, WPid, _Reason},
State = #state { available = Avail }) ->
{noreply, State #state { available = ordsets:del_element(WPid, Avail) },
hibernate};
handle_info(Msg, State) ->
{stop, {unexpected_info, Msg}, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, State) ->
State.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-common/67c4397ffa9f51d87f994aa4db4a68e8e95326ab/src/worker_pool.erl | erlang |
Submitted jobs are functions. They can be executed synchronously
We typically use the worker pool if we want to limit the maximum
parallelism of some job. We are not trying to dodge the cost of
'single' and 'reuse'. Jobs executed in 'single' mode are invoked in
worker process out of the pool. Nested jobs are always executed
immediately in current worker process.
network partitions reply messages for prior failed requests can be
receiving one.
process is available, it communicates it to the pool and is
assigned a job to execute. If job execution fails with an error, no
response is returned to the caller.
Worker processes prioritise certain command-and-control messages
from the pool.
Future improvement points: job prioritisation.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------- | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(worker_pool).
Generic worker pool manager .
( using worker_pool : submit/1 , worker_pool : submit/2 ) or asynchronously
( using worker_pool : submit_async/1 ) .
creating Erlang processes .
Supports nested submission of jobs and two execution modes :
a one - off process . Those executed in ' reuse ' mode are invoked in a
' single ' mode is offered to work around a bug in : after
sent to clients - a reused worker pool process can crash on
Caller submissions are enqueued internally . When the next worker
-behaviour(gen_server2).
-export([start_link/1,
submit/1, submit/2, submit/3,
submit_async/1, submit_async/2,
dispatch_sync/1, dispatch_sync/2,
ready/2,
idle/2,
default_pool/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-type mfargs() :: {atom(), atom(), [any()]}.
-spec start_link(atom()) -> {'ok', pid()} | {'error', any()}.
-spec submit(fun (() -> A) | mfargs()) -> A.
-spec submit(fun (() -> A) | mfargs(), 'reuse' | 'single') -> A.
-spec submit(atom(), fun (() -> A) | mfargs(), 'reuse' | 'single') -> A.
-spec submit_async(fun (() -> any()) | mfargs()) -> 'ok'.
-spec dispatch_sync(fun(() -> any()) | mfargs()) -> 'ok'.
-spec ready(atom(), pid()) -> 'ok'.
-spec idle(atom(), pid()) -> 'ok'.
-spec default_pool() -> atom().
-define(DEFAULT_POOL, ?MODULE).
-define(HIBERNATE_AFTER_MIN, 1000).
-define(DESIRED_HIBERNATE, 10000).
-record(state, { available, pending }).
start_link(Name) -> gen_server2:start_link({local, Name}, ?MODULE, [],
[{timeout, infinity}]).
submit(Fun) ->
submit(?DEFAULT_POOL, Fun, reuse).
ProcessModel = : = single is for working around the mnesia_locker bug .
submit(Fun, ProcessModel) ->
submit(?DEFAULT_POOL, Fun, ProcessModel).
submit(Server, Fun, ProcessModel) ->
case get(worker_pool_worker) of
true -> worker_pool_worker:run(Fun);
_ -> Pid = gen_server2:call(Server, {next_free, self()}, infinity),
worker_pool_worker:submit(Pid, Fun, ProcessModel)
end.
submit_async(Fun) -> submit_async(?DEFAULT_POOL, Fun).
submit_async(Server, Fun) -> gen_server2:cast(Server, {run_async, Fun}).
dispatch_sync(Fun) ->
dispatch_sync(?DEFAULT_POOL, Fun).
dispatch_sync(Server, Fun) ->
Pid = gen_server2:call(Server, {next_free, self()}, infinity),
worker_pool_worker:submit_async(Pid, Fun).
ready(Server, WPid) -> gen_server2:cast(Server, {ready, WPid}).
idle(Server, WPid) -> gen_server2:cast(Server, {idle, WPid}).
default_pool() -> ?DEFAULT_POOL.
init([]) ->
{ok, #state { pending = queue:new(), available = ordsets:new() }, hibernate,
{backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN, ?DESIRED_HIBERNATE}}.
handle_call({next_free, CPid}, From, State = #state { available = [],
pending = Pending }) ->
{noreply, State#state{pending = queue:in({next_free, From, CPid}, Pending)},
hibernate};
handle_call({next_free, CPid}, _From, State = #state { available =
[WPid | Avail1] }) ->
worker_pool_worker:next_job_from(WPid, CPid),
{reply, WPid, State #state { available = Avail1 }, hibernate};
handle_call(Msg, _From, State) ->
{stop, {unexpected_call, Msg}, State}.
handle_cast({ready, WPid}, State) ->
erlang:monitor(process, WPid),
handle_cast({idle, WPid}, State);
handle_cast({idle, WPid}, State = #state { available = Avail,
pending = Pending }) ->
{noreply,
case queue:out(Pending) of
{empty, _Pending} ->
State #state { available = ordsets:add_element(WPid, Avail) };
{{value, {next_free, From, CPid}}, Pending1} ->
worker_pool_worker:next_job_from(WPid, CPid),
gen_server2:reply(From, WPid),
State #state { pending = Pending1 };
{{value, {run_async, Fun}}, Pending1} ->
worker_pool_worker:submit_async(WPid, Fun),
State #state { pending = Pending1 }
end, hibernate};
handle_cast({run_async, Fun}, State = #state { available = [],
pending = Pending }) ->
{noreply, State #state { pending = queue:in({run_async, Fun}, Pending)},
hibernate};
handle_cast({run_async, Fun}, State = #state { available = [WPid | Avail1] }) ->
worker_pool_worker:submit_async(WPid, Fun),
{noreply, State #state { available = Avail1 }, hibernate};
handle_cast(Msg, State) ->
{stop, {unexpected_cast, Msg}, State}.
handle_info({'DOWN', _MRef, process, WPid, _Reason},
State = #state { available = Avail }) ->
{noreply, State #state { available = ordsets:del_element(WPid, Avail) },
hibernate};
handle_info(Msg, State) ->
{stop, {unexpected_info, Msg}, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, State) ->
State.
|
7b4274167113c79e53c75bba7f00a271c940fbae7e743b5ed71f830ae3d301bb | freizl/dive-into-haskell | max-two-dim-array.hs | module Main where
import Test.QuickCheck
maximumArrayOfArray :: [[Int]] -> (Int, Int)
maximumArrayOfArray [] = (0, 0)
maximumArrayOfArray xss = (j, k)
where ((_, k), j) = maximumWithIndex $ map maximumWithIndex xss
maximumWithIndex :: Ord a =>
[a]
^ ( MaxValue , its Index )
maximumWithIndex xs = maximum (zip xs [0..n])
where n = length xs - 1
data1, data2 :: [[Int]]
data1 = [[1..3], [4..6], [7..9]]
data2 = [[2..4], [8, 9], [1..5]]
prop_test1, prop_test2 :: Bool
prop_test1 = maximumArrayOfArray data1 == (2, 2)
prop_test2 = maximumArrayOfArray data2 == (1, 1)
testSuits :: IO ()
testSuits = mapM_ quickCheck [prop_test1, prop_test2]
| null | https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/codes/sandbox/max-two-dim-array.hs | haskell | module Main where
import Test.QuickCheck
maximumArrayOfArray :: [[Int]] -> (Int, Int)
maximumArrayOfArray [] = (0, 0)
maximumArrayOfArray xss = (j, k)
where ((_, k), j) = maximumWithIndex $ map maximumWithIndex xss
maximumWithIndex :: Ord a =>
[a]
^ ( MaxValue , its Index )
maximumWithIndex xs = maximum (zip xs [0..n])
where n = length xs - 1
data1, data2 :: [[Int]]
data1 = [[1..3], [4..6], [7..9]]
data2 = [[2..4], [8, 9], [1..5]]
prop_test1, prop_test2 :: Bool
prop_test1 = maximumArrayOfArray data1 == (2, 2)
prop_test2 = maximumArrayOfArray data2 == (1, 1)
testSuits :: IO ()
testSuits = mapM_ quickCheck [prop_test1, prop_test2]
| |
5b46b966dd2ce6b0be36803b24c80894a91246ee81baab957e7adb2fd41cfd43 | tamarin-prover/tamarin-prover | Batch.hs | # LANGUAGE FlexibleContexts #
-- |
Copyright : ( c ) 2010 , 2011 &
-- License : GPL v3 (see LICENSE)
--
Maintainer : < >
Portability : GHC only
--
Main module for the Tamarin prover .
module Main.Mode.Batch (
batchMode
) where
import Control.Basics
import Data.List
import Data.Bitraversable (bisequence)
import System.Console.CmdArgs.Explicit as CmdArgs
import System.FilePath
import System.Timing (timedIO)
import Extension.Data.Label
import qualified Text.PrettyPrint.Class as Pretty
import Theory hiding (closeTheory)
import qualified Sapic
import qualified Export
import Main.Console
import Main.Environment
import Main.TheoryLoader
import Main.Utils
import Theory.Module
import Control.Monad.Except (MonadIO(liftIO), runExceptT)
import System.Exit (die)
import Theory.Tools.Wellformedness (prettyWfErrorReport)
import Text.Printf (printf)
-- | Batch processing mode.
batchMode :: TamarinMode
batchMode = tamarinMode
"batch"
"Security protocol analysis and verification."
setupFlags
run
where
setupFlags defaultMode = defaultMode
{ modeArgs = ([], Just $ flagArg (updateArg "inFile") "FILES")
, modeGroupFlags = Group
{ groupUnnamed =
theoryLoadFlags ++
-- [ flagNone ["html"] (addEmptyArg "html")
-- "generate HTML visualization of proofs"
[ flagNone ["no-compress"] (addEmptyArg "noCompress")
"Do not use compressed sequent visualization"
, flagNone ["parse-only"] (addEmptyArg "parseOnly")
"Just parse the input file and pretty print it as-is"
] ++
outputFlags ++
toolFlags
, groupHidden = []
, groupNamed = []
}
}
outputFlags =
[ flagOpt "" ["output","o"] (updateArg "outFile") "FILE" "Output file"
, flagOpt "" ["Output","O"] (updateArg "outDir") "DIR" "Output directory"
, flagOpt "spthy" ["output-module", "m"] (updateArg "outModule") moduleList
moduleDescriptions
]
moduleConstructors = enumFrom minBound :: [ModuleType]
moduleList = intercalate "|" $ map show moduleConstructors
moduleDescriptions = "What to output:" ++ intercalate " " (map (\x -> "\n -"++description x) moduleConstructors) ++ "."
-- | Process a theory file.
run :: TamarinMode -> Arguments -> IO ()
run thisMode as
| null inFiles = helpAndExit thisMode (Just "no input files given")
| argExists "parseOnly" as || argExists "outModule" as = do
res <- mapM (processThy "") inFiles
let (thys, _) = unzip res
mapM_ (putStrLn . renderDoc) thys
putStrLn ""
| otherwise = do
versionData <- ensureMaudeAndGetVersion as
resTimed <- mapM (timedIO . processThy versionData) inFiles
let (docs, reps, times) = unzip3 $ fmap (\((d, r), t) -> (d, r, t)) resTimed
if writeOutput then do
let maybeOutFiles = sequence $ mkOutPath <$> inFiles
outFiles <- case maybeOutFiles of
Just f -> return f
Nothing -> die "Please specify a valid output file/directory"
let repsWithInfo = ppRep <$> zip4 inFiles (Just <$> outFiles) times reps
let summary = Pretty.vcat $ intersperse (Pretty.text "") repsWithInfo
mapM_ (\(o, d) -> writeFileWithDirs o (renderDoc d)) (zip outFiles docs)
putStrLn $ renderDoc $ ppSummary summary
else do
let repsWithInfo = ppRep <$> zip4 inFiles (repeat Nothing) times reps
let summary = Pretty.vcat $ intersperse (Pretty.text "") repsWithInfo
mapM_ (putStrLn . renderDoc) docs
putStrLn $ renderDoc $ ppSummary summary
where
ppSummary summary = Pretty.vcat [ Pretty.text $ ""
, Pretty.text $ replicate 78 '='
, Pretty.text $ "summary of summaries:"
, Pretty.text $ ""
, summary
, Pretty.text $ ""
, Pretty.text $ replicate 78 '=' ]
ppRep (inFile, outFile, time, summary)=
Pretty.vcat [ Pretty.text $ "analyzed: " ++ inFile
, Pretty.text $ ""
, Pretty.text $ ""
, Pretty.nest 2 $ Pretty.vcat [
maybe Pretty.emptyDoc (\o -> Pretty.text $ "output: " ++ o) outFile
, Pretty.text $ printf "processing time: %.2fs" (realToFrac time :: Double)
, Pretty.text $ ""
, summary ] ]
-- handles to arguments
-----------------------
inFiles = reverse $ findArg "inFile" as
thyLoadOptions = case mkTheoryLoadOptions as of
Left (ArgumentError e) -> error e
Right opts -> opts
-- output generation
--------------------
writeOutput = argExists "outFile" as || argExists "outDir" as
mkOutPath :: FilePath -- ^ Input file name.
-> Maybe FilePath -- ^ Output file name.
mkOutPath inFile =
do outFile <- findArg "outFile" as
guard (outFile /= "")
return outFile
<|>
do outDir <- findArg "outDir" as
return $ mkAutoPath outDir (takeBaseName inFile)
-- automatically generate the filename for output
mkAutoPath :: FilePath -> String -> FilePath
mkAutoPath dir baseName
| argExists "html" as = dir </> baseName
| otherwise = dir </> addExtension (baseName ++ "_analyzed") "spthy"
-- theory processing functions
------------------------------
processThy :: String -> FilePath -> IO (Pretty.Doc, Pretty.Doc)
processThy versionData inFile = either handleError return <=< runExceptT $ do
srcThy <- liftIO $ readFile inFile
thy <- loadTheory thyLoadOptions srcThy inFile
if isParseOnlyMode then do
either (\t -> bisequence (liftIO $ choosePretty t, return Pretty.emptyDoc))
(\d -> return (prettyOpenDiffTheory d, Pretty.emptyDoc)) thy
else do
let sig = either (get thySignature) (get diffThySignature) thy
sig' <- liftIO $ toSignatureWithMaude (get oMaudePath thyLoadOptions) sig
(report, thy') <- closeTheory versionData thyLoadOptions sig' thy
either (\t -> return (prettyClosedTheory t, ppWf report Pretty.$--$ prettyClosedSummary t))
(\d -> return (prettyClosedDiffTheory d, ppWf report Pretty.$--$ prettyClosedDiffSummary d)) thy'
where
isParseOnlyMode = get oParseOnlyMode thyLoadOptions
handleError (ParserError e) = error $ show e
handleError (WarningError report) = do
putStrLn $ renderDoc $ Pretty.vcat [ Pretty.text ""
, Pretty.text "WARNING: the following wellformedness checks failed!"
, Pretty.text ""
, prettyWfErrorReport report
, Pretty.text "" ]
die "quit-on-warning mode selected - aborting on wellformedness errors."
ppWf [] = Pretty.emptyDoc
ppWf rep = Pretty.vcat $ Pretty.text ("WARNING: " ++ show (length rep) ++ " wellformedness check failed!")
: [ Pretty.text " The analysis results might be wrong!" | get oProveMode thyLoadOptions ]
choosePretty = case get oOutputModule thyLoadOptions of
output as is , including SAPIC elements
output as is , including SAPIC elements
Just ModuleSpthyTyped -> return . prettyOpenTheory <=< Sapic.typeTheory <=< Sapic.warnings -- additionally type
Just ModuleMsr -> return . prettyOpenTranslatedTheory
<=< (return . filterLemma (lemmaSelector thyLoadOptions))
<=< (return . removeTranslationItems)
<=< Sapic.typeTheory
<=< Sapic.warnings
Just ModuleProVerif -> Export.prettyProVerifTheory (lemmaSelector thyLoadOptions) <=< Sapic.typeTheoryEnv <=< Sapic.warnings
Just ModuleProVerifEquivalence -> Export.prettyProVerifEquivTheory <=< Sapic.typeTheoryEnv <=< Sapic.warnings
Just ModuleDeepSec -> Export.prettyDeepSecTheory <=< Sapic.typeTheory <=< Sapic.warnings | null | https://raw.githubusercontent.com/tamarin-prover/tamarin-prover/a8107748bd57d80b41f2f8bf8a756f2cbb4c5049/src/Main/Mode/Batch.hs | haskell | |
License : GPL v3 (see LICENSE)
| Batch processing mode.
[ flagNone ["html"] (addEmptyArg "html")
"generate HTML visualization of proofs"
| Process a theory file.
handles to arguments
---------------------
output generation
------------------
^ Input file name.
^ Output file name.
automatically generate the filename for output
theory processing functions
----------------------------
$ prettyClosedSummary t))
$ prettyClosedDiffSummary d)) thy'
additionally type | # LANGUAGE FlexibleContexts #
Copyright : ( c ) 2010 , 2011 &
Maintainer : < >
Portability : GHC only
Main module for the Tamarin prover .
module Main.Mode.Batch (
batchMode
) where
import Control.Basics
import Data.List
import Data.Bitraversable (bisequence)
import System.Console.CmdArgs.Explicit as CmdArgs
import System.FilePath
import System.Timing (timedIO)
import Extension.Data.Label
import qualified Text.PrettyPrint.Class as Pretty
import Theory hiding (closeTheory)
import qualified Sapic
import qualified Export
import Main.Console
import Main.Environment
import Main.TheoryLoader
import Main.Utils
import Theory.Module
import Control.Monad.Except (MonadIO(liftIO), runExceptT)
import System.Exit (die)
import Theory.Tools.Wellformedness (prettyWfErrorReport)
import Text.Printf (printf)
batchMode :: TamarinMode
batchMode = tamarinMode
"batch"
"Security protocol analysis and verification."
setupFlags
run
where
setupFlags defaultMode = defaultMode
{ modeArgs = ([], Just $ flagArg (updateArg "inFile") "FILES")
, modeGroupFlags = Group
{ groupUnnamed =
theoryLoadFlags ++
[ flagNone ["no-compress"] (addEmptyArg "noCompress")
"Do not use compressed sequent visualization"
, flagNone ["parse-only"] (addEmptyArg "parseOnly")
"Just parse the input file and pretty print it as-is"
] ++
outputFlags ++
toolFlags
, groupHidden = []
, groupNamed = []
}
}
outputFlags =
[ flagOpt "" ["output","o"] (updateArg "outFile") "FILE" "Output file"
, flagOpt "" ["Output","O"] (updateArg "outDir") "DIR" "Output directory"
, flagOpt "spthy" ["output-module", "m"] (updateArg "outModule") moduleList
moduleDescriptions
]
moduleConstructors = enumFrom minBound :: [ModuleType]
moduleList = intercalate "|" $ map show moduleConstructors
moduleDescriptions = "What to output:" ++ intercalate " " (map (\x -> "\n -"++description x) moduleConstructors) ++ "."
run :: TamarinMode -> Arguments -> IO ()
run thisMode as
| null inFiles = helpAndExit thisMode (Just "no input files given")
| argExists "parseOnly" as || argExists "outModule" as = do
res <- mapM (processThy "") inFiles
let (thys, _) = unzip res
mapM_ (putStrLn . renderDoc) thys
putStrLn ""
| otherwise = do
versionData <- ensureMaudeAndGetVersion as
resTimed <- mapM (timedIO . processThy versionData) inFiles
let (docs, reps, times) = unzip3 $ fmap (\((d, r), t) -> (d, r, t)) resTimed
if writeOutput then do
let maybeOutFiles = sequence $ mkOutPath <$> inFiles
outFiles <- case maybeOutFiles of
Just f -> return f
Nothing -> die "Please specify a valid output file/directory"
let repsWithInfo = ppRep <$> zip4 inFiles (Just <$> outFiles) times reps
let summary = Pretty.vcat $ intersperse (Pretty.text "") repsWithInfo
mapM_ (\(o, d) -> writeFileWithDirs o (renderDoc d)) (zip outFiles docs)
putStrLn $ renderDoc $ ppSummary summary
else do
let repsWithInfo = ppRep <$> zip4 inFiles (repeat Nothing) times reps
let summary = Pretty.vcat $ intersperse (Pretty.text "") repsWithInfo
mapM_ (putStrLn . renderDoc) docs
putStrLn $ renderDoc $ ppSummary summary
where
ppSummary summary = Pretty.vcat [ Pretty.text $ ""
, Pretty.text $ replicate 78 '='
, Pretty.text $ "summary of summaries:"
, Pretty.text $ ""
, summary
, Pretty.text $ ""
, Pretty.text $ replicate 78 '=' ]
ppRep (inFile, outFile, time, summary)=
Pretty.vcat [ Pretty.text $ "analyzed: " ++ inFile
, Pretty.text $ ""
, Pretty.text $ ""
, Pretty.nest 2 $ Pretty.vcat [
maybe Pretty.emptyDoc (\o -> Pretty.text $ "output: " ++ o) outFile
, Pretty.text $ printf "processing time: %.2fs" (realToFrac time :: Double)
, Pretty.text $ ""
, summary ] ]
inFiles = reverse $ findArg "inFile" as
thyLoadOptions = case mkTheoryLoadOptions as of
Left (ArgumentError e) -> error e
Right opts -> opts
writeOutput = argExists "outFile" as || argExists "outDir" as
mkOutPath inFile =
do outFile <- findArg "outFile" as
guard (outFile /= "")
return outFile
<|>
do outDir <- findArg "outDir" as
return $ mkAutoPath outDir (takeBaseName inFile)
mkAutoPath :: FilePath -> String -> FilePath
mkAutoPath dir baseName
| argExists "html" as = dir </> baseName
| otherwise = dir </> addExtension (baseName ++ "_analyzed") "spthy"
processThy :: String -> FilePath -> IO (Pretty.Doc, Pretty.Doc)
processThy versionData inFile = either handleError return <=< runExceptT $ do
srcThy <- liftIO $ readFile inFile
thy <- loadTheory thyLoadOptions srcThy inFile
if isParseOnlyMode then do
either (\t -> bisequence (liftIO $ choosePretty t, return Pretty.emptyDoc))
(\d -> return (prettyOpenDiffTheory d, Pretty.emptyDoc)) thy
else do
let sig = either (get thySignature) (get diffThySignature) thy
sig' <- liftIO $ toSignatureWithMaude (get oMaudePath thyLoadOptions) sig
(report, thy') <- closeTheory versionData thyLoadOptions sig' thy
where
isParseOnlyMode = get oParseOnlyMode thyLoadOptions
handleError (ParserError e) = error $ show e
handleError (WarningError report) = do
putStrLn $ renderDoc $ Pretty.vcat [ Pretty.text ""
, Pretty.text "WARNING: the following wellformedness checks failed!"
, Pretty.text ""
, prettyWfErrorReport report
, Pretty.text "" ]
die "quit-on-warning mode selected - aborting on wellformedness errors."
ppWf [] = Pretty.emptyDoc
ppWf rep = Pretty.vcat $ Pretty.text ("WARNING: " ++ show (length rep) ++ " wellformedness check failed!")
: [ Pretty.text " The analysis results might be wrong!" | get oProveMode thyLoadOptions ]
choosePretty = case get oOutputModule thyLoadOptions of
output as is , including SAPIC elements
output as is , including SAPIC elements
Just ModuleMsr -> return . prettyOpenTranslatedTheory
<=< (return . filterLemma (lemmaSelector thyLoadOptions))
<=< (return . removeTranslationItems)
<=< Sapic.typeTheory
<=< Sapic.warnings
Just ModuleProVerif -> Export.prettyProVerifTheory (lemmaSelector thyLoadOptions) <=< Sapic.typeTheoryEnv <=< Sapic.warnings
Just ModuleProVerifEquivalence -> Export.prettyProVerifEquivTheory <=< Sapic.typeTheoryEnv <=< Sapic.warnings
Just ModuleDeepSec -> Export.prettyDeepSecTheory <=< Sapic.typeTheory <=< Sapic.warnings |
186881e9acffaea1631f1f573f223c94eda134a9df1b1cc14ab61d8f009702f1 | rbonichon/smtpp | logic.mli | type arith_sort = Integer | Real | Mixed ;;
(* The basic sort upon which arithmetic can be based *)
type arith_kind = Difference | Linear | NonLinear ;;
Kind of arithmetics used in SMT - LIB benchmarks .
They form a simple lattice .
They form a simple lattice.
*)
val max_kind_opt : arith_kind option -> arith_kind option -> arith_kind option
type t = {
smt_name : string;
mutable array : bool ; (* Array theory on / off ? *)
mutable uninterpreted_functions : bool ;
mutable bitvectors : bool ;
mutable quantifiers : bool ;
mutable arithmetic_sort : arith_sort option ;
mutable arithmetic_kind : arith_kind option ;
}
;;
val default : t
val parse_logic : string -> t
val pp_from_core : Format.formatter -> t -> unit
| null | https://raw.githubusercontent.com/rbonichon/smtpp/57eb74bccbb0f30293ee058ded4b01baa1067756/src/logic.mli | ocaml | The basic sort upon which arithmetic can be based
Array theory on / off ? | type arith_sort = Integer | Real | Mixed ;;
type arith_kind = Difference | Linear | NonLinear ;;
Kind of arithmetics used in SMT - LIB benchmarks .
They form a simple lattice .
They form a simple lattice.
*)
val max_kind_opt : arith_kind option -> arith_kind option -> arith_kind option
type t = {
smt_name : string;
mutable uninterpreted_functions : bool ;
mutable bitvectors : bool ;
mutable quantifiers : bool ;
mutable arithmetic_sort : arith_sort option ;
mutable arithmetic_kind : arith_kind option ;
}
;;
val default : t
val parse_logic : string -> t
val pp_from_core : Format.formatter -> t -> unit
|
d7d504cec9a69304c15b525e8c7f8282d1ae897a10d37856339c0d3f99fbafbb | darcy-shen/dotTeXmacs | init-graph.scm | ; basic functions and macros
(define-macro (foreach i . b)
`(for-each (lambda (,(car i))
,(cons 'begin b))
,(cadr i)))
(define-macro (foreach-number i . b)
`(do ((,(car i) ,(cadr i)
(,(if (memq (caddr i) '(> >=)) '- '+) ,(car i) 1)))
((,(if (eq? (caddr i) '>)
'<=
(if (eq? (caddr i) '<)
'>=
(if (eq? (caddr i) '>=) '< '>)))
,(car i) ,(cadddr i))
,(car i))
,(cons 'begin b)))
(define (list-max nrlist)
(if (null? nrlist) '() (eval (cons 'max nrlist))))
(define (list-sum nrlist)
(if (null? nrlist) '() (eval (cons '+ nrlist))))
; functions for table
(define CELL_HCENTER
'(cwith "1" "-1" "1" "1" "cell-halign" "c"))
(define TABLE_HEAD_COLOR
'(cwith "1" "1" "1" "1" "cell-background" "yellow"))
(define (get-block body)
(cons 'block (cons body '())))
(define (do-get-tformat body)
(list 'tformat CELL_HCENTER TABLE_HEAD_COLOR body))
(define (get-row body)
(cons 'row (cons body '())))
(define (get-cell body)
(cons 'cell (cons body '())))
(define (do-get-table body)
(define result '())
(foreach (i body)
(set! result (cons (get-row (get-cell i)) result)))
(set! result (reverse result))
(cons 'table result))
(define (do-get-block body)
(get-block (do-get-tformat (do-get-table body))))
; functions for graphics
(define (do-get-graphics body) (cons 'graphics body))
(define (do-get-point x y)
(cons 'point (cons (number->string x) (cons (number->string y) '()))))
(define (do-get-x point)
(string->number (list-ref point 1)))
(define (do-get-y point)
(string->number (list-ref point 2)))
in TeXmacs when you look into the source , > appears the same as < gtr >
; but in the exported TeXmacs Scheme source file, they are different
(define (do-get-line point1 point2)
(list 'with "arrow-end" "|<gtr>"
(list 'line
point1
(do-get-point (/ (+ (do-get-x point1) (do-get-x point2)) 2.0)
(do-get-y point1))
(do-get-point (/ (+ (do-get-x point1) (do-get-x point2)) 2.0)
(do-get-y point2))
point2)))
(define (do-get-text-at body position)
(list 'with "text-at-valign" "center" "text-at-halign" "left"
(list 'text-at body position)))
; functions for struct graph
(define (get-width body)
(cadr (box-info body "w")))
(define (get-height body)
(cadr (box-info body "h")))
(define (get-geometry body)
(list (get-width body) (get-height body)))
(define (extract-width elem)
(string->number (car (caddr (car (cadr elem))))))
(define (extract-height elem)
(string->number (cadr (caddr (car (cadr elem))))))
(define (extract-self-width elem)
(string->number (car (cadr (car (cadr elem))))))
(define (extract-self-height elem)
(string->number (cadr (cadr (car (cadr elem))))))
(define (extract-string elem)
(if (list? elem) (cadr elem) elem))
(define (tmlen->graph num)
(/ num 60550.0))
(define (tmlen->gh num)
(/ num 599040.0))
(define (tmlen->gw num)
(/ num 998400.0))
(define (tmlen->par num)
(/ num 998400.0))
(define (tmlen->cm num)
(/ num 60472.4))
(define (cm->tmlen num)
(* num 60472.4))
(define (cm->string num)
(string-append (number->string num) "cm"))
(define (ln->tmlen num)
(/ num 1066))
(define HGAP 80000)
(define VGAP 50000)
(define HPADDING 0.1)
(define VPADDING 0.1)
(define (get-self-and-group-geometry name-body)
(define flag #t)
(define result '())
(define table-content '())
(define body (caddr name-body))
(define name (cadr name-body))
(define the-block '())
; calculate flag
(foreach (elem (cddr body))
(if (list? elem) (set! flag #f) (null? '())))
; calculate table content
(set! table-content (cons (cadr body) table-content))
(foreach (elem (cddr body))
(set! table-content (cons (extract-string elem) table-content)))
(set! table-content (reverse table-content))
(set! the-block (do-get-block table-content))
; calculate result
(foreach (elem (cddr body))
(if (list? elem)
(set! result (cons (get-self-and-group-geometry elem)
result))
(null? '())))
(set! result (reverse result))
; calculate the self geometry and group geometry
(if flag (set! result (cons
(list table-content
(get-geometry the-block)
(get-geometry the-block))
result))
(set! result
(cons (list table-content
(get-geometry the-block)
(list (number->string
(+ (string->number (get-width the-block))
HGAP
(list-max (map extract-width result))))
(number->string
(max (string->number
(get-height the-block))
(+ (list-sum (map extract-height result))
(* VGAP (- (length result) 1)))))))
result)))
(list name result))
; get the position of the struct body
(define (get-position body left bottom top)
(define result '())
(define new-left (+ left (extract-self-width body) HGAP))
(define new-vgap 0)
(define sub-body '())
(define height-list '())
(define tmp-v '())
;; input: (h1 h2 h3) base gap
output : ( base X+h1 ) ( base+h1+gap X+h2 ) ( )
(define (get-tmp-v alist base gap)
(define result '())
(set! alist (reverse alist))
(set! result (cons (list base (+ base (car alist))) result))
(foreach-number (i 1 < (length alist))
(set! result (rcons result
`(,(+ gap (last (last result)))
,(+ gap (list-ref alist i)
(last (last result)))))))
(reverse result))
(set! sub-body (cdr (cadr body)))
(set! height-list (map extract-height sub-body)) ;; edited
;; calculate the new vertical gap
(if (< (length height-list) 2) (null? '())
(set! new-vgap
(/ (- top (+ (list-sum height-list) bottom))
(- (length sub-body) 1))))
(if (= (length height-list) 1) (set! tmp-v (list (list bottom top)))
(null? '()))
(if (< (length height-list) 2) (null? '())
(set! tmp-v (get-tmp-v height-list bottom new-vgap)))
(if (null? height-list) (null? '())
(foreach-number (i 0 < (length height-list))
(set! result
(cons (get-position (list-ref sub-body i)
new-left
(car (list-ref tmp-v i))
(cadr (list-ref tmp-v i)))
result))))
(set! result (reverse result))
(set! result (cons (rcons (car (cadr body))
(list left (/ (+ bottom top) 2.0)))
result))
(list (car body) result))
(define (do-get-struct-tables body)
(define result '())
(define table-content '())
(define point (list-ref (car (cadr body)) 3))
(set! table-content (car (car (cadr body))))
(foreach (elem (cdr (cadr body)))
(set! result (append (do-get-struct-tables elem) result)))
(cons (do-get-text-at
(do-get-block table-content)
(do-get-point (tmlen->graph (car point)) (tmlen->graph (cadr point))))
result))
sx = x , sy = y + ( height/2)*(1 - 1/(length content ) )
(define (do-get-struct-position body)
(define content (car body))
(define x (car (last body)))
(define y (cadr (last body)))
(define height (string->number (cadr (cadr body))))
(do-get-point (tmlen->graph x)
(tmlen->graph (+ y (* (/ height 2.0)
(- 1 (/ 1 (length content))))))))
; sx = x + width
; sy = y + height/2 - (height / (length content)) * ((list-ref)+ 1/2)
(define (list-rref elem alist)
(cond ((null? alist) '())
(else (cond ((eq? elem (car alist)) 0)
(else (+ 1 (list-rref elem (cdr alist))))))))
(define (do-get-member-position elem body)
(define content (car body))
(define x (car (last body)))
(define y (cadr (last body)))
(define height (string->number (cadr (cadr body))))
(define width (string->number (car (cadr body))))
(do-get-point (tmlen->graph (+ x width))
(tmlen->graph (- (+ y (/ height 2.0))
(* (/ height (length content))
(+ (list-rref elem content) (/ 1 2)))))))
(define (do-get-lines body)
(define result '())
(define sub-body (cdr body))
(define name-body (car body))
(foreach (elem sub-body)
(set! result (append result
(do-get-lines (cadr elem)))))
(foreach (elem sub-body)
(set! result (cons (do-get-line (do-get-member-position
(car elem) name-body)
(do-get-struct-position
(car (cadr elem))))
result)))
result)
(tm-define (do-struct-graph body)
(:secure #t)
(define result '())
(define canvas-width 0)
(define canvas-height 0)
(set! body (list 'tree "root" body))
(set! body (get-self-and-group-geometry body))
(set! canvas-width (+ (extract-width body) (cm->tmlen (* 2 HPADDING))))
(set! canvas-height (extract-height body))
(set! body (get-position body 0 0 canvas-height))
(set! canvas-height (+ canvas-height (cm->tmlen (* 2 VPADDING))))
(display* body "\n")
(set! result (do-get-struct-tables body))
(set! result (append result (do-get-lines (cadr body))))
(set! result (list 'with "gr-mode" "point"
"gr-frame"
(list 'tuple "scale" "1cm"
(list 'tuple (cm->string HPADDING)
(cm->string VPADDING)))
"gr-geometry"
(list 'tuple "geometry"
(cm->string (tmlen->cm canvas-width))
(cm->string (tmlen->cm canvas-height)) "center")
(do-get-graphics result)))
result)
(tm-define (struct-graph body)
(:secure #t)
(set! body (tree->stree body))
(do-struct-graph body))
(define (get-list stree)
(define result '())
(cond ((list? stree)
(foreach (elem stree)
(set! result (cons (get-list elem) result)))
(set! result (cons 'list (reverse result))))
(else (set! result stree)))
result)
(tm-define (edit-struct-graph)
(:secure #t)
(define code '())
(with t (focus-tree)
(set! code (list 'do-struct-graph
(get-list (cadr (tree->stree t)))))
(tree-set! t (eval code))))
(kbd-map ("M-e" (edit-struct-graph)))
; draw a rose
(tm-define (rose r nsteps)
(:secure #t)
(define pi (acos -1))
(define points '())
(define lines '())
(set! r (tree->number r))
(set! nsteps (tree->number nsteps))
(foreach-number (i 0 < nsteps)
(with t (/ (* 2 i pi) nsteps)
(set! points
(cons (do-get-point (* r (cos t))
(* r (sin t)))
points))))
(foreach (p1 points)
(foreach (p2 points)
(set! lines (cons `(line ,p1 ,p2) lines))))
`(with "gr-geometry"
,(cons 'tuple
'("geometry" "0.5par" "0.5par" "center"))
,(do-get-graphics (append lines points))))
| null | https://raw.githubusercontent.com/darcy-shen/dotTeXmacs/27833efb9020ba158021cce15c2192c75a152778/legacy-code/graph/progs/init-graph.scm | scheme | basic functions and macros
functions for table
functions for graphics
but in the exported TeXmacs Scheme source file, they are different
functions for struct graph
calculate flag
calculate table content
calculate result
calculate the self geometry and group geometry
get the position of the struct body
input: (h1 h2 h3) base gap
edited
calculate the new vertical gap
sx = x + width
sy = y + height/2 - (height / (length content)) * ((list-ref)+ 1/2)
draw a rose | (define-macro (foreach i . b)
`(for-each (lambda (,(car i))
,(cons 'begin b))
,(cadr i)))
(define-macro (foreach-number i . b)
`(do ((,(car i) ,(cadr i)
(,(if (memq (caddr i) '(> >=)) '- '+) ,(car i) 1)))
((,(if (eq? (caddr i) '>)
'<=
(if (eq? (caddr i) '<)
'>=
(if (eq? (caddr i) '>=) '< '>)))
,(car i) ,(cadddr i))
,(car i))
,(cons 'begin b)))
(define (list-max nrlist)
(if (null? nrlist) '() (eval (cons 'max nrlist))))
(define (list-sum nrlist)
(if (null? nrlist) '() (eval (cons '+ nrlist))))
(define CELL_HCENTER
'(cwith "1" "-1" "1" "1" "cell-halign" "c"))
(define TABLE_HEAD_COLOR
'(cwith "1" "1" "1" "1" "cell-background" "yellow"))
(define (get-block body)
(cons 'block (cons body '())))
(define (do-get-tformat body)
(list 'tformat CELL_HCENTER TABLE_HEAD_COLOR body))
(define (get-row body)
(cons 'row (cons body '())))
(define (get-cell body)
(cons 'cell (cons body '())))
(define (do-get-table body)
(define result '())
(foreach (i body)
(set! result (cons (get-row (get-cell i)) result)))
(set! result (reverse result))
(cons 'table result))
(define (do-get-block body)
(get-block (do-get-tformat (do-get-table body))))
(define (do-get-graphics body) (cons 'graphics body))
(define (do-get-point x y)
(cons 'point (cons (number->string x) (cons (number->string y) '()))))
(define (do-get-x point)
(string->number (list-ref point 1)))
(define (do-get-y point)
(string->number (list-ref point 2)))
in TeXmacs when you look into the source , > appears the same as < gtr >
(define (do-get-line point1 point2)
(list 'with "arrow-end" "|<gtr>"
(list 'line
point1
(do-get-point (/ (+ (do-get-x point1) (do-get-x point2)) 2.0)
(do-get-y point1))
(do-get-point (/ (+ (do-get-x point1) (do-get-x point2)) 2.0)
(do-get-y point2))
point2)))
(define (do-get-text-at body position)
(list 'with "text-at-valign" "center" "text-at-halign" "left"
(list 'text-at body position)))
(define (get-width body)
(cadr (box-info body "w")))
(define (get-height body)
(cadr (box-info body "h")))
(define (get-geometry body)
(list (get-width body) (get-height body)))
(define (extract-width elem)
(string->number (car (caddr (car (cadr elem))))))
(define (extract-height elem)
(string->number (cadr (caddr (car (cadr elem))))))
(define (extract-self-width elem)
(string->number (car (cadr (car (cadr elem))))))
(define (extract-self-height elem)
(string->number (cadr (cadr (car (cadr elem))))))
(define (extract-string elem)
(if (list? elem) (cadr elem) elem))
(define (tmlen->graph num)
(/ num 60550.0))
(define (tmlen->gh num)
(/ num 599040.0))
(define (tmlen->gw num)
(/ num 998400.0))
(define (tmlen->par num)
(/ num 998400.0))
(define (tmlen->cm num)
(/ num 60472.4))
(define (cm->tmlen num)
(* num 60472.4))
(define (cm->string num)
(string-append (number->string num) "cm"))
(define (ln->tmlen num)
(/ num 1066))
(define HGAP 80000)
(define VGAP 50000)
(define HPADDING 0.1)
(define VPADDING 0.1)
(define (get-self-and-group-geometry name-body)
(define flag #t)
(define result '())
(define table-content '())
(define body (caddr name-body))
(define name (cadr name-body))
(define the-block '())
(foreach (elem (cddr body))
(if (list? elem) (set! flag #f) (null? '())))
(set! table-content (cons (cadr body) table-content))
(foreach (elem (cddr body))
(set! table-content (cons (extract-string elem) table-content)))
(set! table-content (reverse table-content))
(set! the-block (do-get-block table-content))
(foreach (elem (cddr body))
(if (list? elem)
(set! result (cons (get-self-and-group-geometry elem)
result))
(null? '())))
(set! result (reverse result))
(if flag (set! result (cons
(list table-content
(get-geometry the-block)
(get-geometry the-block))
result))
(set! result
(cons (list table-content
(get-geometry the-block)
(list (number->string
(+ (string->number (get-width the-block))
HGAP
(list-max (map extract-width result))))
(number->string
(max (string->number
(get-height the-block))
(+ (list-sum (map extract-height result))
(* VGAP (- (length result) 1)))))))
result)))
(list name result))
(define (get-position body left bottom top)
(define result '())
(define new-left (+ left (extract-self-width body) HGAP))
(define new-vgap 0)
(define sub-body '())
(define height-list '())
(define tmp-v '())
output : ( base X+h1 ) ( base+h1+gap X+h2 ) ( )
(define (get-tmp-v alist base gap)
(define result '())
(set! alist (reverse alist))
(set! result (cons (list base (+ base (car alist))) result))
(foreach-number (i 1 < (length alist))
(set! result (rcons result
`(,(+ gap (last (last result)))
,(+ gap (list-ref alist i)
(last (last result)))))))
(reverse result))
(set! sub-body (cdr (cadr body)))
(if (< (length height-list) 2) (null? '())
(set! new-vgap
(/ (- top (+ (list-sum height-list) bottom))
(- (length sub-body) 1))))
(if (= (length height-list) 1) (set! tmp-v (list (list bottom top)))
(null? '()))
(if (< (length height-list) 2) (null? '())
(set! tmp-v (get-tmp-v height-list bottom new-vgap)))
(if (null? height-list) (null? '())
(foreach-number (i 0 < (length height-list))
(set! result
(cons (get-position (list-ref sub-body i)
new-left
(car (list-ref tmp-v i))
(cadr (list-ref tmp-v i)))
result))))
(set! result (reverse result))
(set! result (cons (rcons (car (cadr body))
(list left (/ (+ bottom top) 2.0)))
result))
(list (car body) result))
(define (do-get-struct-tables body)
(define result '())
(define table-content '())
(define point (list-ref (car (cadr body)) 3))
(set! table-content (car (car (cadr body))))
(foreach (elem (cdr (cadr body)))
(set! result (append (do-get-struct-tables elem) result)))
(cons (do-get-text-at
(do-get-block table-content)
(do-get-point (tmlen->graph (car point)) (tmlen->graph (cadr point))))
result))
sx = x , sy = y + ( height/2)*(1 - 1/(length content ) )
(define (do-get-struct-position body)
(define content (car body))
(define x (car (last body)))
(define y (cadr (last body)))
(define height (string->number (cadr (cadr body))))
(do-get-point (tmlen->graph x)
(tmlen->graph (+ y (* (/ height 2.0)
(- 1 (/ 1 (length content))))))))
(define (list-rref elem alist)
(cond ((null? alist) '())
(else (cond ((eq? elem (car alist)) 0)
(else (+ 1 (list-rref elem (cdr alist))))))))
(define (do-get-member-position elem body)
(define content (car body))
(define x (car (last body)))
(define y (cadr (last body)))
(define height (string->number (cadr (cadr body))))
(define width (string->number (car (cadr body))))
(do-get-point (tmlen->graph (+ x width))
(tmlen->graph (- (+ y (/ height 2.0))
(* (/ height (length content))
(+ (list-rref elem content) (/ 1 2)))))))
(define (do-get-lines body)
(define result '())
(define sub-body (cdr body))
(define name-body (car body))
(foreach (elem sub-body)
(set! result (append result
(do-get-lines (cadr elem)))))
(foreach (elem sub-body)
(set! result (cons (do-get-line (do-get-member-position
(car elem) name-body)
(do-get-struct-position
(car (cadr elem))))
result)))
result)
(tm-define (do-struct-graph body)
(:secure #t)
(define result '())
(define canvas-width 0)
(define canvas-height 0)
(set! body (list 'tree "root" body))
(set! body (get-self-and-group-geometry body))
(set! canvas-width (+ (extract-width body) (cm->tmlen (* 2 HPADDING))))
(set! canvas-height (extract-height body))
(set! body (get-position body 0 0 canvas-height))
(set! canvas-height (+ canvas-height (cm->tmlen (* 2 VPADDING))))
(display* body "\n")
(set! result (do-get-struct-tables body))
(set! result (append result (do-get-lines (cadr body))))
(set! result (list 'with "gr-mode" "point"
"gr-frame"
(list 'tuple "scale" "1cm"
(list 'tuple (cm->string HPADDING)
(cm->string VPADDING)))
"gr-geometry"
(list 'tuple "geometry"
(cm->string (tmlen->cm canvas-width))
(cm->string (tmlen->cm canvas-height)) "center")
(do-get-graphics result)))
result)
(tm-define (struct-graph body)
(:secure #t)
(set! body (tree->stree body))
(do-struct-graph body))
(define (get-list stree)
(define result '())
(cond ((list? stree)
(foreach (elem stree)
(set! result (cons (get-list elem) result)))
(set! result (cons 'list (reverse result))))
(else (set! result stree)))
result)
(tm-define (edit-struct-graph)
(:secure #t)
(define code '())
(with t (focus-tree)
(set! code (list 'do-struct-graph
(get-list (cadr (tree->stree t)))))
(tree-set! t (eval code))))
(kbd-map ("M-e" (edit-struct-graph)))
(tm-define (rose r nsteps)
(:secure #t)
(define pi (acos -1))
(define points '())
(define lines '())
(set! r (tree->number r))
(set! nsteps (tree->number nsteps))
(foreach-number (i 0 < nsteps)
(with t (/ (* 2 i pi) nsteps)
(set! points
(cons (do-get-point (* r (cos t))
(* r (sin t)))
points))))
(foreach (p1 points)
(foreach (p2 points)
(set! lines (cons `(line ,p1 ,p2) lines))))
`(with "gr-geometry"
,(cons 'tuple
'("geometry" "0.5par" "0.5par" "center"))
,(do-get-graphics (append lines points))))
|
260b28f2db154067c60a44c6562b5adcc4b00beeb229d230ef3ea8460460ac1c | synduce/Synduce | test.ml | (* Non-empty lists type. *)
type list = Elt of int * int | Cons of int * int * list
(* A binary search tree with integer keys and positive natural numbers as values. *)
type bst_map = KeyValue of int * int | Node of int * bst_map * bst_map
let rec min_key = function KeyValue (k, v) -> k | Node (a, l, r) -> min (min_key l) (min_key r)
let rec max_key = function KeyValue (k, v) -> k | Node (a, l, r) -> max (max_key l) (max_key r)
let rec is_imap = function
| KeyValue (k, v) -> true
| Node (a, l, r) -> max_key l < a && a <= min_key r && is_imap l && is_imap r
let rec repr = function KeyValue (k, v) -> Elt (k, v) | Node (a, l, r) -> append (repr l) (repr r)
and append x = function
| Elt (x0, y0) -> Cons (x0, y0, x)
| Cons (hd0, hd1, tl) -> Cons (hd0, hd1, append x tl)
(* Return most frequent element with its count. *)
let spec key l =
let rec f = function
| Elt (k, v) -> if k > key then v else 0
| Cons (hdk, hdv, tl) -> if hdk > key then hdv + f tl else f tl
in
f l
Synthesize a parallel version that is also linear time .
let target key t =
let rec g = function
| KeyValue (k, v) -> [%synt s0] key k v
| Node (hd_key, l, r) ->
if hd_key > key then [%synt join1] key hd_key (g l) (g r)
else [%synt join2] key hd_key (g r)
in
g t
[@@requires is_imap]
| null | https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/constraints/bst/test.ml | ocaml | Non-empty lists type.
A binary search tree with integer keys and positive natural numbers as values.
Return most frequent element with its count. | type list = Elt of int * int | Cons of int * int * list
type bst_map = KeyValue of int * int | Node of int * bst_map * bst_map
let rec min_key = function KeyValue (k, v) -> k | Node (a, l, r) -> min (min_key l) (min_key r)
let rec max_key = function KeyValue (k, v) -> k | Node (a, l, r) -> max (max_key l) (max_key r)
let rec is_imap = function
| KeyValue (k, v) -> true
| Node (a, l, r) -> max_key l < a && a <= min_key r && is_imap l && is_imap r
let rec repr = function KeyValue (k, v) -> Elt (k, v) | Node (a, l, r) -> append (repr l) (repr r)
and append x = function
| Elt (x0, y0) -> Cons (x0, y0, x)
| Cons (hd0, hd1, tl) -> Cons (hd0, hd1, append x tl)
let spec key l =
let rec f = function
| Elt (k, v) -> if k > key then v else 0
| Cons (hdk, hdv, tl) -> if hdk > key then hdv + f tl else f tl
in
f l
Synthesize a parallel version that is also linear time .
let target key t =
let rec g = function
| KeyValue (k, v) -> [%synt s0] key k v
| Node (hd_key, l, r) ->
if hd_key > key then [%synt join1] key hd_key (g l) (g r)
else [%synt join2] key hd_key (g r)
in
g t
[@@requires is_imap]
|
0723d77c40cbe7e6647cc98df5cdf896224d881e83ed18ac28cb81d850a4d6a6 | lispgames/perfectstorm | quadtree.lisp | (in-package :storm)
(defparameter *quadtree-default-depth* 6)
(defparameter *quadtree-epsilon* 0.0000023)
; new generics
(defgeneric localize (object1 object2))
; for vertices
(defgeneric lines (vertex)) ;
(defgeneric add-neighbour (vertex1 vertex2)) ;
(defgeneric remove-neighbour (vertex1 vertex2)) ;
(defgeneric compare (vertex1 vertex2)) ;
returns the interection of the margins of vertex1 and ( as ` line ` object )
(defgeneric split! (vertex &key)) ;
; for edges
(defgeneric weight (edge))
(defgeneric opposite-vertex (edge vertex))
(defgeneric connects-vertices? (edge vertex1 vertex2))
;;; some functions for debugging
(defun quadtree-test ()
(let* ((objects
(list
(make-instance 'polygon :corners (list (make-point 50 30)
(make-point 30 50)
(make-point 50 70)
(make-point 70 50)))
(make-instance 'polygon :corners (list (make-point 0 80)
(make-point 10 50)
(make-point -10 10)))
(make-instance 'polygon :corners (list (make-point -40 -40)
(make-point -160 30)
(make-point -150 -100)
(make-point -100 -50)))
(make-instance 'polygon :corners (list (make-point 15 0)
(make-point 40 0)
(make-point 25 -30)
(make-point 80 -40)
(make-point 60 10)
(make-point 90 -30)
(make-point 100 -100)
(make-point 30 -80))))))
(make-instance 'quadtree
:bottom-left-corner (make-point -200 -200)
:width 400
:height 400
:objects objects)))
TODO this should be somewhere else
(defun objects-draw (objects)
(dolist (o objects)
(loop :for i :below (length (corners o)) :do
(push (make-instance 'visible-line
:size-y 0.2
:points (list (elt (corners o) i)
(elt-mod (corners o) (+ i 1))))
*gui-things*))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass quadtree ()
((root
:reader root)
(display-list
:initform nil
:accessor display-list)))
(defmethod initialize-instance :after ((quadtree quadtree)
&key
(bounding-box nil)
(bottom-left-corner nil) (width 0) (height 0)
(objects ())
(quadtree-depth *quadtree-default-depth*))
initialize quadtree from bounding - box or bottom - left - corner , width and height
(setf (slot-value quadtree 'root)
(make-instance
'quadtree-vertex
:parent nil
:corners (cond
(bounding-box
(list
(make-point (xmin bounding-box) (ymax bounding-box))
(make-point (xmin bounding-box) (ymin bounding-box))
(make-point (xmax bounding-box) (ymin bounding-box))
(make-point (xmax bounding-box) (ymax bounding-box))))
(bottom-left-corner
(list
(make-point (x bottom-left-corner) (+ (y bottom-left-corner) height))
(make-point (x bottom-left-corner) (y bottom-left-corner))
(make-point (+ (x bottom-left-corner) width) (y bottom-left-corner))
(make-point (+ (x bottom-left-corner) width) (+ (y bottom-left-corner) height))))
(t
(error "you have to initialize the quadtree with a bounding-box or a bottom-left-corner, width and height")))))
(setf (objects (root quadtree)) objects)
; build up tree
(split! (root quadtree) :quadtree-depth quadtree-depth))
throws exception , if point not in quadtree , returns leaf else
(defmethod localize ((quadtree quadtree) (point vektor))
(let ((result (localize (root quadtree) point)))
(if result
result
(error "quadtree doesn't contain point ~a" point))))
(defmethod traverse (function (quadtree quadtree) &key (mode :leaves) (collect-results nil))
(traverse function (root quadtree) :mode mode :collect-results collect-results))
(defmethod draw ((quadtree quadtree))
(when (not (display-list quadtree))
(setf (display-list quadtree) (gl:gen-lists 1))
(gl:with-new-list ((display-list quadtree) :compile)
(gl:color 1 0 0 0.9)
(gl:bind-texture :texture-2d (gethash 'visible-line *textures*))
(traverse (lambda (v)
(draw-line-strip (corners v) 1 :closed t :bind-texture nil))
quadtree :mode :all :collect-results nil)
(gl:color 0 1 0 0.9)
(traverse (lambda (v)
(loop :for edge :in (incident-edges v)
:do (when (eq (first (vertices edge)) v)
(draw-line-strip (list (center v)
(center (opposite-vertex edge v)))
1
:closed nil :bind-texture nil))))
quadtree :collect-results nil)))
(gl:call-list (display-list quadtree)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass quadtree-vertex ()
((corners
:initarg :corners
:initform (error "quadtree-vertex needs corners")
:reader corners)
(center
:reader center)
(objects
:initform ()
:accessor objects)
(parent
:initarg :parent
:initform (error "quadtree-vertex is an orphan :(")
:reader parent)
(level
:accessor level)
(children
:initform ()
:accessor children)
(incident-edges
:initform ()
:accessor incident-edges)
(bounding-box
:initform nil)
(a*-data
:accessor a*-data)))
(defmethod initialize-instance :after ((v quadtree-vertex) &key)
(setf (slot-value v 'center) (convex-combination (first (corners v)) (third (corners v)) 0.5))
(setf (level v) (if (parent v) (+ 1 (level (parent v))) 0)))
(defmethod bounding-box ((v quadtree-vertex))
(when (not (slot-value v 'bounding-box))
(setf (slot-value v 'bounding-box)
(make-instance 'bounding-box
:xmin (x (second (corners v)))
:xmax (x (fourth (corners v)))
:ymin (y (second (corners v)))
:ymax (y (fourth (corners v))))))
(slot-value v 'bounding-box))
(defmethod contains? ((v quadtree-vertex) (p vektor))
(contains? (bounding-box v) p))
; ATTENTION: possible numerical problems here!
two vertices v and u are incident iff an edge of one of them is part of an edge of the other .
; due to numerical inaccuracies it might happen that the bounding-box check below fails
( the one edge might be slightly away from the other ) .
maybe ( distance one - edge other - edge ) < eps should be used here ( for each pair of edges ) but
; this solution is much faster and seems to work perfectly.
;
i think that nothing bad can happen if you consider the way the quadtree is computed ...
; you want proof? i have none... ;)
(defmethod incident? ((v quadtree-vertex) (u quadtree-vertex))
(or
(= 2 (loop :for corner :in (corners v) :sum
(if (contains? (bounding-box u) corner) 1 0)))
(= 2 (loop :for corner :in (corners u) :sum
(if (contains? (bounding-box v) corner) 1 0)))))
(defmethod localize ((v quadtree-vertex) (p vektor))
(when (children v)
(dolist (child (children v))
(when (and child (contains? child p))
(return-from localize (localize child p))))
(return-from localize nil))
v)
(defmethod add-neighbour ((v quadtree-vertex) (u quadtree-vertex))
(let ((edge (make-instance 'quadtree-edge :vertices (list v u))))
(push edge (incident-edges v))
(push edge (incident-edges u))))
(defmethod remove-neighbour ((v quadtree-vertex) (u quadtree-vertex))
(setf (incident-edges v) (remove-if (lambda (e) (connects-vertices? e u v)) (incident-edges v)))
(setf (incident-edges u) (remove-if (lambda (e) (connects-vertices? e u v)) (incident-edges u))))
(defmacro quadtree-vertex-with-neighbours (vertex &body body)
`(dolist (edge (incident-edges ,vertex))
(let ((neighbour (opposite-vertex edge ,vertex)))
,@body)))
(defmethod compare ((v quadtree-vertex) (u quadtree-vertex))
(- (level u) (level v)))
(defmethod margin-lines ((v quadtree-vertex))
(loop :for i :below 4 :collect
(make-line (elt (corners v) i) (elt-mod (corners v) (+ i 1)))))
(defmethod common-margin ((v quadtree-vertex) (u quadtree-vertex))
(destructuring-bind (smaller bigger) (if (> 0 (compare v u)) (list v u) (list u v))
(dolist (margin-line (margin-lines smaller))
(when (intersect margin-line (make-line (center smaller) (center bigger)))
(return-from common-margin margin-line)))))
(defmethod star-point? ((v quadtree-vertex) (u quadtree-vertex) (p vektor))
(let ((cmp (compare v u))
(common-margin (common-margin v u)))
(or (= 0 cmp)
(< (abs (reduce #'+ (mapcar (lambda (c)
(distance common-margin
(make-line p c)))
(corners (if (> 0 cmp) v u)))))
*quadtree-epsilon*))))
(defmethod split! ((parent quadtree-vertex) &key (quadtree-depth *quadtree-default-depth*))
(macrolet ((select-corners (i j k l) `(list (elt corners ,i)
(elt corners ,j)
(elt corners ,k)
(elt corners ,l))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; calculate splitting points (the children's corners)
;
; scheme (of identifiers):
;
; a,b,c,d : corners of parent
; 0,1,...,8 : index of corner in list of corners
; c-0,...,c-3 : children
;
; a=0-----1-----2=d
; | | |
; | c-0 | c-3 |
; | | |
; 3-----4-----5
; | | |
; | c-1 | c-2 |
; | | |
; b=6-----7-----8=c
;
(let* ((a (first (corners parent)))
(b (second (corners parent)))
(c (third (corners parent)))
(d (fourth (corners parent)))
(corners (list a (convex-combination a d 0.5) d
(convex-combination a b 0.5) (convex-combination a c 0.5) (convex-combination c d 0.5)
b (convex-combination b c 0.5) c))
(children (list (make-instance 'quadtree-vertex :corners (select-corners 0 3 4 1) :parent parent)
(make-instance 'quadtree-vertex :corners (select-corners 3 6 7 4) :parent parent)
(make-instance 'quadtree-vertex :corners (select-corners 4 7 8 5) :parent parent)
(make-instance 'quadtree-vertex :corners (select-corners 1 4 5 2) :parent parent))))
(setf (children parent) children)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; allocate objects
(loop
:for i :below 4 :do
(block allocate-objects-to-child-i
(let* ((child (elt children i))
(child-polygon (make-instance 'polygon :corners (corners child))))
(dolist (o (objects parent))
(let ((intersection (intersects? child-polygon o :check-inclusion t)))
(when intersection
(if (eq intersection child-polygon)
; child is completely inside of the object (see documentation of 'intersects?')
; => drop and continue with next child
(progn
(setf (elt children i) nil)
(return-from allocate-objects-to-child-i))
; object intersects child
(push o (objects child)))))))))
; children must not contain any obects if finest resolution is reached
; => remove children that contain objects
(when (= quadtree-depth 0)
(setf children (mapcar (lambda (c) (if (and c (objects c)) nil c)) children)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; update neighbourhood
; allocate neighbours to children
(dolist (edge (incident-edges parent))
(let ((neighbour (opposite-vertex edge parent)))
(dolist (child children)
(when (and child (incident? child neighbour))
(add-neighbour child neighbour)))))
; some children are neighbours
(loop
:for i :below 4 :do
(when (and (elt children i) (elt-mod children (+ i 1)))
(add-neighbour (elt children i) (elt-mod children (+ i 1)))))
; the parent's neighbours are removed
(dolist (edge (copy-list (incident-edges parent)))
(remove-neighbour parent (opposite-vertex edge parent)))
; go on splitting?
(when (> quadtree-depth 0)
(dolist (child children)
(when (and child (objects child))
(split! child :quadtree-depth (- quadtree-depth 1))))))))
(defmethod traverse (function (v quadtree-vertex) &key (mode :leaves) (collect-results nil))
(let ((results ()))
(if (children v)
(progn
(when (not (eq mode :leaves))
(let ((result (funcall function v)))
(when collect-results
(push result results))))
(dolist (child (children v))
(when child
(let ((result (traverse function child :mode mode :collect-results collect-results)))
(when collect-results
(setf results (append result results)))))))
; vertex has no children => leaf
(let ((result (funcall function v)))
(when collect-results
(push result results))))
results))
(defmethod print-object ((v quadtree-vertex) stream)
(format stream "{quadtree-vertex: ~a}" (corners v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass quadtree-edge ()
((vertices
:initarg :vertices
:initform (error "quadtree-edge needs vertices")
:reader vertices)
(weight
:initform nil)
(margin-crossing-point
:reader margin-crossing-point)))
(defmethod initialize-instance :after ((edge quadtree-edge) &key)
(let* ((u (first (vertices edge)))
(v (second (vertices edge)))
(common-margin (common-margin u v)))
(setf (slot-value edge 'margin-crossing-point)
(intersect (make-line (center u) (center v)) common-margin))))
(defmethod weight ((edge quadtree-edge))
(when (not (slot-value edge 'weight))
(setf (slot-value edge 'weight)
(distance (center (first (vertices edge)))
(center (second (vertices edge))))))
(slot-value edge 'weight))
(defmethod opposite-vertex ((edge quadtree-edge) (vertex quadtree-vertex))
(if (eq vertex (first (vertices edge)))
(second (vertices edge))
(first (vertices edge))))
(defmethod connects-vertices? ((edge quadtree-edge) (v quadtree-vertex) (u quadtree-vertex))
(or (and (eq (first (vertices edge)) v) (eq (second (vertices edge)) u))
(and (eq (first (vertices edge)) u) (eq (second (vertices edge)) v))))
| null | https://raw.githubusercontent.com/lispgames/perfectstorm/a21e0420deb3ec83e9d776241ab37e78c5f29b94/perfectstorm/quadtree.lisp | lisp | new generics
for vertices
for edges
some functions for debugging
build up tree
ATTENTION: possible numerical problems here!
due to numerical inaccuracies it might happen that the bounding-box check below fails
this solution is much faster and seems to work perfectly.
you want proof? i have none... ;)
calculate splitting points (the children's corners)
scheme (of identifiers):
a,b,c,d : corners of parent
0,1,...,8 : index of corner in list of corners
c-0,...,c-3 : children
a=0-----1-----2=d
| | |
| c-0 | c-3 |
| | |
3-----4-----5
| | |
| c-1 | c-2 |
| | |
b=6-----7-----8=c
allocate objects
child is completely inside of the object (see documentation of 'intersects?')
=> drop and continue with next child
object intersects child
children must not contain any obects if finest resolution is reached
=> remove children that contain objects
update neighbourhood
allocate neighbours to children
some children are neighbours
the parent's neighbours are removed
go on splitting?
vertex has no children => leaf
| (in-package :storm)
(defparameter *quadtree-default-depth* 6)
(defparameter *quadtree-epsilon* 0.0000023)
(defgeneric localize (object1 object2))
returns the interection of the margins of vertex1 and ( as ` line ` object )
(defgeneric weight (edge))
(defgeneric opposite-vertex (edge vertex))
(defgeneric connects-vertices? (edge vertex1 vertex2))
(defun quadtree-test ()
(let* ((objects
(list
(make-instance 'polygon :corners (list (make-point 50 30)
(make-point 30 50)
(make-point 50 70)
(make-point 70 50)))
(make-instance 'polygon :corners (list (make-point 0 80)
(make-point 10 50)
(make-point -10 10)))
(make-instance 'polygon :corners (list (make-point -40 -40)
(make-point -160 30)
(make-point -150 -100)
(make-point -100 -50)))
(make-instance 'polygon :corners (list (make-point 15 0)
(make-point 40 0)
(make-point 25 -30)
(make-point 80 -40)
(make-point 60 10)
(make-point 90 -30)
(make-point 100 -100)
(make-point 30 -80))))))
(make-instance 'quadtree
:bottom-left-corner (make-point -200 -200)
:width 400
:height 400
:objects objects)))
TODO this should be somewhere else
(defun objects-draw (objects)
(dolist (o objects)
(loop :for i :below (length (corners o)) :do
(push (make-instance 'visible-line
:size-y 0.2
:points (list (elt (corners o) i)
(elt-mod (corners o) (+ i 1))))
*gui-things*))))
(defclass quadtree ()
((root
:reader root)
(display-list
:initform nil
:accessor display-list)))
(defmethod initialize-instance :after ((quadtree quadtree)
&key
(bounding-box nil)
(bottom-left-corner nil) (width 0) (height 0)
(objects ())
(quadtree-depth *quadtree-default-depth*))
initialize quadtree from bounding - box or bottom - left - corner , width and height
(setf (slot-value quadtree 'root)
(make-instance
'quadtree-vertex
:parent nil
:corners (cond
(bounding-box
(list
(make-point (xmin bounding-box) (ymax bounding-box))
(make-point (xmin bounding-box) (ymin bounding-box))
(make-point (xmax bounding-box) (ymin bounding-box))
(make-point (xmax bounding-box) (ymax bounding-box))))
(bottom-left-corner
(list
(make-point (x bottom-left-corner) (+ (y bottom-left-corner) height))
(make-point (x bottom-left-corner) (y bottom-left-corner))
(make-point (+ (x bottom-left-corner) width) (y bottom-left-corner))
(make-point (+ (x bottom-left-corner) width) (+ (y bottom-left-corner) height))))
(t
(error "you have to initialize the quadtree with a bounding-box or a bottom-left-corner, width and height")))))
(setf (objects (root quadtree)) objects)
(split! (root quadtree) :quadtree-depth quadtree-depth))
throws exception , if point not in quadtree , returns leaf else
(defmethod localize ((quadtree quadtree) (point vektor))
(let ((result (localize (root quadtree) point)))
(if result
result
(error "quadtree doesn't contain point ~a" point))))
(defmethod traverse (function (quadtree quadtree) &key (mode :leaves) (collect-results nil))
(traverse function (root quadtree) :mode mode :collect-results collect-results))
(defmethod draw ((quadtree quadtree))
(when (not (display-list quadtree))
(setf (display-list quadtree) (gl:gen-lists 1))
(gl:with-new-list ((display-list quadtree) :compile)
(gl:color 1 0 0 0.9)
(gl:bind-texture :texture-2d (gethash 'visible-line *textures*))
(traverse (lambda (v)
(draw-line-strip (corners v) 1 :closed t :bind-texture nil))
quadtree :mode :all :collect-results nil)
(gl:color 0 1 0 0.9)
(traverse (lambda (v)
(loop :for edge :in (incident-edges v)
:do (when (eq (first (vertices edge)) v)
(draw-line-strip (list (center v)
(center (opposite-vertex edge v)))
1
:closed nil :bind-texture nil))))
quadtree :collect-results nil)))
(gl:call-list (display-list quadtree)))
(defclass quadtree-vertex ()
((corners
:initarg :corners
:initform (error "quadtree-vertex needs corners")
:reader corners)
(center
:reader center)
(objects
:initform ()
:accessor objects)
(parent
:initarg :parent
:initform (error "quadtree-vertex is an orphan :(")
:reader parent)
(level
:accessor level)
(children
:initform ()
:accessor children)
(incident-edges
:initform ()
:accessor incident-edges)
(bounding-box
:initform nil)
(a*-data
:accessor a*-data)))
(defmethod initialize-instance :after ((v quadtree-vertex) &key)
(setf (slot-value v 'center) (convex-combination (first (corners v)) (third (corners v)) 0.5))
(setf (level v) (if (parent v) (+ 1 (level (parent v))) 0)))
(defmethod bounding-box ((v quadtree-vertex))
(when (not (slot-value v 'bounding-box))
(setf (slot-value v 'bounding-box)
(make-instance 'bounding-box
:xmin (x (second (corners v)))
:xmax (x (fourth (corners v)))
:ymin (y (second (corners v)))
:ymax (y (fourth (corners v))))))
(slot-value v 'bounding-box))
(defmethod contains? ((v quadtree-vertex) (p vektor))
(contains? (bounding-box v) p))
two vertices v and u are incident iff an edge of one of them is part of an edge of the other .
( the one edge might be slightly away from the other ) .
maybe ( distance one - edge other - edge ) < eps should be used here ( for each pair of edges ) but
i think that nothing bad can happen if you consider the way the quadtree is computed ...
(defmethod incident? ((v quadtree-vertex) (u quadtree-vertex))
(or
(= 2 (loop :for corner :in (corners v) :sum
(if (contains? (bounding-box u) corner) 1 0)))
(= 2 (loop :for corner :in (corners u) :sum
(if (contains? (bounding-box v) corner) 1 0)))))
(defmethod localize ((v quadtree-vertex) (p vektor))
(when (children v)
(dolist (child (children v))
(when (and child (contains? child p))
(return-from localize (localize child p))))
(return-from localize nil))
v)
(defmethod add-neighbour ((v quadtree-vertex) (u quadtree-vertex))
(let ((edge (make-instance 'quadtree-edge :vertices (list v u))))
(push edge (incident-edges v))
(push edge (incident-edges u))))
(defmethod remove-neighbour ((v quadtree-vertex) (u quadtree-vertex))
(setf (incident-edges v) (remove-if (lambda (e) (connects-vertices? e u v)) (incident-edges v)))
(setf (incident-edges u) (remove-if (lambda (e) (connects-vertices? e u v)) (incident-edges u))))
(defmacro quadtree-vertex-with-neighbours (vertex &body body)
`(dolist (edge (incident-edges ,vertex))
(let ((neighbour (opposite-vertex edge ,vertex)))
,@body)))
(defmethod compare ((v quadtree-vertex) (u quadtree-vertex))
(- (level u) (level v)))
(defmethod margin-lines ((v quadtree-vertex))
(loop :for i :below 4 :collect
(make-line (elt (corners v) i) (elt-mod (corners v) (+ i 1)))))
(defmethod common-margin ((v quadtree-vertex) (u quadtree-vertex))
(destructuring-bind (smaller bigger) (if (> 0 (compare v u)) (list v u) (list u v))
(dolist (margin-line (margin-lines smaller))
(when (intersect margin-line (make-line (center smaller) (center bigger)))
(return-from common-margin margin-line)))))
(defmethod star-point? ((v quadtree-vertex) (u quadtree-vertex) (p vektor))
(let ((cmp (compare v u))
(common-margin (common-margin v u)))
(or (= 0 cmp)
(< (abs (reduce #'+ (mapcar (lambda (c)
(distance common-margin
(make-line p c)))
(corners (if (> 0 cmp) v u)))))
*quadtree-epsilon*))))
(defmethod split! ((parent quadtree-vertex) &key (quadtree-depth *quadtree-default-depth*))
(macrolet ((select-corners (i j k l) `(list (elt corners ,i)
(elt corners ,j)
(elt corners ,k)
(elt corners ,l))))
(let* ((a (first (corners parent)))
(b (second (corners parent)))
(c (third (corners parent)))
(d (fourth (corners parent)))
(corners (list a (convex-combination a d 0.5) d
(convex-combination a b 0.5) (convex-combination a c 0.5) (convex-combination c d 0.5)
b (convex-combination b c 0.5) c))
(children (list (make-instance 'quadtree-vertex :corners (select-corners 0 3 4 1) :parent parent)
(make-instance 'quadtree-vertex :corners (select-corners 3 6 7 4) :parent parent)
(make-instance 'quadtree-vertex :corners (select-corners 4 7 8 5) :parent parent)
(make-instance 'quadtree-vertex :corners (select-corners 1 4 5 2) :parent parent))))
(setf (children parent) children)
(loop
:for i :below 4 :do
(block allocate-objects-to-child-i
(let* ((child (elt children i))
(child-polygon (make-instance 'polygon :corners (corners child))))
(dolist (o (objects parent))
(let ((intersection (intersects? child-polygon o :check-inclusion t)))
(when intersection
(if (eq intersection child-polygon)
(progn
(setf (elt children i) nil)
(return-from allocate-objects-to-child-i))
(push o (objects child)))))))))
(when (= quadtree-depth 0)
(setf children (mapcar (lambda (c) (if (and c (objects c)) nil c)) children)))
(dolist (edge (incident-edges parent))
(let ((neighbour (opposite-vertex edge parent)))
(dolist (child children)
(when (and child (incident? child neighbour))
(add-neighbour child neighbour)))))
(loop
:for i :below 4 :do
(when (and (elt children i) (elt-mod children (+ i 1)))
(add-neighbour (elt children i) (elt-mod children (+ i 1)))))
(dolist (edge (copy-list (incident-edges parent)))
(remove-neighbour parent (opposite-vertex edge parent)))
(when (> quadtree-depth 0)
(dolist (child children)
(when (and child (objects child))
(split! child :quadtree-depth (- quadtree-depth 1))))))))
(defmethod traverse (function (v quadtree-vertex) &key (mode :leaves) (collect-results nil))
(let ((results ()))
(if (children v)
(progn
(when (not (eq mode :leaves))
(let ((result (funcall function v)))
(when collect-results
(push result results))))
(dolist (child (children v))
(when child
(let ((result (traverse function child :mode mode :collect-results collect-results)))
(when collect-results
(setf results (append result results)))))))
(let ((result (funcall function v)))
(when collect-results
(push result results))))
results))
(defmethod print-object ((v quadtree-vertex) stream)
(format stream "{quadtree-vertex: ~a}" (corners v)))
(defclass quadtree-edge ()
((vertices
:initarg :vertices
:initform (error "quadtree-edge needs vertices")
:reader vertices)
(weight
:initform nil)
(margin-crossing-point
:reader margin-crossing-point)))
(defmethod initialize-instance :after ((edge quadtree-edge) &key)
(let* ((u (first (vertices edge)))
(v (second (vertices edge)))
(common-margin (common-margin u v)))
(setf (slot-value edge 'margin-crossing-point)
(intersect (make-line (center u) (center v)) common-margin))))
(defmethod weight ((edge quadtree-edge))
(when (not (slot-value edge 'weight))
(setf (slot-value edge 'weight)
(distance (center (first (vertices edge)))
(center (second (vertices edge))))))
(slot-value edge 'weight))
(defmethod opposite-vertex ((edge quadtree-edge) (vertex quadtree-vertex))
(if (eq vertex (first (vertices edge)))
(second (vertices edge))
(first (vertices edge))))
(defmethod connects-vertices? ((edge quadtree-edge) (v quadtree-vertex) (u quadtree-vertex))
(or (and (eq (first (vertices edge)) v) (eq (second (vertices edge)) u))
(and (eq (first (vertices edge)) u) (eq (second (vertices edge)) v))))
|
14fc808d35f726a6b09eeeb91c7622872aaf175d083beb3932e90a5e4461cd53 | slovnicki/pLam | Config.hs | module Config where
importPath = "import/"
| null | https://raw.githubusercontent.com/slovnicki/pLam/459589cf08fb53051215442ec7b0669106bbf225/src/Config.hs | haskell | module Config where
importPath = "import/"
| |
018a7d3d2ee52326a2369aa9a9c1044b80f65efbe7fb84555c48b84df396d9aa | spechub/Hets | CASL2VSEImport.hs | # LANGUAGE MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances #
|
Module : ./Comorphisms / CASL2VSEImport.hs
Description : embedding from CASL to VSE , plus wrapping procedures
with default implementations
Copyright : ( c ) M.Codescu , DFKI Bremen 2008
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( imports Logic . Logic )
The embedding comorphism from CASL to VSE .
Module : ./Comorphisms/CASL2VSEImport.hs
Description : embedding from CASL to VSE, plus wrapping procedures
with default implementations
Copyright : (c) M.Codescu, DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (imports Logic.Logic)
The embedding comorphism from CASL to VSE.
-}
module Comorphisms.CASL2VSEImport (CASL2VSEImport (..)) where
import Logic.Logic
import Logic.Comorphism
import CASL.Logic_CASL
import CASL.Sublogic as SL
import CASL.Sign
import CASL.AS_Basic_CASL
import CASL.Morphism
import VSE.Logic_VSE
import VSE.As
import VSE.Ana
import Common.AS_Annotation
import Common.Id
import Common.ProofTree
import Common.Result
import qualified Common.Lib.MapSet as MapSet
import qualified Control.Monad.Fail as Fail
import qualified Data.Set as Set
import qualified Data.Map as Map
-- | The identity of the comorphism
data CASL2VSEImport = CASL2VSEImport deriving (Show)
instance Language CASL2VSEImport -- default definition is okay
instance Comorphism CASL2VSEImport
CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree
VSE ()
VSEBasicSpec Sentence SYMB_ITEMS SYMB_MAP_ITEMS
VSESign
VSEMor
Symbol RawSymbol () where
sourceLogic CASL2VSEImport = CASL
sourceSublogic CASL2VSEImport = SL.cFol
targetLogic CASL2VSEImport = VSE
mapSublogic CASL2VSEImport _ = Just ()
map_theory CASL2VSEImport = mapCASLTheory
map_morphism CASL2VSEImport = return . mapMor
map_sentence CASL2VSEImport _ = return . mapFORMULA
map_symbol CASL2VSEImport = error "nyi"
check these 3 , but should be fine
has_model_expansion CASL2VSEImport = True
is_weakly_amalgamable CASL2VSEImport = True
isInclusionComorphism CASL2VSEImport = True
mapCASLTheory :: (CASLSign, [Named CASLFORMULA]) ->
Result (VSESign, [Named Sentence])
mapCASLTheory (sig, n_sens) =
let (tsig, genAx) = mapSig sig
tsens = map (mapNamed mapFORMULA) n_sens
in if not $ null $ checkCases tsig (tsens ++ genAx)
then Fail.fail "case error in signature"
else return (tsig, tsens ++ genAx)
mkIfProg :: FORMULA () -> Program
mkIfProg f =
mkRanged $ If f (mkRanged $ Return aTrue) $ mkRanged $ Return aFalse
mapSig :: CASLSign -> (VSESign, [Named Sentence])
mapSig sign =
let wrapSort (procsym, axs) s = let
restrName = gnRestrName s
eqName = gnEqName s
sProcs = [(restrName, Profile [Procparam In s] Nothing),
(eqName,
Profile [Procparam In s, Procparam In s]
(Just uBoolean))]
sSens = [makeNamed ("ga_restriction_" ++ show s) $ ExtFORMULA $
mkRanged
(Defprocs
[Defproc Proc restrName [xVar]
(mkRanged (Block [] (mkRanged Skip)))
nullRange])
, makeNamed ("ga_equality_" ++ show s) $ ExtFORMULA $
mkRanged
(Defprocs
[Defproc Func eqName (map mkSimpleId ["x", "y"])
(mkRanged (Block [] (mkIfProg (mkStEq
(Qual_var (mkSimpleId "x") s nullRange)
(Qual_var (mkSimpleId "y") s nullRange)
))))
nullRange])
]
in
(sProcs ++ procsym, sSens ++ axs)
(sortProcs, sortSens) = foldl wrapSort ([], []) $
Set.toList $ sortSet sign
wrapOp (procsym, axs) (i, opTypes) = let
funName = mkGenName i
fProcs = map (\ profile ->
(funName,
Profile
(map (Procparam In) $ opArgs profile)
(Just $ opRes profile))) opTypes
fSens = map (\ (OpType fKind w s) -> let vars = genVars w in
makeNamed "" $ ExtFORMULA $ Ranged
(Defprocs
[Defproc
Func funName (map fst vars)
( Ranged (Block []
(Ranged
(Block
[Var_decl [yVar] s nullRange]
(Ranged
(Seq
(Ranged
(Assign
yVar
(Application
(Qual_op_name i
(Op_type fKind w s nullRange)
nullRange )
(map (\ (v, ss) ->
Qual_var v ss nullRange) vars)
nullRange))
nullRange)
(Ranged
(Return
(Qual_var yVar s nullRange))
nullRange)
) -- end seq
nullRange)
) -- end block
nullRange) -- end procedure body
) nullRange)
nullRange]
)
nullRange
) opTypes
in
(procsym ++ fProcs, axs ++ fSens)
(opProcs, opSens) = foldl wrapOp ([], []) $
MapSet.toList $ opMap sign
wrapPred (procsym, axs) (i, predTypes) = let
procName = mkGenName i
pProcs = map (\ profile -> (procName,
Profile
(map (Procparam In) $ predArgs profile)
(Just uBoolean))) predTypes
pSens = map (\ (PredType w) -> let vars = genVars w in
makeNamed "" $ ExtFORMULA $ mkRanged
(Defprocs
[Defproc
Func procName (map fst vars)
(mkRanged (Block [] (mkIfProg
(Predication
(Qual_pred_name
i
(Pred_type w nullRange)
nullRange)
(map (\ (v, ss) ->
Qual_var v ss nullRange) vars)
nullRange))))
nullRange]
)
) predTypes
in
(procsym ++ pProcs, axs ++ pSens)
(predProcs, predSens) = foldl wrapPred ([], []) $
MapSet.toList $ predMap sign
procs = Procs $ Map.fromList (sortProcs ++ opProcs ++ predProcs)
newPreds = procsToPredMap procs
newOps = procsToOpMap procs
in (sign { opMap = addOpMapSet (opMap sign) newOps,
predMap = addMapSet (predMap sign) newPreds,
extendedInfo = procs,
sentences = [] }, sortSens ++ opSens ++ predSens)
mapMor :: CASLMor -> VSEMor
mapMor m = let
(om, pm) = vseMorExt m
in m
{ msource = fst $ mapSig $ msource m
, mtarget = fst $ mapSig $ mtarget m
, op_map = Map.union om $ op_map m
, pred_map = Map.union pm $ pred_map m
, extended_map = emptyMorExt
}
| null | https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/Comorphisms/CASL2VSEImport.hs | haskell | | The identity of the comorphism
default definition is okay
end seq
end block
end procedure body | # LANGUAGE MultiParamTypeClasses , TypeSynonymInstances , FlexibleInstances #
|
Module : ./Comorphisms / CASL2VSEImport.hs
Description : embedding from CASL to VSE , plus wrapping procedures
with default implementations
Copyright : ( c ) M.Codescu , DFKI Bremen 2008
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( imports Logic . Logic )
The embedding comorphism from CASL to VSE .
Module : ./Comorphisms/CASL2VSEImport.hs
Description : embedding from CASL to VSE, plus wrapping procedures
with default implementations
Copyright : (c) M.Codescu, DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (imports Logic.Logic)
The embedding comorphism from CASL to VSE.
-}
module Comorphisms.CASL2VSEImport (CASL2VSEImport (..)) where
import Logic.Logic
import Logic.Comorphism
import CASL.Logic_CASL
import CASL.Sublogic as SL
import CASL.Sign
import CASL.AS_Basic_CASL
import CASL.Morphism
import VSE.Logic_VSE
import VSE.As
import VSE.Ana
import Common.AS_Annotation
import Common.Id
import Common.ProofTree
import Common.Result
import qualified Common.Lib.MapSet as MapSet
import qualified Control.Monad.Fail as Fail
import qualified Data.Set as Set
import qualified Data.Map as Map
data CASL2VSEImport = CASL2VSEImport deriving (Show)
instance Comorphism CASL2VSEImport
CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree
VSE ()
VSEBasicSpec Sentence SYMB_ITEMS SYMB_MAP_ITEMS
VSESign
VSEMor
Symbol RawSymbol () where
sourceLogic CASL2VSEImport = CASL
sourceSublogic CASL2VSEImport = SL.cFol
targetLogic CASL2VSEImport = VSE
mapSublogic CASL2VSEImport _ = Just ()
map_theory CASL2VSEImport = mapCASLTheory
map_morphism CASL2VSEImport = return . mapMor
map_sentence CASL2VSEImport _ = return . mapFORMULA
map_symbol CASL2VSEImport = error "nyi"
check these 3 , but should be fine
has_model_expansion CASL2VSEImport = True
is_weakly_amalgamable CASL2VSEImport = True
isInclusionComorphism CASL2VSEImport = True
mapCASLTheory :: (CASLSign, [Named CASLFORMULA]) ->
Result (VSESign, [Named Sentence])
mapCASLTheory (sig, n_sens) =
let (tsig, genAx) = mapSig sig
tsens = map (mapNamed mapFORMULA) n_sens
in if not $ null $ checkCases tsig (tsens ++ genAx)
then Fail.fail "case error in signature"
else return (tsig, tsens ++ genAx)
mkIfProg :: FORMULA () -> Program
mkIfProg f =
mkRanged $ If f (mkRanged $ Return aTrue) $ mkRanged $ Return aFalse
mapSig :: CASLSign -> (VSESign, [Named Sentence])
mapSig sign =
let wrapSort (procsym, axs) s = let
restrName = gnRestrName s
eqName = gnEqName s
sProcs = [(restrName, Profile [Procparam In s] Nothing),
(eqName,
Profile [Procparam In s, Procparam In s]
(Just uBoolean))]
sSens = [makeNamed ("ga_restriction_" ++ show s) $ ExtFORMULA $
mkRanged
(Defprocs
[Defproc Proc restrName [xVar]
(mkRanged (Block [] (mkRanged Skip)))
nullRange])
, makeNamed ("ga_equality_" ++ show s) $ ExtFORMULA $
mkRanged
(Defprocs
[Defproc Func eqName (map mkSimpleId ["x", "y"])
(mkRanged (Block [] (mkIfProg (mkStEq
(Qual_var (mkSimpleId "x") s nullRange)
(Qual_var (mkSimpleId "y") s nullRange)
))))
nullRange])
]
in
(sProcs ++ procsym, sSens ++ axs)
(sortProcs, sortSens) = foldl wrapSort ([], []) $
Set.toList $ sortSet sign
wrapOp (procsym, axs) (i, opTypes) = let
funName = mkGenName i
fProcs = map (\ profile ->
(funName,
Profile
(map (Procparam In) $ opArgs profile)
(Just $ opRes profile))) opTypes
fSens = map (\ (OpType fKind w s) -> let vars = genVars w in
makeNamed "" $ ExtFORMULA $ Ranged
(Defprocs
[Defproc
Func funName (map fst vars)
( Ranged (Block []
(Ranged
(Block
[Var_decl [yVar] s nullRange]
(Ranged
(Seq
(Ranged
(Assign
yVar
(Application
(Qual_op_name i
(Op_type fKind w s nullRange)
nullRange )
(map (\ (v, ss) ->
Qual_var v ss nullRange) vars)
nullRange))
nullRange)
(Ranged
(Return
(Qual_var yVar s nullRange))
nullRange)
nullRange)
) nullRange)
nullRange]
)
nullRange
) opTypes
in
(procsym ++ fProcs, axs ++ fSens)
(opProcs, opSens) = foldl wrapOp ([], []) $
MapSet.toList $ opMap sign
wrapPred (procsym, axs) (i, predTypes) = let
procName = mkGenName i
pProcs = map (\ profile -> (procName,
Profile
(map (Procparam In) $ predArgs profile)
(Just uBoolean))) predTypes
pSens = map (\ (PredType w) -> let vars = genVars w in
makeNamed "" $ ExtFORMULA $ mkRanged
(Defprocs
[Defproc
Func procName (map fst vars)
(mkRanged (Block [] (mkIfProg
(Predication
(Qual_pred_name
i
(Pred_type w nullRange)
nullRange)
(map (\ (v, ss) ->
Qual_var v ss nullRange) vars)
nullRange))))
nullRange]
)
) predTypes
in
(procsym ++ pProcs, axs ++ pSens)
(predProcs, predSens) = foldl wrapPred ([], []) $
MapSet.toList $ predMap sign
procs = Procs $ Map.fromList (sortProcs ++ opProcs ++ predProcs)
newPreds = procsToPredMap procs
newOps = procsToOpMap procs
in (sign { opMap = addOpMapSet (opMap sign) newOps,
predMap = addMapSet (predMap sign) newPreds,
extendedInfo = procs,
sentences = [] }, sortSens ++ opSens ++ predSens)
mapMor :: CASLMor -> VSEMor
mapMor m = let
(om, pm) = vseMorExt m
in m
{ msource = fst $ mapSig $ msource m
, mtarget = fst $ mapSig $ mtarget m
, op_map = Map.union om $ op_map m
, pred_map = Map.union pm $ pred_map m
, extended_map = emptyMorExt
}
|
5e00b4ce6735ae7e841345a692586844e3f36ca443694732c0828ed418cf6902 | tfausak/patrol | MachException.hs | module Patrol.Type.MachException where
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import qualified Patrol.Extra.Aeson as Aeson
-- | <-payloads/types/#machexception>
data MachException = MachException
{ code :: Maybe Int,
exception :: Maybe Int,
name :: Text.Text,
subcode :: Maybe Int
}
deriving (Eq, Show)
instance Aeson.ToJSON MachException where
toJSON machException =
Aeson.intoObject
[ Aeson.pair "code" $ code machException,
Aeson.pair "exception" $ exception machException,
Aeson.pair "name" $ name machException,
Aeson.pair "subcode" $ subcode machException
]
empty :: MachException
empty =
MachException
{ code = Nothing,
exception = Nothing,
name = Text.empty,
subcode = Nothing
}
| null | https://raw.githubusercontent.com/tfausak/patrol/1cae55b3840b328cda7de85ea424333fcab434cb/source/library/Patrol/Type/MachException.hs | haskell | | <-payloads/types/#machexception> | module Patrol.Type.MachException where
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import qualified Patrol.Extra.Aeson as Aeson
data MachException = MachException
{ code :: Maybe Int,
exception :: Maybe Int,
name :: Text.Text,
subcode :: Maybe Int
}
deriving (Eq, Show)
instance Aeson.ToJSON MachException where
toJSON machException =
Aeson.intoObject
[ Aeson.pair "code" $ code machException,
Aeson.pair "exception" $ exception machException,
Aeson.pair "name" $ name machException,
Aeson.pair "subcode" $ subcode machException
]
empty :: MachException
empty =
MachException
{ code = Nothing,
exception = Nothing,
name = Text.empty,
subcode = Nothing
}
|
9cde7143bcee3f759dc8f848c85424c27a3a1a67853049102c1e05585cbe8fb7 | reiddraper/knockbox | internal.clj | ;; -------------------------------------------------------------------
Copyright ( c ) 2011 Basho Technologies , Inc. All Rights Reserved .
;;
This file is provided to you under the Apache License ,
;; Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
;; a copy of the License at
;;
;; -2.0
;;
;; Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
;; KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations
;; under the License.
;;
;; -------------------------------------------------------------------
(ns knockbox.internal
(:require [clojure.string :as string])
(:import java.util.UUID))
(def ^:private counter (atom 0N))
(def ^:private uuid (.toString (java.util.UUID/randomUUID)))
(defn next-count! []
(swap! counter inc))
(defn- time-since-epoch! []
(.getTime (java.util.Date.)))
(defn sorted-unique-id!
"Return unique ids that are roughly sorted
by time. In the case that two ids are generated
at the same time across JVMs, they unique because
of the UUID. In the case two ids are generated
at the same time on the same machine, there is
also a counter
Example:
[1331496905454 \"327c4f9a-d3c8-453e-b332-8e04d1db0a2e\" 7N]"
[]
[(time-since-epoch!)
uuid
(next-count!)])
| null | https://raw.githubusercontent.com/reiddraper/knockbox/ed22221759d0d3dbe4f1b1f83355e95e945de729/src/knockbox/internal.clj | clojure | -------------------------------------------------------------------
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.
------------------------------------------------------------------- | Copyright ( c ) 2011 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
(ns knockbox.internal
(:require [clojure.string :as string])
(:import java.util.UUID))
(def ^:private counter (atom 0N))
(def ^:private uuid (.toString (java.util.UUID/randomUUID)))
(defn next-count! []
(swap! counter inc))
(defn- time-since-epoch! []
(.getTime (java.util.Date.)))
(defn sorted-unique-id!
"Return unique ids that are roughly sorted
by time. In the case that two ids are generated
at the same time across JVMs, they unique because
of the UUID. In the case two ids are generated
at the same time on the same machine, there is
also a counter
Example:
[1331496905454 \"327c4f9a-d3c8-453e-b332-8e04d1db0a2e\" 7N]"
[]
[(time-since-epoch!)
uuid
(next-count!)])
|
b0bdbc196ab964ea5b83c086d34317bc0c1f06923e3de92f32d8b3e1aecdfd5d | haskell/haskell-language-server | DestructAllNonVarTopMatch.expected.hs | and :: (a, b) -> Bool -> Bool -> Bool
and (a, b) False False = _w0
and (a, b) False True = _w1
and (a, b) True False = _w2
and (a, b) True True = _w3
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/f3ad27ba1634871b2240b8cd7de9f31b91a2e502/plugins/hls-tactics-plugin/new/test/golden/DestructAllNonVarTopMatch.expected.hs | haskell | and :: (a, b) -> Bool -> Bool -> Bool
and (a, b) False False = _w0
and (a, b) False True = _w1
and (a, b) True False = _w2
and (a, b) True True = _w3
| |
ac2704ea82fd641cc4fec27cda4a1da10c49401004c53feb88ecfc9489498821 | dparis/phzr-demo | macros.clj | (ns phzr-demo.macros
(:refer-clojure :exclude [slurp]))
(defmacro slurp [file]
(clojure.core/slurp file))
| null | https://raw.githubusercontent.com/dparis/phzr-demo/9679dc697709bfbba5f1993821ba78b6ccba2a94/src/phzr_demo/macros.clj | clojure | (ns phzr-demo.macros
(:refer-clojure :exclude [slurp]))
(defmacro slurp [file]
(clojure.core/slurp file))
| |
cd4d6aaa3682fa3da6b05601fac76786cc30bdc612ebaecb0b678c24b8e3b7a0 | janestreet/learn-ocaml-workshop | parser.ml | open Core
module Angstrom = struct
include Angstrom
include Base.Monad.Make(struct
type nonrec 'a t = 'a t
let bind t ~f = t >>= f
let map = `Define_using_bind
let return = return
end)
end
open Angstrom
open Angstrom.Let_syntax
module P = struct
let is_space = function | ' ' -> true | _ -> false
let is_letter = Char.is_alpha
let is_digit = Char.is_digit
let is_letter_or_digit = Char.is_alphanum
let is_special = function
| '[' | ']' | '\\' | '`' | '_' | '^' | '{' | '|' | '}' -> true
| _ -> false
;;
let is_nospcrlfcl = function
| '\000' | '\r' | '\n' | ' ' | ':' -> false | _ -> true
;;
end
let letters = take_while1 P.is_letter
let digits = take_while1 P.is_digit
let (<||>) a b = take_while1 (fun char -> a char || b char)
let space = string " "
let crlf = string "\r\n"
let rec at_most m p =
if m = 0
then return []
else
(lift2 (fun x xs -> x :: xs) p (at_most (m - 1) p))
<|> return []
;;
let between ~lower ~upper p =
lift2 (fun xs ys -> xs @ ys)
(count lower p)
(at_most upper p)
;;
let user =
take_while1
(function | '\000' | '\r' | '\n' | ' ' | '@' -> false | _ -> true)
<?> "user"
;;
let hostname =
let shortname =
lift2 (fun hd tl -> (Char.to_string hd) ^ tl)
(satisfy P.is_letter_or_digit)
(peek_char
>>= function
| None ->
satisfy P.is_letter_or_digit >>| Char.to_string
| Some _ ->
P.is_letter_or_digit <||> (fun c -> c = '-'))
<?> "shortname"
in
lift2 (fun s1 s2 ->
match s2 with
| [] -> s1
| s2 ->
s1 ^ "." ^ String.concat ~sep:"." s2)
shortname
(many (string "." *> shortname))
<?> "hostname"
;;
let hostaddr =
let ip4addr =
(sep_by
(char '.')
(between ~lower:1 ~upper:3 digits >>| String.concat))
>>| List.intersperse ~sep:"."
>>= fun l ->
match
Option.try_with (fun () -> Unix.Inet_addr.of_string (String.concat l))
with
| None -> fail (sprintf "Failed to parse inet_addr %s" (String.concat l))
| Some inet_addr -> return inet_addr
in
let ip6addr = fail "IPv6 support unimplemented" in
(ip4addr <|> ip6addr)
<?> "hostaddr"
;;
let host =
let open Message.Prefix in
((Host.hostname <$> hostname) <|> (Host.inet_addr <$> hostaddr))
<?> "host"
;;
let servername = hostname <?> "servername"
let prefix : Message.Prefix.t t =
let open Message.Prefix in
let server_prefix = lift (fun s -> Server s) servername <* space in
let user_prefix =
let nickname =
lift2 (^)
(P.is_letter <||> P.is_special)
(between ~lower:0 ~upper:8
(satisfy (function
| '-' -> true
| c ->
P.is_letter c || P.is_digit c || P.is_special c))
>>| String.of_char_list)
in
let user =
lift2 (fun user host -> { User. user; host })
(option None (Option.return <$> char '!' *> user))
(char '@' *> host)
in
(lift2 (fun nickname user -> User { nickname ; user })
nickname
(option None (Option.return <$> user)))
<* space
in
(string ":" *> (user_prefix <|> server_prefix))
<?> "prefix"
;;
let params =
let middle =
lift2 (fun first rest ->
Char.to_string first ^ rest)
(satisfy (P.is_nospcrlfcl))
(take_while (fun c -> c = ':' || P.is_nospcrlfcl c))
in
let trailing =
take_while1 (fun c -> P.is_space c || c = ':' || P.is_nospcrlfcl c)
>>| List.return
in
let variant1 =
lift2 (@)
(at_most 14 (space *> middle))
(option [] (space *> char ':' *> trailing))
in
let variant2 =
lift2 (@)
(count 14 (space *> middle))
(option []
(space
*> (at_most 1 (char ':'))
*> trailing))
in
(variant1 <|> variant2)
<?> "params"
;;
let command =
let command =
(lift2 (fun maybe_command peek ->
match peek with
| None -> maybe_command
| Some c ->
if c = ' '
then maybe_command
else [])
(many1 letters
<|> (count 3 (satisfy P.is_digit)
>>| String.of_char_list
>>| List.return))
peek_char)
<?> "command"
in
String.concat
<$> command
>>| Message.Command.of_string
;;
let message =
let%bind maybe_prefix =
option None (Option.return <$> prefix)
in
let%bind command = command in
let%bind params = option [] params in
crlf
*> return
{ Message.
prefix = maybe_prefix
; command
; params }
<?> "message"
;;
| null | https://raw.githubusercontent.com/janestreet/learn-ocaml-workshop/1ba9576b48b48a892644eb20c201c2c4aa643c32/solutions/irc-bot/lib/parser.ml | ocaml | open Core
module Angstrom = struct
include Angstrom
include Base.Monad.Make(struct
type nonrec 'a t = 'a t
let bind t ~f = t >>= f
let map = `Define_using_bind
let return = return
end)
end
open Angstrom
open Angstrom.Let_syntax
module P = struct
let is_space = function | ' ' -> true | _ -> false
let is_letter = Char.is_alpha
let is_digit = Char.is_digit
let is_letter_or_digit = Char.is_alphanum
let is_special = function
| '[' | ']' | '\\' | '`' | '_' | '^' | '{' | '|' | '}' -> true
| _ -> false
;;
let is_nospcrlfcl = function
| '\000' | '\r' | '\n' | ' ' | ':' -> false | _ -> true
;;
end
let letters = take_while1 P.is_letter
let digits = take_while1 P.is_digit
let (<||>) a b = take_while1 (fun char -> a char || b char)
let space = string " "
let crlf = string "\r\n"
let rec at_most m p =
if m = 0
then return []
else
(lift2 (fun x xs -> x :: xs) p (at_most (m - 1) p))
<|> return []
;;
let between ~lower ~upper p =
lift2 (fun xs ys -> xs @ ys)
(count lower p)
(at_most upper p)
;;
let user =
take_while1
(function | '\000' | '\r' | '\n' | ' ' | '@' -> false | _ -> true)
<?> "user"
;;
let hostname =
let shortname =
lift2 (fun hd tl -> (Char.to_string hd) ^ tl)
(satisfy P.is_letter_or_digit)
(peek_char
>>= function
| None ->
satisfy P.is_letter_or_digit >>| Char.to_string
| Some _ ->
P.is_letter_or_digit <||> (fun c -> c = '-'))
<?> "shortname"
in
lift2 (fun s1 s2 ->
match s2 with
| [] -> s1
| s2 ->
s1 ^ "." ^ String.concat ~sep:"." s2)
shortname
(many (string "." *> shortname))
<?> "hostname"
;;
let hostaddr =
let ip4addr =
(sep_by
(char '.')
(between ~lower:1 ~upper:3 digits >>| String.concat))
>>| List.intersperse ~sep:"."
>>= fun l ->
match
Option.try_with (fun () -> Unix.Inet_addr.of_string (String.concat l))
with
| None -> fail (sprintf "Failed to parse inet_addr %s" (String.concat l))
| Some inet_addr -> return inet_addr
in
let ip6addr = fail "IPv6 support unimplemented" in
(ip4addr <|> ip6addr)
<?> "hostaddr"
;;
let host =
let open Message.Prefix in
((Host.hostname <$> hostname) <|> (Host.inet_addr <$> hostaddr))
<?> "host"
;;
let servername = hostname <?> "servername"
let prefix : Message.Prefix.t t =
let open Message.Prefix in
let server_prefix = lift (fun s -> Server s) servername <* space in
let user_prefix =
let nickname =
lift2 (^)
(P.is_letter <||> P.is_special)
(between ~lower:0 ~upper:8
(satisfy (function
| '-' -> true
| c ->
P.is_letter c || P.is_digit c || P.is_special c))
>>| String.of_char_list)
in
let user =
lift2 (fun user host -> { User. user; host })
(option None (Option.return <$> char '!' *> user))
(char '@' *> host)
in
(lift2 (fun nickname user -> User { nickname ; user })
nickname
(option None (Option.return <$> user)))
<* space
in
(string ":" *> (user_prefix <|> server_prefix))
<?> "prefix"
;;
let params =
let middle =
lift2 (fun first rest ->
Char.to_string first ^ rest)
(satisfy (P.is_nospcrlfcl))
(take_while (fun c -> c = ':' || P.is_nospcrlfcl c))
in
let trailing =
take_while1 (fun c -> P.is_space c || c = ':' || P.is_nospcrlfcl c)
>>| List.return
in
let variant1 =
lift2 (@)
(at_most 14 (space *> middle))
(option [] (space *> char ':' *> trailing))
in
let variant2 =
lift2 (@)
(count 14 (space *> middle))
(option []
(space
*> (at_most 1 (char ':'))
*> trailing))
in
(variant1 <|> variant2)
<?> "params"
;;
let command =
let command =
(lift2 (fun maybe_command peek ->
match peek with
| None -> maybe_command
| Some c ->
if c = ' '
then maybe_command
else [])
(many1 letters
<|> (count 3 (satisfy P.is_digit)
>>| String.of_char_list
>>| List.return))
peek_char)
<?> "command"
in
String.concat
<$> command
>>| Message.Command.of_string
;;
let message =
let%bind maybe_prefix =
option None (Option.return <$> prefix)
in
let%bind command = command in
let%bind params = option [] params in
crlf
*> return
{ Message.
prefix = maybe_prefix
; command
; params }
<?> "message"
;;
| |
a0ec71e563d831d9bc167b7bd2e4f5944a657f50cd8a176da3906dda00d04a1d | k00mi/mqtt-hs | keepalive.hs | # Language OverloadedStrings , GADTs #
module Keepalive where
import Control.Concurrent
import Control.Concurrent.STM
import Data.ByteString (ByteString)
import Data.Word (Word16)
import Network.MQTT
import Network.MQTT.Internal
import System.Timeout (timeout)
t :: Topic
t = "topic"
p :: ByteString
p = "payload"
tout :: Word16
tout = 2 -- seconds
main :: IO ()
main = do
cmds <- newTChanIO
pub <- newTChanIO
let mqtt = (defaultConfig (Cmds cmds) pub) { cKeepAlive = Just tout }
_ <- forkIO $ do
-- dup cmds, publish, wait for timeout, check for keepalive msg
cmds' <- atomically $ dupTChan cmds
publish mqtt NoConfirm False t p
CmdSend (SomeMessage (Message _h (Publish{}))) <- atomically (readTChan cmds')
maybeAwait <- timeout (secToMicro (fromIntegral tout * 2)) $
atomically (readTChan cmds')
case maybeAwait of
Nothing -> putStrLn "FAILED: no CmdAwait within timeout"
Just (CmdAwait _) -> return ()
Just (CmdSend _) -> putStrLn "FAILED: unexpected CmdSend"
Just (CmdStopWaiting _) -> putStrLn "FAILED: unexpected CmdStopWaiting"
Just CmdDisconnect -> putStrLn "FAILED: unexpected CmdDisconnect"
timeout ? ?
cmdSend <- atomically $ readTChan cmds'
case cmdSend of
(CmdSend (SomeMessage (Message _h PingReq))) -> return ()
(CmdSend (SomeMessage _)) -> putStrLn "FAILED: unexpected message"
(CmdAwait _) -> putStrLn "FAILED: unexpected CmdAwait"
(CmdStopWaiting _) -> putStrLn "FAILED: unexpected CmdStopWaiting"
CmdDisconnect -> putStrLn "FAILED: unexpected CmdDisconnect"
disconnect mqtt
term <- run mqtt
case term of
UserRequested -> return ()
_ -> putStrLn $ "FAILED: term = " ++ show term
| null | https://raw.githubusercontent.com/k00mi/mqtt-hs/8bade1e192fb4b15db751de70185eac83c2a878d/tests/keepalive.hs | haskell | seconds
dup cmds, publish, wait for timeout, check for keepalive msg | # Language OverloadedStrings , GADTs #
module Keepalive where
import Control.Concurrent
import Control.Concurrent.STM
import Data.ByteString (ByteString)
import Data.Word (Word16)
import Network.MQTT
import Network.MQTT.Internal
import System.Timeout (timeout)
t :: Topic
t = "topic"
p :: ByteString
p = "payload"
tout :: Word16
main :: IO ()
main = do
cmds <- newTChanIO
pub <- newTChanIO
let mqtt = (defaultConfig (Cmds cmds) pub) { cKeepAlive = Just tout }
_ <- forkIO $ do
cmds' <- atomically $ dupTChan cmds
publish mqtt NoConfirm False t p
CmdSend (SomeMessage (Message _h (Publish{}))) <- atomically (readTChan cmds')
maybeAwait <- timeout (secToMicro (fromIntegral tout * 2)) $
atomically (readTChan cmds')
case maybeAwait of
Nothing -> putStrLn "FAILED: no CmdAwait within timeout"
Just (CmdAwait _) -> return ()
Just (CmdSend _) -> putStrLn "FAILED: unexpected CmdSend"
Just (CmdStopWaiting _) -> putStrLn "FAILED: unexpected CmdStopWaiting"
Just CmdDisconnect -> putStrLn "FAILED: unexpected CmdDisconnect"
timeout ? ?
cmdSend <- atomically $ readTChan cmds'
case cmdSend of
(CmdSend (SomeMessage (Message _h PingReq))) -> return ()
(CmdSend (SomeMessage _)) -> putStrLn "FAILED: unexpected message"
(CmdAwait _) -> putStrLn "FAILED: unexpected CmdAwait"
(CmdStopWaiting _) -> putStrLn "FAILED: unexpected CmdStopWaiting"
CmdDisconnect -> putStrLn "FAILED: unexpected CmdDisconnect"
disconnect mqtt
term <- run mqtt
case term of
UserRequested -> return ()
_ -> putStrLn $ "FAILED: term = " ++ show term
|
ff9771bfaad2faaf93ab4ca7e4fb36fde713eeccdee7a32719bf21b47996c765 | gator1/jepsen | comments.clj | (ns jepsen.cockroach.comments
"Checks for a strict serializability anomaly in which T1 < T2, but T2 is
visible without T1.
We perform concurrent blind inserts across n tables, and meanwhile, perform
reads of both tables in a transaction. To verify, we replay the history,
tracking the writes which were known to have completed before the invocation
of any write w_i. If w_i is visible, and some w_j < w_i is *not* visible,
we've found a violation of strict serializability.
Splits keys up onto different tables to make sure they fall in different
shard ranges"
(:refer-clojure :exclude [test])
(:require [jepsen [cockroach :as cockroach]
[client :as client]
[checker :as checker]
[generator :as gen]
[independent :as independent]
[util :as util :refer [meh]]
[reconnect :as rc]]
[jepsen.cockroach.client :as c]
[jepsen.cockroach.nemesis :as cln]
[clojure.java.jdbc :as j]
[clojure.core.reducers :as r]
[clojure.set :as set]
[clojure.tools.logging :refer :all]
[knossos.model :as model]
[knossos.op :as op]))
(def table-prefix "String prepended to all table names." "comment_")
(defn table-names
"Names of all tables"
[table-count]
(map (partial str table-prefix) (range table-count)))
(defn id->table
"Turns an id into a table id"
[table-count id]
(str table-prefix (mod (hash id) table-count)))
(defrecord Client [table-count table-created? client]
client/Client
(setup! [this test node]
(Thread/sleep 2000)
(let [client (c/client node)]
(locking table-created?
(when (compare-and-set! table-created? false true)
(rc/with-conn [c client]
(c/with-timeout
(info "Creating tables" (pr-str (table-names table-count)))
(doseq [t (table-names table-count)]
(j/execute! c [(str "create table " t
" (id int primary key,
key int)")])
(info "Created table" t))))))
(assoc this :client client)))
(invoke! [this test op]
(c/with-exception->op op
(rc/with-conn [c client]
(c/with-timeout
(case (:f op)
:write (let [[k id] (:value op)
table (id->table table-count id)]
(c/insert! c table {:id id, :key k})
(cockroach/update-keyrange! test table id)
(assoc op :type :ok))
:read (c/with-txn [c c]
(->> (table-names table-count)
(mapcat (fn [table]
(c/query c [(str "select id from "
table
" where key = ?")
(key (:value op))])))
(map :id)
(into (sorted-set))
(independent/tuple (key (:value op)))
(assoc op :type :ok, :value))))))))
(teardown! [this test]
(rc/close! client)))
(defn checker
[]
(reify checker/Checker
(check [this test model history opts]
Determine first - order write precedence graph
(let [expected (loop [completed (sorted-set)
expected {}
[op & more :as history] history]
(cond
; Done
(not (seq history))
expected
; We know this value is definitely written
(= :write (:f op))
(cond ; Write is beginning; record precedence
(op/invoke? op)
(recur completed
(assoc expected (:value op) completed)
more)
; Write is completing; we can now expect to see
; it
(op/ok? op)
(recur (conj completed (:value op))
expected more)
true
(recur completed expected more))
true
(recur completed expected more)))
errors (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(reduce (fn [errors op]
(let [seen (:value op)
our-expected (->> seen
(map expected)
(reduce set/union))
missing (set/difference our-expected
seen)]
(if (empty? missing)
errors
(conj errors
(-> op
(dissoc :value)
(assoc :missing missing)
(assoc :expected-count
(count our-expected)))))))
[]))]
{:valid? (empty? errors)
:errors errors}))))
(defn reads [] {:type :invoke, :f :read, :value nil})
(defn writes []
(->> (range)
(map (fn [k] {:type :invoke, :f :write, :value k}))
gen/seq))
(defn test
[opts]
(let [reads (reads)
writes (writes)]
(cockroach/basic-test
(merge
{:name "comments"
:client {:client (Client. 10 (atom false) nil)
:during (independent/concurrent-generator
(count (:nodes opts))
(range)
(fn [k]
(->> (gen/mix [reads writes])
(gen/stagger 1/100)
(gen/limit 500))))
:final nil}
:checker (checker/compose
{:perf (checker/perf)
:sequential (independent/checker (checker))})}
opts))))
| null | https://raw.githubusercontent.com/gator1/jepsen/1932cbd72cbc1f6c2a27abe0fe347ea989f0cfbb/cockroachdb/src/jepsen/cockroach/comments.clj | clojure | Done
We know this value is definitely written
Write is beginning; record precedence
Write is completing; we can now expect to see
it | (ns jepsen.cockroach.comments
"Checks for a strict serializability anomaly in which T1 < T2, but T2 is
visible without T1.
We perform concurrent blind inserts across n tables, and meanwhile, perform
reads of both tables in a transaction. To verify, we replay the history,
tracking the writes which were known to have completed before the invocation
of any write w_i. If w_i is visible, and some w_j < w_i is *not* visible,
we've found a violation of strict serializability.
Splits keys up onto different tables to make sure they fall in different
shard ranges"
(:refer-clojure :exclude [test])
(:require [jepsen [cockroach :as cockroach]
[client :as client]
[checker :as checker]
[generator :as gen]
[independent :as independent]
[util :as util :refer [meh]]
[reconnect :as rc]]
[jepsen.cockroach.client :as c]
[jepsen.cockroach.nemesis :as cln]
[clojure.java.jdbc :as j]
[clojure.core.reducers :as r]
[clojure.set :as set]
[clojure.tools.logging :refer :all]
[knossos.model :as model]
[knossos.op :as op]))
(def table-prefix "String prepended to all table names." "comment_")
(defn table-names
"Names of all tables"
[table-count]
(map (partial str table-prefix) (range table-count)))
(defn id->table
"Turns an id into a table id"
[table-count id]
(str table-prefix (mod (hash id) table-count)))
(defrecord Client [table-count table-created? client]
client/Client
(setup! [this test node]
(Thread/sleep 2000)
(let [client (c/client node)]
(locking table-created?
(when (compare-and-set! table-created? false true)
(rc/with-conn [c client]
(c/with-timeout
(info "Creating tables" (pr-str (table-names table-count)))
(doseq [t (table-names table-count)]
(j/execute! c [(str "create table " t
" (id int primary key,
key int)")])
(info "Created table" t))))))
(assoc this :client client)))
(invoke! [this test op]
(c/with-exception->op op
(rc/with-conn [c client]
(c/with-timeout
(case (:f op)
:write (let [[k id] (:value op)
table (id->table table-count id)]
(c/insert! c table {:id id, :key k})
(cockroach/update-keyrange! test table id)
(assoc op :type :ok))
:read (c/with-txn [c c]
(->> (table-names table-count)
(mapcat (fn [table]
(c/query c [(str "select id from "
table
" where key = ?")
(key (:value op))])))
(map :id)
(into (sorted-set))
(independent/tuple (key (:value op)))
(assoc op :type :ok, :value))))))))
(teardown! [this test]
(rc/close! client)))
(defn checker
[]
(reify checker/Checker
(check [this test model history opts]
Determine first - order write precedence graph
(let [expected (loop [completed (sorted-set)
expected {}
[op & more :as history] history]
(cond
(not (seq history))
expected
(= :write (:f op))
(op/invoke? op)
(recur completed
(assoc expected (:value op) completed)
more)
(op/ok? op)
(recur (conj completed (:value op))
expected more)
true
(recur completed expected more))
true
(recur completed expected more)))
errors (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(reduce (fn [errors op]
(let [seen (:value op)
our-expected (->> seen
(map expected)
(reduce set/union))
missing (set/difference our-expected
seen)]
(if (empty? missing)
errors
(conj errors
(-> op
(dissoc :value)
(assoc :missing missing)
(assoc :expected-count
(count our-expected)))))))
[]))]
{:valid? (empty? errors)
:errors errors}))))
(defn reads [] {:type :invoke, :f :read, :value nil})
(defn writes []
(->> (range)
(map (fn [k] {:type :invoke, :f :write, :value k}))
gen/seq))
(defn test
[opts]
(let [reads (reads)
writes (writes)]
(cockroach/basic-test
(merge
{:name "comments"
:client {:client (Client. 10 (atom false) nil)
:during (independent/concurrent-generator
(count (:nodes opts))
(range)
(fn [k]
(->> (gen/mix [reads writes])
(gen/stagger 1/100)
(gen/limit 500))))
:final nil}
:checker (checker/compose
{:perf (checker/perf)
:sequential (independent/checker (checker))})}
opts))))
|
0632d8bba944e9181831237467a9e20147bdaef2e0b41539b3c266ebb2f39af8 | FlowerWrong/mblog | socket_examples.erl | %% ---
Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
%% Copyrights apply to this code. It may not be used to create training material,
%% courses, books, articles, and the like. Contact us if you are in doubt.
%% We make no guarantees that this code is fit for any purpose.
%% Visit for more book information.
%%---
-module(socket_examples).
-compile(export_all).
-import(lists, [reverse/1]).
nano_get_url() ->
nano_get_url("www.google.com").
nano_get_url(Host) ->
( 1 )
( 2 )
receive_data(Socket, []).
receive_data(Socket, SoFar) ->
receive
( 3 )
receive_data(Socket, [Bin|SoFar]);
( 4 )
( 5 )
end.
nano_client_eval(Str) ->
{ok, Socket} =
gen_tcp:connect("localhost", 2345,
[binary, {packet, 4}]),
ok = gen_tcp:send(Socket, term_to_binary(Str)),
receive
{tcp,Socket,Bin} ->
io:format("Client received binary = ~p~n",[Bin]),
Val = binary_to_term(Bin),
io:format("Client result = ~p~n",[Val]),
gen_tcp:close(Socket)
end.
start_nano_server() ->
( 6 )
{reuseaddr, true},
{active, true}]),
( 7 )
gen_tcp:close(Listen), %% (8)
loop(Socket).
loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("Server received binary = ~p~n",[Bin]),
( 9 )
io:format("Server (unpacked) ~p~n",[Str]),
( 10 )
io:format("Server replying = ~p~n",[Reply]),
( 11 )
loop(Socket);
{tcp_closed, Socket} ->
io:format("Server socket closed~n")
end.
error_test() ->
spawn(fun() -> error_test_server() end),
lib_misc:sleep(2000),
{ok,Socket} = gen_tcp:connect("localhost",4321,[binary, {packet, 2}]),
io:format("connected to:~p~n",[Socket]),
gen_tcp:send(Socket, <<"123">>),
receive
Any ->
io:format("Any=~p~n",[Any])
end.
error_test_server() ->
{ok, Listen} = gen_tcp:listen(4321, [binary,{packet,2}]),
{ok, Socket} = gen_tcp:accept(Listen),
error_test_server_loop(Socket).
error_test_server_loop(Socket) ->
receive
{tcp, Socket, Data} ->
io:format("received:~p~n",[Data]),
_ = atom_to_list(Data),
error_test_server_loop(Socket)
end.
| null | https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/socket_examples.erl | erlang | ---
Copyrights apply to this code. It may not be used to create training material,
courses, books, articles, and the like. Contact us if you are in doubt.
We make no guarantees that this code is fit for any purpose.
Visit for more book information.
---
(8) | Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
-module(socket_examples).
-compile(export_all).
-import(lists, [reverse/1]).
nano_get_url() ->
nano_get_url("www.google.com").
nano_get_url(Host) ->
( 1 )
( 2 )
receive_data(Socket, []).
receive_data(Socket, SoFar) ->
receive
( 3 )
receive_data(Socket, [Bin|SoFar]);
( 4 )
( 5 )
end.
nano_client_eval(Str) ->
{ok, Socket} =
gen_tcp:connect("localhost", 2345,
[binary, {packet, 4}]),
ok = gen_tcp:send(Socket, term_to_binary(Str)),
receive
{tcp,Socket,Bin} ->
io:format("Client received binary = ~p~n",[Bin]),
Val = binary_to_term(Bin),
io:format("Client result = ~p~n",[Val]),
gen_tcp:close(Socket)
end.
start_nano_server() ->
( 6 )
{reuseaddr, true},
{active, true}]),
( 7 )
loop(Socket).
loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("Server received binary = ~p~n",[Bin]),
( 9 )
io:format("Server (unpacked) ~p~n",[Str]),
( 10 )
io:format("Server replying = ~p~n",[Reply]),
( 11 )
loop(Socket);
{tcp_closed, Socket} ->
io:format("Server socket closed~n")
end.
error_test() ->
spawn(fun() -> error_test_server() end),
lib_misc:sleep(2000),
{ok,Socket} = gen_tcp:connect("localhost",4321,[binary, {packet, 2}]),
io:format("connected to:~p~n",[Socket]),
gen_tcp:send(Socket, <<"123">>),
receive
Any ->
io:format("Any=~p~n",[Any])
end.
error_test_server() ->
{ok, Listen} = gen_tcp:listen(4321, [binary,{packet,2}]),
{ok, Socket} = gen_tcp:accept(Listen),
error_test_server_loop(Socket).
error_test_server_loop(Socket) ->
receive
{tcp, Socket, Data} ->
io:format("received:~p~n",[Data]),
_ = atom_to_list(Data),
error_test_server_loop(Socket)
end.
|
5aefa3c26138543ffd2d2a2baa75ad8c77e8ed10bdd7bfac956485e66f7fbbd8 | tnelson/Forge | reader.rkt | #lang racket/base
(require forge/lang/alloy-syntax/parser)
(require forge/lang/alloy-syntax/tokenizer)
(require (only-in forge/lang/reader
coerce-ints-to-atoms))
(define (read-syntax path port)
(define parse-tree (parse path (make-tokenizer port)))
(define ints-coerced (coerce-ints-to-atoms parse-tree))
(define module-datum `(module forge/new-mode-mod forge/new-mode/lang/expander
; Only necessary if you run custom stuff here
; (require forge/sigs)
; Auto-provide all defined values
(provide (except-out (all-defined-out)
forge:n))
; Used for evaluator
(define-namespace-anchor forge:n)
(forge:nsa forge:n)
; Enable new-mode commands
; Only necessary if you run custom stuff here
; (require forge/new-mode/library)
,ints-coerced))
(datum->syntax #f module-datum))
(provide read-syntax) | null | https://raw.githubusercontent.com/tnelson/Forge/1687cba0ebdb598c29c51845d43c98a459d0588f/forge/new-mode/lang/reader.rkt | racket | Only necessary if you run custom stuff here
(require forge/sigs)
Auto-provide all defined values
Used for evaluator
Enable new-mode commands
Only necessary if you run custom stuff here
(require forge/new-mode/library) | #lang racket/base
(require forge/lang/alloy-syntax/parser)
(require forge/lang/alloy-syntax/tokenizer)
(require (only-in forge/lang/reader
coerce-ints-to-atoms))
(define (read-syntax path port)
(define parse-tree (parse path (make-tokenizer port)))
(define ints-coerced (coerce-ints-to-atoms parse-tree))
(define module-datum `(module forge/new-mode-mod forge/new-mode/lang/expander
(provide (except-out (all-defined-out)
forge:n))
(define-namespace-anchor forge:n)
(forge:nsa forge:n)
,ints-coerced))
(datum->syntax #f module-datum))
(provide read-syntax) |
39fea6e5e085eaed08f2e867e80b0bf253dfadd0833fb4ea04f61af44913f6e6 | Decentralized-Pictures/T4L3NT | frozen_deposits_storage.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
val init :
Raw_context.t -> Signature.Public_key_hash.t -> Raw_context.t tzresult Lwt.t
val allocated : Raw_context.t -> Contract_repr.t -> bool Lwt.t
val get : Raw_context.t -> Contract_repr.t -> Storage.deposits tzresult Lwt.t
val find :
Raw_context.t -> Contract_repr.t -> Storage.deposits option tzresult Lwt.t
val credit_only_call_from_token :
Raw_context.t ->
Signature.Public_key_hash.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
val spend_only_call_from_token :
Raw_context.t ->
Signature.Public_key_hash.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
val update_deposits_cap :
Raw_context.t ->
Contract_repr.t ->
Tez_repr.t ->
(Raw_context.t * Tez_repr.t) tzresult Lwt.t
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_012_Psithaca/lib_protocol/frozen_deposits_storage.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
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
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*************************************************************************** | Copyright ( c ) 2021 Nomadic Labs < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
val init :
Raw_context.t -> Signature.Public_key_hash.t -> Raw_context.t tzresult Lwt.t
val allocated : Raw_context.t -> Contract_repr.t -> bool Lwt.t
val get : Raw_context.t -> Contract_repr.t -> Storage.deposits tzresult Lwt.t
val find :
Raw_context.t -> Contract_repr.t -> Storage.deposits option tzresult Lwt.t
val credit_only_call_from_token :
Raw_context.t ->
Signature.Public_key_hash.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
val spend_only_call_from_token :
Raw_context.t ->
Signature.Public_key_hash.t ->
Tez_repr.t ->
Raw_context.t tzresult Lwt.t
val update_deposits_cap :
Raw_context.t ->
Contract_repr.t ->
Tez_repr.t ->
(Raw_context.t * Tez_repr.t) tzresult Lwt.t
|
b4b8280daa039a80f20f6aecd15918a1dcc538097b01c5d11c8061e57693c7b7 | jaredly/belt | belt_Id.ml | type ('a,'id) hash = 'a -> int
type ('a,'id) eq = 'a -> 'a -> bool
type ('a,'id) cmp = 'a -> 'a -> int
let getHashInternal: ('a,'id) hash -> 'a -> int = Obj.magic
let getEqInternal: ('a,'id) eq -> 'a -> 'a -> bool = Obj.magic
let getCmpInternal: ('a,'id) cmp -> 'a -> 'a -> int = Obj.magic
module type Comparable =
sig type identity type t val cmp : (t,identity) cmp end
type ('key,'id) comparable =
(module Comparable with type t = 'key and type identity = 'id)
module MakeComparableU(M:sig type t val cmp : t -> t -> int end) =
struct type identity
type t = M.t
let cmp = M.cmp end
module MakeComparable(M:sig type t val cmp : t -> t -> int end) =
struct
type identity
type t = M.t
let cmp = let cmp = M.cmp in fun a -> fun b -> cmp a b
end
let comparableU (type key) ~cmp =
let module N = MakeComparableU(struct type t = key
let cmp = cmp end) in ((module
N) : (module Comparable with type t = key))
let comparable (type key) ~cmp =
let module N = MakeComparable(struct type t = key
let cmp = cmp end) in ((module
N) : (module Comparable with type t = key))
module type Hashable =
sig
type identity
type t
val hash : (t,identity) hash
val eq : (t,identity) eq
end
type ('key,'id) hashable =
(module Hashable with type t = 'key and type identity = 'id)
module MakeHashableU(M:sig type t val hash : t -> int val eq : t -> t -> bool
end) =
struct type identity
type t = M.t
let hash = M.hash
let eq = M.eq end
module MakeHashable(M:sig type t val hash : t -> int val eq : t -> t -> bool
end) =
struct
type identity
type t = M.t
let hash = let hash = M.hash in fun a -> hash a
let eq = let eq = M.eq in fun a -> fun b -> eq a b
end
let hashableU (type key) ~hash ~eq =
let module N =
MakeHashableU(struct type t = key
let hash = hash
let eq = eq end) in ((module
N) : (module Hashable with type t = key))
let hashable (type key) ~hash ~eq =
let module N =
MakeHashable(struct type t = key
let hash = hash
let eq = eq end) in ((module
N) : (module Hashable with type t = key)) | null | https://raw.githubusercontent.com/jaredly/belt/4d07f859403fdbd3fbfc5a9547c6066d657a2131/belt/belt_Id.ml | ocaml | type ('a,'id) hash = 'a -> int
type ('a,'id) eq = 'a -> 'a -> bool
type ('a,'id) cmp = 'a -> 'a -> int
let getHashInternal: ('a,'id) hash -> 'a -> int = Obj.magic
let getEqInternal: ('a,'id) eq -> 'a -> 'a -> bool = Obj.magic
let getCmpInternal: ('a,'id) cmp -> 'a -> 'a -> int = Obj.magic
module type Comparable =
sig type identity type t val cmp : (t,identity) cmp end
type ('key,'id) comparable =
(module Comparable with type t = 'key and type identity = 'id)
module MakeComparableU(M:sig type t val cmp : t -> t -> int end) =
struct type identity
type t = M.t
let cmp = M.cmp end
module MakeComparable(M:sig type t val cmp : t -> t -> int end) =
struct
type identity
type t = M.t
let cmp = let cmp = M.cmp in fun a -> fun b -> cmp a b
end
let comparableU (type key) ~cmp =
let module N = MakeComparableU(struct type t = key
let cmp = cmp end) in ((module
N) : (module Comparable with type t = key))
let comparable (type key) ~cmp =
let module N = MakeComparable(struct type t = key
let cmp = cmp end) in ((module
N) : (module Comparable with type t = key))
module type Hashable =
sig
type identity
type t
val hash : (t,identity) hash
val eq : (t,identity) eq
end
type ('key,'id) hashable =
(module Hashable with type t = 'key and type identity = 'id)
module MakeHashableU(M:sig type t val hash : t -> int val eq : t -> t -> bool
end) =
struct type identity
type t = M.t
let hash = M.hash
let eq = M.eq end
module MakeHashable(M:sig type t val hash : t -> int val eq : t -> t -> bool
end) =
struct
type identity
type t = M.t
let hash = let hash = M.hash in fun a -> hash a
let eq = let eq = M.eq in fun a -> fun b -> eq a b
end
let hashableU (type key) ~hash ~eq =
let module N =
MakeHashableU(struct type t = key
let hash = hash
let eq = eq end) in ((module
N) : (module Hashable with type t = key))
let hashable (type key) ~hash ~eq =
let module N =
MakeHashable(struct type t = key
let hash = hash
let eq = eq end) in ((module
N) : (module Hashable with type t = key)) | |
e3b0f2aed3c8aa8fe3dc5f1be5803f451c8dc9014e3aba01399b19eea464d163 | sanette/bogue | b_utils.ml | (** Utilities *)
(* Function names should be unambiguous enough to make it safe to open this
module anywhere. *)
open Tsdl
exception Sdl_error of string
let nop _ = ()
let debug =
let d = try
match Sys.getenv "BOGUE_DEBUG" |> String.capitalize_ascii with
| "YES"
| "1"
| "TRUE" -> true
| _ -> false
with Not_found -> false (* set to false for production *)
| e -> raise e in
ref d
let log_channel = ref stdout
let close_log () = close_out !log_channel
let flush_log () = flush !log_channel
let debug_thread = 1
let debug_warning = 2
let debug_graphics = 4
let debug_error = 8
let debug_io = 16
let debug_memory = 32
let debug_board = 64
let debug_event = 128
let debug_custom = 256
let debug_user = 512 (* messages that can be of interest to the (non developer)
user *)
let debug_disable = 1024 (* use this to disable the debug message *)
let debug_code =
ref (debug_error
+ debug_warning
+ debug_graphics
+ debug_thread
+ debug_io
+ debug_board
+ debug_memory
+ debug_event
+ debug_custom
+ debug_user)
(* debug_code := !debug_code lor debug_thread;; *)
let debug_code = ref 511 ; ;
let debug_vars =
[ "Thread", debug_thread;
"Warning", debug_warning;
"Graphics", debug_graphics;
"ERROR", debug_error;
"I/O", debug_io;
"Memory", debug_memory;
"Board", debug_board;
"Event", debug_event;
"Custom", debug_custom;
"User", debug_user]
let debug_to_string =
let debug_array = Array.of_list debug_vars in
fun c ->
let rec loop i n list =
if i = 0 || n = 16 then list
else let code = i land 1 in
if code = 0 then loop (i lsr 1) (n+1) list
else let s = if n > 0 && n < 11
then fst debug_array.(n-1)
else "Unknown" in
loop (i lsr 1) (n+1) (s::list) in
String.concat "; " (loop c 1 [])
Should we put this in a Var / Atomic ?
(* TODO: use this to reduce the number of lock if there is no thread *)
let threads_created = ref 0
(* couleurs xterm, cf : *)
let xterm_red = "\027[0;31m"
let xterm_blue = "\027[0;94m"
let xterm_light_grey = "\027[1;30m"
let xterm_nc = "\027[0m"
let print s = Printf.ksprintf print_endline s
let invalid_arg s = Printf.ksprintf invalid_arg s
let print_debug_old s =
Printf.ksprintf
(fun s ->
if !debug
then print_endline
(xterm_blue ^ "[" ^ (string_of_int (Int32.to_int (Sdl.get_ticks ()) mod 60000)) ^ "] : " ^ xterm_nc ^ s)) s
let debug_select_old code s =
if !debug && (code land !debug_code <> 0)
then print_endline (xterm_red ^ (debug_to_string code) ^ xterm_nc ^ ": " ^ s)
let iksprintf _f = Printf.ikfprintf (fun () -> ()) ()
let printd code =
let debug = !debug && (code land !debug_code <> 0) in
let printf = Printf.(if debug then ksprintf else iksprintf) in
printf (fun s ->
output_string !log_channel
(xterm_blue ^
"[" ^ (string_of_int (Int32.to_int (Sdl.get_ticks ()) mod 60000)) ^ "]" ^
xterm_light_grey ^ "[" ^
(string_of_int (Thread.id (Thread.self ()))) ^ "]" ^ xterm_nc ^ " :\t " ^
xterm_nc ^ xterm_red ^ (debug_to_string code) ^ xterm_nc ^ ": "
^ s ^ "\n");
if !log_channel = stdout then flush !log_channel)
(* check if string s starts with string sub *)
let startswith s sub =
String.length sub = 0 || begin
String.length s >= String.length sub &&
String.sub s 0 (String.length sub) = sub
end
create function for generating integers , starting from 1
let fresh_int () =
let id = ref 0 in
fun () ->
if !id < max_int then (incr id; !id)
else failwith "Too many ids created!"
(* round float to nearest integer: *)
let round x =
int_of_float (Float.round x)
let pi = Float.pi
let square x = x *. x
let rec pwr_old k x =
assert (k>=0);
if k = 0 then 1. else x *. (pwr_old (k-1) x)
let pwr k x = Float.pow x (float k)
Use Int.max and Int.min for ocaml > = 4.13
let imax (x:int) (y:int) =
if x > y then x else y
let imin (x:int) (y:int) =
if x < y then x else y
let fmax = Float.max
let fmin = Float.min
let go : 'a Tsdl.Sdl.result -> 'a = function
| Error _ -> raise (Sdl_error ("SDL ERROR: " ^ (Sdl.get_error ())))
| Ok r -> r
(* List utilities *)
(******************)
let list_iter list f = List.iter f list
Return an option containing the first element of the list for which the
function f does not return None
function f does not return None *)
let rec list_check f l =
match l with
| [] -> None
| x::rest -> begin
match f x with
| None -> list_check f rest
| s -> s
end
(* Idem where the function f returns true *)
let list_check_ok f l =
list_check (fun x -> if f x then Some x else None) l
Return the first element of the list satisfying p , and its index
let list_findi p l =
let rec loop i = function
| [] -> None
| a::rest -> if p a then Some (a, i)
else loop (i+1) rest in
loop 0 l
Split l into two lists l1rev , l2 , where the first element of l2 is the first
element of l for which f is true ( l2 can be empty ) . We always have : l =
l2 .
element of l for which f is true (l2 can be empty). We always have: l =
List.rev_append l1rev l2. *)
let list_split_first_rev f l =
let rec loop l1rev = function
| [] -> l1rev, []
| x::rest as l2 -> if f x then l1rev, l2
else loop (x::l1rev) rest in
loop [] l
let list_split_before l equal x =
let l1rev, l2 = list_split_first_rev (equal x) l in
List.rev l1rev, l2
Return l1rev , x , l2 , where x is the first element for which f x = true and l
is the concatenation of List.rev l1 , x and l2
is the concatenation of List.rev l1, x and l2 *)
let list_split_at_rev f l =
match list_split_first_rev f l with
| _, [] -> raise Not_found
| l1, x::l2 -> l1, x, l2
Replace the first element for which f returns true by x
let list_replace f l x =
let l1, _, l2 = list_split_at_rev f l in
List.rev_append l1 (x :: l2)
returns the list where the first element for which f is true is removed
let list_remove_first f l =
match list_split_first_rev f l with
| _, [] -> raise Not_found
| l1, _::l2 -> List.rev_append l1 l2
splits a list atfer the xth element
let split_list_rev list x =
let rec loop head tail i =
if i >= x then (head, tail)
else match tail with
| [] -> printd debug_error
"Error: position too far in list"; raise Not_found
| a::rest -> loop (a::head) rest (i+1) in
loop [] list 0
let split_list list x =
let daeh, tail = split_list_rev list x in
List.rev daeh, tail
(* checks if 'a' contained in the list, with 'equal' function *)
let rec mem equal a list =
match list with
| [] -> false
| b::rest -> equal a b || mem equal a rest
(* checks if all elements are different (using the 'equal' function) *)
(* not used, use "repeated" below instead *)
let rec injective equal list =
match list with
| [] -> true
| a::rest -> if mem equal a rest then false else injective equal rest
Check if some element is repeated and return the first one . Note this is
O(n² ) in the worse case . One could use sort_uniq instead which should be O(n
log n ) .
O(n²) in the worse case. One could use sort_uniq instead which should be O(n
log n). *)
let rec repeated equal list =
match list with
| [] -> None
| a::rest -> if mem equal a rest then Some a else repeated equal rest
(* max of a list *)
in case of equal elements , the * first * one is selected
let list_max compare list =
match list with
| [] -> None
| a::rest ->
Some (List.fold_left
(fun max x ->
printd debug_warning " Compare=%d " ( compare x min ) ;
if compare x max > 0 then x else max)
a rest)
let run f = f ()
monadic operations . Starting with ocaml 4.08 we can use the Option module .
exception None_option
(* used when the option should not be None. *)
(* let map_option o f = match o with
* | Some x -> Some (f x)
* | None -> None *)
let map_option o f = Option.map f o
(* let do_option o f = match o with
* | Some x -> f x
* | None -> () *)
let do_option o f = Option.iter f o
(* let check_option o f = match o with
* | Some x -> f x
* | None -> None *)
let check_option = Option.bind
(* Warning the "d" is always evaluated, so it's not always a good idea to use
this...use the lazy or fn version instead. *)
let default o d = match o with
| Some x -> x
| None -> d
let default_lazy o d = match o with
| Some x -> x
| None -> Lazy.force d
let default_fn o f = match o with
| Some x -> x
| None -> f ()
let default_option o od = match o with
| None -> od
| o -> o
let map2_option o1 o2 f = match o1, o2 with
| Some x1, Some x2 -> Some (f x1 x2)
| _ -> None
let one_of_two o1 o2 = match o1, o2 with
| None, None -> None
| _, None -> o1
| None, _ -> o2
| _ -> printd debug_warning "one_of_two takes first of two options"; o1
let remove_option = function
| Some x -> x
| None -> raise None_option
let (let@) f x = f x
* This can be used to write , for instance ,
[ let@ x = Var.with_protect v in foo ] instead of
[ Var.with_protect v ( fun x - > foo ) ] ,
where [ foo ] is any expression using [ x ] .
{ b Warning :} the whole sequence of expressions is used . For instance
[ let@ x = Var.with_protect v in foo ; bar ]
will use the function
[ x - > foo ; bar ]
and hence is not the same as
[ Var.with_protect v ( fun x - > foo ) ; bar ] .
It can be wise to write [ begin let@ ... in .. end ]
See also
[let@ x = Var.with_protect v in foo] instead of
[Var.with_protect v (fun x -> foo)],
where [foo] is any expression using [x].
{b Warning:} the whole sequence of expressions is used. For instance
[let@ x = Var.with_protect v in foo; bar]
will use the function
[x -> foo; bar]
and hence is not the same as
[Var.with_protect v (fun x -> foo); bar].
It can be wise to write [begin let@ ... in .. end]
See also *)
(* memo *)
standard memo fns . Do n't use when the variable is mutable , it would store the
old value for ever when the variable changes .
old value for ever when the variable changes. *)
let memo ~name f =
let store = Hashtbl.create 100 in
fun x -> match Hashtbl.find_opt store x with
| Some y -> y
| None -> let result = f x in
Hashtbl.add store x result;
printd debug_memory "##Size of %s Hashtbl : %u" name (Hashtbl.length store);
result
let memo2 f =
let store = Hashtbl.create 100 in
fun x y -> match Hashtbl.find_opt store (x,y) with
| Some y -> y
| None -> let result = f x y in
Hashtbl.add store (x,y) result;
printd debug_memory "##Size of Hashtbl2 : %u" (Hashtbl.length store);
result
let memo3 f =
let store3 = Hashtbl.create 100 in
(fun x y z -> match Hashtbl.find_opt store3 (x,y,z) with
| Some y -> y
| None -> let result = f x y z in
Hashtbl.add store3 (x,y,z) result;
printd debug_memory "###Size of Hashtbl3 : %u" (Hashtbl.length store3);
result),
store3
(* inutile ? *)
let list_sum list =
List.fold_left (+) 0 list
let find_file list_list =
let which command =
BETTER : ( specially for portability to WIN / MAC ) use
/
/ *)
try
let s = Unix.open_process_in ("which " ^ command) in
let res = try
Some (input_line s)
with
| _ -> None in begin
match Unix.close_process_in s with
| Unix.WEXITED 0 -> res
| Unix.WEXITED 1 -> None (* in principle this is redundant since `res`
is already None at this point *)
| _ -> printd (debug_error + debug_io)
"The `which` command exited with error.";
None
end
with
| _ -> printd (debug_error + debug_io) "Cannot use the `which` command.";
None
| null | https://raw.githubusercontent.com/sanette/bogue/abf8f294855d8f46fd4f68bb33b2c2907f0ec07a/lib/b_utils.ml | ocaml | * Utilities
Function names should be unambiguous enough to make it safe to open this
module anywhere.
set to false for production
messages that can be of interest to the (non developer)
user
use this to disable the debug message
debug_code := !debug_code lor debug_thread;;
TODO: use this to reduce the number of lock if there is no thread
couleurs xterm, cf :
check if string s starts with string sub
round float to nearest integer:
List utilities
****************
Idem where the function f returns true
checks if 'a' contained in the list, with 'equal' function
checks if all elements are different (using the 'equal' function)
not used, use "repeated" below instead
max of a list
used when the option should not be None.
let map_option o f = match o with
* | Some x -> Some (f x)
* | None -> None
let do_option o f = match o with
* | Some x -> f x
* | None -> ()
let check_option o f = match o with
* | Some x -> f x
* | None -> None
Warning the "d" is always evaluated, so it's not always a good idea to use
this...use the lazy or fn version instead.
memo
inutile ?
in principle this is redundant since `res`
is already None at this point | open Tsdl
exception Sdl_error of string
let nop _ = ()
let debug =
let d = try
match Sys.getenv "BOGUE_DEBUG" |> String.capitalize_ascii with
| "YES"
| "1"
| "TRUE" -> true
| _ -> false
| e -> raise e in
ref d
let log_channel = ref stdout
let close_log () = close_out !log_channel
let flush_log () = flush !log_channel
let debug_thread = 1
let debug_warning = 2
let debug_graphics = 4
let debug_error = 8
let debug_io = 16
let debug_memory = 32
let debug_board = 64
let debug_event = 128
let debug_custom = 256
let debug_code =
ref (debug_error
+ debug_warning
+ debug_graphics
+ debug_thread
+ debug_io
+ debug_board
+ debug_memory
+ debug_event
+ debug_custom
+ debug_user)
let debug_code = ref 511 ; ;
let debug_vars =
[ "Thread", debug_thread;
"Warning", debug_warning;
"Graphics", debug_graphics;
"ERROR", debug_error;
"I/O", debug_io;
"Memory", debug_memory;
"Board", debug_board;
"Event", debug_event;
"Custom", debug_custom;
"User", debug_user]
let debug_to_string =
let debug_array = Array.of_list debug_vars in
fun c ->
let rec loop i n list =
if i = 0 || n = 16 then list
else let code = i land 1 in
if code = 0 then loop (i lsr 1) (n+1) list
else let s = if n > 0 && n < 11
then fst debug_array.(n-1)
else "Unknown" in
loop (i lsr 1) (n+1) (s::list) in
String.concat "; " (loop c 1 [])
Should we put this in a Var / Atomic ?
let threads_created = ref 0
let xterm_red = "\027[0;31m"
let xterm_blue = "\027[0;94m"
let xterm_light_grey = "\027[1;30m"
let xterm_nc = "\027[0m"
let print s = Printf.ksprintf print_endline s
let invalid_arg s = Printf.ksprintf invalid_arg s
let print_debug_old s =
Printf.ksprintf
(fun s ->
if !debug
then print_endline
(xterm_blue ^ "[" ^ (string_of_int (Int32.to_int (Sdl.get_ticks ()) mod 60000)) ^ "] : " ^ xterm_nc ^ s)) s
let debug_select_old code s =
if !debug && (code land !debug_code <> 0)
then print_endline (xterm_red ^ (debug_to_string code) ^ xterm_nc ^ ": " ^ s)
let iksprintf _f = Printf.ikfprintf (fun () -> ()) ()
let printd code =
let debug = !debug && (code land !debug_code <> 0) in
let printf = Printf.(if debug then ksprintf else iksprintf) in
printf (fun s ->
output_string !log_channel
(xterm_blue ^
"[" ^ (string_of_int (Int32.to_int (Sdl.get_ticks ()) mod 60000)) ^ "]" ^
xterm_light_grey ^ "[" ^
(string_of_int (Thread.id (Thread.self ()))) ^ "]" ^ xterm_nc ^ " :\t " ^
xterm_nc ^ xterm_red ^ (debug_to_string code) ^ xterm_nc ^ ": "
^ s ^ "\n");
if !log_channel = stdout then flush !log_channel)
let startswith s sub =
String.length sub = 0 || begin
String.length s >= String.length sub &&
String.sub s 0 (String.length sub) = sub
end
create function for generating integers , starting from 1
let fresh_int () =
let id = ref 0 in
fun () ->
if !id < max_int then (incr id; !id)
else failwith "Too many ids created!"
let round x =
int_of_float (Float.round x)
let pi = Float.pi
let square x = x *. x
let rec pwr_old k x =
assert (k>=0);
if k = 0 then 1. else x *. (pwr_old (k-1) x)
let pwr k x = Float.pow x (float k)
Use Int.max and Int.min for ocaml > = 4.13
let imax (x:int) (y:int) =
if x > y then x else y
let imin (x:int) (y:int) =
if x < y then x else y
let fmax = Float.max
let fmin = Float.min
let go : 'a Tsdl.Sdl.result -> 'a = function
| Error _ -> raise (Sdl_error ("SDL ERROR: " ^ (Sdl.get_error ())))
| Ok r -> r
let list_iter list f = List.iter f list
Return an option containing the first element of the list for which the
function f does not return None
function f does not return None *)
let rec list_check f l =
match l with
| [] -> None
| x::rest -> begin
match f x with
| None -> list_check f rest
| s -> s
end
let list_check_ok f l =
list_check (fun x -> if f x then Some x else None) l
Return the first element of the list satisfying p , and its index
let list_findi p l =
let rec loop i = function
| [] -> None
| a::rest -> if p a then Some (a, i)
else loop (i+1) rest in
loop 0 l
Split l into two lists l1rev , l2 , where the first element of l2 is the first
element of l for which f is true ( l2 can be empty ) . We always have : l =
l2 .
element of l for which f is true (l2 can be empty). We always have: l =
List.rev_append l1rev l2. *)
let list_split_first_rev f l =
let rec loop l1rev = function
| [] -> l1rev, []
| x::rest as l2 -> if f x then l1rev, l2
else loop (x::l1rev) rest in
loop [] l
let list_split_before l equal x =
let l1rev, l2 = list_split_first_rev (equal x) l in
List.rev l1rev, l2
Return l1rev , x , l2 , where x is the first element for which f x = true and l
is the concatenation of List.rev l1 , x and l2
is the concatenation of List.rev l1, x and l2 *)
let list_split_at_rev f l =
match list_split_first_rev f l with
| _, [] -> raise Not_found
| l1, x::l2 -> l1, x, l2
Replace the first element for which f returns true by x
let list_replace f l x =
let l1, _, l2 = list_split_at_rev f l in
List.rev_append l1 (x :: l2)
returns the list where the first element for which f is true is removed
let list_remove_first f l =
match list_split_first_rev f l with
| _, [] -> raise Not_found
| l1, _::l2 -> List.rev_append l1 l2
splits a list atfer the xth element
let split_list_rev list x =
let rec loop head tail i =
if i >= x then (head, tail)
else match tail with
| [] -> printd debug_error
"Error: position too far in list"; raise Not_found
| a::rest -> loop (a::head) rest (i+1) in
loop [] list 0
let split_list list x =
let daeh, tail = split_list_rev list x in
List.rev daeh, tail
let rec mem equal a list =
match list with
| [] -> false
| b::rest -> equal a b || mem equal a rest
let rec injective equal list =
match list with
| [] -> true
| a::rest -> if mem equal a rest then false else injective equal rest
Check if some element is repeated and return the first one . Note this is
O(n² ) in the worse case . One could use sort_uniq instead which should be O(n
log n ) .
O(n²) in the worse case. One could use sort_uniq instead which should be O(n
log n). *)
let rec repeated equal list =
match list with
| [] -> None
| a::rest -> if mem equal a rest then Some a else repeated equal rest
in case of equal elements , the * first * one is selected
let list_max compare list =
match list with
| [] -> None
| a::rest ->
Some (List.fold_left
(fun max x ->
printd debug_warning " Compare=%d " ( compare x min ) ;
if compare x max > 0 then x else max)
a rest)
let run f = f ()
monadic operations . Starting with ocaml 4.08 we can use the Option module .
exception None_option
let map_option o f = Option.map f o
let do_option o f = Option.iter f o
let check_option = Option.bind
let default o d = match o with
| Some x -> x
| None -> d
let default_lazy o d = match o with
| Some x -> x
| None -> Lazy.force d
let default_fn o f = match o with
| Some x -> x
| None -> f ()
let default_option o od = match o with
| None -> od
| o -> o
let map2_option o1 o2 f = match o1, o2 with
| Some x1, Some x2 -> Some (f x1 x2)
| _ -> None
let one_of_two o1 o2 = match o1, o2 with
| None, None -> None
| _, None -> o1
| None, _ -> o2
| _ -> printd debug_warning "one_of_two takes first of two options"; o1
let remove_option = function
| Some x -> x
| None -> raise None_option
let (let@) f x = f x
* This can be used to write , for instance ,
[ let@ x = Var.with_protect v in foo ] instead of
[ Var.with_protect v ( fun x - > foo ) ] ,
where [ foo ] is any expression using [ x ] .
{ b Warning :} the whole sequence of expressions is used . For instance
[ let@ x = Var.with_protect v in foo ; bar ]
will use the function
[ x - > foo ; bar ]
and hence is not the same as
[ Var.with_protect v ( fun x - > foo ) ; bar ] .
It can be wise to write [ begin let@ ... in .. end ]
See also
[let@ x = Var.with_protect v in foo] instead of
[Var.with_protect v (fun x -> foo)],
where [foo] is any expression using [x].
{b Warning:} the whole sequence of expressions is used. For instance
[let@ x = Var.with_protect v in foo; bar]
will use the function
[x -> foo; bar]
and hence is not the same as
[Var.with_protect v (fun x -> foo); bar].
It can be wise to write [begin let@ ... in .. end]
See also *)
standard memo fns . Do n't use when the variable is mutable , it would store the
old value for ever when the variable changes .
old value for ever when the variable changes. *)
let memo ~name f =
let store = Hashtbl.create 100 in
fun x -> match Hashtbl.find_opt store x with
| Some y -> y
| None -> let result = f x in
Hashtbl.add store x result;
printd debug_memory "##Size of %s Hashtbl : %u" name (Hashtbl.length store);
result
let memo2 f =
let store = Hashtbl.create 100 in
fun x y -> match Hashtbl.find_opt store (x,y) with
| Some y -> y
| None -> let result = f x y in
Hashtbl.add store (x,y) result;
printd debug_memory "##Size of Hashtbl2 : %u" (Hashtbl.length store);
result
let memo3 f =
let store3 = Hashtbl.create 100 in
(fun x y z -> match Hashtbl.find_opt store3 (x,y,z) with
| Some y -> y
| None -> let result = f x y z in
Hashtbl.add store3 (x,y,z) result;
printd debug_memory "###Size of Hashtbl3 : %u" (Hashtbl.length store3);
result),
store3
let list_sum list =
List.fold_left (+) 0 list
let find_file list_list =
let which command =
BETTER : ( specially for portability to WIN / MAC ) use
/
/ *)
try
let s = Unix.open_process_in ("which " ^ command) in
let res = try
Some (input_line s)
with
| _ -> None in begin
match Unix.close_process_in s with
| Unix.WEXITED 0 -> res
| _ -> printd (debug_error + debug_io)
"The `which` command exited with error.";
None
end
with
| _ -> printd (debug_error + debug_io) "Cannot use the `which` command.";
None
|
4fb0cc1d25d7661ea8b2c387e96d6749f30381f0cc6bfd93b9660fd3664db522 | alan-turing-institute/advent-of-code-2021 | day_10.rkt | #lang racket
; define as const
(define LHS-RHS-MAP (hash #\( #\)
#\[ #\]
#\{ #\}
#\< #\>))
(define (parse-input input-str)
(map string->list (string-split input-str)))
; stack operations
(define (stack-push stack item)
(cons item stack))
(define (stack-pop stack)
(values (car stack) (cdr stack)))
(define (lhs stack item)
(let ([s (stack-push stack item)])
(values s null)))
(define (rhs stack item)
(let-values ([(left-bracket s) (stack-pop stack)])
popped item should be correct lhs for current rhs item
(if (equal? (hash-ref LHS-RHS-MAP left-bracket) item)
(values s null)
;otherwise error, set illegal item
(values s item))))
(define (parse-line line)
(for/fold ([stack '()]
[illegal-item null])
([item line]
#:break (not (null? illegal-item)))
(if (hash-has-key? LHS-RHS-MAP item)
is LHS bracket
(lhs stack item)
; otherwise is RHS bracket, check match
(rhs stack item)
)
)
)
return middle item from list after sorting , ignoring zeros
can assume only positive ( other than zero )
; will always be odd number of items
(define (middle-ignore-zeros xs)
(let ([l (sort (filter positive? xs) <)])
(first (list-tail l (quotient (length l) 2)))))
; --------- PARTS ---------
(define (part-one input-str)
; points map provided by puzzle
; use chars
(define points-map (hash #\) 3
#\] 57
#\} 1197
#\> 25137))
(for/sum ([line (parse-input input-str)])
(let-values ([(stack error-item) (parse-line line)])
(hash-ref points-map error-item 0))))
(define (part-two input-str)
(define points-map (hash #\( 1
#\[ 2
#\{ 3
#\< 4))
(middle-ignore-zeros (for/list ([line (parse-input input-str)])
(let-values ([(stack last-item) (parse-line line)])
(if (null? last-item)
; no error
(for/fold ([sum 0])
([lhs-item stack])
(+ (* sum 5) (hash-ref points-map lhs-item))
)
; else
0
)))))
; --------- MAIN ---------
(module+ main
(require 2htdp/batch-io)
(define instr (read-file "input_10.txt"))
(define answer-one (part-one instr))
(display "answer 1\n")
(display answer-one);
(define answer-two (part-two instr))
(display "\n\n###\n\nanswer 2\n")
(display answer-two)
)
; --------- TEST ---------
(module+ test
(require rackunit)
(define testin #<<EOS
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
EOS
)
(check-equal? (part-one testin) 26397 "Part one test")
(check-equal? (part-two testin) 288957 "Part two test")
)
| null | https://raw.githubusercontent.com/alan-turing-institute/advent-of-code-2021/525029fba3230ed88deaf61c9f3eb10a3ff35908/day-10/racket_lannelin/day_10.rkt | racket | define as const
stack operations
otherwise error, set illegal item
otherwise is RHS bracket, check match
will always be odd number of items
--------- PARTS ---------
points map provided by puzzle
use chars
no error
else
--------- MAIN ---------
--------- TEST --------- | #lang racket
(define LHS-RHS-MAP (hash #\( #\)
#\[ #\]
#\{ #\}
#\< #\>))
(define (parse-input input-str)
(map string->list (string-split input-str)))
(define (stack-push stack item)
(cons item stack))
(define (stack-pop stack)
(values (car stack) (cdr stack)))
(define (lhs stack item)
(let ([s (stack-push stack item)])
(values s null)))
(define (rhs stack item)
(let-values ([(left-bracket s) (stack-pop stack)])
popped item should be correct lhs for current rhs item
(if (equal? (hash-ref LHS-RHS-MAP left-bracket) item)
(values s null)
(values s item))))
(define (parse-line line)
(for/fold ([stack '()]
[illegal-item null])
([item line]
#:break (not (null? illegal-item)))
(if (hash-has-key? LHS-RHS-MAP item)
is LHS bracket
(lhs stack item)
(rhs stack item)
)
)
)
return middle item from list after sorting , ignoring zeros
can assume only positive ( other than zero )
(define (middle-ignore-zeros xs)
(let ([l (sort (filter positive? xs) <)])
(first (list-tail l (quotient (length l) 2)))))
(define (part-one input-str)
(define points-map (hash #\) 3
#\] 57
#\} 1197
#\> 25137))
(for/sum ([line (parse-input input-str)])
(let-values ([(stack error-item) (parse-line line)])
(hash-ref points-map error-item 0))))
(define (part-two input-str)
(define points-map (hash #\( 1
#\[ 2
#\{ 3
#\< 4))
(middle-ignore-zeros (for/list ([line (parse-input input-str)])
(let-values ([(stack last-item) (parse-line line)])
(if (null? last-item)
(for/fold ([sum 0])
([lhs-item stack])
(+ (* sum 5) (hash-ref points-map lhs-item))
)
0
)))))
(module+ main
(require 2htdp/batch-io)
(define instr (read-file "input_10.txt"))
(define answer-one (part-one instr))
(display "answer 1\n")
(define answer-two (part-two instr))
(display "\n\n###\n\nanswer 2\n")
(display answer-two)
)
(module+ test
(require rackunit)
(define testin #<<EOS
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
EOS
)
(check-equal? (part-one testin) 26397 "Part one test")
(check-equal? (part-two testin) 288957 "Part two test")
)
|
0383c0a6e8af9b01c05e10dc37d302b8cdcef91f571438c35264f793aaf963d4 | owainlewis/digital-ocean | images.clj | (ns digitalocean.v1.images
(require [digitalocean.v1.core :as core]))
;; GET /images
(defn all-images
"List all Digital Ocean images"
[client-id api-key]
(core/get-for "images" client-id api-key))
(def images (memoize all-images))
(defn ubuntu-images [client-id api-key]
(->> (images client-id api-key)
(filter #(boolean
(re-find #"Ubuntu"
(:distribution %))))))
(defn image-id-action
"Helper function for images with an image_id"
([action]
(fn [client-id api-key image-id]
(let [f (core/simple-id-action "images" image-id action)]
(f client-id api-key)))))
;; GET /images/[image_id]
(defn image
"Fetch a single image"
[client-id api-key image-id]
(let [response (core/request (str "images/" image-id) client-id api-key)]
(->> response :image)))
;; GET /images/[image_id]/destroy
(def destroy-image (image-id-action "destroy"))
;; GET /images/[image_id]/transfer
| null | https://raw.githubusercontent.com/owainlewis/digital-ocean/25ce510a369429b191ea5b18f0eef77b618ee88d/src/digitalocean/v1/images.clj | clojure | GET /images
GET /images/[image_id]
GET /images/[image_id]/destroy
GET /images/[image_id]/transfer | (ns digitalocean.v1.images
(require [digitalocean.v1.core :as core]))
(defn all-images
"List all Digital Ocean images"
[client-id api-key]
(core/get-for "images" client-id api-key))
(def images (memoize all-images))
(defn ubuntu-images [client-id api-key]
(->> (images client-id api-key)
(filter #(boolean
(re-find #"Ubuntu"
(:distribution %))))))
(defn image-id-action
"Helper function for images with an image_id"
([action]
(fn [client-id api-key image-id]
(let [f (core/simple-id-action "images" image-id action)]
(f client-id api-key)))))
(defn image
"Fetch a single image"
[client-id api-key image-id]
(let [response (core/request (str "images/" image-id) client-id api-key)]
(->> response :image)))
(def destroy-image (image-id-action "destroy"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.