_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 |
|---|---|---|---|---|---|---|---|---|
efce644039d4e8bcedb49a75ab51bb2d7c271575eead0305a85062cffcd817f8 | returntocorp/semgrep | Apply_equivalences.mli | val apply : Equivalence.t list -> Lang.t -> Pattern.t -> Pattern.t
| null | https://raw.githubusercontent.com/returntocorp/semgrep/70af5900482dd15fcce9b8508bd387f7355a531d/src/matching/Apply_equivalences.mli | ocaml | val apply : Equivalence.t list -> Lang.t -> Pattern.t -> Pattern.t
| |
ed6387b708cb5033e9fb994a58b236d69b876588f0f26dc7395d18653ed5ba18 | jablo/cablesim | mac_generator.erl | %%%-------------------------------------------------------------------
@author
08 March 2013 by < >
@doc Unique MAC address generator
%%% @end
%%%-------------------------------------------------------------------
-module(mac_generator).
-behaviour(gen_server).
-include("debug.hrl").
%% Public API
-export([start_link/0, nextmac/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {prefixdict}).
%%====================================================================
%% API
%%====================================================================
%% @doc
Starts the address generator server
%% @end
%%--------------------------------------------------------------------
start_link() ->
?debug("mac_generator:start_link()~n"),
X = gen_server:start_link({local, ?MODULE}, ?MODULE,
[],
[]),
?debug("mac_generator:start_link() returns ~p~n", [X]),
X. %{debug,[trace]}{debug,[log]}
%% @doc
Calcalate a next mac address based on a mac vendor prefix . Repeated calls
%% will generate a new unique mac address (based on an increasing counter).
A fully specified address will just be returned unmodified .
%% @end
nextmac(M = {_,_,_,_,_,_}) ->
M;
nextmac(Prefix = {_,_,_}) ->
?debug("mac_generator:nextmac(~p)~n", [Prefix]),
gen_server:call(?MODULE, {nextmac, Prefix}).
%%---------------------------------------------------------------------
%% Gen-server callbacks
%%---------------------------------------------------------------------
%% @doc Initialize an instance of the cmts server process
) - > { ok , State } |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
init(_Arg) ->
?debug("mac_generator:init(~p)~n", [_Arg]),
X = {ok, #state{prefixdict=dict:new()}},
?debug("mac_generator:init(~p) returns ~p~n", [_Arg, X]),
X.
handle_call(_X = {nextmac, Prefix}, From, State) ->
?debug("mac_generator:handle_call(~p, ~p, ~p) ~n", [_X, From, State]),
handle_nextmac(Prefix, From, State);
handle_call(_X = {test}, _F, S) ->
?debug("TEST: mac_generator:(~p, ~p, ~p) ~n", [_X, _F, S]),
{reply, ok, S};
handle_call(_X, _F, _S) ->
?debug("no match: mac_generator:(~p, ~p, ~p) ~n", [_X, _F, _S]),
error.
handle_nextmac(Prefix = {A, B, C}, _From, State = #state{prefixdict=Prefixes}) ->
{Prefixes2, Count} = case dict:find(Prefix, Prefixes) of
{ok, Countx} ->
{dict:store(Prefix, Countx+1, Prefixes), Countx};
_ ->
Countx = 0,
{dict:store(Prefix, 1, Prefixes), Countx}
end,
State2 = State#state{prefixdict=Prefixes2},
Mac = {A, B, C, Count div 256 div 256, Count div 256, Count rem 256},
{reply, Mac, State2}.
handle_cast(stop, State) ->
{stop, normal, State}.
handle_info(_Info, State) ->
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, _State) ->
ok.
| null | https://raw.githubusercontent.com/jablo/cablesim/da6628190f9ec5c426df73e921ff575470d1a078/src/mac_generator.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
Public API
gen_server callbacks
====================================================================
API
====================================================================
@doc
@end
--------------------------------------------------------------------
{debug,[trace]}{debug,[log]}
@doc
will generate a new unique mac address (based on an increasing counter).
@end
---------------------------------------------------------------------
Gen-server callbacks
---------------------------------------------------------------------
@doc Initialize an instance of the cmts server process
ignore |
{stop, Reason} | @author
08 March 2013 by < >
@doc Unique MAC address generator
-module(mac_generator).
-behaviour(gen_server).
-include("debug.hrl").
-export([start_link/0, nextmac/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {prefixdict}).
Starts the address generator server
start_link() ->
?debug("mac_generator:start_link()~n"),
X = gen_server:start_link({local, ?MODULE}, ?MODULE,
[],
[]),
?debug("mac_generator:start_link() returns ~p~n", [X]),
Calcalate a next mac address based on a mac vendor prefix . Repeated calls
A fully specified address will just be returned unmodified .
nextmac(M = {_,_,_,_,_,_}) ->
M;
nextmac(Prefix = {_,_,_}) ->
?debug("mac_generator:nextmac(~p)~n", [Prefix]),
gen_server:call(?MODULE, {nextmac, Prefix}).
) - > { ok , State } |
{ ok , State , Timeout } |
init(_Arg) ->
?debug("mac_generator:init(~p)~n", [_Arg]),
X = {ok, #state{prefixdict=dict:new()}},
?debug("mac_generator:init(~p) returns ~p~n", [_Arg, X]),
X.
handle_call(_X = {nextmac, Prefix}, From, State) ->
?debug("mac_generator:handle_call(~p, ~p, ~p) ~n", [_X, From, State]),
handle_nextmac(Prefix, From, State);
handle_call(_X = {test}, _F, S) ->
?debug("TEST: mac_generator:(~p, ~p, ~p) ~n", [_X, _F, S]),
{reply, ok, S};
handle_call(_X, _F, _S) ->
?debug("no match: mac_generator:(~p, ~p, ~p) ~n", [_X, _F, _S]),
error.
handle_nextmac(Prefix = {A, B, C}, _From, State = #state{prefixdict=Prefixes}) ->
{Prefixes2, Count} = case dict:find(Prefix, Prefixes) of
{ok, Countx} ->
{dict:store(Prefix, Countx+1, Prefixes), Countx};
_ ->
Countx = 0,
{dict:store(Prefix, 1, Prefixes), Countx}
end,
State2 = State#state{prefixdict=Prefixes2},
Mac = {A, B, C, Count div 256 div 256, Count div 256, Count rem 256},
{reply, Mac, State2}.
handle_cast(stop, State) ->
{stop, normal, State}.
handle_info(_Info, State) ->
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
terminate(_Reason, _State) ->
ok.
|
5897a4d5d5ddebd13eb55f7c724068f380b31463e6f3b75a438871d3a159c8ce | bscarlet/llvm-general | Threading.hs | | functionality necessary when running in multiple threads at the same time .
module LLVM.General.Threading (
setMultithreaded,
isMultithreaded
) where
import LLVM.General.Prelude
import LLVM.General.Internal.Threading
# DEPRECATED setMultithreaded " LLVM no longer features runtime control of multithreading support " #
| This function used set the multithreading mode of , but that feature no longer exists . Threading is
-- controlled only at runtime with the configure flag --enable-threads (default is YES). This function will
-- now check that the the compiled-in multithreading support (returned by 'isMultithreaded') is
-- sufficient to support the requested access, and fail if not, so as to prevent uncontrolled use of a
version of compiled to be capable only of singled threaded use by haskell code requesting
-- multithreading support.
setMultithreaded :: Bool -> IO ()
setMultithreaded desired = do
actual <- isMultithreaded
when (desired && not actual) $
fail $ "Multithreading support requested but not available. " ++
"Please use an LLVM built with threading enabled"
return ()
| null | https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/LLVM/General/Threading.hs | haskell | controlled only at runtime with the configure flag --enable-threads (default is YES). This function will
now check that the the compiled-in multithreading support (returned by 'isMultithreaded') is
sufficient to support the requested access, and fail if not, so as to prevent uncontrolled use of a
multithreading support. | | functionality necessary when running in multiple threads at the same time .
module LLVM.General.Threading (
setMultithreaded,
isMultithreaded
) where
import LLVM.General.Prelude
import LLVM.General.Internal.Threading
# DEPRECATED setMultithreaded " LLVM no longer features runtime control of multithreading support " #
| This function used set the multithreading mode of , but that feature no longer exists . Threading is
version of compiled to be capable only of singled threaded use by haskell code requesting
setMultithreaded :: Bool -> IO ()
setMultithreaded desired = do
actual <- isMultithreaded
when (desired && not actual) $
fail $ "Multithreading support requested but not available. " ++
"Please use an LLVM built with threading enabled"
return ()
|
4d6253325e294e44d9672152aac84d3ad42cb2f86de8741d63622c49d17792d3 | soegaard/remacs | region.rkt | #lang racket/base
(provide (all-defined-out))
(require racket/list
"representation.rkt"
"parameters.rkt"
"text.rkt"
"mark.rkt"
"point.rkt")
;;;
;;; REGIONS
;;;
The region is the text between point and the first mark .
The representation of the region is therefore implicitly given by the point and the first mark .
; set-mark-command sets a mark, and then a region exists
(define (region-beginning)
(define b (current-buffer))
(define mark (buffer-the-mark b))
(define point (buffer-point b))
(min (mark-position mark)
(mark-position point)))
(define (region-end)
(define b (current-buffer))
(define mark (buffer-the-mark b))
(define point (buffer-point b))
(max (mark-position mark)
(mark-position point)))
(define (region-size)
(- (region-end) (region-beginning)))
(define (region->string)
(define b (current-buffer))
(cond
[(use-region?)
(define t (buffer-text b))
(subtext->string t (region-beginning) (region-end))]
[else #f]))
(define (region-between-marks->string beg end [b (current-buffer)])
(define from (min (mark-position beg) (mark-position end)))
(define to (max (mark-position beg) (mark-position end)))
(subtext->string (buffer-text b) from to))
(define (use-region?)
(define b (current-buffer))
(define mark (buffer-the-mark b))
(and #t ; (transient-mode-on? b)
(mark-active? mark)
(let ()
(define beg (region-beginning))
(define end (region-end))
(and beg end (> end beg)))))
(define (region-mark [b (current-buffer)])
(buffer-the-mark b))
(define (deactivate-region-mark)
(cond [(region-mark) => mark-deactivate!]))
| null | https://raw.githubusercontent.com/soegaard/remacs/8681b3acfe93335e2bc2133c6f144af9e0a1289e/region.rkt | racket |
REGIONS
set-mark-command sets a mark, and then a region exists
(transient-mode-on? b) | #lang racket/base
(provide (all-defined-out))
(require racket/list
"representation.rkt"
"parameters.rkt"
"text.rkt"
"mark.rkt"
"point.rkt")
The region is the text between point and the first mark .
The representation of the region is therefore implicitly given by the point and the first mark .
(define (region-beginning)
(define b (current-buffer))
(define mark (buffer-the-mark b))
(define point (buffer-point b))
(min (mark-position mark)
(mark-position point)))
(define (region-end)
(define b (current-buffer))
(define mark (buffer-the-mark b))
(define point (buffer-point b))
(max (mark-position mark)
(mark-position point)))
(define (region-size)
(- (region-end) (region-beginning)))
(define (region->string)
(define b (current-buffer))
(cond
[(use-region?)
(define t (buffer-text b))
(subtext->string t (region-beginning) (region-end))]
[else #f]))
(define (region-between-marks->string beg end [b (current-buffer)])
(define from (min (mark-position beg) (mark-position end)))
(define to (max (mark-position beg) (mark-position end)))
(subtext->string (buffer-text b) from to))
(define (use-region?)
(define b (current-buffer))
(define mark (buffer-the-mark b))
(mark-active? mark)
(let ()
(define beg (region-beginning))
(define end (region-end))
(and beg end (> end beg)))))
(define (region-mark [b (current-buffer)])
(buffer-the-mark b))
(define (deactivate-region-mark)
(cond [(region-mark) => mark-deactivate!]))
|
4e02163b9a96a7cf4c3c9b7b34920cbb941bed7b3c7cf39519b96fbd419e49c5 | mattmundell/nightshade | new-assem.lisp | ;;; Efficient retargetable scheduling assembler.
;;;
FIX rename assembler.lisp
(in-package "NEW-ASSEM")
(in-package :c)
(import '(branch flushable) :new-assem)
(import '(sset-element sset make-sset do-elements
sset-adjoin sset-delete sset-empty)
:new-assem)
(in-package :new-assem)
(export '(emit-byte emit-skip emit-back-patch emit-chooser emit-postit
define-emitter define-instruction define-instruction-macro
def-assembler-params branch flushable variable-length reads writes
;;
segment make-segment segment-name segment-collect-dynamic-statistics
assemble align inst without-scheduling
label label-p gen-label emit-label label-position
append-segment finalize-segment
segment-map-output release-segment))
#[ Assembly
Resolve branches and convert into object code and fixup information.
Phase position: 22/23 (back)
Presence: required
Files: codegen
Entry functions: `new-assem:finalize-segment'
Call sequences:
native-compile-component
generate-code
new-assem:finalize-segment
new-assem:compress-output
new-assem:finalize-positions
new-assem:process-back-patches
In effect, we do much of the work of assembly when the compiler is compiled.
The assembler makes one pass fixing up branch offsets, then squeezes out the
space left by branch shortening and dumps out the code along with the load-time
fixup information. The assembler also deals with dumping unboxed non-immediate
constants and symbols. Boxed constants are created by explicit constructor
code in the top-level form, while immediate constants are generated using
inline code.
XXX The basic output of the assembler is:
A code vector
A representation of the fixups along with indices into the code vector for
the fixup locations
A PC map translating PCs into source paths
This information can then be used to build an output file or an in-core
function object.
The assembler is table-driven and supports arbitrary instruction formats. As
far as the assembler is concerned, an instruction is a bit sequence that is
broken down into subsequences. Some of the subsequences are constant in value,
while others can be determined at assemble or load time.
Assemble Node Form*
Allow instructions to be emitted during the evaluation of the Forms by
defining Inst as a local macro. This macro caches various global
information in local variables. Node tells the assembler what node
ultimately caused this code to be generated. This is used to create the
pc=>source map for the debugger.
Assemble-Elsewhere Node Form*
Similar to Assemble, but the current assembler location is changed to
somewhere else. This is useful for generating error code and similar
things. Assemble-Elsewhere may not be nested.
Inst Name Arg*
Emit the instruction Name with the specified arguments.
Gen-Label
Emit-Label (Label)
Gen-Label returns a Label object, which describes a place in the code.
Emit-Label marks the current position as being the location of Label.
]#
#[ Writing Assembly Code
VOP writers expect:
MOVE
You write when you port the assembler.
EMIT-LABEL
Assembler interface like INST. Takes a label you made and says "stick it
here."
GEN-LABEL
Returns a new label suitable for use with EMIT-LABEL exactly once and
for referencing as often as necessary.
INST
Recognizes and dispatches to instructions you defined for assembler.
ALIGN
This takes the number of zero bits you want in the low end of the address
of the next instruction.
ASSEMBLE
ASSEMBLE-ELSEWHERE
Get ready for assembling stuff. Takes a VOP and arbitrary PROGN-style
body. Wrap these around instruction emission code announcing the first
pass of our assembler.
CURRENT-NFP-TN
This returns a TN for the NFP if the caller uses the number stack, or
nil.
SB-ALLOCATED-SIZE
This returns the size of some storage based used by the currently
compiling component.
...
VOP idioms
;;;
STORE-STACK-TN
LOAD-STACK-TN
These move a value from a register to the control stack, or from the
control stack to a register. They take care of checking the TN types,
modifying offsets according to the address units per word, etc.
]#
#[ Pipeline Reorganization
On some machines, move memory references backward in the code so that
they can overlap with computation. On machines with delayed branch
instructions, locate instructions that can be moved into delay slots.
Phase position: 21/23 (back)
Presence: required
Files: codegen
Entry functions: `new-assem:finalize-segment'
Call sequences:
c:native-compile-component
c:generate-code
new-assem:finalize-segment
new-assem:schedule-pending-instructions
new-assem:add-to-nth-list
new-assem:schedule-one-inst
new-assem:advance-one-inst
new-assem:note-resolved-dependencies
c:emit-nop
]#
Assembly control parameters .
(defstruct (assem-params
(:print-function %print-assem-params))
(backend (ext:required-argument) :type c::backend)
(scheduler-p nil :type (member t nil))
(instructions (make-hash-table :test #'equal) :type hash-table)
(max-locations 0 :type index))
;;;
(c::defprinter assem-params
(backend :prin1 (c:backend-name backend)))
;;; DEF-ASSEMBLER-PARAMS -- Interface.
;;;
(defmacro def-assembler-params (&rest options)
"Set up the assembler."
`(eval-when (compile load eval)
(setf (c:backend-assembler-params c:*target-backend*)
(make-assem-params :backend c:*target-backend*
,@options))))
;;;; Constants.
ASSEMBLY - UNIT - BITS -- Number of bits in the minimum assembly unit ,
;;; (also refered to as a ``byte''). Hopefully, different instruction
;;; sets won't require chainging this.
;;;
(defconstant assembly-unit-bits 8)
(deftype assembly-unit ()
`(unsigned-byte ,assembly-unit-bits))
;;; OUTPUT-BLOCK-SIZE -- The size (in bytes) to use per output block. Each
;;; output block is a chunk of raw memory, pointed to by a sap.
;;;
(defconstant output-block-size (* 8 1024))
(deftype output-block-index ()
`(integer 0 ,output-block-size))
MAX - ALIGNMENT -- The maximum alignment we can guarentee given the object
format . If the loader only loads objects 8 - byte aligned , we ca n't do
;;; any better then that ourselves.
;;;
(defconstant max-alignment 3)
(deftype alignment ()
`(integer 0 ,max-alignment))
MAX - INDEX -- The maximum an index will ever become . Well , actually ,
;;; just a bound on it so we can define a type. There is no real hard
;;; limit on indexes, but we will run out of memory sometime.
;;;
(defconstant max-index (1- most-positive-fixnum))
(deftype index ()
`(integer 0 ,max-index))
MAX - POSN -- Like MAX - INDEX , except for positions .
;;;
(defconstant max-posn (1- most-positive-fixnum))
(deftype posn ()
`(integer 0 ,max-posn))
;;;; The SEGMENT structure.
;;; SEGMENT -- This structure holds the state of the assembler.
;;;
(defstruct (segment
(:print-function %print-segment)
(:constructor make-segment (&key name run-scheduler inst-hook)))
;;
;; The name of this segment. Only using in trace files.
(name "Unnamed" :type simple-base-string)
;;
;; Whether or not run the scheduler. Note: if the instruction defintions
;; were not compiled with the scheduler turned on, this has no effect.
(run-scheduler nil)
;;
;; If a function, then it is funcalled for each inst emitted with the
segment , the VOP , the name of the inst ( as a string ) , and the inst
;; arguments.
(inst-hook nil :type (or function null))
;;
;; Where to deposit the next byte.
(fill-pointer (system:int-sap 0) :type system:system-area-pointer)
;;
;; Where the current output block ends. If fill-pointer is ever sap= to
;; this, don't deposit a byte. Move the fill pointer into a new block.
(block-end (system:int-sap 0) :type system:system-area-pointer)
;;
;; What position does this correspond to. Initially, positions and indexes
;; are the same, but after we start collapsing choosers, positions can change
;; while indexes stay the same.
(current-posn 0 :type posn)
;;
;; Where in the output blocks are we currently outputing.
(current-index 0 :type index)
;;
;; A vector of the output blocks.
(output-blocks (make-array 4 :initial-element nil) :type simple-vector)
;;
;; A list of all the annotations that have been output to this segment.
(annotations nil :type list)
;;
;; A pointer to the last cons cell in the annotations list. This is
;; so we can quickly add things to the end of the annotations list.
(last-annotation nil :type list)
;;
;; The number of bits of alignment at the last time we synchronized.
(alignment max-alignment :type alignment)
;;
;; The position the last time we synchronized.
(sync-posn 0 :type posn)
;;
;; The posn and index everything ends at. This is not maintained while the
;; data is being generated, but is filled in after. Basically, we copy
;; current-posn and current-index so that we can trash them while processing
;; choosers and back-patches.
(final-posn 0 :type posn)
(final-index 0 :type index)
;;
;; *** State used by the scheduler during instruction queueing.
;;
List of 's . These are accumulated between instructions .
(postits nil :type list)
;;
;; ``Number'' for last instruction queued. Used only to supply insts
;; with unique sset-element-number's.
(inst-number 0 :type index)
;;
;; Simple-Vectors mapping locations to the instruction that reads them and
;; instructions that write them.
(readers (make-array (assem-params-max-locations
(c:backend-assembler-params c:*backend*))
:initial-element nil)
:type simple-vector)
(writers (make-array (assem-params-max-locations
(c:backend-assembler-params c:*backend*))
:initial-element nil)
:type simple-vector)
;;
The number of additional cycles before the next control transfer , or NIL
;; if a control transfer hasn't been queued. When a delayed branch is
;; queued, this slot is set to the delay count.
(branch-countdown nil :type (or null (and fixnum unsigned-byte)))
;;
* * * These two slots are used by both the queuing noise and the
;; scheduling noise.
;;
;; All the instructions that are pending and don't have any unresolved
;; dependents. We don't list branches here even if they would otherwise
;; qualify. They are listed above.
;;
(emittable-insts-sset (make-sset) :type sset)
;;
;; List of queued branches. We handle these specially, because they have to
be emitted at a specific place ( e.g. one slot before the end of the
;; block).
(queued-branches nil :type list)
;;
;; *** State used by the scheduler during instruction scheduling.
;;
;; The instructions who would have had a read dependent removed if it were
;; not for a delay slot. This is a list of lists. Each element in the
;; top level list corresponds to yet another cycle of delay. Each element
in the second level lists is a dotted pair , holding the dependency
;; instruction and the dependent to remove.
(delayed nil :type list)
;;
;; The emittable insts again, except this time as a list sorted by depth.
(emittable-insts-queue nil :type list)
;;
;; Whether or not to collect dynamic statistics. This is just the same as
;; *collect-dynamic-statistics* but is faster to reference.
(collect-dynamic-statistics nil))
(c::defprinter segment name)
;;;; Structures/types used by the scheduler.
(c:def-boolean-attribute instruction
;;
;; This attribute is set if the scheduler can freely flush this instruction
if it thinks it is not needed . Examples are NOP and instructions that
;; have no side effect not described by the writes.
flushable
;;
;; This attribute is set when an instruction can cause a control transfer.
;; For test instructions, the delay is used to determine how many
;; instructions follow the branch.
branch
;;
;; This attribute indicates that this ``instruction'' can be variable length,
;; and therefore better never be used in a branch delay slot.
variable-length)
(defstruct (instruction
(:include sset-element)
(:print-function %print-instruction)
(:conc-name inst-)
(:constructor make-instruction (number emitter attributes delay)))
;;
;; The function to envoke to actually emit this instruction. Gets called
with the segment as its one argument .
(emitter (required-argument) :type (or null function))
;;
;; The attributes of this instruction.
(attributes (instruction-attributes) :type c:attributes)
;;
;; Number of instructions or cycles of delay before additional instructions
;; can read our writes.
(delay 0 :type (and fixnum unsigned-byte))
;;
;; The maximum number of instructions in the longest dependency chain from
this instruction to one of the independent instructions . This is used
as a heuristic at to which instructions should be scheduled first .
(depth nil :type (or null (and fixnum unsigned-byte)))
;;
* * When trying remember which of the next four is which , note that the
` ` read '' or ` ` write '' always referes to the dependent ( second )
;; instruction.
;;
;; Instructions whos writes this instruction tries to read.
(read-dependencies (make-sset) :type sset)
;;
;; Instructions whos writes or reads are overwritten by this instruction.
(write-dependencies (make-sset) :type sset)
;;
;; Instructions who write what we read or write.
(write-dependents (make-sset) :type sset)
;;
;; Instructions who read what we write.
(read-dependents (make-sset) :type sset))
;;;
#+debug (defvar *inst-ids* (make-hash-table :test #'eq))
#+debug (defvar *next-inst-id* 0)
(defun %print-instruction (inst stream depth)
(declare (ignore depth))
(print-unreadable-object (inst stream :type t :identity t)
#+debug
(princ (or (gethash inst *inst-ids*)
(setf (gethash inst *inst-ids*)
(incf *next-inst-id*)))
stream)
(format stream #+debug " emitter=~S" #-debug "emitter=~S"
(let ((emitter (inst-emitter inst)))
(if emitter
(multiple-value-bind
(lambda lexenv-p name)
(function-lambda-expression emitter)
(declare (ignore lambda lexenv-p))
name)
'<flushed>)))
(when (inst-depth inst)
(format stream ", depth=~D" (inst-depth inst)))))
#+debug
(defun reset-inst-ids ()
(clrhash *inst-ids*)
(setf *next-inst-id* 0))
;;;; The scheduler itself.
;;; WITHOUT-SCHEDULING -- interface.
;;;
(defmacro without-scheduling ((&optional (segment '*current-segment*))
&body body)
"Execute BODY (as a progn) without scheduling any of the instructions
generated inside it. DO NOT throw or return-from out of it."
(let ((var (gensym))
(seg (gensym)))
`(let* ((,seg ,segment)
(,var (segment-run-scheduler ,seg)))
(when ,var
(schedule-pending-instructions ,seg)
(setf (segment-run-scheduler ,seg) nil))
,@body
(setf (segment-run-scheduler ,seg) ,var))))
(defmacro note-dependencies ((segment inst) &body body)
(ext:once-only ((segment segment) (inst inst))
`(macrolet ((reads (loc) `(note-read-dependency ,',segment ,',inst ,loc))
(writes (loc &rest keys)
`(note-write-dependency ,',segment ,',inst ,loc ,@keys)))
,@body)))
(defun note-read-dependency (segment inst read)
(multiple-value-bind (loc-num size)
(c:location-number read)
#+debug (format *trace-output* "~&~S reads ~S[~D for ~D]~%"
inst read loc-num size)
(when loc-num
Iterate over all the locations for this TN .
(do ((index loc-num (1+ index))
(end-loc (+ loc-num (or size 1))))
((>= index end-loc))
(declare (type (mod 2048) index end-loc))
(let ((writers (svref (segment-writers segment) index)))
(when writers
;; The inst that wrote the value we want to read must have
;; completed.
(let ((writer (car writers)))
(sset-adjoin writer (inst-read-dependencies inst))
(sset-adjoin inst (inst-read-dependents writer))
(sset-delete writer (segment-emittable-insts-sset segment))
;; And it must have been completed *after* all other
;; writes to that location. Actually, that isn't quite
;; true. Each of the earlier writes could be done
;; either before this last write, or after the read, but
;; we have no way of representing that.
(dolist (other-writer (cdr writers))
(sset-adjoin other-writer (inst-write-dependencies writer))
(sset-adjoin writer (inst-write-dependents other-writer))
(sset-delete other-writer
(segment-emittable-insts-sset segment))))
;; And we don't need to remember about earlier writes any
;; more. Shortening the writers list means that we won't
;; bother generating as many explicit arcs in the graph.
(setf (cdr writers) nil)))
(push inst (svref (segment-readers segment) index)))))
(ext:undefined-value))
(defun note-write-dependency (segment inst write &key partially)
(multiple-value-bind (loc-num size)
(c:location-number write)
#+debug (format *trace-output* "~&~S writes ~S[~D for ~D]~%"
inst write loc-num size)
(when loc-num
Iterate over all the locations for this TN .
(do ((index loc-num (1+ index))
(end-loc (+ loc-num (or size 1))))
((>= index end-loc))
(declare (type (mod 2048) index end-loc))
;; All previous reads of this location must have completed.
(dolist (prev-inst (svref (segment-readers segment) index))
(unless (eq prev-inst inst)
(sset-adjoin prev-inst (inst-write-dependencies inst))
(sset-adjoin inst (inst-write-dependents prev-inst))
(sset-delete prev-inst (segment-emittable-insts-sset segment))))
(when partially
;; All previous writes to the location must have completed.
(dolist (prev-inst (svref (segment-writers segment) index))
(sset-adjoin prev-inst (inst-write-dependencies inst))
(sset-adjoin inst (inst-write-dependents prev-inst))
(sset-delete prev-inst (segment-emittable-insts-sset segment)))
;; And we can forget about remembering them, because
;; depending on us is as good as depending on them.
(setf (svref (segment-writers segment) index) nil))
(push inst (svref (segment-writers segment) index)))))
(ext:undefined-value))
;;; QUEUE-INST -- internal.
;;;
;;; This routine is called by FIX? due to uses of the INST macro when the scheduler
;;; is turned on. The change to the dependency graph has already been
;;; computed, so we just have to check to see if the basic block is terminated.
;;;
(defun queue-inst (segment inst)
#+debug (format *trace-output* "~&Queuing ~S~%" inst)
#+debug
(format *trace-output* " reads ~S~% writes ~S~%"
(ext:collect ((reads))
(do-elements (read (inst-read-dependencies inst))
(reads read))
(reads))
(ext:collect ((writes))
(do-elements (write (inst-write-dependencies inst))
(writes write))
(writes)))
(assert (segment-run-scheduler segment))
(let ((countdown (segment-branch-countdown segment)))
(when countdown
(decf countdown)
(assert (not (instruction-attributep (inst-attributes inst)
variable-length))))
(cond ((instruction-attributep (inst-attributes inst) branch)
(unless countdown
(setf countdown (inst-delay inst)))
(push (cons countdown inst)
(segment-queued-branches segment)))
(t
(sset-adjoin inst (segment-emittable-insts-sset segment))))
(when countdown
(setf (segment-branch-countdown segment) countdown)
(when (zerop countdown)
(schedule-pending-instructions segment))))
(ext:undefined-value))
;;; SCHEDULE-PENDING-INSTRUCTIONS -- internal.
;;;
;;; Emit all the pending instructions, and reset any state. This is called
;;; whenever we hit a label (i.e. an entry point of some kind) and when the
;;; user turns the scheduler off (otherwise, the queued instructions would
;;; sit there until the scheduler was turned back on, and be emitted in the
;;; wrong place).
;;;
(defun schedule-pending-instructions (segment)
(assert (segment-run-scheduler segment))
;;
;; Quick blow-out if nothing to do.
(when (and (sset-empty (segment-emittable-insts-sset segment))
(null (segment-queued-branches segment)))
(return-from schedule-pending-instructions
(ext:undefined-value)))
;;
#+debug
(format *trace-output* "~&Scheduling pending instructions...~%")
;;
;; Note that any values live at the end of the block have to be computed
;; last.
(let ((emittable-insts (segment-emittable-insts-sset segment))
(writers (segment-writers segment)))
(dotimes (index (length writers))
(let* ((writer (svref writers index))
(inst (car writer))
(overwritten (cdr writer)))
(when writer
(when overwritten
(let ((write-dependencies (inst-write-dependencies inst)))
(dolist (other-inst overwritten)
(sset-adjoin inst (inst-write-dependents other-inst))
(sset-adjoin other-inst write-dependencies)
(sset-delete other-inst emittable-insts))))
;; If the value is live at the end of the block, we can't flush it.
(setf (instruction-attributep (inst-attributes inst) flushable)
nil)))))
;;
;; Grovel through the entire graph in the forward direction finding all
;; the leaf instructions. FIX leaf? 0 delay?
(labels ((grovel-inst (inst)
(let ((max 0))
(do-elements (dep (inst-write-dependencies inst))
(let ((dep-depth (or (inst-depth dep) (grovel-inst dep))))
(when (> dep-depth max)
(setf max dep-depth))))
(do-elements (dep (inst-read-dependencies inst))
(let ((dep-depth
(+ (or (inst-depth dep) (grovel-inst dep))
(inst-delay dep))))
(when (> dep-depth max)
(setf max dep-depth))))
(cond ((and (sset-empty (inst-read-dependents inst))
(instruction-attributep (inst-attributes inst)
flushable))
#+debug
(format *trace-output* "Flushing ~S~%" inst)
(setf (inst-emitter inst) nil)
(setf (inst-depth inst) max))
(t
(setf (inst-depth inst) max))))))
(let ((emittable-insts nil)
(delayed nil))
(do-elements (inst (segment-emittable-insts-sset segment))
(grovel-inst inst)
(if (zerop (inst-delay inst))
(push inst emittable-insts)
(setf delayed
(add-to-nth-list delayed inst (1- (inst-delay inst))))))
(setf (segment-emittable-insts-queue segment)
(sort emittable-insts #'> :key #'inst-depth))
(setf (segment-delayed segment) delayed))
(dolist (branch (segment-queued-branches segment))
(grovel-inst (cdr branch))))
#+debug
(format *trace-output* "Queued branches: ~S~%"
(segment-queued-branches segment))
#+debug
(format *trace-output* "Initially emittable: ~S~%"
(segment-emittable-insts-queue segment))
#+debug
(format *trace-output* "Initially delayed: ~S~%"
(segment-delayed segment))
;;
;; Accumulate the results in reverse order. Well, actually, this list will
;; be in forward order, because we are generating the reverse order in
;; reverse.
(let ((results nil))
;;
;; Schedule all the branches in their exact locations.
(let ((insts-from-end (segment-branch-countdown segment)))
(dolist (branch (segment-queued-branches segment))
(let ((inst (cdr branch)))
(dotimes (i (- (car branch) insts-from-end))
;; Each time through this loop we need to emit another instruction.
First , we check to see if there is any instruction that must
;; be emitted before (i.e. must come after) the branch inst. If
so , emit it . Otherwise , just pick one of the emittable insts .
;; If there is nothing to do, then emit a nop.
# # # Note : despite the fact that this is a loop , it really wo n't
work for repetitions other then zero and one . For example , if
the branch has two dependents and one of them dpends on the
;; other, then the stuff that grabs a dependent could easily
;; grab the wrong one. But I don't feel like fixing this because
;; it doesn't matter for any of the architectures we are using
;; or plan on using.
(flet ((maybe-schedule-dependent (dependents)
(do-elements (inst dependents)
;; If do-elements enters the body, then there is a
;; dependent. Emit it.
(note-resolved-dependencies segment inst)
;; Remove it from the emittable insts.
(setf (segment-emittable-insts-queue segment)
(delete inst
(segment-emittable-insts-queue segment)
:test #'eq))
;; And if it was delayed, removed it from the delayed
;; list. This can happen if there is a load in a
;; branch delay slot.
(block scan-delayed
(do ((delayed (segment-delayed segment)
(cdr delayed)))
((null delayed))
(do ((prev nil cons)
(cons (car delayed) (cdr cons)))
((null cons))
(when (eq (car cons) inst)
(if prev
(setf (cdr prev) (cdr cons))
(setf (car delayed) (cdr cons)))
(return-from scan-delayed nil)))))
;; And return it.
(return inst))))
(let ((fill (or (maybe-schedule-dependent
(inst-read-dependents inst))
(maybe-schedule-dependent
(inst-write-dependents inst))
(schedule-one-inst segment t)
:nop)))
#+debug
(format *trace-output* "Filling branch delay slot with ~S~%"
fill)
(push fill results)))
(advance-one-inst segment)
(incf insts-from-end))
(note-resolved-dependencies segment inst)
(push inst results)
#+debug
(format *trace-output* "Emitting ~S~%" inst)
(advance-one-inst segment))))
;;
;; Keep scheduling stuff until we run out.
(loop
(let ((inst (schedule-one-inst segment nil)))
FIX ( push ( or ( s - o - i .. ) ( return ) ) results ) ? ( while ... )
(push inst results)
(advance-one-inst segment)))
;;
;; Now call the emitters, but turn the scheduler off for the duration.
(setf (segment-run-scheduler segment) nil)
(dolist (inst results)
(if (eq inst :nop)
(c:emit-nop segment)
(funcall (inst-emitter inst) segment)))
(setf (segment-run-scheduler segment) t))
;;
;; Clear out any residue left over. FIX "residue" implies "left over"
(setf (segment-inst-number segment) 0)
(setf (segment-queued-branches segment) nil)
(setf (segment-branch-countdown segment) nil)
(setf (segment-emittable-insts-sset segment) (make-sset))
(fill (segment-readers segment) nil)
(fill (segment-writers segment) nil)
;;
(ext:undefined-value))
ADD - TO - NTH - LIST -- internal .
;;;
;;; Utility for maintaining the segment-delayed list. We cdr down list
;;; n times (extending it if necessary) and then push thing on into the car
;;; of that cons cell.
;;;
(defun add-to-nth-list (list thing n)
(do ((cell (or list (setf list (list nil)))
(or (cdr cell) (setf (cdr cell) (list nil))))
(i n (1- i)))
((zerop i)
(push thing (car cell))
list)))
;;; SCHEDULE-ONE-INST -- internal.
;;;
;;; Find the next instruction to schedule and return it after updating
;;; any dependency information. If we can't do anything useful right
now , but there is more work to be done , return : NOP to indicate that
a nop must be emitted . If we are all done , return NIL .
;;;
(defun schedule-one-inst (segment delay-slot-p)
(do ((prev nil remaining)
(remaining (segment-emittable-insts-queue segment) (cdr remaining)))
((null remaining))
(let ((inst (car remaining)))
(unless (and delay-slot-p
(instruction-attributep (inst-attributes inst)
variable-length))
;; We've got us a live one here. Go for it.
#+debug
(format *Trace-output* "Emitting ~S~%" inst)
;; Delete it from the list of insts.
(if prev
(setf (cdr prev) (cdr remaining))
(setf (segment-emittable-insts-queue segment)
(cdr remaining)))
;; Note that this inst has been emitted.
(note-resolved-dependencies segment inst)
;; And return.
(return-from schedule-one-inst
;; Are we wanting to flush this instruction?
(if (inst-emitter inst)
;; Nope, it's still a go. So return it.
inst
;; Yes, so pick a new one. We have to start over,
;; because note-resolved-dependencies might have
;; changed the emittable-insts-queue.
(schedule-one-inst segment delay-slot-p))))))
;; Nothing to do, so make something up.
(cond ((segment-delayed segment)
;; No emittable instructions, but we have more work to do. Emit
a NOP to fill in a delay slot .
#+debug (format *trace-output* "Emitting a NOP.~%")
:nop)
(t
;; All done.
nil)))
;;; NOTE-RESOLVED-DEPENDENCIES -- internal.
;;;
;;; This function is called whenever an instruction has been scheduled, and we
;;; want to know what possibilities that opens up. So look at all the
;;; instructions that this one depends on, and remove this instruction from
;;; their dependents list. If we were the last dependent, then that
;;; dependency can be emitted now.
;;;
(defun note-resolved-dependencies (segment inst)
(assert (sset-empty (inst-read-dependents inst)))
(assert (sset-empty (inst-write-dependents inst)))
(do-elements (dep (inst-write-dependencies inst))
;; These are the instructions who have to be completed before our
;; write fires. Doesn't matter how far before, just before.
(let ((dependents (inst-write-dependents dep)))
(sset-delete inst dependents)
(when (and (sset-empty dependents)
(sset-empty (inst-read-dependents dep)))
(insert-emittable-inst segment dep))))
(do-elements (dep (inst-read-dependencies inst))
;; These are the instructions who write values we read. If there
;; is no delay, then just remove us from the dependent list.
;; Otherwise, record the fact that in n cycles, we should be
;; removed.
(if (zerop (inst-delay dep))
(let ((dependents (inst-read-dependents dep)))
(sset-delete inst dependents)
(when (and (sset-empty dependents)
(sset-empty (inst-write-dependents dep)))
(insert-emittable-inst segment dep)))
(setf (segment-delayed segment)
(add-to-nth-list (segment-delayed segment)
(cons dep inst)
(inst-delay dep)))))
(ext:undefined-value))
;;; ADVANCE-ONE-INST -- internal.
;;;
;;; Process the next entry in segment-delayed. This is called whenever anyone
;;; emits an instruction.
;;;
(defun advance-one-inst (segment)
(let ((delayed-stuff (pop (segment-delayed segment))))
(dolist (stuff delayed-stuff)
(if (consp stuff)
(let* ((dependency (car stuff))
(dependent (cdr stuff))
(dependents (inst-read-dependents dependency)))
(sset-delete dependent dependents)
(when (and (sset-empty dependents)
(sset-empty (inst-write-dependents dependency)))
(insert-emittable-inst segment dependency)))
(insert-emittable-inst segment stuff)))))
;;; INSERT-EMITTABLE-INST -- internal.
;;;
;;; Note that inst is emittable by sticking it in the SEGMENT-EMITTABLE-INSTS-
;;; QUEUE list. We keep the emittable-insts sorted with the largest ``depths''
;;; first. Except that if INST is a branch, don't bother. It will be handled
;;; correctly by the branch emitting code in SCHEDULE-PENDING-INSTRUCTIONS.
;;;
(defun insert-emittable-inst (segment inst)
(unless (instruction-attributep (inst-attributes inst) branch)
#+debug
(format *Trace-output* "Now emittable: ~S~%" inst)
(do ((my-depth (inst-depth inst))
(remaining (segment-emittable-insts-queue segment) (cdr remaining))
(prev nil remaining))
((or (null remaining) (> my-depth (inst-depth (car remaining))))
(if prev
(setf (cdr prev) (cons inst remaining))
(setf (segment-emittable-insts-queue segment)
(cons inst remaining))))))
(ext:undefined-value))
;;;; Structure used during output emission.
ANNOTATION -- Common supertype for all the different kinds of annotations .
;;;
(defstruct (annotation
(:constructor nil))
;;
;; Where in the raw output stream was this annotation emitted.
(index 0 :type index)
;;
;; What position does that correspond to.
(posn nil :type (or index null)))
;;; LABEL -- Doesn't need any additional information beyond what is in the
;;; annotation structure.
;;;
(defstruct (label
(:include annotation)
(:constructor gen-label ())
(:print-function %print-label))
)
;;;
(defun %print-label (label stream depth)
(declare (ignore depth))
(if (or *print-escape* *print-readably*)
(print-unreadable-object (label stream :type t)
(prin1 (c:label-id label) stream))
(format stream "L~D" (c:label-id label))))
;;; ALIGNMENT-NOTE -- A constraint on how the output stream must be aligned.
;;;
(defstruct (alignment-note
(:include annotation)
(:conc-name alignment-)
(:predicate alignment-p)
(:constructor make-alignment (bits size fill-byte)))
;;
The minimum number of low - order bits that must be zero .
(bits 0 :type alignment)
;;
;; The amount of filler we are assuming this alignment op will take.
(size 0 :type (integer 0 #.(1- (ash 1 max-alignment))))
;;
;; The byte used as filling.
(fill-byte 0 :type (or assembly-unit (signed-byte #.assembly-unit-bits))))
;;; BACK-PATCH -- a reference to someplace that needs to be back-patched when
;;; we actually know what label positions, etc. are.
;;;
(defstruct (back-patch
(:include annotation)
(:constructor make-back-patch (size function)))
;;
;; The area effected by this back-patch.
(size 0 :type index)
;;
;; The function to use to generate the real data
(function nil :type function))
CHOOSER -- Similar to a back - patch , but also an indication that the amount
;;; of stuff output depends on label-positions, etc. Back-patches can't change
;;; their mind about how much stuff to emit, but choosers can.
;;;
(defstruct (chooser
(:include annotation)
(:constructor make-chooser
(size alignment maybe-shrink worst-case-fun)))
;;
;; The worst case size for this chooser. There is this much space allocated
;; in the output buffer.
(size 0 :type index)
;;
;; The worst case alignment this chooser is guarenteed to preserve.
(alignment 0 :type alignment)
;;
;; The function to call to determine of we can use a shorter sequence. It
;; returns NIL if nothing shorter can be used, or emits that sequence and
;; returns T.
(maybe-shrink nil :type function)
;;
;; The function to call to generate the worst case sequence. This is used
;; when nothing else can be condensed.
(worst-case-fun nil :type function))
FILLER -- Used internally when we figure out a chooser or alignment does n't
;;; really need as much space as we initially gave it.
;;;
(defstruct (filler
(:include annotation)
(:constructor make-filler (bytes)))
;;
;; The number of bytes of filler here.
(bytes 0 :type index))
;;;; Output buffer utility functions.
;;; A list of all the output-blocks we have allocated but aren't using.
;;; We free-list them because allocation more is slow and the garbage collector
;;; doesn't know about them, so it can't be slowed down by use keep ahold of
;;; them.
;;;
(defvar *available-output-blocks* nil)
;;; A list of all the output-blocks we have ever allocated. We don't really
;;; need to keep tract of this if RELEASE-OUTPUT-BLOCK were always called,
;;; but...
;;;
(defvar *all-output-blocks* nil)
;;; NEW-OUTPUT-BLOCK -- internal.
;;;
;;; Return a new output block, allocating one if necessary.
;;;
(defun new-output-block ()
(if *available-output-blocks*
(pop *available-output-blocks*)
(let ((block (system:allocate-system-memory output-block-size)))
(push block *all-output-blocks*)
block)))
;;; RELEASE-OUTPUT-BLOCK -- internal.
;;;
;;; Return block to the list of avaiable blocks.
;;;
(defun release-output-block (block)
(push block *available-output-blocks*))
;;; FORGET-OUTPUT-BLOCKS -- internal.
;;;
;;; We call this whenever a core starts up, because system-memory isn't
;;; saves with the core. If we didn't, we would find our hands full of
;;; bogus SAPs, which would make all sorts of things unhappy.
;;;
(defun forget-output-blocks ()
(setf *all-output-blocks* nil)
(setf *available-output-blocks* nil))
;;;
(pushnew 'forget-output-blocks ext:*after-save-initializations*)
;;;; Output functions.
;;; FIND-NEW-FILL-POINTER -- internal.
;;;
Find us a new fill pointer for the current index in segment . Allocate
;;; any additional storage as necessary.
;;;
(defun find-new-fill-pointer (segment)
(declare (type segment segment))
(let* ((index (segment-current-index segment))
(blocks (segment-output-blocks segment))
(num-blocks (length blocks)))
(multiple-value-bind
(block-num offset)
(truncate index output-block-size)
(when (>= block-num num-blocks)
(setf blocks
(adjust-array blocks (+ block-num 3) :initial-element nil))
(setf (segment-output-blocks segment) blocks))
(let ((block (or (aref blocks block-num)
(setf (aref blocks block-num) (new-output-block)))))
(setf (segment-block-end segment)
(system:sap+ block output-block-size))
(setf (segment-fill-pointer segment) (system:sap+ block offset))))))
;;; EMIT-BYTE -- interface.
;;;
Emit the supplied BYTE to SEGMENT , growing it if necessary .
;;;
(declaim (inline emit-byte))
(defun emit-byte (segment byte)
"Emit BYTE to SEGMENT."
(declare (type segment segment)
(type (or assembly-unit (signed-byte #.assembly-unit-bits)) byte))
(let* ((orig-ptr (segment-fill-pointer segment))
(ptr (if (system:sap= orig-ptr (segment-block-end segment))
(find-new-fill-pointer segment)
orig-ptr)))
(setf (system:sap-ref-8 ptr 0) (ldb (byte assembly-unit-bits 0) byte))
(setf (segment-fill-pointer segment) (system:sap+ ptr 1)))
(incf (segment-current-posn segment))
(incf (segment-current-index segment))
(ext:undefined-value))
;;; EMIT-SKIP -- interface.
;;;
(defun emit-skip (segment amount &optional (fill-byte 0))
"Output AMOUNT zeros (in bytes) to SEGMENT."
(declare (type segment segment)
(type index amount))
(dotimes (i amount)
(emit-byte segment fill-byte))
(ext:undefined-value))
;;; EMIT-ANNOTATION -- internal.
;;;
;;; Used to handle the common parts of annotation emission. We just
;;; assign the posn and index of the note and tack it on to the end
;;; of the segment's annotations list.
;;;
(defun emit-annotation (segment note)
(declare (type segment segment)
(type annotation note))
(when (annotation-posn note)
(error "Attempt to emit ~S for the second time."))
(setf (annotation-posn note) (segment-current-posn segment))
(setf (annotation-index note) (segment-current-index segment))
(let ((last (segment-last-annotation segment))
(new (list note)))
(setf (segment-last-annotation segment)
(if last
(setf (cdr last) new)
(setf (segment-annotations segment) new))))
(ext:undefined-value))
;;; EMIT-BACK-PATCH -- interface.
;;;
(defun emit-back-patch (segment size function)
"Note that the instruction stream has to be back-patched when label positions
are finally known. SIZE bytes are reserved in SEGMENT, and function will
be called with two arguments: the segment and the position. The function
should look at the position and the position of any labels it wants to
and emit the correct sequence. (And it better be the same size as SIZE).
SIZE can be zero, which is useful if you just want to find out where things
ended up."
(emit-annotation segment (make-back-patch size function))
(emit-skip segment size))
;;; EMIT-CHOOSER -- interface.
;;;
(defun emit-chooser (segment size alignment maybe-shrink worst-case-fun)
"Note that the instruction stream here depends on the actual positions of
various labels, so can't be output until label positions are known. Space
is made in SEGMENT for at least SIZE bytes. When all output has been
generated, the MAYBE-SHRINK functions for all choosers are called with
three arguments: the segment, the position, and a magic value. The MAYBE-
SHRINK decides if it can use a shorter sequence, and if so, emits that
sequence to the segment and returns T. If it can't do better than the
worst case, it should return NIL (without emitting anything). When calling
LABEL-POSITION, it should pass it the position and the magic-value it was
passed so that LABEL-POSITION can return the correct result. If the chooser
never decides to use a shorter sequence, the WORST-CASE-FUN will be called,
just like a BACK-PATCH. (See EMIT-BACK-PATCH.)"
(declare (type segment segment) (type index size) (type alignment alignment)
(type function maybe-shrink worst-case-fun))
(let ((chooser (make-chooser size alignment maybe-shrink worst-case-fun)))
(emit-annotation segment chooser)
(emit-skip segment size)
(adjust-alignment-after-chooser segment chooser)))
;;; ADJUST-ALIGNMENT-AFTER-CHOOSER -- internal.
;;;
Called in EMIT - CHOOSER and COMPRESS - SEGMENT in order to recompute the
;;; current alignment information in light of this chooser. If the alignment
;;; guarenteed byte the chooser is less then the segments current alignment,
;;; we have to adjust the segments notion of the current alignment.
;;;
;;; The hard part is recomputing the sync posn, because it's not just the
choosers posn . Consider a chooser that emits either one or three words .
It preserves 8 - byte ( 3 bit ) alignments , because the difference between
the two choices is 8 bytes .
;;;
(defun adjust-alignment-after-chooser (segment chooser)
(declare (type segment segment) (type chooser chooser))
(let ((alignment (chooser-alignment chooser))
(seg-alignment (segment-alignment segment)))
(when (< alignment seg-alignment)
;; The chooser might change the alignment of the output. So we have
;; to figure out what the worst case alignment could be.
(setf (segment-alignment segment) alignment)
(let* ((posn (chooser-posn chooser))
(sync-posn (segment-sync-posn segment))
(offset (- posn sync-posn))
(delta (logand offset (1- (ash 1 alignment)))))
(setf (segment-sync-posn segment) (- posn delta)))))
(ext:undefined-value))
;;; EMIT-FILLER -- internal.
;;;
;;; Used internally whenever a chooser or alignment decides it doesn't need
;;; as much space as it originally though.
;;;
(defun emit-filler (segment bytes)
(let ((last (segment-last-annotation segment)))
(cond ((and last (filler-p (car last)))
(incf (filler-bytes (car last)) bytes))
(t
(emit-annotation segment (make-filler bytes)))))
(incf (segment-current-index segment) bytes)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(ext:undefined-value))
;;; %EMIT-LABEL -- internal.
;;;
;;; EMIT-LABEL (the interface) basically just expands into this, supplying
the segment and vop .
;;;
(defun %emit-label (segment vop label)
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(let ((postits (segment-postits segment)))
(setf (segment-postits segment) ())
(dolist (postit postits)
(emit-back-patch segment 0 postit)))
(let ((hook (segment-inst-hook segment)))
(when hook
(funcall hook segment vop :label label)))
(emit-annotation segment label))
;;; EMIT-ALIGNMENT -- internal.
;;;
;;; Called by the ALIGN macro to emit an alignment note. We check to see
;;; if we can guarentee the alignment restriction by just outputing a fixed
;;; number of bytes. If so, we do so. Otherwise, we create and emit
;;; an alignment note.
;;;
(defun emit-alignment (segment vop bits &optional (fill-byte 0))
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(let ((hook (segment-inst-hook segment)))
(when hook
(funcall hook segment vop :align bits)))
(let ((alignment (segment-alignment segment))
(offset (- (segment-current-posn segment)
(segment-sync-posn segment))))
(cond ((> bits alignment)
We need more bits of alignment . First emit enough noise
;; to get back in sync with alignment, and then emit an alignment
;; note to cover the rest.
(let ((slop (logand offset (1- (ash 1 alignment)))))
(unless (zerop slop)
(emit-skip segment (- (ash 1 alignment) slop) fill-byte)))
(let ((size (logand (1- (ash 1 bits))
(lognot (1- (ash 1 alignment))))))
(assert (> size 0))
(emit-annotation segment (make-alignment bits size fill-byte))
(emit-skip segment size fill-byte))
(setf (segment-alignment segment) bits)
(setf (segment-sync-posn segment) (segment-current-posn segment)))
(t
;; The last alignment was more restrictive then this one.
;; So we can just figure out how much noise to emit assuming
;; the last alignment was met.
(let* ((mask (1- (ash 1 bits)))
(new-offset (logand (+ offset mask) (lognot mask))))
(emit-skip segment (- new-offset offset) fill-byte))
;; But we emit an alignment with size=0 so we can verify
;; that everything works.
(emit-annotation segment (make-alignment bits 0 fill-byte)))))
(ext:undefined-value))
;;; FIND-ALIGNMENT -- internal.
;;;
;;; Used to find how ``aligned'' different offsets are. Returns the number
;;; of low-order 0 bits, up to MAX-ALIGNMENT.
;;;
(defun find-alignment (offset)
(dotimes (i max-alignment max-alignment)
(when (logbitp i offset)
(return i))))
;;; EMIT-POSTIT -- Internal.
;;;
;;; Emit a postit. The function will be called as a back-patch with the
position the following instruction is finally emitted . do not
;;; interfere at all with scheduling.
;;;
(defun %emit-postit (segment function)
(push function (segment-postits segment))
(ext:undefined-value))
;;;; Output compression/position assignment.
COMPRESS - OUTPUT -- internal .
;;;
;;; Grovel though all the annotations looking for choosers. When we find
;;; a chooser, invoke the maybe-shrink function. If it returns T, it output
;;; some other byte sequence.
;;;
(defun compress-output (segment)
it better not take more than one or two passes .
(let ((delta 0))
(setf (segment-alignment segment) max-alignment)
(setf (segment-sync-posn segment) 0)
(do* ((prev nil)
(remaining (segment-annotations segment) next)
(next (cdr remaining) (cdr remaining)))
((null remaining))
(let* ((note (car remaining))
(posn (annotation-posn note)))
(unless (zerop delta)
(decf posn delta)
(setf (annotation-posn note) posn))
(cond
((chooser-p note)
(setf (segment-current-index segment) (chooser-index note))
(setf (segment-current-posn segment) posn)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(setf (segment-last-annotation segment) prev)
(cond
((funcall (chooser-maybe-shrink note) segment posn delta)
;; It emitted some replacement.
(let ((new-size (- (segment-current-index segment)
(chooser-index note)))
(old-size (chooser-size note)))
(when (> new-size old-size)
(error "~S emitted ~D bytes, but claimed it's max was ~D"
note new-size old-size))
(let ((additional-delta (- old-size new-size)))
(when (< (find-alignment additional-delta)
(chooser-alignment note))
(error "~S shrunk by ~D bytes, but claimed that it ~
preserve ~D bits of alignment."
note additional-delta (chooser-alignment note)))
(incf delta additional-delta)
(emit-filler segment additional-delta))
(setf prev (segment-last-annotation segment))
(if prev
(setf (cdr prev) (cdr remaining))
(setf (segment-annotations segment)
(cdr remaining)))))
(t
;; The chooser passed on shrinking. Make sure it didn't emit
;; anything.
(unless (= (segment-current-index segment) (chooser-index note))
(error "Chooser ~S passed, but not before emitting ~D bytes."
note
(- (segment-current-index segment)
(chooser-index note))))
;; Act like we just emitted this chooser.
(let ((size (chooser-size note)))
(incf (segment-current-index segment) size)
(incf (segment-current-posn segment) size))
;; Adjust the alignment accordingly.
(adjust-alignment-after-chooser segment note)
;; And keep this chooser for next time around.
(setf prev remaining))))
((alignment-p note)
(unless (zerop (alignment-size note))
;; Re-emit the alignment, letting it collapse if we know anything
;; more about the alignment guarantees of the segment.
(let ((index (alignment-index note)))
(setf (segment-current-index segment) index)
(setf (segment-current-posn segment) posn)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(setf (segment-last-annotation segment) prev)
(emit-alignment segment nil (alignment-bits note)
(alignment-fill-byte note))
(let* ((new-index (segment-current-index segment))
(size (- new-index index))
(old-size (alignment-size note))
(additional-delta (- old-size size)))
(when (minusp additional-delta)
(error "Alignment ~S needs more space now? It was ~D, ~
and is ~D now."
note old-size size))
(when (plusp additional-delta)
(emit-filler segment additional-delta)
(incf delta additional-delta)))
(setf prev (segment-last-annotation segment))
(if prev
(setf (cdr prev) (cdr remaining))
(setf (segment-annotations segment)
(cdr remaining))))))
(t
(setf prev remaining)))))
(when (zerop delta)
(return))
(decf (segment-final-posn segment) delta)))
(ext:undefined-value))
;;; FINALIZE-POSITIONS -- internal.
;;;
;;; We have run all the choosers we can, so now we have to figure out exactly
;;; how much space each alignment note needs.
;;;
(defun finalize-positions (segment)
(let ((delta 0))
(do* ((prev nil)
(remaining (segment-annotations segment) next)
(next (cdr remaining) (cdr remaining)))
((null remaining))
(let* ((note (car remaining))
(posn (- (annotation-posn note) delta)))
(cond
((alignment-p note)
(let* ((bits (alignment-bits note))
(mask (1- (ash 1 bits)))
(new-posn (logand (+ posn mask) (lognot mask)))
(size (- new-posn posn))
(old-size (alignment-size note))
(additional-delta (- old-size size)))
(assert (<= 0 size old-size))
(unless (zerop additional-delta)
(setf (segment-last-annotation segment) prev)
(incf delta additional-delta)
(setf (segment-current-index segment) (alignment-index note))
(setf (segment-current-posn segment) posn)
(emit-filler segment additional-delta)
(setf prev (segment-last-annotation segment)))
(if prev
(setf (cdr prev) next)
(setf (segment-annotations segment) next))))
(t
(setf (annotation-posn note) posn)
(setf prev remaining)
(setf next (cdr remaining))))))
(unless (zerop delta)
(decf (segment-final-posn segment) delta)))
(ext:undefined-value))
;;; PROCESS-BACK-PATCHES -- internal.
;;;
;;; Grovel over segment, filling in any backpatches. If any choosers are
;;; left over, we need to emit their worst case variant.
;;;
(defun process-back-patches (segment)
(do* ((prev nil)
(remaining (segment-annotations segment) next)
(next (cdr remaining) (cdr remaining)))
((null remaining))
(let ((note (car remaining)))
(flet ((fill-in (function old-size)
(let ((index (annotation-index note))
(posn (annotation-posn note)))
(setf (segment-current-index segment) index)
(setf (segment-current-posn segment) posn)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(setf (segment-last-annotation segment) prev)
(funcall function segment posn)
(let ((new-size (- (segment-current-index segment) index)))
(unless (= new-size old-size)
(error "~S emitted ~D bytes, but claimed it's was ~D"
note new-size old-size)))
(let ((tail (segment-last-annotation segment)))
(if tail
(setf (cdr tail) next)
(setf (segment-annotations segment) next)))
(setf next (cdr prev)))))
(cond ((back-patch-p note)
(fill-in (back-patch-function note)
(back-patch-size note)))
((chooser-p note)
(fill-in (chooser-worst-case-fun note)
(chooser-size note)))
(t
(setf prev remaining)))))))
Interface to the rest of the compiler .
;;; *CURRENT-SEGMENT* -- internal.
;;;
The holds the current segment while assembling . Use to change
;;; it.
;;;
(defvar *current-segment*)
;;; *CURRENT-VOP* -- internal.
;;;
Just like * CURRENT - SEGMENT * , but holds the current vop . Used only to keep
;;; track of which vops emit which insts.
;;;
(defvar *current-vop* nil)
;;; ASSEMBLE -- interface.
;;;
;;; We also symbol-macrolet *current-segment* to a local holding the segment
;;; so uses of *current-segment* inside the body don't have to keep
dereferencing the symbol . Given that is the only interface to
;;; *current-segment*, we don't have to worry about the special value becoming
;;; out of sync with the lexical value. Unless some bozo closes over it,
;;; but nobody does anything like that...
;;;
(defmacro assemble ((&optional segment vop &key labels) &body body
&environment env)
"Execute BODY (as a progn) with SEGMENT as the current segment."
(flet ((label-name-p (thing)
(and thing (symbolp thing))))
(let* ((seg-var (gensym "SEGMENT-"))
(vop-var (gensym "VOP-"))
(visable-labels (keep-if #'label-name-p body))
(inherited-labels
(multiple-value-bind
(expansion expanded)
(macroexpand '..inherited-labels.. env)
(if expanded expansion nil)))
(new-labels (append labels
(set-difference visable-labels
inherited-labels)))
(nested-labels (set-difference (append inherited-labels new-labels)
visable-labels)))
(when (intersection labels inherited-labels)
(error "Duplicate nested labels: ~S"
(intersection labels inherited-labels)))
`(let* ((,seg-var ,(or segment '*current-segment*))
(,vop-var ,(or vop '*current-vop*))
,@(when segment
`((*current-segment* ,seg-var)))
,@(when vop
`((*current-vop* ,vop-var)))
,@(mapcar #'(lambda (name)
`(,name (gen-label)))
new-labels))
(symbol-macrolet ((*current-segment* ,seg-var)
(*current-vop* ,vop-var)
,@(when (or inherited-labels nested-labels)
`((..inherited-labels.. ,nested-labels))))
,@(mapcar #'(lambda (form)
(if (label-name-p form)
`(emit-label ,form)
form))
body))))))
;;; INST -- interface.
;;;
(defmacro inst (&whole whole instruction &rest args &environment env)
"Emit the specified instruction to the current segment."
(let ((inst (gethash (symbol-name instruction)
(assem-params-instructions
(c:backend-assembler-params c:*target-backend*)))))
(cond ((null inst)
(error "Unknown instruction: ~S" instruction))
((functionp inst)
(funcall inst (cdr whole) env))
(t
`(,inst *current-segment* *current-vop* ,@args)))))
;;; EMIT-LABEL -- interface.
;;;
(defmacro emit-label (label)
"Emit LABEL at this location in the current segment."
`(%emit-label *current-segment* *current-vop* ,label))
;;; EMIT-POSTIT -- interface.
;;;
(defmacro emit-postit (function)
`(%emit-postit *current-segment* ,function))
;;; ALIGN -- interface.
;;;
(defmacro align (bits &optional (fill-byte 0))
"Emit an alignment restriction to the current segment."
`(emit-alignment *current-segment* *current-vop* ,bits ,fill-byte))
;;; LABEL-POSITION -- interface.
;;;
(defun label-position (label &optional if-after delta)
"Return the current position for LABEL. Chooser maybe-shrink functions
should supply IF-AFTER and DELTA to assure correct results."
(let ((posn (label-posn label)))
(if (and if-after (> posn if-after))
(- posn delta)
posn)))
;;; APPEND-SEGMENT -- interface.
;;;
(defun append-segment (segment other-segment)
"Append OTHER-SEGMENT to the end of SEGMENT. Don't use OTHER-SEGMENT
for anything after this."
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(let ((postits (segment-postits segment)))
(setf (segment-postits segment) (segment-postits other-segment))
(dolist (postit postits)
(emit-back-patch segment 0 postit)))
(if (c:backend-featurep :x86)
(emit-alignment segment nil max-alignment #x90)
(emit-alignment segment nil max-alignment))
(let ((offset-in-last-block (rem (segment-current-index segment)
output-block-size)))
(unless (zerop offset-in-last-block)
(emit-filler segment (- output-block-size offset-in-last-block))))
(let* ((blocks (segment-output-blocks segment))
(next-block-num (floor (segment-current-index segment)
output-block-size))
(other-blocks (segment-output-blocks other-segment)))
(setf blocks
(adjust-array blocks (+ next-block-num (length other-blocks))))
(setf (segment-output-blocks segment) blocks)
(replace blocks other-blocks :start1 next-block-num))
(let ((index-delta (segment-current-index segment))
(posn-delta (segment-current-posn segment))
(other-annotations (segment-annotations other-segment)))
(setf (segment-current-index segment)
(+ index-delta (segment-current-index other-segment)))
(setf (segment-current-posn segment)
(+ posn-delta (segment-current-posn other-segment)))
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(when other-annotations
(dolist (note other-annotations)
(incf (annotation-index note) index-delta)
(incf (annotation-posn note) posn-delta))
(let ((last (segment-last-annotation segment)))
(if last
(setf (cdr last) other-annotations)
(setf (segment-annotations segment) other-annotations))
(setf (segment-last-annotation segment)
(segment-last-annotation other-segment)))))
(ext:undefined-value))
;;; FINALIZE-SEGMENT -- interface.
;;;
(defun finalize-segment (segment)
"Does any final processing of SEGMENT and returns the total number of bytes
covered by this segment."
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(setf (segment-run-scheduler segment) nil)
FIX brand name
(setf (segment-postits segment) nil)
(dolist (postit postits)
(emit-back-patch segment 0 postit)))
(setf (segment-final-index segment) (segment-current-index segment))
(setf (segment-final-posn segment) (segment-current-posn segment))
(setf (segment-inst-hook segment) nil)
(compress-output segment)
(finalize-positions segment)
(process-back-patches segment)
(segment-final-posn segment))
;;; SEGMENT-MAP-OUTPUT -- interface.
;;;
(defun segment-map-output (segment function)
"Call FUNCTION on all the output accumulated in SEGMENT. FUNCTION is called
zero or more times with two arguments: a SAP and a number of bytes."
(let ((old-index 0)
(blocks (segment-output-blocks segment))
(sap (system:int-sap 0))
(end (system:int-sap 0)))
(labels ((map-until (index)
(unless (system:sap< sap end)
(multiple-value-bind
(block-num block-offset)
(floor old-index output-block-size)
(let ((block (aref blocks block-num)))
(setf sap (system:sap+ block block-offset))
(setf end (system:sap+ block output-block-size)))))
(let* ((desired (- index old-index))
(available (system:sap- end sap))
(amount (min desired available)))
(funcall function sap amount)
(incf old-index amount)
(setf sap (system:sap+ sap amount))
(when (< amount desired)
(map-until index)))))
(dolist (note (segment-annotations segment))
(when (filler-p note)
(let ((index (filler-index note)))
(when (< old-index index)
(map-until index)))
(let ((bytes (filler-bytes note)))
(incf old-index bytes)
(setf sap (system:sap+ sap bytes)))))
(let ((index (segment-final-index segment)))
(when (< old-index index)
(map-until index))))))
;;; RELEASE-SEGMENT -- interface.
;;;
(defun release-segment (segment)
"Releases any output buffers held on to by segment."
(let ((blocks (segment-output-blocks segment)))
(loop
for block across blocks
do (when block
(release-output-block block))))
(ext:undefined-value))
Interface to the instruction set definition .
;;; DEFINE-EMITTER -- Interface.
;;;
;;; Define a function named NAME that merges it's arguments into a single
;;; integer and then emits the bytes of that integer in the correct order
;;; based on the endianness of the target-backend.
;;;
(defmacro define-emitter (name total-bits &rest byte-specs)
(ext:collect ((arg-names) (arg-types))
(let* ((total-bits (eval total-bits))
(overall-mask (ash -1 total-bits))
(num-bytes (multiple-value-bind
(quo rem)
(truncate total-bits assembly-unit-bits)
(unless (zerop rem)
(error "~D isn't an even multiple of ~D"
total-bits assembly-unit-bits))
quo))
(bytes (make-array num-bytes :initial-element nil))
(segment-arg (gensym "SEGMENT-")))
(dolist (byte-spec-expr byte-specs)
(let* ((byte-spec (eval byte-spec-expr))
(byte-size (byte-size byte-spec))
(byte-posn (byte-position byte-spec))
(arg (gensym (format nil "~:@(ARG-FOR-~S-~)" byte-spec-expr))))
(when (ldb-test (byte byte-size byte-posn) overall-mask)
(error "Byte spec ~S either overlaps another byte spec, or ~
extends past the end."
byte-spec-expr))
(setf (ldb byte-spec overall-mask) -1)
(arg-names arg)
(arg-types `(type (integer ,(ash -1 (1- byte-size))
,(1- (ash 1 byte-size)))
,arg))
(multiple-value-bind
(start-byte offset)
(floor byte-posn assembly-unit-bits)
(let ((end-byte (floor (1- (+ byte-posn byte-size))
assembly-unit-bits)))
(flet ((maybe-ash (expr offset)
(if (zerop offset)
expr
`(ash ,expr ,offset))))
(declare (inline maybe-ash))
(cond ((zerop byte-size))
((= start-byte end-byte)
(push (maybe-ash `(ldb (byte ,byte-size 0) ,arg)
offset)
(svref bytes start-byte)))
(t
(push (maybe-ash
`(ldb (byte ,(- assembly-unit-bits offset) 0)
,arg)
offset)
(svref bytes start-byte))
(do ((index (1+ start-byte) (1+ index)))
((>= index end-byte))
(push
`(ldb (byte ,assembly-unit-bits
,(- (* assembly-unit-bits
(- index start-byte))
offset))
,arg)
(svref bytes index)))
(let ((len (rem (+ byte-size offset)
assembly-unit-bits)))
(push
`(ldb (byte ,(if (zerop len)
assembly-unit-bits
len)
,(- (* assembly-unit-bits
(- end-byte start-byte))
offset))
,arg)
(svref bytes end-byte))))))))))
(unless (= overall-mask -1)
(error "There are holes."))
(let ((forms nil))
(dotimes (i num-bytes)
(let ((pieces (svref bytes i)))
(assert pieces)
(push `(emit-byte ,segment-arg
,(if (cdr pieces)
`(logior ,@pieces)
(car pieces)))
forms)))
`(defun ,name (,segment-arg ,@(arg-names))
(declare (type segment ,segment-arg) ,@(arg-types))
,@(ecase (c:backend-byte-order c:*target-backend*)
(:little-endian (nreverse forms))
(:big-endian forms))
',name)))))
(defun grovel-lambda-list (lambda-list vop-var)
(let ((segment-name (car lambda-list))
(vop-var (or vop-var (gensym "VOP-"))))
(ext:collect ((new-lambda-list))
(new-lambda-list segment-name)
(new-lambda-list vop-var)
(labels
((grovel (state lambda-list)
(when lambda-list
(let ((param (car lambda-list)))
(cond
((member param lambda-list-keywords)
(new-lambda-list param)
(grovel param (cdr lambda-list)))
(t
(ecase state
((nil)
(new-lambda-list param)
`(cons ,param ,(grovel state (cdr lambda-list))))
(&optional
(multiple-value-bind
(name default supplied-p)
(if (consp param)
(values (first param)
(second param)
(or (third param)
(gensym "SUPPLIED-P-")))
(values param nil (gensym "SUPPLIED-P-")))
(new-lambda-list (list name default supplied-p))
`(and ,supplied-p
(cons ,(if (consp name)
(second name)
name)
,(grovel state (cdr lambda-list))))))
(&key
(multiple-value-bind
(name default supplied-p)
(if (consp param)
(values (first param)
(second param)
(or (third param)
(gensym "SUPPLIED-P-")))
(values param nil (gensym "SUPPLIED-P-")))
(new-lambda-list (list name default supplied-p))
(multiple-value-bind
(key var)
(if (consp name)
(values (first name) (second name))
(values (intern (symbol-name name) :keyword)
name))
`(append (and ,supplied-p (list ',key ,var))
,(grovel state (cdr lambda-list))))))
(&rest
(new-lambda-list param)
(grovel state (cdr lambda-list))
param))))))))
(let ((reconstructor (grovel nil (cdr lambda-list))))
(values (new-lambda-list)
segment-name
vop-var
reconstructor))))))
(defun extract-nths (index glue list-of-lists-of-lists)
(mapcar #'(lambda (list-of-lists)
(cons glue
(mapcar #'(lambda (list)
(nth index list))
list-of-lists)))
list-of-lists-of-lists))
;;; DEFINE-INSTRUCTION -- interface.
;;;
(defmacro define-instruction (name lambda-list &rest options)
(let* ((sym-name (symbol-name name))
(defun-name (ext:symbolicate sym-name "-INST-EMITTER"))
(vop-var nil)
(postits (gensym "POSTITS-"))
(emitter nil)
(decls nil)
(attributes nil)
(cost nil)
(dependencies nil)
(delay nil)
(pinned nil)
(pdefs nil))
(dolist (option-spec options)
(multiple-value-bind
(option args)
(if (consp option-spec)
(values (car option-spec) (cdr option-spec))
(values option-spec nil))
(case option
(:emitter
(when emitter
(error "Can only specify one emitter per instruction."))
(setf emitter args))
(:declare
(setf decls (append decls args)))
(:attributes
(setf attributes (append attributes args)))
(:cost
(setf cost (first args)))
(:dependencies
(setf dependencies (append dependencies args)))
(:delay
(when delay
(error "Can only specify delay once per instruction."))
(setf delay args))
(:pinned
(setf pinned t))
(:vop-var
(if vop-var
(error "Can only specify :vop-var once.")
(setf vop-var (car args))))
(:printer
(push
(eval
`(list
(multiple-value-list
,(disassem:gen-printer-def-forms-def-form name
(cdr option-spec)))))
pdefs))
(:printer-list
same as : printer , but is evaled first , and is a list of printers
(push
(eval
`(eval
`(list ,@(mapcar #'(lambda (printer)
`(multiple-value-list
,(disassem:gen-printer-def-forms-def-form
',name printer nil)))
,(cadr option-spec)))))
pdefs))
(t
(error "Unknown option: ~S" option)))))
(setf pdefs (nreverse pdefs))
(multiple-value-bind
(new-lambda-list segment-name vop-name arg-reconstructor)
(grovel-lambda-list lambda-list vop-var)
(push `(let ((hook (segment-inst-hook ,segment-name)))
(when hook
(funcall hook ,segment-name ,vop-name ,sym-name
,arg-reconstructor)))
emitter)
(push `(dolist (postit ,postits)
(emit-back-patch ,segment-name 0 postit))
emitter)
(unless cost (setf cost 1))
(push `(when (segment-collect-dynamic-statistics ,segment-name)
(let* ((info (c:ir2-component-dyncount-info
(c:component-info c:*compile-component*)))
(costs (c:dyncount-info-costs info))
(block-number (c:block-number
(c:ir2-block-block
(c:vop-block ,vop-name)))))
(incf (aref costs block-number) ,cost)))
emitter)
(when (assem-params-scheduler-p
(c:backend-assembler-params c:*target-backend*))
(if pinned
(setf emitter
`((when (segment-run-scheduler ,segment-name)
(schedule-pending-instructions ,segment-name))
,@emitter))
(let ((flet-name
(gensym (concatenate 'string "EMIT-" sym-name "-INST-")))
(inst-name (gensym "INST-")))
(setf emitter `((flet ((,flet-name (,segment-name)
,@emitter))
(if (segment-run-scheduler ,segment-name)
(let ((,inst-name
(make-instruction
(incf (segment-inst-number
,segment-name))
#',flet-name
(instruction-attributes
,@attributes)
(progn ,@delay))))
,@(when dependencies
`((note-dependencies
(,segment-name ,inst-name)
,@dependencies)))
(queue-inst ,segment-name ,inst-name))
(,flet-name ,segment-name))))))))
`(progn
(defun ,defun-name ,new-lambda-list
,@(when decls
`((declare ,@decls)))
(let ((,postits (segment-postits ,segment-name)))
(setf (segment-postits ,segment-name) nil)
(symbol-macrolet
((*current-segment*
(macrolet ((lose ()
(error "Can't use INST without an ASSEMBLE ~
inside emitters.")))
(lose))))
,@emitter))
(ext:undefined-value))
(eval-when (compile load eval)
(%define-instruction ,sym-name ',defun-name))
,@(extract-nths 1 'progn pdefs)
,@(when pdefs
`((disassem:install-inst-flavors
',name
(append ,@(extract-nths 0 'list pdefs)))))))))
;;; DEFINE-INSTRUCTION-MACRO -- interface.
;;;
(defmacro define-instruction-macro (name lambda-list &body body)
(let ((whole (gensym "WHOLE-"))
(env (gensym "ENV-")))
(multiple-value-bind
(body local-defs)
(lisp::parse-defmacro lambda-list whole body name 'instruction-macro
:environment env)
`(eval-when (compile load eval)
(%define-instruction ,(symbol-name name)
#'(lambda (,whole ,env)
,@local-defs
(block ,name
,body)))))))
(defun %define-instruction (name defun)
(setf (gethash name
(assem-params-instructions
(c:backend-assembler-params c:*target-backend*)))
defun)
name)
| null | https://raw.githubusercontent.com/mattmundell/nightshade/d8abd7bd3424b95b70bed599e0cfe033e15299e0/src/compiler/new-assem.lisp | lisp | Efficient retargetable scheduling assembler.
DEF-ASSEMBLER-PARAMS -- Interface.
Constants.
(also refered to as a ``byte''). Hopefully, different instruction
sets won't require chainging this.
OUTPUT-BLOCK-SIZE -- The size (in bytes) to use per output block. Each
output block is a chunk of raw memory, pointed to by a sap.
any better then that ourselves.
just a bound on it so we can define a type. There is no real hard
limit on indexes, but we will run out of memory sometime.
The SEGMENT structure.
SEGMENT -- This structure holds the state of the assembler.
The name of this segment. Only using in trace files.
Whether or not run the scheduler. Note: if the instruction defintions
were not compiled with the scheduler turned on, this has no effect.
If a function, then it is funcalled for each inst emitted with the
arguments.
Where to deposit the next byte.
Where the current output block ends. If fill-pointer is ever sap= to
this, don't deposit a byte. Move the fill pointer into a new block.
What position does this correspond to. Initially, positions and indexes
are the same, but after we start collapsing choosers, positions can change
while indexes stay the same.
Where in the output blocks are we currently outputing.
A vector of the output blocks.
A list of all the annotations that have been output to this segment.
A pointer to the last cons cell in the annotations list. This is
so we can quickly add things to the end of the annotations list.
The number of bits of alignment at the last time we synchronized.
The position the last time we synchronized.
The posn and index everything ends at. This is not maintained while the
data is being generated, but is filled in after. Basically, we copy
current-posn and current-index so that we can trash them while processing
choosers and back-patches.
*** State used by the scheduler during instruction queueing.
``Number'' for last instruction queued. Used only to supply insts
with unique sset-element-number's.
Simple-Vectors mapping locations to the instruction that reads them and
instructions that write them.
if a control transfer hasn't been queued. When a delayed branch is
queued, this slot is set to the delay count.
scheduling noise.
All the instructions that are pending and don't have any unresolved
dependents. We don't list branches here even if they would otherwise
qualify. They are listed above.
List of queued branches. We handle these specially, because they have to
block).
*** State used by the scheduler during instruction scheduling.
The instructions who would have had a read dependent removed if it were
not for a delay slot. This is a list of lists. Each element in the
top level list corresponds to yet another cycle of delay. Each element
instruction and the dependent to remove.
The emittable insts again, except this time as a list sorted by depth.
Whether or not to collect dynamic statistics. This is just the same as
*collect-dynamic-statistics* but is faster to reference.
Structures/types used by the scheduler.
This attribute is set if the scheduler can freely flush this instruction
have no side effect not described by the writes.
This attribute is set when an instruction can cause a control transfer.
For test instructions, the delay is used to determine how many
instructions follow the branch.
This attribute indicates that this ``instruction'' can be variable length,
and therefore better never be used in a branch delay slot.
The function to envoke to actually emit this instruction. Gets called
The attributes of this instruction.
Number of instructions or cycles of delay before additional instructions
can read our writes.
The maximum number of instructions in the longest dependency chain from
instruction.
Instructions whos writes this instruction tries to read.
Instructions whos writes or reads are overwritten by this instruction.
Instructions who write what we read or write.
Instructions who read what we write.
The scheduler itself.
WITHOUT-SCHEDULING -- interface.
The inst that wrote the value we want to read must have
completed.
And it must have been completed *after* all other
writes to that location. Actually, that isn't quite
true. Each of the earlier writes could be done
either before this last write, or after the read, but
we have no way of representing that.
And we don't need to remember about earlier writes any
more. Shortening the writers list means that we won't
bother generating as many explicit arcs in the graph.
All previous reads of this location must have completed.
All previous writes to the location must have completed.
And we can forget about remembering them, because
depending on us is as good as depending on them.
QUEUE-INST -- internal.
This routine is called by FIX? due to uses of the INST macro when the scheduler
is turned on. The change to the dependency graph has already been
computed, so we just have to check to see if the basic block is terminated.
SCHEDULE-PENDING-INSTRUCTIONS -- internal.
Emit all the pending instructions, and reset any state. This is called
whenever we hit a label (i.e. an entry point of some kind) and when the
user turns the scheduler off (otherwise, the queued instructions would
sit there until the scheduler was turned back on, and be emitted in the
wrong place).
Quick blow-out if nothing to do.
Note that any values live at the end of the block have to be computed
last.
If the value is live at the end of the block, we can't flush it.
Grovel through the entire graph in the forward direction finding all
the leaf instructions. FIX leaf? 0 delay?
Accumulate the results in reverse order. Well, actually, this list will
be in forward order, because we are generating the reverse order in
reverse.
Schedule all the branches in their exact locations.
Each time through this loop we need to emit another instruction.
be emitted before (i.e. must come after) the branch inst. If
If there is nothing to do, then emit a nop.
other, then the stuff that grabs a dependent could easily
grab the wrong one. But I don't feel like fixing this because
it doesn't matter for any of the architectures we are using
or plan on using.
If do-elements enters the body, then there is a
dependent. Emit it.
Remove it from the emittable insts.
And if it was delayed, removed it from the delayed
list. This can happen if there is a load in a
branch delay slot.
And return it.
Keep scheduling stuff until we run out.
Now call the emitters, but turn the scheduler off for the duration.
Clear out any residue left over. FIX "residue" implies "left over"
Utility for maintaining the segment-delayed list. We cdr down list
n times (extending it if necessary) and then push thing on into the car
of that cons cell.
SCHEDULE-ONE-INST -- internal.
Find the next instruction to schedule and return it after updating
any dependency information. If we can't do anything useful right
We've got us a live one here. Go for it.
Delete it from the list of insts.
Note that this inst has been emitted.
And return.
Are we wanting to flush this instruction?
Nope, it's still a go. So return it.
Yes, so pick a new one. We have to start over,
because note-resolved-dependencies might have
changed the emittable-insts-queue.
Nothing to do, so make something up.
No emittable instructions, but we have more work to do. Emit
All done.
NOTE-RESOLVED-DEPENDENCIES -- internal.
This function is called whenever an instruction has been scheduled, and we
want to know what possibilities that opens up. So look at all the
instructions that this one depends on, and remove this instruction from
their dependents list. If we were the last dependent, then that
dependency can be emitted now.
These are the instructions who have to be completed before our
write fires. Doesn't matter how far before, just before.
These are the instructions who write values we read. If there
is no delay, then just remove us from the dependent list.
Otherwise, record the fact that in n cycles, we should be
removed.
ADVANCE-ONE-INST -- internal.
Process the next entry in segment-delayed. This is called whenever anyone
emits an instruction.
INSERT-EMITTABLE-INST -- internal.
Note that inst is emittable by sticking it in the SEGMENT-EMITTABLE-INSTS-
QUEUE list. We keep the emittable-insts sorted with the largest ``depths''
first. Except that if INST is a branch, don't bother. It will be handled
correctly by the branch emitting code in SCHEDULE-PENDING-INSTRUCTIONS.
Structure used during output emission.
Where in the raw output stream was this annotation emitted.
What position does that correspond to.
LABEL -- Doesn't need any additional information beyond what is in the
annotation structure.
ALIGNMENT-NOTE -- A constraint on how the output stream must be aligned.
The amount of filler we are assuming this alignment op will take.
The byte used as filling.
BACK-PATCH -- a reference to someplace that needs to be back-patched when
we actually know what label positions, etc. are.
The area effected by this back-patch.
The function to use to generate the real data
of stuff output depends on label-positions, etc. Back-patches can't change
their mind about how much stuff to emit, but choosers can.
The worst case size for this chooser. There is this much space allocated
in the output buffer.
The worst case alignment this chooser is guarenteed to preserve.
The function to call to determine of we can use a shorter sequence. It
returns NIL if nothing shorter can be used, or emits that sequence and
returns T.
The function to call to generate the worst case sequence. This is used
when nothing else can be condensed.
really need as much space as we initially gave it.
The number of bytes of filler here.
Output buffer utility functions.
A list of all the output-blocks we have allocated but aren't using.
We free-list them because allocation more is slow and the garbage collector
doesn't know about them, so it can't be slowed down by use keep ahold of
them.
A list of all the output-blocks we have ever allocated. We don't really
need to keep tract of this if RELEASE-OUTPUT-BLOCK were always called,
but...
NEW-OUTPUT-BLOCK -- internal.
Return a new output block, allocating one if necessary.
RELEASE-OUTPUT-BLOCK -- internal.
Return block to the list of avaiable blocks.
FORGET-OUTPUT-BLOCKS -- internal.
We call this whenever a core starts up, because system-memory isn't
saves with the core. If we didn't, we would find our hands full of
bogus SAPs, which would make all sorts of things unhappy.
Output functions.
FIND-NEW-FILL-POINTER -- internal.
any additional storage as necessary.
EMIT-BYTE -- interface.
EMIT-SKIP -- interface.
EMIT-ANNOTATION -- internal.
Used to handle the common parts of annotation emission. We just
assign the posn and index of the note and tack it on to the end
of the segment's annotations list.
EMIT-BACK-PATCH -- interface.
EMIT-CHOOSER -- interface.
ADJUST-ALIGNMENT-AFTER-CHOOSER -- internal.
current alignment information in light of this chooser. If the alignment
guarenteed byte the chooser is less then the segments current alignment,
we have to adjust the segments notion of the current alignment.
The hard part is recomputing the sync posn, because it's not just the
The chooser might change the alignment of the output. So we have
to figure out what the worst case alignment could be.
EMIT-FILLER -- internal.
Used internally whenever a chooser or alignment decides it doesn't need
as much space as it originally though.
%EMIT-LABEL -- internal.
EMIT-LABEL (the interface) basically just expands into this, supplying
EMIT-ALIGNMENT -- internal.
Called by the ALIGN macro to emit an alignment note. We check to see
if we can guarentee the alignment restriction by just outputing a fixed
number of bytes. If so, we do so. Otherwise, we create and emit
an alignment note.
to get back in sync with alignment, and then emit an alignment
note to cover the rest.
The last alignment was more restrictive then this one.
So we can just figure out how much noise to emit assuming
the last alignment was met.
But we emit an alignment with size=0 so we can verify
that everything works.
FIND-ALIGNMENT -- internal.
Used to find how ``aligned'' different offsets are. Returns the number
of low-order 0 bits, up to MAX-ALIGNMENT.
EMIT-POSTIT -- Internal.
Emit a postit. The function will be called as a back-patch with the
interfere at all with scheduling.
Output compression/position assignment.
Grovel though all the annotations looking for choosers. When we find
a chooser, invoke the maybe-shrink function. If it returns T, it output
some other byte sequence.
It emitted some replacement.
The chooser passed on shrinking. Make sure it didn't emit
anything.
Act like we just emitted this chooser.
Adjust the alignment accordingly.
And keep this chooser for next time around.
Re-emit the alignment, letting it collapse if we know anything
more about the alignment guarantees of the segment.
FINALIZE-POSITIONS -- internal.
We have run all the choosers we can, so now we have to figure out exactly
how much space each alignment note needs.
PROCESS-BACK-PATCHES -- internal.
Grovel over segment, filling in any backpatches. If any choosers are
left over, we need to emit their worst case variant.
*CURRENT-SEGMENT* -- internal.
it.
*CURRENT-VOP* -- internal.
track of which vops emit which insts.
ASSEMBLE -- interface.
We also symbol-macrolet *current-segment* to a local holding the segment
so uses of *current-segment* inside the body don't have to keep
*current-segment*, we don't have to worry about the special value becoming
out of sync with the lexical value. Unless some bozo closes over it,
but nobody does anything like that...
INST -- interface.
EMIT-LABEL -- interface.
EMIT-POSTIT -- interface.
ALIGN -- interface.
LABEL-POSITION -- interface.
APPEND-SEGMENT -- interface.
FINALIZE-SEGMENT -- interface.
SEGMENT-MAP-OUTPUT -- interface.
RELEASE-SEGMENT -- interface.
DEFINE-EMITTER -- Interface.
Define a function named NAME that merges it's arguments into a single
integer and then emits the bytes of that integer in the correct order
based on the endianness of the target-backend.
DEFINE-INSTRUCTION -- interface.
DEFINE-INSTRUCTION-MACRO -- interface.
| FIX rename assembler.lisp
(in-package "NEW-ASSEM")
(in-package :c)
(import '(branch flushable) :new-assem)
(import '(sset-element sset make-sset do-elements
sset-adjoin sset-delete sset-empty)
:new-assem)
(in-package :new-assem)
(export '(emit-byte emit-skip emit-back-patch emit-chooser emit-postit
define-emitter define-instruction define-instruction-macro
def-assembler-params branch flushable variable-length reads writes
segment make-segment segment-name segment-collect-dynamic-statistics
assemble align inst without-scheduling
label label-p gen-label emit-label label-position
append-segment finalize-segment
segment-map-output release-segment))
#[ Assembly
Resolve branches and convert into object code and fixup information.
Phase position: 22/23 (back)
Presence: required
Files: codegen
Entry functions: `new-assem:finalize-segment'
Call sequences:
native-compile-component
generate-code
new-assem:finalize-segment
new-assem:compress-output
new-assem:finalize-positions
new-assem:process-back-patches
In effect, we do much of the work of assembly when the compiler is compiled.
The assembler makes one pass fixing up branch offsets, then squeezes out the
space left by branch shortening and dumps out the code along with the load-time
fixup information. The assembler also deals with dumping unboxed non-immediate
constants and symbols. Boxed constants are created by explicit constructor
code in the top-level form, while immediate constants are generated using
inline code.
XXX The basic output of the assembler is:
A code vector
A representation of the fixups along with indices into the code vector for
the fixup locations
A PC map translating PCs into source paths
This information can then be used to build an output file or an in-core
function object.
The assembler is table-driven and supports arbitrary instruction formats. As
far as the assembler is concerned, an instruction is a bit sequence that is
broken down into subsequences. Some of the subsequences are constant in value,
while others can be determined at assemble or load time.
Assemble Node Form*
Allow instructions to be emitted during the evaluation of the Forms by
defining Inst as a local macro. This macro caches various global
information in local variables. Node tells the assembler what node
ultimately caused this code to be generated. This is used to create the
pc=>source map for the debugger.
Assemble-Elsewhere Node Form*
Similar to Assemble, but the current assembler location is changed to
somewhere else. This is useful for generating error code and similar
things. Assemble-Elsewhere may not be nested.
Inst Name Arg*
Emit the instruction Name with the specified arguments.
Gen-Label
Emit-Label (Label)
Gen-Label returns a Label object, which describes a place in the code.
Emit-Label marks the current position as being the location of Label.
]#
#[ Writing Assembly Code
VOP writers expect:
MOVE
You write when you port the assembler.
EMIT-LABEL
Assembler interface like INST. Takes a label you made and says "stick it
here."
GEN-LABEL
Returns a new label suitable for use with EMIT-LABEL exactly once and
for referencing as often as necessary.
INST
Recognizes and dispatches to instructions you defined for assembler.
ALIGN
This takes the number of zero bits you want in the low end of the address
of the next instruction.
ASSEMBLE
ASSEMBLE-ELSEWHERE
Get ready for assembling stuff. Takes a VOP and arbitrary PROGN-style
body. Wrap these around instruction emission code announcing the first
pass of our assembler.
CURRENT-NFP-TN
This returns a TN for the NFP if the caller uses the number stack, or
nil.
SB-ALLOCATED-SIZE
This returns the size of some storage based used by the currently
compiling component.
...
VOP idioms
STORE-STACK-TN
LOAD-STACK-TN
These move a value from a register to the control stack, or from the
control stack to a register. They take care of checking the TN types,
modifying offsets according to the address units per word, etc.
]#
#[ Pipeline Reorganization
On some machines, move memory references backward in the code so that
they can overlap with computation. On machines with delayed branch
instructions, locate instructions that can be moved into delay slots.
Phase position: 21/23 (back)
Presence: required
Files: codegen
Entry functions: `new-assem:finalize-segment'
Call sequences:
c:native-compile-component
c:generate-code
new-assem:finalize-segment
new-assem:schedule-pending-instructions
new-assem:add-to-nth-list
new-assem:schedule-one-inst
new-assem:advance-one-inst
new-assem:note-resolved-dependencies
c:emit-nop
]#
Assembly control parameters .
(defstruct (assem-params
(:print-function %print-assem-params))
(backend (ext:required-argument) :type c::backend)
(scheduler-p nil :type (member t nil))
(instructions (make-hash-table :test #'equal) :type hash-table)
(max-locations 0 :type index))
(c::defprinter assem-params
(backend :prin1 (c:backend-name backend)))
(defmacro def-assembler-params (&rest options)
"Set up the assembler."
`(eval-when (compile load eval)
(setf (c:backend-assembler-params c:*target-backend*)
(make-assem-params :backend c:*target-backend*
,@options))))
ASSEMBLY - UNIT - BITS -- Number of bits in the minimum assembly unit ,
(defconstant assembly-unit-bits 8)
(deftype assembly-unit ()
`(unsigned-byte ,assembly-unit-bits))
(defconstant output-block-size (* 8 1024))
(deftype output-block-index ()
`(integer 0 ,output-block-size))
MAX - ALIGNMENT -- The maximum alignment we can guarentee given the object
format . If the loader only loads objects 8 - byte aligned , we ca n't do
(defconstant max-alignment 3)
(deftype alignment ()
`(integer 0 ,max-alignment))
MAX - INDEX -- The maximum an index will ever become . Well , actually ,
(defconstant max-index (1- most-positive-fixnum))
(deftype index ()
`(integer 0 ,max-index))
MAX - POSN -- Like MAX - INDEX , except for positions .
(defconstant max-posn (1- most-positive-fixnum))
(deftype posn ()
`(integer 0 ,max-posn))
(defstruct (segment
(:print-function %print-segment)
(:constructor make-segment (&key name run-scheduler inst-hook)))
(name "Unnamed" :type simple-base-string)
(run-scheduler nil)
segment , the VOP , the name of the inst ( as a string ) , and the inst
(inst-hook nil :type (or function null))
(fill-pointer (system:int-sap 0) :type system:system-area-pointer)
(block-end (system:int-sap 0) :type system:system-area-pointer)
(current-posn 0 :type posn)
(current-index 0 :type index)
(output-blocks (make-array 4 :initial-element nil) :type simple-vector)
(annotations nil :type list)
(last-annotation nil :type list)
(alignment max-alignment :type alignment)
(sync-posn 0 :type posn)
(final-posn 0 :type posn)
(final-index 0 :type index)
List of 's . These are accumulated between instructions .
(postits nil :type list)
(inst-number 0 :type index)
(readers (make-array (assem-params-max-locations
(c:backend-assembler-params c:*backend*))
:initial-element nil)
:type simple-vector)
(writers (make-array (assem-params-max-locations
(c:backend-assembler-params c:*backend*))
:initial-element nil)
:type simple-vector)
The number of additional cycles before the next control transfer , or NIL
(branch-countdown nil :type (or null (and fixnum unsigned-byte)))
* * * These two slots are used by both the queuing noise and the
(emittable-insts-sset (make-sset) :type sset)
be emitted at a specific place ( e.g. one slot before the end of the
(queued-branches nil :type list)
in the second level lists is a dotted pair , holding the dependency
(delayed nil :type list)
(emittable-insts-queue nil :type list)
(collect-dynamic-statistics nil))
(c::defprinter segment name)
(c:def-boolean-attribute instruction
if it thinks it is not needed . Examples are NOP and instructions that
flushable
branch
variable-length)
(defstruct (instruction
(:include sset-element)
(:print-function %print-instruction)
(:conc-name inst-)
(:constructor make-instruction (number emitter attributes delay)))
with the segment as its one argument .
(emitter (required-argument) :type (or null function))
(attributes (instruction-attributes) :type c:attributes)
(delay 0 :type (and fixnum unsigned-byte))
this instruction to one of the independent instructions . This is used
as a heuristic at to which instructions should be scheduled first .
(depth nil :type (or null (and fixnum unsigned-byte)))
* * When trying remember which of the next four is which , note that the
` ` read '' or ` ` write '' always referes to the dependent ( second )
(read-dependencies (make-sset) :type sset)
(write-dependencies (make-sset) :type sset)
(write-dependents (make-sset) :type sset)
(read-dependents (make-sset) :type sset))
#+debug (defvar *inst-ids* (make-hash-table :test #'eq))
#+debug (defvar *next-inst-id* 0)
(defun %print-instruction (inst stream depth)
(declare (ignore depth))
(print-unreadable-object (inst stream :type t :identity t)
#+debug
(princ (or (gethash inst *inst-ids*)
(setf (gethash inst *inst-ids*)
(incf *next-inst-id*)))
stream)
(format stream #+debug " emitter=~S" #-debug "emitter=~S"
(let ((emitter (inst-emitter inst)))
(if emitter
(multiple-value-bind
(lambda lexenv-p name)
(function-lambda-expression emitter)
(declare (ignore lambda lexenv-p))
name)
'<flushed>)))
(when (inst-depth inst)
(format stream ", depth=~D" (inst-depth inst)))))
#+debug
(defun reset-inst-ids ()
(clrhash *inst-ids*)
(setf *next-inst-id* 0))
(defmacro without-scheduling ((&optional (segment '*current-segment*))
&body body)
"Execute BODY (as a progn) without scheduling any of the instructions
generated inside it. DO NOT throw or return-from out of it."
(let ((var (gensym))
(seg (gensym)))
`(let* ((,seg ,segment)
(,var (segment-run-scheduler ,seg)))
(when ,var
(schedule-pending-instructions ,seg)
(setf (segment-run-scheduler ,seg) nil))
,@body
(setf (segment-run-scheduler ,seg) ,var))))
(defmacro note-dependencies ((segment inst) &body body)
(ext:once-only ((segment segment) (inst inst))
`(macrolet ((reads (loc) `(note-read-dependency ,',segment ,',inst ,loc))
(writes (loc &rest keys)
`(note-write-dependency ,',segment ,',inst ,loc ,@keys)))
,@body)))
(defun note-read-dependency (segment inst read)
(multiple-value-bind (loc-num size)
(c:location-number read)
#+debug (format *trace-output* "~&~S reads ~S[~D for ~D]~%"
inst read loc-num size)
(when loc-num
Iterate over all the locations for this TN .
(do ((index loc-num (1+ index))
(end-loc (+ loc-num (or size 1))))
((>= index end-loc))
(declare (type (mod 2048) index end-loc))
(let ((writers (svref (segment-writers segment) index)))
(when writers
(let ((writer (car writers)))
(sset-adjoin writer (inst-read-dependencies inst))
(sset-adjoin inst (inst-read-dependents writer))
(sset-delete writer (segment-emittable-insts-sset segment))
(dolist (other-writer (cdr writers))
(sset-adjoin other-writer (inst-write-dependencies writer))
(sset-adjoin writer (inst-write-dependents other-writer))
(sset-delete other-writer
(segment-emittable-insts-sset segment))))
(setf (cdr writers) nil)))
(push inst (svref (segment-readers segment) index)))))
(ext:undefined-value))
(defun note-write-dependency (segment inst write &key partially)
(multiple-value-bind (loc-num size)
(c:location-number write)
#+debug (format *trace-output* "~&~S writes ~S[~D for ~D]~%"
inst write loc-num size)
(when loc-num
Iterate over all the locations for this TN .
(do ((index loc-num (1+ index))
(end-loc (+ loc-num (or size 1))))
((>= index end-loc))
(declare (type (mod 2048) index end-loc))
(dolist (prev-inst (svref (segment-readers segment) index))
(unless (eq prev-inst inst)
(sset-adjoin prev-inst (inst-write-dependencies inst))
(sset-adjoin inst (inst-write-dependents prev-inst))
(sset-delete prev-inst (segment-emittable-insts-sset segment))))
(when partially
(dolist (prev-inst (svref (segment-writers segment) index))
(sset-adjoin prev-inst (inst-write-dependencies inst))
(sset-adjoin inst (inst-write-dependents prev-inst))
(sset-delete prev-inst (segment-emittable-insts-sset segment)))
(setf (svref (segment-writers segment) index) nil))
(push inst (svref (segment-writers segment) index)))))
(ext:undefined-value))
(defun queue-inst (segment inst)
#+debug (format *trace-output* "~&Queuing ~S~%" inst)
#+debug
(format *trace-output* " reads ~S~% writes ~S~%"
(ext:collect ((reads))
(do-elements (read (inst-read-dependencies inst))
(reads read))
(reads))
(ext:collect ((writes))
(do-elements (write (inst-write-dependencies inst))
(writes write))
(writes)))
(assert (segment-run-scheduler segment))
(let ((countdown (segment-branch-countdown segment)))
(when countdown
(decf countdown)
(assert (not (instruction-attributep (inst-attributes inst)
variable-length))))
(cond ((instruction-attributep (inst-attributes inst) branch)
(unless countdown
(setf countdown (inst-delay inst)))
(push (cons countdown inst)
(segment-queued-branches segment)))
(t
(sset-adjoin inst (segment-emittable-insts-sset segment))))
(when countdown
(setf (segment-branch-countdown segment) countdown)
(when (zerop countdown)
(schedule-pending-instructions segment))))
(ext:undefined-value))
(defun schedule-pending-instructions (segment)
(assert (segment-run-scheduler segment))
(when (and (sset-empty (segment-emittable-insts-sset segment))
(null (segment-queued-branches segment)))
(return-from schedule-pending-instructions
(ext:undefined-value)))
#+debug
(format *trace-output* "~&Scheduling pending instructions...~%")
(let ((emittable-insts (segment-emittable-insts-sset segment))
(writers (segment-writers segment)))
(dotimes (index (length writers))
(let* ((writer (svref writers index))
(inst (car writer))
(overwritten (cdr writer)))
(when writer
(when overwritten
(let ((write-dependencies (inst-write-dependencies inst)))
(dolist (other-inst overwritten)
(sset-adjoin inst (inst-write-dependents other-inst))
(sset-adjoin other-inst write-dependencies)
(sset-delete other-inst emittable-insts))))
(setf (instruction-attributep (inst-attributes inst) flushable)
nil)))))
(labels ((grovel-inst (inst)
(let ((max 0))
(do-elements (dep (inst-write-dependencies inst))
(let ((dep-depth (or (inst-depth dep) (grovel-inst dep))))
(when (> dep-depth max)
(setf max dep-depth))))
(do-elements (dep (inst-read-dependencies inst))
(let ((dep-depth
(+ (or (inst-depth dep) (grovel-inst dep))
(inst-delay dep))))
(when (> dep-depth max)
(setf max dep-depth))))
(cond ((and (sset-empty (inst-read-dependents inst))
(instruction-attributep (inst-attributes inst)
flushable))
#+debug
(format *trace-output* "Flushing ~S~%" inst)
(setf (inst-emitter inst) nil)
(setf (inst-depth inst) max))
(t
(setf (inst-depth inst) max))))))
(let ((emittable-insts nil)
(delayed nil))
(do-elements (inst (segment-emittable-insts-sset segment))
(grovel-inst inst)
(if (zerop (inst-delay inst))
(push inst emittable-insts)
(setf delayed
(add-to-nth-list delayed inst (1- (inst-delay inst))))))
(setf (segment-emittable-insts-queue segment)
(sort emittable-insts #'> :key #'inst-depth))
(setf (segment-delayed segment) delayed))
(dolist (branch (segment-queued-branches segment))
(grovel-inst (cdr branch))))
#+debug
(format *trace-output* "Queued branches: ~S~%"
(segment-queued-branches segment))
#+debug
(format *trace-output* "Initially emittable: ~S~%"
(segment-emittable-insts-queue segment))
#+debug
(format *trace-output* "Initially delayed: ~S~%"
(segment-delayed segment))
(let ((results nil))
(let ((insts-from-end (segment-branch-countdown segment)))
(dolist (branch (segment-queued-branches segment))
(let ((inst (cdr branch)))
(dotimes (i (- (car branch) insts-from-end))
First , we check to see if there is any instruction that must
so , emit it . Otherwise , just pick one of the emittable insts .
# # # Note : despite the fact that this is a loop , it really wo n't
work for repetitions other then zero and one . For example , if
the branch has two dependents and one of them dpends on the
(flet ((maybe-schedule-dependent (dependents)
(do-elements (inst dependents)
(note-resolved-dependencies segment inst)
(setf (segment-emittable-insts-queue segment)
(delete inst
(segment-emittable-insts-queue segment)
:test #'eq))
(block scan-delayed
(do ((delayed (segment-delayed segment)
(cdr delayed)))
((null delayed))
(do ((prev nil cons)
(cons (car delayed) (cdr cons)))
((null cons))
(when (eq (car cons) inst)
(if prev
(setf (cdr prev) (cdr cons))
(setf (car delayed) (cdr cons)))
(return-from scan-delayed nil)))))
(return inst))))
(let ((fill (or (maybe-schedule-dependent
(inst-read-dependents inst))
(maybe-schedule-dependent
(inst-write-dependents inst))
(schedule-one-inst segment t)
:nop)))
#+debug
(format *trace-output* "Filling branch delay slot with ~S~%"
fill)
(push fill results)))
(advance-one-inst segment)
(incf insts-from-end))
(note-resolved-dependencies segment inst)
(push inst results)
#+debug
(format *trace-output* "Emitting ~S~%" inst)
(advance-one-inst segment))))
(loop
(let ((inst (schedule-one-inst segment nil)))
FIX ( push ( or ( s - o - i .. ) ( return ) ) results ) ? ( while ... )
(push inst results)
(advance-one-inst segment)))
(setf (segment-run-scheduler segment) nil)
(dolist (inst results)
(if (eq inst :nop)
(c:emit-nop segment)
(funcall (inst-emitter inst) segment)))
(setf (segment-run-scheduler segment) t))
(setf (segment-inst-number segment) 0)
(setf (segment-queued-branches segment) nil)
(setf (segment-branch-countdown segment) nil)
(setf (segment-emittable-insts-sset segment) (make-sset))
(fill (segment-readers segment) nil)
(fill (segment-writers segment) nil)
(ext:undefined-value))
ADD - TO - NTH - LIST -- internal .
(defun add-to-nth-list (list thing n)
(do ((cell (or list (setf list (list nil)))
(or (cdr cell) (setf (cdr cell) (list nil))))
(i n (1- i)))
((zerop i)
(push thing (car cell))
list)))
now , but there is more work to be done , return : NOP to indicate that
a nop must be emitted . If we are all done , return NIL .
(defun schedule-one-inst (segment delay-slot-p)
(do ((prev nil remaining)
(remaining (segment-emittable-insts-queue segment) (cdr remaining)))
((null remaining))
(let ((inst (car remaining)))
(unless (and delay-slot-p
(instruction-attributep (inst-attributes inst)
variable-length))
#+debug
(format *Trace-output* "Emitting ~S~%" inst)
(if prev
(setf (cdr prev) (cdr remaining))
(setf (segment-emittable-insts-queue segment)
(cdr remaining)))
(note-resolved-dependencies segment inst)
(return-from schedule-one-inst
(if (inst-emitter inst)
inst
(schedule-one-inst segment delay-slot-p))))))
(cond ((segment-delayed segment)
a NOP to fill in a delay slot .
#+debug (format *trace-output* "Emitting a NOP.~%")
:nop)
(t
nil)))
(defun note-resolved-dependencies (segment inst)
(assert (sset-empty (inst-read-dependents inst)))
(assert (sset-empty (inst-write-dependents inst)))
(do-elements (dep (inst-write-dependencies inst))
(let ((dependents (inst-write-dependents dep)))
(sset-delete inst dependents)
(when (and (sset-empty dependents)
(sset-empty (inst-read-dependents dep)))
(insert-emittable-inst segment dep))))
(do-elements (dep (inst-read-dependencies inst))
(if (zerop (inst-delay dep))
(let ((dependents (inst-read-dependents dep)))
(sset-delete inst dependents)
(when (and (sset-empty dependents)
(sset-empty (inst-write-dependents dep)))
(insert-emittable-inst segment dep)))
(setf (segment-delayed segment)
(add-to-nth-list (segment-delayed segment)
(cons dep inst)
(inst-delay dep)))))
(ext:undefined-value))
(defun advance-one-inst (segment)
(let ((delayed-stuff (pop (segment-delayed segment))))
(dolist (stuff delayed-stuff)
(if (consp stuff)
(let* ((dependency (car stuff))
(dependent (cdr stuff))
(dependents (inst-read-dependents dependency)))
(sset-delete dependent dependents)
(when (and (sset-empty dependents)
(sset-empty (inst-write-dependents dependency)))
(insert-emittable-inst segment dependency)))
(insert-emittable-inst segment stuff)))))
(defun insert-emittable-inst (segment inst)
(unless (instruction-attributep (inst-attributes inst) branch)
#+debug
(format *Trace-output* "Now emittable: ~S~%" inst)
(do ((my-depth (inst-depth inst))
(remaining (segment-emittable-insts-queue segment) (cdr remaining))
(prev nil remaining))
((or (null remaining) (> my-depth (inst-depth (car remaining))))
(if prev
(setf (cdr prev) (cons inst remaining))
(setf (segment-emittable-insts-queue segment)
(cons inst remaining))))))
(ext:undefined-value))
ANNOTATION -- Common supertype for all the different kinds of annotations .
(defstruct (annotation
(:constructor nil))
(index 0 :type index)
(posn nil :type (or index null)))
(defstruct (label
(:include annotation)
(:constructor gen-label ())
(:print-function %print-label))
)
(defun %print-label (label stream depth)
(declare (ignore depth))
(if (or *print-escape* *print-readably*)
(print-unreadable-object (label stream :type t)
(prin1 (c:label-id label) stream))
(format stream "L~D" (c:label-id label))))
(defstruct (alignment-note
(:include annotation)
(:conc-name alignment-)
(:predicate alignment-p)
(:constructor make-alignment (bits size fill-byte)))
The minimum number of low - order bits that must be zero .
(bits 0 :type alignment)
(size 0 :type (integer 0 #.(1- (ash 1 max-alignment))))
(fill-byte 0 :type (or assembly-unit (signed-byte #.assembly-unit-bits))))
(defstruct (back-patch
(:include annotation)
(:constructor make-back-patch (size function)))
(size 0 :type index)
(function nil :type function))
CHOOSER -- Similar to a back - patch , but also an indication that the amount
(defstruct (chooser
(:include annotation)
(:constructor make-chooser
(size alignment maybe-shrink worst-case-fun)))
(size 0 :type index)
(alignment 0 :type alignment)
(maybe-shrink nil :type function)
(worst-case-fun nil :type function))
FILLER -- Used internally when we figure out a chooser or alignment does n't
(defstruct (filler
(:include annotation)
(:constructor make-filler (bytes)))
(bytes 0 :type index))
(defvar *available-output-blocks* nil)
(defvar *all-output-blocks* nil)
(defun new-output-block ()
(if *available-output-blocks*
(pop *available-output-blocks*)
(let ((block (system:allocate-system-memory output-block-size)))
(push block *all-output-blocks*)
block)))
(defun release-output-block (block)
(push block *available-output-blocks*))
(defun forget-output-blocks ()
(setf *all-output-blocks* nil)
(setf *available-output-blocks* nil))
(pushnew 'forget-output-blocks ext:*after-save-initializations*)
Find us a new fill pointer for the current index in segment . Allocate
(defun find-new-fill-pointer (segment)
(declare (type segment segment))
(let* ((index (segment-current-index segment))
(blocks (segment-output-blocks segment))
(num-blocks (length blocks)))
(multiple-value-bind
(block-num offset)
(truncate index output-block-size)
(when (>= block-num num-blocks)
(setf blocks
(adjust-array blocks (+ block-num 3) :initial-element nil))
(setf (segment-output-blocks segment) blocks))
(let ((block (or (aref blocks block-num)
(setf (aref blocks block-num) (new-output-block)))))
(setf (segment-block-end segment)
(system:sap+ block output-block-size))
(setf (segment-fill-pointer segment) (system:sap+ block offset))))))
Emit the supplied BYTE to SEGMENT , growing it if necessary .
(declaim (inline emit-byte))
(defun emit-byte (segment byte)
"Emit BYTE to SEGMENT."
(declare (type segment segment)
(type (or assembly-unit (signed-byte #.assembly-unit-bits)) byte))
(let* ((orig-ptr (segment-fill-pointer segment))
(ptr (if (system:sap= orig-ptr (segment-block-end segment))
(find-new-fill-pointer segment)
orig-ptr)))
(setf (system:sap-ref-8 ptr 0) (ldb (byte assembly-unit-bits 0) byte))
(setf (segment-fill-pointer segment) (system:sap+ ptr 1)))
(incf (segment-current-posn segment))
(incf (segment-current-index segment))
(ext:undefined-value))
(defun emit-skip (segment amount &optional (fill-byte 0))
"Output AMOUNT zeros (in bytes) to SEGMENT."
(declare (type segment segment)
(type index amount))
(dotimes (i amount)
(emit-byte segment fill-byte))
(ext:undefined-value))
(defun emit-annotation (segment note)
(declare (type segment segment)
(type annotation note))
(when (annotation-posn note)
(error "Attempt to emit ~S for the second time."))
(setf (annotation-posn note) (segment-current-posn segment))
(setf (annotation-index note) (segment-current-index segment))
(let ((last (segment-last-annotation segment))
(new (list note)))
(setf (segment-last-annotation segment)
(if last
(setf (cdr last) new)
(setf (segment-annotations segment) new))))
(ext:undefined-value))
(defun emit-back-patch (segment size function)
"Note that the instruction stream has to be back-patched when label positions
are finally known. SIZE bytes are reserved in SEGMENT, and function will
be called with two arguments: the segment and the position. The function
should look at the position and the position of any labels it wants to
and emit the correct sequence. (And it better be the same size as SIZE).
SIZE can be zero, which is useful if you just want to find out where things
ended up."
(emit-annotation segment (make-back-patch size function))
(emit-skip segment size))
(defun emit-chooser (segment size alignment maybe-shrink worst-case-fun)
"Note that the instruction stream here depends on the actual positions of
various labels, so can't be output until label positions are known. Space
is made in SEGMENT for at least SIZE bytes. When all output has been
generated, the MAYBE-SHRINK functions for all choosers are called with
three arguments: the segment, the position, and a magic value. The MAYBE-
SHRINK decides if it can use a shorter sequence, and if so, emits that
sequence to the segment and returns T. If it can't do better than the
worst case, it should return NIL (without emitting anything). When calling
LABEL-POSITION, it should pass it the position and the magic-value it was
passed so that LABEL-POSITION can return the correct result. If the chooser
never decides to use a shorter sequence, the WORST-CASE-FUN will be called,
just like a BACK-PATCH. (See EMIT-BACK-PATCH.)"
(declare (type segment segment) (type index size) (type alignment alignment)
(type function maybe-shrink worst-case-fun))
(let ((chooser (make-chooser size alignment maybe-shrink worst-case-fun)))
(emit-annotation segment chooser)
(emit-skip segment size)
(adjust-alignment-after-chooser segment chooser)))
Called in EMIT - CHOOSER and COMPRESS - SEGMENT in order to recompute the
choosers posn . Consider a chooser that emits either one or three words .
It preserves 8 - byte ( 3 bit ) alignments , because the difference between
the two choices is 8 bytes .
(defun adjust-alignment-after-chooser (segment chooser)
(declare (type segment segment) (type chooser chooser))
(let ((alignment (chooser-alignment chooser))
(seg-alignment (segment-alignment segment)))
(when (< alignment seg-alignment)
(setf (segment-alignment segment) alignment)
(let* ((posn (chooser-posn chooser))
(sync-posn (segment-sync-posn segment))
(offset (- posn sync-posn))
(delta (logand offset (1- (ash 1 alignment)))))
(setf (segment-sync-posn segment) (- posn delta)))))
(ext:undefined-value))
(defun emit-filler (segment bytes)
(let ((last (segment-last-annotation segment)))
(cond ((and last (filler-p (car last)))
(incf (filler-bytes (car last)) bytes))
(t
(emit-annotation segment (make-filler bytes)))))
(incf (segment-current-index segment) bytes)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(ext:undefined-value))
the segment and vop .
(defun %emit-label (segment vop label)
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(let ((postits (segment-postits segment)))
(setf (segment-postits segment) ())
(dolist (postit postits)
(emit-back-patch segment 0 postit)))
(let ((hook (segment-inst-hook segment)))
(when hook
(funcall hook segment vop :label label)))
(emit-annotation segment label))
(defun emit-alignment (segment vop bits &optional (fill-byte 0))
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(let ((hook (segment-inst-hook segment)))
(when hook
(funcall hook segment vop :align bits)))
(let ((alignment (segment-alignment segment))
(offset (- (segment-current-posn segment)
(segment-sync-posn segment))))
(cond ((> bits alignment)
We need more bits of alignment . First emit enough noise
(let ((slop (logand offset (1- (ash 1 alignment)))))
(unless (zerop slop)
(emit-skip segment (- (ash 1 alignment) slop) fill-byte)))
(let ((size (logand (1- (ash 1 bits))
(lognot (1- (ash 1 alignment))))))
(assert (> size 0))
(emit-annotation segment (make-alignment bits size fill-byte))
(emit-skip segment size fill-byte))
(setf (segment-alignment segment) bits)
(setf (segment-sync-posn segment) (segment-current-posn segment)))
(t
(let* ((mask (1- (ash 1 bits)))
(new-offset (logand (+ offset mask) (lognot mask))))
(emit-skip segment (- new-offset offset) fill-byte))
(emit-annotation segment (make-alignment bits 0 fill-byte)))))
(ext:undefined-value))
(defun find-alignment (offset)
(dotimes (i max-alignment max-alignment)
(when (logbitp i offset)
(return i))))
position the following instruction is finally emitted . do not
(defun %emit-postit (segment function)
(push function (segment-postits segment))
(ext:undefined-value))
COMPRESS - OUTPUT -- internal .
(defun compress-output (segment)
it better not take more than one or two passes .
(let ((delta 0))
(setf (segment-alignment segment) max-alignment)
(setf (segment-sync-posn segment) 0)
(do* ((prev nil)
(remaining (segment-annotations segment) next)
(next (cdr remaining) (cdr remaining)))
((null remaining))
(let* ((note (car remaining))
(posn (annotation-posn note)))
(unless (zerop delta)
(decf posn delta)
(setf (annotation-posn note) posn))
(cond
((chooser-p note)
(setf (segment-current-index segment) (chooser-index note))
(setf (segment-current-posn segment) posn)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(setf (segment-last-annotation segment) prev)
(cond
((funcall (chooser-maybe-shrink note) segment posn delta)
(let ((new-size (- (segment-current-index segment)
(chooser-index note)))
(old-size (chooser-size note)))
(when (> new-size old-size)
(error "~S emitted ~D bytes, but claimed it's max was ~D"
note new-size old-size))
(let ((additional-delta (- old-size new-size)))
(when (< (find-alignment additional-delta)
(chooser-alignment note))
(error "~S shrunk by ~D bytes, but claimed that it ~
preserve ~D bits of alignment."
note additional-delta (chooser-alignment note)))
(incf delta additional-delta)
(emit-filler segment additional-delta))
(setf prev (segment-last-annotation segment))
(if prev
(setf (cdr prev) (cdr remaining))
(setf (segment-annotations segment)
(cdr remaining)))))
(t
(unless (= (segment-current-index segment) (chooser-index note))
(error "Chooser ~S passed, but not before emitting ~D bytes."
note
(- (segment-current-index segment)
(chooser-index note))))
(let ((size (chooser-size note)))
(incf (segment-current-index segment) size)
(incf (segment-current-posn segment) size))
(adjust-alignment-after-chooser segment note)
(setf prev remaining))))
((alignment-p note)
(unless (zerop (alignment-size note))
(let ((index (alignment-index note)))
(setf (segment-current-index segment) index)
(setf (segment-current-posn segment) posn)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(setf (segment-last-annotation segment) prev)
(emit-alignment segment nil (alignment-bits note)
(alignment-fill-byte note))
(let* ((new-index (segment-current-index segment))
(size (- new-index index))
(old-size (alignment-size note))
(additional-delta (- old-size size)))
(when (minusp additional-delta)
(error "Alignment ~S needs more space now? It was ~D, ~
and is ~D now."
note old-size size))
(when (plusp additional-delta)
(emit-filler segment additional-delta)
(incf delta additional-delta)))
(setf prev (segment-last-annotation segment))
(if prev
(setf (cdr prev) (cdr remaining))
(setf (segment-annotations segment)
(cdr remaining))))))
(t
(setf prev remaining)))))
(when (zerop delta)
(return))
(decf (segment-final-posn segment) delta)))
(ext:undefined-value))
(defun finalize-positions (segment)
(let ((delta 0))
(do* ((prev nil)
(remaining (segment-annotations segment) next)
(next (cdr remaining) (cdr remaining)))
((null remaining))
(let* ((note (car remaining))
(posn (- (annotation-posn note) delta)))
(cond
((alignment-p note)
(let* ((bits (alignment-bits note))
(mask (1- (ash 1 bits)))
(new-posn (logand (+ posn mask) (lognot mask)))
(size (- new-posn posn))
(old-size (alignment-size note))
(additional-delta (- old-size size)))
(assert (<= 0 size old-size))
(unless (zerop additional-delta)
(setf (segment-last-annotation segment) prev)
(incf delta additional-delta)
(setf (segment-current-index segment) (alignment-index note))
(setf (segment-current-posn segment) posn)
(emit-filler segment additional-delta)
(setf prev (segment-last-annotation segment)))
(if prev
(setf (cdr prev) next)
(setf (segment-annotations segment) next))))
(t
(setf (annotation-posn note) posn)
(setf prev remaining)
(setf next (cdr remaining))))))
(unless (zerop delta)
(decf (segment-final-posn segment) delta)))
(ext:undefined-value))
(defun process-back-patches (segment)
(do* ((prev nil)
(remaining (segment-annotations segment) next)
(next (cdr remaining) (cdr remaining)))
((null remaining))
(let ((note (car remaining)))
(flet ((fill-in (function old-size)
(let ((index (annotation-index note))
(posn (annotation-posn note)))
(setf (segment-current-index segment) index)
(setf (segment-current-posn segment) posn)
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(setf (segment-last-annotation segment) prev)
(funcall function segment posn)
(let ((new-size (- (segment-current-index segment) index)))
(unless (= new-size old-size)
(error "~S emitted ~D bytes, but claimed it's was ~D"
note new-size old-size)))
(let ((tail (segment-last-annotation segment)))
(if tail
(setf (cdr tail) next)
(setf (segment-annotations segment) next)))
(setf next (cdr prev)))))
(cond ((back-patch-p note)
(fill-in (back-patch-function note)
(back-patch-size note)))
((chooser-p note)
(fill-in (chooser-worst-case-fun note)
(chooser-size note)))
(t
(setf prev remaining)))))))
Interface to the rest of the compiler .
The holds the current segment while assembling . Use to change
(defvar *current-segment*)
Just like * CURRENT - SEGMENT * , but holds the current vop . Used only to keep
(defvar *current-vop* nil)
dereferencing the symbol . Given that is the only interface to
(defmacro assemble ((&optional segment vop &key labels) &body body
&environment env)
"Execute BODY (as a progn) with SEGMENT as the current segment."
(flet ((label-name-p (thing)
(and thing (symbolp thing))))
(let* ((seg-var (gensym "SEGMENT-"))
(vop-var (gensym "VOP-"))
(visable-labels (keep-if #'label-name-p body))
(inherited-labels
(multiple-value-bind
(expansion expanded)
(macroexpand '..inherited-labels.. env)
(if expanded expansion nil)))
(new-labels (append labels
(set-difference visable-labels
inherited-labels)))
(nested-labels (set-difference (append inherited-labels new-labels)
visable-labels)))
(when (intersection labels inherited-labels)
(error "Duplicate nested labels: ~S"
(intersection labels inherited-labels)))
`(let* ((,seg-var ,(or segment '*current-segment*))
(,vop-var ,(or vop '*current-vop*))
,@(when segment
`((*current-segment* ,seg-var)))
,@(when vop
`((*current-vop* ,vop-var)))
,@(mapcar #'(lambda (name)
`(,name (gen-label)))
new-labels))
(symbol-macrolet ((*current-segment* ,seg-var)
(*current-vop* ,vop-var)
,@(when (or inherited-labels nested-labels)
`((..inherited-labels.. ,nested-labels))))
,@(mapcar #'(lambda (form)
(if (label-name-p form)
`(emit-label ,form)
form))
body))))))
(defmacro inst (&whole whole instruction &rest args &environment env)
"Emit the specified instruction to the current segment."
(let ((inst (gethash (symbol-name instruction)
(assem-params-instructions
(c:backend-assembler-params c:*target-backend*)))))
(cond ((null inst)
(error "Unknown instruction: ~S" instruction))
((functionp inst)
(funcall inst (cdr whole) env))
(t
`(,inst *current-segment* *current-vop* ,@args)))))
(defmacro emit-label (label)
"Emit LABEL at this location in the current segment."
`(%emit-label *current-segment* *current-vop* ,label))
(defmacro emit-postit (function)
`(%emit-postit *current-segment* ,function))
(defmacro align (bits &optional (fill-byte 0))
"Emit an alignment restriction to the current segment."
`(emit-alignment *current-segment* *current-vop* ,bits ,fill-byte))
(defun label-position (label &optional if-after delta)
"Return the current position for LABEL. Chooser maybe-shrink functions
should supply IF-AFTER and DELTA to assure correct results."
(let ((posn (label-posn label)))
(if (and if-after (> posn if-after))
(- posn delta)
posn)))
(defun append-segment (segment other-segment)
"Append OTHER-SEGMENT to the end of SEGMENT. Don't use OTHER-SEGMENT
for anything after this."
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(let ((postits (segment-postits segment)))
(setf (segment-postits segment) (segment-postits other-segment))
(dolist (postit postits)
(emit-back-patch segment 0 postit)))
(if (c:backend-featurep :x86)
(emit-alignment segment nil max-alignment #x90)
(emit-alignment segment nil max-alignment))
(let ((offset-in-last-block (rem (segment-current-index segment)
output-block-size)))
(unless (zerop offset-in-last-block)
(emit-filler segment (- output-block-size offset-in-last-block))))
(let* ((blocks (segment-output-blocks segment))
(next-block-num (floor (segment-current-index segment)
output-block-size))
(other-blocks (segment-output-blocks other-segment)))
(setf blocks
(adjust-array blocks (+ next-block-num (length other-blocks))))
(setf (segment-output-blocks segment) blocks)
(replace blocks other-blocks :start1 next-block-num))
(let ((index-delta (segment-current-index segment))
(posn-delta (segment-current-posn segment))
(other-annotations (segment-annotations other-segment)))
(setf (segment-current-index segment)
(+ index-delta (segment-current-index other-segment)))
(setf (segment-current-posn segment)
(+ posn-delta (segment-current-posn other-segment)))
(setf (segment-fill-pointer segment) (system:int-sap 0))
(setf (segment-block-end segment) (system:int-sap 0))
(when other-annotations
(dolist (note other-annotations)
(incf (annotation-index note) index-delta)
(incf (annotation-posn note) posn-delta))
(let ((last (segment-last-annotation segment)))
(if last
(setf (cdr last) other-annotations)
(setf (segment-annotations segment) other-annotations))
(setf (segment-last-annotation segment)
(segment-last-annotation other-segment)))))
(ext:undefined-value))
(defun finalize-segment (segment)
"Does any final processing of SEGMENT and returns the total number of bytes
covered by this segment."
(when (segment-run-scheduler segment)
(schedule-pending-instructions segment))
(setf (segment-run-scheduler segment) nil)
FIX brand name
(setf (segment-postits segment) nil)
(dolist (postit postits)
(emit-back-patch segment 0 postit)))
(setf (segment-final-index segment) (segment-current-index segment))
(setf (segment-final-posn segment) (segment-current-posn segment))
(setf (segment-inst-hook segment) nil)
(compress-output segment)
(finalize-positions segment)
(process-back-patches segment)
(segment-final-posn segment))
(defun segment-map-output (segment function)
"Call FUNCTION on all the output accumulated in SEGMENT. FUNCTION is called
zero or more times with two arguments: a SAP and a number of bytes."
(let ((old-index 0)
(blocks (segment-output-blocks segment))
(sap (system:int-sap 0))
(end (system:int-sap 0)))
(labels ((map-until (index)
(unless (system:sap< sap end)
(multiple-value-bind
(block-num block-offset)
(floor old-index output-block-size)
(let ((block (aref blocks block-num)))
(setf sap (system:sap+ block block-offset))
(setf end (system:sap+ block output-block-size)))))
(let* ((desired (- index old-index))
(available (system:sap- end sap))
(amount (min desired available)))
(funcall function sap amount)
(incf old-index amount)
(setf sap (system:sap+ sap amount))
(when (< amount desired)
(map-until index)))))
(dolist (note (segment-annotations segment))
(when (filler-p note)
(let ((index (filler-index note)))
(when (< old-index index)
(map-until index)))
(let ((bytes (filler-bytes note)))
(incf old-index bytes)
(setf sap (system:sap+ sap bytes)))))
(let ((index (segment-final-index segment)))
(when (< old-index index)
(map-until index))))))
(defun release-segment (segment)
"Releases any output buffers held on to by segment."
(let ((blocks (segment-output-blocks segment)))
(loop
for block across blocks
do (when block
(release-output-block block))))
(ext:undefined-value))
Interface to the instruction set definition .
(defmacro define-emitter (name total-bits &rest byte-specs)
(ext:collect ((arg-names) (arg-types))
(let* ((total-bits (eval total-bits))
(overall-mask (ash -1 total-bits))
(num-bytes (multiple-value-bind
(quo rem)
(truncate total-bits assembly-unit-bits)
(unless (zerop rem)
(error "~D isn't an even multiple of ~D"
total-bits assembly-unit-bits))
quo))
(bytes (make-array num-bytes :initial-element nil))
(segment-arg (gensym "SEGMENT-")))
(dolist (byte-spec-expr byte-specs)
(let* ((byte-spec (eval byte-spec-expr))
(byte-size (byte-size byte-spec))
(byte-posn (byte-position byte-spec))
(arg (gensym (format nil "~:@(ARG-FOR-~S-~)" byte-spec-expr))))
(when (ldb-test (byte byte-size byte-posn) overall-mask)
(error "Byte spec ~S either overlaps another byte spec, or ~
extends past the end."
byte-spec-expr))
(setf (ldb byte-spec overall-mask) -1)
(arg-names arg)
(arg-types `(type (integer ,(ash -1 (1- byte-size))
,(1- (ash 1 byte-size)))
,arg))
(multiple-value-bind
(start-byte offset)
(floor byte-posn assembly-unit-bits)
(let ((end-byte (floor (1- (+ byte-posn byte-size))
assembly-unit-bits)))
(flet ((maybe-ash (expr offset)
(if (zerop offset)
expr
`(ash ,expr ,offset))))
(declare (inline maybe-ash))
(cond ((zerop byte-size))
((= start-byte end-byte)
(push (maybe-ash `(ldb (byte ,byte-size 0) ,arg)
offset)
(svref bytes start-byte)))
(t
(push (maybe-ash
`(ldb (byte ,(- assembly-unit-bits offset) 0)
,arg)
offset)
(svref bytes start-byte))
(do ((index (1+ start-byte) (1+ index)))
((>= index end-byte))
(push
`(ldb (byte ,assembly-unit-bits
,(- (* assembly-unit-bits
(- index start-byte))
offset))
,arg)
(svref bytes index)))
(let ((len (rem (+ byte-size offset)
assembly-unit-bits)))
(push
`(ldb (byte ,(if (zerop len)
assembly-unit-bits
len)
,(- (* assembly-unit-bits
(- end-byte start-byte))
offset))
,arg)
(svref bytes end-byte))))))))))
(unless (= overall-mask -1)
(error "There are holes."))
(let ((forms nil))
(dotimes (i num-bytes)
(let ((pieces (svref bytes i)))
(assert pieces)
(push `(emit-byte ,segment-arg
,(if (cdr pieces)
`(logior ,@pieces)
(car pieces)))
forms)))
`(defun ,name (,segment-arg ,@(arg-names))
(declare (type segment ,segment-arg) ,@(arg-types))
,@(ecase (c:backend-byte-order c:*target-backend*)
(:little-endian (nreverse forms))
(:big-endian forms))
',name)))))
(defun grovel-lambda-list (lambda-list vop-var)
(let ((segment-name (car lambda-list))
(vop-var (or vop-var (gensym "VOP-"))))
(ext:collect ((new-lambda-list))
(new-lambda-list segment-name)
(new-lambda-list vop-var)
(labels
((grovel (state lambda-list)
(when lambda-list
(let ((param (car lambda-list)))
(cond
((member param lambda-list-keywords)
(new-lambda-list param)
(grovel param (cdr lambda-list)))
(t
(ecase state
((nil)
(new-lambda-list param)
`(cons ,param ,(grovel state (cdr lambda-list))))
(&optional
(multiple-value-bind
(name default supplied-p)
(if (consp param)
(values (first param)
(second param)
(or (third param)
(gensym "SUPPLIED-P-")))
(values param nil (gensym "SUPPLIED-P-")))
(new-lambda-list (list name default supplied-p))
`(and ,supplied-p
(cons ,(if (consp name)
(second name)
name)
,(grovel state (cdr lambda-list))))))
(&key
(multiple-value-bind
(name default supplied-p)
(if (consp param)
(values (first param)
(second param)
(or (third param)
(gensym "SUPPLIED-P-")))
(values param nil (gensym "SUPPLIED-P-")))
(new-lambda-list (list name default supplied-p))
(multiple-value-bind
(key var)
(if (consp name)
(values (first name) (second name))
(values (intern (symbol-name name) :keyword)
name))
`(append (and ,supplied-p (list ',key ,var))
,(grovel state (cdr lambda-list))))))
(&rest
(new-lambda-list param)
(grovel state (cdr lambda-list))
param))))))))
(let ((reconstructor (grovel nil (cdr lambda-list))))
(values (new-lambda-list)
segment-name
vop-var
reconstructor))))))
(defun extract-nths (index glue list-of-lists-of-lists)
(mapcar #'(lambda (list-of-lists)
(cons glue
(mapcar #'(lambda (list)
(nth index list))
list-of-lists)))
list-of-lists-of-lists))
(defmacro define-instruction (name lambda-list &rest options)
(let* ((sym-name (symbol-name name))
(defun-name (ext:symbolicate sym-name "-INST-EMITTER"))
(vop-var nil)
(postits (gensym "POSTITS-"))
(emitter nil)
(decls nil)
(attributes nil)
(cost nil)
(dependencies nil)
(delay nil)
(pinned nil)
(pdefs nil))
(dolist (option-spec options)
(multiple-value-bind
(option args)
(if (consp option-spec)
(values (car option-spec) (cdr option-spec))
(values option-spec nil))
(case option
(:emitter
(when emitter
(error "Can only specify one emitter per instruction."))
(setf emitter args))
(:declare
(setf decls (append decls args)))
(:attributes
(setf attributes (append attributes args)))
(:cost
(setf cost (first args)))
(:dependencies
(setf dependencies (append dependencies args)))
(:delay
(when delay
(error "Can only specify delay once per instruction."))
(setf delay args))
(:pinned
(setf pinned t))
(:vop-var
(if vop-var
(error "Can only specify :vop-var once.")
(setf vop-var (car args))))
(:printer
(push
(eval
`(list
(multiple-value-list
,(disassem:gen-printer-def-forms-def-form name
(cdr option-spec)))))
pdefs))
(:printer-list
same as : printer , but is evaled first , and is a list of printers
(push
(eval
`(eval
`(list ,@(mapcar #'(lambda (printer)
`(multiple-value-list
,(disassem:gen-printer-def-forms-def-form
',name printer nil)))
,(cadr option-spec)))))
pdefs))
(t
(error "Unknown option: ~S" option)))))
(setf pdefs (nreverse pdefs))
(multiple-value-bind
(new-lambda-list segment-name vop-name arg-reconstructor)
(grovel-lambda-list lambda-list vop-var)
(push `(let ((hook (segment-inst-hook ,segment-name)))
(when hook
(funcall hook ,segment-name ,vop-name ,sym-name
,arg-reconstructor)))
emitter)
(push `(dolist (postit ,postits)
(emit-back-patch ,segment-name 0 postit))
emitter)
(unless cost (setf cost 1))
(push `(when (segment-collect-dynamic-statistics ,segment-name)
(let* ((info (c:ir2-component-dyncount-info
(c:component-info c:*compile-component*)))
(costs (c:dyncount-info-costs info))
(block-number (c:block-number
(c:ir2-block-block
(c:vop-block ,vop-name)))))
(incf (aref costs block-number) ,cost)))
emitter)
(when (assem-params-scheduler-p
(c:backend-assembler-params c:*target-backend*))
(if pinned
(setf emitter
`((when (segment-run-scheduler ,segment-name)
(schedule-pending-instructions ,segment-name))
,@emitter))
(let ((flet-name
(gensym (concatenate 'string "EMIT-" sym-name "-INST-")))
(inst-name (gensym "INST-")))
(setf emitter `((flet ((,flet-name (,segment-name)
,@emitter))
(if (segment-run-scheduler ,segment-name)
(let ((,inst-name
(make-instruction
(incf (segment-inst-number
,segment-name))
#',flet-name
(instruction-attributes
,@attributes)
(progn ,@delay))))
,@(when dependencies
`((note-dependencies
(,segment-name ,inst-name)
,@dependencies)))
(queue-inst ,segment-name ,inst-name))
(,flet-name ,segment-name))))))))
`(progn
(defun ,defun-name ,new-lambda-list
,@(when decls
`((declare ,@decls)))
(let ((,postits (segment-postits ,segment-name)))
(setf (segment-postits ,segment-name) nil)
(symbol-macrolet
((*current-segment*
(macrolet ((lose ()
(error "Can't use INST without an ASSEMBLE ~
inside emitters.")))
(lose))))
,@emitter))
(ext:undefined-value))
(eval-when (compile load eval)
(%define-instruction ,sym-name ',defun-name))
,@(extract-nths 1 'progn pdefs)
,@(when pdefs
`((disassem:install-inst-flavors
',name
(append ,@(extract-nths 0 'list pdefs)))))))))
(defmacro define-instruction-macro (name lambda-list &body body)
(let ((whole (gensym "WHOLE-"))
(env (gensym "ENV-")))
(multiple-value-bind
(body local-defs)
(lisp::parse-defmacro lambda-list whole body name 'instruction-macro
:environment env)
`(eval-when (compile load eval)
(%define-instruction ,(symbol-name name)
#'(lambda (,whole ,env)
,@local-defs
(block ,name
,body)))))))
(defun %define-instruction (name defun)
(setf (gethash name
(assem-params-instructions
(c:backend-assembler-params c:*target-backend*)))
defun)
name)
|
8664754ff23849fa008156e553d87a2829912c23edb3184d28ea2072eb8936c1 | jafingerhut/clojure-benchmarks | nbody.clj-10.clj | Author : ( )
Date : Aug 10 , 2009
(ns nbody
(:gen-class))
(set! *warn-on-reflection* true)
(defmacro mass [p] `(double (aget ~p 0)))
(defmacro posx [p] `(double (aget ~p 1)))
(defmacro posy [p] `(double (aget ~p 2)))
(defmacro posz [p] `(double (aget ~p 3)))
(defmacro velx [p] `(double (aget ~p 4)))
(defmacro vely [p] `(double (aget ~p 5)))
(defmacro velz [p] `(double (aget ~p 6)))
(defmacro set-mass! [p new-mass] `(aset-double ~p 0 ~new-mass))
(defmacro set-posx! [p new-posx] `(aset-double ~p 1 ~new-posx))
(defmacro set-posy! [p new-posy] `(aset-double ~p 2 ~new-posy))
(defmacro set-posz! [p new-posz] `(aset-double ~p 3 ~new-posz))
(defmacro set-velx! [p new-velx] `(aset-double ~p 4 ~new-velx))
(defmacro set-vely! [p new-vely] `(aset-double ~p 5 ~new-vely))
(defmacro set-velz! [p new-velz] `(aset-double ~p 6 ~new-velz))
(defn planet-construct [p]
;; Don't bother keeping the name around
(let [p-arr (make-array Double/TYPE 7)]
(set-mass! p-arr (:mass p))
(set-posx! p-arr ((:pos p) 0))
(set-posy! p-arr ((:pos p) 1))
(set-posz! p-arr ((:pos p) 2))
(set-velx! p-arr ((:velocity p) 0))
(set-vely! p-arr ((:velocity p) 1))
(set-velz! p-arr ((:velocity p) 2))
p-arr))
(defn offset-momentum [bodies]
(let [n (int (count bodies))]
(loop [momx (double 0.0)
momy (double 0.0)
momz (double 0.0)
i (int 0)]
(if (< i n)
(let [b (bodies i)
m (mass b)]
(recur (+ momx (* m (velx b)))
(+ momy (* m (vely b)))
(+ momz (* m (velz b)))
(unchecked-inc i)))
[momx momy momz]))))
(defn n-body-system []
(let [PI (double 3.141592653589793)
SOLAR-MASS (double (* (double 4) PI PI))
DAYS-PER-YEAR (double 365.24)
bodies
(to-array
[ (planet-construct
{:name "sun"
:mass SOLAR-MASS
:pos [0 0 0]
:velocity [0 0 0]})
(planet-construct
{:name "jupiter"
:mass (double (* 9.54791938424326609e-04 SOLAR-MASS))
:pos [(double 4.84143144246472090e+00)
(double -1.16032004402742839e+00)
(double -1.03622044471123109e-01)]
:velocity [(double (* 1.66007664274403694e-03 DAYS-PER-YEAR))
(double (* 7.69901118419740425e-03 DAYS-PER-YEAR))
(double (* -6.90460016972063023e-05 DAYS-PER-YEAR))]})
(planet-construct
{:name "saturn"
:mass (double (* 2.85885980666130812e-04 SOLAR-MASS))
:pos [(double 8.34336671824457987e+00)
(double 4.12479856412430479e+00)
(double -4.03523417114321381e-01)]
:velocity [(double (* -2.76742510726862411e-03 DAYS-PER-YEAR))
(double (* 4.99852801234917238e-03 DAYS-PER-YEAR))
(double (* 2.30417297573763929e-05 DAYS-PER-YEAR))]})
(planet-construct
{:name "uranus"
:mass (double (* 4.36624404335156298e-05 SOLAR-MASS))
:pos [(double 1.28943695621391310e+01)
(double -1.51111514016986312e+01)
(double -2.23307578892655734e-01)]
:velocity [(double (* 2.96460137564761618e-03 DAYS-PER-YEAR))
(double (* 2.37847173959480950e-03 DAYS-PER-YEAR))
(double (* -2.96589568540237556e-05 DAYS-PER-YEAR))]})
(planet-construct
{:name "neptune"
:mass (double (* 5.15138902046611451e-05 SOLAR-MASS))
:pos [(double 1.53796971148509165e+01)
(double -2.59193146099879641e+01)
(double 1.79258772950371181e-01)]
:velocity [(double (* 2.68067772490389322e-03 DAYS-PER-YEAR))
(double (* 1.62824170038242295e-03 DAYS-PER-YEAR))
(double (* -9.51592254519715870e-05 DAYS-PER-YEAR))]})
])]
(let [[momx momy momz] (offset-momentum (vec bodies))
a (double (/ -1.0 SOLAR-MASS))
sun-index 0
sun (aget bodies sun-index)]
(set-velx! sun (* a momx))
(set-vely! sun (* a momy))
(set-velz! sun (* a momz))
(aset bodies sun-index sun)
bodies)))
(defn kinetic-energy-1 [body]
(* (double 0.5) (mass body)
(+ (* (velx body) (velx body))
(* (vely body) (vely body))
(* (velz body) (velz body)))))
(defn kinetic-energy [bodies]
(reduce + (map kinetic-energy-1 bodies)))
(defn distance-between [b1 b2]
(let [dx (double (- (posx b1) (posx b2)))
dy (double (- (posy b1) (posy b2)))
dz (double (- (posz b1) (posz b2)))]
(Math/sqrt (+ (* dx dx) (* dy dy) (* dz dz)))))
(defn all-seq-ordered-pairs [s]
(loop [s1 (seq s)
pairs ()]
(if s1
(let [s1item (first s1)]
(recur (next s1)
(into pairs (map (fn [s2item] [s1item s2item]) (next s1)))))
pairs)))
(defn potential-energy-body-pair [[b1 b2]]
(let [distance (distance-between b1 b2)]
(/ (* (mass b1) (mass b2))
distance)))
(defn potential-energy [bodies]
(- (reduce + (map potential-energy-body-pair
(all-seq-ordered-pairs bodies)))))
(defn energy [bodies]
Yes , we do n't want to create vec 's from bodies all the time , but
;; recall that this function is only called twice during the whole
;; program. advance! and what it calls are the real hot spot.
(let [v (vec bodies)]
(+ (kinetic-energy v) (potential-energy v))))
(defmacro add-to-vel! [#^doubles body delta-vx delta-vy delta-vz]
`(do
(set-velx! ~body (+ (velx ~body) ~delta-vx))
(set-vely! ~body (+ (vely ~body) ~delta-vy))
(set-velz! ~body (+ (velz ~body) ~delta-vz))))
(defn bodies-update-velocities! [#^"[Ljava.lang.Object;" bodies delta-t]
(let [n (int (alength bodies))
n-1 (int (dec n))
delta-t (double delta-t)]
(loop [i1 (int 0)]
(if (< i1 n-1)
(let [#^doubles b1 (aget bodies i1)]
(loop [i2 (int (inc i1))]
(if (< i2 n)
(let [#^doubles b2 (aget bodies i2)
delta-posx (- (posx b1) (posx b2))
delta-posy (- (posy b1) (posy b2))
delta-posz (- (posz b1) (posz b2))
dist-squared (+ (+ (* delta-posx delta-posx)
(* delta-posy delta-posy))
(* delta-posz delta-posz))
dist (Math/sqrt dist-squared)
mag (/ (/ delta-t dist-squared) dist)
b1-scale (* (- mag) (mass b2))
dv1x (* delta-posx b1-scale)
dv1y (* delta-posy b1-scale)
dv1z (* delta-posz b1-scale)
b2-scale (* mag (mass b1))
dv2x (* delta-posx b2-scale)
dv2y (* delta-posy b2-scale)
dv2z (* delta-posz b2-scale)]
(add-to-vel! b1 dv1x dv1y dv1z)
(add-to-vel! b2 dv2x dv2y dv2z)
(recur (unchecked-inc i2)))))
(recur (unchecked-inc i1)))))))
(defn bodies-update-positions! [#^"[Ljava.lang.Object;" bodies delta-t]
(let [n (int (alength bodies))
delta-t (double delta-t)]
(loop [i (int 0)]
(if (< i n)
(let [#^doubles b (aget bodies i)]
(set-posx! b (+ (posx b) (* (velx b) delta-t)))
(set-posy! b (+ (posy b) (* (vely b) delta-t)))
(set-posz! b (+ (posz b) (* (velz b) delta-t)))
(recur (unchecked-inc i)))))))
(defn advance! [bodies delta-t]
(bodies-update-velocities! bodies delta-t)
(bodies-update-positions! bodies delta-t))
(defn usage [exit-code]
(printf "usage: %s n\n" *file*)
(printf " n, a positive integer, is the number of simulation steps to run\n")
(flush)
(. System (exit exit-code)))
(defn -main [& args]
(when (not= (count args) 1)
(usage 1))
(def n
(let [arg (nth args 0)]
(when (not (re-matches #"^\d+$" arg))
(usage 1))
(let [temp (. Integer valueOf arg 10)]
(when (< temp 1)
(usage 1))
temp)))
(let [bodies (n-body-system)
delta-t (double 0.01)]
(printf "%.9f\n" (energy bodies))
(loop [i (int n)]
(if (zero? i)
(printf "%.9f\n" (energy bodies))
(do
(advance! bodies delta-t)
(recur (unchecked-dec i))))))
(flush))
| null | https://raw.githubusercontent.com/jafingerhut/clojure-benchmarks/474a8a4823727dd371f1baa9809517f9e0b508d4/nbody/nbody.clj-10.clj | clojure | Don't bother keeping the name around
recall that this function is only called twice during the whole
program. advance! and what it calls are the real hot spot. | Author : ( )
Date : Aug 10 , 2009
(ns nbody
(:gen-class))
(set! *warn-on-reflection* true)
(defmacro mass [p] `(double (aget ~p 0)))
(defmacro posx [p] `(double (aget ~p 1)))
(defmacro posy [p] `(double (aget ~p 2)))
(defmacro posz [p] `(double (aget ~p 3)))
(defmacro velx [p] `(double (aget ~p 4)))
(defmacro vely [p] `(double (aget ~p 5)))
(defmacro velz [p] `(double (aget ~p 6)))
(defmacro set-mass! [p new-mass] `(aset-double ~p 0 ~new-mass))
(defmacro set-posx! [p new-posx] `(aset-double ~p 1 ~new-posx))
(defmacro set-posy! [p new-posy] `(aset-double ~p 2 ~new-posy))
(defmacro set-posz! [p new-posz] `(aset-double ~p 3 ~new-posz))
(defmacro set-velx! [p new-velx] `(aset-double ~p 4 ~new-velx))
(defmacro set-vely! [p new-vely] `(aset-double ~p 5 ~new-vely))
(defmacro set-velz! [p new-velz] `(aset-double ~p 6 ~new-velz))
(defn planet-construct [p]
(let [p-arr (make-array Double/TYPE 7)]
(set-mass! p-arr (:mass p))
(set-posx! p-arr ((:pos p) 0))
(set-posy! p-arr ((:pos p) 1))
(set-posz! p-arr ((:pos p) 2))
(set-velx! p-arr ((:velocity p) 0))
(set-vely! p-arr ((:velocity p) 1))
(set-velz! p-arr ((:velocity p) 2))
p-arr))
(defn offset-momentum [bodies]
(let [n (int (count bodies))]
(loop [momx (double 0.0)
momy (double 0.0)
momz (double 0.0)
i (int 0)]
(if (< i n)
(let [b (bodies i)
m (mass b)]
(recur (+ momx (* m (velx b)))
(+ momy (* m (vely b)))
(+ momz (* m (velz b)))
(unchecked-inc i)))
[momx momy momz]))))
(defn n-body-system []
(let [PI (double 3.141592653589793)
SOLAR-MASS (double (* (double 4) PI PI))
DAYS-PER-YEAR (double 365.24)
bodies
(to-array
[ (planet-construct
{:name "sun"
:mass SOLAR-MASS
:pos [0 0 0]
:velocity [0 0 0]})
(planet-construct
{:name "jupiter"
:mass (double (* 9.54791938424326609e-04 SOLAR-MASS))
:pos [(double 4.84143144246472090e+00)
(double -1.16032004402742839e+00)
(double -1.03622044471123109e-01)]
:velocity [(double (* 1.66007664274403694e-03 DAYS-PER-YEAR))
(double (* 7.69901118419740425e-03 DAYS-PER-YEAR))
(double (* -6.90460016972063023e-05 DAYS-PER-YEAR))]})
(planet-construct
{:name "saturn"
:mass (double (* 2.85885980666130812e-04 SOLAR-MASS))
:pos [(double 8.34336671824457987e+00)
(double 4.12479856412430479e+00)
(double -4.03523417114321381e-01)]
:velocity [(double (* -2.76742510726862411e-03 DAYS-PER-YEAR))
(double (* 4.99852801234917238e-03 DAYS-PER-YEAR))
(double (* 2.30417297573763929e-05 DAYS-PER-YEAR))]})
(planet-construct
{:name "uranus"
:mass (double (* 4.36624404335156298e-05 SOLAR-MASS))
:pos [(double 1.28943695621391310e+01)
(double -1.51111514016986312e+01)
(double -2.23307578892655734e-01)]
:velocity [(double (* 2.96460137564761618e-03 DAYS-PER-YEAR))
(double (* 2.37847173959480950e-03 DAYS-PER-YEAR))
(double (* -2.96589568540237556e-05 DAYS-PER-YEAR))]})
(planet-construct
{:name "neptune"
:mass (double (* 5.15138902046611451e-05 SOLAR-MASS))
:pos [(double 1.53796971148509165e+01)
(double -2.59193146099879641e+01)
(double 1.79258772950371181e-01)]
:velocity [(double (* 2.68067772490389322e-03 DAYS-PER-YEAR))
(double (* 1.62824170038242295e-03 DAYS-PER-YEAR))
(double (* -9.51592254519715870e-05 DAYS-PER-YEAR))]})
])]
(let [[momx momy momz] (offset-momentum (vec bodies))
a (double (/ -1.0 SOLAR-MASS))
sun-index 0
sun (aget bodies sun-index)]
(set-velx! sun (* a momx))
(set-vely! sun (* a momy))
(set-velz! sun (* a momz))
(aset bodies sun-index sun)
bodies)))
(defn kinetic-energy-1 [body]
(* (double 0.5) (mass body)
(+ (* (velx body) (velx body))
(* (vely body) (vely body))
(* (velz body) (velz body)))))
(defn kinetic-energy [bodies]
(reduce + (map kinetic-energy-1 bodies)))
(defn distance-between [b1 b2]
(let [dx (double (- (posx b1) (posx b2)))
dy (double (- (posy b1) (posy b2)))
dz (double (- (posz b1) (posz b2)))]
(Math/sqrt (+ (* dx dx) (* dy dy) (* dz dz)))))
(defn all-seq-ordered-pairs [s]
(loop [s1 (seq s)
pairs ()]
(if s1
(let [s1item (first s1)]
(recur (next s1)
(into pairs (map (fn [s2item] [s1item s2item]) (next s1)))))
pairs)))
(defn potential-energy-body-pair [[b1 b2]]
(let [distance (distance-between b1 b2)]
(/ (* (mass b1) (mass b2))
distance)))
(defn potential-energy [bodies]
(- (reduce + (map potential-energy-body-pair
(all-seq-ordered-pairs bodies)))))
(defn energy [bodies]
Yes , we do n't want to create vec 's from bodies all the time , but
(let [v (vec bodies)]
(+ (kinetic-energy v) (potential-energy v))))
(defmacro add-to-vel! [#^doubles body delta-vx delta-vy delta-vz]
`(do
(set-velx! ~body (+ (velx ~body) ~delta-vx))
(set-vely! ~body (+ (vely ~body) ~delta-vy))
(set-velz! ~body (+ (velz ~body) ~delta-vz))))
(defn bodies-update-velocities! [#^"[Ljava.lang.Object;" bodies delta-t]
(let [n (int (alength bodies))
n-1 (int (dec n))
delta-t (double delta-t)]
(loop [i1 (int 0)]
(if (< i1 n-1)
(let [#^doubles b1 (aget bodies i1)]
(loop [i2 (int (inc i1))]
(if (< i2 n)
(let [#^doubles b2 (aget bodies i2)
delta-posx (- (posx b1) (posx b2))
delta-posy (- (posy b1) (posy b2))
delta-posz (- (posz b1) (posz b2))
dist-squared (+ (+ (* delta-posx delta-posx)
(* delta-posy delta-posy))
(* delta-posz delta-posz))
dist (Math/sqrt dist-squared)
mag (/ (/ delta-t dist-squared) dist)
b1-scale (* (- mag) (mass b2))
dv1x (* delta-posx b1-scale)
dv1y (* delta-posy b1-scale)
dv1z (* delta-posz b1-scale)
b2-scale (* mag (mass b1))
dv2x (* delta-posx b2-scale)
dv2y (* delta-posy b2-scale)
dv2z (* delta-posz b2-scale)]
(add-to-vel! b1 dv1x dv1y dv1z)
(add-to-vel! b2 dv2x dv2y dv2z)
(recur (unchecked-inc i2)))))
(recur (unchecked-inc i1)))))))
(defn bodies-update-positions! [#^"[Ljava.lang.Object;" bodies delta-t]
(let [n (int (alength bodies))
delta-t (double delta-t)]
(loop [i (int 0)]
(if (< i n)
(let [#^doubles b (aget bodies i)]
(set-posx! b (+ (posx b) (* (velx b) delta-t)))
(set-posy! b (+ (posy b) (* (vely b) delta-t)))
(set-posz! b (+ (posz b) (* (velz b) delta-t)))
(recur (unchecked-inc i)))))))
(defn advance! [bodies delta-t]
(bodies-update-velocities! bodies delta-t)
(bodies-update-positions! bodies delta-t))
(defn usage [exit-code]
(printf "usage: %s n\n" *file*)
(printf " n, a positive integer, is the number of simulation steps to run\n")
(flush)
(. System (exit exit-code)))
(defn -main [& args]
(when (not= (count args) 1)
(usage 1))
(def n
(let [arg (nth args 0)]
(when (not (re-matches #"^\d+$" arg))
(usage 1))
(let [temp (. Integer valueOf arg 10)]
(when (< temp 1)
(usage 1))
temp)))
(let [bodies (n-body-system)
delta-t (double 0.01)]
(printf "%.9f\n" (energy bodies))
(loop [i (int n)]
(if (zero? i)
(printf "%.9f\n" (energy bodies))
(do
(advance! bodies delta-t)
(recur (unchecked-dec i))))))
(flush))
|
28c8e5265a18d27727006bfae5bceb0b19c84994c75b6ccd13bb5cdff2c3725a | wadehennessey/wcl | bufmac.lisp | -*- Mode : LISP ; Syntax : Common - lisp ; Package : XLIB ; Base : 10 ; Lowercase : Yes -*-
This file contains macro definitions for the BUFFER object for Common - Lisp
X windows version 11
;;;
TEXAS INSTRUMENTS INCORPORATED
;;; P.O. BOX 2909
AUSTIN , TEXAS 78769
;;;
Copyright ( C ) 1987 Texas Instruments Incorporated .
;;;
;;; Permission is granted to any individual or institution to use, copy, modify,
;;; and distribute this software, provided that this complete copyright and
;;; permission notice is maintained, intact, in all copies and supporting
;;; documentation.
;;;
Texas Instruments Incorporated provides this software " as is " without
;;; express or implied warranty.
;;;
(in-package :xlib)
;;; The read- macros are in buffer.lisp, because event-case depends on (most of) them.
(defmacro write-card8 (byte-index item)
`(aset-card8 (the card8 ,item) buffer-bbuf (index+ buffer-boffset ,byte-index)))
(defmacro write-int8 (byte-index item)
`(aset-int8 (the int8 ,item)
buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-card16 (byte-index item)
#+clx-overlapping-arrays
`(aset-card16 (the card16 ,item) buffer-wbuf
(index+ buffer-woffset (index-ash ,byte-index -1)))
#-clx-overlapping-arrays
`(aset-card16 (the card16 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-int16 (byte-index item)
#+clx-overlapping-arrays
`(aset-int16 (the int16 ,item) buffer-wbuf
(index+ buffer-woffset (index-ash ,byte-index -1)))
#-clx-overlapping-arrays
`(aset-int16 (the int16 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-card32 (byte-index item)
#+clx-overlapping-arrays
`(aset-card32 (the card32 ,item) buffer-lbuf
(index+ buffer-loffset (index-ash ,byte-index -2)))
#-clx-overlapping-arrays
`(aset-card32 (the card32 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-int32 (byte-index item)
#+clx-overlapping-arrays
`(aset-int32 (the int32 ,item) buffer-lbuf
(index+ buffer-loffset (index-ash ,byte-index -2)))
#-clx-overlapping-arrays
`(aset-int32 (the int32 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-card29 (byte-index item)
#+clx-overlapping-arrays
`(aset-card29 (the card29 ,item) buffer-lbuf
(index+ buffer-loffset (index-ash ,byte-index -2)))
#-clx-overlapping-arrays
`(aset-card29 (the card29 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
This is used for 2 - byte characters , which may not be aligned on 2 - byte boundaries
and always are written high - order byte first .
(defmacro write-char2b (byte-index item)
;; It is impossible to do an overlapping write, so only nonoverlapping here.
`(let ((%item ,item)
(%byte-index (index+ buffer-boffset ,byte-index)))
(declare (type card16 %item)
(type array-index %byte-index))
(aset-card8 (the card8 (ldb (byte 8 8) %item)) buffer-bbuf %byte-index)
(aset-card8 (the card8 (ldb (byte 8 0) %item)) buffer-bbuf (index+ %byte-index 1))))
(defmacro set-buffer-offset (value &environment env)
env
`(let ((.boffset. ,value))
(declare (type array-index .boffset.))
(setq buffer-boffset .boffset.)
#+clx-overlapping-arrays
,@(when (member 16 (macroexpand '(%buffer-sizes) env))
`((setq buffer-woffset (index-ash .boffset. -1))))
#+clx-overlapping-arrays
,@(when (member 32 (macroexpand '(%buffer-sizes) env))
`((setq buffer-loffset (index-ash .boffset. -2))))
#+clx-overlapping-arrays
.boffset.))
(defmacro advance-buffer-offset (value)
`(set-buffer-offset (index+ buffer-boffset ,value)))
(defmacro with-buffer-output ((buffer &key (sizes '(8 16 32)) length index) &body body)
(unless (listp sizes) (setq sizes (list sizes)))
`(let ((%buffer ,buffer))
(declare (type display %buffer))
,(declare-bufmac)
,(when length
`(when (index>= (index+ (buffer-boffset %buffer) ,length) (buffer-size %buffer))
(buffer-flush %buffer)))
(let* ((buffer-boffset (the array-index ,(or index `(buffer-boffset %buffer))))
#-clx-overlapping-arrays
(buffer-bbuf (buffer-obuf8 %buffer))
#+clx-overlapping-arrays
,@(append
(when (member 8 sizes)
`((buffer-bbuf (buffer-obuf8 %buffer))))
(when (or (member 16 sizes) (member 160 sizes))
`((buffer-woffset (index-ash buffer-boffset -1))
(buffer-wbuf (buffer-obuf16 %buffer))))
(when (member 32 sizes)
`((buffer-loffset (index-ash buffer-boffset -2))
(buffer-lbuf (buffer-obuf32 %buffer))))))
(declare (type array-index buffer-boffset))
#-clx-overlapping-arrays
(declare (type buffer-bytes buffer-bbuf)
(array-register buffer-bbuf))
#+clx-overlapping-arrays
,@(append
(when (member 8 sizes)
'((declare (type buffer-bytes buffer-bbuf)
(array-register buffer-bbuf))))
(when (member 16 sizes)
'((declare (type array-index buffer-woffset))
(declare (type buffer-words buffer-wbuf)
(array-register buffer-wbuf))))
(when (member 32 sizes)
'((declare (type array-index buffer-loffset))
(declare (type buffer-longs buffer-lbuf)
(array-register buffer-lbuf)))))
buffer-boffset
#-clx-overlapping-arrays
buffer-bbuf
#+clx-overlapping-arrays
,@(append
(when (member 8 sizes) '(buffer-bbuf))
(when (member 16 sizes) '(buffer-woffset buffer-wbuf))
(when (member 32 sizes) '(buffer-loffset buffer-lbuf)))
#+clx-overlapping-arrays
(macrolet ((%buffer-sizes () ',sizes))
,@body)
#-clx-overlapping-arrays
,@body)))
;;; This macro is just used internally in buffer
(defmacro writing-buffer-chunks (type args decls &body body)
(when (> (length body) 2)
(error "writing-buffer-chunks called with too many forms"))
(let* ((size (* 8 (index-increment type)))
(form #-clx-overlapping-arrays
(first body)
#+clx-overlapping-arrays ; XXX type dependencies
(or (second body)
(first body))))
`(with-buffer-output (buffer :index boffset :sizes ,(reverse (adjoin size '(8))))
;; Loop filling the buffer
(do* (,@args
;; Number of bytes needed to output
(len ,(if (= size 8)
`(index- end start)
`(index-ash (index- end start) ,(truncate size 16)))
(index- len chunk))
;; Number of bytes available in buffer
(chunk (index-min len (index- (buffer-size buffer) buffer-boffset))
(index-min len (index- (buffer-size buffer) buffer-boffset))))
((not (index-plusp len)))
(declare ,@decls
(type array-index len chunk))
,form
(index-incf buffer-boffset chunk)
;; Flush the buffer
(when (and (index-plusp len) (index>= buffer-boffset (buffer-size buffer)))
(setf (buffer-boffset buffer) buffer-boffset)
(buffer-flush buffer)
(setq buffer-boffset (buffer-boffset buffer))
#+clx-overlapping-arrays
,(case size
(16 '(setq buffer-woffset (index-ash buffer-boffset -1)))
(32 '(setq buffer-loffset (index-ash buffer-boffset -2))))))
(setf (buffer-boffset buffer) (lround buffer-boffset)))))
| null | https://raw.githubusercontent.com/wadehennessey/wcl/841316ffe06743d4c14b4ed70819bdb39158df6a/src/clx/bufmac.lisp | lisp | Syntax : Common - lisp ; Package : XLIB ; Base : 10 ; Lowercase : Yes -*-
P.O. BOX 2909
Permission is granted to any individual or institution to use, copy, modify,
and distribute this software, provided that this complete copyright and
permission notice is maintained, intact, in all copies and supporting
documentation.
express or implied warranty.
The read- macros are in buffer.lisp, because event-case depends on (most of) them.
It is impossible to do an overlapping write, so only nonoverlapping here.
This macro is just used internally in buffer
XXX type dependencies
Loop filling the buffer
Number of bytes needed to output
Number of bytes available in buffer
Flush the buffer |
This file contains macro definitions for the BUFFER object for Common - Lisp
X windows version 11
TEXAS INSTRUMENTS INCORPORATED
AUSTIN , TEXAS 78769
Copyright ( C ) 1987 Texas Instruments Incorporated .
Texas Instruments Incorporated provides this software " as is " without
(in-package :xlib)
(defmacro write-card8 (byte-index item)
`(aset-card8 (the card8 ,item) buffer-bbuf (index+ buffer-boffset ,byte-index)))
(defmacro write-int8 (byte-index item)
`(aset-int8 (the int8 ,item)
buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-card16 (byte-index item)
#+clx-overlapping-arrays
`(aset-card16 (the card16 ,item) buffer-wbuf
(index+ buffer-woffset (index-ash ,byte-index -1)))
#-clx-overlapping-arrays
`(aset-card16 (the card16 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-int16 (byte-index item)
#+clx-overlapping-arrays
`(aset-int16 (the int16 ,item) buffer-wbuf
(index+ buffer-woffset (index-ash ,byte-index -1)))
#-clx-overlapping-arrays
`(aset-int16 (the int16 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-card32 (byte-index item)
#+clx-overlapping-arrays
`(aset-card32 (the card32 ,item) buffer-lbuf
(index+ buffer-loffset (index-ash ,byte-index -2)))
#-clx-overlapping-arrays
`(aset-card32 (the card32 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-int32 (byte-index item)
#+clx-overlapping-arrays
`(aset-int32 (the int32 ,item) buffer-lbuf
(index+ buffer-loffset (index-ash ,byte-index -2)))
#-clx-overlapping-arrays
`(aset-int32 (the int32 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
(defmacro write-card29 (byte-index item)
#+clx-overlapping-arrays
`(aset-card29 (the card29 ,item) buffer-lbuf
(index+ buffer-loffset (index-ash ,byte-index -2)))
#-clx-overlapping-arrays
`(aset-card29 (the card29 ,item) buffer-bbuf
(index+ buffer-boffset ,byte-index)))
This is used for 2 - byte characters , which may not be aligned on 2 - byte boundaries
and always are written high - order byte first .
(defmacro write-char2b (byte-index item)
`(let ((%item ,item)
(%byte-index (index+ buffer-boffset ,byte-index)))
(declare (type card16 %item)
(type array-index %byte-index))
(aset-card8 (the card8 (ldb (byte 8 8) %item)) buffer-bbuf %byte-index)
(aset-card8 (the card8 (ldb (byte 8 0) %item)) buffer-bbuf (index+ %byte-index 1))))
(defmacro set-buffer-offset (value &environment env)
env
`(let ((.boffset. ,value))
(declare (type array-index .boffset.))
(setq buffer-boffset .boffset.)
#+clx-overlapping-arrays
,@(when (member 16 (macroexpand '(%buffer-sizes) env))
`((setq buffer-woffset (index-ash .boffset. -1))))
#+clx-overlapping-arrays
,@(when (member 32 (macroexpand '(%buffer-sizes) env))
`((setq buffer-loffset (index-ash .boffset. -2))))
#+clx-overlapping-arrays
.boffset.))
(defmacro advance-buffer-offset (value)
`(set-buffer-offset (index+ buffer-boffset ,value)))
(defmacro with-buffer-output ((buffer &key (sizes '(8 16 32)) length index) &body body)
(unless (listp sizes) (setq sizes (list sizes)))
`(let ((%buffer ,buffer))
(declare (type display %buffer))
,(declare-bufmac)
,(when length
`(when (index>= (index+ (buffer-boffset %buffer) ,length) (buffer-size %buffer))
(buffer-flush %buffer)))
(let* ((buffer-boffset (the array-index ,(or index `(buffer-boffset %buffer))))
#-clx-overlapping-arrays
(buffer-bbuf (buffer-obuf8 %buffer))
#+clx-overlapping-arrays
,@(append
(when (member 8 sizes)
`((buffer-bbuf (buffer-obuf8 %buffer))))
(when (or (member 16 sizes) (member 160 sizes))
`((buffer-woffset (index-ash buffer-boffset -1))
(buffer-wbuf (buffer-obuf16 %buffer))))
(when (member 32 sizes)
`((buffer-loffset (index-ash buffer-boffset -2))
(buffer-lbuf (buffer-obuf32 %buffer))))))
(declare (type array-index buffer-boffset))
#-clx-overlapping-arrays
(declare (type buffer-bytes buffer-bbuf)
(array-register buffer-bbuf))
#+clx-overlapping-arrays
,@(append
(when (member 8 sizes)
'((declare (type buffer-bytes buffer-bbuf)
(array-register buffer-bbuf))))
(when (member 16 sizes)
'((declare (type array-index buffer-woffset))
(declare (type buffer-words buffer-wbuf)
(array-register buffer-wbuf))))
(when (member 32 sizes)
'((declare (type array-index buffer-loffset))
(declare (type buffer-longs buffer-lbuf)
(array-register buffer-lbuf)))))
buffer-boffset
#-clx-overlapping-arrays
buffer-bbuf
#+clx-overlapping-arrays
,@(append
(when (member 8 sizes) '(buffer-bbuf))
(when (member 16 sizes) '(buffer-woffset buffer-wbuf))
(when (member 32 sizes) '(buffer-loffset buffer-lbuf)))
#+clx-overlapping-arrays
(macrolet ((%buffer-sizes () ',sizes))
,@body)
#-clx-overlapping-arrays
,@body)))
(defmacro writing-buffer-chunks (type args decls &body body)
(when (> (length body) 2)
(error "writing-buffer-chunks called with too many forms"))
(let* ((size (* 8 (index-increment type)))
(form #-clx-overlapping-arrays
(first body)
(or (second body)
(first body))))
`(with-buffer-output (buffer :index boffset :sizes ,(reverse (adjoin size '(8))))
(do* (,@args
(len ,(if (= size 8)
`(index- end start)
`(index-ash (index- end start) ,(truncate size 16)))
(index- len chunk))
(chunk (index-min len (index- (buffer-size buffer) buffer-boffset))
(index-min len (index- (buffer-size buffer) buffer-boffset))))
((not (index-plusp len)))
(declare ,@decls
(type array-index len chunk))
,form
(index-incf buffer-boffset chunk)
(when (and (index-plusp len) (index>= buffer-boffset (buffer-size buffer)))
(setf (buffer-boffset buffer) buffer-boffset)
(buffer-flush buffer)
(setq buffer-boffset (buffer-boffset buffer))
#+clx-overlapping-arrays
,(case size
(16 '(setq buffer-woffset (index-ash buffer-boffset -1)))
(32 '(setq buffer-loffset (index-ash buffer-boffset -2))))))
(setf (buffer-boffset buffer) (lround buffer-boffset)))))
|
8d93a9ce42f83c8d6655c48e71f26f3bb569ce360efc08cde78bce7661cf6437 | facebook/flow | propertyFindRefs.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Ast = Flow_ast
open Loc_collections
open GetDefUtils
let loc_of_aloc = Parsing_heaps.Reader.loc_of_aloc
let add_ref_kind kind = Base.List.map ~f:(fun loc -> (kind, loc))
module LiteralToPropLoc : sig
(* Returns a map from object_literal_loc to prop_loc, for all object literals which contain the
* given property name. *)
val make : (Loc.t, Loc.t) Ast.Program.t -> prop_name:string -> Loc.t LocMap.t
end = struct
class locmap_builder prop_name =
object (this)
inherit [Loc.t LocMap.t] Object_key_visitor.visitor ~init:LocMap.empty
method! private visit_object_key
(literal_loc : Loc.t) (key : (Loc.t, Loc.t) Ast.Expression.Object.Property.key) =
let open Ast.Expression.Object in
match key with
| Property.Identifier (prop_loc, { Ast.Identifier.name; comments = _ })
when name = prop_name ->
this#update_acc (fun map -> LocMap.add literal_loc prop_loc map)
TODO consider supporting other property keys ( e.g. literals ) . Also update the
* optimization in property_access_searcher below when this happens .
* optimization in property_access_searcher below when this happens. *)
| _ -> ()
end
let make ast ~prop_name =
let builder = new locmap_builder prop_name in
builder#eval builder#program ast
end
module Potential_refs_search = struct
exception Found_import
class searcher ~(target_name : string) ~(potential_refs : Type.t ALocMap.t ref) =
object (_this)
inherit
[ALoc.t, ALoc.t * Type.t, ALoc.t, ALoc.t * Type.t] Flow_polymorphic_ast_mapper.mapper as super
method on_loc_annot x = x
method on_type_annot x = x
method! import_declaration loc decl =
let open Flow_ast.Statement.ImportDeclaration in
try super#import_declaration loc decl with
| Found_import ->
let { source = ((_, module_t), _); _ } = decl in
(* Replace previous bindings of `loc`. We should always use the result of the last call to
the hook for a given location (this may no longer be relevant with the removal of
generate-tests) *)
potential_refs := ALocMap.add loc module_t !potential_refs;
decl
method! import_named_specifier ~import_kind:_ specifier =
let open Flow_ast.Statement.ImportDeclaration in
let { kind = _; local; remote } = specifier in
let (_, { Flow_ast.Identifier.name; _ }) = Base.Option.value ~default:remote local in
if name = target_name then
raise Found_import
else
specifier
method! member expr =
let open Flow_ast.Expression.Member in
let { _object = ((_, ty), _); property; comments = _ } = expr in
(match property with
| PropertyIdentifier ((loc, _), { Flow_ast.Identifier.name; _ })
| PropertyPrivateName (loc, { Flow_ast.PrivateName.name; _ })
when name = target_name ->
potential_refs := ALocMap.add loc ty !potential_refs
| PropertyIdentifier _
| PropertyPrivateName _
| PropertyExpression _ ->
());
super#member expr
method! pattern ?kind expr =
let ((_, ty), patt) = expr in
let _ =
match patt with
| Ast.Pattern.Object { Ast.Pattern.Object.properties; _ } ->
List.iter
(fun prop ->
let open Ast.Pattern.Object in
match prop with
| Property (_, { Property.key; _ }) ->
(match key with
| Property.Identifier ((loc, _), { Ast.Identifier.name; _ })
| Property.Literal (loc, { Ast.Literal.value = Ast.Literal.String name; _ }) ->
if name = target_name then potential_refs := ALocMap.add loc ty !potential_refs;
()
| Property.Computed _
| Property.Literal _ ->
())
| RestElement _ -> ())
properties
| Ast.Pattern.Identifier { Ast.Pattern.Identifier.name; _ } ->
let ((loc, ty), { Flow_ast.Identifier.name = id_name; _ }) = name in
(* If the location is already in the map, it was set by a parent *)
if id_name = target_name && (not @@ ALocMap.mem loc !potential_refs) then
potential_refs := ALocMap.add loc ty !potential_refs;
()
| Ast.Pattern.Array _
| Ast.Pattern.Expression _ ->
()
in
super#pattern ?kind expr
end
let search ~target_name ~potential_refs ast =
let s = new searcher ~target_name ~potential_refs in
let _ = s#program ast in
()
end
(* Returns `true` iff the given type is a reference to the symbol we are interested in *)
let type_matches_locs ~reader cx ty prop_def_info name =
let rec def_loc_matches_locs = function
| FoundClass ty_def_locs ->
prop_def_info
|> Nel.exists (function
| Object _ -> false
| Class loc ->
Only take the first extracted def loc -- that is , the one for the actual definition
* and not overridden implementations , and compare it to the list of def locs we are
* interested in
* and not overridden implementations, and compare it to the list of def locs we are
* interested in *)
loc = Nel.hd ty_def_locs
)
| FoundObject loc ->
prop_def_info
|> Nel.exists (function
| Class _ -> false
| Object def_loc -> loc = def_loc
)
| FoundUnion def_locs -> def_locs |> Nel.map def_loc_matches_locs |> Nel.fold_left ( || ) false
TODO we may want to surface AnyType results somehow since we ca n't be sure whether they
* are references or not . For now we 'll leave them out .
* are references or not. For now we'll leave them out. *)
| NoDefFound
| UnsupportedType
| AnyType ->
false
in
extract_def_loc ~reader cx ty name >>| def_loc_matches_locs
let get_loc_of_def_info ~cx ~reader ~obj_to_obj_map prop_def_info =
(* let prop_loc_map = build_prop_location_map ~cx ~reader obj_to_obj_map in *)
let prop_obj_locs =
Nel.fold_left
(fun acc def_info ->
match def_info with
| Class _ -> acc
| Object def_loc -> Loc_collections.LocSet.add def_loc acc)
Loc_collections.LocSet.empty
prop_def_info
in
(* Iterates all the map prop values. If any match prop_def_info, add the obj loc to the result *)
Loc_collections.LocMap.fold
(fun loc props_tmap_set result ->
Type.Properties.Set.fold
(fun props_id result' ->
let props = Context.find_props cx props_id in
NameUtils.Map.fold
(fun _name prop result'' ->
match Type.Property.read_loc prop with
| Some aloc when Loc_collections.LocSet.mem (loc_of_aloc ~reader aloc) prop_obj_locs
->
loc :: result''
| _ -> result'')
props
result')
props_tmap_set
result)
obj_to_obj_map
[]
let process_prop_refs ~reader cx potential_refs file_key prop_def_info name =
potential_refs
|> ALocMap.bindings
|> Base.List.map ~f:(fun (ref_loc, ty) ->
type_matches_locs ~reader cx ty prop_def_info name >>| function
| true -> Some (loc_of_aloc ~reader ref_loc)
| false -> None
)
|> Result.all
|> Result.map_error ~f:(fun err ->
Printf.sprintf
"Encountered while finding refs in `%s`: %s"
(File_key.to_string file_key)
err
)
>>| fun refs -> refs |> Base.List.filter_opt |> add_ref_kind FindRefsTypes.PropertyAccess
let property_find_refs_in_file ~reader ast_info type_info file_key def_info name =
let potential_refs : Type.t ALocMap.t ref = ref ALocMap.empty in
let (cx, typed_ast, obj_to_obj_map) = type_info in
let (ast, _file_sig, _info) = ast_info in
let local_defs =
Nel.to_list (all_locs_of_property_def_info def_info)
|> List.filter (fun loc -> loc.Loc.source = Some file_key)
|> add_ref_kind FindRefsTypes.PropertyDefinition
in
let has_symbol = PropertyAccessSearcher.search name ast in
if not has_symbol then
Ok local_defs
else (
Potential_refs_search.search ~target_name:name ~potential_refs typed_ast;
let literal_prop_refs_result =
(* Lazy to avoid this computation if there are no potentially-relevant object literals to
* examine *)
let prop_loc_map = lazy (LiteralToPropLoc.make ast ~prop_name:name) in
get_loc_of_def_info ~cx ~reader ~obj_to_obj_map def_info
|> List.filter_map (fun obj_loc -> LocMap.find_opt obj_loc (Lazy.force prop_loc_map))
|> add_ref_kind FindRefsTypes.PropertyDefinition
in
process_prop_refs ~reader cx !potential_refs file_key def_info name
>>| ( @ ) local_defs
>>| ( @ ) literal_prop_refs_result
)
let find_local_refs ~reader file_key ast_info type_info loc =
match get_def_info ~reader type_info loc with
| Error _ as err -> err
| Ok None -> Ok None
| Ok (Some (def_info, name)) ->
property_find_refs_in_file ~reader ast_info type_info file_key def_info name >>= fun refs ->
Ok (Some (name, refs))
| null | https://raw.githubusercontent.com/facebook/flow/5f4b8172d0d14ac5e4b3bb69b3c879d0fffe6886/src/services/references/propertyFindRefs.ml | ocaml | Returns a map from object_literal_loc to prop_loc, for all object literals which contain the
* given property name.
Replace previous bindings of `loc`. We should always use the result of the last call to
the hook for a given location (this may no longer be relevant with the removal of
generate-tests)
If the location is already in the map, it was set by a parent
Returns `true` iff the given type is a reference to the symbol we are interested in
let prop_loc_map = build_prop_location_map ~cx ~reader obj_to_obj_map in
Iterates all the map prop values. If any match prop_def_info, add the obj loc to the result
Lazy to avoid this computation if there are no potentially-relevant object literals to
* examine |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Ast = Flow_ast
open Loc_collections
open GetDefUtils
let loc_of_aloc = Parsing_heaps.Reader.loc_of_aloc
let add_ref_kind kind = Base.List.map ~f:(fun loc -> (kind, loc))
module LiteralToPropLoc : sig
val make : (Loc.t, Loc.t) Ast.Program.t -> prop_name:string -> Loc.t LocMap.t
end = struct
class locmap_builder prop_name =
object (this)
inherit [Loc.t LocMap.t] Object_key_visitor.visitor ~init:LocMap.empty
method! private visit_object_key
(literal_loc : Loc.t) (key : (Loc.t, Loc.t) Ast.Expression.Object.Property.key) =
let open Ast.Expression.Object in
match key with
| Property.Identifier (prop_loc, { Ast.Identifier.name; comments = _ })
when name = prop_name ->
this#update_acc (fun map -> LocMap.add literal_loc prop_loc map)
TODO consider supporting other property keys ( e.g. literals ) . Also update the
* optimization in property_access_searcher below when this happens .
* optimization in property_access_searcher below when this happens. *)
| _ -> ()
end
let make ast ~prop_name =
let builder = new locmap_builder prop_name in
builder#eval builder#program ast
end
module Potential_refs_search = struct
exception Found_import
class searcher ~(target_name : string) ~(potential_refs : Type.t ALocMap.t ref) =
object (_this)
inherit
[ALoc.t, ALoc.t * Type.t, ALoc.t, ALoc.t * Type.t] Flow_polymorphic_ast_mapper.mapper as super
method on_loc_annot x = x
method on_type_annot x = x
method! import_declaration loc decl =
let open Flow_ast.Statement.ImportDeclaration in
try super#import_declaration loc decl with
| Found_import ->
let { source = ((_, module_t), _); _ } = decl in
potential_refs := ALocMap.add loc module_t !potential_refs;
decl
method! import_named_specifier ~import_kind:_ specifier =
let open Flow_ast.Statement.ImportDeclaration in
let { kind = _; local; remote } = specifier in
let (_, { Flow_ast.Identifier.name; _ }) = Base.Option.value ~default:remote local in
if name = target_name then
raise Found_import
else
specifier
method! member expr =
let open Flow_ast.Expression.Member in
let { _object = ((_, ty), _); property; comments = _ } = expr in
(match property with
| PropertyIdentifier ((loc, _), { Flow_ast.Identifier.name; _ })
| PropertyPrivateName (loc, { Flow_ast.PrivateName.name; _ })
when name = target_name ->
potential_refs := ALocMap.add loc ty !potential_refs
| PropertyIdentifier _
| PropertyPrivateName _
| PropertyExpression _ ->
());
super#member expr
method! pattern ?kind expr =
let ((_, ty), patt) = expr in
let _ =
match patt with
| Ast.Pattern.Object { Ast.Pattern.Object.properties; _ } ->
List.iter
(fun prop ->
let open Ast.Pattern.Object in
match prop with
| Property (_, { Property.key; _ }) ->
(match key with
| Property.Identifier ((loc, _), { Ast.Identifier.name; _ })
| Property.Literal (loc, { Ast.Literal.value = Ast.Literal.String name; _ }) ->
if name = target_name then potential_refs := ALocMap.add loc ty !potential_refs;
()
| Property.Computed _
| Property.Literal _ ->
())
| RestElement _ -> ())
properties
| Ast.Pattern.Identifier { Ast.Pattern.Identifier.name; _ } ->
let ((loc, ty), { Flow_ast.Identifier.name = id_name; _ }) = name in
if id_name = target_name && (not @@ ALocMap.mem loc !potential_refs) then
potential_refs := ALocMap.add loc ty !potential_refs;
()
| Ast.Pattern.Array _
| Ast.Pattern.Expression _ ->
()
in
super#pattern ?kind expr
end
let search ~target_name ~potential_refs ast =
let s = new searcher ~target_name ~potential_refs in
let _ = s#program ast in
()
end
let type_matches_locs ~reader cx ty prop_def_info name =
let rec def_loc_matches_locs = function
| FoundClass ty_def_locs ->
prop_def_info
|> Nel.exists (function
| Object _ -> false
| Class loc ->
Only take the first extracted def loc -- that is , the one for the actual definition
* and not overridden implementations , and compare it to the list of def locs we are
* interested in
* and not overridden implementations, and compare it to the list of def locs we are
* interested in *)
loc = Nel.hd ty_def_locs
)
| FoundObject loc ->
prop_def_info
|> Nel.exists (function
| Class _ -> false
| Object def_loc -> loc = def_loc
)
| FoundUnion def_locs -> def_locs |> Nel.map def_loc_matches_locs |> Nel.fold_left ( || ) false
TODO we may want to surface AnyType results somehow since we ca n't be sure whether they
* are references or not . For now we 'll leave them out .
* are references or not. For now we'll leave them out. *)
| NoDefFound
| UnsupportedType
| AnyType ->
false
in
extract_def_loc ~reader cx ty name >>| def_loc_matches_locs
let get_loc_of_def_info ~cx ~reader ~obj_to_obj_map prop_def_info =
let prop_obj_locs =
Nel.fold_left
(fun acc def_info ->
match def_info with
| Class _ -> acc
| Object def_loc -> Loc_collections.LocSet.add def_loc acc)
Loc_collections.LocSet.empty
prop_def_info
in
Loc_collections.LocMap.fold
(fun loc props_tmap_set result ->
Type.Properties.Set.fold
(fun props_id result' ->
let props = Context.find_props cx props_id in
NameUtils.Map.fold
(fun _name prop result'' ->
match Type.Property.read_loc prop with
| Some aloc when Loc_collections.LocSet.mem (loc_of_aloc ~reader aloc) prop_obj_locs
->
loc :: result''
| _ -> result'')
props
result')
props_tmap_set
result)
obj_to_obj_map
[]
let process_prop_refs ~reader cx potential_refs file_key prop_def_info name =
potential_refs
|> ALocMap.bindings
|> Base.List.map ~f:(fun (ref_loc, ty) ->
type_matches_locs ~reader cx ty prop_def_info name >>| function
| true -> Some (loc_of_aloc ~reader ref_loc)
| false -> None
)
|> Result.all
|> Result.map_error ~f:(fun err ->
Printf.sprintf
"Encountered while finding refs in `%s`: %s"
(File_key.to_string file_key)
err
)
>>| fun refs -> refs |> Base.List.filter_opt |> add_ref_kind FindRefsTypes.PropertyAccess
let property_find_refs_in_file ~reader ast_info type_info file_key def_info name =
let potential_refs : Type.t ALocMap.t ref = ref ALocMap.empty in
let (cx, typed_ast, obj_to_obj_map) = type_info in
let (ast, _file_sig, _info) = ast_info in
let local_defs =
Nel.to_list (all_locs_of_property_def_info def_info)
|> List.filter (fun loc -> loc.Loc.source = Some file_key)
|> add_ref_kind FindRefsTypes.PropertyDefinition
in
let has_symbol = PropertyAccessSearcher.search name ast in
if not has_symbol then
Ok local_defs
else (
Potential_refs_search.search ~target_name:name ~potential_refs typed_ast;
let literal_prop_refs_result =
let prop_loc_map = lazy (LiteralToPropLoc.make ast ~prop_name:name) in
get_loc_of_def_info ~cx ~reader ~obj_to_obj_map def_info
|> List.filter_map (fun obj_loc -> LocMap.find_opt obj_loc (Lazy.force prop_loc_map))
|> add_ref_kind FindRefsTypes.PropertyDefinition
in
process_prop_refs ~reader cx !potential_refs file_key def_info name
>>| ( @ ) local_defs
>>| ( @ ) literal_prop_refs_result
)
let find_local_refs ~reader file_key ast_info type_info loc =
match get_def_info ~reader type_info loc with
| Error _ as err -> err
| Ok None -> Ok None
| Ok (Some (def_info, name)) ->
property_find_refs_in_file ~reader ast_info type_info file_key def_info name >>= fun refs ->
Ok (Some (name, refs))
|
9f4e16dac2a3331dad08935a9f9fe6a99fdee795d400b8f30e3aaf3ea3bc75de | okeuday/erlbench | uuid.erl | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
%%%
%%%------------------------------------------------------------------------
%%% @doc
%%% ==Erlang UUID Generation==
[ ] is the reference for official UUIDs .
%%% This implementation provides a version 1 UUID that includes both the
Erlang pid identifier ( ID , Serial , Creation ) and the distributed Erlang
node name within the 48 bit node ID . To make room for the Erlang pid
identifier , the 48 bits from the MAC address
( i.e. , 3 OCI ( Organizationally Unique Identifier ) bytes and
3 NIC ( Network Interface Controller ) specific bytes ) and
the distributed Erlang node name are bitwise - XORed down to 16 bits .
The Erlang pid is bitwise - XORed from 72 bits down to 32 bits .
The version 3 ( MD5 ) , version 4 ( random ) , and version 5 ( SHA )
%%% methods are provided as specified within the RFC.
%%% @end
%%%
MIT License
%%%
Copyright ( c ) 2011 - 2017 < mjtruog at protonmail dot com >
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a
%%% copy of this software and associated documentation files (the "Software"),
to deal 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.
%%%
@author < mjtruog at protonmail dot com >
2011 - 2017
%%% @version 1.7.1 {@date} {@time}
%%%------------------------------------------------------------------------
-module(uuid).
-author('mjtruog at protonmail dot com').
%% external interface
-export([new/1,
new/2,
get_v1/1,
get_v1_time/0,
get_v1_time/1,
get_v1_datetime/1,
get_v1_datetime/2,
is_v1/1,
get_v3/1,
get_v3/2,
get_v3_compat/1,
get_v3_compat/2,
is_v3/1,
get_v4/0,
get_v4/1,
get_v4_urandom/0,
is_v4/1,
get_v5/1,
get_v5/2,
get_v5_compat/1,
get_v5_compat/2,
is_v5/1,
uuid_to_list/1,
uuid_to_string/1,
uuid_to_string/2,
string_to_uuid/1,
is_uuid/1,
increment/1,
mac_address/0,
test/0]).
-ifdef(ERLANG_OTP_VERSION_16).
-define(TIMESTAMP_ERLANG_NOW, true).
-else.
-ifdef(ERLANG_OTP_VERSION_17).
-define(TIMESTAMP_ERLANG_NOW, true).
-else.
-define(ERLANG_OTP_VERSION_18_FEATURES, true).
-endif.
-endif.
-ifdef(TIMESTAMP_ERLANG_NOW).
-type timestamp_type_internal() :: 'erlang_now' | 'os'.
-else.
-type timestamp_type_internal() :: 'erlang_timestamp' | 'os' | 'warp'.
-endif.
-record(uuid_state,
{
node_id :: <<_:48>>,
clock_seq :: 0..16383,
timestamp_type :: timestamp_type_internal(),
timestamp_last :: integer() % microseconds
}).
-type uuid() :: <<_:128>>.
-type timestamp_type() :: 'erlang' | 'os' | 'warp'.
-type state() :: #uuid_state{}.
-export_type([uuid/0,
timestamp_type/0,
state/0]).
-include("uuid.hrl").
%%%------------------------------------------------------------------------
%%% External interface functions
%%%------------------------------------------------------------------------
%%-------------------------------------------------------------------------
%% @doc
%% ===Create new UUID state for v1 UUID generation.===
%% @end
%%-------------------------------------------------------------------------
-spec new(Pid :: pid()) ->
state().
new(Pid) when is_pid(Pid) ->
new(Pid, [{timestamp_type, erlang}]).
%%-------------------------------------------------------------------------
%% @doc
%% ===Create new UUID state for v1 UUID generation using a specific type of timestamp.===
The timestamp can either be based on erlang 's adjustment of time
%% (for only strictly monotonically increasing time values) or the
%% operating system's time without any adjustment
%% (with timestamp_type values `erlang' and `os', respectively).
If you want 's adjustment of time without enforcement of increasing
time values , use the ` warp ' timestamp_type value with Erlang > = 18.0 .
%% @end
%%-------------------------------------------------------------------------
-spec new(Pid :: pid(),
Options :: timestamp_type() |
list({timestamp_type, timestamp_type()} |
{mac_address, list(non_neg_integer())})) ->
state().
new(Pid, TimestampType)
when is_pid(Pid),
((TimestampType =:= erlang) orelse
(TimestampType =:= os) orelse
(TimestampType =:= warp)) ->
new(Pid, [{timestamp_type, TimestampType}]);
new(Pid, Options)
when is_pid(Pid), is_list(Options) ->
TimestampType = case lists:keyfind(timestamp_type, 1, Options) of
{timestamp_type, Value1} ->
Value1;
false ->
erlang
end,
MacAddress = case lists:keyfind(mac_address, 1, Options) of
{mac_address, Value2} ->
Value2;
false ->
mac_address()
end,
make the version 1 UUID specific to the Erlang node and pid
48 bits for the first MAC address found is included with the
distributed Erlang node name
<<NodeD01, NodeD02, NodeD03, NodeD04, NodeD05,
NodeD06, NodeD07, NodeD08, NodeD09, NodeD10,
NodeD11, NodeD12, NodeD13, NodeD14, NodeD15,
NodeD16, NodeD17, NodeD18, NodeD19, NodeD20>> =
crypto:hash(sha, erlang:list_to_binary(MacAddress ++
erlang:atom_to_list(node()))),
% later, when the pid format changes, handle the different format
ExternalTermFormatVersion = 131,
PidExtType = 103,
<<ExternalTermFormatVersion:8,
PidExtType:8,
PidBin/binary>> = erlang:term_to_binary(Pid),
72 bits for the Erlang pid
ID ( Node specific , 15 bits )
PidSR1:8, PidSR2:8, PidSR3:8, PidSR4:8, % Serial (extra uniqueness)
PidCR1:8 % Node Creation Count
>> = binary:part(PidBin, erlang:byte_size(PidBin), -9),
reduce the 160 bit NodeData checksum to 16 bits
NodeByte1 = ((((((((NodeD01 bxor NodeD02)
bxor NodeD03)
bxor NodeD04)
bxor NodeD05)
bxor NodeD06)
bxor NodeD07)
bxor NodeD08)
bxor NodeD09)
bxor NodeD10,
NodeByte2 = (((((((((NodeD11 bxor NodeD12)
bxor NodeD13)
bxor NodeD14)
bxor NodeD15)
bxor NodeD16)
bxor NodeD17)
bxor NodeD18)
bxor NodeD19)
bxor NodeD20)
bxor PidCR1,
reduce the Erlang pid to 32 bits
PidByte1 = PidID1 bxor PidSR4,
PidByte2 = PidID2 bxor PidSR3,
PidByte3 = PidID3 bxor PidSR2,
PidByte4 = PidID4 bxor PidSR1,
ClockSeq = pseudo_random(16384) - 1,
TimestampTypeInternal = if
TimestampType =:= os ->
os;
TimestampType =:= erlang ->
timestamp_type_erlang();
TimestampType =:= warp ->
case erlang:function_exported(erlang, system_time, 0) of
true ->
Erlang > = 18.0
warp;
false ->
Erlang < 18.0
erlang:exit(badarg)
end
end,
TimestampLast = timestamp(TimestampTypeInternal),
#uuid_state{node_id = <<NodeByte1:8, NodeByte2:8,
PidByte1:8, PidByte2:8,
PidByte3:8, PidByte4:8>>,
clock_seq = ClockSeq,
timestamp_type = TimestampTypeInternal,
timestamp_last = TimestampLast}.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a v1 UUID.===
%% @end
%%-------------------------------------------------------------------------
-spec get_v1(State :: state()) ->
{uuid(), NewState :: state()}.
get_v1(#uuid_state{node_id = NodeId,
clock_seq = ClockSeq,
timestamp_type = TimestampTypeInternal,
timestamp_last = TimestampLast} = State) ->
MicroSeconds = timestamp(TimestampTypeInternal, TimestampLast),
16#01b21dd213814000 is the number of 100 - ns intervals between the
UUID epoch 1582 - 10 - 15 00:00:00 and the UNIX epoch 1970 - 01 - 01 00:00:00 .
Time = MicroSeconds * 10 + 16#01b21dd213814000,
will be larger than 60 bits after 5236 - 03 - 31 21:21:00
<<TimeHigh:12, TimeMid:16, TimeLow:32>> = <<Time:60>>,
{<<TimeLow:32, TimeMid:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
TimeHigh:12,
1:1, 0:1, % RFC 4122 variant bits
ClockSeq:14,
NodeId/binary>>,
State#uuid_state{timestamp_last = MicroSeconds}}.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get the current time value in a manner consistent with the v1 UUID.===
%% The result is an integer in microseconds.
%% @end
%%-------------------------------------------------------------------------
-spec get_v1_time() ->
non_neg_integer().
get_v1_time() ->
get_v1_time(erlang).
%%-------------------------------------------------------------------------
%% @doc
%% ===Get the current time value in a manner consistent with the v1 UUID.===
%% The result is an integer in microseconds.
%% @end
%%-------------------------------------------------------------------------
-spec get_v1_time(timestamp_type() | state() | uuid()) ->
non_neg_integer().
-ifdef(TIMESTAMP_ERLANG_NOW).
Erlang < 18.0
get_v1_time(erlang) ->
timestamp(erlang_now);
get_v1_time(os) ->
timestamp(os);
get_v1_time(warp) ->
erlang:exit(badarg);
get_v1_time(#uuid_state{timestamp_type = TimestampTypeInternal}) ->
timestamp(TimestampTypeInternal);
get_v1_time(Value)
when is_binary(Value), byte_size(Value) == 16 ->
<<TimeLow:32, TimeMid:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
TimeHigh:12,
1:1, 0:1, % RFC 4122 variant bits
_:14,
_:48>> = Value,
<<Time:60>> = <<TimeHigh:12, TimeMid:16, TimeLow:32>>,
microseconds since UNIX epoch
-else.
Erlang > = 18.0
get_v1_time(erlang) ->
timestamp(erlang_timestamp);
get_v1_time(os) ->
timestamp(os);
get_v1_time(warp) ->
timestamp(warp);
get_v1_time(#uuid_state{timestamp_type = TimestampTypeInternal}) ->
timestamp(TimestampTypeInternal);
get_v1_time(Value)
when is_binary(Value), byte_size(Value) == 16 ->
<<TimeLow:32, TimeMid:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
TimeHigh:12,
1:1, 0:1, % RFC 4122 variant bits
_:14,
_:48>> = Value,
<<Time:60>> = <<TimeHigh:12, TimeMid:16, TimeLow:32>>,
microseconds since UNIX epoch
-endif.
%%-------------------------------------------------------------------------
%% @doc
= = = Get an ISO8601 datetime in UTC from a v1 UUID 's time value.===
%% -datetime
%% @end
%%-------------------------------------------------------------------------
-spec get_v1_datetime(Value :: timestamp_type() | state() | uuid() |
erlang:timestamp()) ->
string().
get_v1_datetime({_, _, MicroSeconds} = Timestamp) ->
{{DateYYYY, DateMM, DateDD},
{TimeHH, TimeMM, TimeSS}} = calendar:now_to_universal_time(Timestamp),
[DateYYYY0, DateYYYY1,
DateYYYY2, DateYYYY3] = int_to_dec_list(DateYYYY, 4),
[DateMM0, DateMM1] = int_to_dec_list(DateMM, 2),
[DateDD0, DateDD1] = int_to_dec_list(DateDD, 2),
[TimeHH0, TimeHH1] = int_to_dec_list(TimeHH, 2),
[TimeMM0, TimeMM1] = int_to_dec_list(TimeMM, 2),
[TimeSS0, TimeSS1] = int_to_dec_list(TimeSS, 2),
[MicroSeconds0, MicroSeconds1,
MicroSeconds2, MicroSeconds3,
MicroSeconds4, MicroSeconds5] = int_to_dec_list(MicroSeconds, 6),
[DateYYYY0, DateYYYY1, DateYYYY2, DateYYYY3, $-,
DateMM0, DateMM1, $-, DateDD0, DateDD1, $T,
TimeHH0, TimeHH1, $:, TimeMM0, TimeMM1, $:, TimeSS0, TimeSS1, $.,
MicroSeconds0, MicroSeconds1,
MicroSeconds2, MicroSeconds3,
MicroSeconds4, MicroSeconds5, $Z];
get_v1_datetime(Value) ->
get_v1_datetime(Value, 0).
%%-------------------------------------------------------------------------
%% @doc
= = = Get an ISO8601 datetime in UTC from a v1 UUID 's time value with an offset in microseconds.===
%% -datetime
%% @end
%%-------------------------------------------------------------------------
-spec get_v1_datetime(Value :: timestamp_type() | state() | uuid() |
erlang:timestamp(),
MicroSecondsOffset :: integer()) ->
string().
get_v1_datetime(Value, MicroSecondsOffset)
when is_integer(MicroSecondsOffset) ->
MicroSecondsTotal = get_v1_time(Value) + MicroSecondsOffset,
MegaSeconds = MicroSecondsTotal div 1000000000000,
Seconds = (MicroSecondsTotal div 1000000) - MegaSeconds * 1000000,
MicroSeconds = MicroSecondsTotal rem 1000000,
get_v1_datetime({MegaSeconds, Seconds, MicroSeconds}).
%%-------------------------------------------------------------------------
%% @doc
= = = Is the binary a v1 UUID?===
%% @end
%%-------------------------------------------------------------------------
-spec is_v1(Value :: any()) ->
boolean().
is_v1(<<_TimeLow:32, _TimeMid:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
_TimeHigh:12,
1:1, 0:1, % RFC 4122 variant bits
_ClockSeq:14,
_NodeId:48>>) ->
true;
is_v1(_) ->
false.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a v3 UUID.===
%% @end
%%-------------------------------------------------------------------------
-spec get_v3(Data :: binary()) ->
uuid().
get_v3(Data) when is_binary(Data) ->
<<B1:48, B4a:4, B2:12, B4b:2, B3:14, B4c:48>> =
crypto:hash(md5, Data),
B4 = (B4a bxor B4b) bxor B4c,
<<B1:48,
version 3 bits
B2:12,
1:1, 0:1, % RFC 4122 variant bits
B3:14,
B4:48>>.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a v3 UUID in a particular namespace.===
%% @end
%%-------------------------------------------------------------------------
-spec get_v3(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v3(dns, Data) ->
get_v3(?UUID_NAMESPACE_DNS, Data);
get_v3(url, Data) ->
get_v3(?UUID_NAMESPACE_URL, Data);
get_v3(oid, Data) ->
get_v3(?UUID_NAMESPACE_OID, Data);
get_v3(x500, Data) ->
get_v3(?UUID_NAMESPACE_X500, Data);
get_v3(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v3(<<Namespace/binary, DataBin/binary>>).
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a compatible v3 UUID.===
Do not use all bits from the checksum so that the UUID matches external
%% implementations.
%% @end
%%-------------------------------------------------------------------------
-spec get_v3_compat(Data :: binary()) ->
uuid().
get_v3_compat(Data) when is_binary(Data) ->
<<B1:48, _:4, B2:12, _:2, B3:14, B4:48>> =
crypto:hash(md5, Data),
<<B1:48,
version 3 bits
B2:12,
1:1, 0:1, % RFC 4122 variant bits
B3:14,
B4:48>>.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a compatible v3 UUID in a particular namespace.===
Do not use all bits from the checksum so that the UUID matches external
%% implementations.
%% @end
%%-------------------------------------------------------------------------
-spec get_v3_compat(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v3_compat(dns, Data) ->
get_v3_compat(?UUID_NAMESPACE_DNS, Data);
get_v3_compat(url, Data) ->
get_v3_compat(?UUID_NAMESPACE_URL, Data);
get_v3_compat(oid, Data) ->
get_v3_compat(?UUID_NAMESPACE_OID, Data);
get_v3_compat(x500, Data) ->
get_v3_compat(?UUID_NAMESPACE_X500, Data);
get_v3_compat(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v3_compat(<<Namespace/binary, DataBin/binary>>).
%%-------------------------------------------------------------------------
%% @doc
= = = Is the binary a v3 UUID?===
%% @end
%%-------------------------------------------------------------------------
-spec is_v3(Value :: any()) ->
boolean().
is_v3(<<_:48,
version 3 bits
_:12,
1:1, 0:1, % RFC 4122 variant bits
_:62>>) ->
true;
is_v3(_) ->
false.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a v4 UUID (using crypto/openssl).===
%% crypto:strong_rand_bytes/1 repeats in the same way as
RAND_bytes within OpenSSL .
%% @end
%%-------------------------------------------------------------------------
-spec get_v4() ->
uuid().
get_v4() ->
get_v4(strong).
-spec get_v4('strong' | 'cached' | quickrand_cache:state()) ->
uuid() | {uuid(), quickrand_cache:state()}.
get_v4(strong) ->
<<Rand1:48, _:4, Rand2:12, _:2, Rand3:62>> =
crypto:strong_rand_bytes(16),
<<Rand1:48,
version 4 bits
Rand2:12,
1:1, 0:1, % RFC 4122 variant bits
Rand3:62>>;
get_v4(cached) ->
<<Rand1:48, _:4, Rand2:12, _:2, Rand3:62>> =
quickrand_cache:rand_bytes(16),
<<Rand1:48,
version 4 bits
Rand2:12,
1:1, 0:1, % RFC 4122 variant bits
Rand3:62>>;
get_v4(Cache) when element(1, Cache) =:= quickrand_cache ->
{<<Rand1:48, _:4, Rand2:12, _:2, Rand3:62>>, NewCache} =
quickrand_cache:rand_bytes(16, Cache),
{<<Rand1:48,
version 4 bits
Rand2:12,
1:1, 0:1, % RFC 4122 variant bits
Rand3:62>>, NewCache}.
%%-------------------------------------------------------------------------
%% @doc
= = = Get a v4 UUID ( using Wichmann - Hill 2006).===
random_wh06_int : uniform/1 repeats every 2.66e36 ( 2 ^ 121 ) approx .
( see and , in
%% 'Generating good pseudo-random numbers',
Computational Statistics and Data Analysis 51 ( 2006 ) 1614 - 1622 )
a single random_wh06_int : uniform/1 call can provide a maximum of 124 bits
( see for details )
%% @end
%%-------------------------------------------------------------------------
-spec get_v4_urandom() ->
uuid().
get_v4_urandom() ->
random 122 bits
Rand = random_wh06_int:uniform(5316911983139663491615228241121378304) - 1,
<<Rand1:48, Rand2:12, Rand3:62>> = <<Rand:122>>,
<<Rand1:48,
version 4 bits
Rand2:12,
1:1, 0:1, % RFC 4122 variant bits
Rand3:62>>.
%%-------------------------------------------------------------------------
%% @doc
= = = Is the binary a v4 UUID?===
%% @end
%%-------------------------------------------------------------------------
-spec is_v4(Value :: any()) ->
boolean().
is_v4(<<_:48,
version 4 bits
_:12,
1:1, 0:1, % RFC 4122 variant bits
_:62>>) ->
true;
is_v4(_) ->
false.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a v5 UUID.===
%% @end
%%-------------------------------------------------------------------------
-spec get_v5(Data :: binary()) ->
uuid().
get_v5(Data) when is_binary(Data) ->
<<B1:48, B4a:4, B2:12, B4b:2, B3:14, B4c:32, B4d:48>> =
crypto:hash(sha, Data),
B4 = ((B4a bxor B4b) bxor B4c) bxor B4d,
<<B1:48,
version 5 bits
B2:12,
1:1, 0:1, % RFC 4122 variant bits
B3:14,
B4:48>>.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a v5 UUID in a particular namespace.===
%% @end
%%-------------------------------------------------------------------------
-spec get_v5(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v5(dns, Data) ->
get_v5(?UUID_NAMESPACE_DNS, Data);
get_v5(url, Data) ->
get_v5(?UUID_NAMESPACE_URL, Data);
get_v5(oid, Data) ->
get_v5(?UUID_NAMESPACE_OID, Data);
get_v5(x500, Data) ->
get_v5(?UUID_NAMESPACE_X500, Data);
get_v5(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v5(<<Namespace/binary, DataBin/binary>>).
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a compatible v5 UUID.===
Do not use all bits from the checksum so that the UUID matches external
%% implementations.
%% @end
%%-------------------------------------------------------------------------
-spec get_v5_compat(Data :: binary()) ->
uuid().
get_v5_compat(Data) when is_binary(Data) ->
<<B1:48, _:4, B2:12, _:2, B3:14, B4:48, _:32>> =
crypto:hash(sha, Data),
<<B1:48,
version 5 bits
B2:12,
1:1, 0:1, % RFC 4122 variant bits
B3:14,
B4:48>>.
%%-------------------------------------------------------------------------
%% @doc
%% ===Get a compatible v5 UUID in a particular namespace.===
Do not use all bits from the checksum so that the UUID matches external
%% implementations.
%% @end
%%-------------------------------------------------------------------------
-spec get_v5_compat(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v5_compat(dns, Data) ->
get_v5_compat(?UUID_NAMESPACE_DNS, Data);
get_v5_compat(url, Data) ->
get_v5_compat(?UUID_NAMESPACE_URL, Data);
get_v5_compat(oid, Data) ->
get_v5_compat(?UUID_NAMESPACE_OID, Data);
get_v5_compat(x500, Data) ->
get_v5_compat(?UUID_NAMESPACE_X500, Data);
get_v5_compat(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v5_compat(<<Namespace/binary, DataBin/binary>>).
%%-------------------------------------------------------------------------
%% @doc
= = = Is the binary a v5 UUID?===
%% @end
%%-------------------------------------------------------------------------
-spec is_v5(Value :: any()) ->
boolean().
is_v5(<<_:48,
version 5 bits
_:12,
1:1, 0:1, % RFC 4122 variant bits
_:62>>) ->
true;
is_v5(_) ->
false.
%%-------------------------------------------------------------------------
%% @doc
%% ===Convert a UUID to a list.===
%% @end
%%-------------------------------------------------------------------------
-spec uuid_to_list(uuid()) ->
iolist().
uuid_to_list(<<B1:32/unsigned-integer,
B2:16/unsigned-integer,
B3:16/unsigned-integer,
B4:16/unsigned-integer,
B5:48/unsigned-integer>>) ->
[B1, B2, B3, B4, B5].
%%-------------------------------------------------------------------------
%% @doc
%% ===Convert a UUID to a string representation.===
%% @end
%%-------------------------------------------------------------------------
-spec uuid_to_string(Value :: uuid()) ->
string().
uuid_to_string(Value) ->
uuid_to_string(Value, standard).
%%-------------------------------------------------------------------------
%% @doc
%% ===Convert a UUID to a string representation based on an option.===
%% @end
%%-------------------------------------------------------------------------
-spec uuid_to_string(Value :: uuid(),
Option :: standard | nodash |
list_standard | list_nodash |
binary_standard | binary_nodash) ->
string() | binary().
uuid_to_string(<<Value:128/unsigned-integer>>, standard) ->
[N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32] =
int_to_hex_list(Value, 32),
[N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32];
uuid_to_string(<<Value:128/unsigned-integer>>, nodash) ->
int_to_hex_list(Value, 32);
uuid_to_string(Value, list_standard) ->
uuid_to_string(Value, standard);
uuid_to_string(Value, list_nodash) ->
uuid_to_string(Value, nodash);
uuid_to_string(<<Value:128/unsigned-integer>>, binary_standard) ->
[N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32] =
int_to_hex_list(Value, 32),
<<N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32>>;
uuid_to_string(<<Value:128/unsigned-integer>>, binary_nodash) ->
[N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32] =
int_to_hex_list(Value, 32),
<<N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32>>.
%%-------------------------------------------------------------------------
%% @doc
%% ===Convert a string representation to a UUID.===
%% @end
%%-------------------------------------------------------------------------
-spec string_to_uuid(string() | binary()) ->
uuid().
string_to_uuid([N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32]) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid([N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32]) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid(<<N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32>>) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid(<<N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32>>) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid(_) ->
erlang:exit(badarg).
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32) ->
B01 = hex_to_int(N01, N02),
B02 = hex_to_int(N03, N04),
B03 = hex_to_int(N05, N06),
B04 = hex_to_int(N07, N08),
B05 = hex_to_int(N09, N10),
B06 = hex_to_int(N11, N12),
B07 = hex_to_int(N13, N14),
B08 = hex_to_int(N15, N16),
B09 = hex_to_int(N17, N18),
B10 = hex_to_int(N19, N20),
B11 = hex_to_int(N21, N22),
B12 = hex_to_int(N23, N24),
B13 = hex_to_int(N25, N26),
B14 = hex_to_int(N27, N28),
B15 = hex_to_int(N29, N30),
B16 = hex_to_int(N31, N32),
<<B01, B02, B03, B04, B05, B06, B07, B08,
B09, B10, B11, B12, B13, B14, B15, B16>>.
%%-------------------------------------------------------------------------
%% @doc
= = = Is the term a UUID?===
%% @end
%%-------------------------------------------------------------------------
-spec is_uuid(any()) ->
boolean().
is_uuid(<<_:48,
Version:4/unsigned-integer,
_:12,
1:1, 0:1, % RFC 4122 variant bits
_:62>>) ->
(Version == 1) orelse
(Version == 3) orelse
(Version == 4) orelse
(Version == 5);
is_uuid(_) ->
false.
%%-------------------------------------------------------------------------
%% @doc
%% ===Increment the clock sequence of v1 UUID state or a UUID.===
%% Call to increment the clock sequence counter after the system clock has
%% been set backwards (see the RFC). This is only necessary
%% if the `os' or `warp' timestamp_type is used with a v1 UUID.
%% The v3, v4 and v5 UUIDs are supported for completeness.
%% @end
%%-------------------------------------------------------------------------
-spec increment(state() | uuid()) ->
state() | uuid().
increment(<<TimeLow:32, TimeMid:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
TimeHigh:12,
1:1, 0:1, % RFC 4122 variant bits
ClockSeq:14,
NodeId:48>>) ->
NextClockSeq = ClockSeq + 1,
NewClockSeq = if
NextClockSeq == 16384 ->
0;
true ->
NextClockSeq
end,
<<TimeLow:32, TimeMid:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
TimeHigh:12,
1:1, 0:1, % RFC 4122 variant bits
NewClockSeq:14,
NodeId:48>>;
increment(<<Rand1:48,
Version:4/unsigned-integer,
Rand2:12,
1:1, 0:1, % RFC 4122 variant bits
Rand3:62>>)
when (Version == 4) orelse (Version == 5) orelse (Version == 3) ->
<<Value:16/little-unsigned-integer-unit:8>> = <<Rand1:48,
Rand2:12,
Rand3:62,
0:6>>,
NextValue = Value + 1,
NewValue = if
NextValue == 5316911983139663491615228241121378304 ->
1;
true ->
NextValue
end,
<<NewRand1:48,
NewRand2:12,
NewRand3:62,
0:6>> = <<NewValue:16/little-unsigned-integer-unit:8>>,
<<NewRand1:48,
Version:4/unsigned-integer,
NewRand2:12,
1:1, 0:1, % RFC 4122 variant bits
NewRand3:62>>;
increment(#uuid_state{clock_seq = ClockSeq} = State) ->
NextClockSeq = ClockSeq + 1,
NewClockSeq = if
NextClockSeq == 16384 ->
0;
true ->
NextClockSeq
end,
State#uuid_state{clock_seq = NewClockSeq}.
%%-------------------------------------------------------------------------
%% @doc
= = = Provide a usable network interface MAC address.===
%% @end
%%-------------------------------------------------------------------------
-spec mac_address() ->
list(non_neg_integer()).
mac_address() ->
{ok, Ifs} = inet:getifaddrs(),
mac_address(lists:keysort(1, Ifs)).
%%-------------------------------------------------------------------------
%% @doc
%% ===Regression test.===
%% @end
%%-------------------------------------------------------------------------
-spec test() ->
ok.
test() ->
version 1 tests
uuidgen -t ; date
" Fri Dec 7 19:13:58 PST 2012 "
( Sat Dec 8 03:13:58 UTC 2012 )
V1uuid1 = uuid:string_to_uuid("4ea4b020-40e5-11e2-ac70-001fd0a5484e"),
"4ea4b020-40e5-11e2-ac70-001fd0a5484e" =
uuid:uuid_to_string(V1uuid1, standard),
<<V1TimeLow1:32, V1TimeMid1:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
V1TimeHigh1:12,
1:1, 0:1, % RFC 4122 variant bits
V1ClockSeq1:14,
V1NodeId1/binary>> = V1uuid1,
true = uuid:is_uuid(V1uuid1),
true = uuid:is_v1(V1uuid1),
"2012-12-08T03:13:58.564048Z" = uuid:get_v1_datetime(V1uuid1),
<<V1Time1:60>> = <<V1TimeHigh1:12, V1TimeMid1:16, V1TimeLow1:32>>,
V1Time1total = erlang:trunc((V1Time1 - 16#01b21dd213814000) / 10),
V1Time1mega = erlang:trunc(V1Time1total / 1000000000000),
V1Time1sec = erlang:trunc(V1Time1total / 1000000 - V1Time1mega * 1000000),
V1Time1micro = erlang:trunc(V1Time1total -
(V1Time1mega * 1000000 + V1Time1sec) * 1000000),
{{2012, 12, 8}, {3, 13, 58}} =
calendar:now_to_datetime({V1Time1mega, V1Time1sec, V1Time1micro}),
max version 1 timestamp :
"5236-03-31T21:21:00.684697Z" = uuid:get_v1_datetime(<<16#ffffffff:32,
16#ffff:16,
0:1, 0:1, 0:1, 1:1,
16#fff:12,
1:1, 0:1,
0:14, 0:48>>),
% $ python
% >>> import uuid
% >>> import time
% >>> uuid.uuid1().hex;time.time()
% '50d15f5c40e911e2a0eb001fd0a5484e'
1354938160.1998589
V1uuid2 = uuid:string_to_uuid("50d15f5c40e911e2a0eb001fd0a5484e"),
"50d15f5c40e911e2a0eb001fd0a5484e" =
uuid:uuid_to_string(V1uuid2, nodash),
"2012-12-08T03:42:40.199254Z" = uuid:get_v1_datetime(V1uuid2),
<<V1TimeLow2:32, V1TimeMid2:16,
0:1, 0:1, 0:1, 1:1, % version 1 bits
V1TimeHigh2:12,
1:1, 0:1, % RFC 4122 variant bits
V1ClockSeq2:14,
V1NodeId2/binary>> = V1uuid2,
true = uuid:is_v1(V1uuid2),
<<V1Time2:60>> = <<V1TimeHigh2:12, V1TimeMid2:16, V1TimeLow2:32>>,
V1Time2total = erlang:trunc((V1Time2 - 16#01b21dd213814000) / 10),
V1Time2Amega = erlang:trunc(V1Time2total / 1000000000000),
V1Time2Asec = erlang:trunc(V1Time2total / 1000000 - V1Time2Amega * 1000000),
V1Time2Amicro = erlang:trunc(V1Time2total -
(V1Time2Amega * 1000000 + V1Time2Asec) * 1000000),
V1Time2B = 1354938160.1998589,
V1Time2Bmega = erlang:trunc(V1Time2B / 1000000),
V1Time2Bsec = erlang:trunc(V1Time2B - V1Time2Bmega * 1000000),
V1Time2Bmicro = erlang:trunc(V1Time2B * 1000000 -
(V1Time2Bmega * 1000000 + V1Time2Bsec) * 1000000),
true = (V1Time2Amega == V1Time2Bmega),
true = (V1Time2Asec == V1Time2Bsec),
true = (V1Time2Amicro < V1Time2Bmicro) and
((V1Time2Amicro + 605) == V1Time2Bmicro),
true = V1ClockSeq1 /= V1ClockSeq2,
true = V1NodeId1 == V1NodeId2,
{V1uuid3, _} = uuid:get_v1(uuid:new(self(), erlang)),
V1uuid3timeB = uuid:get_v1_time(erlang),
V1uuid3timeA = uuid:get_v1_time(V1uuid3),
true = (V1uuid3timeA < V1uuid3timeB) and
((V1uuid3timeA + 1000) > V1uuid3timeB),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("3ff0fc1e-c23b-11e2-b8a0-38607751fca5"))),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("67ff79a6-c23b-11e2-b374-38607751fca5"))),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("7134eede-c23b-11e2-a4a7-38607751fca5"))),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("717003c0-c23b-11e2-83a4-38607751fca5"))),
{V1uuid4, _} = uuid:get_v1(uuid:new(self(), os)),
V1uuid4timeB = uuid:get_v1_time(os),
V1uuid4timeA = uuid:get_v1_time(V1uuid4),
true = (V1uuid4timeA < V1uuid4timeB) and
((V1uuid4timeA + 1000) > V1uuid4timeB),
V1State0 = uuid:new(self()),
{V1uuid5, V1State1} = uuid:get_v1(V1State0),
{V1uuid6, V1State2} = uuid:get_v1(V1State1),
{V1uuid7, V1State3} = uuid:get_v1(V1State2),
{V1uuid8, V1State4} = uuid:get_v1(V1State3),
{V1uuid9, V1State5} = uuid:get_v1(V1State4),
{V1uuid10, V1State6} = uuid:get_v1(V1State5),
{V1uuid11, _} = uuid:get_v1(V1State6),
V1uuidL0 = [V1uuid5, V1uuid6, V1uuid7, V1uuid8,
V1uuid9, V1uuid10, V1uuid11],
V1uuidL1 = [V1uuid11, V1uuid9, V1uuid8, V1uuid7,
V1uuid6, V1uuid10, V1uuid5],
true = V1uuidL0 == lists:usort(V1uuidL1),
version 3 tests
% $ python
% >>> import uuid
> > > uuid.uuid3(uuid . , ' test').hex
% '45a113acc7f230b090a5a399ab912716'
V3uuid1 = uuid:string_to_uuid("45a113acc7f230b090a5a399ab912716"),
"45a113acc7f230b090a5a399ab912716" =
uuid:uuid_to_string(V3uuid1, nodash),
<<V3uuid1A:48,
version 3 bits
V3uuid1B:12,
1:1, 0:1, % RFC 4122 variant bits
V3uuid1C:14,
V3uuid1D:48>> = V3uuid1,
true = uuid:is_v3(V3uuid1),
V3uuid2 = uuid:get_v3(?UUID_NAMESPACE_DNS, <<"test">>),
true = (V3uuid2 == uuid:get_v3(dns, <<"test">>)),
<<V3uuid2A:48,
version 3 bits
V3uuid2B:12,
1:1, 0:1, % RFC 4122 variant bits
V3uuid2C:14,
V3uuid2D:48>> = V3uuid2,
true = uuid:is_v3(V3uuid2),
true = ((V3uuid1A == V3uuid2A) and
(V3uuid1B == V3uuid2B) and
(V3uuid1C == V3uuid2C)),
% check fails:
since the python uuid discards bits from MD5 while this module
% bitwise xor the middle bits to utilize the whole checksum
false = (V3uuid1D == V3uuid2D),
replicate the same UUID value used in other implementations
% where bits are discarded from the checksum
V3uuid1 = uuid:get_v3_compat(?UUID_NAMESPACE_DNS, <<"test">>),
true = (uuid:get_v3_compat(dns, <<"test1">>) ==
uuid:string_to_uuid("c501822b22a837ff91a99545f4689a3d")),
true = (uuid:get_v3_compat(dns, <<"test2">>) ==
uuid:string_to_uuid("f191764306b23e6dab770a5044067d0a")),
true = (uuid:get_v3_compat(dns, <<"test3">>) ==
uuid:string_to_uuid("bf7f1e5a6b28310c8f9ef815dbd56fb7")),
true = (uuid:get_v3_compat(dns, <<"test4">>) ==
uuid:string_to_uuid("fe584e2496c83d2d8b39f1cc6a877f72")),
version 4 tests
uuidgen -r
V4uuid1 = uuid:string_to_uuid("ffe8b758-a5dc-4bf4-9eb0-878e010e8df7"),
"ffe8b758-a5dc-4bf4-9eb0-878e010e8df7" =
uuid:uuid_to_string(V4uuid1, standard),
<<V4Rand1A:48,
version 4 bits
V4Rand1B:12,
1:1, 0:1, % RFC 4122 variant bits
V4Rand1C:14,
V4Rand1D:48>> = V4uuid1,
true = uuid:is_v4(V4uuid1),
% $ python
% >>> import uuid
% >>> uuid.uuid4().hex
% 'cc9769818fe747398e2422e99fee2753'
V4uuid2 = uuid:string_to_uuid("cc9769818fe747398e2422e99fee2753"),
"cc9769818fe747398e2422e99fee2753" =
uuid:uuid_to_string(V4uuid2, nodash),
<<V4Rand2A:48,
version 4 bits
V4Rand2B:12,
1:1, 0:1, % RFC 4122 variant bits
V4Rand2C:14,
V4Rand2D:48>> = V4uuid2,
true = uuid:is_v4(V4uuid2),
V4uuid3 = uuid:get_v4(strong),
<<_:48,
version 4 bits
_:12,
1:1, 0:1, % RFC 4122 variant bits
_:14,
_:48>> = V4uuid3,
true = uuid:is_v4(V4uuid3),
true = (V4Rand1A /= V4Rand2A),
true = (V4Rand1B /= V4Rand2B),
true = (V4Rand1C /= V4Rand2C),
true = (V4Rand1D /= V4Rand2D),
true = V4uuid3 /= uuid:increment(V4uuid3),
version 5 tests
% $ python
% >>> import uuid
> > > uuid.uuid5(uuid . , ' test').hex
% '4be0643f1d98573b97cdca98a65347dd'
V5uuid1 = uuid:string_to_uuid("4be0643f1d98573b97cdca98a65347dd"),
"4be0643f1d98573b97cdca98a65347dd" =
uuid:uuid_to_string(V5uuid1, nodash),
<<V5uuid1A:48,
version 5 bits
V5uuid1B:12,
1:1, 0:1, % RFC 4122 variant bits
V5uuid1C:14,
V5uuid1D:48>> = V5uuid1,
true = uuid:is_v5(V5uuid1),
V5uuid2 = uuid:get_v5(?UUID_NAMESPACE_DNS, <<"test">>),
true = (V5uuid2 == uuid:get_v5(dns, <<"test">>)),
<<V5uuid2A:48,
version 5 bits
V5uuid2B:12,
1:1, 0:1, % RFC 4122 variant bits
V5uuid2C:14,
V5uuid2D:48>> = V5uuid2,
true = uuid:is_v5(V5uuid2),
true = ((V5uuid1A == V5uuid2A) and
(V5uuid1B == V5uuid2B) and
(V5uuid1C == V5uuid2C)),
% check fails:
since the python uuid discards bits from SHA while this module
% bitwise xor the remaining bits to utilize the whole checksum
false = (V5uuid1D == V5uuid2D),
replicate the same UUID value used in other implementations
% where bits are discarded from the checksum
V5uuid1 = uuid:get_v5_compat(?UUID_NAMESPACE_DNS, <<"test">>),
true = (uuid:get_v5_compat(dns, <<"test1">>) ==
uuid:string_to_uuid("86e3aed315535d238d612286215e65f1")),
true = (uuid:get_v5_compat(dns, <<"test2">>) ==
uuid:string_to_uuid("6eabff02c9685cbcbc7f3b672928a761")),
true = (uuid:get_v5_compat(dns, <<"test3">>) ==
uuid:string_to_uuid("20ca53afd04c58a2a8b3d02b9e414e80")),
true = (uuid:get_v5_compat(dns, <<"test4">>) ==
uuid:string_to_uuid("3e673fdc1a4f5b168890dbe7e763f7b5")),
ok.
%%%------------------------------------------------------------------------
%%% Private functions
%%%------------------------------------------------------------------------
-compile({inline,
[{timestamp,1},
{timestamp,2},
{int_to_dec,1},
{int_to_hex,1},
{hex_to_int,1}]}).
-ifdef(TIMESTAMP_ERLANG_NOW).
timestamp_type_erlang() ->
Erlang < 18.0
false = erlang:function_exported(erlang, system_time, 0),
erlang_now.
timestamp(erlang_now) ->
{MegaSeconds, Seconds, MicroSeconds} = erlang:now(),
(MegaSeconds * 1000000 + Seconds) * 1000000 + MicroSeconds;
timestamp(os) ->
{MegaSeconds, Seconds, MicroSeconds} = os:timestamp(),
(MegaSeconds * 1000000 + Seconds) * 1000000 + MicroSeconds.
timestamp(erlang_now, _) ->
timestamp(erlang_now);
timestamp(os, _) ->
timestamp(os).
-else.
timestamp_type_erlang() ->
Erlang > = 18.0
true = erlang:function_exported(erlang, system_time, 0),
erlang_timestamp.
timestamp(erlang_timestamp) ->
erlang:system_time(micro_seconds);
timestamp(os) ->
{MegaSeconds, Seconds, MicroSeconds} = os:timestamp(),
(MegaSeconds * 1000000 + Seconds) * 1000000 + MicroSeconds;
timestamp(warp) ->
erlang:system_time(micro_seconds).
timestamp(erlang_timestamp, TimestampLast) ->
TimestampNext = timestamp(erlang_timestamp),
if
TimestampNext > TimestampLast ->
TimestampNext;
true ->
TimestampLast + 1
end;
timestamp(os, _) ->
timestamp(os);
timestamp(warp, _) ->
timestamp(warp).
-endif.
int_to_dec_list(I, N) when is_integer(I), I >= 0 ->
int_to_dec_list([], I, 1, N).
int_to_dec_list(L, I, Count, N)
when I < 10 ->
int_to_list_pad([int_to_dec(I) | L], N - Count);
int_to_dec_list(L, I, Count, N) ->
int_to_dec_list([int_to_dec(I rem 10) | L], I div 10, Count + 1, N).
int_to_hex_list(I, N) when is_integer(I), I >= 0 ->
int_to_hex_list([], I, 1, N).
int_to_list_pad(L, 0) ->
L;
int_to_list_pad(L, Count) ->
int_to_list_pad([$0 | L], Count - 1).
int_to_hex_list(L, I, Count, N)
when I < 16 ->
int_to_list_pad([int_to_hex(I) | L], N - Count);
int_to_hex_list(L, I, Count, N) ->
int_to_hex_list([int_to_hex(I rem 16) | L], I div 16, Count + 1, N).
int_to_dec(I) when 0 =< I, I =< 9 ->
I + $0.
int_to_hex(I) when 0 =< I, I =< 9 ->
I + $0;
int_to_hex(I) when 10 =< I, I =< 15 ->
(I - 10) + $a.
hex_to_int(C1, C2) ->
hex_to_int(C1) * 16 + hex_to_int(C2).
hex_to_int(C) when $0 =< C, C =< $9 ->
C - $0;
hex_to_int(C) when $A =< C, C =< $F ->
C - $A + 10;
hex_to_int(C) when $a =< C, C =< $f ->
C - $a + 10.
mac_address([]) ->
[0, 0, 0, 0, 0, 0];
mac_address([{_, L} | Rest]) ->
case lists:keyfind(hwaddr, 1, L) of
false ->
mac_address(Rest);
{hwaddr, MAC} ->
case lists:sum(MAC) of
0 ->
mac_address(Rest);
_ ->
MAC
end
end.
-ifdef(ERLANG_OTP_VERSION_18_FEATURES).
pseudo_random(N) ->
assuming exsplus for 58 bits , period 8.31e34
rand:uniform(N).
-else.
pseudo_random(N) ->
period 2.78e13
random:uniform(N).
-endif.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
internal_test_() ->
[
{"internal tests", ?_assertEqual(ok, test())}
].
-endif.
| null | https://raw.githubusercontent.com/okeuday/erlbench/9fc02a2e748b287b85f6e9641db6b2ca68791fa4/src/uuid.erl | erlang |
------------------------------------------------------------------------
@doc
==Erlang UUID Generation==
This implementation provides a version 1 UUID that includes both the
methods are provided as specified within the RFC.
@end
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
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.
@version 1.7.1 {@date} {@time}
------------------------------------------------------------------------
external interface
microseconds
------------------------------------------------------------------------
External interface functions
------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Create new UUID state for v1 UUID generation.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Create new UUID state for v1 UUID generation using a specific type of timestamp.===
(for only strictly monotonically increasing time values) or the
operating system's time without any adjustment
(with timestamp_type values `erlang' and `os', respectively).
@end
-------------------------------------------------------------------------
later, when the pid format changes, handle the different format
Serial (extra uniqueness)
Node Creation Count
-------------------------------------------------------------------------
@doc
===Get a v1 UUID.===
@end
-------------------------------------------------------------------------
version 1 bits
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get the current time value in a manner consistent with the v1 UUID.===
The result is an integer in microseconds.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Get the current time value in a manner consistent with the v1 UUID.===
The result is an integer in microseconds.
@end
-------------------------------------------------------------------------
version 1 bits
RFC 4122 variant bits
version 1 bits
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
-datetime
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
-datetime
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------------
version 1 bits
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get a v3 UUID.===
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get a v3 UUID in a particular namespace.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Get a compatible v3 UUID.===
implementations.
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get a compatible v3 UUID in a particular namespace.===
implementations.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get a v4 UUID (using crypto/openssl).===
crypto:strong_rand_bytes/1 repeats in the same way as
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
RFC 4122 variant bits
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
'Generating good pseudo-random numbers',
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get a v5 UUID.===
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get a v5 UUID in a particular namespace.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Get a compatible v5 UUID.===
implementations.
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Get a compatible v5 UUID in a particular namespace.===
implementations.
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Convert a UUID to a list.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Convert a UUID to a string representation.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Convert a UUID to a string representation based on an option.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Convert a string representation to a UUID.===
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------------
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
===Increment the clock sequence of v1 UUID state or a UUID.===
Call to increment the clock sequence counter after the system clock has
been set backwards (see the RFC). This is only necessary
if the `os' or `warp' timestamp_type is used with a v1 UUID.
The v3, v4 and v5 UUIDs are supported for completeness.
@end
-------------------------------------------------------------------------
version 1 bits
RFC 4122 variant bits
version 1 bits
RFC 4122 variant bits
RFC 4122 variant bits
RFC 4122 variant bits
-------------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------------
-------------------------------------------------------------------------
@doc
===Regression test.===
@end
-------------------------------------------------------------------------
version 1 bits
RFC 4122 variant bits
$ python
>>> import uuid
>>> import time
>>> uuid.uuid1().hex;time.time()
'50d15f5c40e911e2a0eb001fd0a5484e'
version 1 bits
RFC 4122 variant bits
$ python
>>> import uuid
'45a113acc7f230b090a5a399ab912716'
RFC 4122 variant bits
RFC 4122 variant bits
check fails:
bitwise xor the middle bits to utilize the whole checksum
where bits are discarded from the checksum
RFC 4122 variant bits
$ python
>>> import uuid
>>> uuid.uuid4().hex
'cc9769818fe747398e2422e99fee2753'
RFC 4122 variant bits
RFC 4122 variant bits
$ python
>>> import uuid
'4be0643f1d98573b97cdca98a65347dd'
RFC 4122 variant bits
RFC 4122 variant bits
check fails:
bitwise xor the remaining bits to utilize the whole checksum
where bits are discarded from the checksum
------------------------------------------------------------------------
Private functions
------------------------------------------------------------------------ | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
[ ] is the reference for official UUIDs .
Erlang pid identifier ( ID , Serial , Creation ) and the distributed Erlang
node name within the 48 bit node ID . To make room for the Erlang pid
identifier , the 48 bits from the MAC address
( i.e. , 3 OCI ( Organizationally Unique Identifier ) bytes and
3 NIC ( Network Interface Controller ) specific bytes ) and
the distributed Erlang node name are bitwise - XORed down to 16 bits .
The Erlang pid is bitwise - XORed from 72 bits down to 32 bits .
The version 3 ( MD5 ) , version 4 ( random ) , and version 5 ( SHA )
MIT License
Copyright ( c ) 2011 - 2017 < mjtruog at protonmail dot com >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
@author < mjtruog at protonmail dot com >
2011 - 2017
-module(uuid).
-author('mjtruog at protonmail dot com').
-export([new/1,
new/2,
get_v1/1,
get_v1_time/0,
get_v1_time/1,
get_v1_datetime/1,
get_v1_datetime/2,
is_v1/1,
get_v3/1,
get_v3/2,
get_v3_compat/1,
get_v3_compat/2,
is_v3/1,
get_v4/0,
get_v4/1,
get_v4_urandom/0,
is_v4/1,
get_v5/1,
get_v5/2,
get_v5_compat/1,
get_v5_compat/2,
is_v5/1,
uuid_to_list/1,
uuid_to_string/1,
uuid_to_string/2,
string_to_uuid/1,
is_uuid/1,
increment/1,
mac_address/0,
test/0]).
-ifdef(ERLANG_OTP_VERSION_16).
-define(TIMESTAMP_ERLANG_NOW, true).
-else.
-ifdef(ERLANG_OTP_VERSION_17).
-define(TIMESTAMP_ERLANG_NOW, true).
-else.
-define(ERLANG_OTP_VERSION_18_FEATURES, true).
-endif.
-endif.
-ifdef(TIMESTAMP_ERLANG_NOW).
-type timestamp_type_internal() :: 'erlang_now' | 'os'.
-else.
-type timestamp_type_internal() :: 'erlang_timestamp' | 'os' | 'warp'.
-endif.
-record(uuid_state,
{
node_id :: <<_:48>>,
clock_seq :: 0..16383,
timestamp_type :: timestamp_type_internal(),
}).
-type uuid() :: <<_:128>>.
-type timestamp_type() :: 'erlang' | 'os' | 'warp'.
-type state() :: #uuid_state{}.
-export_type([uuid/0,
timestamp_type/0,
state/0]).
-include("uuid.hrl").
-spec new(Pid :: pid()) ->
state().
new(Pid) when is_pid(Pid) ->
new(Pid, [{timestamp_type, erlang}]).
The timestamp can either be based on erlang 's adjustment of time
If you want 's adjustment of time without enforcement of increasing
time values , use the ` warp ' timestamp_type value with Erlang > = 18.0 .
-spec new(Pid :: pid(),
Options :: timestamp_type() |
list({timestamp_type, timestamp_type()} |
{mac_address, list(non_neg_integer())})) ->
state().
new(Pid, TimestampType)
when is_pid(Pid),
((TimestampType =:= erlang) orelse
(TimestampType =:= os) orelse
(TimestampType =:= warp)) ->
new(Pid, [{timestamp_type, TimestampType}]);
new(Pid, Options)
when is_pid(Pid), is_list(Options) ->
TimestampType = case lists:keyfind(timestamp_type, 1, Options) of
{timestamp_type, Value1} ->
Value1;
false ->
erlang
end,
MacAddress = case lists:keyfind(mac_address, 1, Options) of
{mac_address, Value2} ->
Value2;
false ->
mac_address()
end,
make the version 1 UUID specific to the Erlang node and pid
48 bits for the first MAC address found is included with the
distributed Erlang node name
<<NodeD01, NodeD02, NodeD03, NodeD04, NodeD05,
NodeD06, NodeD07, NodeD08, NodeD09, NodeD10,
NodeD11, NodeD12, NodeD13, NodeD14, NodeD15,
NodeD16, NodeD17, NodeD18, NodeD19, NodeD20>> =
crypto:hash(sha, erlang:list_to_binary(MacAddress ++
erlang:atom_to_list(node()))),
ExternalTermFormatVersion = 131,
PidExtType = 103,
<<ExternalTermFormatVersion:8,
PidExtType:8,
PidBin/binary>> = erlang:term_to_binary(Pid),
72 bits for the Erlang pid
ID ( Node specific , 15 bits )
>> = binary:part(PidBin, erlang:byte_size(PidBin), -9),
reduce the 160 bit NodeData checksum to 16 bits
NodeByte1 = ((((((((NodeD01 bxor NodeD02)
bxor NodeD03)
bxor NodeD04)
bxor NodeD05)
bxor NodeD06)
bxor NodeD07)
bxor NodeD08)
bxor NodeD09)
bxor NodeD10,
NodeByte2 = (((((((((NodeD11 bxor NodeD12)
bxor NodeD13)
bxor NodeD14)
bxor NodeD15)
bxor NodeD16)
bxor NodeD17)
bxor NodeD18)
bxor NodeD19)
bxor NodeD20)
bxor PidCR1,
reduce the Erlang pid to 32 bits
PidByte1 = PidID1 bxor PidSR4,
PidByte2 = PidID2 bxor PidSR3,
PidByte3 = PidID3 bxor PidSR2,
PidByte4 = PidID4 bxor PidSR1,
ClockSeq = pseudo_random(16384) - 1,
TimestampTypeInternal = if
TimestampType =:= os ->
os;
TimestampType =:= erlang ->
timestamp_type_erlang();
TimestampType =:= warp ->
case erlang:function_exported(erlang, system_time, 0) of
true ->
Erlang > = 18.0
warp;
false ->
Erlang < 18.0
erlang:exit(badarg)
end
end,
TimestampLast = timestamp(TimestampTypeInternal),
#uuid_state{node_id = <<NodeByte1:8, NodeByte2:8,
PidByte1:8, PidByte2:8,
PidByte3:8, PidByte4:8>>,
clock_seq = ClockSeq,
timestamp_type = TimestampTypeInternal,
timestamp_last = TimestampLast}.
-spec get_v1(State :: state()) ->
{uuid(), NewState :: state()}.
get_v1(#uuid_state{node_id = NodeId,
clock_seq = ClockSeq,
timestamp_type = TimestampTypeInternal,
timestamp_last = TimestampLast} = State) ->
MicroSeconds = timestamp(TimestampTypeInternal, TimestampLast),
16#01b21dd213814000 is the number of 100 - ns intervals between the
UUID epoch 1582 - 10 - 15 00:00:00 and the UNIX epoch 1970 - 01 - 01 00:00:00 .
Time = MicroSeconds * 10 + 16#01b21dd213814000,
will be larger than 60 bits after 5236 - 03 - 31 21:21:00
<<TimeHigh:12, TimeMid:16, TimeLow:32>> = <<Time:60>>,
{<<TimeLow:32, TimeMid:16,
TimeHigh:12,
ClockSeq:14,
NodeId/binary>>,
State#uuid_state{timestamp_last = MicroSeconds}}.
-spec get_v1_time() ->
non_neg_integer().
get_v1_time() ->
get_v1_time(erlang).
-spec get_v1_time(timestamp_type() | state() | uuid()) ->
non_neg_integer().
-ifdef(TIMESTAMP_ERLANG_NOW).
Erlang < 18.0
get_v1_time(erlang) ->
timestamp(erlang_now);
get_v1_time(os) ->
timestamp(os);
get_v1_time(warp) ->
erlang:exit(badarg);
get_v1_time(#uuid_state{timestamp_type = TimestampTypeInternal}) ->
timestamp(TimestampTypeInternal);
get_v1_time(Value)
when is_binary(Value), byte_size(Value) == 16 ->
<<TimeLow:32, TimeMid:16,
TimeHigh:12,
_:14,
_:48>> = Value,
<<Time:60>> = <<TimeHigh:12, TimeMid:16, TimeLow:32>>,
microseconds since UNIX epoch
-else.
Erlang > = 18.0
get_v1_time(erlang) ->
timestamp(erlang_timestamp);
get_v1_time(os) ->
timestamp(os);
get_v1_time(warp) ->
timestamp(warp);
get_v1_time(#uuid_state{timestamp_type = TimestampTypeInternal}) ->
timestamp(TimestampTypeInternal);
get_v1_time(Value)
when is_binary(Value), byte_size(Value) == 16 ->
<<TimeLow:32, TimeMid:16,
TimeHigh:12,
_:14,
_:48>> = Value,
<<Time:60>> = <<TimeHigh:12, TimeMid:16, TimeLow:32>>,
microseconds since UNIX epoch
-endif.
= = = Get an ISO8601 datetime in UTC from a v1 UUID 's time value.===
-spec get_v1_datetime(Value :: timestamp_type() | state() | uuid() |
erlang:timestamp()) ->
string().
get_v1_datetime({_, _, MicroSeconds} = Timestamp) ->
{{DateYYYY, DateMM, DateDD},
{TimeHH, TimeMM, TimeSS}} = calendar:now_to_universal_time(Timestamp),
[DateYYYY0, DateYYYY1,
DateYYYY2, DateYYYY3] = int_to_dec_list(DateYYYY, 4),
[DateMM0, DateMM1] = int_to_dec_list(DateMM, 2),
[DateDD0, DateDD1] = int_to_dec_list(DateDD, 2),
[TimeHH0, TimeHH1] = int_to_dec_list(TimeHH, 2),
[TimeMM0, TimeMM1] = int_to_dec_list(TimeMM, 2),
[TimeSS0, TimeSS1] = int_to_dec_list(TimeSS, 2),
[MicroSeconds0, MicroSeconds1,
MicroSeconds2, MicroSeconds3,
MicroSeconds4, MicroSeconds5] = int_to_dec_list(MicroSeconds, 6),
[DateYYYY0, DateYYYY1, DateYYYY2, DateYYYY3, $-,
DateMM0, DateMM1, $-, DateDD0, DateDD1, $T,
TimeHH0, TimeHH1, $:, TimeMM0, TimeMM1, $:, TimeSS0, TimeSS1, $.,
MicroSeconds0, MicroSeconds1,
MicroSeconds2, MicroSeconds3,
MicroSeconds4, MicroSeconds5, $Z];
get_v1_datetime(Value) ->
get_v1_datetime(Value, 0).
= = = Get an ISO8601 datetime in UTC from a v1 UUID 's time value with an offset in microseconds.===
-spec get_v1_datetime(Value :: timestamp_type() | state() | uuid() |
erlang:timestamp(),
MicroSecondsOffset :: integer()) ->
string().
get_v1_datetime(Value, MicroSecondsOffset)
when is_integer(MicroSecondsOffset) ->
MicroSecondsTotal = get_v1_time(Value) + MicroSecondsOffset,
MegaSeconds = MicroSecondsTotal div 1000000000000,
Seconds = (MicroSecondsTotal div 1000000) - MegaSeconds * 1000000,
MicroSeconds = MicroSecondsTotal rem 1000000,
get_v1_datetime({MegaSeconds, Seconds, MicroSeconds}).
= = = Is the binary a v1 UUID?===
-spec is_v1(Value :: any()) ->
boolean().
is_v1(<<_TimeLow:32, _TimeMid:16,
_TimeHigh:12,
_ClockSeq:14,
_NodeId:48>>) ->
true;
is_v1(_) ->
false.
-spec get_v3(Data :: binary()) ->
uuid().
get_v3(Data) when is_binary(Data) ->
<<B1:48, B4a:4, B2:12, B4b:2, B3:14, B4c:48>> =
crypto:hash(md5, Data),
B4 = (B4a bxor B4b) bxor B4c,
<<B1:48,
version 3 bits
B2:12,
B3:14,
B4:48>>.
-spec get_v3(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v3(dns, Data) ->
get_v3(?UUID_NAMESPACE_DNS, Data);
get_v3(url, Data) ->
get_v3(?UUID_NAMESPACE_URL, Data);
get_v3(oid, Data) ->
get_v3(?UUID_NAMESPACE_OID, Data);
get_v3(x500, Data) ->
get_v3(?UUID_NAMESPACE_X500, Data);
get_v3(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v3(<<Namespace/binary, DataBin/binary>>).
Do not use all bits from the checksum so that the UUID matches external
-spec get_v3_compat(Data :: binary()) ->
uuid().
get_v3_compat(Data) when is_binary(Data) ->
<<B1:48, _:4, B2:12, _:2, B3:14, B4:48>> =
crypto:hash(md5, Data),
<<B1:48,
version 3 bits
B2:12,
B3:14,
B4:48>>.
Do not use all bits from the checksum so that the UUID matches external
-spec get_v3_compat(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v3_compat(dns, Data) ->
get_v3_compat(?UUID_NAMESPACE_DNS, Data);
get_v3_compat(url, Data) ->
get_v3_compat(?UUID_NAMESPACE_URL, Data);
get_v3_compat(oid, Data) ->
get_v3_compat(?UUID_NAMESPACE_OID, Data);
get_v3_compat(x500, Data) ->
get_v3_compat(?UUID_NAMESPACE_X500, Data);
get_v3_compat(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v3_compat(<<Namespace/binary, DataBin/binary>>).
= = = Is the binary a v3 UUID?===
-spec is_v3(Value :: any()) ->
boolean().
is_v3(<<_:48,
version 3 bits
_:12,
_:62>>) ->
true;
is_v3(_) ->
false.
RAND_bytes within OpenSSL .
-spec get_v4() ->
uuid().
get_v4() ->
get_v4(strong).
-spec get_v4('strong' | 'cached' | quickrand_cache:state()) ->
uuid() | {uuid(), quickrand_cache:state()}.
get_v4(strong) ->
<<Rand1:48, _:4, Rand2:12, _:2, Rand3:62>> =
crypto:strong_rand_bytes(16),
<<Rand1:48,
version 4 bits
Rand2:12,
Rand3:62>>;
get_v4(cached) ->
<<Rand1:48, _:4, Rand2:12, _:2, Rand3:62>> =
quickrand_cache:rand_bytes(16),
<<Rand1:48,
version 4 bits
Rand2:12,
Rand3:62>>;
get_v4(Cache) when element(1, Cache) =:= quickrand_cache ->
{<<Rand1:48, _:4, Rand2:12, _:2, Rand3:62>>, NewCache} =
quickrand_cache:rand_bytes(16, Cache),
{<<Rand1:48,
version 4 bits
Rand2:12,
Rand3:62>>, NewCache}.
= = = Get a v4 UUID ( using Wichmann - Hill 2006).===
random_wh06_int : uniform/1 repeats every 2.66e36 ( 2 ^ 121 ) approx .
( see and , in
Computational Statistics and Data Analysis 51 ( 2006 ) 1614 - 1622 )
a single random_wh06_int : uniform/1 call can provide a maximum of 124 bits
( see for details )
-spec get_v4_urandom() ->
uuid().
get_v4_urandom() ->
random 122 bits
Rand = random_wh06_int:uniform(5316911983139663491615228241121378304) - 1,
<<Rand1:48, Rand2:12, Rand3:62>> = <<Rand:122>>,
<<Rand1:48,
version 4 bits
Rand2:12,
Rand3:62>>.
= = = Is the binary a v4 UUID?===
-spec is_v4(Value :: any()) ->
boolean().
is_v4(<<_:48,
version 4 bits
_:12,
_:62>>) ->
true;
is_v4(_) ->
false.
-spec get_v5(Data :: binary()) ->
uuid().
get_v5(Data) when is_binary(Data) ->
<<B1:48, B4a:4, B2:12, B4b:2, B3:14, B4c:32, B4d:48>> =
crypto:hash(sha, Data),
B4 = ((B4a bxor B4b) bxor B4c) bxor B4d,
<<B1:48,
version 5 bits
B2:12,
B3:14,
B4:48>>.
-spec get_v5(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v5(dns, Data) ->
get_v5(?UUID_NAMESPACE_DNS, Data);
get_v5(url, Data) ->
get_v5(?UUID_NAMESPACE_URL, Data);
get_v5(oid, Data) ->
get_v5(?UUID_NAMESPACE_OID, Data);
get_v5(x500, Data) ->
get_v5(?UUID_NAMESPACE_X500, Data);
get_v5(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v5(<<Namespace/binary, DataBin/binary>>).
Do not use all bits from the checksum so that the UUID matches external
-spec get_v5_compat(Data :: binary()) ->
uuid().
get_v5_compat(Data) when is_binary(Data) ->
<<B1:48, _:4, B2:12, _:2, B3:14, B4:48, _:32>> =
crypto:hash(sha, Data),
<<B1:48,
version 5 bits
B2:12,
B3:14,
B4:48>>.
Do not use all bits from the checksum so that the UUID matches external
-spec get_v5_compat(Namespace :: dns | url | oid | x500 | binary(),
Data :: binary() | iolist()) ->
uuid().
get_v5_compat(dns, Data) ->
get_v5_compat(?UUID_NAMESPACE_DNS, Data);
get_v5_compat(url, Data) ->
get_v5_compat(?UUID_NAMESPACE_URL, Data);
get_v5_compat(oid, Data) ->
get_v5_compat(?UUID_NAMESPACE_OID, Data);
get_v5_compat(x500, Data) ->
get_v5_compat(?UUID_NAMESPACE_X500, Data);
get_v5_compat(Namespace, Data) when is_binary(Namespace) ->
DataBin = if
is_binary(Data) ->
Data;
is_list(Data) ->
erlang:iolist_to_binary(Data)
end,
get_v5_compat(<<Namespace/binary, DataBin/binary>>).
= = = Is the binary a v5 UUID?===
-spec is_v5(Value :: any()) ->
boolean().
is_v5(<<_:48,
version 5 bits
_:12,
_:62>>) ->
true;
is_v5(_) ->
false.
-spec uuid_to_list(uuid()) ->
iolist().
uuid_to_list(<<B1:32/unsigned-integer,
B2:16/unsigned-integer,
B3:16/unsigned-integer,
B4:16/unsigned-integer,
B5:48/unsigned-integer>>) ->
[B1, B2, B3, B4, B5].
-spec uuid_to_string(Value :: uuid()) ->
string().
uuid_to_string(Value) ->
uuid_to_string(Value, standard).
-spec uuid_to_string(Value :: uuid(),
Option :: standard | nodash |
list_standard | list_nodash |
binary_standard | binary_nodash) ->
string() | binary().
uuid_to_string(<<Value:128/unsigned-integer>>, standard) ->
[N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32] =
int_to_hex_list(Value, 32),
[N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32];
uuid_to_string(<<Value:128/unsigned-integer>>, nodash) ->
int_to_hex_list(Value, 32);
uuid_to_string(Value, list_standard) ->
uuid_to_string(Value, standard);
uuid_to_string(Value, list_nodash) ->
uuid_to_string(Value, nodash);
uuid_to_string(<<Value:128/unsigned-integer>>, binary_standard) ->
[N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32] =
int_to_hex_list(Value, 32),
<<N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32>>;
uuid_to_string(<<Value:128/unsigned-integer>>, binary_nodash) ->
[N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32] =
int_to_hex_list(Value, 32),
<<N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26, N27, N28, N29, N30, N31, N32>>.
-spec string_to_uuid(string() | binary()) ->
uuid().
string_to_uuid([N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32]) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid([N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32]) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid(<<N01, N02, N03, N04, N05, N06, N07, N08, $-,
N09, N10, N11, N12, $-,
N13, N14, N15, N16, $-,
N17, N18, N19, N20, $-,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32>>) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid(<<N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32>>) ->
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32);
string_to_uuid(_) ->
erlang:exit(badarg).
string_to_uuid(N01, N02, N03, N04, N05, N06, N07, N08,
N09, N10, N11, N12,
N13, N14, N15, N16,
N17, N18, N19, N20,
N21, N22, N23, N24, N25, N26,
N27, N28, N29, N30, N31, N32) ->
B01 = hex_to_int(N01, N02),
B02 = hex_to_int(N03, N04),
B03 = hex_to_int(N05, N06),
B04 = hex_to_int(N07, N08),
B05 = hex_to_int(N09, N10),
B06 = hex_to_int(N11, N12),
B07 = hex_to_int(N13, N14),
B08 = hex_to_int(N15, N16),
B09 = hex_to_int(N17, N18),
B10 = hex_to_int(N19, N20),
B11 = hex_to_int(N21, N22),
B12 = hex_to_int(N23, N24),
B13 = hex_to_int(N25, N26),
B14 = hex_to_int(N27, N28),
B15 = hex_to_int(N29, N30),
B16 = hex_to_int(N31, N32),
<<B01, B02, B03, B04, B05, B06, B07, B08,
B09, B10, B11, B12, B13, B14, B15, B16>>.
= = = Is the term a UUID?===
-spec is_uuid(any()) ->
boolean().
is_uuid(<<_:48,
Version:4/unsigned-integer,
_:12,
_:62>>) ->
(Version == 1) orelse
(Version == 3) orelse
(Version == 4) orelse
(Version == 5);
is_uuid(_) ->
false.
-spec increment(state() | uuid()) ->
state() | uuid().
increment(<<TimeLow:32, TimeMid:16,
TimeHigh:12,
ClockSeq:14,
NodeId:48>>) ->
NextClockSeq = ClockSeq + 1,
NewClockSeq = if
NextClockSeq == 16384 ->
0;
true ->
NextClockSeq
end,
<<TimeLow:32, TimeMid:16,
TimeHigh:12,
NewClockSeq:14,
NodeId:48>>;
increment(<<Rand1:48,
Version:4/unsigned-integer,
Rand2:12,
Rand3:62>>)
when (Version == 4) orelse (Version == 5) orelse (Version == 3) ->
<<Value:16/little-unsigned-integer-unit:8>> = <<Rand1:48,
Rand2:12,
Rand3:62,
0:6>>,
NextValue = Value + 1,
NewValue = if
NextValue == 5316911983139663491615228241121378304 ->
1;
true ->
NextValue
end,
<<NewRand1:48,
NewRand2:12,
NewRand3:62,
0:6>> = <<NewValue:16/little-unsigned-integer-unit:8>>,
<<NewRand1:48,
Version:4/unsigned-integer,
NewRand2:12,
NewRand3:62>>;
increment(#uuid_state{clock_seq = ClockSeq} = State) ->
NextClockSeq = ClockSeq + 1,
NewClockSeq = if
NextClockSeq == 16384 ->
0;
true ->
NextClockSeq
end,
State#uuid_state{clock_seq = NewClockSeq}.
= = = Provide a usable network interface MAC address.===
-spec mac_address() ->
list(non_neg_integer()).
mac_address() ->
{ok, Ifs} = inet:getifaddrs(),
mac_address(lists:keysort(1, Ifs)).
-spec test() ->
ok.
test() ->
version 1 tests
uuidgen -t ; date
" Fri Dec 7 19:13:58 PST 2012 "
( Sat Dec 8 03:13:58 UTC 2012 )
V1uuid1 = uuid:string_to_uuid("4ea4b020-40e5-11e2-ac70-001fd0a5484e"),
"4ea4b020-40e5-11e2-ac70-001fd0a5484e" =
uuid:uuid_to_string(V1uuid1, standard),
<<V1TimeLow1:32, V1TimeMid1:16,
V1TimeHigh1:12,
V1ClockSeq1:14,
V1NodeId1/binary>> = V1uuid1,
true = uuid:is_uuid(V1uuid1),
true = uuid:is_v1(V1uuid1),
"2012-12-08T03:13:58.564048Z" = uuid:get_v1_datetime(V1uuid1),
<<V1Time1:60>> = <<V1TimeHigh1:12, V1TimeMid1:16, V1TimeLow1:32>>,
V1Time1total = erlang:trunc((V1Time1 - 16#01b21dd213814000) / 10),
V1Time1mega = erlang:trunc(V1Time1total / 1000000000000),
V1Time1sec = erlang:trunc(V1Time1total / 1000000 - V1Time1mega * 1000000),
V1Time1micro = erlang:trunc(V1Time1total -
(V1Time1mega * 1000000 + V1Time1sec) * 1000000),
{{2012, 12, 8}, {3, 13, 58}} =
calendar:now_to_datetime({V1Time1mega, V1Time1sec, V1Time1micro}),
max version 1 timestamp :
"5236-03-31T21:21:00.684697Z" = uuid:get_v1_datetime(<<16#ffffffff:32,
16#ffff:16,
0:1, 0:1, 0:1, 1:1,
16#fff:12,
1:1, 0:1,
0:14, 0:48>>),
1354938160.1998589
V1uuid2 = uuid:string_to_uuid("50d15f5c40e911e2a0eb001fd0a5484e"),
"50d15f5c40e911e2a0eb001fd0a5484e" =
uuid:uuid_to_string(V1uuid2, nodash),
"2012-12-08T03:42:40.199254Z" = uuid:get_v1_datetime(V1uuid2),
<<V1TimeLow2:32, V1TimeMid2:16,
V1TimeHigh2:12,
V1ClockSeq2:14,
V1NodeId2/binary>> = V1uuid2,
true = uuid:is_v1(V1uuid2),
<<V1Time2:60>> = <<V1TimeHigh2:12, V1TimeMid2:16, V1TimeLow2:32>>,
V1Time2total = erlang:trunc((V1Time2 - 16#01b21dd213814000) / 10),
V1Time2Amega = erlang:trunc(V1Time2total / 1000000000000),
V1Time2Asec = erlang:trunc(V1Time2total / 1000000 - V1Time2Amega * 1000000),
V1Time2Amicro = erlang:trunc(V1Time2total -
(V1Time2Amega * 1000000 + V1Time2Asec) * 1000000),
V1Time2B = 1354938160.1998589,
V1Time2Bmega = erlang:trunc(V1Time2B / 1000000),
V1Time2Bsec = erlang:trunc(V1Time2B - V1Time2Bmega * 1000000),
V1Time2Bmicro = erlang:trunc(V1Time2B * 1000000 -
(V1Time2Bmega * 1000000 + V1Time2Bsec) * 1000000),
true = (V1Time2Amega == V1Time2Bmega),
true = (V1Time2Asec == V1Time2Bsec),
true = (V1Time2Amicro < V1Time2Bmicro) and
((V1Time2Amicro + 605) == V1Time2Bmicro),
true = V1ClockSeq1 /= V1ClockSeq2,
true = V1NodeId1 == V1NodeId2,
{V1uuid3, _} = uuid:get_v1(uuid:new(self(), erlang)),
V1uuid3timeB = uuid:get_v1_time(erlang),
V1uuid3timeA = uuid:get_v1_time(V1uuid3),
true = (V1uuid3timeA < V1uuid3timeB) and
((V1uuid3timeA + 1000) > V1uuid3timeB),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("3ff0fc1e-c23b-11e2-b8a0-38607751fca5"))),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("67ff79a6-c23b-11e2-b374-38607751fca5"))),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("7134eede-c23b-11e2-a4a7-38607751fca5"))),
true = is_number(uuid:get_v1_time(
uuid:string_to_uuid("717003c0-c23b-11e2-83a4-38607751fca5"))),
{V1uuid4, _} = uuid:get_v1(uuid:new(self(), os)),
V1uuid4timeB = uuid:get_v1_time(os),
V1uuid4timeA = uuid:get_v1_time(V1uuid4),
true = (V1uuid4timeA < V1uuid4timeB) and
((V1uuid4timeA + 1000) > V1uuid4timeB),
V1State0 = uuid:new(self()),
{V1uuid5, V1State1} = uuid:get_v1(V1State0),
{V1uuid6, V1State2} = uuid:get_v1(V1State1),
{V1uuid7, V1State3} = uuid:get_v1(V1State2),
{V1uuid8, V1State4} = uuid:get_v1(V1State3),
{V1uuid9, V1State5} = uuid:get_v1(V1State4),
{V1uuid10, V1State6} = uuid:get_v1(V1State5),
{V1uuid11, _} = uuid:get_v1(V1State6),
V1uuidL0 = [V1uuid5, V1uuid6, V1uuid7, V1uuid8,
V1uuid9, V1uuid10, V1uuid11],
V1uuidL1 = [V1uuid11, V1uuid9, V1uuid8, V1uuid7,
V1uuid6, V1uuid10, V1uuid5],
true = V1uuidL0 == lists:usort(V1uuidL1),
version 3 tests
> > > uuid.uuid3(uuid . , ' test').hex
V3uuid1 = uuid:string_to_uuid("45a113acc7f230b090a5a399ab912716"),
"45a113acc7f230b090a5a399ab912716" =
uuid:uuid_to_string(V3uuid1, nodash),
<<V3uuid1A:48,
version 3 bits
V3uuid1B:12,
V3uuid1C:14,
V3uuid1D:48>> = V3uuid1,
true = uuid:is_v3(V3uuid1),
V3uuid2 = uuid:get_v3(?UUID_NAMESPACE_DNS, <<"test">>),
true = (V3uuid2 == uuid:get_v3(dns, <<"test">>)),
<<V3uuid2A:48,
version 3 bits
V3uuid2B:12,
V3uuid2C:14,
V3uuid2D:48>> = V3uuid2,
true = uuid:is_v3(V3uuid2),
true = ((V3uuid1A == V3uuid2A) and
(V3uuid1B == V3uuid2B) and
(V3uuid1C == V3uuid2C)),
since the python uuid discards bits from MD5 while this module
false = (V3uuid1D == V3uuid2D),
replicate the same UUID value used in other implementations
V3uuid1 = uuid:get_v3_compat(?UUID_NAMESPACE_DNS, <<"test">>),
true = (uuid:get_v3_compat(dns, <<"test1">>) ==
uuid:string_to_uuid("c501822b22a837ff91a99545f4689a3d")),
true = (uuid:get_v3_compat(dns, <<"test2">>) ==
uuid:string_to_uuid("f191764306b23e6dab770a5044067d0a")),
true = (uuid:get_v3_compat(dns, <<"test3">>) ==
uuid:string_to_uuid("bf7f1e5a6b28310c8f9ef815dbd56fb7")),
true = (uuid:get_v3_compat(dns, <<"test4">>) ==
uuid:string_to_uuid("fe584e2496c83d2d8b39f1cc6a877f72")),
version 4 tests
uuidgen -r
V4uuid1 = uuid:string_to_uuid("ffe8b758-a5dc-4bf4-9eb0-878e010e8df7"),
"ffe8b758-a5dc-4bf4-9eb0-878e010e8df7" =
uuid:uuid_to_string(V4uuid1, standard),
<<V4Rand1A:48,
version 4 bits
V4Rand1B:12,
V4Rand1C:14,
V4Rand1D:48>> = V4uuid1,
true = uuid:is_v4(V4uuid1),
V4uuid2 = uuid:string_to_uuid("cc9769818fe747398e2422e99fee2753"),
"cc9769818fe747398e2422e99fee2753" =
uuid:uuid_to_string(V4uuid2, nodash),
<<V4Rand2A:48,
version 4 bits
V4Rand2B:12,
V4Rand2C:14,
V4Rand2D:48>> = V4uuid2,
true = uuid:is_v4(V4uuid2),
V4uuid3 = uuid:get_v4(strong),
<<_:48,
version 4 bits
_:12,
_:14,
_:48>> = V4uuid3,
true = uuid:is_v4(V4uuid3),
true = (V4Rand1A /= V4Rand2A),
true = (V4Rand1B /= V4Rand2B),
true = (V4Rand1C /= V4Rand2C),
true = (V4Rand1D /= V4Rand2D),
true = V4uuid3 /= uuid:increment(V4uuid3),
version 5 tests
> > > uuid.uuid5(uuid . , ' test').hex
V5uuid1 = uuid:string_to_uuid("4be0643f1d98573b97cdca98a65347dd"),
"4be0643f1d98573b97cdca98a65347dd" =
uuid:uuid_to_string(V5uuid1, nodash),
<<V5uuid1A:48,
version 5 bits
V5uuid1B:12,
V5uuid1C:14,
V5uuid1D:48>> = V5uuid1,
true = uuid:is_v5(V5uuid1),
V5uuid2 = uuid:get_v5(?UUID_NAMESPACE_DNS, <<"test">>),
true = (V5uuid2 == uuid:get_v5(dns, <<"test">>)),
<<V5uuid2A:48,
version 5 bits
V5uuid2B:12,
V5uuid2C:14,
V5uuid2D:48>> = V5uuid2,
true = uuid:is_v5(V5uuid2),
true = ((V5uuid1A == V5uuid2A) and
(V5uuid1B == V5uuid2B) and
(V5uuid1C == V5uuid2C)),
since the python uuid discards bits from SHA while this module
false = (V5uuid1D == V5uuid2D),
replicate the same UUID value used in other implementations
V5uuid1 = uuid:get_v5_compat(?UUID_NAMESPACE_DNS, <<"test">>),
true = (uuid:get_v5_compat(dns, <<"test1">>) ==
uuid:string_to_uuid("86e3aed315535d238d612286215e65f1")),
true = (uuid:get_v5_compat(dns, <<"test2">>) ==
uuid:string_to_uuid("6eabff02c9685cbcbc7f3b672928a761")),
true = (uuid:get_v5_compat(dns, <<"test3">>) ==
uuid:string_to_uuid("20ca53afd04c58a2a8b3d02b9e414e80")),
true = (uuid:get_v5_compat(dns, <<"test4">>) ==
uuid:string_to_uuid("3e673fdc1a4f5b168890dbe7e763f7b5")),
ok.
-compile({inline,
[{timestamp,1},
{timestamp,2},
{int_to_dec,1},
{int_to_hex,1},
{hex_to_int,1}]}).
-ifdef(TIMESTAMP_ERLANG_NOW).
timestamp_type_erlang() ->
Erlang < 18.0
false = erlang:function_exported(erlang, system_time, 0),
erlang_now.
timestamp(erlang_now) ->
{MegaSeconds, Seconds, MicroSeconds} = erlang:now(),
(MegaSeconds * 1000000 + Seconds) * 1000000 + MicroSeconds;
timestamp(os) ->
{MegaSeconds, Seconds, MicroSeconds} = os:timestamp(),
(MegaSeconds * 1000000 + Seconds) * 1000000 + MicroSeconds.
timestamp(erlang_now, _) ->
timestamp(erlang_now);
timestamp(os, _) ->
timestamp(os).
-else.
timestamp_type_erlang() ->
Erlang > = 18.0
true = erlang:function_exported(erlang, system_time, 0),
erlang_timestamp.
timestamp(erlang_timestamp) ->
erlang:system_time(micro_seconds);
timestamp(os) ->
{MegaSeconds, Seconds, MicroSeconds} = os:timestamp(),
(MegaSeconds * 1000000 + Seconds) * 1000000 + MicroSeconds;
timestamp(warp) ->
erlang:system_time(micro_seconds).
timestamp(erlang_timestamp, TimestampLast) ->
TimestampNext = timestamp(erlang_timestamp),
if
TimestampNext > TimestampLast ->
TimestampNext;
true ->
TimestampLast + 1
end;
timestamp(os, _) ->
timestamp(os);
timestamp(warp, _) ->
timestamp(warp).
-endif.
int_to_dec_list(I, N) when is_integer(I), I >= 0 ->
int_to_dec_list([], I, 1, N).
int_to_dec_list(L, I, Count, N)
when I < 10 ->
int_to_list_pad([int_to_dec(I) | L], N - Count);
int_to_dec_list(L, I, Count, N) ->
int_to_dec_list([int_to_dec(I rem 10) | L], I div 10, Count + 1, N).
int_to_hex_list(I, N) when is_integer(I), I >= 0 ->
int_to_hex_list([], I, 1, N).
int_to_list_pad(L, 0) ->
L;
int_to_list_pad(L, Count) ->
int_to_list_pad([$0 | L], Count - 1).
int_to_hex_list(L, I, Count, N)
when I < 16 ->
int_to_list_pad([int_to_hex(I) | L], N - Count);
int_to_hex_list(L, I, Count, N) ->
int_to_hex_list([int_to_hex(I rem 16) | L], I div 16, Count + 1, N).
int_to_dec(I) when 0 =< I, I =< 9 ->
I + $0.
int_to_hex(I) when 0 =< I, I =< 9 ->
I + $0;
int_to_hex(I) when 10 =< I, I =< 15 ->
(I - 10) + $a.
hex_to_int(C1, C2) ->
hex_to_int(C1) * 16 + hex_to_int(C2).
hex_to_int(C) when $0 =< C, C =< $9 ->
C - $0;
hex_to_int(C) when $A =< C, C =< $F ->
C - $A + 10;
hex_to_int(C) when $a =< C, C =< $f ->
C - $a + 10.
mac_address([]) ->
[0, 0, 0, 0, 0, 0];
mac_address([{_, L} | Rest]) ->
case lists:keyfind(hwaddr, 1, L) of
false ->
mac_address(Rest);
{hwaddr, MAC} ->
case lists:sum(MAC) of
0 ->
mac_address(Rest);
_ ->
MAC
end
end.
-ifdef(ERLANG_OTP_VERSION_18_FEATURES).
pseudo_random(N) ->
assuming exsplus for 58 bits , period 8.31e34
rand:uniform(N).
-else.
pseudo_random(N) ->
period 2.78e13
random:uniform(N).
-endif.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
internal_test_() ->
[
{"internal tests", ?_assertEqual(ok, test())}
].
-endif.
|
24967e0518573384bdf758223b30f436380180625a7662a1ccd275819ce75e6c | rescript-lang/rescript-compiler | matching_polyfill.ml | Copyright ( C ) 2020- , Authors of ReScript
*
* 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 .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a 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 .
*
* 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.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a 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. *)
let is_nullary_variant (x : Types.constructor_arguments) =
match x with Types.Cstr_tuple [] -> true | _ -> false
let names_from_construct_pattern (pat : Typedtree.pattern) =
let names_from_type_variant (cstrs : Types.constructor_declaration list) =
let consts, blocks =
Ext_list.fold_left cstrs ([], []) (fun (consts, blocks) cstr ->
if is_nullary_variant cstr.cd_args then
(Ident.name cstr.cd_id :: consts, blocks)
else (consts, Ident.name cstr.cd_id :: blocks))
in
Some
{
Lambda.consts = Ext_array.reverse_of_list consts;
blocks = Ext_array.reverse_of_list blocks;
}
in
let rec resolve_path n (path : Path.t) =
match Env.find_type path pat.pat_env with
| { type_kind = Type_variant cstrs; _ } -> names_from_type_variant cstrs
| { type_kind = Type_abstract; type_manifest = Some t; _ } -> (
match (Ctype.unalias t).desc with
| Tconstr (pathn, _, _) ->
Format.eprintf " XXX path%d:%s path%d:%s@. " n ( Path.name path ) ( n+1 ) ( Path.name ) ;
resolve_path (n + 1) pathn
| _ -> None)
| { type_kind = Type_abstract; type_manifest = None; _ } -> None
| { type_kind = Type_record _ | Type_open (* Exceptions *); _ } -> None
in
match (Btype.repr pat.pat_type).desc with
| Tconstr (path, _, _) -> resolve_path 0 path
| _ -> assert false
*
Note it is a bit tricky when there is unbound var ,
its type will be Tvar which is too complicated to support subtyping
Note it is a bit tricky when there is unbound var,
its type will be Tvar which is too complicated to support subtyping
*)
let variant_is_subtype (env : Env.t) (row_desc : Types.row_desc)
(ty : Types.type_expr) : bool =
match row_desc with
| {
row_closed = true;
row_fixed = _;
row_fields = (name, (Rabsent | Rpresent None)) :: rest;
} ->
if Ext_string.is_valid_hash_number name then
Ext_list.for_all rest (function
| name, (Rabsent | Rpresent None) ->
Ext_string.is_valid_hash_number name
| _ -> false)
&& Typeopt.is_base_type env ty Predef.path_int
else
Ext_list.for_all rest (function
| name, (Rabsent | Rpresent None) ->
not (Ext_string.is_valid_hash_number name)
| _ -> false)
&& Typeopt.is_base_type env ty Predef.path_string
| _ -> false
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/e60482c6f6a69994907b9bd56e58ce87052e3659/jscomp/core/matching_polyfill.ml | ocaml | Exceptions | Copyright ( C ) 2020- , Authors of ReScript
*
* 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 .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a 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 .
*
* 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.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a 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. *)
let is_nullary_variant (x : Types.constructor_arguments) =
match x with Types.Cstr_tuple [] -> true | _ -> false
let names_from_construct_pattern (pat : Typedtree.pattern) =
let names_from_type_variant (cstrs : Types.constructor_declaration list) =
let consts, blocks =
Ext_list.fold_left cstrs ([], []) (fun (consts, blocks) cstr ->
if is_nullary_variant cstr.cd_args then
(Ident.name cstr.cd_id :: consts, blocks)
else (consts, Ident.name cstr.cd_id :: blocks))
in
Some
{
Lambda.consts = Ext_array.reverse_of_list consts;
blocks = Ext_array.reverse_of_list blocks;
}
in
let rec resolve_path n (path : Path.t) =
match Env.find_type path pat.pat_env with
| { type_kind = Type_variant cstrs; _ } -> names_from_type_variant cstrs
| { type_kind = Type_abstract; type_manifest = Some t; _ } -> (
match (Ctype.unalias t).desc with
| Tconstr (pathn, _, _) ->
Format.eprintf " XXX path%d:%s path%d:%s@. " n ( Path.name path ) ( n+1 ) ( Path.name ) ;
resolve_path (n + 1) pathn
| _ -> None)
| { type_kind = Type_abstract; type_manifest = None; _ } -> None
in
match (Btype.repr pat.pat_type).desc with
| Tconstr (path, _, _) -> resolve_path 0 path
| _ -> assert false
*
Note it is a bit tricky when there is unbound var ,
its type will be Tvar which is too complicated to support subtyping
Note it is a bit tricky when there is unbound var,
its type will be Tvar which is too complicated to support subtyping
*)
let variant_is_subtype (env : Env.t) (row_desc : Types.row_desc)
(ty : Types.type_expr) : bool =
match row_desc with
| {
row_closed = true;
row_fixed = _;
row_fields = (name, (Rabsent | Rpresent None)) :: rest;
} ->
if Ext_string.is_valid_hash_number name then
Ext_list.for_all rest (function
| name, (Rabsent | Rpresent None) ->
Ext_string.is_valid_hash_number name
| _ -> false)
&& Typeopt.is_base_type env ty Predef.path_int
else
Ext_list.for_all rest (function
| name, (Rabsent | Rpresent None) ->
not (Ext_string.is_valid_hash_number name)
| _ -> false)
&& Typeopt.is_base_type env ty Predef.path_string
| _ -> false
|
2fe645109fe22dbaa5cd490cfce718f11eb6760352e01b879468657c433296aa | racket/htdp | guess1.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname guess1) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
(require htdp/guess)
;; check-guess : number number -> symbol
;; to determine how guess and target relate to each other
(define (check-guess guess target)
(cond
((< target guess) 'TooLarge)
((= target guess) 'Perfect)
((> target guess) 'TooSmall)))
;; Tests:
(eq? (check-guess 5000 5631) 'TooSmall)
(eq? (check-guess 6000 5631) 'TooLarge)
(eq? (check-guess 5631 5631) 'Perfect)
;; Test with GUI lib: set lib to guess-lib.ss
(check-expect (guess-with-gui check-guess) true)
; (guess-with-gui list)
; (define (foo x) x) (guess-with-gui foo)
( guess - with - gui first )
| null | https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-test/htdp/tests/guess1.rkt | racket | about the language level of this file in a form that our tools can easily process.
check-guess : number number -> symbol
to determine how guess and target relate to each other
Tests:
Test with GUI lib: set lib to guess-lib.ss
(guess-with-gui list)
(define (foo x) x) (guess-with-gui foo) | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname guess1) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ())))
(require htdp/guess)
(define (check-guess guess target)
(cond
((< target guess) 'TooLarge)
((= target guess) 'Perfect)
((> target guess) 'TooSmall)))
(eq? (check-guess 5000 5631) 'TooSmall)
(eq? (check-guess 6000 5631) 'TooLarge)
(eq? (check-guess 5631 5631) 'Perfect)
(check-expect (guess-with-gui check-guess) true)
( guess - with - gui first )
|
77159ea967577661add07062282e6f50fac65d0768525a91711b3e36ab56c8c9 | code-iai/ros_emacs_utils | swank-sprof.lisp | ;;; swank-sprof.lisp
;;
Authors :
;;
License : MIT
;;
(in-package :swank)
#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :sb-sprof))
#+sbcl(progn
(defvar *call-graph* nil)
(defvar *node-numbers* nil)
(defvar *number-nodes* nil)
(defun frame-name (name)
(if (consp name)
(case (first name)
((sb-c::xep sb-c::tl-xep
sb-c::&more-processor
sb-c::top-level-form
sb-c::&optional-processor)
(second name))
(sb-pcl::fast-method
(cdr name))
((flet labels lambda)
(let* ((in (member :in name)))
(if (stringp (cadr in))
(append (ldiff name in) (cddr in))
name)))
(t
name))
name))
(defun pretty-name (name)
(let ((*package* (find-package :common-lisp-user))
(*print-right-margin* most-positive-fixnum))
(format nil "~S" (frame-name name))))
(defun samples-percent (count)
(sb-sprof::samples-percent *call-graph* count))
(defun node-values (node)
(values (pretty-name (sb-sprof::node-name node))
(samples-percent (sb-sprof::node-count node))
(samples-percent (sb-sprof::node-accrued-count node))))
(defun filter-swank-nodes (nodes)
(let ((swank-packages (load-time-value
(mapcar #'find-package
'(swank swank/rpc swank/mop
swank/match swank/backend)))))
(remove-if (lambda (node)
(let ((name (sb-sprof::node-name node)))
(and (symbolp name)
(member (symbol-package name) swank-packages
:test #'eq))))
nodes)))
(defun serialize-call-graph (&key exclude-swank)
(let ((nodes (sb-sprof::call-graph-flat-nodes *call-graph*)))
(when exclude-swank
(setf nodes (filter-swank-nodes nodes)))
(setf nodes (sort (copy-list nodes) #'>
;; :key #'sb-sprof::node-count)))
:key #'sb-sprof::node-accrued-count))
(setf *number-nodes* (make-hash-table))
(setf *node-numbers* (make-hash-table))
(loop for node in nodes
for i from 1
with total = 0
collect (multiple-value-bind (name self cumulative)
(node-values node)
(setf (gethash node *node-numbers*) i
(gethash i *number-nodes*) node)
(incf total self)
(list i name self cumulative total)) into list
finally (return
(let ((rest (- 100 total)))
(return (append list
`((nil "Elsewhere" ,rest nil nil)))))))))
(defslimefun swank-sprof-get-call-graph (&key exclude-swank)
(when (setf *call-graph* (sb-sprof:report :type nil))
(serialize-call-graph :exclude-swank exclude-swank)))
(defslimefun swank-sprof-expand-node (index)
(let* ((node (gethash index *number-nodes*)))
(labels ((caller-count (v)
(loop for e in (sb-sprof::vertex-edges v) do
(when (eq (sb-sprof::edge-vertex e) node)
(return-from caller-count (sb-sprof::call-count e))))
0)
(serialize-node (node count)
(etypecase node
(sb-sprof::cycle
(list (sb-sprof::cycle-index node)
(sb-sprof::cycle-name node)
(samples-percent count)))
(sb-sprof::node
(let ((name (node-values node)))
(list (gethash node *node-numbers*)
name
(samples-percent count)))))))
(list :callers (loop for node in
(sort (copy-list (sb-sprof::node-callers node)) #'>
:key #'caller-count)
collect (serialize-node node
(caller-count node)))
:calls (let ((edges (sort (copy-list (sb-sprof::vertex-edges node))
#'>
:key #'sb-sprof::call-count)))
(loop for edge in edges
collect
(serialize-node (sb-sprof::edge-vertex edge)
(sb-sprof::call-count edge))))))))
(defslimefun swank-sprof-disassemble (index)
(let* ((node (gethash index *number-nodes*))
(debug-info (sb-sprof::node-debug-info node)))
(with-output-to-string (s)
(typecase debug-info
(sb-impl::code-component
(sb-disassem::disassemble-memory (sb-vm::code-instructions debug-info)
(sb-vm::%code-code-size debug-info)
:stream s))
(sb-di::compiled-debug-fun
(let ((component (sb-di::compiled-debug-fun-component debug-info)))
(sb-disassem::disassemble-code-component component :stream s)))
(t `(:error "No disassembly available"))))))
(defslimefun swank-sprof-source-location (index)
(let* ((node (gethash index *number-nodes*))
(debug-info (sb-sprof::node-debug-info node)))
(or (when (typep debug-info 'sb-di::compiled-debug-fun)
(let* ((component (sb-di::compiled-debug-fun-component debug-info))
(function (sb-kernel::%code-entry-points component)))
(when function
(find-source-location function))))
`(:error "No source location available"))))
(defslimefun swank-sprof-start (&key (mode :cpu))
(sb-sprof:start-profiling :mode mode))
(defslimefun swank-sprof-stop ()
(sb-sprof:stop-profiling))
)
(provide :swank-sprof)
| null | https://raw.githubusercontent.com/code-iai/ros_emacs_utils/67aafa699ff0d8c6476ec577a8587bac3d498028/slime_wrapper/slime/contrib/swank-sprof.lisp | lisp | swank-sprof.lisp
:key #'sb-sprof::node-count))) | Authors :
License : MIT
(in-package :swank)
#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :sb-sprof))
#+sbcl(progn
(defvar *call-graph* nil)
(defvar *node-numbers* nil)
(defvar *number-nodes* nil)
(defun frame-name (name)
(if (consp name)
(case (first name)
((sb-c::xep sb-c::tl-xep
sb-c::&more-processor
sb-c::top-level-form
sb-c::&optional-processor)
(second name))
(sb-pcl::fast-method
(cdr name))
((flet labels lambda)
(let* ((in (member :in name)))
(if (stringp (cadr in))
(append (ldiff name in) (cddr in))
name)))
(t
name))
name))
(defun pretty-name (name)
(let ((*package* (find-package :common-lisp-user))
(*print-right-margin* most-positive-fixnum))
(format nil "~S" (frame-name name))))
(defun samples-percent (count)
(sb-sprof::samples-percent *call-graph* count))
(defun node-values (node)
(values (pretty-name (sb-sprof::node-name node))
(samples-percent (sb-sprof::node-count node))
(samples-percent (sb-sprof::node-accrued-count node))))
(defun filter-swank-nodes (nodes)
(let ((swank-packages (load-time-value
(mapcar #'find-package
'(swank swank/rpc swank/mop
swank/match swank/backend)))))
(remove-if (lambda (node)
(let ((name (sb-sprof::node-name node)))
(and (symbolp name)
(member (symbol-package name) swank-packages
:test #'eq))))
nodes)))
(defun serialize-call-graph (&key exclude-swank)
(let ((nodes (sb-sprof::call-graph-flat-nodes *call-graph*)))
(when exclude-swank
(setf nodes (filter-swank-nodes nodes)))
(setf nodes (sort (copy-list nodes) #'>
:key #'sb-sprof::node-accrued-count))
(setf *number-nodes* (make-hash-table))
(setf *node-numbers* (make-hash-table))
(loop for node in nodes
for i from 1
with total = 0
collect (multiple-value-bind (name self cumulative)
(node-values node)
(setf (gethash node *node-numbers*) i
(gethash i *number-nodes*) node)
(incf total self)
(list i name self cumulative total)) into list
finally (return
(let ((rest (- 100 total)))
(return (append list
`((nil "Elsewhere" ,rest nil nil)))))))))
(defslimefun swank-sprof-get-call-graph (&key exclude-swank)
(when (setf *call-graph* (sb-sprof:report :type nil))
(serialize-call-graph :exclude-swank exclude-swank)))
(defslimefun swank-sprof-expand-node (index)
(let* ((node (gethash index *number-nodes*)))
(labels ((caller-count (v)
(loop for e in (sb-sprof::vertex-edges v) do
(when (eq (sb-sprof::edge-vertex e) node)
(return-from caller-count (sb-sprof::call-count e))))
0)
(serialize-node (node count)
(etypecase node
(sb-sprof::cycle
(list (sb-sprof::cycle-index node)
(sb-sprof::cycle-name node)
(samples-percent count)))
(sb-sprof::node
(let ((name (node-values node)))
(list (gethash node *node-numbers*)
name
(samples-percent count)))))))
(list :callers (loop for node in
(sort (copy-list (sb-sprof::node-callers node)) #'>
:key #'caller-count)
collect (serialize-node node
(caller-count node)))
:calls (let ((edges (sort (copy-list (sb-sprof::vertex-edges node))
#'>
:key #'sb-sprof::call-count)))
(loop for edge in edges
collect
(serialize-node (sb-sprof::edge-vertex edge)
(sb-sprof::call-count edge))))))))
(defslimefun swank-sprof-disassemble (index)
(let* ((node (gethash index *number-nodes*))
(debug-info (sb-sprof::node-debug-info node)))
(with-output-to-string (s)
(typecase debug-info
(sb-impl::code-component
(sb-disassem::disassemble-memory (sb-vm::code-instructions debug-info)
(sb-vm::%code-code-size debug-info)
:stream s))
(sb-di::compiled-debug-fun
(let ((component (sb-di::compiled-debug-fun-component debug-info)))
(sb-disassem::disassemble-code-component component :stream s)))
(t `(:error "No disassembly available"))))))
(defslimefun swank-sprof-source-location (index)
(let* ((node (gethash index *number-nodes*))
(debug-info (sb-sprof::node-debug-info node)))
(or (when (typep debug-info 'sb-di::compiled-debug-fun)
(let* ((component (sb-di::compiled-debug-fun-component debug-info))
(function (sb-kernel::%code-entry-points component)))
(when function
(find-source-location function))))
`(:error "No source location available"))))
(defslimefun swank-sprof-start (&key (mode :cpu))
(sb-sprof:start-profiling :mode mode))
(defslimefun swank-sprof-stop ()
(sb-sprof:stop-profiling))
)
(provide :swank-sprof)
|
9d9a1b7c380b2c1dc2345ac75b858c6730ee652bb2f5c0508c53a7fb9975a7cc | sibylfs/sibylfs_src | dump.mli | (****************************************************************************)
Copyright ( c ) 2013 , 2014 , 2015 , , , ,
( as part of the SibylFS project )
(* *)
(* Permission to use, copy, modify, and/or distribute this software for *)
(* any purpose with or without fee is hereby granted, provided that the *)
(* above copyright notice and this permission notice appear in all *)
(* copies. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL
(* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED *)
(* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE *)
(* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL *)
(* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR *)
PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR
(* PERFORMANCE OF THIS SOFTWARE. *)
(* *)
Meta :
(* - Headers maintained using headache. *)
(* - License source: *)
(****************************************************************************)
(* Dump *)
(* *)
(* This library is concerned with creating dumps of the current fs-state *)
open Diff
* { 2 Basic types }
type file = Fs_interface.Fs_dump_intf.file = {
file_path : string;
file_node : int;
file_size : int;
file_sha : string;
} with sexp
type dir = Fs_interface.Fs_dump_intf.dir = {
dir_path : string;
dir_node : int;
} with sexp
type symlink = Fs_interface.Fs_dump_intf.symlink = {
link_path : string;
link_val : string;
} with sexp
type error = Fs_interface.Fs_dump_intf.error with sexp
type dump_error = Unix_error of error | Unknown of string
exception Dump_error of dump_error
type entry = Fs_interface.Fs_dump_intf.entry =
| DE_file of file
| DE_dir of dir
| DE_symlink of symlink
| DE_error of error
with sexp
type t = entry list with sexp
(* Difference types *)
type d_file = {
d_files : file * file;
d_file_path : string diff;
d_file_size : int diff;
d_file_sha : string diff;
} with sexp
type d_dir = {
d_dirs : dir * dir;
d_dir_path : string diff;
} with sexp
type d_symlink = {
d_links : symlink * symlink;
d_link_path : string diff;
d_link_val : string diff;
} with sexp
type d_error = {
d_errors : error * error;
d_error : Fs_interface.Fs_spec_intf.Fs_types.error diff;
d_error_call : string diff;
d_error_path : string diff;
} with sexp
type deviant =
| DDE_file of d_file
| DDE_dir of d_dir
| DDE_symlink of d_symlink
| DDE_error of d_error
with sexp
type d_entry =
| DDE_missing of entry
| DDE_unexpected of entry
| DDE_deviant of deviant
| DDE_type_error of entry diff
with sexp
type d_t =
| D_path of string diff
| D_t of d_entry list
with sexp
val path : entry -> string
val to_csv_strings : t -> string list
(** [diff da1 da2] checks whether the label [Dump da1]
and [Dump da2] agree with each other. It returns an optional
error message. If [None] is returned, everything is OK. *)
val diff : string * t -> string * t -> d_t option
val string_of_d_t : d_t -> string
* { 2 Creating dumps }
(** The module type [Dump_fs_operations] abstacts the operations
needed to greate a dump of a fs *)
module type Dump_fs_operations = sig
type state
type dir_status
(** [ls_path s p] returns a list of all the files and directories
under path [p] excluding [p] itself. It does not list the
content of subdirectories. [p] is assumed to be a directory (not
a symlink to a directory). *)
val ls_path : state -> Fs_path.t -> string list
(** [kind_of_path s p] returns the file-kind of the file
identified by path [p], If such a file does not exist, or
is not a dir, regular file or symbolic link, [kind_of_path]
fails. *)
val kind_of_path : state -> Fs_path.t -> Unix.file_kind
* [ sha1_of_path s p ] returns the file - size and the hash of
path [ p ] in state [ s ] . If [ path ] is not a regular file ,
the function fails .
path [p] in state [s]. If [path] is not a regular file,
the function fails. *)
val sha1_of_path : state -> Fs_path.t -> (int * string)
* [ s p ] reads the symbolic link indentified by path [ p ]
in state [ s ] . If [ path ] is not a symbolic link ,
the function fails .
in state [s]. If [path] is not a symbolic link,
the function fails. *)
val readlink : state -> Fs_path.t -> string
(** [inode_of_file_path s p] gets the inode of the file indentified
by path [p] in state [s]. If [path] is not a regular file, the
function fails. *)
val inode_of_file_path : state -> Fs_path.t -> int
(** [inode_of_dir_path s p] gets the inode of the file indentified
by path [p] in state [s]. If [path] is not a directory, the
function fails. *)
val inode_of_dir_path : state -> Fs_path.t -> int
* [ enter_dir p ] indicates that a directory is entered . This
might be used to set some permissions so further commands
wo n't fail . It returns some state , which is used to
undo changes via [ leave_dir ]
might be used to set some permissions so further commands
won't fail. It returns some state, which is used to
undo changes via [leave_dir] *)
val enter_dir : state -> Fs_path.t -> dir_status
(** see [enter_dir] *)
val leave_dir : state -> Fs_path.t -> dir_status -> unit
end
(** [Dump_fs_operations] are used to instantiate [Make] to create dumps. *)
module Make(DO : Dump_fs_operations) : sig
(** [of_path s0 p] creates dump of path [p] in
state [s0]. Dump might fail for various reasons. In
this case [Dump_error] is raised. Common reasons for it to
fail are [p] not describing and existing directory in
state [s0] or insufficient permissions to dump this
directory. *)
val of_path : DO.state -> string -> t
end
| null | https://raw.githubusercontent.com/sibylfs/sibylfs_src/30675bc3b91e73f7133d0c30f18857bb1f4df8fa/fs_test/lib/dump.mli | ocaml | **************************************************************************
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.
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
PERFORMANCE OF THIS SOFTWARE.
- Headers maintained using headache.
- License source:
**************************************************************************
Dump
This library is concerned with creating dumps of the current fs-state
Difference types
* [diff da1 da2] checks whether the label [Dump da1]
and [Dump da2] agree with each other. It returns an optional
error message. If [None] is returned, everything is OK.
* The module type [Dump_fs_operations] abstacts the operations
needed to greate a dump of a fs
* [ls_path s p] returns a list of all the files and directories
under path [p] excluding [p] itself. It does not list the
content of subdirectories. [p] is assumed to be a directory (not
a symlink to a directory).
* [kind_of_path s p] returns the file-kind of the file
identified by path [p], If such a file does not exist, or
is not a dir, regular file or symbolic link, [kind_of_path]
fails.
* [inode_of_file_path s p] gets the inode of the file indentified
by path [p] in state [s]. If [path] is not a regular file, the
function fails.
* [inode_of_dir_path s p] gets the inode of the file indentified
by path [p] in state [s]. If [path] is not a directory, the
function fails.
* see [enter_dir]
* [Dump_fs_operations] are used to instantiate [Make] to create dumps.
* [of_path s0 p] creates dump of path [p] in
state [s0]. Dump might fail for various reasons. In
this case [Dump_error] is raised. Common reasons for it to
fail are [p] not describing and existing directory in
state [s0] or insufficient permissions to dump this
directory. | Copyright ( c ) 2013 , 2014 , 2015 , , , ,
( as part of the SibylFS project )
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL
PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR
Meta :
open Diff
* { 2 Basic types }
type file = Fs_interface.Fs_dump_intf.file = {
file_path : string;
file_node : int;
file_size : int;
file_sha : string;
} with sexp
type dir = Fs_interface.Fs_dump_intf.dir = {
dir_path : string;
dir_node : int;
} with sexp
type symlink = Fs_interface.Fs_dump_intf.symlink = {
link_path : string;
link_val : string;
} with sexp
type error = Fs_interface.Fs_dump_intf.error with sexp
type dump_error = Unix_error of error | Unknown of string
exception Dump_error of dump_error
type entry = Fs_interface.Fs_dump_intf.entry =
| DE_file of file
| DE_dir of dir
| DE_symlink of symlink
| DE_error of error
with sexp
type t = entry list with sexp
type d_file = {
d_files : file * file;
d_file_path : string diff;
d_file_size : int diff;
d_file_sha : string diff;
} with sexp
type d_dir = {
d_dirs : dir * dir;
d_dir_path : string diff;
} with sexp
type d_symlink = {
d_links : symlink * symlink;
d_link_path : string diff;
d_link_val : string diff;
} with sexp
type d_error = {
d_errors : error * error;
d_error : Fs_interface.Fs_spec_intf.Fs_types.error diff;
d_error_call : string diff;
d_error_path : string diff;
} with sexp
type deviant =
| DDE_file of d_file
| DDE_dir of d_dir
| DDE_symlink of d_symlink
| DDE_error of d_error
with sexp
type d_entry =
| DDE_missing of entry
| DDE_unexpected of entry
| DDE_deviant of deviant
| DDE_type_error of entry diff
with sexp
type d_t =
| D_path of string diff
| D_t of d_entry list
with sexp
val path : entry -> string
val to_csv_strings : t -> string list
val diff : string * t -> string * t -> d_t option
val string_of_d_t : d_t -> string
* { 2 Creating dumps }
module type Dump_fs_operations = sig
type state
type dir_status
val ls_path : state -> Fs_path.t -> string list
val kind_of_path : state -> Fs_path.t -> Unix.file_kind
* [ sha1_of_path s p ] returns the file - size and the hash of
path [ p ] in state [ s ] . If [ path ] is not a regular file ,
the function fails .
path [p] in state [s]. If [path] is not a regular file,
the function fails. *)
val sha1_of_path : state -> Fs_path.t -> (int * string)
* [ s p ] reads the symbolic link indentified by path [ p ]
in state [ s ] . If [ path ] is not a symbolic link ,
the function fails .
in state [s]. If [path] is not a symbolic link,
the function fails. *)
val readlink : state -> Fs_path.t -> string
val inode_of_file_path : state -> Fs_path.t -> int
val inode_of_dir_path : state -> Fs_path.t -> int
* [ enter_dir p ] indicates that a directory is entered . This
might be used to set some permissions so further commands
wo n't fail . It returns some state , which is used to
undo changes via [ leave_dir ]
might be used to set some permissions so further commands
won't fail. It returns some state, which is used to
undo changes via [leave_dir] *)
val enter_dir : state -> Fs_path.t -> dir_status
val leave_dir : state -> Fs_path.t -> dir_status -> unit
end
module Make(DO : Dump_fs_operations) : sig
val of_path : DO.state -> string -> t
end
|
92ef7c750307c79f97bd92ee074184ee2d0599fb312ca5a1732488dd65b7ee9b | pkhuong/bitap-regexp | generate-epsilon.lisp | (defun %make-simd-pack-ub128 (x)
(%make-simd-pack-ub64 (ldb (byte 64 0) x)
(ldb (byte 64 64) x)))
(defun %simd-pack-ub128 (x)
(multiple-value-bind (low high)
(%simd-pack-ub64s x)
(logior low (ash high 64))))
(defconstant +state-size+ 128)
(defconstant +chunk-size+ 64)
(deftype index ()
`(and unsigned-byte fixnum))
(defstruct (row
(:constructor %make-row (index row indices)))
(index 0 :type index :read-only t)
(number nil :type (or null index))
(row nil :type (unsigned-byte #.+state-size+) :read-only t)
(indices nil :type (simple-array index 1) :read-only t))
(defun make-row (index &key row indices)
(declare (type (or null (unsigned-byte #.+state-size+)) row)
(type (or null (simple-array index 1)) indices))
(assert (or row indices))
(cond ((and row indices)
(setf (logbitp index row) 1)
(dotimes (i +state-size+)
(when (logbitp i row)
(assert (find i indices))))
(map nil (lambda (i)
(assert (logbitp i row)))
indices))
(row
(setf (logbitp index row) 1)
(let ((acc '()))
(dotimes (i +state-size+)
(when (logbitp i row)
(push i acc)))
(setf indices (coerce (nreverse acc)
'(simple-array index 1)))))
(indices
(setf row 0)
(map nil (lambda (i)
(setf (logbitp i row) 1))
indices)))
(assert (logbitp index row))
(assert indices)
(%make-row index row (sort (copy-seq indices) #'<)))
(defun make-rows (adjacency)
(let ((rows (make-array +state-size+ :initial-element 0)))
(loop for (i . j) in adjacency
do (setf (logbitp j (aref rows i)) 1))
(let ((i 0))
(map 'simple-vector (lambda (row)
(prog1 (make-row i :row row)
(incf i)))
rows))))
(defun order-rows (rows)
(declare (type simple-vector rows))
(assert (= +state-size+ (length rows)))
(setf rows (sort (copy-seq rows)
#'>
:key (lambda (row)
(+ (* +state-size+ (length (row-indices row)))
(row-index row)))))
(dotimes (i (length rows) rows)
(setf (row-number (aref rows i)) i)))
(defstruct (op
(:constructor nil))
(src 0 :type (or index list) :read-only t)
(anti-deps #() :type vector :read-only t))
(defstruct (simple-op
(:include op)
(:constructor make-simple-op (src dst &aux (anti-deps (vector dst)))))
(dst 0 :type index :read-only t))
(defstruct (row-op
(:include op)
(:constructor make-row-op (src row)))
(row nil :type (unsigned-byte #.+state-size+) :read-only t))
(defstruct (multi-row-op
(:include op)
(:constructor make-multi-row-op (src row)))
(row nil :type (unsigned-byte #.+state-size+) :read-only t))
(defun find-simple-op (row rows)
(let* ((i (row-index row))
(number (row-number row))
(op (logandc2 (row-row row) (ash 1 i)))
(value -1)
(dst nil))
(map nil (lambda (j)
(let ((other (aref rows j))
(op (logandc2 op (ash 1 j))))
(when (and (/= i j)
(> (row-number other) number)
(= op (logand op (row-row other)))
(> (row-number other) value))
(setf value (row-number other)
dst j))))
(row-indices row))
(when dst
(make-simple-op i dst))))
(defun find-row-op (row)
(let ((i (row-index row)))
(when (notevery (lambda (j)
(eql j i))
(row-indices row))
(make-row-op i (row-row row)))))
(defun find-multirow-ops (ops)
(let ((row-ops (make-hash-table)))
(map nil (lambda (op)
(when (row-op-p op)
(setf (gethash (row-op-src op) row-ops)
(list op))))
ops)
(let ((acc '()))
(map nil (lambda (op)
(etypecase op
(simple-op
(let* ((dst (simple-op-dst op))
(entry (gethash dst row-ops)))
(if entry
(push (simple-op-src op) (cdr entry))
(push op acc))))
(row-op
(let ((entry (shiftf (gethash (row-op-src op) row-ops) nil)))
(assert entry)
(destructuring-bind (op . others)
entry
(let ((src (row-op-src op)))
(cond ((not others)
(push op acc))
(t
(push (make-multi-row-op (cons src others)
(logior (row-op-row op)
(ash 1 src)))
acc)))))))))
ops)
(coerce (nreverse acc) 'simple-vector))))
(defun merge-row-ops (ops)
(flet ((row-op-mask (op)
(logandc2 (row-op-row op)
(ash 1 (row-op-src op)))))
(let ((row-ops (make-hash-table))
acc)
(map nil (lambda (op)
(when (row-op-p op)
(push op (gethash (row-op-mask op) row-ops))))
ops)
(map nil (lambda (op)
(if (row-op-p op)
(let* ((mask (row-op-mask op))
(ops (shiftf (gethash mask row-ops) nil)))
(cond ((null ops))
((cdr ops)
(push (make-multi-row-op (mapcar #'row-op-src ops)
mask)
acc))
(t (push op acc))))
(push op acc)))
ops)
(coerce (nreverse acc) 'simple-vector))))
(defun find-ops (ordered-rows rows)
(merge-row-ops
(find-multirow-ops
(delete nil (map 'simple-vector
(lambda (src)
(or (find-simple-op src rows)
(find-row-op src)))
ordered-rows)))))
try to find up to 4 - wide parallelism
(defvar *bundle-size* 4)
(defun find-shifts (ready)
;; which chunk . mod-chunk shift
(let ((shifts (make-hash-table :test 'equal)))
(map nil (lambda (ready)
(when (simple-op-p ready)
(let ((chunk (truncate (op-src ready) +chunk-size+))
(shift (- (mod (simple-op-dst ready) +chunk-size+)
(mod (op-src ready) +chunk-size+))))
(push ready (gethash (cons chunk shift) shifts)))))
ready)
(sort (alexandria:hash-table-alist shifts)
#'> :key #'length)))
(defun find-rows (ready)
(nreverse (remove-if-not (lambda (x)
(typep x '(or row-op multi-row-op)))
ready)))
(defgeneric generate (op))
(defmethod generate ((shift list))
(destructuring-bind ((chunk . shift) . ops)
shift
(let ((mask (let ((low 0)
(high 0))
(mapc (lambda (op)
(let ((src (op-src op))
(dst-chunk (truncate (simple-op-dst op)
+chunk-size+)))
(assert (= (truncate src +chunk-size+) chunk))
(ecase dst-chunk
(0
(setf (logbitp (mod src +chunk-size+) low) 1))
(1
(setf (logbitp (mod src +chunk-size+) high) 1)))))
ops)
(if (= (ash low shift)
(ash high shift)
(ash (ldb (byte +chunk-size+ 0) -1) shift))
nil
(%make-simd-pack-ub64 low high))))
(source (if (every (lambda (op)
(= (truncate (simple-op-src op) +chunk-size+)
(truncate (simple-op-dst op) +chunk-size+)))
ops)
'source
(ecase chunk
(0 'low-source)
(1 'high-source)))))
`(lambda (source low-source high-source ones zero)
(declare (ignore ones zero)
(ignorable source low-source high-source))
',(acons chunk shift ops)
(let ((select ,(if mask
`(pand ,source ,mask)
source)))
,(cond ((zerop shift)
'select)
((minusp shift)
`(psrlq select ,(- shift)))
(t
`(psllq select ,shift))))))))
(defmethod generate ((op row-op))
(let* ((src (row-op-src op))
(row (row-op-row op))
(ones `(psllq ones ,(mod src +chunk-size+))))
(if (or (and (< src 64) (typep row '(unsigned-byte 64)))
(and (>= src 64) (zerop (ldb (byte 64 0) row))))
`(lambda (source low-source high-source ones zero)
(declare (ignore low-source high-source zero))
',op
(let* ((ones ,ones)
(select (pand source ones))
(mask (pcmpeqq select ones)))
(pand mask ,(%make-simd-pack-ub128 row))))
`(lambda (source low-source high-source ones zero)
(declare (ignorable low-source high-source)
(ignore source zero))
',op
,(let ((source (ecase (truncate src +chunk-size+)
(0 'low-source)
(1 'high-source))))
`(let* ((ones ,ones)
(select (pand ,source ones))
(mask (pcmpeqq select ones)))
(pand mask ,(%make-simd-pack-ub128 row))))))))
(defmethod generate ((op multi-row-op))
(let* ((src (multi-row-op-src op))
(row (multi-row-op-row op))
(low-mask 0)
(high-mask 0))
(dolist (src src)
(multiple-value-bind (chunk offset)
(truncate src +chunk-size+)
(ecase chunk
(0 (setf (logbitp offset low-mask) 1))
(1 (setf (logbitp offset high-mask) 1)))))
(if (or (and (zerop high-mask) (typep row '(unsigned-byte 64)))
(and (zerop low-mask) (zerop (ldb (byte 64 0) row))))
`(lambda (source low-source high-source ones zero)
(declare (ignore low-source high-source ones))
',op
(let* ((select (pand source ,(%make-simd-pack-ub64 low-mask high-mask)))
(maskn (pcmpeqq select zero)))
(pandn maskn ,(%make-simd-pack-ub128 row))))
`(lambda (source low-source high-source ones zero)
(declare (ignorable low-source high-source)
(ignore source ones))
',op
,(let ((low-select (and (plusp low-mask)
(if (= low-mask (ldb (byte 64 0) -1))
'low-source
`(pand low-source ,(%make-simd-pack-ub64 low-mask
low-mask)))))
(high-select (and (plusp high-mask)
(if (= high-mask (ldb (byte 64 0) -1))
'high-source
`(pand high-source ,(%make-simd-pack-ub64 high-mask
high-mask))))))
`(let* ((select ,(cond ((and low-select high-select)
`(por ,low-select
,high-select))
(low-select)
(high-select)
(t (error "No source?"))))
(maskn (pcmpeqq select zero)))
(pandn maskn ,(%make-simd-pack-ub128 row))))))))
(defun retire-ops (ready)
(let ((shifts (find-shifts ready))
(rows (find-rows ready))
(chosen '())
(instructions '()))
(loop for i below *bundle-size*
while (or shifts rows)
do (multiple-value-bind (choice instruction)
;; start with rows: they can never be coalesced
and either uses exactly one memory op
(if rows
(let ((row (pop rows)))
(values row (generate row)))
(let ((shift (pop shifts)))
(values (cdr shift)
(generate shift))))
(if (listp choice)
(setf chosen (append choice chosen))
(push choice chosen))
(push instruction instructions)))
(values chosen (nreverse instructions))))
(defun schedule-ops (ops)
(let ((schedule (map-into (make-array +state-size+)
(lambda ()
(cons 0 nil)))))
(map nil (lambda (op)
(let ((src (op-src op)))
(when (listp src) ; choose a representative
(setf src (first src))) ; arbitrarily
(setf (cdr (aref schedule src)) op)
(map nil (lambda (anti-dep)
(incf (car (aref schedule anti-dep))))
(op-anti-deps op))))
ops)
(let ((ready '())
(retired '()))
(labels ((find-ready ()
(loop for cons across schedule
for (countdown . op) = cons
when (and op (zerop countdown)
(typecase (op-src op)
(index t)
(cons
(every (lambda (src)
(zerop (car (aref schedule src))))
(op-src op)))))
do (push op ready)
(setf (cdr cons) nil)))
(maybe-exit ()
(when (null ready)
(assert (every (lambda (x)
(null (cdr x)))
schedule))
(return-from schedule-ops (nreverse retired)))))
(loop
(find-ready)
(maybe-exit)
(multiple-value-bind (done instruction)
(retire-ops ready)
(mapc (lambda (done)
(map nil (lambda (anti-dep)
(decf (car (aref schedule anti-dep))))
(op-anti-deps done)))
done)
(setf ready (set-difference ready done))
(push instruction retired)))))))
(defun emit-instructions-1 (scheduled-instructions input)
(let ((source (gensym "SOURCE"))
(low (gensym "LOW"))
(high (gensym "HIGH"))
(ones (gensym "ONES"))
(zero (gensym "ZERO")))
(labels ((emit-por-tree (temps)
(assert temps)
(if (null (cdr temps))
(car temps)
(let* ((half (ceiling (length temps) 2)))
`(por ,(emit-por-tree (subseq temps 0 half))
,(emit-por-tree (subseq temps half))))))
(emit-one-step (step)
(let (temps)
`(let* ((,low (punpcklqdq ,source ,source))
(,high (punpckhqdq ,source ,source))
,@(loop for op in step
for temp = (gensym "ROW")
do (push temp temps)
collect `(,temp (,op ,source ,low ,high ,ones ,zero))))
,(emit-por-tree (cons source (nreverse temps)))))))
(if scheduled-instructions
(values `(let ((,source ,input))
(declare (type (simd-pack integer) ,source))
(let* ,(loop for bundle in scheduled-instructions
collect `(,source ,(emit-one-step bundle)))
,source))
;; avoid constant propagation
`(let ((,ones (to-simd-pack-integer
(%make-simd-pack-ub64 1 1)))
(,zero (to-simd-pack-integer
(%make-simd-pack-ub64 0 0))))
(declare (type (simd-pack integer) ,ones ,zero))))
(values `(the (simd-pack integer) ,input) nil)))))
(defun emit-instructions (scheduled-instructions input)
(multiple-value-bind (body around)
(emit-instructions-1 scheduled-instructions input)
(if around
(append around (list body))
body)))
(defun compile-adjacency (adjacency input &key raw)
(let* ((rows (make-rows adjacency))
(order (order-rows rows))
(ops (find-ops order rows))
(schedule (schedule-ops ops)))
(funcall (if raw #'emit-instructions-1 #'emit-instructions)
schedule input)))
(defun transitive-closure (arcs)
(declare (optimize debug))
(let ((transpose (map 'simple-vector
(lambda (dst)
(let ((hash (make-hash-table)))
(map nil (lambda (dst)
(setf (gethash dst hash) t))
dst)
hash))
(transpose arcs)))
delta)
(loop
(setf delta nil)
(dotimes (i 128)
(let ((acc (aref transpose i)))
(flet ((try (dst)
(unless (gethash dst acc)
(setf delta t)
(setf (gethash dst acc) t))))
(try i)
(maphash (lambda (j _) _
(maphash (lambda (k v) v
(try k))
(aref transpose j)))
acc))))
(unless delta
(return)))
(loop for i upfrom 0
for spec across transpose
do (remhash i spec)
append (map 'list (lambda (j)
(cons i j))
(sort (alexandria:hash-table-keys spec) #'<)))))
(defvar *max* 128)
(defun random-transitions (n &aux (max *max*))
(transitive-closure
(let ((keys (make-hash-table :test 'equal)))
(loop repeat (* n n)
while (< (hash-table-count keys) n)
do (setf (gethash (cons (random max) (random max)) keys) t))
(alexandria:hash-table-keys keys))))
(defun transpose (transitions)
(let ((destinations (make-array 128 :initial-element '())))
(loop for (src . dst) in transitions
do (pushnew dst (aref destinations src))
finally (return destinations))))
(defun test (transitions)
(declare (optimize debug))
(let* ((code (compile nil `(lambda (x)
(declare (type (simd-pack integer) x))
,(compile-adjacency transitions 'x))))
(spec (transpose transitions)))
(dotimes (i 128)
(let ((result (%simd-pack-ub128
(funcall code (%make-simd-pack-ub128 (ash 1 i)))))
(expected (adjoin i (aref spec i))))
(assert (= (logcount result) (length expected)))
(map nil (lambda (j)
(assert (logbitp j result)))
expected)))))
(defvar *state* (sb-ext:seed-random-state 1234578))
(defun n-tests (min max repetitions)
(declare (optimize debug))
(loop for count from min upto max do
(format t "count: ~A -" count)
(finish-output)
(let ((*random-state* (make-random-state *state*)))
(loop repeat repetitions
for random = (random-transitions count)
do (format t " ~A" (length random))
(finish-output)
(test random)))
(format t "~%")
(finish-output)))
| null | https://raw.githubusercontent.com/pkhuong/bitap-regexp/b24beb2dd74e4f79263f3f8f5d09199f16dc9c34/generate-epsilon.lisp | lisp | which chunk . mod-chunk shift
start with rows: they can never be coalesced
choose a representative
arbitrarily
avoid constant propagation | (defun %make-simd-pack-ub128 (x)
(%make-simd-pack-ub64 (ldb (byte 64 0) x)
(ldb (byte 64 64) x)))
(defun %simd-pack-ub128 (x)
(multiple-value-bind (low high)
(%simd-pack-ub64s x)
(logior low (ash high 64))))
(defconstant +state-size+ 128)
(defconstant +chunk-size+ 64)
(deftype index ()
`(and unsigned-byte fixnum))
(defstruct (row
(:constructor %make-row (index row indices)))
(index 0 :type index :read-only t)
(number nil :type (or null index))
(row nil :type (unsigned-byte #.+state-size+) :read-only t)
(indices nil :type (simple-array index 1) :read-only t))
(defun make-row (index &key row indices)
(declare (type (or null (unsigned-byte #.+state-size+)) row)
(type (or null (simple-array index 1)) indices))
(assert (or row indices))
(cond ((and row indices)
(setf (logbitp index row) 1)
(dotimes (i +state-size+)
(when (logbitp i row)
(assert (find i indices))))
(map nil (lambda (i)
(assert (logbitp i row)))
indices))
(row
(setf (logbitp index row) 1)
(let ((acc '()))
(dotimes (i +state-size+)
(when (logbitp i row)
(push i acc)))
(setf indices (coerce (nreverse acc)
'(simple-array index 1)))))
(indices
(setf row 0)
(map nil (lambda (i)
(setf (logbitp i row) 1))
indices)))
(assert (logbitp index row))
(assert indices)
(%make-row index row (sort (copy-seq indices) #'<)))
(defun make-rows (adjacency)
(let ((rows (make-array +state-size+ :initial-element 0)))
(loop for (i . j) in adjacency
do (setf (logbitp j (aref rows i)) 1))
(let ((i 0))
(map 'simple-vector (lambda (row)
(prog1 (make-row i :row row)
(incf i)))
rows))))
(defun order-rows (rows)
(declare (type simple-vector rows))
(assert (= +state-size+ (length rows)))
(setf rows (sort (copy-seq rows)
#'>
:key (lambda (row)
(+ (* +state-size+ (length (row-indices row)))
(row-index row)))))
(dotimes (i (length rows) rows)
(setf (row-number (aref rows i)) i)))
(defstruct (op
(:constructor nil))
(src 0 :type (or index list) :read-only t)
(anti-deps #() :type vector :read-only t))
(defstruct (simple-op
(:include op)
(:constructor make-simple-op (src dst &aux (anti-deps (vector dst)))))
(dst 0 :type index :read-only t))
(defstruct (row-op
(:include op)
(:constructor make-row-op (src row)))
(row nil :type (unsigned-byte #.+state-size+) :read-only t))
(defstruct (multi-row-op
(:include op)
(:constructor make-multi-row-op (src row)))
(row nil :type (unsigned-byte #.+state-size+) :read-only t))
(defun find-simple-op (row rows)
(let* ((i (row-index row))
(number (row-number row))
(op (logandc2 (row-row row) (ash 1 i)))
(value -1)
(dst nil))
(map nil (lambda (j)
(let ((other (aref rows j))
(op (logandc2 op (ash 1 j))))
(when (and (/= i j)
(> (row-number other) number)
(= op (logand op (row-row other)))
(> (row-number other) value))
(setf value (row-number other)
dst j))))
(row-indices row))
(when dst
(make-simple-op i dst))))
(defun find-row-op (row)
(let ((i (row-index row)))
(when (notevery (lambda (j)
(eql j i))
(row-indices row))
(make-row-op i (row-row row)))))
(defun find-multirow-ops (ops)
(let ((row-ops (make-hash-table)))
(map nil (lambda (op)
(when (row-op-p op)
(setf (gethash (row-op-src op) row-ops)
(list op))))
ops)
(let ((acc '()))
(map nil (lambda (op)
(etypecase op
(simple-op
(let* ((dst (simple-op-dst op))
(entry (gethash dst row-ops)))
(if entry
(push (simple-op-src op) (cdr entry))
(push op acc))))
(row-op
(let ((entry (shiftf (gethash (row-op-src op) row-ops) nil)))
(assert entry)
(destructuring-bind (op . others)
entry
(let ((src (row-op-src op)))
(cond ((not others)
(push op acc))
(t
(push (make-multi-row-op (cons src others)
(logior (row-op-row op)
(ash 1 src)))
acc)))))))))
ops)
(coerce (nreverse acc) 'simple-vector))))
(defun merge-row-ops (ops)
(flet ((row-op-mask (op)
(logandc2 (row-op-row op)
(ash 1 (row-op-src op)))))
(let ((row-ops (make-hash-table))
acc)
(map nil (lambda (op)
(when (row-op-p op)
(push op (gethash (row-op-mask op) row-ops))))
ops)
(map nil (lambda (op)
(if (row-op-p op)
(let* ((mask (row-op-mask op))
(ops (shiftf (gethash mask row-ops) nil)))
(cond ((null ops))
((cdr ops)
(push (make-multi-row-op (mapcar #'row-op-src ops)
mask)
acc))
(t (push op acc))))
(push op acc)))
ops)
(coerce (nreverse acc) 'simple-vector))))
(defun find-ops (ordered-rows rows)
(merge-row-ops
(find-multirow-ops
(delete nil (map 'simple-vector
(lambda (src)
(or (find-simple-op src rows)
(find-row-op src)))
ordered-rows)))))
try to find up to 4 - wide parallelism
(defvar *bundle-size* 4)
(defun find-shifts (ready)
(let ((shifts (make-hash-table :test 'equal)))
(map nil (lambda (ready)
(when (simple-op-p ready)
(let ((chunk (truncate (op-src ready) +chunk-size+))
(shift (- (mod (simple-op-dst ready) +chunk-size+)
(mod (op-src ready) +chunk-size+))))
(push ready (gethash (cons chunk shift) shifts)))))
ready)
(sort (alexandria:hash-table-alist shifts)
#'> :key #'length)))
(defun find-rows (ready)
(nreverse (remove-if-not (lambda (x)
(typep x '(or row-op multi-row-op)))
ready)))
(defgeneric generate (op))
(defmethod generate ((shift list))
(destructuring-bind ((chunk . shift) . ops)
shift
(let ((mask (let ((low 0)
(high 0))
(mapc (lambda (op)
(let ((src (op-src op))
(dst-chunk (truncate (simple-op-dst op)
+chunk-size+)))
(assert (= (truncate src +chunk-size+) chunk))
(ecase dst-chunk
(0
(setf (logbitp (mod src +chunk-size+) low) 1))
(1
(setf (logbitp (mod src +chunk-size+) high) 1)))))
ops)
(if (= (ash low shift)
(ash high shift)
(ash (ldb (byte +chunk-size+ 0) -1) shift))
nil
(%make-simd-pack-ub64 low high))))
(source (if (every (lambda (op)
(= (truncate (simple-op-src op) +chunk-size+)
(truncate (simple-op-dst op) +chunk-size+)))
ops)
'source
(ecase chunk
(0 'low-source)
(1 'high-source)))))
`(lambda (source low-source high-source ones zero)
(declare (ignore ones zero)
(ignorable source low-source high-source))
',(acons chunk shift ops)
(let ((select ,(if mask
`(pand ,source ,mask)
source)))
,(cond ((zerop shift)
'select)
((minusp shift)
`(psrlq select ,(- shift)))
(t
`(psllq select ,shift))))))))
(defmethod generate ((op row-op))
(let* ((src (row-op-src op))
(row (row-op-row op))
(ones `(psllq ones ,(mod src +chunk-size+))))
(if (or (and (< src 64) (typep row '(unsigned-byte 64)))
(and (>= src 64) (zerop (ldb (byte 64 0) row))))
`(lambda (source low-source high-source ones zero)
(declare (ignore low-source high-source zero))
',op
(let* ((ones ,ones)
(select (pand source ones))
(mask (pcmpeqq select ones)))
(pand mask ,(%make-simd-pack-ub128 row))))
`(lambda (source low-source high-source ones zero)
(declare (ignorable low-source high-source)
(ignore source zero))
',op
,(let ((source (ecase (truncate src +chunk-size+)
(0 'low-source)
(1 'high-source))))
`(let* ((ones ,ones)
(select (pand ,source ones))
(mask (pcmpeqq select ones)))
(pand mask ,(%make-simd-pack-ub128 row))))))))
(defmethod generate ((op multi-row-op))
(let* ((src (multi-row-op-src op))
(row (multi-row-op-row op))
(low-mask 0)
(high-mask 0))
(dolist (src src)
(multiple-value-bind (chunk offset)
(truncate src +chunk-size+)
(ecase chunk
(0 (setf (logbitp offset low-mask) 1))
(1 (setf (logbitp offset high-mask) 1)))))
(if (or (and (zerop high-mask) (typep row '(unsigned-byte 64)))
(and (zerop low-mask) (zerop (ldb (byte 64 0) row))))
`(lambda (source low-source high-source ones zero)
(declare (ignore low-source high-source ones))
',op
(let* ((select (pand source ,(%make-simd-pack-ub64 low-mask high-mask)))
(maskn (pcmpeqq select zero)))
(pandn maskn ,(%make-simd-pack-ub128 row))))
`(lambda (source low-source high-source ones zero)
(declare (ignorable low-source high-source)
(ignore source ones))
',op
,(let ((low-select (and (plusp low-mask)
(if (= low-mask (ldb (byte 64 0) -1))
'low-source
`(pand low-source ,(%make-simd-pack-ub64 low-mask
low-mask)))))
(high-select (and (plusp high-mask)
(if (= high-mask (ldb (byte 64 0) -1))
'high-source
`(pand high-source ,(%make-simd-pack-ub64 high-mask
high-mask))))))
`(let* ((select ,(cond ((and low-select high-select)
`(por ,low-select
,high-select))
(low-select)
(high-select)
(t (error "No source?"))))
(maskn (pcmpeqq select zero)))
(pandn maskn ,(%make-simd-pack-ub128 row))))))))
(defun retire-ops (ready)
(let ((shifts (find-shifts ready))
(rows (find-rows ready))
(chosen '())
(instructions '()))
(loop for i below *bundle-size*
while (or shifts rows)
do (multiple-value-bind (choice instruction)
and either uses exactly one memory op
(if rows
(let ((row (pop rows)))
(values row (generate row)))
(let ((shift (pop shifts)))
(values (cdr shift)
(generate shift))))
(if (listp choice)
(setf chosen (append choice chosen))
(push choice chosen))
(push instruction instructions)))
(values chosen (nreverse instructions))))
(defun schedule-ops (ops)
(let ((schedule (map-into (make-array +state-size+)
(lambda ()
(cons 0 nil)))))
(map nil (lambda (op)
(let ((src (op-src op)))
(setf (cdr (aref schedule src)) op)
(map nil (lambda (anti-dep)
(incf (car (aref schedule anti-dep))))
(op-anti-deps op))))
ops)
(let ((ready '())
(retired '()))
(labels ((find-ready ()
(loop for cons across schedule
for (countdown . op) = cons
when (and op (zerop countdown)
(typecase (op-src op)
(index t)
(cons
(every (lambda (src)
(zerop (car (aref schedule src))))
(op-src op)))))
do (push op ready)
(setf (cdr cons) nil)))
(maybe-exit ()
(when (null ready)
(assert (every (lambda (x)
(null (cdr x)))
schedule))
(return-from schedule-ops (nreverse retired)))))
(loop
(find-ready)
(maybe-exit)
(multiple-value-bind (done instruction)
(retire-ops ready)
(mapc (lambda (done)
(map nil (lambda (anti-dep)
(decf (car (aref schedule anti-dep))))
(op-anti-deps done)))
done)
(setf ready (set-difference ready done))
(push instruction retired)))))))
(defun emit-instructions-1 (scheduled-instructions input)
(let ((source (gensym "SOURCE"))
(low (gensym "LOW"))
(high (gensym "HIGH"))
(ones (gensym "ONES"))
(zero (gensym "ZERO")))
(labels ((emit-por-tree (temps)
(assert temps)
(if (null (cdr temps))
(car temps)
(let* ((half (ceiling (length temps) 2)))
`(por ,(emit-por-tree (subseq temps 0 half))
,(emit-por-tree (subseq temps half))))))
(emit-one-step (step)
(let (temps)
`(let* ((,low (punpcklqdq ,source ,source))
(,high (punpckhqdq ,source ,source))
,@(loop for op in step
for temp = (gensym "ROW")
do (push temp temps)
collect `(,temp (,op ,source ,low ,high ,ones ,zero))))
,(emit-por-tree (cons source (nreverse temps)))))))
(if scheduled-instructions
(values `(let ((,source ,input))
(declare (type (simd-pack integer) ,source))
(let* ,(loop for bundle in scheduled-instructions
collect `(,source ,(emit-one-step bundle)))
,source))
`(let ((,ones (to-simd-pack-integer
(%make-simd-pack-ub64 1 1)))
(,zero (to-simd-pack-integer
(%make-simd-pack-ub64 0 0))))
(declare (type (simd-pack integer) ,ones ,zero))))
(values `(the (simd-pack integer) ,input) nil)))))
(defun emit-instructions (scheduled-instructions input)
(multiple-value-bind (body around)
(emit-instructions-1 scheduled-instructions input)
(if around
(append around (list body))
body)))
(defun compile-adjacency (adjacency input &key raw)
(let* ((rows (make-rows adjacency))
(order (order-rows rows))
(ops (find-ops order rows))
(schedule (schedule-ops ops)))
(funcall (if raw #'emit-instructions-1 #'emit-instructions)
schedule input)))
(defun transitive-closure (arcs)
(declare (optimize debug))
(let ((transpose (map 'simple-vector
(lambda (dst)
(let ((hash (make-hash-table)))
(map nil (lambda (dst)
(setf (gethash dst hash) t))
dst)
hash))
(transpose arcs)))
delta)
(loop
(setf delta nil)
(dotimes (i 128)
(let ((acc (aref transpose i)))
(flet ((try (dst)
(unless (gethash dst acc)
(setf delta t)
(setf (gethash dst acc) t))))
(try i)
(maphash (lambda (j _) _
(maphash (lambda (k v) v
(try k))
(aref transpose j)))
acc))))
(unless delta
(return)))
(loop for i upfrom 0
for spec across transpose
do (remhash i spec)
append (map 'list (lambda (j)
(cons i j))
(sort (alexandria:hash-table-keys spec) #'<)))))
(defvar *max* 128)
(defun random-transitions (n &aux (max *max*))
(transitive-closure
(let ((keys (make-hash-table :test 'equal)))
(loop repeat (* n n)
while (< (hash-table-count keys) n)
do (setf (gethash (cons (random max) (random max)) keys) t))
(alexandria:hash-table-keys keys))))
(defun transpose (transitions)
(let ((destinations (make-array 128 :initial-element '())))
(loop for (src . dst) in transitions
do (pushnew dst (aref destinations src))
finally (return destinations))))
(defun test (transitions)
(declare (optimize debug))
(let* ((code (compile nil `(lambda (x)
(declare (type (simd-pack integer) x))
,(compile-adjacency transitions 'x))))
(spec (transpose transitions)))
(dotimes (i 128)
(let ((result (%simd-pack-ub128
(funcall code (%make-simd-pack-ub128 (ash 1 i)))))
(expected (adjoin i (aref spec i))))
(assert (= (logcount result) (length expected)))
(map nil (lambda (j)
(assert (logbitp j result)))
expected)))))
(defvar *state* (sb-ext:seed-random-state 1234578))
(defun n-tests (min max repetitions)
(declare (optimize debug))
(loop for count from min upto max do
(format t "count: ~A -" count)
(finish-output)
(let ((*random-state* (make-random-state *state*)))
(loop repeat repetitions
for random = (random-transitions count)
do (format t " ~A" (length random))
(finish-output)
(test random)))
(format t "~%")
(finish-output)))
|
65de439cb1853453b60d3eea386c71ccca082dfd8616ef7676742926d4c19402 | rescript-lang/rescript-compiler | ext_position.ml | Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P.
*
* 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 .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a 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 .
*
* 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.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a 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. *)
type t = Lexing.position = {
pos_fname : string;
pos_lnum : int;
pos_bol : int;
pos_cnum : int;
}
let offset (x : t) (y : t) =
{
x with
pos_lnum = x.pos_lnum + y.pos_lnum - 1;
pos_cnum = x.pos_cnum + y.pos_cnum;
pos_bol = (if y.pos_lnum = 1 then x.pos_bol else x.pos_cnum + y.pos_bol);
}
let print fmt (pos : t) =
Format.fprintf fmt "(line %d, column %d)" pos.pos_lnum
(pos.pos_cnum - pos.pos_bol)
let lexbuf_from_channel_with_fname ic fname =
let x = Lexing.from_function (fun buf n -> input ic buf 0 n) in
let pos : t =
{
pos_fname = fname;
pos_lnum = 1;
pos_bol = 0;
copied from zero_pos
}
in
x.lex_start_p <- pos;
x.lex_curr_p <- pos;
x
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/e60482c6f6a69994907b9bd56e58ce87052e3659/jscomp/ext/ext_position.ml | ocaml | Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P.
*
* 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 .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a 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 .
*
* 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.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a 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. *)
type t = Lexing.position = {
pos_fname : string;
pos_lnum : int;
pos_bol : int;
pos_cnum : int;
}
let offset (x : t) (y : t) =
{
x with
pos_lnum = x.pos_lnum + y.pos_lnum - 1;
pos_cnum = x.pos_cnum + y.pos_cnum;
pos_bol = (if y.pos_lnum = 1 then x.pos_bol else x.pos_cnum + y.pos_bol);
}
let print fmt (pos : t) =
Format.fprintf fmt "(line %d, column %d)" pos.pos_lnum
(pos.pos_cnum - pos.pos_bol)
let lexbuf_from_channel_with_fname ic fname =
let x = Lexing.from_function (fun buf n -> input ic buf 0 n) in
let pos : t =
{
pos_fname = fname;
pos_lnum = 1;
pos_bol = 0;
copied from zero_pos
}
in
x.lex_start_p <- pos;
x.lex_curr_p <- pos;
x
| |
8b6e4da8569bfda550395320287d5b7b3071c13f5792a193a1fe18cd4aa0a5ec | flipstone/haskell-for-beginners | 5_type_synonyms.hs | -- Implement your complex number solution yet again, but
-- this time use a type synonym and represent complex
-- numbers using a tuple.
--
-- Create a Result type based on Either that assumes the
-- left side is a String containing an error message. If you're
-- cool, partially apply the type constructor to get new
-- type.
--
-- Define a version of Data.List.find that returns a Result.
-- It should return an error if the list is no matching element
-- is found, with appropriate messages in each case.
| null | https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/problems/chapter_08/5_type_synonyms.hs | haskell | Implement your complex number solution yet again, but
this time use a type synonym and represent complex
numbers using a tuple.
Create a Result type based on Either that assumes the
left side is a String containing an error message. If you're
cool, partially apply the type constructor to get new
type.
Define a version of Data.List.find that returns a Result.
It should return an error if the list is no matching element
is found, with appropriate messages in each case. | |
29a1905cff8d23b0799e2024fb429372a9c64c1de3a19a57f5d00427eee9591d | DavidAlphaFox/RabbitMQ | rabbit_binary_generator.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
%%
-module(rabbit_binary_generator).
-include("rabbit_framing.hrl").
-include("rabbit.hrl").
-export([build_simple_method_frame/3,
build_simple_content_frames/4,
build_heartbeat_frame/0]).
-export([generate_table/1]).
-export([check_empty_frame_size/0]).
-export([ensure_content_encoded/2, clear_encoded_content/1]).
-export([map_exception/3]).
%%----------------------------------------------------------------------------
-ifdef(use_specs).
-type(frame() :: [binary()]).
-spec(build_simple_method_frame/3 ::
(rabbit_channel:channel_number(), rabbit_framing:amqp_method_record(),
rabbit_types:protocol())
-> frame()).
-spec(build_simple_content_frames/4 ::
(rabbit_channel:channel_number(), rabbit_types:content(),
non_neg_integer(), rabbit_types:protocol())
-> [frame()]).
-spec(build_heartbeat_frame/0 :: () -> frame()).
-spec(generate_table/1 :: (rabbit_framing:amqp_table()) -> binary()).
-spec(check_empty_frame_size/0 :: () -> 'ok').
-spec(ensure_content_encoded/2 ::
(rabbit_types:content(), rabbit_types:protocol()) ->
rabbit_types:encoded_content()).
-spec(clear_encoded_content/1 ::
(rabbit_types:content()) -> rabbit_types:unencoded_content()).
-spec(map_exception/3 :: (rabbit_channel:channel_number(),
rabbit_types:amqp_error() | any(),
rabbit_types:protocol()) ->
{rabbit_channel:channel_number(),
rabbit_framing:amqp_method_record()}).
-endif.
%%----------------------------------------------------------------------------
%% 构建简单操作结果的frame
%%
build_simple_method_frame(ChannelInt, MethodRecord, Protocol) ->
%% 使用特定版本构建操作方法的记录
MethodFields = Protocol:encode_method_fields(MethodRecord),
%% 得到操作方法的名字
MethodName = rabbit_misc:method_record_type(MethodRecord),
得到操作方法的ID
{ClassId, MethodId} = Protocol:method_id(MethodName),
%% 创建frame
create_frame(1, ChannelInt, [<<ClassId:16, MethodId:16>>, MethodFields]).
build_simple_content_frames(ChannelInt, Content, FrameMax, Protocol) ->
#content{class_id = ClassId,
properties_bin = ContentPropertiesBin,
payload_fragments_rev = PayloadFragmentsRev} =
ensure_content_encoded(Content, Protocol),
{BodySize, ContentFrames} =
build_content_frames(PayloadFragmentsRev, FrameMax, ChannelInt),
HeaderFrame = create_frame(2, ChannelInt,
[<<ClassId:16, 0:16, BodySize:64>>,
ContentPropertiesBin]),
[HeaderFrame | ContentFrames].
build_content_frames(FragsRev, FrameMax, ChannelInt) ->
BodyPayloadMax = if FrameMax == 0 -> iolist_size(FragsRev);
true -> FrameMax - ?EMPTY_FRAME_SIZE
end,
build_content_frames(0, [], BodyPayloadMax, [],
lists:reverse(FragsRev), BodyPayloadMax, ChannelInt).
build_content_frames(SizeAcc, FramesAcc, _FragSizeRem, [],
[], _BodyPayloadMax, _ChannelInt) ->
{SizeAcc, lists:reverse(FramesAcc)};
build_content_frames(SizeAcc, FramesAcc, FragSizeRem, FragAcc,
Frags, BodyPayloadMax, ChannelInt)
when FragSizeRem == 0 orelse Frags == [] ->
Frame = create_frame(3, ChannelInt, lists:reverse(FragAcc)),
FrameSize = BodyPayloadMax - FragSizeRem,
build_content_frames(SizeAcc + FrameSize, [Frame | FramesAcc],
BodyPayloadMax, [], Frags, BodyPayloadMax, ChannelInt);
build_content_frames(SizeAcc, FramesAcc, FragSizeRem, FragAcc,
[Frag | Frags], BodyPayloadMax, ChannelInt) ->
Size = size(Frag),
{NewFragSizeRem, NewFragAcc, NewFrags} =
if Size == 0 -> {FragSizeRem, FragAcc, Frags};
Size =< FragSizeRem -> {FragSizeRem - Size, [Frag | FragAcc], Frags};
true -> <<Head:FragSizeRem/binary, Tail/binary>> =
Frag,
{0, [Head | FragAcc], [Tail | Frags]}
end,
build_content_frames(SizeAcc, FramesAcc, NewFragSizeRem, NewFragAcc,
NewFrags, BodyPayloadMax, ChannelInt).
build_heartbeat_frame() ->
create_frame(?FRAME_HEARTBEAT, 0, <<>>).
%% Frame类型,Channle号和数据负载
create_frame(TypeInt, ChannelInt, Payload) ->
%% 类型,channel号
%% 内容长度,内容,frame的结尾
[<<TypeInt:8, ChannelInt:16, (iolist_size(Payload)):32>>, Payload,
?FRAME_END].
table_field_to_binary supports the 0 - 8/0 - 9 standard types , S ,
I , D , T and F , as well as the QPid extensions b , d , f , l , s , t , x ,
%% and V.
table_field_to_binary({FName, T, V}) ->
[short_string_to_binary(FName) | field_value_to_binary(T, V)].
field_value_to_binary(longstr, V) -> [$S | long_string_to_binary(V)];
field_value_to_binary(signedint, V) -> [$I, <<V:32/signed>>];
field_value_to_binary(decimal, V) -> {Before, After} = V,
[$D, Before, <<After:32>>];
field_value_to_binary(timestamp, V) -> [$T, <<V:64>>];
field_value_to_binary(table, V) -> [$F | table_to_binary(V)];
field_value_to_binary(array, V) -> [$A | array_to_binary(V)];
field_value_to_binary(byte, V) -> [$b, <<V:8/signed>>];
field_value_to_binary(double, V) -> [$d, <<V:64/float>>];
field_value_to_binary(float, V) -> [$f, <<V:32/float>>];
field_value_to_binary(long, V) -> [$l, <<V:64/signed>>];
field_value_to_binary(short, V) -> [$s, <<V:16/signed>>];
field_value_to_binary(bool, V) -> [$t, if V -> 1; true -> 0 end];
field_value_to_binary(binary, V) -> [$x | long_string_to_binary(V)];
field_value_to_binary(void, _V) -> [$V].
table_to_binary(Table) when is_list(Table) ->
BinTable = generate_table_iolist(Table),
[<<(iolist_size(BinTable)):32>> | BinTable].
array_to_binary(Array) when is_list(Array) ->
BinArray = generate_array_iolist(Array),
[<<(iolist_size(BinArray)):32>> | BinArray].
generate_table(Table) when is_list(Table) ->
list_to_binary(generate_table_iolist(Table)).
generate_table_iolist(Table) ->
lists:map(fun table_field_to_binary/1, Table).
generate_array_iolist(Array) ->
lists:map(fun ({T, V}) -> field_value_to_binary(T, V) end, Array).
short_string_to_binary(String) ->
Len = string_length(String),
if Len < 256 -> [<<Len:8>>, String];
true -> exit(content_properties_shortstr_overflow)
end.
long_string_to_binary(String) ->
Len = string_length(String),
[<<Len:32>>, String].
string_length(String) when is_binary(String) -> size(String);
string_length(String) -> length(String).
check_empty_frame_size() ->
%% Intended to ensure that EMPTY_FRAME_SIZE is defined correctly.
%% 用来检查iolist_size是否是兼容的
%% 如果不兼容,那么直接就可以终止启动了
case iolist_size(create_frame(?FRAME_BODY, 0, <<>>)) of
?EMPTY_FRAME_SIZE -> ok;
ComputedSize -> exit({incorrect_empty_frame_size,
ComputedSize, ?EMPTY_FRAME_SIZE})
end.
ensure_content_encoded(Content = #content{properties_bin = PropBin,
protocol = Protocol}, Protocol)
when PropBin =/= none ->
Content;
ensure_content_encoded(Content = #content{properties = none,
properties_bin = PropBin,
protocol = Protocol}, Protocol1)
when PropBin =/= none ->
Props = Protocol:decode_properties(Content#content.class_id, PropBin),
Content#content{properties = Props,
properties_bin = Protocol1:encode_properties(Props),
protocol = Protocol1};
ensure_content_encoded(Content = #content{properties = Props}, Protocol)
when Props =/= none ->
Content#content{properties_bin = Protocol:encode_properties(Props),
protocol = Protocol}.
clear_encoded_content(Content = #content{properties_bin = none,
protocol = none}) ->
Content;
clear_encoded_content(Content = #content{properties = none}) ->
%% Only clear when we can rebuild the properties_bin later in
%% accordance to the content record definition comment - maximum
one of properties and properties_bin can be ' none '
Content;
clear_encoded_content(Content = #content{}) ->
Content#content{properties_bin = none, protocol = none}.
NB : this function is also used by the Erlang client
map_exception(Channel, Reason, Protocol) ->
{SuggestedClose, ReplyCode, ReplyText, FailedMethod} =
lookup_amqp_exception(Reason, Protocol),
{ClassId, MethodId} = case FailedMethod of
{_, _} -> FailedMethod;
none -> {0, 0};
_ -> Protocol:method_id(FailedMethod)
end,
case SuggestedClose orelse (Channel == 0) of
true -> {0, #'connection.close'{reply_code = ReplyCode,
reply_text = ReplyText,
class_id = ClassId,
method_id = MethodId}};
false -> {Channel, #'channel.close'{reply_code = ReplyCode,
reply_text = ReplyText,
class_id = ClassId,
method_id = MethodId}}
end.
lookup_amqp_exception(#amqp_error{name = Name,
explanation = Expl,
method = Method},
Protocol) ->
{ShouldClose, Code, Text} = Protocol:lookup_amqp_exception(Name),
ExplBin = amqp_exception_explanation(Text, Expl),
{ShouldClose, Code, ExplBin, Method};
lookup_amqp_exception(Other, Protocol) ->
rabbit_log:warning("Non-AMQP exit reason '~p'~n", [Other]),
{ShouldClose, Code, Text} = Protocol:lookup_amqp_exception(internal_error),
{ShouldClose, Code, Text, none}.
amqp_exception_explanation(Text, Expl) ->
ExplBin = list_to_binary(Expl),
CompleteTextBin = <<Text/binary, " - ", ExplBin/binary>>,
if size(CompleteTextBin) > 255 -> <<CompleteTextBin:252/binary, "...">>;
true -> CompleteTextBin
end.
| null | https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/src/rabbit_binary_generator.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
构建简单操作结果的frame
使用特定版本构建操作方法的记录
得到操作方法的名字
创建frame
Frame类型,Channle号和数据负载
类型,channel号
内容长度,内容,frame的结尾
and V.
Intended to ensure that EMPTY_FRAME_SIZE is defined correctly.
用来检查iolist_size是否是兼容的
如果不兼容,那么直接就可以终止启动了
Only clear when we can rebuild the properties_bin later in
accordance to the content record definition comment - maximum | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
-module(rabbit_binary_generator).
-include("rabbit_framing.hrl").
-include("rabbit.hrl").
-export([build_simple_method_frame/3,
build_simple_content_frames/4,
build_heartbeat_frame/0]).
-export([generate_table/1]).
-export([check_empty_frame_size/0]).
-export([ensure_content_encoded/2, clear_encoded_content/1]).
-export([map_exception/3]).
-ifdef(use_specs).
-type(frame() :: [binary()]).
-spec(build_simple_method_frame/3 ::
(rabbit_channel:channel_number(), rabbit_framing:amqp_method_record(),
rabbit_types:protocol())
-> frame()).
-spec(build_simple_content_frames/4 ::
(rabbit_channel:channel_number(), rabbit_types:content(),
non_neg_integer(), rabbit_types:protocol())
-> [frame()]).
-spec(build_heartbeat_frame/0 :: () -> frame()).
-spec(generate_table/1 :: (rabbit_framing:amqp_table()) -> binary()).
-spec(check_empty_frame_size/0 :: () -> 'ok').
-spec(ensure_content_encoded/2 ::
(rabbit_types:content(), rabbit_types:protocol()) ->
rabbit_types:encoded_content()).
-spec(clear_encoded_content/1 ::
(rabbit_types:content()) -> rabbit_types:unencoded_content()).
-spec(map_exception/3 :: (rabbit_channel:channel_number(),
rabbit_types:amqp_error() | any(),
rabbit_types:protocol()) ->
{rabbit_channel:channel_number(),
rabbit_framing:amqp_method_record()}).
-endif.
build_simple_method_frame(ChannelInt, MethodRecord, Protocol) ->
MethodFields = Protocol:encode_method_fields(MethodRecord),
MethodName = rabbit_misc:method_record_type(MethodRecord),
得到操作方法的ID
{ClassId, MethodId} = Protocol:method_id(MethodName),
create_frame(1, ChannelInt, [<<ClassId:16, MethodId:16>>, MethodFields]).
build_simple_content_frames(ChannelInt, Content, FrameMax, Protocol) ->
#content{class_id = ClassId,
properties_bin = ContentPropertiesBin,
payload_fragments_rev = PayloadFragmentsRev} =
ensure_content_encoded(Content, Protocol),
{BodySize, ContentFrames} =
build_content_frames(PayloadFragmentsRev, FrameMax, ChannelInt),
HeaderFrame = create_frame(2, ChannelInt,
[<<ClassId:16, 0:16, BodySize:64>>,
ContentPropertiesBin]),
[HeaderFrame | ContentFrames].
build_content_frames(FragsRev, FrameMax, ChannelInt) ->
BodyPayloadMax = if FrameMax == 0 -> iolist_size(FragsRev);
true -> FrameMax - ?EMPTY_FRAME_SIZE
end,
build_content_frames(0, [], BodyPayloadMax, [],
lists:reverse(FragsRev), BodyPayloadMax, ChannelInt).
build_content_frames(SizeAcc, FramesAcc, _FragSizeRem, [],
[], _BodyPayloadMax, _ChannelInt) ->
{SizeAcc, lists:reverse(FramesAcc)};
build_content_frames(SizeAcc, FramesAcc, FragSizeRem, FragAcc,
Frags, BodyPayloadMax, ChannelInt)
when FragSizeRem == 0 orelse Frags == [] ->
Frame = create_frame(3, ChannelInt, lists:reverse(FragAcc)),
FrameSize = BodyPayloadMax - FragSizeRem,
build_content_frames(SizeAcc + FrameSize, [Frame | FramesAcc],
BodyPayloadMax, [], Frags, BodyPayloadMax, ChannelInt);
build_content_frames(SizeAcc, FramesAcc, FragSizeRem, FragAcc,
[Frag | Frags], BodyPayloadMax, ChannelInt) ->
Size = size(Frag),
{NewFragSizeRem, NewFragAcc, NewFrags} =
if Size == 0 -> {FragSizeRem, FragAcc, Frags};
Size =< FragSizeRem -> {FragSizeRem - Size, [Frag | FragAcc], Frags};
true -> <<Head:FragSizeRem/binary, Tail/binary>> =
Frag,
{0, [Head | FragAcc], [Tail | Frags]}
end,
build_content_frames(SizeAcc, FramesAcc, NewFragSizeRem, NewFragAcc,
NewFrags, BodyPayloadMax, ChannelInt).
build_heartbeat_frame() ->
create_frame(?FRAME_HEARTBEAT, 0, <<>>).
create_frame(TypeInt, ChannelInt, Payload) ->
[<<TypeInt:8, ChannelInt:16, (iolist_size(Payload)):32>>, Payload,
?FRAME_END].
table_field_to_binary supports the 0 - 8/0 - 9 standard types , S ,
I , D , T and F , as well as the QPid extensions b , d , f , l , s , t , x ,
table_field_to_binary({FName, T, V}) ->
[short_string_to_binary(FName) | field_value_to_binary(T, V)].
field_value_to_binary(longstr, V) -> [$S | long_string_to_binary(V)];
field_value_to_binary(signedint, V) -> [$I, <<V:32/signed>>];
field_value_to_binary(decimal, V) -> {Before, After} = V,
[$D, Before, <<After:32>>];
field_value_to_binary(timestamp, V) -> [$T, <<V:64>>];
field_value_to_binary(table, V) -> [$F | table_to_binary(V)];
field_value_to_binary(array, V) -> [$A | array_to_binary(V)];
field_value_to_binary(byte, V) -> [$b, <<V:8/signed>>];
field_value_to_binary(double, V) -> [$d, <<V:64/float>>];
field_value_to_binary(float, V) -> [$f, <<V:32/float>>];
field_value_to_binary(long, V) -> [$l, <<V:64/signed>>];
field_value_to_binary(short, V) -> [$s, <<V:16/signed>>];
field_value_to_binary(bool, V) -> [$t, if V -> 1; true -> 0 end];
field_value_to_binary(binary, V) -> [$x | long_string_to_binary(V)];
field_value_to_binary(void, _V) -> [$V].
table_to_binary(Table) when is_list(Table) ->
BinTable = generate_table_iolist(Table),
[<<(iolist_size(BinTable)):32>> | BinTable].
array_to_binary(Array) when is_list(Array) ->
BinArray = generate_array_iolist(Array),
[<<(iolist_size(BinArray)):32>> | BinArray].
generate_table(Table) when is_list(Table) ->
list_to_binary(generate_table_iolist(Table)).
generate_table_iolist(Table) ->
lists:map(fun table_field_to_binary/1, Table).
generate_array_iolist(Array) ->
lists:map(fun ({T, V}) -> field_value_to_binary(T, V) end, Array).
short_string_to_binary(String) ->
Len = string_length(String),
if Len < 256 -> [<<Len:8>>, String];
true -> exit(content_properties_shortstr_overflow)
end.
long_string_to_binary(String) ->
Len = string_length(String),
[<<Len:32>>, String].
string_length(String) when is_binary(String) -> size(String);
string_length(String) -> length(String).
check_empty_frame_size() ->
case iolist_size(create_frame(?FRAME_BODY, 0, <<>>)) of
?EMPTY_FRAME_SIZE -> ok;
ComputedSize -> exit({incorrect_empty_frame_size,
ComputedSize, ?EMPTY_FRAME_SIZE})
end.
ensure_content_encoded(Content = #content{properties_bin = PropBin,
protocol = Protocol}, Protocol)
when PropBin =/= none ->
Content;
ensure_content_encoded(Content = #content{properties = none,
properties_bin = PropBin,
protocol = Protocol}, Protocol1)
when PropBin =/= none ->
Props = Protocol:decode_properties(Content#content.class_id, PropBin),
Content#content{properties = Props,
properties_bin = Protocol1:encode_properties(Props),
protocol = Protocol1};
ensure_content_encoded(Content = #content{properties = Props}, Protocol)
when Props =/= none ->
Content#content{properties_bin = Protocol:encode_properties(Props),
protocol = Protocol}.
clear_encoded_content(Content = #content{properties_bin = none,
protocol = none}) ->
Content;
clear_encoded_content(Content = #content{properties = none}) ->
one of properties and properties_bin can be ' none '
Content;
clear_encoded_content(Content = #content{}) ->
Content#content{properties_bin = none, protocol = none}.
NB : this function is also used by the Erlang client
map_exception(Channel, Reason, Protocol) ->
{SuggestedClose, ReplyCode, ReplyText, FailedMethod} =
lookup_amqp_exception(Reason, Protocol),
{ClassId, MethodId} = case FailedMethod of
{_, _} -> FailedMethod;
none -> {0, 0};
_ -> Protocol:method_id(FailedMethod)
end,
case SuggestedClose orelse (Channel == 0) of
true -> {0, #'connection.close'{reply_code = ReplyCode,
reply_text = ReplyText,
class_id = ClassId,
method_id = MethodId}};
false -> {Channel, #'channel.close'{reply_code = ReplyCode,
reply_text = ReplyText,
class_id = ClassId,
method_id = MethodId}}
end.
lookup_amqp_exception(#amqp_error{name = Name,
explanation = Expl,
method = Method},
Protocol) ->
{ShouldClose, Code, Text} = Protocol:lookup_amqp_exception(Name),
ExplBin = amqp_exception_explanation(Text, Expl),
{ShouldClose, Code, ExplBin, Method};
lookup_amqp_exception(Other, Protocol) ->
rabbit_log:warning("Non-AMQP exit reason '~p'~n", [Other]),
{ShouldClose, Code, Text} = Protocol:lookup_amqp_exception(internal_error),
{ShouldClose, Code, Text, none}.
amqp_exception_explanation(Text, Expl) ->
ExplBin = list_to_binary(Expl),
CompleteTextBin = <<Text/binary, " - ", ExplBin/binary>>,
if size(CompleteTextBin) > 255 -> <<CompleteTextBin:252/binary, "...">>;
true -> CompleteTextBin
end.
|
f8251507e768fb7abaf5bf7b3a968a2ee824fae93b7a93fc582da0b7916dcafe | clj-kondo/clj-kondo | try_plus.clj | (ns macroexpand.try-plus
(:require [clj-kondo.hooks-api :as api]))
(defn expand-catch [catch-node]
(let [[catch catchee & exprs] (:children catch-node)
catchee-sexpr (api/sexpr catchee)]
(cond (vector? catchee-sexpr)
(let [[selector & exprs] exprs]
(api/list-node
[catch (api/token-node 'Exception) (api/token-node '_e#)
(api/list-node
(list* (api/token-node 'let)
(api/vector-node [selector (api/token-node nil)])
exprs))]))
:else catch-node)))
(defn try+ [{:keys [node]}]
(let [children (rest (:children node))
[body catches]
(loop [body children
body-exprs []
catches []]
(if (seq body)
(let [f (first body)
f-sexpr (api/sexpr f)]
(if (and (seq? f-sexpr) (= 'catch (first f-sexpr)))
(recur (rest body)
body-exprs
(conj catches (expand-catch f)))
(recur (rest body)
(conj body-exprs f)
catches)))
[body-exprs catches]))
new-node (api/list-node
[(api/token-node 'let)
(api/vector-node
[(api/token-node '&throw-context) (api/token-node nil)])
(api/token-node '&throw-context) ;; use throw-context to avoid warning
(with-meta (api/list-node (list* (api/token-node 'try)
(concat body catches)))
(meta node))])]
;; (prn (api/sexpr new-node))
{:node new-node}))
| null | https://raw.githubusercontent.com/clj-kondo/clj-kondo/626978461cbf113c376634cdf034d7262deb429f/corpus/.clj-kondo/macroexpand/try_plus.clj | clojure | use throw-context to avoid warning
(prn (api/sexpr new-node)) | (ns macroexpand.try-plus
(:require [clj-kondo.hooks-api :as api]))
(defn expand-catch [catch-node]
(let [[catch catchee & exprs] (:children catch-node)
catchee-sexpr (api/sexpr catchee)]
(cond (vector? catchee-sexpr)
(let [[selector & exprs] exprs]
(api/list-node
[catch (api/token-node 'Exception) (api/token-node '_e#)
(api/list-node
(list* (api/token-node 'let)
(api/vector-node [selector (api/token-node nil)])
exprs))]))
:else catch-node)))
(defn try+ [{:keys [node]}]
(let [children (rest (:children node))
[body catches]
(loop [body children
body-exprs []
catches []]
(if (seq body)
(let [f (first body)
f-sexpr (api/sexpr f)]
(if (and (seq? f-sexpr) (= 'catch (first f-sexpr)))
(recur (rest body)
body-exprs
(conj catches (expand-catch f)))
(recur (rest body)
(conj body-exprs f)
catches)))
[body-exprs catches]))
new-node (api/list-node
[(api/token-node 'let)
(api/vector-node
[(api/token-node '&throw-context) (api/token-node nil)])
(with-meta (api/list-node (list* (api/token-node 'try)
(concat body catches)))
(meta node))])]
{:node new-node}))
|
08d0a140a58a8a8de720ca2f13a2d6c4fa3c7a19793f76495ea012102686d3ed | ghc/nofib | Interval.hs |
- ( The Solid Modeller , written in Haskell )
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use , copy , modify , and distribute this software for any
- purpose and without fee is hereby granted , provided that the above
- copyright notice and this permission notice appear in all copies , and
- that my name not be used in advertising or publicity pertaining to this
- software without specific , written prior permission . I makes no
- representations about the suitability of this software for any purpose .
- It is provided ` ` as is '' without express or implied warranty .
-
- Duncan Sinclair 1993 .
-
- Interval arithmetic package .
-
- Fulsom (The Solid Modeller, written in Haskell)
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use, copy, modify, and distribute this software for any
- purpose and without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies, and
- that my name not be used in advertising or publicity pertaining to this
- software without specific, written prior permission. I makes no
- representations about the suitability of this software for any purpose.
- It is provided ``as is'' without express or implied warranty.
-
- Duncan Sinclair 1993.
-
- Interval arithmetic package.
-
-}
module Interval(Interval, (#), pt, sqr,
tophalf, bothalf, topbit,
lo, hi, mid1, mid2,
up,down,unpt)
where
infix 4 #,:#:
data Interval a = Pt a | a :#: a deriving (Show{-was:Text-})
pt a = Pt a
a # b = a :#: b
instance (Ord a, Eq a) => Eq (Interval a) where
a == b = a >= b && a <= b -- Not correct - but it will do.
a /= b = a > b || a < b
instance (Ord a) => Ord (Interval a) where
(<) = ivLess
(<=) = ivLeEq
(>) = ivGreat
(>=) = ivGrEq
min = ivMin
max = ivMax
instance (Num a, Ord a, Eq a, Show a) => Num (Interval a) where
(+) = ivPlus
(*) = ivMult
negate = ivNegate
abs = ivAbs
signum = ivSignum
fromInteger = ivFromInteger
instance (Show a, Num a, Ord a, Fractional a) => Fractional (Interval a) where
(/) = ivDiv
fromRational = ivFromRational
instance (Show a, RealFloat a) => Floating (Interval a) where
pi = Pt pi
exp = ivExp
log = ivLog
sqrt = ivSqrt
(**) = ivPower
sin = ivSin
cos = ivCos
tan = ivTan
asin = ivAsin
acos = ivAcos
atan = ivAtan
sinh = ivSinh
cosh = ivCosh
tanh = ivTanh
asinh = ivAsinh
acosh = ivAcosh
atanh = ivAtanh
-- Error functions - un-used.
error0 = error "Not implemented."
error1 a = error "Not implemented."
error2 a b = error "Not implemented."
error3 a b c = error "Not implemented."
error4 a b c d = error "Not implemented."
Eq class functions
-- Ord class functions
ivLess (Pt b) (Pt c) = b < c
ivLess (a :#: b) (c :#: d) = b < c
ivLess (Pt b) (c :#: d) = b < c
ivLess (a :#: b) (Pt c) = b < c
ivLeEq (Pt b) (Pt d) = b <= d
ivLeEq (a :#: b) (c :#: d) = b <= d
ivLeEq (Pt b) (c :#: d) = b <= d
ivLeEq (a :#: b) (Pt d) = b <= d
ivGreat (Pt a) (Pt d) = a > d
ivGreat (a :#: b) (c :#: d) = a > d
ivGreat (Pt a) (c :#: d) = a > d
ivGreat (a :#: b) (Pt d) = a > d
ivGrEq (Pt a) (Pt c) = a >= c
ivGrEq (a :#: b) (c :#: d) = a >= c
ivGrEq (Pt a) (c :#: d) = a >= c
ivGrEq (a :#: b) (Pt c) = a >= c
ivMin (Pt a) (Pt c) = Pt (min a c)
ivMin (a :#: b) (c :#: d) = (min a c) :#: (min b d)
ivMin (Pt a) (c :#: d) | a < c = Pt a
| otherwise = c :#: min a d
ivMin (a :#: b) (Pt c) | c < a = Pt c
| otherwise = a :#: min c b
ivMax (Pt a) (Pt c) = Pt (max a c)
ivMax (a :#: b) (c :#: d) = (max a c) :#: (max b d)
ivMax (Pt a) (c :#: d) | a > d = Pt a
| otherwise = max a c :#: d
ivMax (a :#: b) (Pt c) | c > b = Pt c
| otherwise = max c a :#: b
-- Num class functions
ivPlus (Pt a) (Pt c) = Pt (a+c)
ivPlus (a :#: b) (c :#: d) = a+c :#: b+d
ivPlus (Pt a) (c :#: d) = a+c :#: a+d
ivPlus (a :#: b) (Pt c) = a+c :#: b+c
ivNegate (Pt a) = Pt (negate a)
ivNegate (a :#: b) = negate b :#: negate a
ivMult (Pt a) (Pt c) = Pt (a*c)
ivMult (a :#: b) (c :#: d) | (min a c) > 0 = a*c :#: b*d
| (max b d) < 0 = b*d :#: a*c
| otherwise = minmax [e,f,g,h]
where
e = b * c
f = a * d
g = a * c
h = b * d
ivMult (Pt a) (c :#: d) | a > 0 = a*c :#: a*d
| a < 0 = a*d :#: a*c
| otherwise = (Pt 0)
ivMult (c :#: d) (Pt a) | a > 0 = a*c :#: a*d
| a < 0 = a*d :#: a*c
| otherwise = (Pt 0)
finds the lowest , and highest in a list - used for mult .
-- Should use foldl rather than foldr
minmax [a] = a :#: a
minmax (a:as) = case True of
True | (a > s) -> f :#: a
True | (a < f) -> a :#: s
otherwise -> f :#: s
where
(f :#: s) = minmax as
ivAbs (Pt a) = Pt (abs a)
ivAbs (a :#: b) | a<=0 && 0<=b = 0 :#: (max (abs a) (abs b))
| a<=b && b<0 = b :#: a
| 0<a && a<=b = a :#: b
| otherwise = error "abs doesny work!"
ivSignum (Pt a) = Pt (signum a)
ivSignum (a :#: b) = (signum a) :#: (signum b)
ivFromInteger a = Pt (fromInteger a)
-- Fractional class functions
ivDiv a (Pt c) = ivMult a (Pt (1/c))
ivDiv a (c :#: d) = ivMult a (1/c :#: 1/d)
ivFromRational a = Pt (fromRational a)
-- Floating class functions
-- ivPi () = fromRational pi
ivExp (Pt a) = Pt (exp a)
ivExp (a :#: b) = (exp a) :#: (exp b)
ivLog (Pt a) = Pt (log a)
ivLog (a :#: b) = (log a) :#: (log b)
ivSqrt (Pt a) = Pt (sqrt a)
ivSqrt (a :#: b) = (sqrt a) :#: (sqrt b)
Optimise for x * * 2
ivSin :: (Floating a) => (Interval a) -> (Interval a)
ivSin a = error "Floating op not defined."
ivCos :: (Floating a) => (Interval a) -> (Interval a)
ivCos a = error "Floating op not defined."
ivTan :: (Floating a) => (Interval a) -> (Interval a)
ivTan a = error "Floating op not defined."
ivAsin :: (Floating a) => (Interval a) -> (Interval a)
ivAsin a = error "Floating op not defined."
ivAcos :: (Floating a) => (Interval a) -> (Interval a)
ivAcos a = error "Floating op not defined."
ivAtan :: (Floating a) => (Interval a) -> (Interval a)
ivAtan a = error "Floating op not defined."
ivSinh :: (Floating a) => (Interval a) -> (Interval a)
ivSinh a = error "Floating op not defined."
ivCosh :: (Floating a) => (Interval a) -> (Interval a)
ivCosh a = error "Floating op not defined."
ivTanh :: (Floating a) => (Interval a) -> (Interval a)
ivTanh a = error "Floating op not defined."
ivAsinh :: (Floating a) => (Interval a) -> (Interval a)
ivAsinh a = error "Floating op not defined."
ivAcosh :: (Floating a) => (Interval a) -> (Interval a)
ivAcosh a = error "Floating op not defined."
ivAtanh :: (Floating a) => (Interval a) -> (Interval a)
ivAtanh a = error "Floating op not defined."
-- Extra math functions not part of classes
sqr (Pt a) = Pt (a*a)
sqr (a :#: b) | a > 0 = a*a :#: b*b
| b < 0 = b*b :#: a*a
| otherwise = 0 :#: (max e f)
where
e = a * a
f = b * b
-- Other Functions specific to interval type
tophalf (a :#: b) = (a+b)/2 :#: b
bothalf (a :#: b) = a :#: (a+b)/2
topbit (a :#: b) = (a+b)/2-0.001 :#: b
lo (a :#: b) = a
hi (a :#: b) = b
down (a :#: b) = Pt a
up (a :#: b) = Pt b
unpt (Pt a) = a
mid1 (a :#: b) = Pt (a + (b-a)/3)
mid2 (a :#: b) = Pt (b - (b-a)/3)
| null | https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/real/fulsom/Interval.hs | haskell | was:Text
Not correct - but it will do.
Error functions - un-used.
Ord class functions
Num class functions
Should use foldl rather than foldr
Fractional class functions
Floating class functions
ivPi () = fromRational pi
Extra math functions not part of classes
Other Functions specific to interval type |
- ( The Solid Modeller , written in Haskell )
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use , copy , modify , and distribute this software for any
- purpose and without fee is hereby granted , provided that the above
- copyright notice and this permission notice appear in all copies , and
- that my name not be used in advertising or publicity pertaining to this
- software without specific , written prior permission . I makes no
- representations about the suitability of this software for any purpose .
- It is provided ` ` as is '' without express or implied warranty .
-
- Duncan Sinclair 1993 .
-
- Interval arithmetic package .
-
- Fulsom (The Solid Modeller, written in Haskell)
-
- Copyright 1990,1991,1992,1993 Duncan Sinclair
-
- Permissiom to use, copy, modify, and distribute this software for any
- purpose and without fee is hereby granted, provided that the above
- copyright notice and this permission notice appear in all copies, and
- that my name not be used in advertising or publicity pertaining to this
- software without specific, written prior permission. I makes no
- representations about the suitability of this software for any purpose.
- It is provided ``as is'' without express or implied warranty.
-
- Duncan Sinclair 1993.
-
- Interval arithmetic package.
-
-}
module Interval(Interval, (#), pt, sqr,
tophalf, bothalf, topbit,
lo, hi, mid1, mid2,
up,down,unpt)
where
infix 4 #,:#:
pt a = Pt a
a # b = a :#: b
instance (Ord a, Eq a) => Eq (Interval a) where
a /= b = a > b || a < b
instance (Ord a) => Ord (Interval a) where
(<) = ivLess
(<=) = ivLeEq
(>) = ivGreat
(>=) = ivGrEq
min = ivMin
max = ivMax
instance (Num a, Ord a, Eq a, Show a) => Num (Interval a) where
(+) = ivPlus
(*) = ivMult
negate = ivNegate
abs = ivAbs
signum = ivSignum
fromInteger = ivFromInteger
instance (Show a, Num a, Ord a, Fractional a) => Fractional (Interval a) where
(/) = ivDiv
fromRational = ivFromRational
instance (Show a, RealFloat a) => Floating (Interval a) where
pi = Pt pi
exp = ivExp
log = ivLog
sqrt = ivSqrt
(**) = ivPower
sin = ivSin
cos = ivCos
tan = ivTan
asin = ivAsin
acos = ivAcos
atan = ivAtan
sinh = ivSinh
cosh = ivCosh
tanh = ivTanh
asinh = ivAsinh
acosh = ivAcosh
atanh = ivAtanh
error0 = error "Not implemented."
error1 a = error "Not implemented."
error2 a b = error "Not implemented."
error3 a b c = error "Not implemented."
error4 a b c d = error "Not implemented."
Eq class functions
ivLess (Pt b) (Pt c) = b < c
ivLess (a :#: b) (c :#: d) = b < c
ivLess (Pt b) (c :#: d) = b < c
ivLess (a :#: b) (Pt c) = b < c
ivLeEq (Pt b) (Pt d) = b <= d
ivLeEq (a :#: b) (c :#: d) = b <= d
ivLeEq (Pt b) (c :#: d) = b <= d
ivLeEq (a :#: b) (Pt d) = b <= d
ivGreat (Pt a) (Pt d) = a > d
ivGreat (a :#: b) (c :#: d) = a > d
ivGreat (Pt a) (c :#: d) = a > d
ivGreat (a :#: b) (Pt d) = a > d
ivGrEq (Pt a) (Pt c) = a >= c
ivGrEq (a :#: b) (c :#: d) = a >= c
ivGrEq (Pt a) (c :#: d) = a >= c
ivGrEq (a :#: b) (Pt c) = a >= c
ivMin (Pt a) (Pt c) = Pt (min a c)
ivMin (a :#: b) (c :#: d) = (min a c) :#: (min b d)
ivMin (Pt a) (c :#: d) | a < c = Pt a
| otherwise = c :#: min a d
ivMin (a :#: b) (Pt c) | c < a = Pt c
| otherwise = a :#: min c b
ivMax (Pt a) (Pt c) = Pt (max a c)
ivMax (a :#: b) (c :#: d) = (max a c) :#: (max b d)
ivMax (Pt a) (c :#: d) | a > d = Pt a
| otherwise = max a c :#: d
ivMax (a :#: b) (Pt c) | c > b = Pt c
| otherwise = max c a :#: b
ivPlus (Pt a) (Pt c) = Pt (a+c)
ivPlus (a :#: b) (c :#: d) = a+c :#: b+d
ivPlus (Pt a) (c :#: d) = a+c :#: a+d
ivPlus (a :#: b) (Pt c) = a+c :#: b+c
ivNegate (Pt a) = Pt (negate a)
ivNegate (a :#: b) = negate b :#: negate a
ivMult (Pt a) (Pt c) = Pt (a*c)
ivMult (a :#: b) (c :#: d) | (min a c) > 0 = a*c :#: b*d
| (max b d) < 0 = b*d :#: a*c
| otherwise = minmax [e,f,g,h]
where
e = b * c
f = a * d
g = a * c
h = b * d
ivMult (Pt a) (c :#: d) | a > 0 = a*c :#: a*d
| a < 0 = a*d :#: a*c
| otherwise = (Pt 0)
ivMult (c :#: d) (Pt a) | a > 0 = a*c :#: a*d
| a < 0 = a*d :#: a*c
| otherwise = (Pt 0)
finds the lowest , and highest in a list - used for mult .
minmax [a] = a :#: a
minmax (a:as) = case True of
True | (a > s) -> f :#: a
True | (a < f) -> a :#: s
otherwise -> f :#: s
where
(f :#: s) = minmax as
ivAbs (Pt a) = Pt (abs a)
ivAbs (a :#: b) | a<=0 && 0<=b = 0 :#: (max (abs a) (abs b))
| a<=b && b<0 = b :#: a
| 0<a && a<=b = a :#: b
| otherwise = error "abs doesny work!"
ivSignum (Pt a) = Pt (signum a)
ivSignum (a :#: b) = (signum a) :#: (signum b)
ivFromInteger a = Pt (fromInteger a)
ivDiv a (Pt c) = ivMult a (Pt (1/c))
ivDiv a (c :#: d) = ivMult a (1/c :#: 1/d)
ivFromRational a = Pt (fromRational a)
ivExp (Pt a) = Pt (exp a)
ivExp (a :#: b) = (exp a) :#: (exp b)
ivLog (Pt a) = Pt (log a)
ivLog (a :#: b) = (log a) :#: (log b)
ivSqrt (Pt a) = Pt (sqrt a)
ivSqrt (a :#: b) = (sqrt a) :#: (sqrt b)
Optimise for x * * 2
ivSin :: (Floating a) => (Interval a) -> (Interval a)
ivSin a = error "Floating op not defined."
ivCos :: (Floating a) => (Interval a) -> (Interval a)
ivCos a = error "Floating op not defined."
ivTan :: (Floating a) => (Interval a) -> (Interval a)
ivTan a = error "Floating op not defined."
ivAsin :: (Floating a) => (Interval a) -> (Interval a)
ivAsin a = error "Floating op not defined."
ivAcos :: (Floating a) => (Interval a) -> (Interval a)
ivAcos a = error "Floating op not defined."
ivAtan :: (Floating a) => (Interval a) -> (Interval a)
ivAtan a = error "Floating op not defined."
ivSinh :: (Floating a) => (Interval a) -> (Interval a)
ivSinh a = error "Floating op not defined."
ivCosh :: (Floating a) => (Interval a) -> (Interval a)
ivCosh a = error "Floating op not defined."
ivTanh :: (Floating a) => (Interval a) -> (Interval a)
ivTanh a = error "Floating op not defined."
ivAsinh :: (Floating a) => (Interval a) -> (Interval a)
ivAsinh a = error "Floating op not defined."
ivAcosh :: (Floating a) => (Interval a) -> (Interval a)
ivAcosh a = error "Floating op not defined."
ivAtanh :: (Floating a) => (Interval a) -> (Interval a)
ivAtanh a = error "Floating op not defined."
sqr (Pt a) = Pt (a*a)
sqr (a :#: b) | a > 0 = a*a :#: b*b
| b < 0 = b*b :#: a*a
| otherwise = 0 :#: (max e f)
where
e = a * a
f = b * b
tophalf (a :#: b) = (a+b)/2 :#: b
bothalf (a :#: b) = a :#: (a+b)/2
topbit (a :#: b) = (a+b)/2-0.001 :#: b
lo (a :#: b) = a
hi (a :#: b) = b
down (a :#: b) = Pt a
up (a :#: b) = Pt b
unpt (Pt a) = a
mid1 (a :#: b) = Pt (a + (b-a)/3)
mid2 (a :#: b) = Pt (b - (b-a)/3)
|
77e386d7cda530a490f3e82f7678a997d71c65d82e5b68eecca38697d3386a7b | AmpersandTarski/Ampersand | MetaModels.hs | # LANGUAGE ScopedTypeVariables #
module Ampersand.FSpec.MetaModels
( MetaModel (..),
pCtx2Fspec,
)
where
import Ampersand.ADL1
import Ampersand.ADL1.P2A_Converters
import Ampersand.Basics
import Ampersand.FSpec.FSpec
import Ampersand.FSpec.ShowMeatGrinder
import Ampersand.FSpec.ToFSpec.ADL2FSpec
import Ampersand.Input
import Ampersand.Misc.HasClasses
import qualified RIO.NonEmpty as NE
pCtx2Fspec :: (HasFSpecGenOpts env) => env -> P_Context -> Guarded FSpec
pCtx2Fspec env c = do
fSpec <- makeFSpec env <$> pCtx2aCtx env c
checkInvariants fSpec
where
checkInvariants :: FSpec -> Guarded FSpec
checkInvariants fSpec =
if view allowInvariantViolationsL env
then pure fSpec
else case violationsOfInvariants fSpec of
[] -> pure fSpec
h : tl -> Errors (fmap (mkInvariantViolationsError (applyViolText fSpec)) (h NE.:| tl))
| null | https://raw.githubusercontent.com/AmpersandTarski/Ampersand/cb2306a09ce79d5609ccf8d3e28c0a1eb45feafe/src/Ampersand/FSpec/MetaModels.hs | haskell | # LANGUAGE ScopedTypeVariables #
module Ampersand.FSpec.MetaModels
( MetaModel (..),
pCtx2Fspec,
)
where
import Ampersand.ADL1
import Ampersand.ADL1.P2A_Converters
import Ampersand.Basics
import Ampersand.FSpec.FSpec
import Ampersand.FSpec.ShowMeatGrinder
import Ampersand.FSpec.ToFSpec.ADL2FSpec
import Ampersand.Input
import Ampersand.Misc.HasClasses
import qualified RIO.NonEmpty as NE
pCtx2Fspec :: (HasFSpecGenOpts env) => env -> P_Context -> Guarded FSpec
pCtx2Fspec env c = do
fSpec <- makeFSpec env <$> pCtx2aCtx env c
checkInvariants fSpec
where
checkInvariants :: FSpec -> Guarded FSpec
checkInvariants fSpec =
if view allowInvariantViolationsL env
then pure fSpec
else case violationsOfInvariants fSpec of
[] -> pure fSpec
h : tl -> Errors (fmap (mkInvariantViolationsError (applyViolText fSpec)) (h NE.:| tl))
| |
c835f4d0a20e1823213d82e46303d0503075f0a26e307268a1a5b38f7f2f0e2b | parsonsmatt/ghc-cache-buster | Explicit.hs | # LANGUAGE QuasiQuotes , TemplateHaskell #
module GCB.Explicit where
import GCB.Types.Foo (mkFoo)
import GCB.Types.FooExplicit (mkFooExplicit)
import GCB.Types.Quuz (compileQuuz, blargh)
app :: IO ()
app = do
putStrLn "Hello, World!"
let x = [compileQuuz|asdf|]
let foo = mkFoo "asdf"
putStrLn "Goodbye, World!"
blargh
| null | https://raw.githubusercontent.com/parsonsmatt/ghc-cache-buster/c58976e937d42b68b3592bf4b8e4e194601dda00/src/GCB/Explicit.hs | haskell | # LANGUAGE QuasiQuotes , TemplateHaskell #
module GCB.Explicit where
import GCB.Types.Foo (mkFoo)
import GCB.Types.FooExplicit (mkFooExplicit)
import GCB.Types.Quuz (compileQuuz, blargh)
app :: IO ()
app = do
putStrLn "Hello, World!"
let x = [compileQuuz|asdf|]
let foo = mkFoo "asdf"
putStrLn "Goodbye, World!"
blargh
| |
8133903851ea5360a2bfd6fe27af8307856399a89157c06e139b89c2befb254c | lucasvreis/org-mode-hs | Syntect.hs | # LANGUAGE ForeignFunctionInterface #
module Org.Exporters.Highlighting.Syntect where
import Data.Text qualified as T
import Foreign.C.String
import Ondim.HTML
import Text.XmlHtml (docContent, parseHTML)
import Text.XmlHtml qualified as X
import Control.Exception (bracket)
import Org.Parser.Definitions (Affiliated)
foreign import ccall unsafe "render_lines" renderLines :: CString -> CString -> IO CString
foreign import ccall unsafe "free_lines" freeLines :: CString -> IO ()
synctectSrcLinesHtml :: MonadIO m => Affiliated -> Text -> Text -> m (Maybe [[HtmlNode]])
synctectSrcLinesHtml _ (toString -> lang) (toString -> code) = do
let lang' = case lang of
"emacs-lisp" -> "lisp"
_ -> lang
out :: String <-
liftIO $
withCString lang' \lPtr ->
withCString code \cPtr ->
bracket (renderLines lPtr cPtr) freeLines peekCString
pure do
nodes <- fmap docContent $ rightToMaybe $ parseHTML "" (encodeUtf8 out)
pure $ fromNodeList <$> breakLines nodes
where
breakLines :: [X.Node] -> [[X.Node]]
breakLines = go
where
go [] = [[]]
go (X.TextNode t : xs) =
let ts = map X.TextNode (T.split (== '\n') t)
in append ts (go xs)
go (X.Element x y c : ns) =
let els = map (X.Element x y) (go c)
in append els (go ns)
go (n : ns) = insert n (go ns)
insert x (y : ys) = ((x : y) : ys)
insert x [] = [[x]]
append [] ys = ys
append [x] (y : ys) = ((x : y) : ys)
append (x : xs) ys = [x] : append xs ys
| null | https://raw.githubusercontent.com/lucasvreis/org-mode-hs/ad25bebd5de3671dc8363ce83de419a788a6b1a9/org-exporters/src/Org/Exporters/Highlighting/Syntect.hs | haskell | # LANGUAGE ForeignFunctionInterface #
module Org.Exporters.Highlighting.Syntect where
import Data.Text qualified as T
import Foreign.C.String
import Ondim.HTML
import Text.XmlHtml (docContent, parseHTML)
import Text.XmlHtml qualified as X
import Control.Exception (bracket)
import Org.Parser.Definitions (Affiliated)
foreign import ccall unsafe "render_lines" renderLines :: CString -> CString -> IO CString
foreign import ccall unsafe "free_lines" freeLines :: CString -> IO ()
synctectSrcLinesHtml :: MonadIO m => Affiliated -> Text -> Text -> m (Maybe [[HtmlNode]])
synctectSrcLinesHtml _ (toString -> lang) (toString -> code) = do
let lang' = case lang of
"emacs-lisp" -> "lisp"
_ -> lang
out :: String <-
liftIO $
withCString lang' \lPtr ->
withCString code \cPtr ->
bracket (renderLines lPtr cPtr) freeLines peekCString
pure do
nodes <- fmap docContent $ rightToMaybe $ parseHTML "" (encodeUtf8 out)
pure $ fromNodeList <$> breakLines nodes
where
breakLines :: [X.Node] -> [[X.Node]]
breakLines = go
where
go [] = [[]]
go (X.TextNode t : xs) =
let ts = map X.TextNode (T.split (== '\n') t)
in append ts (go xs)
go (X.Element x y c : ns) =
let els = map (X.Element x y) (go c)
in append els (go ns)
go (n : ns) = insert n (go ns)
insert x (y : ys) = ((x : y) : ys)
insert x [] = [[x]]
append [] ys = ys
append [x] (y : ys) = ((x : y) : ys)
append (x : xs) ys = [x] : append xs ys
| |
1eadcfb2414939659b3d67e5896d5e14300f11f272cc321391fc37777f122c33 | ledger/cl-ledger | types.lisp | ;; types.lisp
(declaim (optimize (safety 3) (debug 3) (speed 1) (space 0)))
(in-package :ledger)
(defstruct (item-position)
begin-line
end-line
source)
(deftype item-status ()
'(member :uncleared :pending :cleared))
(defstruct (transaction
(:conc-name get-xact-)
(:print-function print-transaction))
entry
(actual-date nil :type (or fixed-time null))
(effective-date nil :type (or fixed-time null))
(status :uncleared :type item-status)
account
(amount nil :type (or value value-expr null))
(cost nil :type (or value value-expr null))
;;(basis-cost nil :type (or value value-expr null))
(note nil :type (or string null))
(virtualp nil :type boolean)
(generatedp nil :type boolean)
(calculatedp nil :type boolean)
(must-balance-p t :type boolean)
position
data)
(defstruct (value-expr)
(string nil :type string)
(function nil :type function))
(defclass entry ()
((journal :accessor entry-journal :initarg :journal)
(actual-date :accessor entry-actual-date :initarg :actual-date
:initform nil :type (or fixed-time null))
(effective-date :accessor entry-effective-date :initarg :effective-date
:initform nil :type (or fixed-time null))
(status :accessor entry-status :initarg :status
:initform :uncleared :type item-status)
(code :accessor entry-code :initarg :code
:initform nil :type (or string null))
(payee :accessor entry-payee :initarg :payee
:initform nil :type (or string null))
(note :accessor entry-note :initarg :note
:initform nil :type (or string null))
(transactions :accessor entry-transactions :initarg :transactions
:initform nil)
(position :accessor entry-position :initarg :position
:initform nil)
(normalizedp :accessor entry-normalizedp :initarg :normalizedp
:initform nil)
(data :accessor entry-data :initarg :data
:initform nil)))
(defclass account ()
((parent :accessor account-parent :initarg :parent
:initform nil)
(children :accessor account-children :initarg :children
:initform nil :type (or hash-table null))
(name :accessor account-name :initarg :name
:type string)
(fullname :accessor account-fullname :initarg :fullname
:type string)
(data :accessor account-data :initarg :data
:initform nil)))
(defclass journal ()
((binder :accessor journal-binder :initarg :binder)
(contents :accessor journal-contents :initform nil)
(last-content-cell :accessor journal-last-content-cell :initform nil)
(date-format :accessor journal-date-format :initform nil
:type (or string null))
(default-year :accessor journal-default-year :initform nil
:type (or integer null))
(default-account :accessor journal-default-account :initform nil
:type (or account null))
(source :accessor journal-source :initarg :source-path
:initform nil :type (or pathname null))
(read-date :accessor journal-read-date :initarg :read-date
:initform nil :type (or integer null))
(data :accessor journal-data :initarg :data
:initform nil)))
(defclass binder ()
((commodity-pool :accessor binder-commodity-pool :initarg :commodity-pool
:type commodity-pool)
(root-account :accessor binder-root-account :initarg :root-account
:initform (make-instance 'account :name "") :type account)
(journals :accessor binder-journals :initarg :journals
:initform nil)
(data :accessor binder-data :initarg :data
:initform nil)))
(declaim (inline binderp))
(defun binderp (binder)
(typep binder 'binder))
(defgeneric add-transaction (item transaction))
(defgeneric add-journal (binder journal))
(defgeneric find-account (item account-path &key create-if-not-exists-p))
(defgeneric entries-iterator (object))
(defgeneric transactions-iterator (object &optional entry-transform))
(provide 'types)
;; types.lisp ends here
| null | https://raw.githubusercontent.com/ledger/cl-ledger/e25d5f9f721bcf3b30d6569363e723f22d19a3a0/core/types.lisp | lisp | types.lisp
(basis-cost nil :type (or value value-expr null))
types.lisp ends here |
(declaim (optimize (safety 3) (debug 3) (speed 1) (space 0)))
(in-package :ledger)
(defstruct (item-position)
begin-line
end-line
source)
(deftype item-status ()
'(member :uncleared :pending :cleared))
(defstruct (transaction
(:conc-name get-xact-)
(:print-function print-transaction))
entry
(actual-date nil :type (or fixed-time null))
(effective-date nil :type (or fixed-time null))
(status :uncleared :type item-status)
account
(amount nil :type (or value value-expr null))
(cost nil :type (or value value-expr null))
(note nil :type (or string null))
(virtualp nil :type boolean)
(generatedp nil :type boolean)
(calculatedp nil :type boolean)
(must-balance-p t :type boolean)
position
data)
(defstruct (value-expr)
(string nil :type string)
(function nil :type function))
(defclass entry ()
((journal :accessor entry-journal :initarg :journal)
(actual-date :accessor entry-actual-date :initarg :actual-date
:initform nil :type (or fixed-time null))
(effective-date :accessor entry-effective-date :initarg :effective-date
:initform nil :type (or fixed-time null))
(status :accessor entry-status :initarg :status
:initform :uncleared :type item-status)
(code :accessor entry-code :initarg :code
:initform nil :type (or string null))
(payee :accessor entry-payee :initarg :payee
:initform nil :type (or string null))
(note :accessor entry-note :initarg :note
:initform nil :type (or string null))
(transactions :accessor entry-transactions :initarg :transactions
:initform nil)
(position :accessor entry-position :initarg :position
:initform nil)
(normalizedp :accessor entry-normalizedp :initarg :normalizedp
:initform nil)
(data :accessor entry-data :initarg :data
:initform nil)))
(defclass account ()
((parent :accessor account-parent :initarg :parent
:initform nil)
(children :accessor account-children :initarg :children
:initform nil :type (or hash-table null))
(name :accessor account-name :initarg :name
:type string)
(fullname :accessor account-fullname :initarg :fullname
:type string)
(data :accessor account-data :initarg :data
:initform nil)))
(defclass journal ()
((binder :accessor journal-binder :initarg :binder)
(contents :accessor journal-contents :initform nil)
(last-content-cell :accessor journal-last-content-cell :initform nil)
(date-format :accessor journal-date-format :initform nil
:type (or string null))
(default-year :accessor journal-default-year :initform nil
:type (or integer null))
(default-account :accessor journal-default-account :initform nil
:type (or account null))
(source :accessor journal-source :initarg :source-path
:initform nil :type (or pathname null))
(read-date :accessor journal-read-date :initarg :read-date
:initform nil :type (or integer null))
(data :accessor journal-data :initarg :data
:initform nil)))
(defclass binder ()
((commodity-pool :accessor binder-commodity-pool :initarg :commodity-pool
:type commodity-pool)
(root-account :accessor binder-root-account :initarg :root-account
:initform (make-instance 'account :name "") :type account)
(journals :accessor binder-journals :initarg :journals
:initform nil)
(data :accessor binder-data :initarg :data
:initform nil)))
(declaim (inline binderp))
(defun binderp (binder)
(typep binder 'binder))
(defgeneric add-transaction (item transaction))
(defgeneric add-journal (binder journal))
(defgeneric find-account (item account-path &key create-if-not-exists-p))
(defgeneric entries-iterator (object))
(defgeneric transactions-iterator (object &optional entry-transform))
(provide 'types)
|
16657a9e7bafee9760e449c9cd88b460163d16aad24667fae8dc6605db2a7c45 | shayan-najd/NativeMetaprogramming | tcfail201.hs | {-# LANGUAGE RankNTypes #-}
-- Claus reported by email that
GHCi , version 6.9.20080217 loops on this program
-- -ghc/2008-June/043173.html
-- So I'm adding it to the test suite so that we'll see it if it happens again
module Foo where
data HsDoc id
= DocEmpty
| DocParagraph (HsDoc id)
gfoldl' :: (forall a b . c (a -> b) -> a -> c b) -> (forall g . g -> c g) -> a -> c a
gfoldl' k z hsDoc = case hsDoc of
DocEmpty -> z DocEmpty
( DocParagraph hsDoc ) - > z DocParagraph ` k ` hsDoc
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_fail/tcfail201.hs | haskell | # LANGUAGE RankNTypes #
Claus reported by email that
-ghc/2008-June/043173.html
So I'm adding it to the test suite so that we'll see it if it happens again |
GHCi , version 6.9.20080217 loops on this program
module Foo where
data HsDoc id
= DocEmpty
| DocParagraph (HsDoc id)
gfoldl' :: (forall a b . c (a -> b) -> a -> c b) -> (forall g . g -> c g) -> a -> c a
gfoldl' k z hsDoc = case hsDoc of
DocEmpty -> z DocEmpty
( DocParagraph hsDoc ) - > z DocParagraph ` k ` hsDoc
|
3a76d7c89fba6a9bbbb64a375fd63c29721a9f7324f7b4eb1266227a8a1f7f49 | zkat/chanl | conditions.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*-
;;;;
Copyright © 2009 ,
;;;;
;;;; Condition handling through channels
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :chanl.examples)
(export '(with-condition-dumper))
(defun ensure-list (x) (if (listp x) x (list x))) ; Common util
(defstruct (wrapped-condition
(:conc-name wrapped-)
(:type vector)
(:constructor wrap-condition
(condition &aux (restarts (compute-restarts condition)))))
(thread (current-thread) :read-only t)
(condition nil :type condition :read-only t)
(reply-channel (make-instance 'channel) :read-only t)
(restarts nil :read-only t))
(defmacro with-condition-dumper (channel &body body)
`(handler-bind ((condition (lambda (c)
(let ((wrapped (wrap-condition c)))
(send ,channel wrapped)
(let ((restart (recv (wrapped-reply-channel wrapped))))
(cond ((typep restart 'restart)
(invoke-restart restart))
((typep (car restart) 'restart)
(apply 'invoke-restart restart))
(t (error "Invalid restart designator"))))))))
,@body))
;; Some sample code using the above:
;; CHANL> (defvar *chan* (make-channel))
;; *CHAN*
;; CHANL> (defvar a (make-channel))
;; A
;; CHANL> (pexec ()
;; (chanl.examples::with-condition-dumper *chan*
;; (loop (with-simple-restart (continue "Continue the loop")
;; (send a (funcall (recv a)))))))
;; T
;; CHANL> (send a (lambda () (signal (make-condition 'simple-error :format-control "A test"))))
;; #<CHANNEL [unbuffered] @ #xBABEBABEBABE>
;; CHANL> (let ((x (recv *chan*))
( some - restart ( car ( chanl.examples::wrapped - restarts x ) ) ) )
;; (send (chanl.examples::wrapped-reply-channel x) some-restart)
;; some-restart)
;; #<BOGUS object @ #x7FBDBD67C89D>
| null | https://raw.githubusercontent.com/zkat/chanl/3a0ad5b9ae31b3874ac91c541fd997123c2e03db/examples/conditions.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*-
Condition handling through channels
Common util
Some sample code using the above:
CHANL> (defvar *chan* (make-channel))
*CHAN*
CHANL> (defvar a (make-channel))
A
CHANL> (pexec ()
(chanl.examples::with-condition-dumper *chan*
(loop (with-simple-restart (continue "Continue the loop")
(send a (funcall (recv a)))))))
T
CHANL> (send a (lambda () (signal (make-condition 'simple-error :format-control "A test"))))
#<CHANNEL [unbuffered] @ #xBABEBABEBABE>
CHANL> (let ((x (recv *chan*))
(send (chanl.examples::wrapped-reply-channel x) some-restart)
some-restart)
#<BOGUS object @ #x7FBDBD67C89D> | Copyright © 2009 ,
(in-package :chanl.examples)
(export '(with-condition-dumper))
(defstruct (wrapped-condition
(:conc-name wrapped-)
(:type vector)
(:constructor wrap-condition
(condition &aux (restarts (compute-restarts condition)))))
(thread (current-thread) :read-only t)
(condition nil :type condition :read-only t)
(reply-channel (make-instance 'channel) :read-only t)
(restarts nil :read-only t))
(defmacro with-condition-dumper (channel &body body)
`(handler-bind ((condition (lambda (c)
(let ((wrapped (wrap-condition c)))
(send ,channel wrapped)
(let ((restart (recv (wrapped-reply-channel wrapped))))
(cond ((typep restart 'restart)
(invoke-restart restart))
((typep (car restart) 'restart)
(apply 'invoke-restart restart))
(t (error "Invalid restart designator"))))))))
,@body))
( some - restart ( car ( chanl.examples::wrapped - restarts x ) ) ) )
|
3910fc12cebd38d5b1bcef8c0f3188348c7eb284f75a44cefb7ba3be08c3c7fd | keithfancher/kept | Args.hs | module Args
( CLIOpts (..),
cliOptParser,
)
where
import Kept (KeptOptions (..))
import Markdown (MarkdownOpts (..))
import Options.Applicative
import Path (PathOptions (..))
data CLIOpts = CLIOpts
{ keptOptions :: KeptOptions,
inFiles :: [FilePath]
}
cliOptParser :: ParserInfo CLIOpts
cliOptParser =
info
(optWrapperParser <**> helper)
( fullDesc
<> header "kept: Extract your data from Google Keep."
<> progDesc "Pass in one or more of your exported Google Keep JSON files and get some nice markdown in return. Export your Keep JSON data via takeout.google.com."
)
optWrapperParser :: Parser CLIOpts
optWrapperParser =
CLIOpts
<$> keptOptionParser
<*> filePathsParser
keptOptionParser :: Parser KeptOptions
keptOptionParser =
KeptOptions
<$> stdOutFlagParser
<*> tagPathFlagParser
<*> markdownOptionsParser
stdOutFlagParser :: Parser Bool
stdOutFlagParser =
switch
( long "stdout"
<> short 's'
<> help "Print output to screen rather than writing files"
)
tagPathFlagParser :: Parser PathOptions
tagPathFlagParser =
toPathOpt
<$> switch
( long "no-tag-subdirs"
<> short 'n'
<> help "Do not sort notes into tag-based subdirectories"
)
where
-- This is a bit confusing because of the negation. These `switch` options
-- are False by default, so that needs to map to our default desired behavior:
toPathOpt False = TagSubDirs
toPathOpt True = NoTagSubDirs
markdownOptionsParser :: Parser MarkdownOpts
markdownOptionsParser = markdownOptsFromFlags <$> noYamlFlagParser <*> titleFlagParser
Chews up the boolean CLI flags and spits out a proper ` MarkdownOpts ` object .
markdownOptsFromFlags :: Bool -> Bool -> MarkdownOpts
markdownOptsFromFlags noYaml titleInYaml = case (noYaml, titleInYaml) of
check this option first , it takes precedence
(False, True) -> FrontMatterWithTitle -- yes front matter, yes include title in front matter
_ -> FrontMatterDefault -- any remaining option results in default front matter
noYamlFlagParser :: Parser Bool
noYamlFlagParser =
switch
( long "no-yaml"
<> short 'y'
<> help "Do not add YAML front-matter to exported notes (takes precedence over `--title-in-yaml` option)"
)
titleFlagParser :: Parser Bool
titleFlagParser =
switch
( long "title-in-yaml"
<> short 't'
<> help "Include `title` field in YAML front-matter INSTEAD OF as a heading in the note body"
)
filePathsParser :: Parser [FilePath]
filePathsParser =
` some ` = = " one or more " ( as opposed to ` many ` , zero or more )
( argument
str
( metavar "JSON_FILE(S)"
<> help "One or more exported Google Keep JSON files"
)
)
| null | https://raw.githubusercontent.com/keithfancher/kept/21ca2b1f1ac87bb01364962f330562998ae5697a/app/Args.hs | haskell | This is a bit confusing because of the negation. These `switch` options
are False by default, so that needs to map to our default desired behavior:
yes front matter, yes include title in front matter
any remaining option results in default front matter | module Args
( CLIOpts (..),
cliOptParser,
)
where
import Kept (KeptOptions (..))
import Markdown (MarkdownOpts (..))
import Options.Applicative
import Path (PathOptions (..))
data CLIOpts = CLIOpts
{ keptOptions :: KeptOptions,
inFiles :: [FilePath]
}
cliOptParser :: ParserInfo CLIOpts
cliOptParser =
info
(optWrapperParser <**> helper)
( fullDesc
<> header "kept: Extract your data from Google Keep."
<> progDesc "Pass in one or more of your exported Google Keep JSON files and get some nice markdown in return. Export your Keep JSON data via takeout.google.com."
)
optWrapperParser :: Parser CLIOpts
optWrapperParser =
CLIOpts
<$> keptOptionParser
<*> filePathsParser
keptOptionParser :: Parser KeptOptions
keptOptionParser =
KeptOptions
<$> stdOutFlagParser
<*> tagPathFlagParser
<*> markdownOptionsParser
stdOutFlagParser :: Parser Bool
stdOutFlagParser =
switch
( long "stdout"
<> short 's'
<> help "Print output to screen rather than writing files"
)
tagPathFlagParser :: Parser PathOptions
tagPathFlagParser =
toPathOpt
<$> switch
( long "no-tag-subdirs"
<> short 'n'
<> help "Do not sort notes into tag-based subdirectories"
)
where
toPathOpt False = TagSubDirs
toPathOpt True = NoTagSubDirs
markdownOptionsParser :: Parser MarkdownOpts
markdownOptionsParser = markdownOptsFromFlags <$> noYamlFlagParser <*> titleFlagParser
Chews up the boolean CLI flags and spits out a proper ` MarkdownOpts ` object .
markdownOptsFromFlags :: Bool -> Bool -> MarkdownOpts
markdownOptsFromFlags noYaml titleInYaml = case (noYaml, titleInYaml) of
check this option first , it takes precedence
noYamlFlagParser :: Parser Bool
noYamlFlagParser =
switch
( long "no-yaml"
<> short 'y'
<> help "Do not add YAML front-matter to exported notes (takes precedence over `--title-in-yaml` option)"
)
titleFlagParser :: Parser Bool
titleFlagParser =
switch
( long "title-in-yaml"
<> short 't'
<> help "Include `title` field in YAML front-matter INSTEAD OF as a heading in the note body"
)
filePathsParser :: Parser [FilePath]
filePathsParser =
` some ` = = " one or more " ( as opposed to ` many ` , zero or more )
( argument
str
( metavar "JSON_FILE(S)"
<> help "One or more exported Google Keep JSON files"
)
)
|
8d6faaa3709d06647fd52100817efad5c71bcde6287359655bc6ce36dd17d2a0 | glebec/haskell-programming-allen-moronuki | Ex26_08.hs | module Ex26_08 where
import Control.Monad.Trans.Except
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader
-- lexically outer = semantically inner
embedded :: MaybeT -- m (Maybe a)
(ExceptT -- m
String
(ReaderT () IO))
Int -- a
embedded = pure 1
maybeUnwrap :: ExceptT -- m (Either e a)
String -- e
(ReaderT () IO) -- m
(Maybe Int) -- a
maybeUnwrap = runMaybeT embedded
eitherUnwrap :: ReaderT () IO -- r -> m a
(Either -- a
String
(Maybe Int))
eitherUnwrap = runExceptT maybeUnwrap
readerUnwrap :: () -> -- r
IO -- m
(Either -- a
String
(Maybe Int))
readerUnwrap = runReaderT eitherUnwrap
unwrappedResult :: IO (Either String (Maybe Int))
unwrappedResult = readerUnwrap () -- Right (Just 1)
unwrapped2 :: IO (Either String (Maybe Int))
unwrapped2 = (runReaderT . runExceptT . runMaybeT . pure $ 1) ()
-- Exercise: Wrap It Up
NB , the book seems to contradict itself . It says we should
-- re-wrap `readerUnwrap`, but also provides the following snippet:
` embedded = ? ? ? ( const ( Right ( Just 1 ) ) ) ` . Here are two approaches :
-- matches written problem description
embedded' :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded' = MaybeT . ExceptT . ReaderT $ readerUnwrap
-- matches provided code snippet
embedded'' :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded'' = MaybeT . ExceptT . ReaderT . fmap pure $ const (Right (Just 1))
| null | https://raw.githubusercontent.com/glebec/haskell-programming-allen-moronuki/99bd232f523e426d18a5e096f1cf771228c55f52/26-monad-transformers/Ex26_08.hs | haskell | lexically outer = semantically inner
m (Maybe a)
m
a
m (Either e a)
e
m
a
r -> m a
a
r
m
a
Right (Just 1)
Exercise: Wrap It Up
re-wrap `readerUnwrap`, but also provides the following snippet:
matches written problem description
matches provided code snippet | module Ex26_08 where
import Control.Monad.Trans.Except
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Reader
String
(ReaderT () IO))
embedded = pure 1
maybeUnwrap = runMaybeT embedded
String
(Maybe Int))
eitherUnwrap = runExceptT maybeUnwrap
String
(Maybe Int))
readerUnwrap = runReaderT eitherUnwrap
unwrappedResult :: IO (Either String (Maybe Int))
unwrapped2 :: IO (Either String (Maybe Int))
unwrapped2 = (runReaderT . runExceptT . runMaybeT . pure $ 1) ()
NB , the book seems to contradict itself . It says we should
` embedded = ? ? ? ( const ( Right ( Just 1 ) ) ) ` . Here are two approaches :
embedded' :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded' = MaybeT . ExceptT . ReaderT $ readerUnwrap
embedded'' :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded'' = MaybeT . ExceptT . ReaderT . fmap pure $ const (Right (Just 1))
|
55acd29225de52c865c790b028aa38413f1230dacd51714fe8e2e40cd5da1512 | jaspervdj/hakyll | Configuration.hs | --------------------------------------------------------------------------------
-- | Exports a datastructure for the top-level hakyll configuration
module Hakyll.Core.Configuration
( Configuration (..)
, shouldIgnoreFile
, shouldWatchIgnore
, defaultConfiguration
) where
--------------------------------------------------------------------------------
import Data.Default (Default (..))
import Data.List (isPrefixOf, isSuffixOf)
import qualified Network.Wai.Application.Static as Static
import System.Directory (canonicalizePath)
import System.Exit (ExitCode)
import System.FilePath (isAbsolute, normalise, takeFileName, makeRelative)
import System.IO.Error (catchIOError)
import System.Process (system)
--------------------------------------------------------------------------------
data Configuration = Configuration
{ -- | Directory in which the output written
destinationDirectory :: FilePath
| Directory where hakyll 's internal store is kept
storeDirectory :: FilePath
, -- | Directory in which some temporary files will be kept
tmpDirectory :: FilePath
| Directory where hakyll finds the files to compile . This is @.@ by
-- default.
providerDirectory :: FilePath
, -- | Function to determine ignored files
--
-- In 'defaultConfiguration', the following files are ignored:
--
-- * files starting with a @.@
--
-- * files starting with a @#@
--
-- * files ending with a @~@
--
* files ending with @.swp@
--
-- Note that the files in 'destinationDirectory' and 'storeDirectory' will
-- also be ignored. Note that this is the configuration parameter, if you
-- want to use the test, you should use 'shouldIgnoreFile'.
--
ignoreFile :: FilePath -> Bool
, -- | Function to determine files and directories that should not trigger
-- a rebuild when touched in watch mode.
--
-- Paths are passed in relative to the providerDirectory.
--
-- All files that are ignored by 'ignoreFile' are also always ignored by
-- 'watchIgnore'.
watchIgnore :: FilePath -> Bool
, -- | Here, you can plug in a system command to upload/deploy your site.
--
-- Example:
--
> rsync -ave ' ssh -p 2217 ' _ site : hakyll
--
-- You can execute this by using
--
-- > ./site deploy
--
deployCommand :: String
| Function to deploy the site from Haskell .
--
-- By default, this command executes the shell command stored in
-- 'deployCommand'. If you override it, 'deployCommand' will not
-- be used implicitely.
--
-- The 'Configuration' object is passed as a parameter to this
-- function.
--
deploySite :: Configuration -> IO ExitCode
, -- | Use an in-memory cache for items. This is faster but uses more
-- memory.
inMemoryCache :: Bool
| Override default host for preview server . Default is " 127.0.0.1 " ,
-- which binds only on the loopback address.
-- One can also override the host as a command line argument:
./site preview -h " 0.0.0.0 "
previewHost :: String
| Override default port for preview server . Default is 8000 .
-- One can also override the port as a command line argument:
./site preview -p 1234
previewPort :: Int
-- | Override other settings used by the preview server. Default is
' ' .
, previewSettings :: FilePath -> Static.StaticSettings
}
--------------------------------------------------------------------------------
instance Default Configuration where
def = defaultConfiguration
--------------------------------------------------------------------------------
-- | Default configuration for a hakyll application
defaultConfiguration :: Configuration
defaultConfiguration = Configuration
{ destinationDirectory = "_site"
, storeDirectory = "_cache"
, tmpDirectory = "_cache/tmp"
, providerDirectory = "."
, ignoreFile = ignoreFile'
, watchIgnore = const False
, deployCommand = "echo 'No deploy command specified' && exit 1"
, deploySite = system . deployCommand
, inMemoryCache = True
, previewHost = "127.0.0.1"
, previewPort = 8000
, previewSettings = Static.defaultFileServerSettings
}
where
ignoreFile' path
| "." `isPrefixOf` fileName = True
| "#" `isPrefixOf` fileName = True
| "~" `isSuffixOf` fileName = True
| ".swp" `isSuffixOf` fileName = True
| otherwise = False
where
fileName = takeFileName path
--------------------------------------------------------------------------------
-- | Check if a file should be ignored
shouldIgnoreFile :: Configuration -> FilePath -> IO Bool
shouldIgnoreFile conf path = orM
[ inDir (destinationDirectory conf)
, inDir (storeDirectory conf)
, inDir (tmpDirectory conf)
, return (ignoreFile conf path')
]
where
path' = normalise path
absolute = isAbsolute path
inDir dir
| absolute = do
dir' <- catchIOError (canonicalizePath dir) (const $ return dir)
return $ dir' `isPrefixOf` path'
| otherwise = return $ dir `isPrefixOf` path'
orM :: [IO Bool] -> IO Bool
orM [] = return False
orM (x : xs) = x >>= \b -> if b then return True else orM xs
-- | Returns a function to check if a file should be ignored in watch mode
shouldWatchIgnore :: Configuration -> IO (FilePath -> IO Bool)
shouldWatchIgnore conf = do
fullProviderDir <- canonicalizePath $ providerDirectory conf
return (\path ->
let path' = makeRelative fullProviderDir path
in (|| watchIgnore conf path') <$> shouldIgnoreFile conf path)
| null | https://raw.githubusercontent.com/jaspervdj/hakyll/a7e7e52302fd38130ac5ceb677d81bff82af45d6/lib/Hakyll/Core/Configuration.hs | haskell | ------------------------------------------------------------------------------
| Exports a datastructure for the top-level hakyll configuration
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Directory in which the output written
| Directory in which some temporary files will be kept
default.
| Function to determine ignored files
In 'defaultConfiguration', the following files are ignored:
* files starting with a @.@
* files starting with a @#@
* files ending with a @~@
Note that the files in 'destinationDirectory' and 'storeDirectory' will
also be ignored. Note that this is the configuration parameter, if you
want to use the test, you should use 'shouldIgnoreFile'.
| Function to determine files and directories that should not trigger
a rebuild when touched in watch mode.
Paths are passed in relative to the providerDirectory.
All files that are ignored by 'ignoreFile' are also always ignored by
'watchIgnore'.
| Here, you can plug in a system command to upload/deploy your site.
Example:
You can execute this by using
> ./site deploy
By default, this command executes the shell command stored in
'deployCommand'. If you override it, 'deployCommand' will not
be used implicitely.
The 'Configuration' object is passed as a parameter to this
function.
| Use an in-memory cache for items. This is faster but uses more
memory.
which binds only on the loopback address.
One can also override the host as a command line argument:
One can also override the port as a command line argument:
| Override other settings used by the preview server. Default is
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Default configuration for a hakyll application
------------------------------------------------------------------------------
| Check if a file should be ignored
| Returns a function to check if a file should be ignored in watch mode | module Hakyll.Core.Configuration
( Configuration (..)
, shouldIgnoreFile
, shouldWatchIgnore
, defaultConfiguration
) where
import Data.Default (Default (..))
import Data.List (isPrefixOf, isSuffixOf)
import qualified Network.Wai.Application.Static as Static
import System.Directory (canonicalizePath)
import System.Exit (ExitCode)
import System.FilePath (isAbsolute, normalise, takeFileName, makeRelative)
import System.IO.Error (catchIOError)
import System.Process (system)
data Configuration = Configuration
destinationDirectory :: FilePath
| Directory where hakyll 's internal store is kept
storeDirectory :: FilePath
tmpDirectory :: FilePath
| Directory where hakyll finds the files to compile . This is @.@ by
providerDirectory :: FilePath
* files ending with @.swp@
ignoreFile :: FilePath -> Bool
watchIgnore :: FilePath -> Bool
> rsync -ave ' ssh -p 2217 ' _ site : hakyll
deployCommand :: String
| Function to deploy the site from Haskell .
deploySite :: Configuration -> IO ExitCode
inMemoryCache :: Bool
| Override default host for preview server . Default is " 127.0.0.1 " ,
./site preview -h " 0.0.0.0 "
previewHost :: String
| Override default port for preview server . Default is 8000 .
./site preview -p 1234
previewPort :: Int
' ' .
, previewSettings :: FilePath -> Static.StaticSettings
}
instance Default Configuration where
def = defaultConfiguration
defaultConfiguration :: Configuration
defaultConfiguration = Configuration
{ destinationDirectory = "_site"
, storeDirectory = "_cache"
, tmpDirectory = "_cache/tmp"
, providerDirectory = "."
, ignoreFile = ignoreFile'
, watchIgnore = const False
, deployCommand = "echo 'No deploy command specified' && exit 1"
, deploySite = system . deployCommand
, inMemoryCache = True
, previewHost = "127.0.0.1"
, previewPort = 8000
, previewSettings = Static.defaultFileServerSettings
}
where
ignoreFile' path
| "." `isPrefixOf` fileName = True
| "#" `isPrefixOf` fileName = True
| "~" `isSuffixOf` fileName = True
| ".swp" `isSuffixOf` fileName = True
| otherwise = False
where
fileName = takeFileName path
shouldIgnoreFile :: Configuration -> FilePath -> IO Bool
shouldIgnoreFile conf path = orM
[ inDir (destinationDirectory conf)
, inDir (storeDirectory conf)
, inDir (tmpDirectory conf)
, return (ignoreFile conf path')
]
where
path' = normalise path
absolute = isAbsolute path
inDir dir
| absolute = do
dir' <- catchIOError (canonicalizePath dir) (const $ return dir)
return $ dir' `isPrefixOf` path'
| otherwise = return $ dir `isPrefixOf` path'
orM :: [IO Bool] -> IO Bool
orM [] = return False
orM (x : xs) = x >>= \b -> if b then return True else orM xs
shouldWatchIgnore :: Configuration -> IO (FilePath -> IO Bool)
shouldWatchIgnore conf = do
fullProviderDir <- canonicalizePath $ providerDirectory conf
return (\path ->
let path' = makeRelative fullProviderDir path
in (|| watchIgnore conf path') <$> shouldIgnoreFile conf path)
|
ac4d9fef854997a943a312387e175cb60fbadd763d8f8f6d2c30fc040b02fd44 | karamellpelle/grid | File.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
You should have received a copy of the GNU General Public License
-- along with grid. If not, see </>.
--
module LevelTools.File
(
wLevel,
wWorldHeader,
findSimilarFileName,
rLevelFile,
rCompatibleHeaderLevel,
) where
import MyPrelude
import Game
import Game.LevelPuzzleMode.File.Field
import qualified Game.LevelPuzzleMode.File.Version as LP
import Game.LevelPuzzleMode.File.Read
import Game.LevelPuzzleMode.File
import File.Binary
import LevelTools.EditWorld
import System.IO
import System.Directory
import System.FilePath
findSimilarFileName base ext = do
let path = base <.> ext
boolA <- doesFileExist path
boolB <- doesDirectoryExist path
if boolA || boolB then findSimilarFileName (base ++ "~") ext
else return path
version :: [Word8]
version =
[0x6c, 0x30, 0x30, 0x30]
wWorldHeader :: String -> String -> Writer
wWorldHeader creator name = do
wWord8s LP.version
-- creator
wField fieldCreator
wCStringAlign 4 $ creator
-- name
wField fieldName
wCStringAlign 4 $ name
wField fieldLevelS
wLevel :: EditWorld -> Writer
wLevel edit = do
-- header
wWord8s version
wField fieldLevel
let level = editLevel edit
-- name
wField fieldLevelName
wCStringAlign 4 $ levelName level
-- pussle tag
wField fieldLevelPuzzleTag
case levelPuzzleTag level of
False -> wUInt32 0
True -> wUInt32 1
-- segments
wField fieldLevelSegments
wUInt32 $ levelSegments level
-- [(RoomIx, Room)]
let scnt = editSemiContent edit
wField fieldLevelRoomS
forM_ (scontentRooms scnt) $ wSemiRoom
assert : align = = 4
wSemiRoom sroom = do
wField fieldLevelRoom
-- ix
wField fieldLevelRoomIx
wUInt32 $ sroomRoomIx sroom
-- walls
wField fieldLevelRoomWallS
forM_ (sroomWall sroom) wWall
-- dot plain
wField fieldLevelRoomDotPlainS
forM_ (sroomDotPlain sroom) wDotPlain
-- dot bonus
wField fieldLevelRoomDotBonusS
forM_ (sroomDotBonus sroom) wDotBonus
-- dot tele
wField fieldLevelRoomDotTeleS
forM_ (sroomDotTele sroom) wDotTele
-- dot finish
wField fieldLevelRoomDotFinishS
forM_ (sroomDotFinish sroom) wDotFinish
wWall wall = do
wField fieldLevelRoomWall
case wallIsDouble wall of
False -> wUInt32 0
True -> wUInt32 1
let Node n0 n1 n2 = wallNode wall
Node x0 x1 x2 = wallX wall
Node y0 y1 y2 = wallY wall
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wInt32 $ fI x0
wInt32 $ fI x1
wInt32 $ fI x2
wInt32 $ fI y0
wInt32 $ fI y1
wInt32 $ fI y2
wDotPlain dot = do
wField fieldLevelRoomDotPlain
let Node n0 n1 n2 = dotplainNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wUInt32 $ dotplainSize dot
wUInt32 $ dotplainRoom dot
wDotBonus dot = do
wField fieldLevelRoomDotBonus
let Node n0 n1 n2 = dotbonusNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wUInt32 $ dotbonusSize dot
wUInt32 $ dotbonusAdd dot
wDotTele dot = do
wField fieldLevelRoomDotTele
let Node n0 n1 n2 = dotteleNode dot
Node n0' n1' n2' = dotteleNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wUInt32 $ dotteleSize dot
wInt32 $ fI n0'
wInt32 $ fI n1'
wInt32 $ fI n2'
wDotFinish dot = do
wField fieldLevelRoomDotFinish
let Node n0 n1 n2 = dotfinishNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wField :: Field -> Writer
wField field = do
case word32AsWord8s field of
(w0, w1, w2, w3) -> wWord8s [w0, w1, w2, w3]
--------------------------------------------------------------------------------
-- Reader
rCompatibleHeaderLevel :: Reader ()
rCompatibleHeaderLevel = do
ws <- replicateM 4 rAnyWord8
unless (ws == version) $ fail $ "can not read .ldef file with header " ++ show ws
-- | assuming Level
rLevelFile :: Reader (Level, [SemiRoom])
rLevelFile = do
rCompatibleHeaderLevel
-- Level --
rThisField fieldLevel
rThisField fieldLevelName
name <- rCString
rAlign 4
rThisField fieldLevelPuzzleTag
puzzletag <- (/= 0) `fmap` rUInt32
rThisField fieldLevelSegments
segs <- rUInt32
let level = makeLevel name puzzletag segs
-- [ SemiRoom ] --
rThisField fieldLevelRoomS
srooms <- many rSemiRoom
return (level, srooms)
rSemiRoom :: Reader SemiRoom
rSemiRoom = do
rThisField fieldLevelRoom
-- ix
rThisField fieldLevelRoomIx
ix <- rUInt32
-- walls
rThisField fieldLevelRoomWallS
walls <- many rWall
-- dot plain
rThisField fieldLevelRoomDotPlainS
dotplains <- many rDotPlain
-- dot bonus
rThisField fieldLevelRoomDotBonusS
dotbonuss <- many rDotBonus
-- dot tele
rThisField fieldLevelRoomDotTeleS
dotteles <- many rDotTele
-- dot finish
rThisField fieldLevelRoomDotFinishS
dotfinishs <- many rDotFinish
return $ makeSemiRoom ix walls dotplains dotbonuss dotteles dotfinishs
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/designer/source/LevelTools/File.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with grid. If not, see </>.
creator
name
header
name
pussle tag
segments
[(RoomIx, Room)]
ix
walls
dot plain
dot bonus
dot tele
dot finish
------------------------------------------------------------------------------
Reader
| assuming Level
Level --
[ SemiRoom ] --
ix
walls
dot plain
dot bonus
dot tele
dot finish | grid is a game written in Haskell
Copyright ( C ) 2018
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
module LevelTools.File
(
wLevel,
wWorldHeader,
findSimilarFileName,
rLevelFile,
rCompatibleHeaderLevel,
) where
import MyPrelude
import Game
import Game.LevelPuzzleMode.File.Field
import qualified Game.LevelPuzzleMode.File.Version as LP
import Game.LevelPuzzleMode.File.Read
import Game.LevelPuzzleMode.File
import File.Binary
import LevelTools.EditWorld
import System.IO
import System.Directory
import System.FilePath
findSimilarFileName base ext = do
let path = base <.> ext
boolA <- doesFileExist path
boolB <- doesDirectoryExist path
if boolA || boolB then findSimilarFileName (base ++ "~") ext
else return path
version :: [Word8]
version =
[0x6c, 0x30, 0x30, 0x30]
wWorldHeader :: String -> String -> Writer
wWorldHeader creator name = do
wWord8s LP.version
wField fieldCreator
wCStringAlign 4 $ creator
wField fieldName
wCStringAlign 4 $ name
wField fieldLevelS
wLevel :: EditWorld -> Writer
wLevel edit = do
wWord8s version
wField fieldLevel
let level = editLevel edit
wField fieldLevelName
wCStringAlign 4 $ levelName level
wField fieldLevelPuzzleTag
case levelPuzzleTag level of
False -> wUInt32 0
True -> wUInt32 1
wField fieldLevelSegments
wUInt32 $ levelSegments level
let scnt = editSemiContent edit
wField fieldLevelRoomS
forM_ (scontentRooms scnt) $ wSemiRoom
assert : align = = 4
wSemiRoom sroom = do
wField fieldLevelRoom
wField fieldLevelRoomIx
wUInt32 $ sroomRoomIx sroom
wField fieldLevelRoomWallS
forM_ (sroomWall sroom) wWall
wField fieldLevelRoomDotPlainS
forM_ (sroomDotPlain sroom) wDotPlain
wField fieldLevelRoomDotBonusS
forM_ (sroomDotBonus sroom) wDotBonus
wField fieldLevelRoomDotTeleS
forM_ (sroomDotTele sroom) wDotTele
wField fieldLevelRoomDotFinishS
forM_ (sroomDotFinish sroom) wDotFinish
wWall wall = do
wField fieldLevelRoomWall
case wallIsDouble wall of
False -> wUInt32 0
True -> wUInt32 1
let Node n0 n1 n2 = wallNode wall
Node x0 x1 x2 = wallX wall
Node y0 y1 y2 = wallY wall
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wInt32 $ fI x0
wInt32 $ fI x1
wInt32 $ fI x2
wInt32 $ fI y0
wInt32 $ fI y1
wInt32 $ fI y2
wDotPlain dot = do
wField fieldLevelRoomDotPlain
let Node n0 n1 n2 = dotplainNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wUInt32 $ dotplainSize dot
wUInt32 $ dotplainRoom dot
wDotBonus dot = do
wField fieldLevelRoomDotBonus
let Node n0 n1 n2 = dotbonusNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wUInt32 $ dotbonusSize dot
wUInt32 $ dotbonusAdd dot
wDotTele dot = do
wField fieldLevelRoomDotTele
let Node n0 n1 n2 = dotteleNode dot
Node n0' n1' n2' = dotteleNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wUInt32 $ dotteleSize dot
wInt32 $ fI n0'
wInt32 $ fI n1'
wInt32 $ fI n2'
wDotFinish dot = do
wField fieldLevelRoomDotFinish
let Node n0 n1 n2 = dotfinishNode dot
wInt32 $ fI n0
wInt32 $ fI n1
wInt32 $ fI n2
wField :: Field -> Writer
wField field = do
case word32AsWord8s field of
(w0, w1, w2, w3) -> wWord8s [w0, w1, w2, w3]
rCompatibleHeaderLevel :: Reader ()
rCompatibleHeaderLevel = do
ws <- replicateM 4 rAnyWord8
unless (ws == version) $ fail $ "can not read .ldef file with header " ++ show ws
rLevelFile :: Reader (Level, [SemiRoom])
rLevelFile = do
rCompatibleHeaderLevel
rThisField fieldLevel
rThisField fieldLevelName
name <- rCString
rAlign 4
rThisField fieldLevelPuzzleTag
puzzletag <- (/= 0) `fmap` rUInt32
rThisField fieldLevelSegments
segs <- rUInt32
let level = makeLevel name puzzletag segs
rThisField fieldLevelRoomS
srooms <- many rSemiRoom
return (level, srooms)
rSemiRoom :: Reader SemiRoom
rSemiRoom = do
rThisField fieldLevelRoom
rThisField fieldLevelRoomIx
ix <- rUInt32
rThisField fieldLevelRoomWallS
walls <- many rWall
rThisField fieldLevelRoomDotPlainS
dotplains <- many rDotPlain
rThisField fieldLevelRoomDotBonusS
dotbonuss <- many rDotBonus
rThisField fieldLevelRoomDotTeleS
dotteles <- many rDotTele
rThisField fieldLevelRoomDotFinishS
dotfinishs <- many rDotFinish
return $ makeSemiRoom ix walls dotplains dotbonuss dotteles dotfinishs
|
e176b4a4d2b9e21db19885f8f1a41c185a9057f5be8d90a8ed48752635f6dea3 | naoto-ogawa/h-xproto-mysql | Example04.hs | # LANGUAGE DeriveGeneric , ScopedTypeVariables , TemplateHaskell , TypeInType , TypeFamilies , KindSignatures , DataKinds , TypeOperators , GADTs , TypeSynonymInstances , FlexibleInstances #
module Example.Example04 where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Control.Exception.Safe (Exception, MonadThrow, SomeException, throwM, bracket, catch)
import qualified Data.Aeson as JSON
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Int as I
import Data.Kind
import qualified Data.Sequence as Seq
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Word as W
-- protocol buffer library
import qualified Text.ProtocolBuffers as PB
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.ColumnMetaData as PCMD
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.DataModel as PDM
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.Delete as PD
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.Find as PF
-- my library
import DataBase.MySQLX.Exception
import DataBase.MySQLX.Model as XM
import DataBase.MySQLX.NodeSession
import DataBase.MySQLX.Statement
import DataBase.MySQLX.TH
import DataBase.MySQLX.Util
import DataBase.MySQLX.CRUD as CRUD
import GHC.Generics
data BookInfo = BookInfo {
isbn :: String
, title :: String
, author :: String
, currentlyReadingPage :: Int
} deriving (Generic, Show)
instance JSON.FromJSON BookInfo
--
-- JSON Sample : find
--
example4_01 :: IO ()
example4_01 = do
putStrLn "start example4_01"
nodeSess <- openNodeSession $ defaultNodeSesssionInfo {database = "x_protocol_test", user = "root", password="root"}
let f = PB.defaultValue
`setCollection` (mkCollection "x_protocol_test" "mydoc")
`setDataModel` PDM.DOCUMENT
`setCriteria` (exprDocumentPathItem "isbn" @== expr "XXXX-001" )
(_, ret@(x:xs)) <- CRUD.find f nodeSess
let doc = (JSON.eitherDecode' $ cutNull $ Seq.index x 0) :: Either String BookInfo
case doc of
Right x -> do
print x
Left s -> do
print s
return ()
--
-- JSON Sample : insert
--
idea
: : a - > Value
instance where
expr : : Value - > Expr
idea
toJSON :: a -> Value
instance Exprable JSONT.Value where
expr :: Value -> Expr
-}
mysql - sql > select * from mydoc ;
| doc| _ id|
| { " _ i d " : " cbbe7ba36cdb82354db8ec5af29e1f17 " , " " : " XXXX-001 " , " title " : " Effi Briest " , " author " : " " , " currentlyReadingPage " : 42 } | cbbe7ba36cdb82354db8ec5af29e1f17 |
| { " _ i d " : " ebfbf3fac6d6b63d42b75579e6dc4e14 " , " " : " XXXX-003 " , " title " : " ABC " , " author " : " XYZ " , " currentlyReadingPage " : 100 } | ebfbf3fac6d6b63d42b75579e6dc4e14 |
| { " _ i d " : " efe556667944a82142d3151e5b76a7a6 " , " " : " XXXX-002 " , " title " : " " , " author " : " Norway Wood " , " currentlyReadingPage " : 1 } | efe556667944a82142d3151e5b76a7a6 |
mysql-sql> select * from mydoc;
| doc| _id|
| {"_id": "cbbe7ba36cdb82354db8ec5af29e1f17", "isbn": "XXXX-001", "title": "Effi Briest", "author": "Theodor Fontane", "currentlyReadingPage": 42} | cbbe7ba36cdb82354db8ec5af29e1f17 |
| {"_id": "ebfbf3fac6d6b63d42b75579e6dc4e14", "isbn": "XXXX-003", "title": "ABC", "author": "XYZ", "currentlyReadingPage": 100} | ebfbf3fac6d6b63d42b75579e6dc4e14 |
| {"_id": "efe556667944a82142d3151e5b76a7a6", "isbn": "XXXX-002", "title": "Haruki Murakami", "author": "Norway Wood", "currentlyReadingPage": 1} | efe556667944a82142d3151e5b76a7a6 |
-}
| null | https://raw.githubusercontent.com/naoto-ogawa/h-xproto-mysql/1eacd6486c99b849016bf088788cb8d8b166f964/src/Example/Example04.hs | haskell | protocol buffer library
my library
JSON Sample : find
JSON Sample : insert
| # LANGUAGE DeriveGeneric , ScopedTypeVariables , TemplateHaskell , TypeInType , TypeFamilies , KindSignatures , DataKinds , TypeOperators , GADTs , TypeSynonymInstances , FlexibleInstances #
module Example.Example04 where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Control.Exception.Safe (Exception, MonadThrow, SomeException, throwM, bracket, catch)
import qualified Data.Aeson as JSON
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Int as I
import Data.Kind
import qualified Data.Sequence as Seq
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Word as W
import qualified Text.ProtocolBuffers as PB
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.ColumnMetaData as PCMD
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.DataModel as PDM
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.Delete as PD
import qualified Com.Mysql.Cj.Mysqlx.Protobuf.Find as PF
import DataBase.MySQLX.Exception
import DataBase.MySQLX.Model as XM
import DataBase.MySQLX.NodeSession
import DataBase.MySQLX.Statement
import DataBase.MySQLX.TH
import DataBase.MySQLX.Util
import DataBase.MySQLX.CRUD as CRUD
import GHC.Generics
data BookInfo = BookInfo {
isbn :: String
, title :: String
, author :: String
, currentlyReadingPage :: Int
} deriving (Generic, Show)
instance JSON.FromJSON BookInfo
example4_01 :: IO ()
example4_01 = do
putStrLn "start example4_01"
nodeSess <- openNodeSession $ defaultNodeSesssionInfo {database = "x_protocol_test", user = "root", password="root"}
let f = PB.defaultValue
`setCollection` (mkCollection "x_protocol_test" "mydoc")
`setDataModel` PDM.DOCUMENT
`setCriteria` (exprDocumentPathItem "isbn" @== expr "XXXX-001" )
(_, ret@(x:xs)) <- CRUD.find f nodeSess
let doc = (JSON.eitherDecode' $ cutNull $ Seq.index x 0) :: Either String BookInfo
case doc of
Right x -> do
print x
Left s -> do
print s
return ()
idea
: : a - > Value
instance where
expr : : Value - > Expr
idea
toJSON :: a -> Value
instance Exprable JSONT.Value where
expr :: Value -> Expr
-}
mysql - sql > select * from mydoc ;
| doc| _ id|
| { " _ i d " : " cbbe7ba36cdb82354db8ec5af29e1f17 " , " " : " XXXX-001 " , " title " : " Effi Briest " , " author " : " " , " currentlyReadingPage " : 42 } | cbbe7ba36cdb82354db8ec5af29e1f17 |
| { " _ i d " : " ebfbf3fac6d6b63d42b75579e6dc4e14 " , " " : " XXXX-003 " , " title " : " ABC " , " author " : " XYZ " , " currentlyReadingPage " : 100 } | ebfbf3fac6d6b63d42b75579e6dc4e14 |
| { " _ i d " : " efe556667944a82142d3151e5b76a7a6 " , " " : " XXXX-002 " , " title " : " " , " author " : " Norway Wood " , " currentlyReadingPage " : 1 } | efe556667944a82142d3151e5b76a7a6 |
mysql-sql> select * from mydoc;
| doc| _id|
| {"_id": "cbbe7ba36cdb82354db8ec5af29e1f17", "isbn": "XXXX-001", "title": "Effi Briest", "author": "Theodor Fontane", "currentlyReadingPage": 42} | cbbe7ba36cdb82354db8ec5af29e1f17 |
| {"_id": "ebfbf3fac6d6b63d42b75579e6dc4e14", "isbn": "XXXX-003", "title": "ABC", "author": "XYZ", "currentlyReadingPage": 100} | ebfbf3fac6d6b63d42b75579e6dc4e14 |
| {"_id": "efe556667944a82142d3151e5b76a7a6", "isbn": "XXXX-002", "title": "Haruki Murakami", "author": "Norway Wood", "currentlyReadingPage": 1} | efe556667944a82142d3151e5b76a7a6 |
-}
|
84cef0459c5b0f9c1a3a87382e949d3e4689fd5c3a3ea840807dc083f1d0cf2e | wangzhe3224/cs3110 | sorts.ml | (******************************************************************
* INSERTION SORT
******************************************************************)
(* [insert x lst] is a list containing all the elements of [lst] as
* well as [x], sorted according to the built-in operator [>=].
* requires: [lst] is already sorted according to [<=] *)
let rec insert x = function
| [] -> [x]
| h::t ->
if h >= x
then x::h::t
else h::(insert x t)
[ ins_sort lst ] is [ lst ] sorted according to the built - in operator [ < =] .
* performance : O(n^2 ) time , where n is the number of elements in [ lst ] .
* Not tail recursive .
* performance: O(n^2) time, where n is the number of elements in [lst].
* Not tail recursive. *)
let rec ins_sort = function
| [] -> []
| h::t -> insert h (ins_sort t)
(******************************************************************
* MERGE SORT
******************************************************************)
[ take k lst ] is the first [ k ] elements of [ lst ] , or just [ lst ]
* if it has fewer than [ k ] elements .
* requires : [ k>=0 ]
* if it has fewer than [k] elements.
* requires: [k>=0] *)
let rec take k = function
| [] -> []
| h::t ->
if k=0
then []
else h::(take (k-1) t)
[ drop k lst ] is all but the first [ k ] elements of [ lst ] , or just [ ]
* if it has fewer than [ k ] elements .
* requires : [ k>=0 ]
* if it has fewer than [k] elements.
* requires: [k>=0] *)
let rec drop k = function
| [] -> []
| _::t as lst ->
if k=0
then lst
else drop (k-1) t
(* [merge xs ys] is a list containing all the elements of [xs] as well as [ys],
* in sorted order according to [<=].
* requires: [xs] and [ys] are both already sorted according to [<=]. *)
let rec merge xs ys =
match xs, ys with
| [], _ -> ys
| _, [] -> xs
| x::xs', y::ys' ->
if x <= y
then x::(merge xs' ys)
else y::(merge xs ys')
(* [merge_sort lst] is [lst] sorted according to the built-in operator [<=].
* performance: O(n log n) time, where n is the number of elements in [lst].
* Not tail recursive. *)
let rec merge_sort = function
| [] -> []
| [x] -> [x]
| xs ->
let k = (List.length xs) / 2 in
merge
(merge_sort (take k xs))
(merge_sort (drop k xs))
| null | https://raw.githubusercontent.com/wangzhe3224/cs3110/33c1b9662ee5ba4bd13d7ec5a116b539bf086605/labs/lab10/sorts/sorts.ml | ocaml | *****************************************************************
* INSERTION SORT
*****************************************************************
[insert x lst] is a list containing all the elements of [lst] as
* well as [x], sorted according to the built-in operator [>=].
* requires: [lst] is already sorted according to [<=]
*****************************************************************
* MERGE SORT
*****************************************************************
[merge xs ys] is a list containing all the elements of [xs] as well as [ys],
* in sorted order according to [<=].
* requires: [xs] and [ys] are both already sorted according to [<=].
[merge_sort lst] is [lst] sorted according to the built-in operator [<=].
* performance: O(n log n) time, where n is the number of elements in [lst].
* Not tail recursive. |
let rec insert x = function
| [] -> [x]
| h::t ->
if h >= x
then x::h::t
else h::(insert x t)
[ ins_sort lst ] is [ lst ] sorted according to the built - in operator [ < =] .
* performance : O(n^2 ) time , where n is the number of elements in [ lst ] .
* Not tail recursive .
* performance: O(n^2) time, where n is the number of elements in [lst].
* Not tail recursive. *)
let rec ins_sort = function
| [] -> []
| h::t -> insert h (ins_sort t)
[ take k lst ] is the first [ k ] elements of [ lst ] , or just [ lst ]
* if it has fewer than [ k ] elements .
* requires : [ k>=0 ]
* if it has fewer than [k] elements.
* requires: [k>=0] *)
let rec take k = function
| [] -> []
| h::t ->
if k=0
then []
else h::(take (k-1) t)
[ drop k lst ] is all but the first [ k ] elements of [ lst ] , or just [ ]
* if it has fewer than [ k ] elements .
* requires : [ k>=0 ]
* if it has fewer than [k] elements.
* requires: [k>=0] *)
let rec drop k = function
| [] -> []
| _::t as lst ->
if k=0
then lst
else drop (k-1) t
let rec merge xs ys =
match xs, ys with
| [], _ -> ys
| _, [] -> xs
| x::xs', y::ys' ->
if x <= y
then x::(merge xs' ys)
else y::(merge xs ys')
let rec merge_sort = function
| [] -> []
| [x] -> [x]
| xs ->
let k = (List.length xs) / 2 in
merge
(merge_sort (take k xs))
(merge_sort (drop k xs))
|
3515c56010f540a5c0cae514386a948e83f0c372b90994a4cb0974a362edf4ed | callum-oakley/advent-of-code | 15.clj | (ns aoc.2022.15
(:require
[aoc.vector :refer [manhattan-distance]]
[clojure.math.combinatorics :as comb]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(let [readings (->> s (re-seq #"-?\d+") (map read-string) (partition 2)
(map #(vec (reverse %))) (partition 2))]
{:sensors (map (fn [[s b]] [s (manhattan-distance s b)]) readings)
:beacons (set (map second readings))}))
;; Cheating a little by assuming there are no gaps. This turns out to be true.
(defn part-1* [y {:keys [sensors beacons]}]
(let [min-x (apply min (map (fn [[[sy sx] r]] (- sx (- r (abs (- sy y)))))
sensors))
max-x (apply max (map (fn [[[sy sx] r]] (+ sx (- r (abs (- sy y)))))
sensors))]
(- (inc max-x) min-x (count (filter #(= y (first %)) beacons)))))
Find the intersections of the 8 lines that make up the two circles , and then
;; filter those that fall within the boundary.
(defn intersections [s0 s1]
(for [[[[y0 x0] r0] [[y1 x1] r1]] [[s0 s1] [s1 s0]]
sign0 [+ -] sign1 [+ -]
:let [a (- y0 x0 (sign0 r0)) b (+ y1 x1 (sign1 r1))
pos [(/ (+ b a) 2) (/ (- b a) 2)]]
:when (and (every? int? pos)
(= (manhattan-distance pos [y0 x0]) r0)
(= (manhattan-distance pos [y1 x1]) r1))]
pos))
(defn part-2* [bound {:keys [sensors]}]
(->> (comb/combinations sensors 2)
(mapcat (fn [[[c0 r0] [c1 r1]]]
(intersections [c0 (inc r0)] [c1 (inc r1)])))
(remove (fn [pos]
(or (not (every? #(<= 0 % bound) pos))
(some (fn [[c r]] (<= (manhattan-distance c pos) r))
sensors))))
first ((fn [[y x]] (+ y (* 4000000 x))))))
(defn part-1 [readings]
(part-1* 2000000 readings))
(defn part-2 [readings]
(part-2* 4000000 readings))
(def example
"Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3")
(deftest test-example
(is (= 26 (part-1* 10 (parse example))))
(is (= 56000011 (part-2* 20 (parse example)))))
| null | https://raw.githubusercontent.com/callum-oakley/advent-of-code/4f9c3f54779cc6e2d7ff66e0d3d5495b36c15350/src/aoc/2022/15.clj | clojure | Cheating a little by assuming there are no gaps. This turns out to be true.
filter those that fall within the boundary. | (ns aoc.2022.15
(:require
[aoc.vector :refer [manhattan-distance]]
[clojure.math.combinatorics :as comb]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(let [readings (->> s (re-seq #"-?\d+") (map read-string) (partition 2)
(map #(vec (reverse %))) (partition 2))]
{:sensors (map (fn [[s b]] [s (manhattan-distance s b)]) readings)
:beacons (set (map second readings))}))
(defn part-1* [y {:keys [sensors beacons]}]
(let [min-x (apply min (map (fn [[[sy sx] r]] (- sx (- r (abs (- sy y)))))
sensors))
max-x (apply max (map (fn [[[sy sx] r]] (+ sx (- r (abs (- sy y)))))
sensors))]
(- (inc max-x) min-x (count (filter #(= y (first %)) beacons)))))
Find the intersections of the 8 lines that make up the two circles , and then
(defn intersections [s0 s1]
(for [[[[y0 x0] r0] [[y1 x1] r1]] [[s0 s1] [s1 s0]]
sign0 [+ -] sign1 [+ -]
:let [a (- y0 x0 (sign0 r0)) b (+ y1 x1 (sign1 r1))
pos [(/ (+ b a) 2) (/ (- b a) 2)]]
:when (and (every? int? pos)
(= (manhattan-distance pos [y0 x0]) r0)
(= (manhattan-distance pos [y1 x1]) r1))]
pos))
(defn part-2* [bound {:keys [sensors]}]
(->> (comb/combinations sensors 2)
(mapcat (fn [[[c0 r0] [c1 r1]]]
(intersections [c0 (inc r0)] [c1 (inc r1)])))
(remove (fn [pos]
(or (not (every? #(<= 0 % bound) pos))
(some (fn [[c r]] (<= (manhattan-distance c pos) r))
sensors))))
first ((fn [[y x]] (+ y (* 4000000 x))))))
(defn part-1 [readings]
(part-1* 2000000 readings))
(defn part-2 [readings]
(part-2* 4000000 readings))
(def example
"Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3")
(deftest test-example
(is (= 26 (part-1* 10 (parse example))))
(is (= 56000011 (part-2* 20 (parse example)))))
|
80bdebb40883da002caec179076fe9c4ff5b58df565533d4204c3657901e8ae8 | CorticalComputer/Book_NeuroevolutionThroughErlang | actuator.erl | This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM
%%
Copyright ( C ) 2012 by , DXNN Research Group ,
%All rights reserved.
%
This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use .
-module(actuator).
-compile(export_all).
-include("records.hrl").
gen(ExoSelf_PId,Node)->
spawn(Node,?MODULE,prep,[ExoSelf_PId]).
prep(ExoSelf_PId) ->
receive
{ExoSelf_PId,{Id,Cx_PId,Scape,ActuatorName,Parameters,Fanin_PIds}} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,ActuatorName,Parameters,{Fanin_PIds,Fanin_PIds},[])
end.
When is executed it spawns the actuator element and immediately begins to wait for its initial state message .
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{[From_PId|Fanin_PIds],MFanin_PIds},Acc) ->
receive
{From_PId,forward,Input} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{Fanin_PIds,MFanin_PIds},lists:append(Input,Acc));
{ExoSelf_PId,terminate} ->
io:format("Actuator:~p is terminating.~n",[self()]),
ok
end;
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{[],MFanin_PIds},Acc)->
{Fitness,EndFlag} = actuator:AName(lists:reverse(Acc),Parameters,Scape),
Cx_PId ! {self(),sync,Fitness,EndFlag},
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{MFanin_PIds,MFanin_PIds},[]).
The actuator process gathers the control signals from the neurons , appending them to the accumulator . The order in which the signals are accumulated into a vector is in the same order as the neuron ids are stored within NIds . Once all the signals have been gathered , the actuator sends cortex the sync signal , executes its function , and then again begins to wait for the neural signals from the output layer by reseting the Fanin_PIds from the second copy of the list .
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ACTUATORS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
pts(Result,_Scape)->
io:format("actuator:pts(Result): ~p~n",[Result]),
{1,0}.
%The pts/2 actuation function simply prints to screen the vector passed to it.
xor_SendOutput(Output,_Parameters,Scape)->
Scape ! {self(),action,Output},
receive
{Scape,Fitness,HaltFlag}->
{Fitness,HaltFlag}
end.
xor_sim/2 function simply forwards the Output vector to the XOR simulator , and waits for the resulting Fitness and EndFlag from the simulation process .
pb_SendOutput(Output,Parameters,Scape)->
Scape ! {self(),push,Parameters,Output},
receive
{Scape,Fitness,HaltFlag}->
{Fitness,HaltFlag}
end.
dtm_SendOutput(Output,Parameters,Scape)->
Scape ! {self(),move,Parameters,Output},
receive
{Scape,Fitness,HaltFlag}->
io : format("self():~p Fitness:~p HaltFlag:~p ~ n",[self(),Fitness , HaltFlag ] ) ,
{Fitness,HaltFlag}
end.
| null | https://raw.githubusercontent.com/CorticalComputer/Book_NeuroevolutionThroughErlang/81b96e3d7985624a6183cb313a7f9bff0a7e14c5/Ch_15/actuator.erl | erlang |
All rights reserved.
ACTUATORS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The pts/2 actuation function simply prints to screen the vector passed to it. | This source code and work is provided and developed by DXNN Research Group WWW.DXNNResearch . COM
Copyright ( C ) 2012 by , DXNN Research Group ,
This code is licensed under the version 3 of the GNU General Public License . Please see the LICENSE file that accompanies this project for the terms of use .
-module(actuator).
-compile(export_all).
-include("records.hrl").
gen(ExoSelf_PId,Node)->
spawn(Node,?MODULE,prep,[ExoSelf_PId]).
prep(ExoSelf_PId) ->
receive
{ExoSelf_PId,{Id,Cx_PId,Scape,ActuatorName,Parameters,Fanin_PIds}} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,ActuatorName,Parameters,{Fanin_PIds,Fanin_PIds},[])
end.
When is executed it spawns the actuator element and immediately begins to wait for its initial state message .
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{[From_PId|Fanin_PIds],MFanin_PIds},Acc) ->
receive
{From_PId,forward,Input} ->
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{Fanin_PIds,MFanin_PIds},lists:append(Input,Acc));
{ExoSelf_PId,terminate} ->
io:format("Actuator:~p is terminating.~n",[self()]),
ok
end;
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{[],MFanin_PIds},Acc)->
{Fitness,EndFlag} = actuator:AName(lists:reverse(Acc),Parameters,Scape),
Cx_PId ! {self(),sync,Fitness,EndFlag},
loop(Id,ExoSelf_PId,Cx_PId,Scape,AName,Parameters,{MFanin_PIds,MFanin_PIds},[]).
The actuator process gathers the control signals from the neurons , appending them to the accumulator . The order in which the signals are accumulated into a vector is in the same order as the neuron ids are stored within NIds . Once all the signals have been gathered , the actuator sends cortex the sync signal , executes its function , and then again begins to wait for the neural signals from the output layer by reseting the Fanin_PIds from the second copy of the list .
pts(Result,_Scape)->
io:format("actuator:pts(Result): ~p~n",[Result]),
{1,0}.
xor_SendOutput(Output,_Parameters,Scape)->
Scape ! {self(),action,Output},
receive
{Scape,Fitness,HaltFlag}->
{Fitness,HaltFlag}
end.
xor_sim/2 function simply forwards the Output vector to the XOR simulator , and waits for the resulting Fitness and EndFlag from the simulation process .
pb_SendOutput(Output,Parameters,Scape)->
Scape ! {self(),push,Parameters,Output},
receive
{Scape,Fitness,HaltFlag}->
{Fitness,HaltFlag}
end.
dtm_SendOutput(Output,Parameters,Scape)->
Scape ! {self(),move,Parameters,Output},
receive
{Scape,Fitness,HaltFlag}->
io : format("self():~p Fitness:~p HaltFlag:~p ~ n",[self(),Fitness , HaltFlag ] ) ,
{Fitness,HaltFlag}
end.
|
30b14dc94823ad3d28577aac30965f94ee9fa899e0fd6db1df03d7cc5b0affc6 | anwarmamat/cmsc330fall17public | data.mli | type int_tree =
IntLeaf
| IntNode of int * int_tree * int_tree
val empty_int_tree : int_tree
val count : 'a -> 'a list -> int
val divisible_by : int -> int list -> bool list
val divisible_by_first : int list -> bool list
val pairup : 'a list -> 'b list -> ('a * 'b) list
val concat_lists : 'a list list -> 'a list
val int_size : int_tree -> int
val int_max : int_tree -> int
val int_insert : int -> int_tree -> int_tree
val int_mem : int -> int_tree -> bool
val int_insert_all : int list -> int_tree -> int_tree
val int_as_list : int_tree -> int list
val int_common : int_tree -> int -> int -> int
type 'a atree =
Leaf
| Node of 'a * 'a atree * 'a atree
type 'a compfn = 'a -> 'a -> int
type 'a ptree = 'a compfn * 'a atree
val empty_ptree : 'a compfn -> 'a ptree
val pinsert : 'a -> 'a ptree -> 'a compfn * 'a atree
val pmem : 'a -> 'a ptree -> bool
type node = int
type edge = { src : node; dst : node; }
type graph = { nodes : int_tree; edges : edge list; }
val empty_graph : graph
val add_edge : edge -> graph -> graph
val add_edges : edge list -> graph -> graph
val graph_empty : graph -> bool
val graph_size : graph -> node
val is_dst : node -> edge -> bool
val src_edges : node -> graph -> edge list
val reachable : node -> graph -> int_tree
| null | https://raw.githubusercontent.com/anwarmamat/cmsc330fall17public/9a23ec1fc0cc4324e8c316f8d630c4e53af80f04/p2b/data.mli | ocaml | type int_tree =
IntLeaf
| IntNode of int * int_tree * int_tree
val empty_int_tree : int_tree
val count : 'a -> 'a list -> int
val divisible_by : int -> int list -> bool list
val divisible_by_first : int list -> bool list
val pairup : 'a list -> 'b list -> ('a * 'b) list
val concat_lists : 'a list list -> 'a list
val int_size : int_tree -> int
val int_max : int_tree -> int
val int_insert : int -> int_tree -> int_tree
val int_mem : int -> int_tree -> bool
val int_insert_all : int list -> int_tree -> int_tree
val int_as_list : int_tree -> int list
val int_common : int_tree -> int -> int -> int
type 'a atree =
Leaf
| Node of 'a * 'a atree * 'a atree
type 'a compfn = 'a -> 'a -> int
type 'a ptree = 'a compfn * 'a atree
val empty_ptree : 'a compfn -> 'a ptree
val pinsert : 'a -> 'a ptree -> 'a compfn * 'a atree
val pmem : 'a -> 'a ptree -> bool
type node = int
type edge = { src : node; dst : node; }
type graph = { nodes : int_tree; edges : edge list; }
val empty_graph : graph
val add_edge : edge -> graph -> graph
val add_edges : edge list -> graph -> graph
val graph_empty : graph -> bool
val graph_size : graph -> node
val is_dst : node -> edge -> bool
val src_edges : node -> graph -> edge list
val reachable : node -> graph -> int_tree
| |
1e33efd7b265d3b63a349785076332ee2d9608879d6cae76a582b84602866c28 | ocaml/dune | visibility.mli | type t =
| Public
| Private
include Dune_lang.Conv.S with type t := t
val is_public : t -> bool
val is_private : t -> bool
val to_dyn : t -> Dyn.t
module Map : sig
type visibility := t
type 'a t =
{ public : 'a
; private_ : 'a
}
val make_both : 'a -> 'a t
val find : 'a t -> visibility -> 'a
end
| null | https://raw.githubusercontent.com/ocaml/dune/991f9b77e2ced07f5906941814cc640b49d710ea/src/dune_rules/visibility.mli | ocaml | type t =
| Public
| Private
include Dune_lang.Conv.S with type t := t
val is_public : t -> bool
val is_private : t -> bool
val to_dyn : t -> Dyn.t
module Map : sig
type visibility := t
type 'a t =
{ public : 'a
; private_ : 'a
}
val make_both : 'a -> 'a t
val find : 'a t -> visibility -> 'a
end
| |
ebacd861f735cdd3de3faff3635642ae174a1f8d86abb54833bfa271c0364134 | cljdoc/cljdoc | scm.clj | (ns cljdoc.util.scm
"Utilities to extract information from SCM urls (GitHub et al)"
(:require [clojure.string :as string]
[clojure.java.io :as io]
[lambdaisland.uri :as uri]))
(defn owner [scm-url]
(get (string/split (:path (uri/uri scm-url)) #"/") 1))
(defn repo [scm-url]
(get (string/split (:path (uri/uri scm-url)) #"/") 2))
(defn coordinate [scm-url]
(->> (string/split (:path (uri/uri scm-url)) #"/")
(filter seq)
(string/join "/")))
(defn provider [scm-url]
(when-some [host (:host (uri/uri scm-url))]
(cond
(string/ends-with? host "github.com") :github
(string/ends-with? host "gitlab.com") :gitlab
(string/ends-with? host "sr.ht") :sourcehut
(string/ends-with? host "codeberg.org") :codeberg
(string/ends-with? host "bitbucket.org") :bitbucket
(string/starts-with? host "gitea.") :gitea)))
(defn icon-url
"Return url to icon for `scm-url`.
`:asset-prefix` supports online (default) and offline rendering."
([scm-url]
(icon-url scm-url {:asset-prefix "/"}))
([scm-url {:keys [asset-prefix]}]
(let [provider (provider scm-url)]
(case provider
:github "-clone.vercel.app/github"
:gitlab "-clone.vercel.app/gitlab"
:sourcehut (str asset-prefix "sourcehut.svg")
:codeberg (str asset-prefix "codeberg.svg")
:bitbucket "-clone.vercel.app/bitbucket"
:gitea "-clone.vercel.app/gitea"
"-clone.vercel.app/git"))))
(defn- url-scheme
"Some providers share a url scheme, for example :gitlab uses the same scheme as :github, and :codeberg is hosted on :gitea."
[scm-url]
(let [provider (provider scm-url)]
(case provider
:codeberg :gitea
:gitlab :github
provider)))
(defn http-uri
"Given a URI pointing to a git remote, normalize that URI to an HTTP one."
[scm-url]
(cond
(string/starts-with? scm-url "http")
(re-find #"http.*//[^/]*/[^/]*/[^/]*" scm-url)
(or (string/starts-with? scm-url "git@")
(string/starts-with? scm-url "ssh://"))
(-> scm-url
(string/replace #":" "/")
(string/replace #"\.git$" "")
three slashes because of prior :/ replace
(string/replace #"^(ssh///)*git@" "http://"))))
(defn fs-uri
"Normalize a provided `scm-path` to it's canonical path,
return `nil` if the path does not exist on the filesystem."
[scm-path]
(let [f (io/file scm-path)]
(when (.exists f)
(.getCanonicalPath f))))
(defn ssh-uri
"Given a URI pointing to a git remote, normalize that URI to an SSH one."
[scm-url]
(cond
(string/starts-with? scm-url "git@")
scm-url
(string/starts-with? scm-url "http")
(let [{:keys [host path]} (uri/uri scm-url)]
(str "git@" host ":" (subs path 1) ".git"))))
(defn- scm-rev [{:keys [tag commit] :as _scm}]
(or (:name tag) commit))
(defn rev-formatted-base-url
"Return base url appropriate for `scm` for SCM formatted content at revision specifed by `tag` or `commit`.
Favors `tag` over `commit`."
[{:keys [url tag commit] :as scm}]
(let [scheme (url-scheme url)]
(if (= :gitea scheme)
(if (:name tag)
(str url "/src/tag/" (:name tag) "/")
(str url "/src/commit/" commit "/"))
(let [rev (scm-rev scm)]
(case scheme
:sourcehut (str url "/tree/" rev "/")
:bitbucket (str url "/src/" rev "/")
(str url "/blob/" rev "/"))))))
(defn line-anchor [{:keys [url] :as _scm}]
(if (= :bitbucket (provider url))
"#lines-"
"#L"))
(defn rev-raw-base-url
"Return base url approprite for `scm` for SCM unformatted (raw) content at revision specified by `tag` or `commit`.
Favors `tag` over `commit`"
[{:keys [url tag commit] :as scm}]
(let [scheme (url-scheme url)]
(if (= :gitea scheme)
(if (:name tag)
(str url "/raw/tag/" (:name tag) "/")
(str url "/raw/commit/" commit "/"))
(let [rev (scm-rev scm)]
(if (= :sourcehut scheme)
(str url "/blob/" rev "/")
(str url "/raw/" rev "/"))))))
(defn branch-url
"Return url for `source-file` for scm `url` on scm `branch`."
[{:keys [url branch] :as _scm} source-file]
(let [scheme (url-scheme url)
blob-path (cond
(= scheme :sourcehut) "/tree/"
(= scheme :gitea) "/src/branch/"
(= scheme :bitbucket) "/src/"
:else "/blob/")]
(str url blob-path (or branch "master") "/" source-file)))
(defn normalize-git-url
"Ensure that the passed string is a git URL and that it's using HTTPS"
[s]
(cond-> s
(string/starts-with? s "http") (string/replace #"^http://" "https://")
(string/starts-with? s ":") (string/replace #"^:" "/")
(string/ends-with? s ".git") (string/replace #".git$" "")))
| null | https://raw.githubusercontent.com/cljdoc/cljdoc/8787f2a0d01c5cc6ccea8b2f4fd69d96e01379cb/src/cljdoc/util/scm.clj | clojure | (ns cljdoc.util.scm
"Utilities to extract information from SCM urls (GitHub et al)"
(:require [clojure.string :as string]
[clojure.java.io :as io]
[lambdaisland.uri :as uri]))
(defn owner [scm-url]
(get (string/split (:path (uri/uri scm-url)) #"/") 1))
(defn repo [scm-url]
(get (string/split (:path (uri/uri scm-url)) #"/") 2))
(defn coordinate [scm-url]
(->> (string/split (:path (uri/uri scm-url)) #"/")
(filter seq)
(string/join "/")))
(defn provider [scm-url]
(when-some [host (:host (uri/uri scm-url))]
(cond
(string/ends-with? host "github.com") :github
(string/ends-with? host "gitlab.com") :gitlab
(string/ends-with? host "sr.ht") :sourcehut
(string/ends-with? host "codeberg.org") :codeberg
(string/ends-with? host "bitbucket.org") :bitbucket
(string/starts-with? host "gitea.") :gitea)))
(defn icon-url
"Return url to icon for `scm-url`.
`:asset-prefix` supports online (default) and offline rendering."
([scm-url]
(icon-url scm-url {:asset-prefix "/"}))
([scm-url {:keys [asset-prefix]}]
(let [provider (provider scm-url)]
(case provider
:github "-clone.vercel.app/github"
:gitlab "-clone.vercel.app/gitlab"
:sourcehut (str asset-prefix "sourcehut.svg")
:codeberg (str asset-prefix "codeberg.svg")
:bitbucket "-clone.vercel.app/bitbucket"
:gitea "-clone.vercel.app/gitea"
"-clone.vercel.app/git"))))
(defn- url-scheme
"Some providers share a url scheme, for example :gitlab uses the same scheme as :github, and :codeberg is hosted on :gitea."
[scm-url]
(let [provider (provider scm-url)]
(case provider
:codeberg :gitea
:gitlab :github
provider)))
(defn http-uri
"Given a URI pointing to a git remote, normalize that URI to an HTTP one."
[scm-url]
(cond
(string/starts-with? scm-url "http")
(re-find #"http.*//[^/]*/[^/]*/[^/]*" scm-url)
(or (string/starts-with? scm-url "git@")
(string/starts-with? scm-url "ssh://"))
(-> scm-url
(string/replace #":" "/")
(string/replace #"\.git$" "")
three slashes because of prior :/ replace
(string/replace #"^(ssh///)*git@" "http://"))))
(defn fs-uri
"Normalize a provided `scm-path` to it's canonical path,
return `nil` if the path does not exist on the filesystem."
[scm-path]
(let [f (io/file scm-path)]
(when (.exists f)
(.getCanonicalPath f))))
(defn ssh-uri
"Given a URI pointing to a git remote, normalize that URI to an SSH one."
[scm-url]
(cond
(string/starts-with? scm-url "git@")
scm-url
(string/starts-with? scm-url "http")
(let [{:keys [host path]} (uri/uri scm-url)]
(str "git@" host ":" (subs path 1) ".git"))))
(defn- scm-rev [{:keys [tag commit] :as _scm}]
(or (:name tag) commit))
(defn rev-formatted-base-url
"Return base url appropriate for `scm` for SCM formatted content at revision specifed by `tag` or `commit`.
Favors `tag` over `commit`."
[{:keys [url tag commit] :as scm}]
(let [scheme (url-scheme url)]
(if (= :gitea scheme)
(if (:name tag)
(str url "/src/tag/" (:name tag) "/")
(str url "/src/commit/" commit "/"))
(let [rev (scm-rev scm)]
(case scheme
:sourcehut (str url "/tree/" rev "/")
:bitbucket (str url "/src/" rev "/")
(str url "/blob/" rev "/"))))))
(defn line-anchor [{:keys [url] :as _scm}]
(if (= :bitbucket (provider url))
"#lines-"
"#L"))
(defn rev-raw-base-url
"Return base url approprite for `scm` for SCM unformatted (raw) content at revision specified by `tag` or `commit`.
Favors `tag` over `commit`"
[{:keys [url tag commit] :as scm}]
(let [scheme (url-scheme url)]
(if (= :gitea scheme)
(if (:name tag)
(str url "/raw/tag/" (:name tag) "/")
(str url "/raw/commit/" commit "/"))
(let [rev (scm-rev scm)]
(if (= :sourcehut scheme)
(str url "/blob/" rev "/")
(str url "/raw/" rev "/"))))))
(defn branch-url
"Return url for `source-file` for scm `url` on scm `branch`."
[{:keys [url branch] :as _scm} source-file]
(let [scheme (url-scheme url)
blob-path (cond
(= scheme :sourcehut) "/tree/"
(= scheme :gitea) "/src/branch/"
(= scheme :bitbucket) "/src/"
:else "/blob/")]
(str url blob-path (or branch "master") "/" source-file)))
(defn normalize-git-url
"Ensure that the passed string is a git URL and that it's using HTTPS"
[s]
(cond-> s
(string/starts-with? s "http") (string/replace #"^http://" "https://")
(string/starts-with? s ":") (string/replace #"^:" "/")
(string/ends-with? s ".git") (string/replace #".git$" "")))
| |
bc15719ddb048f57c54a4bed93ba493aa09c8ece25755eb6dbe7db7703bd818b | oscarh/gen_httpd | ghtp_utils.erl | %%% ----------------------------------------------------------------------------
Copyright 2008
,
,
%%%
%%% All rights reserved
%%% Redistribution and use in source and binary forms, with or without
%%% modification, are permitted provided that the following conditions are
%%% met:
%%%
%%% * Redistributions of source code must retain the above copyright
%%% notice, this list of conditions and the following disclaimer.
%%% * Redistributions in binary form must reproduce the above copyright
%%% notice, this list of conditions and the following disclaimer in the
%%% documentation and/or other materials provided with the distribution.
%%% * The names of its contributors may not be used to endorse or promote
%%% products derived from this software without specific prior written
%%% permission.
%%%
%%%
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ` ` AS IS '' AND
%%% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%%% ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS 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.
%%% ----------------------------------------------------------------------------
2008 ,
@author < >
@author < > [ ]
%%% @version {@version}, {@date}, {@time}
%%% @doc
Utility module for gen_httpd itself , but also for applications using
%%% gen_httpd.
%%%
%%% == References ==
RFC2396 :
%%% @end
%%% ----------------------------------------------------------------------------
-module(ghtp_utils).
-export([
header_value/2,
header_value/3,
header_values/2,
header_exists/2,
update_header/3,
remove_header/2
]).
-export([timeout/2]).
-export([split_uri/1, parse_query/1, uri_encode/1, uri_decode/1]).
-export([
format_response/3,
format_response/4,
status_line/2,
format_headers/1
]).
-include("gen_httpd_types.hrl").
-define(URI_ENCODE_ESCAPE,
[
Reserved ( RFC 2396 : 2.2 :
$;, $/, $?, $:, $@, $&, $=, $+, $$, $,,
Excluded ( RFC 2396 : 2.4.3 )
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 16#7f,
, $ " , $ { , $ } , $ | , $ \\ , $ ^ , $ [ , $ ] , $ `
]).
%% @type header() = {string(), string()}.
%% @spec (Name, Headers) -> Values
%% Name = string()
%% Headers = [header()]
%% Values = [string()]
%% @doc
%% Returns all values for the header named `Name'.
%% `Name' is expected to be a lowercase string.
%% Returns a list of all values found in the list of headers. Useful for for
%% instance "Transfer-Encoding", of which several can be applied.
%% @end
-spec header_values(string(), [header()]) -> [string()].
header_values(Name, Headers) ->
header_values(Name, Headers, []).
%% @spec (Name, Headers) -> Value | undefined
%% Name = string()
%% Headers = [header()]
%% @doc
%% Returns the value of the header named `Name'.
%% `Name' is expected to be a lowercase string.
%% Returns `undefined' if the header isn't in the list of headers.
%% @end
-spec header_value(string(), [header()]) -> string() | undefined.
header_value(Name, Headers) ->
header_value(Name, Headers, undefined).
%% @spec (Name, Headers, Default :: Default) -> Value | Default
%% Name = string()
%% Headers = [header()]
%% @doc
%% Returns the value of the header named `Name'.
%% `Name' is expected to be a lowercase string.
%% Returns `Default' if the header isn't in the list of headers.
%% @end
-spec header_value(string(), [header()], Type) -> string() | Type.
header_value(Name, [{N, Value} | T], Default) ->
case string:equal(Name, string:to_lower(N)) of
true -> Value;
false -> header_value(Name, T, Default)
end;
header_value(_, [], Default) ->
Default.
%% @spec (Name, Headers) -> boolean()
%% Name = string()
%% Headers = [header()]
%% @doc
%% Checks if a header is defined in the list of headers. `Name' is expected
%% to be a lowercase string.
%% @end
-spec header_exists(string(), [header()]) -> true | false.
header_exists(Name, [{N, _} | T]) ->
case string:equal(Name, string:to_lower(N)) of
true -> true;
false -> header_exists(Name, T)
end;
header_exists(_, []) ->
false.
%% @spec (Name, Value, Headers) -> Headers
%% Name = string()
%% Value = string()
%% Headers = [header()]
%% @doc
Replaces the current value for the first occurrence of ` Name ' with
%% `Value'. If `Name' isn't define, it's added to the list of headers.
-spec update_header(string(), string(), [header()]) -> [header()].
update_header(Name, Value, Headers) ->
update_header(Name, Value, Headers, []).
%% @spec (Name, Headers) -> Headers
%% Name = string()
%% Headers = [header()]
%% @doc
Removes the first occurrence of ` Name ' from the list of headers .
%% @end
-spec remove_header(string(), [header()]) -> [header()].
remove_header(Name, Headers) ->
remove_header(Name, Headers, []).
remove_header(Name, [{Name, _} | T], Acc) ->
Acc ++ T;
remove_header(Name, [{N, _} = Header | T], Acc) ->
case string:equal(Name, string:to_lower(N)) of
true ->
Acc ++ T;
false ->
remove_header(Name, T, [Header | Acc])
end.
%% @spec (String) -> {URI, QueryString}
= string ( )
%% URI = string()
QueryString = string ( )
%% @doc
Splits a URI in to the two parts , the URI and the query string part .
%% If there isn't any query string, the original string is returned... after
%% some gymnastics.
%%
%% @end
-spec split_uri(string()) -> {string(), string()}.
split_uri(String) ->
split_uri(String, []).
( QueryString : : QueryString ) - > [ { Key , Value } ]
QueryString = string ( )
%% Key = string()
%% Value = string()
@doc Turns a query string ( the part after the first ` ? ' in a URI to
%% a list of key value tuples.
The query string can be ` Path'/`URI ' with { @link split_uri/1 } .
%% @end
-spec parse_query(string()) -> [{string(), string()}].
parse_query(QueryStr) ->
case string:tokens(QueryStr, "&") of
[] -> [];
Args ->
lists:map(fun(Arg) ->
case string:tokens(Arg, "=") of
[Key, Value] ->
{uri_decode(Key), uri_decode(Value)};
[Key] ->
{uri_decode(Key), ""}
end
end, Args)
end.
) - > URIEncodedString
= string ( )
%% URIEncodedString = string()
%% @doc
Encodes a string according to RFC2396 .
%% All reserver or excluded characters are turned in to a "%" HEX HEX
%% notation.
%% @end
-spec uri_encode(string()) -> string().
uri_encode(Str) ->
uri_encode(Str, []).
%% @spec uri_decode(URIEncodedString) -> String
%% URIEncodedString = string()
= string ( )
%% @doc
a string according to RFC2396 .
%% All "%" HEX HEX sequences are turned in to the character represented by
%% the HEX HEX number.
%% @end
-spec uri_decode(string()) -> string().
uri_decode(Str) ->
uri_decode(Str, []).
, A , B | Rest ] , Acc ) - >
uri_decode(Rest, [erlang:list_to_integer([A, B], 16) | Acc]);
uri_decode([H | Rest], Acc) ->
uri_decode(Rest, [H | Acc]);
uri_decode([], Acc) ->
lists:reverse(Acc).
@private
-spec format_response(version(), status(), [header()]) -> iolist().
format_response(Vsn, Status, Hdrs) ->
format_response(Vsn, Status, Hdrs, []).
@private
-spec format_response(version(), status(), [header()], iolist() | binary()) ->
iolist().
format_response(Vsn, Status, Hdrs, Body) ->
[status_line(Vsn, Status), format_headers(Hdrs), Body].
@private
-spec format_headers([header()]) -> iolist().
format_headers(Headers) ->
[lists:map(fun({Name, Value}) ->
[Name, $:, $\ , Value, $\r, $\n]
end, Headers), $\r, $\n].
@private
-spec status_line(version(), status()) ->
iolist().
status_line({Major, Minor}, {StatusCode, Reason}) when is_integer(StatusCode) ->
[
"HTTP/", integer_to_list(Major), ".", integer_to_list(Minor), $\ ,
integer_to_list(StatusCode), $\ , Reason, $\r, $\n
];
status_line(Vsn, StatusCode) when is_integer(StatusCode) ->
status_line(Vsn, {StatusCode, reason(StatusCode)}).
@private
-spec timeout(timeout(), {integer(), integer(), integer()}) ->
timeout().
timeout(infinity, _) ->
infinity;
timeout(MS, Start) ->
MS - (timer:now_diff(now(), Start) div 1000).
Internal functions
header_values(Name, [{Field, Value} | Headers], Acc) ->
case string:to_lower(Field) of
Name -> header_values(Name, Headers, [Value | Acc]);
_ -> header_values(Name, Headers, Acc)
end;
header_values(_, [], Acc) ->
Acc.
update_header(Name, Value, [{Name, _} | T], Acc) ->
Acc ++ [{Name, Value}| T];
update_header(Name, Value, [{N, _} = Header | T], Acc) ->
case string:equal(Name, string:to_lower(N)) of
true ->
Acc ++ [{Name, Value}| T];
false ->
update_header(Name, Value, T, [Header | Acc])
end;
update_header(Name, Value, [], Acc) ->
[{Name, Value} | Acc].
split_uri([$? | QueryString], Acc) ->
{lists:reverse(Acc), QueryString};
split_uri([Char | Tail], Acc) ->
split_uri(Tail, [Char | Acc]);
split_uri([], Acc) ->
{lists:reverse(Acc), ""}.
uri_encode([H | T], Acc) ->
uri_encode(T, case lists:member(H, ?URI_ENCODE_ESCAPE) of
true ->
[A, B] = char_to_hex(H),
[B, A, $% | Acc];
false ->
[H | Acc]
end);
uri_encode([], Acc) ->
lists:reverse(Acc).
char_to_hex(Char) ->
string:right(erlang:integer_to_list(Char, 16), 2, $0).
reason(100) -> "Continue";
reason(101) -> "Switching Protocols";
reason(200) -> "OK";
reason(201) -> "Created";
reason(202) -> "Accepted";
reason(203) -> "Non-Authoritative Information";
reason(204) -> "No Content";
reason(206) -> "Partial Content";
reason(300) -> "Multiple Choices";
reason(301) -> "Moved Permanently";
reason(302) -> "Found";
reason(303) -> "See Other";
reason(304) -> "Not Modified";
reason(305) -> "Use Proxy";
reason(307) -> "Temporary Redirect";
reason(400) -> "Bad Request";
reason(401) -> "Unauthorized";
reason(402) -> "Payment Required";
reason(403) -> "Forbidden";
reason(404) -> "Not Found";
reason(405) -> "Method Not Allowed";
reason(406) -> "Not Acceptable";
reason(407) -> "Proxy Authentication Required";
reason(408) -> "Request Time-Out";
reason(409) -> "Conflict";
reason(410) -> "Gone";
reason(411) -> "Length Required";
reason(412) -> "Precondition Failed";
reason(413) -> "Request Entity Too Large";
reason(414) -> "Request-URI Too Large";
reason(415) -> "Unsupported Media Type";
reason(416) -> "Requested range tot satisfiable";
reason(417) -> "Expectation Failed";
reason(500) -> "Internal server error";
reason(501) -> "Not Implemented";
reason(502) -> "Bad Gateway";
reason(503) -> "Service Unavailable";
reason(504) -> "Gateway Time-Out";
reason(505) -> "HTTP Version not supported".
| null | https://raw.githubusercontent.com/oscarh/gen_httpd/5b48e33d8fac30c70e2d89d74c56e057d570064e/src/ghtp_utils.erl | erlang | ----------------------------------------------------------------------------
All rights reserved
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
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.
----------------------------------------------------------------------------
@version {@version}, {@date}, {@time}
@doc
gen_httpd.
== References ==
@end
----------------------------------------------------------------------------
@type header() = {string(), string()}.
@spec (Name, Headers) -> Values
Name = string()
Headers = [header()]
Values = [string()]
@doc
Returns all values for the header named `Name'.
`Name' is expected to be a lowercase string.
Returns a list of all values found in the list of headers. Useful for for
instance "Transfer-Encoding", of which several can be applied.
@end
@spec (Name, Headers) -> Value | undefined
Name = string()
Headers = [header()]
@doc
Returns the value of the header named `Name'.
`Name' is expected to be a lowercase string.
Returns `undefined' if the header isn't in the list of headers.
@end
@spec (Name, Headers, Default :: Default) -> Value | Default
Name = string()
Headers = [header()]
@doc
Returns the value of the header named `Name'.
`Name' is expected to be a lowercase string.
Returns `Default' if the header isn't in the list of headers.
@end
@spec (Name, Headers) -> boolean()
Name = string()
Headers = [header()]
@doc
Checks if a header is defined in the list of headers. `Name' is expected
to be a lowercase string.
@end
@spec (Name, Value, Headers) -> Headers
Name = string()
Value = string()
Headers = [header()]
@doc
`Value'. If `Name' isn't define, it's added to the list of headers.
@spec (Name, Headers) -> Headers
Name = string()
Headers = [header()]
@doc
@end
@spec (String) -> {URI, QueryString}
URI = string()
@doc
If there isn't any query string, the original string is returned... after
some gymnastics.
@end
Key = string()
Value = string()
a list of key value tuples.
@end
URIEncodedString = string()
@doc
All reserver or excluded characters are turned in to a "%" HEX HEX
notation.
@end
@spec uri_decode(URIEncodedString) -> String
URIEncodedString = string()
@doc
All "%" HEX HEX sequences are turned in to the character represented by
the HEX HEX number.
@end
| Acc]; | Copyright 2008
,
,
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
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
2008 ,
@author < >
@author < > [ ]
Utility module for gen_httpd itself , but also for applications using
RFC2396 :
-module(ghtp_utils).
-export([
header_value/2,
header_value/3,
header_values/2,
header_exists/2,
update_header/3,
remove_header/2
]).
-export([timeout/2]).
-export([split_uri/1, parse_query/1, uri_encode/1, uri_decode/1]).
-export([
format_response/3,
format_response/4,
status_line/2,
format_headers/1
]).
-include("gen_httpd_types.hrl").
-define(URI_ENCODE_ESCAPE,
[
Reserved ( RFC 2396 : 2.2 :
$;, $/, $?, $:, $@, $&, $=, $+, $$, $,,
Excluded ( RFC 2396 : 2.4.3 )
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 16#7f,
, $ " , $ { , $ } , $ | , $ \\ , $ ^ , $ [ , $ ] , $ `
]).
-spec header_values(string(), [header()]) -> [string()].
header_values(Name, Headers) ->
header_values(Name, Headers, []).
-spec header_value(string(), [header()]) -> string() | undefined.
header_value(Name, Headers) ->
header_value(Name, Headers, undefined).
-spec header_value(string(), [header()], Type) -> string() | Type.
header_value(Name, [{N, Value} | T], Default) ->
case string:equal(Name, string:to_lower(N)) of
true -> Value;
false -> header_value(Name, T, Default)
end;
header_value(_, [], Default) ->
Default.
-spec header_exists(string(), [header()]) -> true | false.
header_exists(Name, [{N, _} | T]) ->
case string:equal(Name, string:to_lower(N)) of
true -> true;
false -> header_exists(Name, T)
end;
header_exists(_, []) ->
false.
Replaces the current value for the first occurrence of ` Name ' with
-spec update_header(string(), string(), [header()]) -> [header()].
update_header(Name, Value, Headers) ->
update_header(Name, Value, Headers, []).
Removes the first occurrence of ` Name ' from the list of headers .
-spec remove_header(string(), [header()]) -> [header()].
remove_header(Name, Headers) ->
remove_header(Name, Headers, []).
remove_header(Name, [{Name, _} | T], Acc) ->
Acc ++ T;
remove_header(Name, [{N, _} = Header | T], Acc) ->
case string:equal(Name, string:to_lower(N)) of
true ->
Acc ++ T;
false ->
remove_header(Name, T, [Header | Acc])
end.
= string ( )
QueryString = string ( )
Splits a URI in to the two parts , the URI and the query string part .
-spec split_uri(string()) -> {string(), string()}.
split_uri(String) ->
split_uri(String, []).
( QueryString : : QueryString ) - > [ { Key , Value } ]
QueryString = string ( )
@doc Turns a query string ( the part after the first ` ? ' in a URI to
The query string can be ` Path'/`URI ' with { @link split_uri/1 } .
-spec parse_query(string()) -> [{string(), string()}].
parse_query(QueryStr) ->
case string:tokens(QueryStr, "&") of
[] -> [];
Args ->
lists:map(fun(Arg) ->
case string:tokens(Arg, "=") of
[Key, Value] ->
{uri_decode(Key), uri_decode(Value)};
[Key] ->
{uri_decode(Key), ""}
end
end, Args)
end.
) - > URIEncodedString
= string ( )
Encodes a string according to RFC2396 .
-spec uri_encode(string()) -> string().
uri_encode(Str) ->
uri_encode(Str, []).
= string ( )
a string according to RFC2396 .
-spec uri_decode(string()) -> string().
uri_decode(Str) ->
uri_decode(Str, []).
, A , B | Rest ] , Acc ) - >
uri_decode(Rest, [erlang:list_to_integer([A, B], 16) | Acc]);
uri_decode([H | Rest], Acc) ->
uri_decode(Rest, [H | Acc]);
uri_decode([], Acc) ->
lists:reverse(Acc).
@private
-spec format_response(version(), status(), [header()]) -> iolist().
format_response(Vsn, Status, Hdrs) ->
format_response(Vsn, Status, Hdrs, []).
@private
-spec format_response(version(), status(), [header()], iolist() | binary()) ->
iolist().
format_response(Vsn, Status, Hdrs, Body) ->
[status_line(Vsn, Status), format_headers(Hdrs), Body].
@private
-spec format_headers([header()]) -> iolist().
format_headers(Headers) ->
[lists:map(fun({Name, Value}) ->
[Name, $:, $\ , Value, $\r, $\n]
end, Headers), $\r, $\n].
@private
-spec status_line(version(), status()) ->
iolist().
status_line({Major, Minor}, {StatusCode, Reason}) when is_integer(StatusCode) ->
[
"HTTP/", integer_to_list(Major), ".", integer_to_list(Minor), $\ ,
integer_to_list(StatusCode), $\ , Reason, $\r, $\n
];
status_line(Vsn, StatusCode) when is_integer(StatusCode) ->
status_line(Vsn, {StatusCode, reason(StatusCode)}).
@private
-spec timeout(timeout(), {integer(), integer(), integer()}) ->
timeout().
timeout(infinity, _) ->
infinity;
timeout(MS, Start) ->
MS - (timer:now_diff(now(), Start) div 1000).
Internal functions
header_values(Name, [{Field, Value} | Headers], Acc) ->
case string:to_lower(Field) of
Name -> header_values(Name, Headers, [Value | Acc]);
_ -> header_values(Name, Headers, Acc)
end;
header_values(_, [], Acc) ->
Acc.
update_header(Name, Value, [{Name, _} | T], Acc) ->
Acc ++ [{Name, Value}| T];
update_header(Name, Value, [{N, _} = Header | T], Acc) ->
case string:equal(Name, string:to_lower(N)) of
true ->
Acc ++ [{Name, Value}| T];
false ->
update_header(Name, Value, T, [Header | Acc])
end;
update_header(Name, Value, [], Acc) ->
[{Name, Value} | Acc].
split_uri([$? | QueryString], Acc) ->
{lists:reverse(Acc), QueryString};
split_uri([Char | Tail], Acc) ->
split_uri(Tail, [Char | Acc]);
split_uri([], Acc) ->
{lists:reverse(Acc), ""}.
uri_encode([H | T], Acc) ->
uri_encode(T, case lists:member(H, ?URI_ENCODE_ESCAPE) of
true ->
[A, B] = char_to_hex(H),
false ->
[H | Acc]
end);
uri_encode([], Acc) ->
lists:reverse(Acc).
char_to_hex(Char) ->
string:right(erlang:integer_to_list(Char, 16), 2, $0).
reason(100) -> "Continue";
reason(101) -> "Switching Protocols";
reason(200) -> "OK";
reason(201) -> "Created";
reason(202) -> "Accepted";
reason(203) -> "Non-Authoritative Information";
reason(204) -> "No Content";
reason(206) -> "Partial Content";
reason(300) -> "Multiple Choices";
reason(301) -> "Moved Permanently";
reason(302) -> "Found";
reason(303) -> "See Other";
reason(304) -> "Not Modified";
reason(305) -> "Use Proxy";
reason(307) -> "Temporary Redirect";
reason(400) -> "Bad Request";
reason(401) -> "Unauthorized";
reason(402) -> "Payment Required";
reason(403) -> "Forbidden";
reason(404) -> "Not Found";
reason(405) -> "Method Not Allowed";
reason(406) -> "Not Acceptable";
reason(407) -> "Proxy Authentication Required";
reason(408) -> "Request Time-Out";
reason(409) -> "Conflict";
reason(410) -> "Gone";
reason(411) -> "Length Required";
reason(412) -> "Precondition Failed";
reason(413) -> "Request Entity Too Large";
reason(414) -> "Request-URI Too Large";
reason(415) -> "Unsupported Media Type";
reason(416) -> "Requested range tot satisfiable";
reason(417) -> "Expectation Failed";
reason(500) -> "Internal server error";
reason(501) -> "Not Implemented";
reason(502) -> "Bad Gateway";
reason(503) -> "Service Unavailable";
reason(504) -> "Gateway Time-Out";
reason(505) -> "HTTP Version not supported".
|
46415cb8710b65e94f2482f71c9d0828348b85d5b652a6948e666744c12b041e | ocaml/oasis | foo.ml | (******************************************************************************)
OASIS : architecture for building OCaml libraries and applications
(* *)
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
(* *)
(* This library is free software; you can redistribute it and/or modify it *)
(* under the terms of the GNU Lesser General Public License as published by *)
the Free Software Foundation ; either version 2.1 of the License , or ( at
(* your option) any later version, with the OCaml static compilation *)
(* exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *)
(* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *)
(* details. *)
(* *)
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
(******************************************************************************)
let () = prerr_endline "Foo"
| null | https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/test/data/TestFull/dynrun_for_release/foo.ml | ocaml | ****************************************************************************
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
your option) any later version, with the OCaml static compilation
exception.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more
details.
**************************************************************************** | OASIS : architecture for building OCaml libraries and applications
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
the Free Software Foundation ; either version 2.1 of the License , or ( at
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
let () = prerr_endline "Foo"
|
4bd825e315a3021c6c735c3106d8ec7e2eaa458708ad86d588731ced01f1ee22 | quchen/prettyprinter | GenerateReadme.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Main (main) where
import Prelude hiding (words)
import qualified Data.List as L
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Prettyprinter
import Prettyprinter.Render.Text
import MultilineTh
main :: IO ()
main = (T.putStrLn . renderStrict . layoutPretty layoutOptions) readmeContents
where
layoutOptions = LayoutOptions { layoutPageWidth = AvailablePerLine 80 1 }
readmeContents :: Doc ann
readmeContents = (mconcat . L.intersperse vspace)
[ htmlComment "This file was auto-generated by the 'scripts/generate_readme' program."
, h1 "A modern Wadler/Leijen Prettyprinter"
, vcat
[ "[](-ci.org/quchen/prettyprinter)"
, "[]()"
, "[]()"
, "[]()" ]
, h2 "tl;dr"
, paragraph [multiline| A prettyprinter/text rendering engine. Easy to
use, well-documented, ANSI terminal backend exists, HTML backend is
trivial to implement, no name clashes, `Text`-based, extensible. |]
, (pretty . T.unlines)
[ "```haskell"
, "let prettyType = align . sep . zipWith (<+>) (\"::\" : repeat \"->\")"
, " prettySig name ty = pretty name <+> prettyType ty"
, "in prettySig \"example\" [\"Int\", \"Bool\", \"Char\", \"IO ()\"]"
, "```"
, ""
, "```haskell"
, "-- Output for wide enough formats:"
, "example :: Int -> Bool -> Char -> IO ()"
, ""
, "-- Output for narrow formats:"
, "example :: Int"
, " -> Bool"
, " -> Char"
, " -> IO ()"
, "```" ]
, h2 "Longer; want to read"
, paragraph [multiline| This package defines a prettyprinter to format
text in a flexible and convenient way. The idea is to combine a document
out of many small components, then using a layouter to convert it to an
easily renderable simple document, which can then be rendered to a
variety of formats, for example plain `Text`, or Markdown. *What you are
reading right now was generated by this library (see
`GenerateReadme.hs`).* |]
, h2 "Why another prettyprinter?"
, paragraph [multiline| Haskell, more specifically Hackage, has a zoo of
Wadler/Leijen based prettyprinters already. Each of them addresses a
different concern with the classic `wl-pprint` package. This package
solves *all* these issues, and then some. |]
, h3 "`Text` instead of `String`"
, paragraph [multiline| `String` has exactly one use, and that’s showing
Hello World in tutorials. For all other uses, `Text` is what people
should be using. The prettyprinter uses no `String` definitions
anywhere; using a `String` means an immediate conversion to the internal
`Text`-based format. |]
, h3 "Extensive documentation"
, paragraph [multiline| The library is stuffed with runnable examples,
showing use cases for the vast majority of exported values. Many things
reference related definitions, *everything* comes with at least a
sentence explaining its purpose. |]
, h3 "No name clashes"
, paragraph [multiline| Many prettyprinters use the legacy API of the
first Wadler/Leijen prettyprinter, which used e.g. `(<$>)` to separate
lines, which clashes with the ubiquitous synonym for `fmap` that’s been
in Base for ages. These definitions were either removed or renamed, so
there are no name clashes with standard libraries anymore. |]
, h3 "Annotation support"
, paragraph [multiline| Text is not all letters and newlines. Often, we
want to add more information, the simplest kind being some form of
styling. An ANSI terminal supports coloring, a web browser a plethora of
different formattings. |]
, paragraph [multiline| More complex uses of annotations include e.g.
adding type annotations for mouse-over hovers when printing a syntax
tree, adding URLs to documentation, or adding source locations to show
where a certain piece of output comes from.
[Idris](-lang/Idris-dev) is a project that makes
extensive use of such a feature. |]
, paragraph [multiline| Special care has been applied to make
annotations unobtrusive, so that if you don’t need or care about them
there is no overhead, neither in terms of usability nor performance. |]
, h3 "Extensible backends"
, paragraph [multiline| A document can be rendered in many different
ways, for many different clients. There is plain text, there is the ANSI
terminal, there is the browser. Each of these speak different languages,
and the backend is responsible for the translation to those languages.
Backends should be readily available, or easy to implement if a custom
solution is desired. |]
, paragraph [multiline| As a result, each backend requires only minimal
dependencies; if you don’t want to print to an ANSI terminal for
example, there is no need to have a dependency on a terminal library. |]
, h3 "Performance"
, paragraph [multiline| Rendering large documents should be done
efficiently, and the library should make it easy to optimize common use
cases for the programmer. |]
, h3 "Open implementation"
, paragraph [multiline| The type of documents is abstract in most of the
other Wadler/Leijen prettyprinters, making it hard to impossible to
write adaptors from one library to another. The type should be exposed
for such purposes so it is possible to write adaptors from library to
library, or each of them is doomed to live on its own small island of
incompatibility. For this reason, the `Doc` type is fully exposed in a
semi-internal module for this specific use case. |]
, h2 "The prettyprinter family"
, paragraph "The `prettyprinter` family of packages consists of:"
, (indent 2 . unorderedList . map paragraph)
[ [multiline| `prettyprinter` is the core package. It defines the
language to generate nicely laid out documents, which can then be
given to renderers to display them in various ways, e.g. HTML, or
plain text.|]
, [multiline| `prettyprinter-ansi-terminal` provides a renderer suitable
for ANSI terminal output including colors (at the cost of a
dependency more).|]
, [multiline| `prettyprinter-compat-wl-pprint` provides a drop-in
compatibility layer for previous users of the `wl-pprint` package. Use
it for easy adaption of the new `prettyprinter`, but don't develop
anything new with it.|]
, [multiline| `prettyprinter-compat-ansi-wl-pprint` is the same, but for
previous users of `ansi-wl-pprint`.|]
, [multiline| `prettyprinter-compat-annotated-wl-pprint` is the same,
but for previous users of `annotated-wl-pprint`.|]
, [multiline| `prettyprinter-convert-ansi-wl-pprint` is a *converter*,
not a drop-in replacement, for documents generated by `ansi-wl-pprint`.
Useful for interfacing with other libraries that use the other format,
like Trifecta and Optparse-Applicative. |]
]
, h2 "Differences to the old Wadler/Leijen prettyprinters"
, paragraph [multiline| The library originally started as a fork of
`ansi-wl-pprint` until every line had been touched. The result is still in
the same spirit as its predecessors, but modernized to match the current
ecosystem and needs. |]
, paragraph "The most significant changes are:"
, (indent 2 . orderedList . map paragraph)
[ [multiline| `(<$>)` is removed as an operator, since it clashes with
the common alias for `fmap`. |]
, [multiline| All but the essential `<>` and `<+>` operators were
removed or replaced by ordinary names. |]
, [multiline| Everything extensively documented, with references to
other functions and runnable code examples. |]
, [multiline| Use of `Text` instead of `String`. |]
, [multiline| A `fuse` function to optimize often-used documents before
rendering for efficiency. |]
, [multiline| SimpleDoc was renamed `SimpleDocStream`, to contrast the
new `SimpleDocTree`. |]
, [multiline| In the ANSI backend, instead of providing an own
colorization function for each color/intensity/layer combination, they
have been combined in `color`, `colorDull`, `bgColor`, and
`bgColorDull` functions, which can be found in the ANSI terminal
specific `prettyprinter-ansi-terminal` package. |]
]
, h2 "Historical notes"
, paragraph [multiline| This module is based on previous work by Daan
Leijen and Max Bolingbroke, who implemented and significantly extended
the prettyprinter given by a [paper by Phil Wadler in his 1997 paper »A
Prettier
Printer«](),
by adding lots of convenience functions, styling, and new functionality.
Their package, ansi-wl-pprint is widely used in the Haskell ecosystem,
and is at the time of writing maintained by Edward Kmett.|]
]
paragraph :: Text -> Doc ann
paragraph = align . fillSep . map pretty . T.words
vspace :: Doc ann
vspace = hardline <> hardline
h1 :: Doc ann -> Doc ann
h1 x = vspace <> underlineWith "=" x
h2 :: Doc ann -> Doc ann
h2 x = vspace <> underlineWith "-" x
h3 :: Doc ann -> Doc ann
h3 x = vspace <> "###" <+> x
underlineWith :: Text -> Doc ann -> Doc ann
underlineWith symbol x = align (width x (\w ->
hardline <> pretty (T.take w (T.replicate w symbol))))
orderedList :: [Doc ann] -> Doc ann
orderedList = align . vsep . zipWith (\i x -> pretty i <> dot <+> align x) [1::Int ..]
unorderedList :: [Doc ann] -> Doc ann
unorderedList = align . vsep . map ("-" <+>)
htmlComment :: Doc ann -> Doc ann
htmlComment = enclose "<!-- " " -->"
| null | https://raw.githubusercontent.com/quchen/prettyprinter/880f41eac31edfac71d2d66d338e6cfdae4f3715/prettyprinter/app/GenerateReadme.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes # |
module Main (main) where
import Prelude hiding (words)
import qualified Data.List as L
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Prettyprinter
import Prettyprinter.Render.Text
import MultilineTh
main :: IO ()
main = (T.putStrLn . renderStrict . layoutPretty layoutOptions) readmeContents
where
layoutOptions = LayoutOptions { layoutPageWidth = AvailablePerLine 80 1 }
readmeContents :: Doc ann
readmeContents = (mconcat . L.intersperse vspace)
[ htmlComment "This file was auto-generated by the 'scripts/generate_readme' program."
, h1 "A modern Wadler/Leijen Prettyprinter"
, vcat
[ "[](-ci.org/quchen/prettyprinter)"
, "[]()"
, "[]()"
, "[]()" ]
, h2 "tl;dr"
, paragraph [multiline| A prettyprinter/text rendering engine. Easy to
use, well-documented, ANSI terminal backend exists, HTML backend is
trivial to implement, no name clashes, `Text`-based, extensible. |]
, (pretty . T.unlines)
[ "```haskell"
, "let prettyType = align . sep . zipWith (<+>) (\"::\" : repeat \"->\")"
, " prettySig name ty = pretty name <+> prettyType ty"
, "in prettySig \"example\" [\"Int\", \"Bool\", \"Char\", \"IO ()\"]"
, "```"
, ""
, "```haskell"
, "-- Output for wide enough formats:"
, "example :: Int -> Bool -> Char -> IO ()"
, ""
, "-- Output for narrow formats:"
, "example :: Int"
, " -> Bool"
, " -> Char"
, " -> IO ()"
, "```" ]
, h2 "Longer; want to read"
, paragraph [multiline| This package defines a prettyprinter to format
text in a flexible and convenient way. The idea is to combine a document
out of many small components, then using a layouter to convert it to an
easily renderable simple document, which can then be rendered to a
variety of formats, for example plain `Text`, or Markdown. *What you are
reading right now was generated by this library (see
`GenerateReadme.hs`).* |]
, h2 "Why another prettyprinter?"
, paragraph [multiline| Haskell, more specifically Hackage, has a zoo of
Wadler/Leijen based prettyprinters already. Each of them addresses a
different concern with the classic `wl-pprint` package. This package
solves *all* these issues, and then some. |]
, h3 "`Text` instead of `String`"
, paragraph [multiline| `String` has exactly one use, and that’s showing
Hello World in tutorials. For all other uses, `Text` is what people
should be using. The prettyprinter uses no `String` definitions
anywhere; using a `String` means an immediate conversion to the internal
`Text`-based format. |]
, h3 "Extensive documentation"
, paragraph [multiline| The library is stuffed with runnable examples,
showing use cases for the vast majority of exported values. Many things
reference related definitions, *everything* comes with at least a
sentence explaining its purpose. |]
, h3 "No name clashes"
, paragraph [multiline| Many prettyprinters use the legacy API of the
first Wadler/Leijen prettyprinter, which used e.g. `(<$>)` to separate
lines, which clashes with the ubiquitous synonym for `fmap` that’s been
in Base for ages. These definitions were either removed or renamed, so
there are no name clashes with standard libraries anymore. |]
, h3 "Annotation support"
, paragraph [multiline| Text is not all letters and newlines. Often, we
want to add more information, the simplest kind being some form of
styling. An ANSI terminal supports coloring, a web browser a plethora of
different formattings. |]
, paragraph [multiline| More complex uses of annotations include e.g.
adding type annotations for mouse-over hovers when printing a syntax
tree, adding URLs to documentation, or adding source locations to show
where a certain piece of output comes from.
[Idris](-lang/Idris-dev) is a project that makes
extensive use of such a feature. |]
, paragraph [multiline| Special care has been applied to make
annotations unobtrusive, so that if you don’t need or care about them
there is no overhead, neither in terms of usability nor performance. |]
, h3 "Extensible backends"
, paragraph [multiline| A document can be rendered in many different
ways, for many different clients. There is plain text, there is the ANSI
terminal, there is the browser. Each of these speak different languages,
and the backend is responsible for the translation to those languages.
Backends should be readily available, or easy to implement if a custom
solution is desired. |]
, paragraph [multiline| As a result, each backend requires only minimal
dependencies; if you don’t want to print to an ANSI terminal for
example, there is no need to have a dependency on a terminal library. |]
, h3 "Performance"
, paragraph [multiline| Rendering large documents should be done
efficiently, and the library should make it easy to optimize common use
cases for the programmer. |]
, h3 "Open implementation"
, paragraph [multiline| The type of documents is abstract in most of the
other Wadler/Leijen prettyprinters, making it hard to impossible to
write adaptors from one library to another. The type should be exposed
for such purposes so it is possible to write adaptors from library to
library, or each of them is doomed to live on its own small island of
incompatibility. For this reason, the `Doc` type is fully exposed in a
semi-internal module for this specific use case. |]
, h2 "The prettyprinter family"
, paragraph "The `prettyprinter` family of packages consists of:"
, (indent 2 . unorderedList . map paragraph)
[ [multiline| `prettyprinter` is the core package. It defines the
language to generate nicely laid out documents, which can then be
given to renderers to display them in various ways, e.g. HTML, or
plain text.|]
, [multiline| `prettyprinter-ansi-terminal` provides a renderer suitable
for ANSI terminal output including colors (at the cost of a
dependency more).|]
, [multiline| `prettyprinter-compat-wl-pprint` provides a drop-in
compatibility layer for previous users of the `wl-pprint` package. Use
it for easy adaption of the new `prettyprinter`, but don't develop
anything new with it.|]
, [multiline| `prettyprinter-compat-ansi-wl-pprint` is the same, but for
previous users of `ansi-wl-pprint`.|]
, [multiline| `prettyprinter-compat-annotated-wl-pprint` is the same,
but for previous users of `annotated-wl-pprint`.|]
, [multiline| `prettyprinter-convert-ansi-wl-pprint` is a *converter*,
not a drop-in replacement, for documents generated by `ansi-wl-pprint`.
Useful for interfacing with other libraries that use the other format,
like Trifecta and Optparse-Applicative. |]
]
, h2 "Differences to the old Wadler/Leijen prettyprinters"
, paragraph [multiline| The library originally started as a fork of
`ansi-wl-pprint` until every line had been touched. The result is still in
the same spirit as its predecessors, but modernized to match the current
ecosystem and needs. |]
, paragraph "The most significant changes are:"
, (indent 2 . orderedList . map paragraph)
[ [multiline| `(<$>)` is removed as an operator, since it clashes with
the common alias for `fmap`. |]
, [multiline| All but the essential `<>` and `<+>` operators were
removed or replaced by ordinary names. |]
, [multiline| Everything extensively documented, with references to
other functions and runnable code examples. |]
, [multiline| Use of `Text` instead of `String`. |]
, [multiline| A `fuse` function to optimize often-used documents before
rendering for efficiency. |]
, [multiline| SimpleDoc was renamed `SimpleDocStream`, to contrast the
new `SimpleDocTree`. |]
, [multiline| In the ANSI backend, instead of providing an own
colorization function for each color/intensity/layer combination, they
have been combined in `color`, `colorDull`, `bgColor`, and
`bgColorDull` functions, which can be found in the ANSI terminal
specific `prettyprinter-ansi-terminal` package. |]
]
, h2 "Historical notes"
, paragraph [multiline| This module is based on previous work by Daan
Leijen and Max Bolingbroke, who implemented and significantly extended
the prettyprinter given by a [paper by Phil Wadler in his 1997 paper »A
Prettier
Printer«](),
by adding lots of convenience functions, styling, and new functionality.
Their package, ansi-wl-pprint is widely used in the Haskell ecosystem,
and is at the time of writing maintained by Edward Kmett.|]
]
paragraph :: Text -> Doc ann
paragraph = align . fillSep . map pretty . T.words
vspace :: Doc ann
vspace = hardline <> hardline
h1 :: Doc ann -> Doc ann
h1 x = vspace <> underlineWith "=" x
h2 :: Doc ann -> Doc ann
h2 x = vspace <> underlineWith "-" x
h3 :: Doc ann -> Doc ann
h3 x = vspace <> "###" <+> x
underlineWith :: Text -> Doc ann -> Doc ann
underlineWith symbol x = align (width x (\w ->
hardline <> pretty (T.take w (T.replicate w symbol))))
orderedList :: [Doc ann] -> Doc ann
orderedList = align . vsep . zipWith (\i x -> pretty i <> dot <+> align x) [1::Int ..]
unorderedList :: [Doc ann] -> Doc ann
unorderedList = align . vsep . map ("-" <+>)
htmlComment :: Doc ann -> Doc ann
htmlComment = enclose "<!-- " " -->"
|
1b16b3169cb0d4c61c279782f541110c1c4cbc2145b7988f0563e31d5f9620cc | Ptival/language-ocaml | ModuleExpr.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - orphans #
module Language.OCaml.PrettyPrinter.ModuleExpr
( moduleExprPP,
)
where
import Language.OCaml.Definitions.Parsing.ParseTree
( ModuleExpr (pmodDesc),
)
import Language.OCaml.PrettyPrinter.ModuleExprDesc ()
import Prettyprinter (Doc, Pretty (pretty))
moduleExprPP :: ModuleExpr -> Doc a
moduleExprPP = pretty . pmodDesc
instance Pretty ModuleExpr where
pretty = moduleExprPP
| null | https://raw.githubusercontent.com/Ptival/language-ocaml/7b07fd3cc466bb2ad2cac4bfe3099505cb63a4f4/lib/Language/OCaml/PrettyPrinter/ModuleExpr.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
# OPTIONS_GHC -fno - warn - orphans #
module Language.OCaml.PrettyPrinter.ModuleExpr
( moduleExprPP,
)
where
import Language.OCaml.Definitions.Parsing.ParseTree
( ModuleExpr (pmodDesc),
)
import Language.OCaml.PrettyPrinter.ModuleExprDesc ()
import Prettyprinter (Doc, Pretty (pretty))
moduleExprPP :: ModuleExpr -> Doc a
moduleExprPP = pretty . pmodDesc
instance Pretty ModuleExpr where
pretty = moduleExprPP
|
0244b2398e1f833f1ee40147b60813fb57c8cb2d2415b7c6d431cbbc1489194f | rumblesan/improviz | Runtime.hs | # LANGUAGE TemplateHaskell #
module Improviz.Runtime
( ImprovizRuntime
, makeRuntimeState
, initialInterpreter
, currentAst
, updateProgram
, resetProgram
, saveProgram
, resizeRuntime
, programHasChanged
, materialsToLoad
) where
import Configuration.Shaders ( ShaderData )
import Gfx.Context ( GfxContext )
import Gfx.Engine ( GfxEngine )
import qualified Improviz.SystemVars as SV
import Language ( initialInterpreterState
, updateSystemVars
)
import Language.Ast ( Program(..) )
import Language.Interpreter.Types ( InterpreterState )
import Lens.Simple ( (^.)
, makeLenses
, set
, view
)
data ImprovizRuntime gfxContext = ImprovizRuntime
{ _programText :: String
, _lastProgramText :: String
, _currentAst :: Program
, _lastWorkingAst :: Program
, _materialsToLoad :: [ShaderData]
, _initialInterpreter :: InterpreterState
}
makeLenses ''ImprovizRuntime
makeRuntimeState
:: [(FilePath, Program)]
-> GfxEngine
-> GfxContext
-> IO (ImprovizRuntime GfxContext)
makeRuntimeState userCode gfx ctx =
let sysVars = SV.create gfx
in do
is <- initialInterpreterState sysVars userCode ctx
return ImprovizRuntime { _programText = ""
, _lastProgramText = ""
, _currentAst = Program []
, _lastWorkingAst = Program []
, _materialsToLoad = []
, _initialInterpreter = is
}
resizeRuntime
:: GfxEngine -> ImprovizRuntime GfxContext -> ImprovizRuntime GfxContext
resizeRuntime gfx runtime =
let newSysVars = SV.create gfx
interpState = _initialInterpreter runtime
in runtime { _initialInterpreter = updateSystemVars newSysVars interpState }
updateProgram :: String -> Program -> ImprovizRuntime eg -> ImprovizRuntime eg
updateProgram newProgram newAst =
set programText newProgram . set currentAst newAst
resetProgram :: ImprovizRuntime eg -> ImprovizRuntime eg
resetProgram as =
let oldAst = view lastWorkingAst as
oldText = view lastProgramText as
in set programText oldText $ set currentAst oldAst as
saveProgram :: ImprovizRuntime eg -> ImprovizRuntime eg
saveProgram as =
let ast = view currentAst as
text = view programText as
in set lastWorkingAst ast $ set lastProgramText text as
programHasChanged :: ImprovizRuntime eg -> Bool
programHasChanged as = as ^. currentAst /= as ^. lastWorkingAst
| null | https://raw.githubusercontent.com/rumblesan/improviz/e9f797de18c949853fc3bf6037b5e58b3f2494e1/src/Improviz/Runtime.hs | haskell | # LANGUAGE TemplateHaskell #
module Improviz.Runtime
( ImprovizRuntime
, makeRuntimeState
, initialInterpreter
, currentAst
, updateProgram
, resetProgram
, saveProgram
, resizeRuntime
, programHasChanged
, materialsToLoad
) where
import Configuration.Shaders ( ShaderData )
import Gfx.Context ( GfxContext )
import Gfx.Engine ( GfxEngine )
import qualified Improviz.SystemVars as SV
import Language ( initialInterpreterState
, updateSystemVars
)
import Language.Ast ( Program(..) )
import Language.Interpreter.Types ( InterpreterState )
import Lens.Simple ( (^.)
, makeLenses
, set
, view
)
data ImprovizRuntime gfxContext = ImprovizRuntime
{ _programText :: String
, _lastProgramText :: String
, _currentAst :: Program
, _lastWorkingAst :: Program
, _materialsToLoad :: [ShaderData]
, _initialInterpreter :: InterpreterState
}
makeLenses ''ImprovizRuntime
makeRuntimeState
:: [(FilePath, Program)]
-> GfxEngine
-> GfxContext
-> IO (ImprovizRuntime GfxContext)
makeRuntimeState userCode gfx ctx =
let sysVars = SV.create gfx
in do
is <- initialInterpreterState sysVars userCode ctx
return ImprovizRuntime { _programText = ""
, _lastProgramText = ""
, _currentAst = Program []
, _lastWorkingAst = Program []
, _materialsToLoad = []
, _initialInterpreter = is
}
resizeRuntime
:: GfxEngine -> ImprovizRuntime GfxContext -> ImprovizRuntime GfxContext
resizeRuntime gfx runtime =
let newSysVars = SV.create gfx
interpState = _initialInterpreter runtime
in runtime { _initialInterpreter = updateSystemVars newSysVars interpState }
updateProgram :: String -> Program -> ImprovizRuntime eg -> ImprovizRuntime eg
updateProgram newProgram newAst =
set programText newProgram . set currentAst newAst
resetProgram :: ImprovizRuntime eg -> ImprovizRuntime eg
resetProgram as =
let oldAst = view lastWorkingAst as
oldText = view lastProgramText as
in set programText oldText $ set currentAst oldAst as
saveProgram :: ImprovizRuntime eg -> ImprovizRuntime eg
saveProgram as =
let ast = view currentAst as
text = view programText as
in set lastWorkingAst ast $ set lastProgramText text as
programHasChanged :: ImprovizRuntime eg -> Bool
programHasChanged as = as ^. currentAst /= as ^. lastWorkingAst
| |
64042b8a6ecc5e99c2eb0d8009d8adea711cf1b5a8b9236d22c093168e4521c9 | fetburner/compelib | pUnionFind.mli | module F
(Elt : sig
type t
val compare : t -> t -> int
end)
(Map : sig
type key = Elt.t
type size
type 'a t
(* make n : 定義域 n で全要素が未定義の Map を作る *)
val make : size -> 'a t
(* 未定義の添字について呼び出した場合 Not_found を投げる *)
val find : key -> 'a t -> 'a
val add : key -> 'a -> 'a t -> 'a t
end)
: sig
type t
type elt = Elt.t
type dom = Map.size
module Class : sig
(* 集合の識別子 *)
type t
val compare : t -> t -> int
end
val make : dom -> t
(* 要素がどの集合に属するか調べる *)
val find : elt -> t -> Class.t
(* 与えられた集合同士を合併する *)
val union : Class.t -> Class.t -> t -> t
(* 与えられた集合に属する要素の数を求める *)
val cardinal : Class.t -> t -> int
end
| null | https://raw.githubusercontent.com/fetburner/compelib/d8fc5d9acd04e676c4d4d2ca9c6a7140f1b85670/lib/container/pUnionFind.mli | ocaml | make n : 定義域 n で全要素が未定義の Map を作る
未定義の添字について呼び出した場合 Not_found を投げる
集合の識別子
要素がどの集合に属するか調べる
与えられた集合同士を合併する
与えられた集合に属する要素の数を求める | module F
(Elt : sig
type t
val compare : t -> t -> int
end)
(Map : sig
type key = Elt.t
type size
type 'a t
val make : size -> 'a t
val find : key -> 'a t -> 'a
val add : key -> 'a -> 'a t -> 'a t
end)
: sig
type t
type elt = Elt.t
type dom = Map.size
module Class : sig
type t
val compare : t -> t -> int
end
val make : dom -> t
val find : elt -> t -> Class.t
val union : Class.t -> Class.t -> t -> t
val cardinal : Class.t -> t -> int
end
|
6e73e136bceb1879200da63a582e75e913c3c74bbdc5b9ec86d638a70b3db4a4 | oakes/cross-parinfer | project.clj | (defproject cross-parinfer "1.5.1-SNAPSHOT"
:description "A library that wraps Parinfer for Clojure and ClojureScript"
:url "-parinfer"
:license {:name "Public Domain"
:url ""}
:repositories [["clojars" {:url ""
:sign-releases false}]]
:profiles {:dev {:main cross-parinfer.core}})
| null | https://raw.githubusercontent.com/oakes/cross-parinfer/ea7349959296fd2348a1f62de7b21ead7bb88566/project.clj | clojure | (defproject cross-parinfer "1.5.1-SNAPSHOT"
:description "A library that wraps Parinfer for Clojure and ClojureScript"
:url "-parinfer"
:license {:name "Public Domain"
:url ""}
:repositories [["clojars" {:url ""
:sign-releases false}]]
:profiles {:dev {:main cross-parinfer.core}})
| |
090c1dcc03eeeb1f647cd7296bc0ac946dd6644f821d8af913a04aaaa17c351a | abarbu/haskell-torch | DefaultType.hs | # LANGUAGE MultiParamTypeClasses , KindSignatures , FlexibleInstances , DataKinds , PatternSynonyms , StandaloneDeriving , GeneralizedNewtypeDeriving , PolyKinds #
module Plugin.DefaultType(DefaultType,plugin) where
import GhcPlugins
import TcRnTypes
import Constraint
import TcPluginM
import qualified Inst
import InstEnv
import TcSimplify (approximateWC)
import qualified Finder
import Panic (panicDoc)
import Data.List
import TcType
import qualified Data.Map as M
import TyCoRep (Type(..))
import TyCon (TyCon(..))
import Control.Monad (liftM2)
import GHC.TypeLits
class DefaultType x (y :: x)
instance Eq Type where
(==) = eqType
instance Ord Type where
compare = nonDetCmpType
instance Semigroup (TcPluginM [a]) where
(<>) = liftM2 (++)
instance Monoid (TcPluginM [a]) where
mempty = pure mempty
plugin :: Plugin
plugin = defaultPlugin {
defaultingPlugin = install,
pluginRecompile = purePlugin
}
install args = Just $ DefaultingPlugin { dePluginInit = initialize
, dePluginRun = run
, dePluginStop = stop
}
pattern FoundModule :: Module -> FindResult
pattern FoundModule a <- Found _ a
fr_mod :: a -> a
fr_mod = id
lookupModule :: ModuleName -- ^ Name of the module
-> TcPluginM Module
lookupModule mod_nm = do
hsc_env <- TcPluginM.getTopEnv
found_module <- TcPluginM.tcPluginIO $ Finder.findPluginModule hsc_env mod_nm
case found_module of
FoundModule h -> return (fr_mod h)
_ -> do
found_module' <- TcPluginM.findImportedModule mod_nm $ Just $ fsLit "this"
case found_module' of
FoundModule h -> return (fr_mod h)
_ -> panicDoc "Unable to resolve module looked up by plugin: "
(ppr mod_nm)
data PluginState = PluginState { defaultClassName :: Name }
-- | Find a 'Name' in a 'Module' given an 'OccName'
lookupName :: Module -> OccName -> TcPluginM Name
lookupName md occ = lookupOrig md occ
solveDefaultType :: PluginState -> [Ct] -> TcPluginM DefaultingPluginResult
solveDefaultType _ [] = return []
solveDefaultType state wanteds = do
envs <- getInstEnvs
insts <- classInstances envs <$> tcLookupClass (defaultClassName state)
let defaults = foldl' (\m inst ->
case is_tys inst of
[matchty, replacety] ->
M.insertWith (++) matchty [replacety] m) M.empty insts
let groups =
foldl' (\m wanted ->
foldl' (\m var -> M.insertWith (++) var [wanted] m)
m
(filter (isVariableDefaultable defaults) $ tyCoVarsOfCtList wanted))
M.empty wanteds
M.foldMapWithKey (\var cts ->
case M.lookup (tyVarKind var) defaults of
Nothing -> error "Bug, we already checked that this variable has a default"
Just deftys -> do
pure [(deftys, (var, cts))])
groups
where isVariableDefaultable defaults v = isAmbiguousTyVar v && M.member (tyVarKind v) defaults
lookupDefaultTypes :: TcPluginM PluginState
lookupDefaultTypes = do
md <- lookupModule (mkModuleName "Plugin.DefaultType")
name <- lookupName md (mkTcOcc "DefaultType")
pure $ PluginState { defaultClassName = name }
initialize = do
lookupDefaultTypes
run s ws = do
solveDefaultType s (ctsElts $ approximateWC False ws)
stop _ = do
return ()
| null | https://raw.githubusercontent.com/abarbu/haskell-torch/03b2c10bf8ca3d4508d52c2123e753d93b3c4236/default-type-plugin/src/Plugin/DefaultType.hs | haskell | ^ Name of the module
| Find a 'Name' in a 'Module' given an 'OccName' | # LANGUAGE MultiParamTypeClasses , KindSignatures , FlexibleInstances , DataKinds , PatternSynonyms , StandaloneDeriving , GeneralizedNewtypeDeriving , PolyKinds #
module Plugin.DefaultType(DefaultType,plugin) where
import GhcPlugins
import TcRnTypes
import Constraint
import TcPluginM
import qualified Inst
import InstEnv
import TcSimplify (approximateWC)
import qualified Finder
import Panic (panicDoc)
import Data.List
import TcType
import qualified Data.Map as M
import TyCoRep (Type(..))
import TyCon (TyCon(..))
import Control.Monad (liftM2)
import GHC.TypeLits
class DefaultType x (y :: x)
instance Eq Type where
(==) = eqType
instance Ord Type where
compare = nonDetCmpType
instance Semigroup (TcPluginM [a]) where
(<>) = liftM2 (++)
instance Monoid (TcPluginM [a]) where
mempty = pure mempty
plugin :: Plugin
plugin = defaultPlugin {
defaultingPlugin = install,
pluginRecompile = purePlugin
}
install args = Just $ DefaultingPlugin { dePluginInit = initialize
, dePluginRun = run
, dePluginStop = stop
}
pattern FoundModule :: Module -> FindResult
pattern FoundModule a <- Found _ a
fr_mod :: a -> a
fr_mod = id
-> TcPluginM Module
lookupModule mod_nm = do
hsc_env <- TcPluginM.getTopEnv
found_module <- TcPluginM.tcPluginIO $ Finder.findPluginModule hsc_env mod_nm
case found_module of
FoundModule h -> return (fr_mod h)
_ -> do
found_module' <- TcPluginM.findImportedModule mod_nm $ Just $ fsLit "this"
case found_module' of
FoundModule h -> return (fr_mod h)
_ -> panicDoc "Unable to resolve module looked up by plugin: "
(ppr mod_nm)
data PluginState = PluginState { defaultClassName :: Name }
lookupName :: Module -> OccName -> TcPluginM Name
lookupName md occ = lookupOrig md occ
solveDefaultType :: PluginState -> [Ct] -> TcPluginM DefaultingPluginResult
solveDefaultType _ [] = return []
solveDefaultType state wanteds = do
envs <- getInstEnvs
insts <- classInstances envs <$> tcLookupClass (defaultClassName state)
let defaults = foldl' (\m inst ->
case is_tys inst of
[matchty, replacety] ->
M.insertWith (++) matchty [replacety] m) M.empty insts
let groups =
foldl' (\m wanted ->
foldl' (\m var -> M.insertWith (++) var [wanted] m)
m
(filter (isVariableDefaultable defaults) $ tyCoVarsOfCtList wanted))
M.empty wanteds
M.foldMapWithKey (\var cts ->
case M.lookup (tyVarKind var) defaults of
Nothing -> error "Bug, we already checked that this variable has a default"
Just deftys -> do
pure [(deftys, (var, cts))])
groups
where isVariableDefaultable defaults v = isAmbiguousTyVar v && M.member (tyVarKind v) defaults
lookupDefaultTypes :: TcPluginM PluginState
lookupDefaultTypes = do
md <- lookupModule (mkModuleName "Plugin.DefaultType")
name <- lookupName md (mkTcOcc "DefaultType")
pure $ PluginState { defaultClassName = name }
initialize = do
lookupDefaultTypes
run s ws = do
solveDefaultType s (ctsElts $ approximateWC False ws)
stop _ = do
return ()
|
6a00d849199509ef8ec38ffea2b49042f6778ce30568152f233981c5685269bb | irastypain/sicp-on-language-racket | exercise_2_11.rkt | #lang racket
(require "../lib/interval-arithmetic.rkt")
Умножение интервалов ,
; знаки концов интервалов
Версия " в лоб "
(define (mul-interval-v1 x y)
(define (cross-compare pred1 pred2)
(or (and pred1 (not pred2))
(and (not pred1) pred2)))
(let ((lx (lower-bound x))
(ly (lower-bound y))
(ux (upper-bound x))
(uy (upper-bound y)))
(let ((n-lx (< lx 0))
(n-ly (< ly 0))
(n-ux (< ux 0))
(n-uy (< uy 0))
(p1 (* lx ly))
(p2 (* lx uy))
(p3 (* ux ly))
(p4 (* ux uy)))
(cond ((and n-lx n-ux n-ly n-uy)
(make-interval p4 p1))
((and n-lx n-ux (cross-compare n-ly n-uy))
(make-interval p2 p1))
((and n-lx n-ux (not n-ly) (not n-uy))
(make-interval p2 p3))
((and (cross-compare n-lx n-ux) n-ly n-uy)
(make-interval p3 p1))
((and (cross-compare n-lx n-ux)
(cross-compare n-ly n-uy))
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4)))
((and (cross-compare n-lx n-ux) (not n-ly) (not n-uy))
(make-interval p2 p4))
((and (not n-lx) (not n-ux) n-ly n-uy)
(make-interval p3 p2))
((and (not n-lx) (not n-ux) (cross-compare n-ly n-uy))
(make-interval p3 p4))
((and (not n-lx) (not n-ux) (not n-ly) (not n-uy))
(make-interval p1 p4))))))
; Версия "определение положения
"
(define (mul-interval-v2 x y)
(let ((lx (lower-bound x))
(ly (lower-bound y))
(ux (upper-bound x))
(uy (upper-bound y)))
(let ((p1 (* lx ly))
(p2 (* lx uy))
(p3 (* ux ly))
(p4 (* ux uy)))
(cond ((positive? lx)
(cond ((positive? ly)
(make-interval p1 p4))
((negative? uy)
(make-interval p3 p2))
(else
(make-interval p3 p4))))
((negative? ux)
(cond ((positive? ly)
(make-interval p2 p3))
((negative? uy)
(make-interval p4 p1))
(else
(make-interval p2 p1))))
(else
(cond ((positive? ly)
(make-interval p2 p4))
((negative? uy)
(make-interval p3 p1))
(else
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4)))))))))
процедур
(provide mul-interval-v1 mul-interval-v2)
| null | https://raw.githubusercontent.com/irastypain/sicp-on-language-racket/0052f91d3c2432a00e7e15310f416cb77eeb4c9c/src/chapter02/exercise_2_11.rkt | racket | знаки концов интервалов
Версия "определение положения | #lang racket
(require "../lib/interval-arithmetic.rkt")
Умножение интервалов ,
Версия " в лоб "
(define (mul-interval-v1 x y)
(define (cross-compare pred1 pred2)
(or (and pred1 (not pred2))
(and (not pred1) pred2)))
(let ((lx (lower-bound x))
(ly (lower-bound y))
(ux (upper-bound x))
(uy (upper-bound y)))
(let ((n-lx (< lx 0))
(n-ly (< ly 0))
(n-ux (< ux 0))
(n-uy (< uy 0))
(p1 (* lx ly))
(p2 (* lx uy))
(p3 (* ux ly))
(p4 (* ux uy)))
(cond ((and n-lx n-ux n-ly n-uy)
(make-interval p4 p1))
((and n-lx n-ux (cross-compare n-ly n-uy))
(make-interval p2 p1))
((and n-lx n-ux (not n-ly) (not n-uy))
(make-interval p2 p3))
((and (cross-compare n-lx n-ux) n-ly n-uy)
(make-interval p3 p1))
((and (cross-compare n-lx n-ux)
(cross-compare n-ly n-uy))
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4)))
((and (cross-compare n-lx n-ux) (not n-ly) (not n-uy))
(make-interval p2 p4))
((and (not n-lx) (not n-ux) n-ly n-uy)
(make-interval p3 p2))
((and (not n-lx) (not n-ux) (cross-compare n-ly n-uy))
(make-interval p3 p4))
((and (not n-lx) (not n-ux) (not n-ly) (not n-uy))
(make-interval p1 p4))))))
"
(define (mul-interval-v2 x y)
(let ((lx (lower-bound x))
(ly (lower-bound y))
(ux (upper-bound x))
(uy (upper-bound y)))
(let ((p1 (* lx ly))
(p2 (* lx uy))
(p3 (* ux ly))
(p4 (* ux uy)))
(cond ((positive? lx)
(cond ((positive? ly)
(make-interval p1 p4))
((negative? uy)
(make-interval p3 p2))
(else
(make-interval p3 p4))))
((negative? ux)
(cond ((positive? ly)
(make-interval p2 p3))
((negative? uy)
(make-interval p4 p1))
(else
(make-interval p2 p1))))
(else
(cond ((positive? ly)
(make-interval p2 p4))
((negative? uy)
(make-interval p3 p1))
(else
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4)))))))))
процедур
(provide mul-interval-v1 mul-interval-v2)
|
e6a02ca8bfb218d73700ffd6460073d46076854ce0710603a5a429be7e9bf569 | chiroptical/optics-by-example | Lib.hs | # LANGUAGE InstanceSigs #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
module Lib where
import Control.Lens
import qualified Data.ByteString as BS
import Data.Char (toLower, toUpper)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Tree (Tree (Node))
a = ["Borg", "Cardassian", "Talaxian"]
b = a ^? ix 1
c = a ^? ix 10
c' = a ^. ix 10
d = a & ix 1 .~ "Vulkan"
e = a & ix 10 .~ "Romulan"
f = M.fromList [("Katara", "Water"), ("Toph", "Earth"), ("Zuko", "Fire")]
g = f ^? ix "Zuko"
h = f ^? ix "Sokka"
i = ("hello" :: T.Text) ^? ix 0
j = ("hello" :: BS.ByteString) ^? ix 0
k = ("hello" :: BS.ByteString) & ix 0 +~ 2
l = ("hello" :: T.Text) & ix 1 %%~ \_ -> ("aeiou" :: [Char])
m :: Tree Integer
m = Node 1 [Node 2 [Node 4 []], Node 3 [Node 5 [], Node 6 [], Node 7 []]]
Index of first subtree , index of second subtree
n = m ^? ix [1, 2]
o = reverse ^? ix "Stella!"
p = reverse & ix ("password" :: String) .~ "You guessed the magic word!"
q = f ^. at "Zuko"
r = f & at "Zuko" .~ Nothing
s = f & at "Hello" .~ Just "World"
s' = f & at "Hello" ?~ "World"
primes :: S.Set Integer
primes = S.fromList [2, 3, 5, 7, 11, 13]
t = primes ^? ix 5
u = primes ^? ix 4
v = primes & at 14 ?~ ()
Exercises - Indexable Structures
1 . Fill in the blanks
w = ["Larry", "Curly", "Moe"] & ix 1 .~ "Wiggly"
[ " " , " Wiggly " , " " ]
hv = M.fromList [("Superman", "Lex Luther"), ("Batman", "Joker")]
x = hv & at "Spiderman" .~ Just "Goblin"
M.fromList [ ( " Superman " , " " ) , ( " " , " Goblin " ) , ( " Batman " , " Joker " ) ]
y = sans "Superman" hv
M.fromList [ ( " Batman " , " Joker " ) ]
z = S.fromList ['a', 'e', 'i', 'o', 'u'] & at 'y' ?~ () & at 'i' .~ Nothing
S.fromList " aeouy "
2 . Use ` ix ` and ` at ` to go from input to output
input = M.fromList [("candy bars", 13), ("soda", 34), ("gum", 7)]
output = M.fromList [("candy bars", 13), ("ice cream", 5), ("soda", 37)]
a' =
input
& at "gum" .~ Nothing
& at "ice cream" ?~ 5
& at "soda" %~ fmap (+ 3)
newtype Cycled a = Cycled [a] deriving (Show)
type instance Index (Cycled a) = Int
type instance IxValue (Cycled a) = a
instance Ixed (Cycled a) where
-- ix :: Int -> Traversal' (Cycled a) a
ix :: Applicative f => Int -> (a -> f a) -> Cycled a -> f (Cycled a)
ix i handler (Cycled xs) =
Cycled <$> traverseOf (ix (i `mod` length xs)) handler xs
b' = Cycled ['a', 'b', 'c'] & ix (-1) .~ '!'
data Address = Address
{ _buildingNumber :: Maybe String,
_streetName :: Maybe String,
_apartmentNumber :: Maybe String,
_postalCode :: Maybe String
}
deriving (Show)
makeLenses ''Address
data AddressComponent
= BuildingNumber
| StreetName
| ApartmentNumber
| PostalCode
deriving (Show)
type instance Index Address = AddressComponent
type instance IxValue Address = String
instance Ixed Address
instance At Address where
at :: AddressComponent -> Lens' Address (Maybe String)
at BuildingNumber = buildingNumber
at StreetName = streetName
at ApartmentNumber = apartmentNumber
at PostalCode = postalCode
addr = Address Nothing Nothing Nothing Nothing
d' =
addr
& at StreetName ?~ "Baker St."
& at ApartmentNumber ?~ "221B"
Exercises - Custom Indexed Structures
1 . Implement both ` Ixed ` and ` At ` for a newtype wrapper around ` Map `
-- which makes indexing case insensitive
newtype CIMap a = CIMap (M.Map String a) deriving (Show)
makeLenses ''CIMap
type instance Index (CIMap a) = String
type instance IxValue (CIMap a) = a
instance Ixed (CIMap a) where
-- ix :: Applicative f => String -> (a -> f a) -> CIMap a -> f (CIMap a)
ix :: String -> Traversal' (CIMap a) a
ix i handler (CIMap map) =
let lowerMap = M.mapKeys (fmap toLower) map
in CIMap <$> traverseOf (ix (toLower <$> i)) handler lowerMap
f' = CIMap (M.fromList [("HELLO", 0)]) ^? ix "hello"
f_ = CIMap (M.fromList [("hello", 0)]) ^? ix "world"
instance At (CIMap a) where
at :: Functor f => String -> (Maybe a -> f (Maybe a)) -> CIMap a -> f (CIMap a)
at key handler (CIMap map) =
let lowerMap = M.mapKeys (fmap toLower) map
in CIMap <$> (lowerMap & at (toLower <$> key) handler)
g' = CIMap (M.fromList [("HELLO", "derp")]) & at "Hello" ?~ "world"
g_ = g' ^? ix "HELLO"
h' = "abcd" & failover (ix 6) toUpper :: Maybe String
i' = "abcd" & failover (ix 2) toUpper :: Maybe String
j' = "abcd" & failover (ix 2) toUpper :: IO String
k' = M.fromList [('a', 1), ('b', 2)] ^? (ix 'b' `failing` ix 'a')
l' = M.fromList [('a', 1), ('b', 2)] & (ix 'b' `failing` ix 'z') *~ 20
m' = Nothing ^. non 0
n' = Just "value" ^. non "default"
o' = M.fromList [("Garfield", "Lasagna"), ("Leslie", "Waffles")]
p' = o' ^. at "Leslie" . non "Pizza"
equivalent to ` q ' = fromMaybe ' z ' ( " abc " ^ ? ix 10 ) `
q' = ("abc" :: String) ^. pre (ix 10) . non 'z'
r' = [1, 3, 5] ^. pre (traversed . filtered even) . non 2
-- Exercises
1 . Write an optic which focuses the value at key " first " or , failing that
the value at key " second "
t' =
let optic = ix "first" `failing` ix "second"
in ( M.fromList [("first", False), ("second", False)] & optic .~ True,
M.fromList [("second", False)] & optic .~ True
)
2 . Write an optic which focuses first element of type if even or second element
-- otherwise
u' =
let optic = _1 . filtered even `failing` _2
in ( (1, 1) & optic *~ 10,
(2, 1) & optic *~ 10
)
3 . Optic should focus all even numbers or all numbers when no even present
v' =
let optic = traversed . filtered even `failing` traversed
in ( [1, 2, 3, 4] ^.. optic,
[1, 3, 5] ^.. optic
)
4 . Fill in the blanks ...
w' = Nothing ^. non "default"
-- "default"
x' = Nothing & non 100 +~ 7
Just 107
y' =
M.fromList
[ ("Perogies", True),
("Pizza", True),
("Pilsners", True)
]
^. at "Broccoli" . non False
-- False
z' =
M.fromList
[ ("Breath of the wild", 22000000),
("Odyssey", 9070000)
]
& at "Wario's Woods" . non 0
+~ 999
Adds ( " Wario 's Woods",999 ) to Map
a_ = ["Math", "Science", "Geography"] ^. pre (ix 10) . non "Unscheduled"
-- "Unscheduled
b_ = [1, 2, 3, 4] ^.. traversed . pre (filtered even) . non (-1)
[ -1 , 2 , -1 , 4 ]
Comment from Twitch , not in book
c_ = [1, 2, 3, 4] & mapped %~ \n -> if even n then n else (-1)
| null | https://raw.githubusercontent.com/chiroptical/optics-by-example/3ee33546ee18c3a6f5510eec17a69d34e750198e/chapter8/src/Lib.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
ix :: Int -> Traversal' (Cycled a) a
which makes indexing case insensitive
ix :: Applicative f => String -> (a -> f a) -> CIMap a -> f (CIMap a)
Exercises
otherwise
"default"
False
"Unscheduled | # LANGUAGE InstanceSigs #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
module Lib where
import Control.Lens
import qualified Data.ByteString as BS
import Data.Char (toLower, toUpper)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Tree (Tree (Node))
a = ["Borg", "Cardassian", "Talaxian"]
b = a ^? ix 1
c = a ^? ix 10
c' = a ^. ix 10
d = a & ix 1 .~ "Vulkan"
e = a & ix 10 .~ "Romulan"
f = M.fromList [("Katara", "Water"), ("Toph", "Earth"), ("Zuko", "Fire")]
g = f ^? ix "Zuko"
h = f ^? ix "Sokka"
i = ("hello" :: T.Text) ^? ix 0
j = ("hello" :: BS.ByteString) ^? ix 0
k = ("hello" :: BS.ByteString) & ix 0 +~ 2
l = ("hello" :: T.Text) & ix 1 %%~ \_ -> ("aeiou" :: [Char])
m :: Tree Integer
m = Node 1 [Node 2 [Node 4 []], Node 3 [Node 5 [], Node 6 [], Node 7 []]]
Index of first subtree , index of second subtree
n = m ^? ix [1, 2]
o = reverse ^? ix "Stella!"
p = reverse & ix ("password" :: String) .~ "You guessed the magic word!"
q = f ^. at "Zuko"
r = f & at "Zuko" .~ Nothing
s = f & at "Hello" .~ Just "World"
s' = f & at "Hello" ?~ "World"
primes :: S.Set Integer
primes = S.fromList [2, 3, 5, 7, 11, 13]
t = primes ^? ix 5
u = primes ^? ix 4
v = primes & at 14 ?~ ()
Exercises - Indexable Structures
1 . Fill in the blanks
w = ["Larry", "Curly", "Moe"] & ix 1 .~ "Wiggly"
[ " " , " Wiggly " , " " ]
hv = M.fromList [("Superman", "Lex Luther"), ("Batman", "Joker")]
x = hv & at "Spiderman" .~ Just "Goblin"
M.fromList [ ( " Superman " , " " ) , ( " " , " Goblin " ) , ( " Batman " , " Joker " ) ]
y = sans "Superman" hv
M.fromList [ ( " Batman " , " Joker " ) ]
z = S.fromList ['a', 'e', 'i', 'o', 'u'] & at 'y' ?~ () & at 'i' .~ Nothing
S.fromList " aeouy "
2 . Use ` ix ` and ` at ` to go from input to output
input = M.fromList [("candy bars", 13), ("soda", 34), ("gum", 7)]
output = M.fromList [("candy bars", 13), ("ice cream", 5), ("soda", 37)]
a' =
input
& at "gum" .~ Nothing
& at "ice cream" ?~ 5
& at "soda" %~ fmap (+ 3)
newtype Cycled a = Cycled [a] deriving (Show)
type instance Index (Cycled a) = Int
type instance IxValue (Cycled a) = a
instance Ixed (Cycled a) where
ix :: Applicative f => Int -> (a -> f a) -> Cycled a -> f (Cycled a)
ix i handler (Cycled xs) =
Cycled <$> traverseOf (ix (i `mod` length xs)) handler xs
b' = Cycled ['a', 'b', 'c'] & ix (-1) .~ '!'
data Address = Address
{ _buildingNumber :: Maybe String,
_streetName :: Maybe String,
_apartmentNumber :: Maybe String,
_postalCode :: Maybe String
}
deriving (Show)
makeLenses ''Address
data AddressComponent
= BuildingNumber
| StreetName
| ApartmentNumber
| PostalCode
deriving (Show)
type instance Index Address = AddressComponent
type instance IxValue Address = String
instance Ixed Address
instance At Address where
at :: AddressComponent -> Lens' Address (Maybe String)
at BuildingNumber = buildingNumber
at StreetName = streetName
at ApartmentNumber = apartmentNumber
at PostalCode = postalCode
addr = Address Nothing Nothing Nothing Nothing
d' =
addr
& at StreetName ?~ "Baker St."
& at ApartmentNumber ?~ "221B"
Exercises - Custom Indexed Structures
1 . Implement both ` Ixed ` and ` At ` for a newtype wrapper around ` Map `
newtype CIMap a = CIMap (M.Map String a) deriving (Show)
makeLenses ''CIMap
type instance Index (CIMap a) = String
type instance IxValue (CIMap a) = a
instance Ixed (CIMap a) where
ix :: String -> Traversal' (CIMap a) a
ix i handler (CIMap map) =
let lowerMap = M.mapKeys (fmap toLower) map
in CIMap <$> traverseOf (ix (toLower <$> i)) handler lowerMap
f' = CIMap (M.fromList [("HELLO", 0)]) ^? ix "hello"
f_ = CIMap (M.fromList [("hello", 0)]) ^? ix "world"
instance At (CIMap a) where
at :: Functor f => String -> (Maybe a -> f (Maybe a)) -> CIMap a -> f (CIMap a)
at key handler (CIMap map) =
let lowerMap = M.mapKeys (fmap toLower) map
in CIMap <$> (lowerMap & at (toLower <$> key) handler)
g' = CIMap (M.fromList [("HELLO", "derp")]) & at "Hello" ?~ "world"
g_ = g' ^? ix "HELLO"
h' = "abcd" & failover (ix 6) toUpper :: Maybe String
i' = "abcd" & failover (ix 2) toUpper :: Maybe String
j' = "abcd" & failover (ix 2) toUpper :: IO String
k' = M.fromList [('a', 1), ('b', 2)] ^? (ix 'b' `failing` ix 'a')
l' = M.fromList [('a', 1), ('b', 2)] & (ix 'b' `failing` ix 'z') *~ 20
m' = Nothing ^. non 0
n' = Just "value" ^. non "default"
o' = M.fromList [("Garfield", "Lasagna"), ("Leslie", "Waffles")]
p' = o' ^. at "Leslie" . non "Pizza"
equivalent to ` q ' = fromMaybe ' z ' ( " abc " ^ ? ix 10 ) `
q' = ("abc" :: String) ^. pre (ix 10) . non 'z'
r' = [1, 3, 5] ^. pre (traversed . filtered even) . non 2
1 . Write an optic which focuses the value at key " first " or , failing that
the value at key " second "
t' =
let optic = ix "first" `failing` ix "second"
in ( M.fromList [("first", False), ("second", False)] & optic .~ True,
M.fromList [("second", False)] & optic .~ True
)
2 . Write an optic which focuses first element of type if even or second element
u' =
let optic = _1 . filtered even `failing` _2
in ( (1, 1) & optic *~ 10,
(2, 1) & optic *~ 10
)
3 . Optic should focus all even numbers or all numbers when no even present
v' =
let optic = traversed . filtered even `failing` traversed
in ( [1, 2, 3, 4] ^.. optic,
[1, 3, 5] ^.. optic
)
4 . Fill in the blanks ...
w' = Nothing ^. non "default"
x' = Nothing & non 100 +~ 7
Just 107
y' =
M.fromList
[ ("Perogies", True),
("Pizza", True),
("Pilsners", True)
]
^. at "Broccoli" . non False
z' =
M.fromList
[ ("Breath of the wild", 22000000),
("Odyssey", 9070000)
]
& at "Wario's Woods" . non 0
+~ 999
Adds ( " Wario 's Woods",999 ) to Map
a_ = ["Math", "Science", "Geography"] ^. pre (ix 10) . non "Unscheduled"
b_ = [1, 2, 3, 4] ^.. traversed . pre (filtered even) . non (-1)
[ -1 , 2 , -1 , 4 ]
Comment from Twitch , not in book
c_ = [1, 2, 3, 4] & mapped %~ \n -> if even n then n else (-1)
|
cce662aa150a44a18187bb54ad8779c8eba54f6791261deca3ef7315e9d943fc | namin/staged-miniKanren | regexp-tests.scm | (load "staged-mk.scm")
(load "staged-regexp.scm")
(run 6 (q)
(regexp-matcho '(seq foo (rep bar)) q regexp-BLANK))
;; we get some spurious cases
| null | https://raw.githubusercontent.com/namin/staged-miniKanren/f5b665170000720f5d499ab03f31b5c55871ec4f/regexp-tests.scm | scheme | we get some spurious cases | (load "staged-mk.scm")
(load "staged-regexp.scm")
(run 6 (q)
(regexp-matcho '(seq foo (rep bar)) q regexp-BLANK))
|
028a230ae230436080718d24601e3a3543fda1909f452c58168889a774d48c73 | michiakig/sicp | ex-4.04-and-or.scm | ;;;; Structure and Interpretation of Computer Programs
Chapter 4 Section 1 The Metacircular Evaluator
Exercise 4.4
(define (eval-and exp env)
(define (r ops env)
(if (null? (cdr ops)) ; last one
(eval (car ops) env)
(if (eval (car ops) env)
(r (cdr ops) env)
false)))
(r (cdr exp) env))
(define (eval-or exp env)
(define (r ops env)
(if (null? (cdr ops))
(eval (car ops) env)
(let ((val (eval (car ops) env)))
(if val
val
(r (cdr ops) env)))))
(r (cdr exp) env))
| null | https://raw.githubusercontent.com/michiakig/sicp/1aa445f00b7895dbfaa29cf6984b825b4e5af492/ch4/ex-4.04-and-or.scm | scheme | Structure and Interpretation of Computer Programs
last one | Chapter 4 Section 1 The Metacircular Evaluator
Exercise 4.4
(define (eval-and exp env)
(define (r ops env)
(eval (car ops) env)
(if (eval (car ops) env)
(r (cdr ops) env)
false)))
(r (cdr exp) env))
(define (eval-or exp env)
(define (r ops env)
(if (null? (cdr ops))
(eval (car ops) env)
(let ((val (eval (car ops) env)))
(if val
val
(r (cdr ops) env)))))
(r (cdr exp) env))
|
3fbf47aed798120a2c096fe94fb001858cf5939264fcaf58a2c844746a34ca68 | jayrbolton/coursework | Exam2_bolton.hs | -- J Bolton
Haskell exam 2
-- Test cases are at the bottom
module Exam2 where
import Data.List (foldl', foldl1')
import Control.Applicative
data GTree a = Node a [GTree a]
deriving (Show)
( a ) . GTree
instance Functor GTree where
fmap g (Node x []) = Node (g x) []
fmap g (Node x ts) = Node (g x) (map (fmap g) ts)
-- (b). Preorder flatten
flattenGT (Node x []) = [x]
flattenGT (Node x ts) = x : (foldl' (\xs x -> xs++(flattenGT x)) [] ts)
-- (c). Preorder foldr
foldGT f z t = foldr f z (flattenGT t)
foldGT' f z (Node x []) = f x z
foldGT' f z (Node x ((Node y ts):ts')) = f x (foldGT' f z (Node y (ts++ts')))
-- (d). Flatten with fold.
flattenGT' = foldGT (:) []
flattenGT'' = foldGT' (:) []
-- (e).
Proof of functor laws .
( fl1 )
Base case :
Left side :
fmap i d ( Node x [ ] )
= Node ( i d x ) [ ] [ def . of fmap ]
= Node x [ ] [ def . of i d ]
Right side :
i d ( Node x [ ] )
= Node x [ ] [ def . of i d ]
Inductive hypothesis : assume fmap i d = i d for all trees with n nodes or less .
Induction :
Let each t in ts have < = n nodes
Left side :
fmap i d ( Node x ts )
= Node ( i d x ) ( map ( fmap i d ) ts )
[ by the def . of map for lists , fmap i d is applied to each t in ts ,
and by the IH , each fmap i d t is equal to t ]
= Node ( i d x ) ts
= Node x ts
Right side :
i d ( Node x ts )
= Node x ts [ def . of i d ]
( fl2 )
Base case :
Left side :
fmap ( g . h ) ( Node x [ ] )
= Node ( ( g . h ) x ) [ ] [ def . fmap ]
= Node ( g ( h x ) ) [ ] [ def . ( . ) ]
Right side :
( fmap g . fmap h ) ( Node x [ ] )
= ( fmap h ( Node x [ ] ) ) [ def . ( . ) ]
= ( Node ( h x ) [ ] ) [ def . fmap ]
= Node ( g ( h x ) ) [ ] [ def . fmap ]
Inductive hypothesis ( IH ): assume fmap ( g .h ) = . fmap h for all trees
with < = n nodes
Induction :
Let each t in ts have < = n nodes
Left side :
fmap ( g . h ) ( Node x ts )
= Node ( ( g . h ) x ) ( map ( fmap ( g . h ) ) ts ) { def . fmap }
= Node ( ( g . h ) x ) ( map ( fmap g . fmap h ) ts ) { IH }
= Node ( g ( h ( x ) ) ) ( map ( fmap g . fmap h ) ts ) { def . ( . ) }
Right side :
( fmap g . fmap h ) ( Node x ts )
= ( fmap h ( Node x ts ) ) { def . ( . ) }
= ( Node ( h x ) ( map ( fmap h ) ts ) ) { def . fmap }
= Node ( g ( h ( x ) ) ) ( map ( fmap g ) ( map ( fmap h ) ts ) ) { def . fmap }
= Node ( g ( h ( x ) ) ) ( ( map ( fmap g ) . map ( fmap h ) ) ts ) { def . ( . ) }
= Node ( g ( h ( x ) ) ) ( map ( fmap g . fmap h ) ts ) { func law for lists }
Proof of functor laws.
(fl1)
Base case:
Left side:
fmap id (Node x [])
= Node (id x) [] [def. of fmap]
= Node x [] [def. of id]
Right side:
id (Node x [])
= Node x [] [def. of id]
Inductive hypothesis: assume fmap id = id for all trees with n nodes or less.
Induction:
Let each t in ts have <= n nodes
Left side:
fmap id (Node x ts)
= Node (id x) (map (fmap id) ts)
[by the def. of map for lists, fmap id is applied to each t in ts,
and by the IH, each fmap id t is equal to t]
= Node (id x) ts
= Node x ts
Right side:
id (Node x ts)
= Node x ts [def. of id]
(fl2)
Base case:
Left side:
fmap (g . h) (Node x [])
= Node ((g . h) x) [] [def. fmap]
= Node (g (h x)) [] [def. (.)]
Right side:
(fmap g . fmap h) (Node x [])
= fmap g (fmap h (Node x [])) [def. (.)]
= fmap g (Node (h x) []) [def. fmap]
= Node (g (h x)) [] [def. fmap]
Inductive hypothesis (IH): assume fmap (g .h) = fmap g . fmap h for all trees
with <= n nodes
Induction:
Let each t in ts have <= n nodes
Left side:
fmap (g . h) (Node x ts)
= Node ((g . h) x) (map (fmap (g . h)) ts) {def. fmap}
= Node ((g . h) x) (map (fmap g . fmap h) ts) {IH}
= Node (g (h (x))) (map (fmap g . fmap h) ts) {def. (.)}
Right side:
(fmap g . fmap h) (Node x ts)
= fmap g (fmap h (Node x ts)) {def. (.)}
= fmap g (Node (h x) (map (fmap h) ts)) {def. fmap}
= Node (g (h (x))) (map (fmap g) (map (fmap h) ts)) {def. fmap}
= Node (g (h (x))) ((map (fmap g) . map (fmap h)) ts) {def. (.)}
= Node (g (h (x))) (map (fmap g . fmap h) ts) {func law for lists}
-}
2 .
-- (b).
data Expr = Val Int
| BinOp Op Expr Expr
data Op = Mul | Div
evalM :: Expr -> Maybe Int
evalM (Val x) = return x
evalM (BinOp Mul e1 e2) = evalM e1 >>= \v1 ->
evalM e2 >>= \v2 ->
return (v1 * v2)
evalM (BinOp Div e1 e2) = evalM e1 >>= \v1 ->
evalM e2 >>= \v2 ->
v1 `sdiv` v2
sdiv _ 0 = Nothing
sdiv x y = Just (x `div` y)
3 .
itl = \n - > \f - > take n . iterate ( map f )
AST and typing of names Principal Type of AST Node
----------------------- --------------------------
\n : : take n . iterate ( map f )
: : Int - > ( a - > a ) - > [ [ a ] ]
\f : : ( a - > a ) \f - > take n . iterate ( map f )
: : ( a - > a ) - > [ [ a ] ]
( . ) : : ( b - > c ) - > ( a - > b ) - > c taken n . iterate ( map f )
: : [ [ a ] ]
take \ls - > take n ( iterate ( map f ) ls )
: : Int - > [ a ] - > [ a ] : : [ a ] - > [ [ a ] ]
n : : Int n : : Int
iterate iterate ( map f ) : : [ a ] - > [ [ a ] ]
: : ( a - > a ) - > a - > [ a ]
map : : map f : : [ a ] - > [ a ]
( a - > b ) - > [ a ] - > [ b ]
f : : ( a - > a ) f : : ( a - > a )
I assumed that we apply the functions inside the composition , so take becomes
\z - > take n ( iterate ( map f ) z )
= curry ( curry i d )
AST and typing of names Principal Type of AST Node
----------------------- --------------------------
curry : : curry ( curry i d ) : :
( ( a , c ) - > b ) - > a - > c - > b a - > c - > b - > ( ( a , c ) , b )
curry : : curry i d
( ( ( a , c ) , b ) - > ( ( a , ) ) ( a , c ) - > b - > ( ( a , )
- > ( a , c ) - > b - > ( ( a , )
i d : : ( ( a , ) - > ( ( a , c),b ) i d : : ( ( a , ) - > ( ( a , )
It was amazingly difficult to figure out how the types of these functions
unify . I 'm always impressed by all the tricky things can do .
itl = \n -> \f -> take n . iterate (map f)
AST and typing of names Principal Type of AST Node
----------------------- --------------------------
\n :: Int \n -> \f -> take n . iterate (map f)
:: Int -> (a -> a) -> [[a]]
\f :: (a -> a) \f -> take n . iterate (map f)
:: (a -> a) -> [[a]]
(.) :: (b -> c) -> (a -> b) -> c taken n . iterate (map f)
:: [[a]]
take \ls -> take n (iterate (map f) ls)
:: Int -> [a] -> [a] :: [a] -> [[a]]
n :: Int n :: Int
iterate iterate (map f) :: [a] -> [[a]]
:: (a -> a) -> a -> [a]
map :: map f :: [a] -> [a]
(a -> b) -> [a] -> [b]
f :: (a -> a) f :: (a -> a)
I assumed that we apply the functions inside the composition, so take becomes
\z -> take n (iterate (map f) z)
myCurry = curry (curry id)
AST and typing of names Principal Type of AST Node
----------------------- --------------------------
curry :: curry (curry id) ::
((a,c) -> b) -> a -> c -> b a -> c -> b -> ((a, c), b)
curry :: curry id
(((a,c), b) -> ((a,c),b)) (a,c) -> b -> ((a,c),b)
-> (a,c) -> b -> ((a,c),b)
id :: ((a,c),b) -> ((a,c),b) id :: ((a,c),b) -> ((a,c),b)
It was amazingly difficult to figure out how the types of these functions
unify. I'm always impressed by all the tricky things Haskell can do.
-}
4 .
data Error a = Ok a | Error String
deriving (Show)
-- (a).
instance Monad Error where
return x = Ok x
(Error s) >>= _ = Error s
(Ok x) >>= f = f x
-- (b).
evalE :: Expr -> Error Int
evalE (Val x) = return x
evalE (BinOp Mul e1 e2) = evalE e1 >>= \v1 ->
evalE e2 >>= \v2 ->
return (v1 * v2)
evalE (BinOp Div e1 e2) = evalE e1 >>= \v1 ->
evalE e2 >>= \v2 ->
v1 `ediv` v2
ediv _ 0 = Error "Division by zero."
ediv x y = Ok (x `div` y)
-- (c).
instance Functor Error where
fmap _ (Error s) = Error s
fmap g (Ok v) = Ok (g v)
-- (d).
instance Applicative Error where
pure x = Ok x
(Error s1) <*> (Error s2) = Error (s1 ++ " | " ++ s2)
(Error s) <*> _ = Error s
_ <*> (Error s) = Error s
(Ok g) <*> (Ok v) = Ok (g v)
5 .
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
g >=> h = \x -> (g x >>= h)
( ml1 ) ( return > = > g ) = g
return > = > g
= \x - > return x > > = g [ def . > = > ]
= \x - > Ok x > > = g [ def . return ]
= \x - > g x [ def . > > =]
= g
More generally :
return > = > g
= \x - > return x > > = g [ def . > = > ]
= \x - > g x [ 3rd monad law ( TCOP p35 ) ]
= g [ eta rule ]
( ml2 ) ( g > = > return ) = g
To prove this for Error , we have two cases
( case 1 ) g y = Error s
or
( case 2 ) g y = Ok z
( case 1 ) prove : ( g > = > return ) y = g y = Error s
( g > = > return ) y
= ( \p - > g p > > = return ) y [ def . > = > ]
= g y > > = return [ beta rule ]
= Error s > > = return [ assumption ]
= Error s [ def . > > =]
( case 2 ) prove : ( g > = > return ) y = g y = Ok z
( g > = > return ) y
= ( \p - > g p > > = return ) y [ def . > = > ]
= g y > > = return [ beta rule ]
= Ok z > > = return [ assumption ]
= Ok z [ def . > > =]
The general proof from the monad laws :
g > = > return
= \x - > g x > > = return [ def . > = > ]
= \x - > g x [ 2nd monad law ( TCOP p35 ) ]
= g [ eta rule ]
( ml3 ) ( g > = > h ) > = > k = g > = > ( h > = > k )
The general proof from the monad laws :
Left side :
( g > = > h ) > = > k
= ( \x - > g x > > = h ) > = > k [ def . > = > ]
= \y - > ( \x - > g x > > = h ) y > > = k [ def . > = > ]
= \y - > ( g y > > = h ) > > = k [ beta rule ]
Right side :
g > = > ( h > = > k )
= g > = > ( \x - > h x > > = k ) [ def . > = > ]
= \y - > g y > > = ( \x - > h x > > = k ) [ def . > = > ]
= \y - > ( g y > > = h ) > > = k [ third monad law ( TCOP p. 35 ) ]
(ml1) (return >=> g) = g
return >=> g
= \x -> return x >>= g [def. >=>]
= \x -> Ok x >>= g [def. return]
= \x -> g x [def. >>=]
= g
More generally:
return >=> g
= \x -> return x >>= g [def. >=>]
= \x -> g x [3rd monad law (TCOP p35)]
= g [eta rule]
(ml2) (g >=> return) = g
To prove this for Error, we have two cases
(case 1) g y = Error s
or
(case 2) g y = Ok z
(case 1) prove: (g >=> return) y = g y = Error s
(g >=> return) y
= (\p -> g p >>= return) y [def. >=>]
= g y >>= return [beta rule]
= Error s >>= return [assumption]
= Error s [def. >>=]
(case 2) prove: (g >=> return) y = g y = Ok z
(g >=> return) y
= (\p -> g p >>= return) y [def. >=>]
= g y >>= return [beta rule]
= Ok z >>= return [assumption]
= Ok z [def. >>=]
The general proof from the monad laws:
g >=> return
= \x -> g x >>= return [def. >=>]
= \x -> g x [2nd monad law (TCOP p35)]
= g [eta rule]
(ml3) (g >=> h) >=> k = g >=> (h >=> k)
The general proof from the monad laws:
Left side:
(g >=> h) >=> k
= (\x -> g x >>= h) >=> k [def. >=>]
= \y -> (\x -> g x >>= h) y >>= k [def. >=>]
= \y -> (g y >>= h) >>= k [beta rule]
Right side:
g >=> (h >=> k)
= g >=> (\x -> h x >>= k) [def. >=>]
= \y -> g y >>= (\x -> h x >>= k) [def. >=>]
= \y -> (g y >>= h) >>= k [third monad law (TCOP p. 35)]
-}
6 .
-- (a).
iSortCount ls = iSort 0 ls
iSort :: Ord a => Int -> [a] -> (Int, [a])
iSort n [] = (n,[])
iSort n (x:xs) = let (n', xs') = iSort n xs
in ins (n+n') x xs'
ins n x [] = (n,[x])
ins n x (y:ys)
| x <= y = (n+1, x : y : ys)
| otherwise = let (n', ys') = ins (n+1) x ys
in (n', y : ys')
-- (b).
iSortCountM ls = iSortM 0 ls
iSortM n [] = return (n,[])
iSortM n (x:xs) = iSortM n xs >>= \(n',xs') ->
insM (n+n') x xs'
insM n x [] = return (n,[x])
insM n x (y:ys)
| x <= y = return (n+1, x:y:ys)
| otherwise = insM (n+1) x ys >>= \(n',ys') ->
return (n', y:ys')
-- Test cases.
test_tree = Node 1
[Node 2
[Node 4 [],
Node 5 []],
Node 3
[Node 6 [],
Node 7 []]]
test_treesum = foldGT (+) 0 test_tree
test_foldflat = foldGT (:) [] test_tree
test_treesum' = foldGT' (+) 0 test_tree
test_foldflat' = foldGT' (:) [] test_tree
test_folds =
(test_treesum == test_treesum') && (test_foldflat == test_foldflat')
evalM_t0 = evalM (BinOp Div (Val 3) (Val 2))
evalM_t1 = evalM (BinOp Div (Val 3) (Val 0))
evalM_t2 = evalM (BinOp Mul (BinOp Div (Val 4) (Val 2)) (Val 3))
evalM_t3 = evalM (BinOp Mul (BinOp Div (Val 4) (Val 0)) (Val 3))
evalM_t4 = evalM (BinOp Div (Val 12) (BinOp Mul (Val 3) (Val 2)) )
evalM_t5 = evalM (BinOp Div (Val 12) (BinOp Mul (Val 3) (Val 0)) )
evalM_t6 = evalM (BinOp Mul (Val 8) (BinOp Div (Val 2) (Val 0)))
0
0
1
1
6
4
10
| null | https://raw.githubusercontent.com/jayrbolton/coursework/f0da276527d42a6751fb8d29c76de35ce358fe65/computability_and_formal_languages/Haskell/exams/Exam2_bolton.hs | haskell | J Bolton
Test cases are at the bottom
(b). Preorder flatten
(c). Preorder foldr
(d). Flatten with fold.
(e).
(b).
--------------------- --------------------------
--------------------- --------------------------
--------------------- --------------------------
--------------------- --------------------------
(a).
(b).
(c).
(d).
(a).
(b).
Test cases. | Haskell exam 2
module Exam2 where
import Data.List (foldl', foldl1')
import Control.Applicative
data GTree a = Node a [GTree a]
deriving (Show)
( a ) . GTree
instance Functor GTree where
fmap g (Node x []) = Node (g x) []
fmap g (Node x ts) = Node (g x) (map (fmap g) ts)
flattenGT (Node x []) = [x]
flattenGT (Node x ts) = x : (foldl' (\xs x -> xs++(flattenGT x)) [] ts)
foldGT f z t = foldr f z (flattenGT t)
foldGT' f z (Node x []) = f x z
foldGT' f z (Node x ((Node y ts):ts')) = f x (foldGT' f z (Node y (ts++ts')))
flattenGT' = foldGT (:) []
flattenGT'' = foldGT' (:) []
Proof of functor laws .
( fl1 )
Base case :
Left side :
fmap i d ( Node x [ ] )
= Node ( i d x ) [ ] [ def . of fmap ]
= Node x [ ] [ def . of i d ]
Right side :
i d ( Node x [ ] )
= Node x [ ] [ def . of i d ]
Inductive hypothesis : assume fmap i d = i d for all trees with n nodes or less .
Induction :
Let each t in ts have < = n nodes
Left side :
fmap i d ( Node x ts )
= Node ( i d x ) ( map ( fmap i d ) ts )
[ by the def . of map for lists , fmap i d is applied to each t in ts ,
and by the IH , each fmap i d t is equal to t ]
= Node ( i d x ) ts
= Node x ts
Right side :
i d ( Node x ts )
= Node x ts [ def . of i d ]
( fl2 )
Base case :
Left side :
fmap ( g . h ) ( Node x [ ] )
= Node ( ( g . h ) x ) [ ] [ def . fmap ]
= Node ( g ( h x ) ) [ ] [ def . ( . ) ]
Right side :
( fmap g . fmap h ) ( Node x [ ] )
= ( fmap h ( Node x [ ] ) ) [ def . ( . ) ]
= ( Node ( h x ) [ ] ) [ def . fmap ]
= Node ( g ( h x ) ) [ ] [ def . fmap ]
Inductive hypothesis ( IH ): assume fmap ( g .h ) = . fmap h for all trees
with < = n nodes
Induction :
Let each t in ts have < = n nodes
Left side :
fmap ( g . h ) ( Node x ts )
= Node ( ( g . h ) x ) ( map ( fmap ( g . h ) ) ts ) { def . fmap }
= Node ( ( g . h ) x ) ( map ( fmap g . fmap h ) ts ) { IH }
= Node ( g ( h ( x ) ) ) ( map ( fmap g . fmap h ) ts ) { def . ( . ) }
Right side :
( fmap g . fmap h ) ( Node x ts )
= ( fmap h ( Node x ts ) ) { def . ( . ) }
= ( Node ( h x ) ( map ( fmap h ) ts ) ) { def . fmap }
= Node ( g ( h ( x ) ) ) ( map ( fmap g ) ( map ( fmap h ) ts ) ) { def . fmap }
= Node ( g ( h ( x ) ) ) ( ( map ( fmap g ) . map ( fmap h ) ) ts ) { def . ( . ) }
= Node ( g ( h ( x ) ) ) ( map ( fmap g . fmap h ) ts ) { func law for lists }
Proof of functor laws.
(fl1)
Base case:
Left side:
fmap id (Node x [])
= Node (id x) [] [def. of fmap]
= Node x [] [def. of id]
Right side:
id (Node x [])
= Node x [] [def. of id]
Inductive hypothesis: assume fmap id = id for all trees with n nodes or less.
Induction:
Let each t in ts have <= n nodes
Left side:
fmap id (Node x ts)
= Node (id x) (map (fmap id) ts)
[by the def. of map for lists, fmap id is applied to each t in ts,
and by the IH, each fmap id t is equal to t]
= Node (id x) ts
= Node x ts
Right side:
id (Node x ts)
= Node x ts [def. of id]
(fl2)
Base case:
Left side:
fmap (g . h) (Node x [])
= Node ((g . h) x) [] [def. fmap]
= Node (g (h x)) [] [def. (.)]
Right side:
(fmap g . fmap h) (Node x [])
= fmap g (fmap h (Node x [])) [def. (.)]
= fmap g (Node (h x) []) [def. fmap]
= Node (g (h x)) [] [def. fmap]
Inductive hypothesis (IH): assume fmap (g .h) = fmap g . fmap h for all trees
with <= n nodes
Induction:
Let each t in ts have <= n nodes
Left side:
fmap (g . h) (Node x ts)
= Node ((g . h) x) (map (fmap (g . h)) ts) {def. fmap}
= Node ((g . h) x) (map (fmap g . fmap h) ts) {IH}
= Node (g (h (x))) (map (fmap g . fmap h) ts) {def. (.)}
Right side:
(fmap g . fmap h) (Node x ts)
= fmap g (fmap h (Node x ts)) {def. (.)}
= fmap g (Node (h x) (map (fmap h) ts)) {def. fmap}
= Node (g (h (x))) (map (fmap g) (map (fmap h) ts)) {def. fmap}
= Node (g (h (x))) ((map (fmap g) . map (fmap h)) ts) {def. (.)}
= Node (g (h (x))) (map (fmap g . fmap h) ts) {func law for lists}
-}
2 .
data Expr = Val Int
| BinOp Op Expr Expr
data Op = Mul | Div
evalM :: Expr -> Maybe Int
evalM (Val x) = return x
evalM (BinOp Mul e1 e2) = evalM e1 >>= \v1 ->
evalM e2 >>= \v2 ->
return (v1 * v2)
evalM (BinOp Div e1 e2) = evalM e1 >>= \v1 ->
evalM e2 >>= \v2 ->
v1 `sdiv` v2
sdiv _ 0 = Nothing
sdiv x y = Just (x `div` y)
3 .
itl = \n - > \f - > take n . iterate ( map f )
AST and typing of names Principal Type of AST Node
\n : : take n . iterate ( map f )
: : Int - > ( a - > a ) - > [ [ a ] ]
\f : : ( a - > a ) \f - > take n . iterate ( map f )
: : ( a - > a ) - > [ [ a ] ]
( . ) : : ( b - > c ) - > ( a - > b ) - > c taken n . iterate ( map f )
: : [ [ a ] ]
take \ls - > take n ( iterate ( map f ) ls )
: : Int - > [ a ] - > [ a ] : : [ a ] - > [ [ a ] ]
n : : Int n : : Int
iterate iterate ( map f ) : : [ a ] - > [ [ a ] ]
: : ( a - > a ) - > a - > [ a ]
map : : map f : : [ a ] - > [ a ]
( a - > b ) - > [ a ] - > [ b ]
f : : ( a - > a ) f : : ( a - > a )
I assumed that we apply the functions inside the composition , so take becomes
\z - > take n ( iterate ( map f ) z )
= curry ( curry i d )
AST and typing of names Principal Type of AST Node
curry : : curry ( curry i d ) : :
( ( a , c ) - > b ) - > a - > c - > b a - > c - > b - > ( ( a , c ) , b )
curry : : curry i d
( ( ( a , c ) , b ) - > ( ( a , ) ) ( a , c ) - > b - > ( ( a , )
- > ( a , c ) - > b - > ( ( a , )
i d : : ( ( a , ) - > ( ( a , c),b ) i d : : ( ( a , ) - > ( ( a , )
It was amazingly difficult to figure out how the types of these functions
unify . I 'm always impressed by all the tricky things can do .
itl = \n -> \f -> take n . iterate (map f)
AST and typing of names Principal Type of AST Node
\n :: Int \n -> \f -> take n . iterate (map f)
:: Int -> (a -> a) -> [[a]]
\f :: (a -> a) \f -> take n . iterate (map f)
:: (a -> a) -> [[a]]
(.) :: (b -> c) -> (a -> b) -> c taken n . iterate (map f)
:: [[a]]
take \ls -> take n (iterate (map f) ls)
:: Int -> [a] -> [a] :: [a] -> [[a]]
n :: Int n :: Int
iterate iterate (map f) :: [a] -> [[a]]
:: (a -> a) -> a -> [a]
map :: map f :: [a] -> [a]
(a -> b) -> [a] -> [b]
f :: (a -> a) f :: (a -> a)
I assumed that we apply the functions inside the composition, so take becomes
\z -> take n (iterate (map f) z)
myCurry = curry (curry id)
AST and typing of names Principal Type of AST Node
curry :: curry (curry id) ::
((a,c) -> b) -> a -> c -> b a -> c -> b -> ((a, c), b)
curry :: curry id
(((a,c), b) -> ((a,c),b)) (a,c) -> b -> ((a,c),b)
-> (a,c) -> b -> ((a,c),b)
id :: ((a,c),b) -> ((a,c),b) id :: ((a,c),b) -> ((a,c),b)
It was amazingly difficult to figure out how the types of these functions
unify. I'm always impressed by all the tricky things Haskell can do.
-}
4 .
data Error a = Ok a | Error String
deriving (Show)
instance Monad Error where
return x = Ok x
(Error s) >>= _ = Error s
(Ok x) >>= f = f x
evalE :: Expr -> Error Int
evalE (Val x) = return x
evalE (BinOp Mul e1 e2) = evalE e1 >>= \v1 ->
evalE e2 >>= \v2 ->
return (v1 * v2)
evalE (BinOp Div e1 e2) = evalE e1 >>= \v1 ->
evalE e2 >>= \v2 ->
v1 `ediv` v2
ediv _ 0 = Error "Division by zero."
ediv x y = Ok (x `div` y)
instance Functor Error where
fmap _ (Error s) = Error s
fmap g (Ok v) = Ok (g v)
instance Applicative Error where
pure x = Ok x
(Error s1) <*> (Error s2) = Error (s1 ++ " | " ++ s2)
(Error s) <*> _ = Error s
_ <*> (Error s) = Error s
(Ok g) <*> (Ok v) = Ok (g v)
5 .
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
g >=> h = \x -> (g x >>= h)
( ml1 ) ( return > = > g ) = g
return > = > g
= \x - > return x > > = g [ def . > = > ]
= \x - > Ok x > > = g [ def . return ]
= \x - > g x [ def . > > =]
= g
More generally :
return > = > g
= \x - > return x > > = g [ def . > = > ]
= \x - > g x [ 3rd monad law ( TCOP p35 ) ]
= g [ eta rule ]
( ml2 ) ( g > = > return ) = g
To prove this for Error , we have two cases
( case 1 ) g y = Error s
or
( case 2 ) g y = Ok z
( case 1 ) prove : ( g > = > return ) y = g y = Error s
( g > = > return ) y
= ( \p - > g p > > = return ) y [ def . > = > ]
= g y > > = return [ beta rule ]
= Error s > > = return [ assumption ]
= Error s [ def . > > =]
( case 2 ) prove : ( g > = > return ) y = g y = Ok z
( g > = > return ) y
= ( \p - > g p > > = return ) y [ def . > = > ]
= g y > > = return [ beta rule ]
= Ok z > > = return [ assumption ]
= Ok z [ def . > > =]
The general proof from the monad laws :
g > = > return
= \x - > g x > > = return [ def . > = > ]
= \x - > g x [ 2nd monad law ( TCOP p35 ) ]
= g [ eta rule ]
( ml3 ) ( g > = > h ) > = > k = g > = > ( h > = > k )
The general proof from the monad laws :
Left side :
( g > = > h ) > = > k
= ( \x - > g x > > = h ) > = > k [ def . > = > ]
= \y - > ( \x - > g x > > = h ) y > > = k [ def . > = > ]
= \y - > ( g y > > = h ) > > = k [ beta rule ]
Right side :
g > = > ( h > = > k )
= g > = > ( \x - > h x > > = k ) [ def . > = > ]
= \y - > g y > > = ( \x - > h x > > = k ) [ def . > = > ]
= \y - > ( g y > > = h ) > > = k [ third monad law ( TCOP p. 35 ) ]
(ml1) (return >=> g) = g
return >=> g
= \x -> return x >>= g [def. >=>]
= \x -> Ok x >>= g [def. return]
= \x -> g x [def. >>=]
= g
More generally:
return >=> g
= \x -> return x >>= g [def. >=>]
= \x -> g x [3rd monad law (TCOP p35)]
= g [eta rule]
(ml2) (g >=> return) = g
To prove this for Error, we have two cases
(case 1) g y = Error s
or
(case 2) g y = Ok z
(case 1) prove: (g >=> return) y = g y = Error s
(g >=> return) y
= (\p -> g p >>= return) y [def. >=>]
= g y >>= return [beta rule]
= Error s >>= return [assumption]
= Error s [def. >>=]
(case 2) prove: (g >=> return) y = g y = Ok z
(g >=> return) y
= (\p -> g p >>= return) y [def. >=>]
= g y >>= return [beta rule]
= Ok z >>= return [assumption]
= Ok z [def. >>=]
The general proof from the monad laws:
g >=> return
= \x -> g x >>= return [def. >=>]
= \x -> g x [2nd monad law (TCOP p35)]
= g [eta rule]
(ml3) (g >=> h) >=> k = g >=> (h >=> k)
The general proof from the monad laws:
Left side:
(g >=> h) >=> k
= (\x -> g x >>= h) >=> k [def. >=>]
= \y -> (\x -> g x >>= h) y >>= k [def. >=>]
= \y -> (g y >>= h) >>= k [beta rule]
Right side:
g >=> (h >=> k)
= g >=> (\x -> h x >>= k) [def. >=>]
= \y -> g y >>= (\x -> h x >>= k) [def. >=>]
= \y -> (g y >>= h) >>= k [third monad law (TCOP p. 35)]
-}
6 .
iSortCount ls = iSort 0 ls
iSort :: Ord a => Int -> [a] -> (Int, [a])
iSort n [] = (n,[])
iSort n (x:xs) = let (n', xs') = iSort n xs
in ins (n+n') x xs'
ins n x [] = (n,[x])
ins n x (y:ys)
| x <= y = (n+1, x : y : ys)
| otherwise = let (n', ys') = ins (n+1) x ys
in (n', y : ys')
iSortCountM ls = iSortM 0 ls
iSortM n [] = return (n,[])
iSortM n (x:xs) = iSortM n xs >>= \(n',xs') ->
insM (n+n') x xs'
insM n x [] = return (n,[x])
insM n x (y:ys)
| x <= y = return (n+1, x:y:ys)
| otherwise = insM (n+1) x ys >>= \(n',ys') ->
return (n', y:ys')
test_tree = Node 1
[Node 2
[Node 4 [],
Node 5 []],
Node 3
[Node 6 [],
Node 7 []]]
test_treesum = foldGT (+) 0 test_tree
test_foldflat = foldGT (:) [] test_tree
test_treesum' = foldGT' (+) 0 test_tree
test_foldflat' = foldGT' (:) [] test_tree
test_folds =
(test_treesum == test_treesum') && (test_foldflat == test_foldflat')
evalM_t0 = evalM (BinOp Div (Val 3) (Val 2))
evalM_t1 = evalM (BinOp Div (Val 3) (Val 0))
evalM_t2 = evalM (BinOp Mul (BinOp Div (Val 4) (Val 2)) (Val 3))
evalM_t3 = evalM (BinOp Mul (BinOp Div (Val 4) (Val 0)) (Val 3))
evalM_t4 = evalM (BinOp Div (Val 12) (BinOp Mul (Val 3) (Val 2)) )
evalM_t5 = evalM (BinOp Div (Val 12) (BinOp Mul (Val 3) (Val 0)) )
evalM_t6 = evalM (BinOp Mul (Val 8) (BinOp Div (Val 2) (Val 0)))
0
0
1
1
6
4
10
|
d8cbe07060ea3845c2d94690fbc574f2e5888c8fb3b6c2eb4295c58408d5b9b4 | tweag/asterius | T11172.hs | # LANGUAGE UnboxedTuples #
# OPTIONS_GHC -fno - warn - incomplete - patterns #
module Main where
data JSONState = JSONState [()] () () deriving Show
weta_s6yD :: Either a (b, c) -> (# (Either a b, JSONState) #)
weta_s6yD ww_s6ys = case ww_s6ys of
Left l -> (# (Left l, JSONState [] () ()) #)
Right (x, _) -> (# (Right x, JSONState [] () ()) #)
eta_B1 :: (Either a (b, c), t) -> Either a1 (Either a b, JSONState)
eta_B1 (ww_s6ys, _) = case weta_s6yD ww_s6ys of
(# ww_s6zb #) -> Right ww_s6zb
wks_s6yS :: Either a b -> (# (Either a b, JSONState) #)
wks_s6yS ww_s6yH =
case case ww_s6yH of
Left l_a4ay -> eta_B1 (Left l_a4ay, ())
Right r_a4aB -> eta_B1 (Right (r_a4aB, ()), ())
of
Right ww_s6ze -> (# ww_s6ze #)
ks_a49u :: (Either a b, t) -> Either a1 (Either a b, JSONState)
ks_a49u (ww_s6yH, _) = case wks_s6yS ww_s6yH of
(# ww_s6ze #) -> Right ww_s6ze
wks_s6z7 :: Either a b -> (# (Either a b, JSONState) #)
wks_s6z7 ww_s6yW = case (
case ww_s6yW of
Left _ -> ks_a49u (ww_s6yW, JSONState [()] () ())
Right _ -> ks_a49u (ww_s6yW, JSONState [] () ())
) of
Right ww_s6zh -> (# ww_s6zh #)
ks_X3Sb :: Either () Int -> Either String (Either () Int, JSONState)
ks_X3Sb ww_s6yW = case wks_s6z7 ww_s6yW of
(# ww_s6zh #) -> Right ww_s6zh
main :: IO ()
main = print $ ks_X3Sb (Left ())
| null | https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/simplCore/T11172.hs | haskell | # LANGUAGE UnboxedTuples #
# OPTIONS_GHC -fno - warn - incomplete - patterns #
module Main where
data JSONState = JSONState [()] () () deriving Show
weta_s6yD :: Either a (b, c) -> (# (Either a b, JSONState) #)
weta_s6yD ww_s6ys = case ww_s6ys of
Left l -> (# (Left l, JSONState [] () ()) #)
Right (x, _) -> (# (Right x, JSONState [] () ()) #)
eta_B1 :: (Either a (b, c), t) -> Either a1 (Either a b, JSONState)
eta_B1 (ww_s6ys, _) = case weta_s6yD ww_s6ys of
(# ww_s6zb #) -> Right ww_s6zb
wks_s6yS :: Either a b -> (# (Either a b, JSONState) #)
wks_s6yS ww_s6yH =
case case ww_s6yH of
Left l_a4ay -> eta_B1 (Left l_a4ay, ())
Right r_a4aB -> eta_B1 (Right (r_a4aB, ()), ())
of
Right ww_s6ze -> (# ww_s6ze #)
ks_a49u :: (Either a b, t) -> Either a1 (Either a b, JSONState)
ks_a49u (ww_s6yH, _) = case wks_s6yS ww_s6yH of
(# ww_s6ze #) -> Right ww_s6ze
wks_s6z7 :: Either a b -> (# (Either a b, JSONState) #)
wks_s6z7 ww_s6yW = case (
case ww_s6yW of
Left _ -> ks_a49u (ww_s6yW, JSONState [()] () ())
Right _ -> ks_a49u (ww_s6yW, JSONState [] () ())
) of
Right ww_s6zh -> (# ww_s6zh #)
ks_X3Sb :: Either () Int -> Either String (Either () Int, JSONState)
ks_X3Sb ww_s6yW = case wks_s6z7 ww_s6yW of
(# ww_s6zh #) -> Right ww_s6zh
main :: IO ()
main = print $ ks_X3Sb (Left ())
| |
bf6e2ac76b877517766740f48d66f8a1f7ec10c69a7368fe0772e506f1017552 | JeffreyBenjaminBrown/digraphs-with-text | Insert.hs | -- | Sample use:
Dwt.prettyPrint $ fr $ parse expr " " " a # b # # z # ( d # e ) # e # # f # # g # h "
let Right ( _ , ) = runStateT ( mapM ( addExpr . fr . parse expr " " ) [ " a # b " , " # c " , " # # d # " ] ) empty
module Dwt.Hash.Insert (prettyPrint, addExpr) where
import Data.Graph.Inductive hiding (empty, prettyPrint)
import Dwt.Initial.Types
import Dwt.Query.Main
import Dwt.Initial.Measure (isAbsent)
import Dwt.Initial.Util (gelemM)
import Control.Monad.Trans.State
import Control.Monad.Trans.Class (lift)
-- | (At n) represents something already extant in the graph.
-- Leaf and QRel represent something that *might* already exist; it will
-- be searched for. If found, it becomes an At; if not, it is created, and
-- becomes an At.
prettyPrint :: QNode -> IO ()
prettyPrint = it 0 where
space :: Int -> String
space k = replicate (4*k) ' '
it :: Level -> QNode -> IO ()
it indent (QRel _ js (m:ms)) = do
putStrLn $ space indent ++ "QNode: "
it (indent+1) m
let f (j,m) = do putStrLn $ (space $ indent+1) ++ show j
it (indent+1) m
mapM_ f $ zip js ms
it indent l = putStrLn $ space indent ++ show l
addExpr :: QNode -> StateT RSLT (Either DwtErr) Node
addExpr (At n) = get >>= lift . flip gelemM n >> return n
addExpr (QLeaf e) = qPutSt $ QLeaf e
addExpr (QRel isTop js as) = do
ns <- mapM addExpr $ filter (not . isAbsent) as
qPutSt $ QRel isTop js $ reshuffle ns as
where reshuffle :: [Node] -> [QNode] -> [QNode]
reshuffle [] ms = ms
reshuffle ns (Absent:is) = Absent : reshuffle ns is
reshuffle (n:ns) (_:is) = At n : reshuffle ns is
-- ns is shorter or equal, so the case reshuffle _ [] is unnecessary
addExpr q = lift $ Left (Impossible, [ErrQNode q], "addExpr.")
| null | https://raw.githubusercontent.com/JeffreyBenjaminBrown/digraphs-with-text/34e47a52aa9abb6fd42028deba1623a92e278aae/src/Dwt/Hash/Insert.hs | haskell | | Sample use:
| (At n) represents something already extant in the graph.
Leaf and QRel represent something that *might* already exist; it will
be searched for. If found, it becomes an At; if not, it is created, and
becomes an At.
ns is shorter or equal, so the case reshuffle _ [] is unnecessary | Dwt.prettyPrint $ fr $ parse expr " " " a # b # # z # ( d # e ) # e # # f # # g # h "
let Right ( _ , ) = runStateT ( mapM ( addExpr . fr . parse expr " " ) [ " a # b " , " # c " , " # # d # " ] ) empty
module Dwt.Hash.Insert (prettyPrint, addExpr) where
import Data.Graph.Inductive hiding (empty, prettyPrint)
import Dwt.Initial.Types
import Dwt.Query.Main
import Dwt.Initial.Measure (isAbsent)
import Dwt.Initial.Util (gelemM)
import Control.Monad.Trans.State
import Control.Monad.Trans.Class (lift)
prettyPrint :: QNode -> IO ()
prettyPrint = it 0 where
space :: Int -> String
space k = replicate (4*k) ' '
it :: Level -> QNode -> IO ()
it indent (QRel _ js (m:ms)) = do
putStrLn $ space indent ++ "QNode: "
it (indent+1) m
let f (j,m) = do putStrLn $ (space $ indent+1) ++ show j
it (indent+1) m
mapM_ f $ zip js ms
it indent l = putStrLn $ space indent ++ show l
addExpr :: QNode -> StateT RSLT (Either DwtErr) Node
addExpr (At n) = get >>= lift . flip gelemM n >> return n
addExpr (QLeaf e) = qPutSt $ QLeaf e
addExpr (QRel isTop js as) = do
ns <- mapM addExpr $ filter (not . isAbsent) as
qPutSt $ QRel isTop js $ reshuffle ns as
where reshuffle :: [Node] -> [QNode] -> [QNode]
reshuffle [] ms = ms
reshuffle ns (Absent:is) = Absent : reshuffle ns is
reshuffle (n:ns) (_:is) = At n : reshuffle ns is
addExpr q = lift $ Left (Impossible, [ErrQNode q], "addExpr.")
|
a7080064a06cd398c7a6fee64384d40f538fc358b95cff4100976b224418bc24 | derekchiang/Erlang-Web-Crawler | mochiweb_html.erl | @author < >
2007 Mochi Media , Inc.
@doc Loosely tokenizes and generates parse trees for HTML 4 .
-module(mochiweb_html).
-export([tokens/1, parse/1, parse_tokens/1, to_tokens/1, escape/1,
escape_attr/1, to_html/1]).
%% This is a macro to placate syntax highlighters..
-define(QUOTE, $\").
-define(SQUOTE, $\').
-define(ADV_COL(S, N),
S#decoder{column=N+S#decoder.column,
offset=N+S#decoder.offset}).
-define(INC_COL(S),
S#decoder{column=1+S#decoder.column,
offset=1+S#decoder.offset}).
-define(INC_LINE(S),
S#decoder{column=1,
line=1+S#decoder.line,
offset=1+S#decoder.offset}).
-define(INC_CHAR(S, C),
case C of
$\n ->
S#decoder{column=1,
line=1+S#decoder.line,
offset=1+S#decoder.offset};
_ ->
S#decoder{column=1+S#decoder.column,
offset=1+S#decoder.offset}
end).
-define(IS_WHITESPACE(C),
(C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
-define(IS_LITERAL_SAFE(C),
((C >= $A andalso C =< $Z) orelse (C >= $a andalso C =< $z)
orelse (C >= $0 andalso C =< $9))).
-define(PROBABLE_CLOSE(C),
(C =:= $> orelse ?IS_WHITESPACE(C))).
-record(decoder, {line=1,
column=1,
offset=0}).
%% @type html_node() = {string(), [html_attr()], [html_node() | string()]}
%% @type html_attr() = {string(), string()}
%% @type html_token() = html_data() | start_tag() | end_tag() | inline_html() | html_comment() | html_doctype()
%% @type html_data() = {data, string(), Whitespace::boolean()}
@type start_tag ( ) = { start_tag , Name , [ html_attr ( ) ] , ( ) }
%% @type end_tag() = {end_tag, Name}
%% @type html_comment() = {comment, Comment}
@type html_doctype ( ) = { doctype , [ Doctype ] }
@type inline_html ( ) = { ' = ' , ( ) }
%% External API.
@spec parse(string ( ) | binary ( ) ) - > html_node ( )
%% @doc tokenize and then transform the token stream into a HTML tree.
parse(Input) ->
parse_tokens(tokens(Input)).
@spec parse_tokens([html_token ( ) ] ) - > html_node ( )
%% @doc Transform the output of tokens(Doc) into a HTML tree.
parse_tokens(Tokens) when is_list(Tokens) ->
%% Skip over doctype, processing instructions
F = fun (X) ->
case X of
{start_tag, _, _, false} ->
false;
_ ->
true
end
end,
[{start_tag, Tag, Attrs, false} | Rest] = lists:dropwhile(F, Tokens),
{Tree, _} = tree(Rest, [norm({Tag, Attrs})]),
Tree.
) - > [ html_token ( ) ]
@doc Transform the input UTF-8 HTML into a token stream .
tokens(Input) ->
tokens(iolist_to_binary(Input), #decoder{}, []).
to_tokens(html_node ( ) ) - > [ html_token ( ) ]
%% @doc Convert a html_node() tree to a list of tokens.
to_tokens({Tag0}) ->
to_tokens({Tag0, [], []});
to_tokens(T={'=', _}) ->
[T];
to_tokens(T={doctype, _}) ->
[T];
to_tokens(T={comment, _}) ->
[T];
to_tokens({Tag0, Acc}) ->
%% This is only allowed in sub-tags: {p, [{"class", "foo"}]}
to_tokens({Tag0, [], Acc});
to_tokens({Tag0, Attrs, Acc}) ->
Tag = to_tag(Tag0),
case is_singleton(Tag) of
true ->
to_tokens([], [{start_tag, Tag, Attrs, true}]);
false ->
to_tokens([{Tag, Acc}], [{start_tag, Tag, Attrs, false}])
end.
( ) ] | html_node ( ) ) - > iolist ( )
@doc Convert a list of html_token ( ) to a HTML document .
to_html(Node) when is_tuple(Node) ->
to_html(to_tokens(Node));
to_html(Tokens) when is_list(Tokens) ->
to_html(Tokens, []).
escape(string ( ) | atom ( ) | binary ( ) ) - > binary ( )
%% @doc Escape a string such that it's safe for HTML (amp; lt; gt;).
escape(B) when is_binary(B) ->
escape(binary_to_list(B), []);
escape(A) when is_atom(A) ->
escape(atom_to_list(A), []);
escape(S) when is_list(S) ->
escape(S, []).
escape_attr(string ( ) | binary ( ) | atom ( ) | integer ( ) | float ( ) ) - > binary ( )
@doc Escape a string such that it 's safe for HTML attrs
%% (amp; lt; gt; quot;).
escape_attr(B) when is_binary(B) ->
escape_attr(binary_to_list(B), []);
escape_attr(A) when is_atom(A) ->
escape_attr(atom_to_list(A), []);
escape_attr(S) when is_list(S) ->
escape_attr(S, []);
escape_attr(I) when is_integer(I) ->
escape_attr(integer_to_list(I), []);
escape_attr(F) when is_float(F) ->
escape_attr(mochinum:digits(F), []).
to_html([], Acc) ->
lists:reverse(Acc);
to_html([{'=', Content} | Rest], Acc) ->
to_html(Rest, [Content | Acc]);
to_html([{pi, Bin} | Rest], Acc) ->
Open = [<<"<?">>,
Bin,
<<"?>">>],
to_html(Rest, [Open | Acc]);
to_html([{pi, Tag, Attrs} | Rest], Acc) ->
Open = [<<"<?">>,
Tag,
attrs_to_html(Attrs, []),
<<"?>">>],
to_html(Rest, [Open | Acc]);
to_html([{comment, Comment} | Rest], Acc) ->
to_html(Rest, [[<<"<!--">>, Comment, <<"-->">>] | Acc]);
to_html([{doctype, Parts} | Rest], Acc) ->
Inside = doctype_to_html(Parts, Acc),
to_html(Rest, [[<<"<!DOCTYPE">>, Inside, <<">">>] | Acc]);
to_html([{data, Data, _Whitespace} | Rest], Acc) ->
to_html(Rest, [escape(Data) | Acc]);
to_html([{start_tag, Tag, Attrs, Singleton} | Rest], Acc) ->
Open = [<<"<">>,
Tag,
attrs_to_html(Attrs, []),
case Singleton of
true -> <<" />">>;
false -> <<">">>
end],
to_html(Rest, [Open | Acc]);
to_html([{end_tag, Tag} | Rest], Acc) ->
to_html(Rest, [[<<"</">>, Tag, <<">">>] | Acc]).
doctype_to_html([], Acc) ->
lists:reverse(Acc);
doctype_to_html([Word | Rest], Acc) ->
case lists:all(fun (C) -> ?IS_LITERAL_SAFE(C) end,
binary_to_list(iolist_to_binary(Word))) of
true ->
doctype_to_html(Rest, [[<<" ">>, Word] | Acc]);
false ->
doctype_to_html(Rest, [[<<" \"">>, escape_attr(Word), ?QUOTE] | Acc])
end.
attrs_to_html([], Acc) ->
lists:reverse(Acc);
attrs_to_html([{K, V} | Rest], Acc) ->
attrs_to_html(Rest,
[[<<" ">>, escape(K), <<"=\"">>,
escape_attr(V), <<"\"">>] | Acc]).
escape([], Acc) ->
list_to_binary(lists:reverse(Acc));
escape("<" ++ Rest, Acc) ->
escape(Rest, lists:reverse("<", Acc));
escape(">" ++ Rest, Acc) ->
escape(Rest, lists:reverse(">", Acc));
escape("&" ++ Rest, Acc) ->
escape(Rest, lists:reverse("&", Acc));
escape([C | Rest], Acc) ->
escape(Rest, [C | Acc]).
escape_attr([], Acc) ->
list_to_binary(lists:reverse(Acc));
escape_attr("<" ++ Rest, Acc) ->
escape_attr(Rest, lists:reverse("<", Acc));
escape_attr(">" ++ Rest, Acc) ->
escape_attr(Rest, lists:reverse(">", Acc));
escape_attr("&" ++ Rest, Acc) ->
escape_attr(Rest, lists:reverse("&", Acc));
escape_attr([?QUOTE | Rest], Acc) ->
escape_attr(Rest, lists:reverse(""", Acc));
escape_attr([C | Rest], Acc) ->
escape_attr(Rest, [C | Acc]).
to_tag(A) when is_atom(A) ->
norm(atom_to_list(A));
to_tag(L) ->
norm(L).
to_tokens([], Acc) ->
lists:reverse(Acc);
to_tokens([{Tag, []} | Rest], Acc) ->
to_tokens(Rest, [{end_tag, to_tag(Tag)} | Acc]);
to_tokens([{Tag0, [{T0} | R1]} | Rest], Acc) ->
%% Allow {br}
to_tokens([{Tag0, [{T0, [], []} | R1]} | Rest], Acc);
to_tokens([{Tag0, [T0={'=', _C0} | R1]} | Rest], Acc) ->
Allow { ' = ' , ( ) }
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [T0={comment, _C0} | R1]} | Rest], Acc) ->
Allow { comment , ( ) }
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [T0={pi, _S0} | R1]} | Rest], Acc) ->
%% Allow {pi, binary()}
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [T0={pi, _S0, _A0} | R1]} | Rest], Acc) ->
%% Allow {pi, binary(), list()}
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [{T0, A0=[{_, _} | _]} | R1]} | Rest], Acc) ->
%% Allow {p, [{"class", "foo"}]}
to_tokens([{Tag0, [{T0, A0, []} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, C0} | R1]} | Rest], Acc) ->
%% Allow {p, "content"} and {p, <<"content">>}
to_tokens([{Tag0, [{T0, [], C0} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, A1, C0} | R1]} | Rest], Acc) when is_binary(C0) ->
%% Allow {"p", [{"class", "foo"}], <<"content">>}
to_tokens([{Tag0, [{T0, A1, binary_to_list(C0)} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, A1, C0=[C | _]} | R1]} | Rest], Acc)
when is_integer(C) ->
%% Allow {"p", [{"class", "foo"}], "content"}
to_tokens([{Tag0, [{T0, A1, [C0]} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, A1, C1} | R1]} | Rest], Acc) ->
Native { " p " , [ { " class " , " foo " } ] , [ " content " ] }
Tag = to_tag(Tag0),
T1 = to_tag(T0),
case is_singleton(norm(T1)) of
true ->
to_tokens([{Tag, R1} | Rest], [{start_tag, T1, A1, true} | Acc]);
false ->
to_tokens([{T1, C1}, {Tag, R1} | Rest],
[{start_tag, T1, A1, false} | Acc])
end;
to_tokens([{Tag0, [L | R1]} | Rest], Acc) when is_list(L) ->
%% List text
Tag = to_tag(Tag0),
to_tokens([{Tag, R1} | Rest], [{data, iolist_to_binary(L), false} | Acc]);
to_tokens([{Tag0, [B | R1]} | Rest], Acc) when is_binary(B) ->
%% Binary text
Tag = to_tag(Tag0),
to_tokens([{Tag, R1} | Rest], [{data, B, false} | Acc]).
tokens(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary>> ->
lists:reverse(Acc);
_ ->
{Tag, S1} = tokenize(B, S),
case parse_flag(Tag) of
script ->
{Tag2, S2} = tokenize_script(B, S1),
tokens(B, S2, [Tag2, Tag | Acc]);
textarea ->
{Tag2, S2} = tokenize_textarea(B, S1),
tokens(B, S2, [Tag2, Tag | Acc]);
none ->
tokens(B, S1, [Tag | Acc])
end
end.
parse_flag({start_tag, B, _, false}) ->
case string:to_lower(binary_to_list(B)) of
"script" ->
script;
"textarea" ->
textarea;
_ ->
none
end;
parse_flag(_) ->
none.
tokenize(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary, "<!--", _/binary>> ->
tokenize_comment(B, ?ADV_COL(S, 4));
<<_:O/binary, "<!DOCTYPE", _/binary>> ->
tokenize_doctype(B, ?ADV_COL(S, 10));
<<_:O/binary, "<![CDATA[", _/binary>> ->
tokenize_cdata(B, ?ADV_COL(S, 9));
<<_:O/binary, "<?php", _/binary>> ->
{Body, S1} = raw_qgt(B, ?ADV_COL(S, 2)),
{{pi, Body}, S1};
<<_:O/binary, "<?", _/binary>> ->
{Tag, S1} = tokenize_literal(B, ?ADV_COL(S, 2)),
{Attrs, S2} = tokenize_attributes(B, S1),
S3 = find_qgt(B, S2),
{{pi, Tag, Attrs}, S3};
<<_:O/binary, "&", _/binary>> ->
tokenize_charref(B, ?INC_COL(S));
<<_:O/binary, "</", _/binary>> ->
{Tag, S1} = tokenize_literal(B, ?ADV_COL(S, 2)),
{S2, _} = find_gt(B, S1),
{{end_tag, Tag}, S2};
<<_:O/binary, "<", C, _/binary>>
when ?IS_WHITESPACE(C); not ?IS_LITERAL_SAFE(C) ->
%% This isn't really strict HTML
{{data, Data, _Whitespace}, S1} = tokenize_data(B, ?INC_COL(S)),
{{data, <<$<, Data/binary>>, false}, S1};
<<_:O/binary, "<", _/binary>> ->
{Tag, S1} = tokenize_literal(B, ?INC_COL(S)),
{Attrs, S2} = tokenize_attributes(B, S1),
{S3, HasSlash} = find_gt(B, S2),
Singleton = HasSlash orelse is_singleton(Tag),
{{start_tag, Tag, Attrs, Singleton}, S3};
_ ->
tokenize_data(B, S)
end.
tree_data([{data, Data, Whitespace} | Rest], AllWhitespace, Acc) ->
tree_data(Rest, (Whitespace andalso AllWhitespace), [Data | Acc]);
tree_data(Rest, AllWhitespace, Acc) ->
{iolist_to_binary(lists:reverse(Acc)), AllWhitespace, Rest}.
tree([], Stack) ->
{destack(Stack), []};
tree([{end_tag, Tag} | Rest], Stack) ->
case destack(norm(Tag), Stack) of
S when is_list(S) ->
tree(Rest, S);
Result ->
{Result, []}
end;
tree([{start_tag, Tag, Attrs, true} | Rest], S) ->
tree(Rest, append_stack_child(norm({Tag, Attrs}), S));
tree([{start_tag, Tag, Attrs, false} | Rest], S) ->
tree(Rest, stack(norm({Tag, Attrs}), S));
tree([T={pi, _Raw} | Rest], S) ->
tree(Rest, append_stack_child(T, S));
tree([T={pi, _Tag, _Attrs} | Rest], S) ->
tree(Rest, append_stack_child(T, S));
tree([T={comment, _Comment} | Rest], S) ->
tree(Rest, append_stack_child(T, S));
tree(L=[{data, _Data, _Whitespace} | _], S) ->
case tree_data(L, true, []) of
{_, true, Rest} ->
tree(Rest, S);
{Data, false, Rest} ->
tree(Rest, append_stack_child(Data, S))
end;
tree([{doctype, _} | Rest], Stack) ->
tree(Rest, Stack).
norm({Tag, Attrs}) ->
{norm(Tag), [{norm(K), iolist_to_binary(V)} || {K, V} <- Attrs], []};
norm(Tag) when is_binary(Tag) ->
Tag;
norm(Tag) ->
list_to_binary(string:to_lower(Tag)).
stack(T1={TN, _, _}, Stack=[{TN, _, _} | _Rest])
when TN =:= <<"li">> orelse TN =:= <<"option">> ->
[T1 | destack(TN, Stack)];
stack(T1={TN0, _, _}, Stack=[{TN1, _, _} | _Rest])
when (TN0 =:= <<"dd">> orelse TN0 =:= <<"dt">>) andalso
(TN1 =:= <<"dd">> orelse TN1 =:= <<"dt">>) ->
[T1 | destack(TN1, Stack)];
stack(T1, Stack) ->
[T1 | Stack].
append_stack_child(StartTag, [{Name, Attrs, Acc} | Stack]) ->
[{Name, Attrs, [StartTag | Acc]} | Stack].
destack(<<"br">>, Stack) ->
%% This is an ugly hack to make dumb_br_test() pass,
%% this makes it such that br can never have children.
Stack;
destack(TagName, Stack) when is_list(Stack) ->
F = fun (X) ->
case X of
{TagName, _, _} ->
false;
_ ->
true
end
end,
case lists:splitwith(F, Stack) of
{_, []} ->
%% If we're parsing something like XML we might find
%% a <link>tag</link> that is normally a singleton
%% in HTML but isn't here
case {is_singleton(TagName), Stack} of
{true, [{T0, A0, Acc0} | Post0]} ->
case lists:splitwith(F, Acc0) of
{_, []} ->
%% Actually was a singleton
Stack;
{Pre, [{T1, A1, Acc1} | Post1]} ->
[{T0, A0, [{T1, A1, Acc1 ++ lists:reverse(Pre)} | Post1]}
| Post0]
end;
_ ->
%% No match, no state change
Stack
end;
{_Pre, [_T]} ->
%% Unfurl the whole stack, we're done
destack(Stack);
{Pre, [T, {T0, A0, Acc0} | Post]} ->
%% Unfurl up to the tag, then accumulate it
[{T0, A0, [destack(Pre ++ [T]) | Acc0]} | Post]
end.
destack([{Tag, Attrs, Acc}]) ->
{Tag, Attrs, lists:reverse(Acc)};
destack([{T1, A1, Acc1}, {T0, A0, Acc0} | Rest]) ->
destack([{T0, A0, [{T1, A1, lists:reverse(Acc1)} | Acc0]} | Rest]).
is_singleton(<<"br">>) -> true;
is_singleton(<<"hr">>) -> true;
is_singleton(<<"img">>) -> true;
is_singleton(<<"input">>) -> true;
is_singleton(<<"base">>) -> true;
is_singleton(<<"meta">>) -> true;
is_singleton(<<"link">>) -> true;
is_singleton(<<"area">>) -> true;
is_singleton(<<"param">>) -> true;
is_singleton(<<"col">>) -> true;
is_singleton(_) -> false.
tokenize_data(B, S=#decoder{offset=O}) ->
tokenize_data(B, S, O, true).
tokenize_data(B, S=#decoder{offset=O}, Start, Whitespace) ->
case B of
<<_:O/binary, C, _/binary>> when (C =/= $< andalso C =/= $&) ->
tokenize_data(B, ?INC_CHAR(S, C), Start,
(Whitespace andalso ?IS_WHITESPACE(C)));
_ ->
Len = O - Start,
<<_:Start/binary, Data:Len/binary, _/binary>> = B,
{{data, Data, Whitespace}, S}
end.
tokenize_attributes(B, S) ->
tokenize_attributes(B, S, []).
tokenize_attributes(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary>> ->
{lists:reverse(Acc), S};
<<_:O/binary, C, _/binary>> when (C =:= $> orelse C =:= $/) ->
{lists:reverse(Acc), S};
<<_:O/binary, "?>", _/binary>> ->
{lists:reverse(Acc), S};
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
tokenize_attributes(B, ?INC_CHAR(S, C), Acc);
_ ->
{Attr, S1} = tokenize_literal(B, S),
{Value, S2} = tokenize_attr_value(Attr, B, S1),
tokenize_attributes(B, S2, [{Attr, Value} | Acc])
end.
tokenize_attr_value(Attr, B, S) ->
S1 = skip_whitespace(B, S),
O = S1#decoder.offset,
case B of
<<_:O/binary, "=", _/binary>> ->
S2 = skip_whitespace(B, ?INC_COL(S1)),
tokenize_quoted_or_unquoted_attr_value(B, S2);
_ ->
{Attr, S1}
end.
tokenize_quoted_or_unquoted_attr_value(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary>> ->
{ [], S };
<<_:O/binary, Q, _/binary>> when Q =:= ?QUOTE orelse
Q =:= ?SQUOTE ->
tokenize_quoted_attr_value(B, ?INC_COL(S), [], Q);
<<_:O/binary, _/binary>> ->
tokenize_unquoted_attr_value(B, S, [])
end.
tokenize_quoted_attr_value(B, S=#decoder{offset=O}, Acc, Q) ->
case B of
<<_:O/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(B, ?INC_COL(S)),
tokenize_quoted_attr_value(B, S1, [Data|Acc], Q);
<<_:O/binary, Q, _/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), ?INC_COL(S) };
<<_:O/binary, C, _/binary>> ->
tokenize_quoted_attr_value(B, ?INC_COL(S), [C|Acc], Q)
end.
tokenize_unquoted_attr_value(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(B, ?INC_COL(S)),
tokenize_unquoted_attr_value(B, S1, [Data|Acc]);
<<_:O/binary, $/, $>, _/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, C, _/binary>> when ?PROBABLE_CLOSE(C) ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, C, _/binary>> ->
tokenize_unquoted_attr_value(B, ?INC_COL(S), [C|Acc])
end.
skip_whitespace(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
skip_whitespace(B, ?INC_CHAR(S, C));
_ ->
S
end.
tokenize_literal(Bin, S=#decoder{offset=O}) ->
case Bin of
<<_:O/binary, C, _/binary>> when C =:= $>
orelse C =:= $/
orelse C =:= $= ->
%% Handle case where tokenize_literal would consume
0 chars .
{[C], ?INC_COL(S)};
_ ->
tokenize_literal(Bin, S, [])
end.
tokenize_literal(Bin, S=#decoder{offset=O}, Acc) ->
case Bin of
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(Bin, ?INC_COL(S)),
tokenize_literal(Bin, S1, [Data | Acc]);
<<_:O/binary, C, _/binary>> when not (?IS_WHITESPACE(C)
orelse C =:= $>
orelse C =:= $/
orelse C =:= $=) ->
tokenize_literal(Bin, ?INC_COL(S), [C | Acc]);
_ ->
{iolist_to_binary(string:to_lower(lists:reverse(Acc))), S}
end.
raw_qgt(Bin, S=#decoder{offset=O}) ->
raw_qgt(Bin, S, O).
raw_qgt(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, "?>", _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{Raw, ?ADV_COL(S, 2)};
<<_:O/binary, C, _/binary>> ->
raw_qgt(Bin, ?INC_CHAR(S, C), Start);
<<_:O/binary>> ->
<<_:Start/binary, Raw/binary>> = Bin,
{Raw, S}
end.
find_qgt(Bin, S=#decoder{offset=O}) ->
case Bin of
<<_:O/binary, "?>", _/binary>> ->
?ADV_COL(S, 2);
<<_:O/binary, ">", _/binary>> ->
?ADV_COL(S, 1);
<<_:O/binary, "/>", _/binary>> ->
?ADV_COL(S, 2);
%% tokenize_attributes takes care of this state:
%% <<_:O/binary, C, _/binary>> ->
%% find_qgt(Bin, ?INC_CHAR(S, C));
<<_:O/binary>> ->
S
end.
find_gt(Bin, S) ->
find_gt(Bin, S, false).
find_gt(Bin, S=#decoder{offset=O}, HasSlash) ->
case Bin of
<<_:O/binary, $/, _/binary>> ->
find_gt(Bin, ?INC_COL(S), true);
<<_:O/binary, $>, _/binary>> ->
{?INC_COL(S), HasSlash};
<<_:O/binary, C, _/binary>> ->
find_gt(Bin, ?INC_CHAR(S, C), HasSlash);
_ ->
{S, HasSlash}
end.
tokenize_charref(Bin, S=#decoder{offset=O}) ->
try
tokenize_charref(Bin, S, O)
catch
throw:invalid_charref ->
{{data, <<"&">>, false}, S}
end.
tokenize_charref(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary>> ->
throw(invalid_charref);
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C)
orelse C =:= ?SQUOTE
orelse C =:= ?QUOTE
orelse C =:= $/
orelse C =:= $> ->
throw(invalid_charref);
<<_:O/binary, $;, _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
Data = case mochiweb_charref:charref(Raw) of
undefined ->
throw(invalid_charref);
Unichar when is_integer(Unichar) ->
mochiutf8:codepoint_to_bytes(Unichar);
Unichars when is_list(Unichars) ->
unicode:characters_to_binary(Unichars)
end,
{{data, Data, false}, ?INC_COL(S)};
_ ->
tokenize_charref(Bin, ?INC_COL(S), Start)
end.
tokenize_doctype(Bin, S) ->
tokenize_doctype(Bin, S, []).
tokenize_doctype(Bin, S=#decoder{offset=O}, Acc) ->
case Bin of
<<_:O/binary>> ->
{{doctype, lists:reverse(Acc)}, S};
<<_:O/binary, $>, _/binary>> ->
{{doctype, lists:reverse(Acc)}, ?INC_COL(S)};
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
tokenize_doctype(Bin, ?INC_CHAR(S, C), Acc);
_ ->
{Word, S1} = tokenize_word_or_literal(Bin, S),
tokenize_doctype(Bin, S1, [Word | Acc])
end.
tokenize_word_or_literal(Bin, S=#decoder{offset=O}) ->
case Bin of
<<_:O/binary, C, _/binary>> when C =:= ?QUOTE orelse C =:= ?SQUOTE ->
tokenize_word(Bin, ?INC_COL(S), C);
<<_:O/binary, C, _/binary>> when not ?IS_WHITESPACE(C) ->
%% Sanity check for whitespace
tokenize_literal(Bin, S)
end.
tokenize_word(Bin, S, Quote) ->
tokenize_word(Bin, S, Quote, []).
tokenize_word(Bin, S=#decoder{offset=O}, Quote, Acc) ->
case Bin of
<<_:O/binary>> ->
{iolist_to_binary(lists:reverse(Acc)), S};
<<_:O/binary, Quote, _/binary>> ->
{iolist_to_binary(lists:reverse(Acc)), ?INC_COL(S)};
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(Bin, ?INC_COL(S)),
tokenize_word(Bin, S1, Quote, [Data | Acc]);
<<_:O/binary, C, _/binary>> ->
tokenize_word(Bin, ?INC_CHAR(S, C), Quote, [C | Acc])
end.
tokenize_cdata(Bin, S=#decoder{offset=O}) ->
tokenize_cdata(Bin, S, O).
tokenize_cdata(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, "]]>", _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{data, Raw, false}, ?ADV_COL(S, 3)};
<<_:O/binary, C, _/binary>> ->
tokenize_cdata(Bin, ?INC_CHAR(S, C), Start);
_ ->
<<_:O/binary, Raw/binary>> = Bin,
{{data, Raw, false}, S}
end.
tokenize_comment(Bin, S=#decoder{offset=O}) ->
tokenize_comment(Bin, S, O).
tokenize_comment(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, "-->", _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{comment, Raw}, ?ADV_COL(S, 3)};
<<_:O/binary, C, _/binary>> ->
tokenize_comment(Bin, ?INC_CHAR(S, C), Start);
<<_:Start/binary, Raw/binary>> ->
{{comment, Raw}, S}
end.
tokenize_script(Bin, S=#decoder{offset=O}) ->
tokenize_script(Bin, S, O).
tokenize_script(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
%% Just a look-ahead, we want the end_tag separately
<<_:O/binary, $<, $/, SS, CC, RR, II, PP, TT, ZZ, _/binary>>
when (SS =:= $s orelse SS =:= $S) andalso
(CC =:= $c orelse CC =:= $C) andalso
(RR =:= $r orelse RR =:= $R) andalso
(II =:= $i orelse II =:= $I) andalso
(PP =:= $p orelse PP =:= $P) andalso
(TT=:= $t orelse TT =:= $T) andalso
?PROBABLE_CLOSE(ZZ) ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{data, Raw, false}, S};
<<_:O/binary, C, _/binary>> ->
tokenize_script(Bin, ?INC_CHAR(S, C), Start);
<<_:Start/binary, Raw/binary>> ->
{{data, Raw, false}, S}
end.
tokenize_textarea(Bin, S=#decoder{offset=O}) ->
tokenize_textarea(Bin, S, O).
tokenize_textarea(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
%% Just a look-ahead, we want the end_tag separately
<<_:O/binary, $<, $/, TT, EE, XX, TT2, AA, RR, EE2, AA2, ZZ, _/binary>>
when (TT =:= $t orelse TT =:= $T) andalso
(EE =:= $e orelse EE =:= $E) andalso
(XX =:= $x orelse XX =:= $X) andalso
(TT2 =:= $t orelse TT2 =:= $T) andalso
(AA =:= $a orelse AA =:= $A) andalso
(RR =:= $r orelse RR =:= $R) andalso
(EE2 =:= $e orelse EE2 =:= $E) andalso
(AA2 =:= $a orelse AA2 =:= $A) andalso
?PROBABLE_CLOSE(ZZ) ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{data, Raw, false}, S};
<<_:O/binary, C, _/binary>> ->
tokenize_textarea(Bin, ?INC_CHAR(S, C), Start);
<<_:Start/binary, Raw/binary>> ->
{{data, Raw, false}, S}
end.
%%
%% Tests
%%
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
to_html_test() ->
?assertEqual(
<<"<html><head><title>hey!</title></head><body><p class=\"foo\">what's up<br /></p><div>sucka</div>RAW!<!-- comment! --></body></html>">>,
iolist_to_binary(
to_html({html, [],
[{<<"head">>, [],
[{title, <<"hey!">>}]},
{body, [],
[{p, [{class, foo}], [<<"what's">>, <<" up">>, {br}]},
{'div', <<"sucka">>},
{'=', <<"RAW!">>},
{comment, <<" comment! ">>}]}]}))),
?assertEqual(
<<"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"-transitional.dtd\">">>,
iolist_to_binary(
to_html({doctype,
[<<"html">>, <<"PUBLIC">>,
<<"-//W3C//DTD XHTML 1.0 Transitional//EN">>,
<<"-transitional.dtd">>]}))),
?assertEqual(
<<"<html><?xml:namespace prefix=\"o\" ns=\"urn:schemas-microsoft-com:office:office\"?></html>">>,
iolist_to_binary(
to_html({<<"html">>,[],
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}]}))),
ok.
escape_test() ->
?assertEqual(
<<"&quot;\"word ><<up!&quot;">>,
escape(<<""\"word ><<up!"">>)),
?assertEqual(
<<"&quot;\"word ><<up!&quot;">>,
escape(""\"word ><<up!"")),
?assertEqual(
<<"&quot;\"word ><<up!&quot;">>,
escape('"\"word ><<up!"')),
ok.
escape_attr_test() ->
?assertEqual(
<<"&quot;"word ><<up!&quot;">>,
escape_attr(<<""\"word ><<up!"">>)),
?assertEqual(
<<"&quot;"word ><<up!&quot;">>,
escape_attr(""\"word ><<up!"")),
?assertEqual(
<<"&quot;"word ><<up!&quot;">>,
escape_attr('"\"word ><<up!"')),
?assertEqual(
<<"12345">>,
escape_attr(12345)),
?assertEqual(
<<"1.5">>,
escape_attr(1.5)),
ok.
tokens_test() ->
?assertEqual(
[{start_tag, <<"foo">>, [{<<"bar">>, <<"baz">>},
{<<"wibble">>, <<"wibble">>},
{<<"alice">>, <<"bob">>}], true}],
tokens(<<"<foo bar=baz wibble='wibble' alice=\"bob\"/>">>)),
?assertEqual(
[{start_tag, <<"foo">>, [{<<"bar">>, <<"baz">>},
{<<"wibble">>, <<"wibble">>},
{<<"alice">>, <<"bob">>}], true}],
tokens(<<"<foo bar=baz wibble='wibble' alice=bob/>">>)),
?assertEqual(
[{comment, <<"[if lt IE 7]>\n<style type=\"text/css\">\n.no_ie { display: none; }\n</style>\n<![endif]">>}],
tokens(<<"<!--[if lt IE 7]>\n<style type=\"text/css\">\n.no_ie { display: none; }\n</style>\n<![endif]-->">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type=\"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type =\"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type = \"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type= \"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"textarea">>, [], false},
{data, <<"<html></body>">>, false},
{end_tag, <<"textarea">>}],
tokens(<<"<textarea><html></body></textarea>">>)),
?assertEqual(
[{start_tag, <<"textarea">>, [], false},
{data, <<"<html></body></textareaz>">>, false}],
tokens(<<"<textarea ><html></body></textareaz>">>)),
?assertEqual(
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}],
tokens(<<"<?xml:namespace prefix=\"o\" ns=\"urn:schemas-microsoft-com:office:office\"?>">>)),
?assertEqual(
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}],
tokens(<<"<?xml:namespace prefix=o ns=urn:schemas-microsoft-com:office:office \n?>">>)),
?assertEqual(
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}],
tokens(<<"<?xml:namespace prefix=o ns=urn:schemas-microsoft-com:office:office">>)),
?assertEqual(
[{data, <<"<">>, false}],
tokens(<<"<">>)),
?assertEqual(
[{data, <<"not html ">>, false},
{data, <<"< at all">>, false}],
tokens(<<"not html < at all">>)),
ok.
parse_test() ->
D0 = <<"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"\">
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
<title>Foo</title>
<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/rel/dojo/resources/dojo.css\" media=\"screen\">
<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/foo.css\" media=\"screen\">
<!--[if lt IE 7]>
<style type=\"text/css\">
.no_ie { display: none; }
</style>
<![endif]-->
<link rel=\"icon\" href=\"/static/images/favicon.ico\" type=\"image/x-icon\">
<link rel=\"shortcut icon\" href=\"/static/images/favicon.ico\" type=\"image/x-icon\">
</head>
<body id=\"home\" class=\"tundra\"><![CDATA[<<this<!-- is -->CDATA>>]]></body>
</html>">>,
?assertEqual(
{<<"html">>, [],
[{<<"head">>, [],
[{<<"meta">>,
[{<<"http-equiv">>,<<"Content-Type">>},
{<<"content">>,<<"text/html; charset=UTF-8">>}],
[]},
{<<"title">>,[],[<<"Foo">>]},
{<<"link">>,
[{<<"rel">>,<<"stylesheet">>},
{<<"type">>,<<"text/css">>},
{<<"href">>,<<"/static/rel/dojo/resources/dojo.css">>},
{<<"media">>,<<"screen">>}],
[]},
{<<"link">>,
[{<<"rel">>,<<"stylesheet">>},
{<<"type">>,<<"text/css">>},
{<<"href">>,<<"/static/foo.css">>},
{<<"media">>,<<"screen">>}],
[]},
{comment,<<"[if lt IE 7]>\n <style type=\"text/css\">\n .no_ie { display: none; }\n </style>\n <![endif]">>},
{<<"link">>,
[{<<"rel">>,<<"icon">>},
{<<"href">>,<<"/static/images/favicon.ico">>},
{<<"type">>,<<"image/x-icon">>}],
[]},
{<<"link">>,
[{<<"rel">>,<<"shortcut icon">>},
{<<"href">>,<<"/static/images/favicon.ico">>},
{<<"type">>,<<"image/x-icon">>}],
[]}]},
{<<"body">>,
[{<<"id">>,<<"home">>},
{<<"class">>,<<"tundra">>}],
[<<"<<this<!-- is -->CDATA>>">>]}]},
parse(D0)),
?assertEqual(
{<<"html">>,[],
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}]},
parse(
<<"<html><?xml:namespace prefix=\"o\" ns=\"urn:schemas-microsoft-com:office:office\"?></html>">>)),
?assertEqual(
{<<"html">>, [],
[{<<"dd">>, [], [<<"foo">>]},
{<<"dt">>, [], [<<"bar">>]}]},
parse(<<"<html><dd>foo<dt>bar</html>">>)),
Singleton sadness
?assertEqual(
{<<"html">>, [],
[{<<"link">>, [], []},
<<"foo">>,
{<<"br">>, [], []},
<<"bar">>]},
parse(<<"<html><link>foo<br>bar</html>">>)),
?assertEqual(
{<<"html">>, [],
[{<<"link">>, [], [<<"foo">>,
{<<"br">>, [], []},
<<"bar">>]}]},
parse(<<"<html><link>foo<br>bar</link></html>">>)),
%% Case insensitive tags
?assertEqual(
{<<"html">>, [],
[{<<"head">>, [], [<<"foo">>,
{<<"br">>, [], []},
<<"BAR">>]},
{<<"body">>, [{<<"class">>, <<"">>}, {<<"bgcolor">>, <<"#Aa01fF">>}], []}
]},
parse(<<"<html><Head>foo<bR>BAR</head><body Class=\"\" bgcolor=\"#Aa01fF\"></BODY></html>">>)),
ok.
exhaustive_is_singleton_test() ->
T = mochiweb_cover:clause_lookup_table(?MODULE, is_singleton),
[?assertEqual(V, is_singleton(K)) || {K, V} <- T].
tokenize_attributes_test() ->
?assertEqual(
{<<"foo">>,
[{<<"bar">>, <<"b\"az">>},
{<<"wibble">>, <<"wibble">>},
{<<"taco", 16#c2, 16#a9>>, <<"bell">>},
{<<"quux">>, <<"quux">>}],
[]},
parse(<<"<foo bar=\"b"az\" wibble taco©=bell quux">>)),
ok.
tokens2_test() ->
D0 = <<"<channel><title>from __future__ import *</title><link></link><description>Bob's Rants</description></channel>">>,
?assertEqual(
[{start_tag,<<"channel">>,[],false},
{start_tag,<<"title">>,[],false},
{data,<<"from __future__ import *">>,false},
{end_tag,<<"title">>},
{start_tag,<<"link">>,[],true},
{data,<<"">>,false},
{end_tag,<<"link">>},
{start_tag,<<"description">>,[],false},
{data,<<"Bob's Rants">>,false},
{end_tag,<<"description">>},
{end_tag,<<"channel">>}],
tokens(D0)),
ok.
to_tokens_test() ->
?assertEqual(
[{start_tag, <<"p">>, [{class, 1}], false},
{end_tag, <<"p">>}],
to_tokens({p, [{class, 1}], []})),
?assertEqual(
[{start_tag, <<"p">>, [], false},
{end_tag, <<"p">>}],
to_tokens({p})),
?assertEqual(
[{'=', <<"data">>}],
to_tokens({'=', <<"data">>})),
?assertEqual(
[{comment, <<"comment">>}],
to_tokens({comment, <<"comment">>})),
%% This is only allowed in sub-tags:
%% {p, [{"class", "foo"}]} as {p, [{"class", "foo"}], []}
%% On the outside it's always treated as follows:
%% {p, [], [{"class", "foo"}]} as {p, [], [{"class", "foo"}]}
?assertEqual(
[{start_tag, <<"html">>, [], false},
{start_tag, <<"p">>, [{class, 1}], false},
{end_tag, <<"p">>},
{end_tag, <<"html">>}],
to_tokens({html, [{p, [{class, 1}]}]})),
ok.
parse2_test() ->
D0 = <<"<channel><title>from __future__ import *</title><link><br>foo</link><description>Bob's Rants</description></channel>">>,
?assertEqual(
{<<"channel">>,[],
[{<<"title">>,[],[<<"from __future__ import *">>]},
{<<"link">>,[],[
<<"">>,
{<<"br">>,[],[]},
<<"foo">>]},
{<<"description">>,[],[<<"Bob's Rants">>]}]},
parse(D0)),
ok.
parse_tokens_test() ->
D0 = [{doctype,[<<"HTML">>,<<"PUBLIC">>,<<"-//W3C//DTD HTML 4.01 Transitional//EN">>]},
{data,<<"\n">>,true},
{start_tag,<<"html">>,[],false}],
?assertEqual(
{<<"html">>, [], []},
parse_tokens(D0)),
D1 = D0 ++ [{end_tag, <<"html">>}],
?assertEqual(
{<<"html">>, [], []},
parse_tokens(D1)),
D2 = D0 ++ [{start_tag, <<"body">>, [], false}],
?assertEqual(
{<<"html">>, [], [{<<"body">>, [], []}]},
parse_tokens(D2)),
D3 = D0 ++ [{start_tag, <<"head">>, [], false},
{end_tag, <<"head">>},
{start_tag, <<"body">>, [], false}],
?assertEqual(
{<<"html">>, [], [{<<"head">>, [], []}, {<<"body">>, [], []}]},
parse_tokens(D3)),
D4 = D3 ++ [{data,<<"\n">>,true},
{start_tag,<<"div">>,[{<<"class">>,<<"a">>}],false},
{start_tag,<<"a">>,[{<<"name">>,<<"#anchor">>}],false},
{end_tag,<<"a">>},
{end_tag,<<"div">>},
{start_tag,<<"div">>,[{<<"class">>,<<"b">>}],false},
{start_tag,<<"div">>,[{<<"class">>,<<"c">>}],false},
{end_tag,<<"div">>},
{end_tag,<<"div">>}],
?assertEqual(
{<<"html">>, [],
[{<<"head">>, [], []},
{<<"body">>, [],
[{<<"div">>, [{<<"class">>, <<"a">>}], [{<<"a">>, [{<<"name">>, <<"#anchor">>}], []}]},
{<<"div">>, [{<<"class">>, <<"b">>}], [{<<"div">>, [{<<"class">>, <<"c">>}], []}]}
]}]},
parse_tokens(D4)),
D5 = [{start_tag,<<"html">>,[],false},
{data,<<"\n">>,true},
{data,<<"boo">>,false},
{data,<<"hoo">>,false},
{data,<<"\n">>,true},
{end_tag,<<"html">>}],
?assertEqual(
{<<"html">>, [], [<<"\nboohoo\n">>]},
parse_tokens(D5)),
D6 = [{start_tag,<<"html">>,[],false},
{data,<<"\n">>,true},
{data,<<"\n">>,true},
{end_tag,<<"html">>}],
?assertEqual(
{<<"html">>, [], []},
parse_tokens(D6)),
D7 = [{start_tag,<<"html">>,[],false},
{start_tag,<<"ul">>,[],false},
{start_tag,<<"li">>,[],false},
{data,<<"word">>,false},
{start_tag,<<"li">>,[],false},
{data,<<"up">>,false},
{end_tag,<<"li">>},
{start_tag,<<"li">>,[],false},
{data,<<"fdsa">>,false},
{start_tag,<<"br">>,[],true},
{data,<<"asdf">>,false},
{end_tag,<<"ul">>},
{end_tag,<<"html">>}],
?assertEqual(
{<<"html">>, [],
[{<<"ul">>, [],
[{<<"li">>, [], [<<"word">>]},
{<<"li">>, [], [<<"up">>]},
{<<"li">>, [], [<<"fdsa">>,{<<"br">>, [], []}, <<"asdf">>]}]}]},
parse_tokens(D7)),
ok.
destack_test() ->
{<<"a">>, [], []} =
destack([{<<"a">>, [], []}]),
{<<"a">>, [], [{<<"b">>, [], []}]} =
destack([{<<"b">>, [], []}, {<<"a">>, [], []}]),
{<<"a">>, [], [{<<"b">>, [], [{<<"c">>, [], []}]}]} =
destack([{<<"c">>, [], []}, {<<"b">>, [], []}, {<<"a">>, [], []}]),
[{<<"a">>, [], [{<<"b">>, [], [{<<"c">>, [], []}]}]}] =
destack(<<"b">>,
[{<<"c">>, [], []}, {<<"b">>, [], []}, {<<"a">>, [], []}]),
[{<<"b">>, [], [{<<"c">>, [], []}]}, {<<"a">>, [], []}] =
destack(<<"c">>,
[{<<"c">>, [], []}, {<<"b">>, [], []},{<<"a">>, [], []}]),
ok.
doctype_test() ->
?assertEqual(
{<<"html">>,[],[{<<"head">>,[],[]}]},
mochiweb_html:parse("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"\">"
"<html><head></head></body></html>")),
?assertEqual(
{<<"html">>,[],[{<<"head">>,[],[]}]},
mochiweb_html:parse("<html>"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"\">"
"<head></head></body></html>")),
%%
?assertEqual(
{<<"html">>,[],[{<<"head">>,[],[]}]},
mochiweb_html:parse("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"/>"
"<html>"
"<head></head></body></html>")),
ok.
dumb_br_test() ->
%%
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>]},
mochiweb_html:parse("<div><br/><br/>z</br/></br/></div>")),
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>]},
mochiweb_html:parse("<div><br><br>z</br/></br/></div>")),
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>, {<<"br">>, [], []}, {<<"br">>, [], []}]},
mochiweb_html:parse("<div><br><br>z<br/><br/></div>")),
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>]},
mochiweb_html:parse("<div><br><br>z</br></br></div>")).
php_test() ->
%%
?assertEqual(
[{pi, <<"php\n">>}],
mochiweb_html:tokens(
"<?php\n?>")),
?assertEqual(
{<<"div">>, [], [{pi, <<"php\n">>}]},
mochiweb_html:parse(
"<div><?php\n?></div>")),
ok.
parse_unquoted_attr_test() ->
D0 = <<"<html><img src=/images/icon.png/></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png">> } ], [] }
]},
mochiweb_html:parse(D0)),
D1 = <<"<html><img src=/images/icon.png></img></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png">> } ], [] }
]},
mochiweb_html:parse(D1)),
D2 = <<"<html><img src=/images/icon>.png width=100></img></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon>.png">> }, { <<"width">>, <<"100">> } ], [] }
]},
mochiweb_html:parse(D2)),
ok.
parse_quoted_attr_test() ->
D0 = <<"<html><img src='/images/icon.png'></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png">> } ], [] }
]},
mochiweb_html:parse(D0)),
D1 = <<"<html><img src=\"/images/icon.png'></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png'></html>">> } ], [] }
]},
mochiweb_html:parse(D1)),
D2 = <<"<html><img src=\"/images/icon>.png\"></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon>.png">> } ], [] }
]},
mochiweb_html:parse(D2)),
%% Quoted attributes can contain whitespace and newlines
D3 = <<"<html><a href=\"#\" onclick=\"javascript: test(1,\ntrue);\"></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"a">>, [ { <<"href">>, <<"#">> }, {<<"onclick">>, <<"javascript: test(1,\ntrue);">>} ], [] }
]},
mochiweb_html:parse(D3)),
ok.
parse_missing_attr_name_test() ->
D0 = <<"<html =black></html>">>,
?assertEqual(
{<<"html">>, [ { <<"=">>, <<"=">> }, { <<"black">>, <<"black">> } ], [] },
mochiweb_html:parse(D0)),
ok.
parse_broken_pi_test() ->
D0 = <<"<html><?xml:namespace prefix = o ns = \"urn:schemas-microsoft-com:office:office\" /></html>">>,
?assertEqual(
{<<"html">>, [], [
{ pi, <<"xml:namespace">>, [ { <<"prefix">>, <<"o">> },
{ <<"ns">>, <<"urn:schemas-microsoft-com:office:office">> } ] }
] },
mochiweb_html:parse(D0)),
ok.
parse_funny_singletons_test() ->
D0 = <<"<html><input><input>x</input></input></html>">>,
?assertEqual(
{<<"html">>, [], [
{ <<"input">>, [], [] },
{ <<"input">>, [], [ <<"x">> ] }
] },
mochiweb_html:parse(D0)),
ok.
to_html_singleton_test() ->
D0 = <<"<link />">>,
T0 = {<<"link">>,[],[]},
?assertEqual(D0, iolist_to_binary(to_html(T0))),
D1 = <<"<head><link /></head>">>,
T1 = {<<"head">>,[],[{<<"link">>,[],[]}]},
?assertEqual(D1, iolist_to_binary(to_html(T1))),
D2 = <<"<head><link /><link /></head>">>,
T2 = {<<"head">>,[],[{<<"link">>,[],[]}, {<<"link">>,[],[]}]},
?assertEqual(D2, iolist_to_binary(to_html(T2))),
%% Make sure singletons are converted to singletons.
D3 = <<"<head><link /></head>">>,
T3 = {<<"head">>,[],[{<<"link">>,[],[<<"funny">>]}]},
?assertEqual(D3, iolist_to_binary(to_html(T3))),
D4 = <<"<link />">>,
T4 = {<<"link">>,[],[<<"funny">>]},
?assertEqual(D4, iolist_to_binary(to_html(T4))),
ok.
parse_amp_test_() ->
[?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[{<<"onload">>,<<"javascript:A('1&2')">>}],[]}]},
mochiweb_html:parse("<html><body onload=\"javascript:A('1&2')\"></body></html>")),
?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[{<<"onload">>,<<"javascript:A('1& 2')">>}],[]}]},
mochiweb_html:parse("<html><body onload=\"javascript:A('1& 2')\"></body></html>")),
?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[],[<<"& ">>]}]},
mochiweb_html:parse("<html><body>& </body></html>")),
?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[],[<<"&">>]}]},
mochiweb_html:parse("<html><body>&</body></html>"))].
parse_unescaped_lt_test() ->
D1 = <<"<div> < < <a href=\"/\">Back</a></div>">>,
?assertEqual(
{<<"div">>, [], [<<" < < ">>, {<<"a">>, [{<<"href">>, <<"/">>}],
[<<"Back">>]}]},
mochiweb_html:parse(D1)),
D2 = <<"<div> << <a href=\"/\">Back</a></div>">>,
?assertEqual(
{<<"div">>, [], [<<" << ">>, {<<"a">>, [{<<"href">>, <<"/">>}],
[<<"Back">>]}]},
mochiweb_html:parse(D2)).
-endif.
| null | https://raw.githubusercontent.com/derekchiang/Erlang-Web-Crawler/0ff3b8dec1976b4e82f7177f951158a5a87c86f6/mochiweb_html.erl | erlang | This is a macro to placate syntax highlighters..
@type html_node() = {string(), [html_attr()], [html_node() | string()]}
@type html_attr() = {string(), string()}
@type html_token() = html_data() | start_tag() | end_tag() | inline_html() | html_comment() | html_doctype()
@type html_data() = {data, string(), Whitespace::boolean()}
@type end_tag() = {end_tag, Name}
@type html_comment() = {comment, Comment}
External API.
@doc tokenize and then transform the token stream into a HTML tree.
@doc Transform the output of tokens(Doc) into a HTML tree.
Skip over doctype, processing instructions
@doc Convert a html_node() tree to a list of tokens.
This is only allowed in sub-tags: {p, [{"class", "foo"}]}
@doc Escape a string such that it's safe for HTML (amp; lt; gt;).
(amp; lt; gt; quot;).
Allow {br}
Allow {pi, binary()}
Allow {pi, binary(), list()}
Allow {p, [{"class", "foo"}]}
Allow {p, "content"} and {p, <<"content">>}
Allow {"p", [{"class", "foo"}], <<"content">>}
Allow {"p", [{"class", "foo"}], "content"}
List text
Binary text
This isn't really strict HTML
This is an ugly hack to make dumb_br_test() pass,
this makes it such that br can never have children.
If we're parsing something like XML we might find
a <link>tag</link> that is normally a singleton
in HTML but isn't here
Actually was a singleton
No match, no state change
Unfurl the whole stack, we're done
Unfurl up to the tag, then accumulate it
Handle case where tokenize_literal would consume
tokenize_attributes takes care of this state:
<<_:O/binary, C, _/binary>> ->
find_qgt(Bin, ?INC_CHAR(S, C));
Sanity check for whitespace
Just a look-ahead, we want the end_tag separately
Just a look-ahead, we want the end_tag separately
Tests
Case insensitive tags
This is only allowed in sub-tags:
{p, [{"class", "foo"}]} as {p, [{"class", "foo"}], []}
On the outside it's always treated as follows:
{p, [], [{"class", "foo"}]} as {p, [], [{"class", "foo"}]}
Quoted attributes can contain whitespace and newlines
Make sure singletons are converted to singletons. | @author < >
2007 Mochi Media , Inc.
@doc Loosely tokenizes and generates parse trees for HTML 4 .
-module(mochiweb_html).
-export([tokens/1, parse/1, parse_tokens/1, to_tokens/1, escape/1,
escape_attr/1, to_html/1]).
-define(QUOTE, $\").
-define(SQUOTE, $\').
-define(ADV_COL(S, N),
S#decoder{column=N+S#decoder.column,
offset=N+S#decoder.offset}).
-define(INC_COL(S),
S#decoder{column=1+S#decoder.column,
offset=1+S#decoder.offset}).
-define(INC_LINE(S),
S#decoder{column=1,
line=1+S#decoder.line,
offset=1+S#decoder.offset}).
-define(INC_CHAR(S, C),
case C of
$\n ->
S#decoder{column=1,
line=1+S#decoder.line,
offset=1+S#decoder.offset};
_ ->
S#decoder{column=1+S#decoder.column,
offset=1+S#decoder.offset}
end).
-define(IS_WHITESPACE(C),
(C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
-define(IS_LITERAL_SAFE(C),
((C >= $A andalso C =< $Z) orelse (C >= $a andalso C =< $z)
orelse (C >= $0 andalso C =< $9))).
-define(PROBABLE_CLOSE(C),
(C =:= $> orelse ?IS_WHITESPACE(C))).
-record(decoder, {line=1,
column=1,
offset=0}).
@type start_tag ( ) = { start_tag , Name , [ html_attr ( ) ] , ( ) }
@type html_doctype ( ) = { doctype , [ Doctype ] }
@type inline_html ( ) = { ' = ' , ( ) }
@spec parse(string ( ) | binary ( ) ) - > html_node ( )
parse(Input) ->
parse_tokens(tokens(Input)).
@spec parse_tokens([html_token ( ) ] ) - > html_node ( )
parse_tokens(Tokens) when is_list(Tokens) ->
F = fun (X) ->
case X of
{start_tag, _, _, false} ->
false;
_ ->
true
end
end,
[{start_tag, Tag, Attrs, false} | Rest] = lists:dropwhile(F, Tokens),
{Tree, _} = tree(Rest, [norm({Tag, Attrs})]),
Tree.
) - > [ html_token ( ) ]
@doc Transform the input UTF-8 HTML into a token stream .
tokens(Input) ->
tokens(iolist_to_binary(Input), #decoder{}, []).
to_tokens(html_node ( ) ) - > [ html_token ( ) ]
to_tokens({Tag0}) ->
to_tokens({Tag0, [], []});
to_tokens(T={'=', _}) ->
[T];
to_tokens(T={doctype, _}) ->
[T];
to_tokens(T={comment, _}) ->
[T];
to_tokens({Tag0, Acc}) ->
to_tokens({Tag0, [], Acc});
to_tokens({Tag0, Attrs, Acc}) ->
Tag = to_tag(Tag0),
case is_singleton(Tag) of
true ->
to_tokens([], [{start_tag, Tag, Attrs, true}]);
false ->
to_tokens([{Tag, Acc}], [{start_tag, Tag, Attrs, false}])
end.
( ) ] | html_node ( ) ) - > iolist ( )
@doc Convert a list of html_token ( ) to a HTML document .
to_html(Node) when is_tuple(Node) ->
to_html(to_tokens(Node));
to_html(Tokens) when is_list(Tokens) ->
to_html(Tokens, []).
escape(string ( ) | atom ( ) | binary ( ) ) - > binary ( )
escape(B) when is_binary(B) ->
escape(binary_to_list(B), []);
escape(A) when is_atom(A) ->
escape(atom_to_list(A), []);
escape(S) when is_list(S) ->
escape(S, []).
escape_attr(string ( ) | binary ( ) | atom ( ) | integer ( ) | float ( ) ) - > binary ( )
@doc Escape a string such that it 's safe for HTML attrs
escape_attr(B) when is_binary(B) ->
escape_attr(binary_to_list(B), []);
escape_attr(A) when is_atom(A) ->
escape_attr(atom_to_list(A), []);
escape_attr(S) when is_list(S) ->
escape_attr(S, []);
escape_attr(I) when is_integer(I) ->
escape_attr(integer_to_list(I), []);
escape_attr(F) when is_float(F) ->
escape_attr(mochinum:digits(F), []).
to_html([], Acc) ->
lists:reverse(Acc);
to_html([{'=', Content} | Rest], Acc) ->
to_html(Rest, [Content | Acc]);
to_html([{pi, Bin} | Rest], Acc) ->
Open = [<<"<?">>,
Bin,
<<"?>">>],
to_html(Rest, [Open | Acc]);
to_html([{pi, Tag, Attrs} | Rest], Acc) ->
Open = [<<"<?">>,
Tag,
attrs_to_html(Attrs, []),
<<"?>">>],
to_html(Rest, [Open | Acc]);
to_html([{comment, Comment} | Rest], Acc) ->
to_html(Rest, [[<<"<!--">>, Comment, <<"-->">>] | Acc]);
to_html([{doctype, Parts} | Rest], Acc) ->
Inside = doctype_to_html(Parts, Acc),
to_html(Rest, [[<<"<!DOCTYPE">>, Inside, <<">">>] | Acc]);
to_html([{data, Data, _Whitespace} | Rest], Acc) ->
to_html(Rest, [escape(Data) | Acc]);
to_html([{start_tag, Tag, Attrs, Singleton} | Rest], Acc) ->
Open = [<<"<">>,
Tag,
attrs_to_html(Attrs, []),
case Singleton of
true -> <<" />">>;
false -> <<">">>
end],
to_html(Rest, [Open | Acc]);
to_html([{end_tag, Tag} | Rest], Acc) ->
to_html(Rest, [[<<"</">>, Tag, <<">">>] | Acc]).
doctype_to_html([], Acc) ->
lists:reverse(Acc);
doctype_to_html([Word | Rest], Acc) ->
case lists:all(fun (C) -> ?IS_LITERAL_SAFE(C) end,
binary_to_list(iolist_to_binary(Word))) of
true ->
doctype_to_html(Rest, [[<<" ">>, Word] | Acc]);
false ->
doctype_to_html(Rest, [[<<" \"">>, escape_attr(Word), ?QUOTE] | Acc])
end.
attrs_to_html([], Acc) ->
lists:reverse(Acc);
attrs_to_html([{K, V} | Rest], Acc) ->
attrs_to_html(Rest,
[[<<" ">>, escape(K), <<"=\"">>,
escape_attr(V), <<"\"">>] | Acc]).
escape([], Acc) ->
list_to_binary(lists:reverse(Acc));
escape("<" ++ Rest, Acc) ->
escape(Rest, lists:reverse("<", Acc));
escape(">" ++ Rest, Acc) ->
escape(Rest, lists:reverse(">", Acc));
escape("&" ++ Rest, Acc) ->
escape(Rest, lists:reverse("&", Acc));
escape([C | Rest], Acc) ->
escape(Rest, [C | Acc]).
escape_attr([], Acc) ->
list_to_binary(lists:reverse(Acc));
escape_attr("<" ++ Rest, Acc) ->
escape_attr(Rest, lists:reverse("<", Acc));
escape_attr(">" ++ Rest, Acc) ->
escape_attr(Rest, lists:reverse(">", Acc));
escape_attr("&" ++ Rest, Acc) ->
escape_attr(Rest, lists:reverse("&", Acc));
escape_attr([?QUOTE | Rest], Acc) ->
escape_attr(Rest, lists:reverse(""", Acc));
escape_attr([C | Rest], Acc) ->
escape_attr(Rest, [C | Acc]).
to_tag(A) when is_atom(A) ->
norm(atom_to_list(A));
to_tag(L) ->
norm(L).
to_tokens([], Acc) ->
lists:reverse(Acc);
to_tokens([{Tag, []} | Rest], Acc) ->
to_tokens(Rest, [{end_tag, to_tag(Tag)} | Acc]);
to_tokens([{Tag0, [{T0} | R1]} | Rest], Acc) ->
to_tokens([{Tag0, [{T0, [], []} | R1]} | Rest], Acc);
to_tokens([{Tag0, [T0={'=', _C0} | R1]} | Rest], Acc) ->
Allow { ' = ' , ( ) }
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [T0={comment, _C0} | R1]} | Rest], Acc) ->
Allow { comment , ( ) }
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [T0={pi, _S0} | R1]} | Rest], Acc) ->
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [T0={pi, _S0, _A0} | R1]} | Rest], Acc) ->
to_tokens([{Tag0, R1} | Rest], [T0 | Acc]);
to_tokens([{Tag0, [{T0, A0=[{_, _} | _]} | R1]} | Rest], Acc) ->
to_tokens([{Tag0, [{T0, A0, []} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, C0} | R1]} | Rest], Acc) ->
to_tokens([{Tag0, [{T0, [], C0} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, A1, C0} | R1]} | Rest], Acc) when is_binary(C0) ->
to_tokens([{Tag0, [{T0, A1, binary_to_list(C0)} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, A1, C0=[C | _]} | R1]} | Rest], Acc)
when is_integer(C) ->
to_tokens([{Tag0, [{T0, A1, [C0]} | R1]} | Rest], Acc);
to_tokens([{Tag0, [{T0, A1, C1} | R1]} | Rest], Acc) ->
Native { " p " , [ { " class " , " foo " } ] , [ " content " ] }
Tag = to_tag(Tag0),
T1 = to_tag(T0),
case is_singleton(norm(T1)) of
true ->
to_tokens([{Tag, R1} | Rest], [{start_tag, T1, A1, true} | Acc]);
false ->
to_tokens([{T1, C1}, {Tag, R1} | Rest],
[{start_tag, T1, A1, false} | Acc])
end;
to_tokens([{Tag0, [L | R1]} | Rest], Acc) when is_list(L) ->
Tag = to_tag(Tag0),
to_tokens([{Tag, R1} | Rest], [{data, iolist_to_binary(L), false} | Acc]);
to_tokens([{Tag0, [B | R1]} | Rest], Acc) when is_binary(B) ->
Tag = to_tag(Tag0),
to_tokens([{Tag, R1} | Rest], [{data, B, false} | Acc]).
tokens(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary>> ->
lists:reverse(Acc);
_ ->
{Tag, S1} = tokenize(B, S),
case parse_flag(Tag) of
script ->
{Tag2, S2} = tokenize_script(B, S1),
tokens(B, S2, [Tag2, Tag | Acc]);
textarea ->
{Tag2, S2} = tokenize_textarea(B, S1),
tokens(B, S2, [Tag2, Tag | Acc]);
none ->
tokens(B, S1, [Tag | Acc])
end
end.
parse_flag({start_tag, B, _, false}) ->
case string:to_lower(binary_to_list(B)) of
"script" ->
script;
"textarea" ->
textarea;
_ ->
none
end;
parse_flag(_) ->
none.
tokenize(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary, "<!--", _/binary>> ->
tokenize_comment(B, ?ADV_COL(S, 4));
<<_:O/binary, "<!DOCTYPE", _/binary>> ->
tokenize_doctype(B, ?ADV_COL(S, 10));
<<_:O/binary, "<![CDATA[", _/binary>> ->
tokenize_cdata(B, ?ADV_COL(S, 9));
<<_:O/binary, "<?php", _/binary>> ->
{Body, S1} = raw_qgt(B, ?ADV_COL(S, 2)),
{{pi, Body}, S1};
<<_:O/binary, "<?", _/binary>> ->
{Tag, S1} = tokenize_literal(B, ?ADV_COL(S, 2)),
{Attrs, S2} = tokenize_attributes(B, S1),
S3 = find_qgt(B, S2),
{{pi, Tag, Attrs}, S3};
<<_:O/binary, "&", _/binary>> ->
tokenize_charref(B, ?INC_COL(S));
<<_:O/binary, "</", _/binary>> ->
{Tag, S1} = tokenize_literal(B, ?ADV_COL(S, 2)),
{S2, _} = find_gt(B, S1),
{{end_tag, Tag}, S2};
<<_:O/binary, "<", C, _/binary>>
when ?IS_WHITESPACE(C); not ?IS_LITERAL_SAFE(C) ->
{{data, Data, _Whitespace}, S1} = tokenize_data(B, ?INC_COL(S)),
{{data, <<$<, Data/binary>>, false}, S1};
<<_:O/binary, "<", _/binary>> ->
{Tag, S1} = tokenize_literal(B, ?INC_COL(S)),
{Attrs, S2} = tokenize_attributes(B, S1),
{S3, HasSlash} = find_gt(B, S2),
Singleton = HasSlash orelse is_singleton(Tag),
{{start_tag, Tag, Attrs, Singleton}, S3};
_ ->
tokenize_data(B, S)
end.
tree_data([{data, Data, Whitespace} | Rest], AllWhitespace, Acc) ->
tree_data(Rest, (Whitespace andalso AllWhitespace), [Data | Acc]);
tree_data(Rest, AllWhitespace, Acc) ->
{iolist_to_binary(lists:reverse(Acc)), AllWhitespace, Rest}.
tree([], Stack) ->
{destack(Stack), []};
tree([{end_tag, Tag} | Rest], Stack) ->
case destack(norm(Tag), Stack) of
S when is_list(S) ->
tree(Rest, S);
Result ->
{Result, []}
end;
tree([{start_tag, Tag, Attrs, true} | Rest], S) ->
tree(Rest, append_stack_child(norm({Tag, Attrs}), S));
tree([{start_tag, Tag, Attrs, false} | Rest], S) ->
tree(Rest, stack(norm({Tag, Attrs}), S));
tree([T={pi, _Raw} | Rest], S) ->
tree(Rest, append_stack_child(T, S));
tree([T={pi, _Tag, _Attrs} | Rest], S) ->
tree(Rest, append_stack_child(T, S));
tree([T={comment, _Comment} | Rest], S) ->
tree(Rest, append_stack_child(T, S));
tree(L=[{data, _Data, _Whitespace} | _], S) ->
case tree_data(L, true, []) of
{_, true, Rest} ->
tree(Rest, S);
{Data, false, Rest} ->
tree(Rest, append_stack_child(Data, S))
end;
tree([{doctype, _} | Rest], Stack) ->
tree(Rest, Stack).
norm({Tag, Attrs}) ->
{norm(Tag), [{norm(K), iolist_to_binary(V)} || {K, V} <- Attrs], []};
norm(Tag) when is_binary(Tag) ->
Tag;
norm(Tag) ->
list_to_binary(string:to_lower(Tag)).
stack(T1={TN, _, _}, Stack=[{TN, _, _} | _Rest])
when TN =:= <<"li">> orelse TN =:= <<"option">> ->
[T1 | destack(TN, Stack)];
stack(T1={TN0, _, _}, Stack=[{TN1, _, _} | _Rest])
when (TN0 =:= <<"dd">> orelse TN0 =:= <<"dt">>) andalso
(TN1 =:= <<"dd">> orelse TN1 =:= <<"dt">>) ->
[T1 | destack(TN1, Stack)];
stack(T1, Stack) ->
[T1 | Stack].
append_stack_child(StartTag, [{Name, Attrs, Acc} | Stack]) ->
[{Name, Attrs, [StartTag | Acc]} | Stack].
destack(<<"br">>, Stack) ->
Stack;
destack(TagName, Stack) when is_list(Stack) ->
F = fun (X) ->
case X of
{TagName, _, _} ->
false;
_ ->
true
end
end,
case lists:splitwith(F, Stack) of
{_, []} ->
case {is_singleton(TagName), Stack} of
{true, [{T0, A0, Acc0} | Post0]} ->
case lists:splitwith(F, Acc0) of
{_, []} ->
Stack;
{Pre, [{T1, A1, Acc1} | Post1]} ->
[{T0, A0, [{T1, A1, Acc1 ++ lists:reverse(Pre)} | Post1]}
| Post0]
end;
_ ->
Stack
end;
{_Pre, [_T]} ->
destack(Stack);
{Pre, [T, {T0, A0, Acc0} | Post]} ->
[{T0, A0, [destack(Pre ++ [T]) | Acc0]} | Post]
end.
destack([{Tag, Attrs, Acc}]) ->
{Tag, Attrs, lists:reverse(Acc)};
destack([{T1, A1, Acc1}, {T0, A0, Acc0} | Rest]) ->
destack([{T0, A0, [{T1, A1, lists:reverse(Acc1)} | Acc0]} | Rest]).
is_singleton(<<"br">>) -> true;
is_singleton(<<"hr">>) -> true;
is_singleton(<<"img">>) -> true;
is_singleton(<<"input">>) -> true;
is_singleton(<<"base">>) -> true;
is_singleton(<<"meta">>) -> true;
is_singleton(<<"link">>) -> true;
is_singleton(<<"area">>) -> true;
is_singleton(<<"param">>) -> true;
is_singleton(<<"col">>) -> true;
is_singleton(_) -> false.
tokenize_data(B, S=#decoder{offset=O}) ->
tokenize_data(B, S, O, true).
tokenize_data(B, S=#decoder{offset=O}, Start, Whitespace) ->
case B of
<<_:O/binary, C, _/binary>> when (C =/= $< andalso C =/= $&) ->
tokenize_data(B, ?INC_CHAR(S, C), Start,
(Whitespace andalso ?IS_WHITESPACE(C)));
_ ->
Len = O - Start,
<<_:Start/binary, Data:Len/binary, _/binary>> = B,
{{data, Data, Whitespace}, S}
end.
tokenize_attributes(B, S) ->
tokenize_attributes(B, S, []).
tokenize_attributes(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary>> ->
{lists:reverse(Acc), S};
<<_:O/binary, C, _/binary>> when (C =:= $> orelse C =:= $/) ->
{lists:reverse(Acc), S};
<<_:O/binary, "?>", _/binary>> ->
{lists:reverse(Acc), S};
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
tokenize_attributes(B, ?INC_CHAR(S, C), Acc);
_ ->
{Attr, S1} = tokenize_literal(B, S),
{Value, S2} = tokenize_attr_value(Attr, B, S1),
tokenize_attributes(B, S2, [{Attr, Value} | Acc])
end.
tokenize_attr_value(Attr, B, S) ->
S1 = skip_whitespace(B, S),
O = S1#decoder.offset,
case B of
<<_:O/binary, "=", _/binary>> ->
S2 = skip_whitespace(B, ?INC_COL(S1)),
tokenize_quoted_or_unquoted_attr_value(B, S2);
_ ->
{Attr, S1}
end.
tokenize_quoted_or_unquoted_attr_value(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary>> ->
{ [], S };
<<_:O/binary, Q, _/binary>> when Q =:= ?QUOTE orelse
Q =:= ?SQUOTE ->
tokenize_quoted_attr_value(B, ?INC_COL(S), [], Q);
<<_:O/binary, _/binary>> ->
tokenize_unquoted_attr_value(B, S, [])
end.
tokenize_quoted_attr_value(B, S=#decoder{offset=O}, Acc, Q) ->
case B of
<<_:O/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(B, ?INC_COL(S)),
tokenize_quoted_attr_value(B, S1, [Data|Acc], Q);
<<_:O/binary, Q, _/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), ?INC_COL(S) };
<<_:O/binary, C, _/binary>> ->
tokenize_quoted_attr_value(B, ?INC_COL(S), [C|Acc], Q)
end.
tokenize_unquoted_attr_value(B, S=#decoder{offset=O}, Acc) ->
case B of
<<_:O/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(B, ?INC_COL(S)),
tokenize_unquoted_attr_value(B, S1, [Data|Acc]);
<<_:O/binary, $/, $>, _/binary>> ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, C, _/binary>> when ?PROBABLE_CLOSE(C) ->
{ iolist_to_binary(lists:reverse(Acc)), S };
<<_:O/binary, C, _/binary>> ->
tokenize_unquoted_attr_value(B, ?INC_COL(S), [C|Acc])
end.
skip_whitespace(B, S=#decoder{offset=O}) ->
case B of
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
skip_whitespace(B, ?INC_CHAR(S, C));
_ ->
S
end.
tokenize_literal(Bin, S=#decoder{offset=O}) ->
case Bin of
<<_:O/binary, C, _/binary>> when C =:= $>
orelse C =:= $/
orelse C =:= $= ->
0 chars .
{[C], ?INC_COL(S)};
_ ->
tokenize_literal(Bin, S, [])
end.
tokenize_literal(Bin, S=#decoder{offset=O}, Acc) ->
case Bin of
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(Bin, ?INC_COL(S)),
tokenize_literal(Bin, S1, [Data | Acc]);
<<_:O/binary, C, _/binary>> when not (?IS_WHITESPACE(C)
orelse C =:= $>
orelse C =:= $/
orelse C =:= $=) ->
tokenize_literal(Bin, ?INC_COL(S), [C | Acc]);
_ ->
{iolist_to_binary(string:to_lower(lists:reverse(Acc))), S}
end.
raw_qgt(Bin, S=#decoder{offset=O}) ->
raw_qgt(Bin, S, O).
raw_qgt(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, "?>", _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{Raw, ?ADV_COL(S, 2)};
<<_:O/binary, C, _/binary>> ->
raw_qgt(Bin, ?INC_CHAR(S, C), Start);
<<_:O/binary>> ->
<<_:Start/binary, Raw/binary>> = Bin,
{Raw, S}
end.
find_qgt(Bin, S=#decoder{offset=O}) ->
case Bin of
<<_:O/binary, "?>", _/binary>> ->
?ADV_COL(S, 2);
<<_:O/binary, ">", _/binary>> ->
?ADV_COL(S, 1);
<<_:O/binary, "/>", _/binary>> ->
?ADV_COL(S, 2);
<<_:O/binary>> ->
S
end.
find_gt(Bin, S) ->
find_gt(Bin, S, false).
find_gt(Bin, S=#decoder{offset=O}, HasSlash) ->
case Bin of
<<_:O/binary, $/, _/binary>> ->
find_gt(Bin, ?INC_COL(S), true);
<<_:O/binary, $>, _/binary>> ->
{?INC_COL(S), HasSlash};
<<_:O/binary, C, _/binary>> ->
find_gt(Bin, ?INC_CHAR(S, C), HasSlash);
_ ->
{S, HasSlash}
end.
tokenize_charref(Bin, S=#decoder{offset=O}) ->
try
tokenize_charref(Bin, S, O)
catch
throw:invalid_charref ->
{{data, <<"&">>, false}, S}
end.
tokenize_charref(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary>> ->
throw(invalid_charref);
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C)
orelse C =:= ?SQUOTE
orelse C =:= ?QUOTE
orelse C =:= $/
orelse C =:= $> ->
throw(invalid_charref);
<<_:O/binary, $;, _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
Data = case mochiweb_charref:charref(Raw) of
undefined ->
throw(invalid_charref);
Unichar when is_integer(Unichar) ->
mochiutf8:codepoint_to_bytes(Unichar);
Unichars when is_list(Unichars) ->
unicode:characters_to_binary(Unichars)
end,
{{data, Data, false}, ?INC_COL(S)};
_ ->
tokenize_charref(Bin, ?INC_COL(S), Start)
end.
tokenize_doctype(Bin, S) ->
tokenize_doctype(Bin, S, []).
tokenize_doctype(Bin, S=#decoder{offset=O}, Acc) ->
case Bin of
<<_:O/binary>> ->
{{doctype, lists:reverse(Acc)}, S};
<<_:O/binary, $>, _/binary>> ->
{{doctype, lists:reverse(Acc)}, ?INC_COL(S)};
<<_:O/binary, C, _/binary>> when ?IS_WHITESPACE(C) ->
tokenize_doctype(Bin, ?INC_CHAR(S, C), Acc);
_ ->
{Word, S1} = tokenize_word_or_literal(Bin, S),
tokenize_doctype(Bin, S1, [Word | Acc])
end.
tokenize_word_or_literal(Bin, S=#decoder{offset=O}) ->
case Bin of
<<_:O/binary, C, _/binary>> when C =:= ?QUOTE orelse C =:= ?SQUOTE ->
tokenize_word(Bin, ?INC_COL(S), C);
<<_:O/binary, C, _/binary>> when not ?IS_WHITESPACE(C) ->
tokenize_literal(Bin, S)
end.
tokenize_word(Bin, S, Quote) ->
tokenize_word(Bin, S, Quote, []).
tokenize_word(Bin, S=#decoder{offset=O}, Quote, Acc) ->
case Bin of
<<_:O/binary>> ->
{iolist_to_binary(lists:reverse(Acc)), S};
<<_:O/binary, Quote, _/binary>> ->
{iolist_to_binary(lists:reverse(Acc)), ?INC_COL(S)};
<<_:O/binary, $&, _/binary>> ->
{{data, Data, false}, S1} = tokenize_charref(Bin, ?INC_COL(S)),
tokenize_word(Bin, S1, Quote, [Data | Acc]);
<<_:O/binary, C, _/binary>> ->
tokenize_word(Bin, ?INC_CHAR(S, C), Quote, [C | Acc])
end.
tokenize_cdata(Bin, S=#decoder{offset=O}) ->
tokenize_cdata(Bin, S, O).
tokenize_cdata(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, "]]>", _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{data, Raw, false}, ?ADV_COL(S, 3)};
<<_:O/binary, C, _/binary>> ->
tokenize_cdata(Bin, ?INC_CHAR(S, C), Start);
_ ->
<<_:O/binary, Raw/binary>> = Bin,
{{data, Raw, false}, S}
end.
tokenize_comment(Bin, S=#decoder{offset=O}) ->
tokenize_comment(Bin, S, O).
tokenize_comment(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, "-->", _/binary>> ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{comment, Raw}, ?ADV_COL(S, 3)};
<<_:O/binary, C, _/binary>> ->
tokenize_comment(Bin, ?INC_CHAR(S, C), Start);
<<_:Start/binary, Raw/binary>> ->
{{comment, Raw}, S}
end.
tokenize_script(Bin, S=#decoder{offset=O}) ->
tokenize_script(Bin, S, O).
tokenize_script(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, $<, $/, SS, CC, RR, II, PP, TT, ZZ, _/binary>>
when (SS =:= $s orelse SS =:= $S) andalso
(CC =:= $c orelse CC =:= $C) andalso
(RR =:= $r orelse RR =:= $R) andalso
(II =:= $i orelse II =:= $I) andalso
(PP =:= $p orelse PP =:= $P) andalso
(TT=:= $t orelse TT =:= $T) andalso
?PROBABLE_CLOSE(ZZ) ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{data, Raw, false}, S};
<<_:O/binary, C, _/binary>> ->
tokenize_script(Bin, ?INC_CHAR(S, C), Start);
<<_:Start/binary, Raw/binary>> ->
{{data, Raw, false}, S}
end.
tokenize_textarea(Bin, S=#decoder{offset=O}) ->
tokenize_textarea(Bin, S, O).
tokenize_textarea(Bin, S=#decoder{offset=O}, Start) ->
case Bin of
<<_:O/binary, $<, $/, TT, EE, XX, TT2, AA, RR, EE2, AA2, ZZ, _/binary>>
when (TT =:= $t orelse TT =:= $T) andalso
(EE =:= $e orelse EE =:= $E) andalso
(XX =:= $x orelse XX =:= $X) andalso
(TT2 =:= $t orelse TT2 =:= $T) andalso
(AA =:= $a orelse AA =:= $A) andalso
(RR =:= $r orelse RR =:= $R) andalso
(EE2 =:= $e orelse EE2 =:= $E) andalso
(AA2 =:= $a orelse AA2 =:= $A) andalso
?PROBABLE_CLOSE(ZZ) ->
Len = O - Start,
<<_:Start/binary, Raw:Len/binary, _/binary>> = Bin,
{{data, Raw, false}, S};
<<_:O/binary, C, _/binary>> ->
tokenize_textarea(Bin, ?INC_CHAR(S, C), Start);
<<_:Start/binary, Raw/binary>> ->
{{data, Raw, false}, S}
end.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
to_html_test() ->
?assertEqual(
<<"<html><head><title>hey!</title></head><body><p class=\"foo\">what's up<br /></p><div>sucka</div>RAW!<!-- comment! --></body></html>">>,
iolist_to_binary(
to_html({html, [],
[{<<"head">>, [],
[{title, <<"hey!">>}]},
{body, [],
[{p, [{class, foo}], [<<"what's">>, <<" up">>, {br}]},
{'div', <<"sucka">>},
{'=', <<"RAW!">>},
{comment, <<" comment! ">>}]}]}))),
?assertEqual(
<<"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"-transitional.dtd\">">>,
iolist_to_binary(
to_html({doctype,
[<<"html">>, <<"PUBLIC">>,
<<"-//W3C//DTD XHTML 1.0 Transitional//EN">>,
<<"-transitional.dtd">>]}))),
?assertEqual(
<<"<html><?xml:namespace prefix=\"o\" ns=\"urn:schemas-microsoft-com:office:office\"?></html>">>,
iolist_to_binary(
to_html({<<"html">>,[],
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}]}))),
ok.
escape_test() ->
?assertEqual(
<<"&quot;\"word ><<up!&quot;">>,
escape(<<""\"word ><<up!"">>)),
?assertEqual(
<<"&quot;\"word ><<up!&quot;">>,
escape(""\"word ><<up!"")),
?assertEqual(
<<"&quot;\"word ><<up!&quot;">>,
escape('"\"word ><<up!"')),
ok.
escape_attr_test() ->
?assertEqual(
<<"&quot;"word ><<up!&quot;">>,
escape_attr(<<""\"word ><<up!"">>)),
?assertEqual(
<<"&quot;"word ><<up!&quot;">>,
escape_attr(""\"word ><<up!"")),
?assertEqual(
<<"&quot;"word ><<up!&quot;">>,
escape_attr('"\"word ><<up!"')),
?assertEqual(
<<"12345">>,
escape_attr(12345)),
?assertEqual(
<<"1.5">>,
escape_attr(1.5)),
ok.
tokens_test() ->
?assertEqual(
[{start_tag, <<"foo">>, [{<<"bar">>, <<"baz">>},
{<<"wibble">>, <<"wibble">>},
{<<"alice">>, <<"bob">>}], true}],
tokens(<<"<foo bar=baz wibble='wibble' alice=\"bob\"/>">>)),
?assertEqual(
[{start_tag, <<"foo">>, [{<<"bar">>, <<"baz">>},
{<<"wibble">>, <<"wibble">>},
{<<"alice">>, <<"bob">>}], true}],
tokens(<<"<foo bar=baz wibble='wibble' alice=bob/>">>)),
?assertEqual(
[{comment, <<"[if lt IE 7]>\n<style type=\"text/css\">\n.no_ie { display: none; }\n</style>\n<![endif]">>}],
tokens(<<"<!--[if lt IE 7]>\n<style type=\"text/css\">\n.no_ie { display: none; }\n</style>\n<![endif]-->">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type=\"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type =\"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type = \"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"script">>, [{<<"type">>, <<"text/javascript">>}], false},
{data, <<" A= B <= C ">>, false},
{end_tag, <<"script">>}],
tokens(<<"<script type= \"text/javascript\"> A= B <= C </script>">>)),
?assertEqual(
[{start_tag, <<"textarea">>, [], false},
{data, <<"<html></body>">>, false},
{end_tag, <<"textarea">>}],
tokens(<<"<textarea><html></body></textarea>">>)),
?assertEqual(
[{start_tag, <<"textarea">>, [], false},
{data, <<"<html></body></textareaz>">>, false}],
tokens(<<"<textarea ><html></body></textareaz>">>)),
?assertEqual(
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}],
tokens(<<"<?xml:namespace prefix=\"o\" ns=\"urn:schemas-microsoft-com:office:office\"?>">>)),
?assertEqual(
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}],
tokens(<<"<?xml:namespace prefix=o ns=urn:schemas-microsoft-com:office:office \n?>">>)),
?assertEqual(
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}],
tokens(<<"<?xml:namespace prefix=o ns=urn:schemas-microsoft-com:office:office">>)),
?assertEqual(
[{data, <<"<">>, false}],
tokens(<<"<">>)),
?assertEqual(
[{data, <<"not html ">>, false},
{data, <<"< at all">>, false}],
tokens(<<"not html < at all">>)),
ok.
parse_test() ->
D0 = <<"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"\">
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
<title>Foo</title>
<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/rel/dojo/resources/dojo.css\" media=\"screen\">
<link rel=\"stylesheet\" type=\"text/css\" href=\"/static/foo.css\" media=\"screen\">
<!--[if lt IE 7]>
<style type=\"text/css\">
.no_ie { display: none; }
</style>
<![endif]-->
<link rel=\"icon\" href=\"/static/images/favicon.ico\" type=\"image/x-icon\">
<link rel=\"shortcut icon\" href=\"/static/images/favicon.ico\" type=\"image/x-icon\">
</head>
<body id=\"home\" class=\"tundra\"><![CDATA[<<this<!-- is -->CDATA>>]]></body>
</html>">>,
?assertEqual(
{<<"html">>, [],
[{<<"head">>, [],
[{<<"meta">>,
[{<<"http-equiv">>,<<"Content-Type">>},
{<<"content">>,<<"text/html; charset=UTF-8">>}],
[]},
{<<"title">>,[],[<<"Foo">>]},
{<<"link">>,
[{<<"rel">>,<<"stylesheet">>},
{<<"type">>,<<"text/css">>},
{<<"href">>,<<"/static/rel/dojo/resources/dojo.css">>},
{<<"media">>,<<"screen">>}],
[]},
{<<"link">>,
[{<<"rel">>,<<"stylesheet">>},
{<<"type">>,<<"text/css">>},
{<<"href">>,<<"/static/foo.css">>},
{<<"media">>,<<"screen">>}],
[]},
{comment,<<"[if lt IE 7]>\n <style type=\"text/css\">\n .no_ie { display: none; }\n </style>\n <![endif]">>},
{<<"link">>,
[{<<"rel">>,<<"icon">>},
{<<"href">>,<<"/static/images/favicon.ico">>},
{<<"type">>,<<"image/x-icon">>}],
[]},
{<<"link">>,
[{<<"rel">>,<<"shortcut icon">>},
{<<"href">>,<<"/static/images/favicon.ico">>},
{<<"type">>,<<"image/x-icon">>}],
[]}]},
{<<"body">>,
[{<<"id">>,<<"home">>},
{<<"class">>,<<"tundra">>}],
[<<"<<this<!-- is -->CDATA>>">>]}]},
parse(D0)),
?assertEqual(
{<<"html">>,[],
[{pi, <<"xml:namespace">>,
[{<<"prefix">>,<<"o">>},
{<<"ns">>,<<"urn:schemas-microsoft-com:office:office">>}]}]},
parse(
<<"<html><?xml:namespace prefix=\"o\" ns=\"urn:schemas-microsoft-com:office:office\"?></html>">>)),
?assertEqual(
{<<"html">>, [],
[{<<"dd">>, [], [<<"foo">>]},
{<<"dt">>, [], [<<"bar">>]}]},
parse(<<"<html><dd>foo<dt>bar</html>">>)),
Singleton sadness
?assertEqual(
{<<"html">>, [],
[{<<"link">>, [], []},
<<"foo">>,
{<<"br">>, [], []},
<<"bar">>]},
parse(<<"<html><link>foo<br>bar</html>">>)),
?assertEqual(
{<<"html">>, [],
[{<<"link">>, [], [<<"foo">>,
{<<"br">>, [], []},
<<"bar">>]}]},
parse(<<"<html><link>foo<br>bar</link></html>">>)),
?assertEqual(
{<<"html">>, [],
[{<<"head">>, [], [<<"foo">>,
{<<"br">>, [], []},
<<"BAR">>]},
{<<"body">>, [{<<"class">>, <<"">>}, {<<"bgcolor">>, <<"#Aa01fF">>}], []}
]},
parse(<<"<html><Head>foo<bR>BAR</head><body Class=\"\" bgcolor=\"#Aa01fF\"></BODY></html>">>)),
ok.
exhaustive_is_singleton_test() ->
T = mochiweb_cover:clause_lookup_table(?MODULE, is_singleton),
[?assertEqual(V, is_singleton(K)) || {K, V} <- T].
tokenize_attributes_test() ->
?assertEqual(
{<<"foo">>,
[{<<"bar">>, <<"b\"az">>},
{<<"wibble">>, <<"wibble">>},
{<<"taco", 16#c2, 16#a9>>, <<"bell">>},
{<<"quux">>, <<"quux">>}],
[]},
parse(<<"<foo bar=\"b"az\" wibble taco©=bell quux">>)),
ok.
tokens2_test() ->
D0 = <<"<channel><title>from __future__ import *</title><link></link><description>Bob's Rants</description></channel>">>,
?assertEqual(
[{start_tag,<<"channel">>,[],false},
{start_tag,<<"title">>,[],false},
{data,<<"from __future__ import *">>,false},
{end_tag,<<"title">>},
{start_tag,<<"link">>,[],true},
{data,<<"">>,false},
{end_tag,<<"link">>},
{start_tag,<<"description">>,[],false},
{data,<<"Bob's Rants">>,false},
{end_tag,<<"description">>},
{end_tag,<<"channel">>}],
tokens(D0)),
ok.
to_tokens_test() ->
?assertEqual(
[{start_tag, <<"p">>, [{class, 1}], false},
{end_tag, <<"p">>}],
to_tokens({p, [{class, 1}], []})),
?assertEqual(
[{start_tag, <<"p">>, [], false},
{end_tag, <<"p">>}],
to_tokens({p})),
?assertEqual(
[{'=', <<"data">>}],
to_tokens({'=', <<"data">>})),
?assertEqual(
[{comment, <<"comment">>}],
to_tokens({comment, <<"comment">>})),
?assertEqual(
[{start_tag, <<"html">>, [], false},
{start_tag, <<"p">>, [{class, 1}], false},
{end_tag, <<"p">>},
{end_tag, <<"html">>}],
to_tokens({html, [{p, [{class, 1}]}]})),
ok.
parse2_test() ->
D0 = <<"<channel><title>from __future__ import *</title><link><br>foo</link><description>Bob's Rants</description></channel>">>,
?assertEqual(
{<<"channel">>,[],
[{<<"title">>,[],[<<"from __future__ import *">>]},
{<<"link">>,[],[
<<"">>,
{<<"br">>,[],[]},
<<"foo">>]},
{<<"description">>,[],[<<"Bob's Rants">>]}]},
parse(D0)),
ok.
parse_tokens_test() ->
D0 = [{doctype,[<<"HTML">>,<<"PUBLIC">>,<<"-//W3C//DTD HTML 4.01 Transitional//EN">>]},
{data,<<"\n">>,true},
{start_tag,<<"html">>,[],false}],
?assertEqual(
{<<"html">>, [], []},
parse_tokens(D0)),
D1 = D0 ++ [{end_tag, <<"html">>}],
?assertEqual(
{<<"html">>, [], []},
parse_tokens(D1)),
D2 = D0 ++ [{start_tag, <<"body">>, [], false}],
?assertEqual(
{<<"html">>, [], [{<<"body">>, [], []}]},
parse_tokens(D2)),
D3 = D0 ++ [{start_tag, <<"head">>, [], false},
{end_tag, <<"head">>},
{start_tag, <<"body">>, [], false}],
?assertEqual(
{<<"html">>, [], [{<<"head">>, [], []}, {<<"body">>, [], []}]},
parse_tokens(D3)),
D4 = D3 ++ [{data,<<"\n">>,true},
{start_tag,<<"div">>,[{<<"class">>,<<"a">>}],false},
{start_tag,<<"a">>,[{<<"name">>,<<"#anchor">>}],false},
{end_tag,<<"a">>},
{end_tag,<<"div">>},
{start_tag,<<"div">>,[{<<"class">>,<<"b">>}],false},
{start_tag,<<"div">>,[{<<"class">>,<<"c">>}],false},
{end_tag,<<"div">>},
{end_tag,<<"div">>}],
?assertEqual(
{<<"html">>, [],
[{<<"head">>, [], []},
{<<"body">>, [],
[{<<"div">>, [{<<"class">>, <<"a">>}], [{<<"a">>, [{<<"name">>, <<"#anchor">>}], []}]},
{<<"div">>, [{<<"class">>, <<"b">>}], [{<<"div">>, [{<<"class">>, <<"c">>}], []}]}
]}]},
parse_tokens(D4)),
D5 = [{start_tag,<<"html">>,[],false},
{data,<<"\n">>,true},
{data,<<"boo">>,false},
{data,<<"hoo">>,false},
{data,<<"\n">>,true},
{end_tag,<<"html">>}],
?assertEqual(
{<<"html">>, [], [<<"\nboohoo\n">>]},
parse_tokens(D5)),
D6 = [{start_tag,<<"html">>,[],false},
{data,<<"\n">>,true},
{data,<<"\n">>,true},
{end_tag,<<"html">>}],
?assertEqual(
{<<"html">>, [], []},
parse_tokens(D6)),
D7 = [{start_tag,<<"html">>,[],false},
{start_tag,<<"ul">>,[],false},
{start_tag,<<"li">>,[],false},
{data,<<"word">>,false},
{start_tag,<<"li">>,[],false},
{data,<<"up">>,false},
{end_tag,<<"li">>},
{start_tag,<<"li">>,[],false},
{data,<<"fdsa">>,false},
{start_tag,<<"br">>,[],true},
{data,<<"asdf">>,false},
{end_tag,<<"ul">>},
{end_tag,<<"html">>}],
?assertEqual(
{<<"html">>, [],
[{<<"ul">>, [],
[{<<"li">>, [], [<<"word">>]},
{<<"li">>, [], [<<"up">>]},
{<<"li">>, [], [<<"fdsa">>,{<<"br">>, [], []}, <<"asdf">>]}]}]},
parse_tokens(D7)),
ok.
destack_test() ->
{<<"a">>, [], []} =
destack([{<<"a">>, [], []}]),
{<<"a">>, [], [{<<"b">>, [], []}]} =
destack([{<<"b">>, [], []}, {<<"a">>, [], []}]),
{<<"a">>, [], [{<<"b">>, [], [{<<"c">>, [], []}]}]} =
destack([{<<"c">>, [], []}, {<<"b">>, [], []}, {<<"a">>, [], []}]),
[{<<"a">>, [], [{<<"b">>, [], [{<<"c">>, [], []}]}]}] =
destack(<<"b">>,
[{<<"c">>, [], []}, {<<"b">>, [], []}, {<<"a">>, [], []}]),
[{<<"b">>, [], [{<<"c">>, [], []}]}, {<<"a">>, [], []}] =
destack(<<"c">>,
[{<<"c">>, [], []}, {<<"b">>, [], []},{<<"a">>, [], []}]),
ok.
doctype_test() ->
?assertEqual(
{<<"html">>,[],[{<<"head">>,[],[]}]},
mochiweb_html:parse("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"\">"
"<html><head></head></body></html>")),
?assertEqual(
{<<"html">>,[],[{<<"head">>,[],[]}]},
mochiweb_html:parse("<html>"
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"\">"
"<head></head></body></html>")),
?assertEqual(
{<<"html">>,[],[{<<"head">>,[],[]}]},
mochiweb_html:parse("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"/>"
"<html>"
"<head></head></body></html>")),
ok.
dumb_br_test() ->
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>]},
mochiweb_html:parse("<div><br/><br/>z</br/></br/></div>")),
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>]},
mochiweb_html:parse("<div><br><br>z</br/></br/></div>")),
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>, {<<"br">>, [], []}, {<<"br">>, [], []}]},
mochiweb_html:parse("<div><br><br>z<br/><br/></div>")),
?assertEqual(
{<<"div">>,[],[{<<"br">>, [], []}, {<<"br">>, [], []}, <<"z">>]},
mochiweb_html:parse("<div><br><br>z</br></br></div>")).
php_test() ->
?assertEqual(
[{pi, <<"php\n">>}],
mochiweb_html:tokens(
"<?php\n?>")),
?assertEqual(
{<<"div">>, [], [{pi, <<"php\n">>}]},
mochiweb_html:parse(
"<div><?php\n?></div>")),
ok.
parse_unquoted_attr_test() ->
D0 = <<"<html><img src=/images/icon.png/></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png">> } ], [] }
]},
mochiweb_html:parse(D0)),
D1 = <<"<html><img src=/images/icon.png></img></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png">> } ], [] }
]},
mochiweb_html:parse(D1)),
D2 = <<"<html><img src=/images/icon>.png width=100></img></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon>.png">> }, { <<"width">>, <<"100">> } ], [] }
]},
mochiweb_html:parse(D2)),
ok.
parse_quoted_attr_test() ->
D0 = <<"<html><img src='/images/icon.png'></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png">> } ], [] }
]},
mochiweb_html:parse(D0)),
D1 = <<"<html><img src=\"/images/icon.png'></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon.png'></html>">> } ], [] }
]},
mochiweb_html:parse(D1)),
D2 = <<"<html><img src=\"/images/icon>.png\"></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"img">>, [ { <<"src">>, <<"/images/icon>.png">> } ], [] }
]},
mochiweb_html:parse(D2)),
D3 = <<"<html><a href=\"#\" onclick=\"javascript: test(1,\ntrue);\"></html>">>,
?assertEqual(
{<<"html">>,[],[
{ <<"a">>, [ { <<"href">>, <<"#">> }, {<<"onclick">>, <<"javascript: test(1,\ntrue);">>} ], [] }
]},
mochiweb_html:parse(D3)),
ok.
parse_missing_attr_name_test() ->
D0 = <<"<html =black></html>">>,
?assertEqual(
{<<"html">>, [ { <<"=">>, <<"=">> }, { <<"black">>, <<"black">> } ], [] },
mochiweb_html:parse(D0)),
ok.
parse_broken_pi_test() ->
D0 = <<"<html><?xml:namespace prefix = o ns = \"urn:schemas-microsoft-com:office:office\" /></html>">>,
?assertEqual(
{<<"html">>, [], [
{ pi, <<"xml:namespace">>, [ { <<"prefix">>, <<"o">> },
{ <<"ns">>, <<"urn:schemas-microsoft-com:office:office">> } ] }
] },
mochiweb_html:parse(D0)),
ok.
parse_funny_singletons_test() ->
D0 = <<"<html><input><input>x</input></input></html>">>,
?assertEqual(
{<<"html">>, [], [
{ <<"input">>, [], [] },
{ <<"input">>, [], [ <<"x">> ] }
] },
mochiweb_html:parse(D0)),
ok.
to_html_singleton_test() ->
D0 = <<"<link />">>,
T0 = {<<"link">>,[],[]},
?assertEqual(D0, iolist_to_binary(to_html(T0))),
D1 = <<"<head><link /></head>">>,
T1 = {<<"head">>,[],[{<<"link">>,[],[]}]},
?assertEqual(D1, iolist_to_binary(to_html(T1))),
D2 = <<"<head><link /><link /></head>">>,
T2 = {<<"head">>,[],[{<<"link">>,[],[]}, {<<"link">>,[],[]}]},
?assertEqual(D2, iolist_to_binary(to_html(T2))),
D3 = <<"<head><link /></head>">>,
T3 = {<<"head">>,[],[{<<"link">>,[],[<<"funny">>]}]},
?assertEqual(D3, iolist_to_binary(to_html(T3))),
D4 = <<"<link />">>,
T4 = {<<"link">>,[],[<<"funny">>]},
?assertEqual(D4, iolist_to_binary(to_html(T4))),
ok.
parse_amp_test_() ->
[?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[{<<"onload">>,<<"javascript:A('1&2')">>}],[]}]},
mochiweb_html:parse("<html><body onload=\"javascript:A('1&2')\"></body></html>")),
?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[{<<"onload">>,<<"javascript:A('1& 2')">>}],[]}]},
mochiweb_html:parse("<html><body onload=\"javascript:A('1& 2')\"></body></html>")),
?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[],[<<"& ">>]}]},
mochiweb_html:parse("<html><body>& </body></html>")),
?_assertEqual(
{<<"html">>,[],
[{<<"body">>,[],[<<"&">>]}]},
mochiweb_html:parse("<html><body>&</body></html>"))].
parse_unescaped_lt_test() ->
D1 = <<"<div> < < <a href=\"/\">Back</a></div>">>,
?assertEqual(
{<<"div">>, [], [<<" < < ">>, {<<"a">>, [{<<"href">>, <<"/">>}],
[<<"Back">>]}]},
mochiweb_html:parse(D1)),
D2 = <<"<div> << <a href=\"/\">Back</a></div>">>,
?assertEqual(
{<<"div">>, [], [<<" << ">>, {<<"a">>, [{<<"href">>, <<"/">>}],
[<<"Back">>]}]},
mochiweb_html:parse(D2)).
-endif.
|
616a181916dbb94ae00ee5e8a6201878828b41d3524134a0495bddd6ea322233 | camllight/camllight | asynt.mli | value analyse_phrase:
alex__lexème stream -> langage__phrase_logo
and analyse_programme:
alex__lexème stream -> langage__programme_logo;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/examples/minilogo/asynt.mli | ocaml | value analyse_phrase:
alex__lexème stream -> langage__phrase_logo
and analyse_programme:
alex__lexème stream -> langage__programme_logo;;
| |
e41332557f51bf026f7f43d06ef69577e163ac6fcf4bc802e2e2fd4e74f9bf0e | reanimate/reanimate | doc_bellS.hs | #!/usr/bin/env stack
-- stack runghc --package reanimate
module Main(main) where
import Reanimate
import Reanimate.Builtin.Documentation
main :: IO ()
main = reanimate $ docEnv $ signalA (bellS 2) drawProgress
| null | https://raw.githubusercontent.com/reanimate/reanimate/5ea023980ff7f488934d40593cc5069f5fd038b0/examples/doc_bellS.hs | haskell | stack runghc --package reanimate | #!/usr/bin/env stack
module Main(main) where
import Reanimate
import Reanimate.Builtin.Documentation
main :: IO ()
main = reanimate $ docEnv $ signalA (bellS 2) drawProgress
|
48892f9727c041420902e80aa1b2cf631e290ed54d43cfe06ed83504375726f5 | ghollisjr/cl-ana | array-utils.lisp | cl - ana is a Common Lisp data analysis library .
Copyright 2021
;;;;
This file is part of cl - ana .
;;;;
;;;; cl-ana is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; cl-ana is distributed in the hope that it will be useful, but
;;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; General Public License for more details.
;;;;
You should have received a copy of the GNU General Public License
;;;; along with cl-ana. If not, see </>.
;;;;
You may contact ( me ! ) via email at
;;;;
(in-package :cl-ana.array-utils)
;; Looping over array
(defmacro for-array (binding dimensions &body body)
"Iterates over every possible index for an array with supplied
dimensions. If binding is an atom, then the index list will be set to
that variable as a list. If it is a list of symbols, then each symbol
will be bound to its corresponding element from the Cartesian product
element."
(alexandria:with-gensyms (sets dims setdims nsets
index
continue
incr dim)
`(let* ((,dims ,dimensions)
(,nsets (if (atom ,dims)
1
(length ,dims)))
(,setdims (if (atom ,dims)
(vector ,dims)
(map 'vector #'identity ,dims)))
(,index (make-array ,nsets :initial-element 0))
(,continue t))
(loop
while ,continue
do
;; execute body
,(if (atom binding)
`(let ((,binding (map 'list #'identity
,index)))
,@body)
`(destructuring-bind ,binding
(map 'list #'identity
,index)
,@body))
;; iterate
(let* ((,incr t)
(,dim 0))
(loop
while ,incr
do
(if (>= ,dim ,nsets)
(progn
(setf ,incr nil)
(setf ,continue nil))
(progn
(incf (aref ,index ,dim))
(if (>= (aref ,index ,dim)
(aref ,setdims ,dim))
(progn
(setf (aref ,index ,dim) 0)
(incf ,dim))
(setf ,incr nil))))))))))
(defun map-array (array fn)
"Map for arrays. fn should be of the form (lambda (value &rest
indices)...)"
(let* ((result (make-array (array-dimensions array))))
(for-array indices (array-dimensions array)
(setf (apply #'aref result indices)
(apply fn
(apply #'aref array indices)
indices)))
result))
| null | https://raw.githubusercontent.com/ghollisjr/cl-ana/8e8abc17e3d2f8e597f336d7b0f5df39ef2406ee/array-utils/array-utils.lisp | lisp |
cl-ana is free software: you can redistribute it and/or modify it
(at your option) any later version.
cl-ana is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
along with cl-ana. If not, see </>.
Looping over array
execute body
iterate | cl - ana is a Common Lisp data analysis library .
Copyright 2021
This file is part of cl - ana .
under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
You may contact ( me ! ) via email at
(in-package :cl-ana.array-utils)
(defmacro for-array (binding dimensions &body body)
"Iterates over every possible index for an array with supplied
dimensions. If binding is an atom, then the index list will be set to
that variable as a list. If it is a list of symbols, then each symbol
will be bound to its corresponding element from the Cartesian product
element."
(alexandria:with-gensyms (sets dims setdims nsets
index
continue
incr dim)
`(let* ((,dims ,dimensions)
(,nsets (if (atom ,dims)
1
(length ,dims)))
(,setdims (if (atom ,dims)
(vector ,dims)
(map 'vector #'identity ,dims)))
(,index (make-array ,nsets :initial-element 0))
(,continue t))
(loop
while ,continue
do
,(if (atom binding)
`(let ((,binding (map 'list #'identity
,index)))
,@body)
`(destructuring-bind ,binding
(map 'list #'identity
,index)
,@body))
(let* ((,incr t)
(,dim 0))
(loop
while ,incr
do
(if (>= ,dim ,nsets)
(progn
(setf ,incr nil)
(setf ,continue nil))
(progn
(incf (aref ,index ,dim))
(if (>= (aref ,index ,dim)
(aref ,setdims ,dim))
(progn
(setf (aref ,index ,dim) 0)
(incf ,dim))
(setf ,incr nil))))))))))
(defun map-array (array fn)
"Map for arrays. fn should be of the form (lambda (value &rest
indices)...)"
(let* ((result (make-array (array-dimensions array))))
(for-array indices (array-dimensions array)
(setf (apply #'aref result indices)
(apply fn
(apply #'aref array indices)
indices)))
result))
|
660ac67026e132325083c75d4cdb31e0d826bb7bb418811ca1cd05cad2300d6c | input-output-hk/plutus | Machines.hs | -- editorconfig-checker-disable-file
# LANGUAGE TypeFamilies #
module Evaluation.Machines
( test_machines
)
where
import GHC.Exts (fromString)
import PlutusCore
import PlutusCore.Evaluation.Machine.Ck
import PlutusCore.Evaluation.Machine.ExBudgetingDefaults
import PlutusCore.Evaluation.Machine.Exception
import PlutusCore.Generators.Hedgehog.Interesting
import PlutusCore.Generators.Hedgehog.Test
import PlutusCore.Pretty
import Test.Tasty
import Test.Tasty.Hedgehog
testMachine
:: (uni ~ DefaultUni, fun ~ DefaultFun, PrettyPlc internal)
=> String
-> (Term TyName Name uni fun () ->
Either (EvaluationException user internal (Term TyName Name uni fun ())) (Term TyName Name uni fun ()))
-> TestTree
testMachine machine eval =
testGroup machine $ fromInterestingTermGens $ \name ->
testPropertyNamed name (fromString name) . propEvaluate eval
test_machines :: TestTree
test_machines = testGroup
"machines"
[ testMachine "CK" $ evaluateCkNoEmit defaultBuiltinsRuntime
]
| null | https://raw.githubusercontent.com/input-output-hk/plutus/78402fb44148ce97a0a30efe406ba431fc49006c/plutus-core/plutus-core/test/Evaluation/Machines.hs | haskell | editorconfig-checker-disable-file | # LANGUAGE TypeFamilies #
module Evaluation.Machines
( test_machines
)
where
import GHC.Exts (fromString)
import PlutusCore
import PlutusCore.Evaluation.Machine.Ck
import PlutusCore.Evaluation.Machine.ExBudgetingDefaults
import PlutusCore.Evaluation.Machine.Exception
import PlutusCore.Generators.Hedgehog.Interesting
import PlutusCore.Generators.Hedgehog.Test
import PlutusCore.Pretty
import Test.Tasty
import Test.Tasty.Hedgehog
testMachine
:: (uni ~ DefaultUni, fun ~ DefaultFun, PrettyPlc internal)
=> String
-> (Term TyName Name uni fun () ->
Either (EvaluationException user internal (Term TyName Name uni fun ())) (Term TyName Name uni fun ()))
-> TestTree
testMachine machine eval =
testGroup machine $ fromInterestingTermGens $ \name ->
testPropertyNamed name (fromString name) . propEvaluate eval
test_machines :: TestTree
test_machines = testGroup
"machines"
[ testMachine "CK" $ evaluateCkNoEmit defaultBuiltinsRuntime
]
|
5346dca9e79daf6893c02dc2fc3ed57b81f81f99375357ae9dcaaea10c036699 | ghc/packages-Cabal | FilePath.hs | # LANGUAGE CPP #
# OPTIONS_GHC -fno - warn - unused - imports #
module Distribution.Compat.FilePath
( isExtensionOf
, stripExtension
) where
import Data.List ( isSuffixOf, stripPrefix )
import System.FilePath
#if !MIN_VERSION_filepath(1,4,2)
isExtensionOf :: String -> FilePath -> Bool
isExtensionOf ext@('.':_) = isSuffixOf ext . takeExtensions
isExtensionOf ext = isSuffixOf ('.':ext) . takeExtensions
#endif
#if !MIN_VERSION_filepath(1,4,1)
stripExtension :: String -> FilePath -> Maybe FilePath
stripExtension [] path = Just path
stripExtension ext@(x:_) path = stripSuffix dotExt path
where
dotExt = if isExtSeparator x then ext else '.':ext
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
stripSuffix xs ys = fmap reverse $ stripPrefix (reverse xs) (reverse ys)
#endif
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Distribution/Compat/FilePath.hs | haskell | # LANGUAGE CPP #
# OPTIONS_GHC -fno - warn - unused - imports #
module Distribution.Compat.FilePath
( isExtensionOf
, stripExtension
) where
import Data.List ( isSuffixOf, stripPrefix )
import System.FilePath
#if !MIN_VERSION_filepath(1,4,2)
isExtensionOf :: String -> FilePath -> Bool
isExtensionOf ext@('.':_) = isSuffixOf ext . takeExtensions
isExtensionOf ext = isSuffixOf ('.':ext) . takeExtensions
#endif
#if !MIN_VERSION_filepath(1,4,1)
stripExtension :: String -> FilePath -> Maybe FilePath
stripExtension [] path = Just path
stripExtension ext@(x:_) path = stripSuffix dotExt path
where
dotExt = if isExtSeparator x then ext else '.':ext
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
stripSuffix xs ys = fmap reverse $ stripPrefix (reverse xs) (reverse ys)
#endif
| |
f5337ea57ec6633329497fd17c7c551cffbfe2f1ec4ef8e985f16778452071e3 | con-kitty/categorifier-c | KBits.hs | -- | Higher-kinded version of 'Data.Bits.Bits'.
module Categorifier.C.KTypes.KBits
( KBits (..),
)
where
import Data.Proxy (Proxy (..))
class KBits f a where
testBit :: f a -> Int -> f Bool
setBitTo :: f a -> Int -> f Bool -> f a
zeroBits :: f a
instance KBits Proxy a where
testBit Proxy _ = Proxy
setBitTo Proxy _ Proxy = Proxy
zeroBits = Proxy
| null | https://raw.githubusercontent.com/con-kitty/categorifier-c/a34ff2603529b4da7ad6ffe681dad095f102d1b9/Categorifier/C/KTypes/KBits.hs | haskell | | Higher-kinded version of 'Data.Bits.Bits'. | module Categorifier.C.KTypes.KBits
( KBits (..),
)
where
import Data.Proxy (Proxy (..))
class KBits f a where
testBit :: f a -> Int -> f Bool
setBitTo :: f a -> Int -> f Bool -> f a
zeroBits :: f a
instance KBits Proxy a where
testBit Proxy _ = Proxy
setBitTo Proxy _ Proxy = Proxy
zeroBits = Proxy
|
7fea4344d3d3dfacdb2b3802cbacadcea656dc8ab2626732245fead244357909 | atgreen/lisp-openshift | tests.lisp | (in-package #:trivial-backtrace-test)
(deftestsuite generates-backtrace (trivial-backtrace-test)
())
(addtest (generates-backtrace)
test-1
(let ((output nil))
(handler-case
(let ((x 1))
(let ((y (- x (expt 1024 0))))
(/ 2 y)))
(error (c)
(setf output (print-backtrace c :output nil))))
(ensure (stringp output))
(ensure (plusp (length output)))))
| null | https://raw.githubusercontent.com/atgreen/lisp-openshift/40235286bd3c6a61cab9f5af883d9ed9befba849/quicklisp/dists/quicklisp/software/trivial-backtrace-20101006-git/test/tests.lisp | lisp | (in-package #:trivial-backtrace-test)
(deftestsuite generates-backtrace (trivial-backtrace-test)
())
(addtest (generates-backtrace)
test-1
(let ((output nil))
(handler-case
(let ((x 1))
(let ((y (- x (expt 1024 0))))
(/ 2 y)))
(error (c)
(setf output (print-backtrace c :output nil))))
(ensure (stringp output))
(ensure (plusp (length output)))))
| |
ad7a4c63bcda806a2cc10e1cf2e2da704e1c67e034a4dd0a83c2c1a1c473556a | darrenldl/ProVerif-ATP | reduction_helper.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
val get_max_used_phase : process -> int
val reset_name_args : process -> unit
val check_inj_coherent : Pitypes.query -> Pitypes.query
val new_var_pat1 : pattern -> binder
val new_var_pat : pattern -> term
val get_pat_vars : binder list -> pattern -> binder list
val occurs_var_pat : binder -> pattern -> bool
val occurs_var_proc : binder -> process -> bool
val get_need_vars : Pitypes.t_pi_state -> string -> (string * Parsing_helper.extent) list
val meaning_encode : arg_meaning -> string
val meaning_name : arg_meaning -> string
type include_info_t
val prepare_include_info :
envElement Stringmap.StringMap.t -> binder list option -> Ptree.ident list -> include_info_t
val count_name_params : Pitypes.name_param_info list -> int
val extract_name_params_noneed : Pitypes.name_param_info list -> term list
val extract_name_params : string -> include_info_t -> Pitypes.name_param_info list -> term list
val extract_name_params_meaning : string -> include_info_t -> Pitypes.name_param_info list -> arg_meaning list
val extract_name_params_types : string -> include_info_t -> Pitypes.name_param_info list -> typet list -> typet list
val findi : ('a -> bool) -> 'a list -> int * 'a
val skip : int -> 'a list -> 'a list
val replace_at : int -> 'a -> 'a list -> 'a list
val remove_at : int -> 'a list -> 'a list
val add_at : int -> 'a -> 'a list -> 'a list
val equal_terms_modulo : term -> term -> bool
val equal_open_terms_modulo : term -> term -> bool
val equal_facts_modulo : fact -> fact -> bool
val match_modulo : (unit -> 'a) -> term -> term -> 'a
val match_modulo_list :
(unit -> 'a) -> term list -> term list -> 'a
val get_name_charac : term -> funsymb list
val init_name_mapping : funsymb list -> unit
val add_name_for_pat : term -> funsymb
val add_new_name : typet -> funsymb
val display_tag : hypspec list -> term list -> unit
val public_free : term list ref
val match_equiv : (unit -> 'a) -> fact -> fact -> 'a
val match_equiv_list :
(unit -> 'a) -> fact list -> fact list -> 'a
val fact_subst :
fact -> funsymb -> term -> fact
val process_subst :
process -> funsymb -> term -> process
val copy_binder : binder -> binder
val copy_pat : pattern -> pattern
val copy_process : process -> process
val close_term : term -> unit
val close_tree : fact_tree -> unit
val copy_closed : term -> term
val copy_closed_remove_syntactic : term -> term
val rev_name_subst : term -> term
val rev_name_subst_list : term list -> term list
val rev_name_subst_fact : fact -> fact
val follow_link : term -> term
val close_tree_collect_links : (binder * linktype) list ref -> fact_tree -> unit
val getphase : predicate -> int
val disequation_evaluation : term * term -> bool
val is_fail : term -> bool
val update_name_params : when_include -> Pitypes.name_param_info list ->
pattern -> Pitypes.name_param_info list
val transl_check_several_patterns : Pitypes.term_occ list ref -> Pitypes.term_occ -> term -> bool
(* Returns whether the considered term should be added in
the arguments of names.
This function uses [Param.cur_state]. *)
val reduction_check_several_patterns : Pitypes.term_occ -> bool
(* [check_delayed_names q] translates the fresh names in query [q]
that could not be translated in [Pitsyntax.transl_query] because
we need information on the arity/type of name function symbols.
This function must be called after translating the process into
clauses, because this translation determines the arguments of the
name function symbols. *)
val check_delayed_names : Pitypes.query -> Pitypes.query
val collect_constraints : fact_tree -> constraints list list
val close_constraints : constraints list list -> unit
val create_pdf_trace : ('a -> term) -> ('a Pitypes.noninterf_test -> string) -> string -> 'a Pitypes.reduc_state -> int
| null | https://raw.githubusercontent.com/darrenldl/ProVerif-ATP/7af6cfb9e0550ecdb072c471e15b8f22b07408bd/proverif2.00/src/reduction_helper.mli | ocaml | Returns whether the considered term should be added in
the arguments of names.
This function uses [Param.cur_state].
[check_delayed_names q] translates the fresh names in query [q]
that could not be translated in [Pitsyntax.transl_query] because
we need information on the arity/type of name function symbols.
This function must be called after translating the process into
clauses, because this translation determines the arguments of the
name function symbols. | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2018 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2018 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Types
val get_max_used_phase : process -> int
val reset_name_args : process -> unit
val check_inj_coherent : Pitypes.query -> Pitypes.query
val new_var_pat1 : pattern -> binder
val new_var_pat : pattern -> term
val get_pat_vars : binder list -> pattern -> binder list
val occurs_var_pat : binder -> pattern -> bool
val occurs_var_proc : binder -> process -> bool
val get_need_vars : Pitypes.t_pi_state -> string -> (string * Parsing_helper.extent) list
val meaning_encode : arg_meaning -> string
val meaning_name : arg_meaning -> string
type include_info_t
val prepare_include_info :
envElement Stringmap.StringMap.t -> binder list option -> Ptree.ident list -> include_info_t
val count_name_params : Pitypes.name_param_info list -> int
val extract_name_params_noneed : Pitypes.name_param_info list -> term list
val extract_name_params : string -> include_info_t -> Pitypes.name_param_info list -> term list
val extract_name_params_meaning : string -> include_info_t -> Pitypes.name_param_info list -> arg_meaning list
val extract_name_params_types : string -> include_info_t -> Pitypes.name_param_info list -> typet list -> typet list
val findi : ('a -> bool) -> 'a list -> int * 'a
val skip : int -> 'a list -> 'a list
val replace_at : int -> 'a -> 'a list -> 'a list
val remove_at : int -> 'a list -> 'a list
val add_at : int -> 'a -> 'a list -> 'a list
val equal_terms_modulo : term -> term -> bool
val equal_open_terms_modulo : term -> term -> bool
val equal_facts_modulo : fact -> fact -> bool
val match_modulo : (unit -> 'a) -> term -> term -> 'a
val match_modulo_list :
(unit -> 'a) -> term list -> term list -> 'a
val get_name_charac : term -> funsymb list
val init_name_mapping : funsymb list -> unit
val add_name_for_pat : term -> funsymb
val add_new_name : typet -> funsymb
val display_tag : hypspec list -> term list -> unit
val public_free : term list ref
val match_equiv : (unit -> 'a) -> fact -> fact -> 'a
val match_equiv_list :
(unit -> 'a) -> fact list -> fact list -> 'a
val fact_subst :
fact -> funsymb -> term -> fact
val process_subst :
process -> funsymb -> term -> process
val copy_binder : binder -> binder
val copy_pat : pattern -> pattern
val copy_process : process -> process
val close_term : term -> unit
val close_tree : fact_tree -> unit
val copy_closed : term -> term
val copy_closed_remove_syntactic : term -> term
val rev_name_subst : term -> term
val rev_name_subst_list : term list -> term list
val rev_name_subst_fact : fact -> fact
val follow_link : term -> term
val close_tree_collect_links : (binder * linktype) list ref -> fact_tree -> unit
val getphase : predicate -> int
val disequation_evaluation : term * term -> bool
val is_fail : term -> bool
val update_name_params : when_include -> Pitypes.name_param_info list ->
pattern -> Pitypes.name_param_info list
val transl_check_several_patterns : Pitypes.term_occ list ref -> Pitypes.term_occ -> term -> bool
val reduction_check_several_patterns : Pitypes.term_occ -> bool
val check_delayed_names : Pitypes.query -> Pitypes.query
val collect_constraints : fact_tree -> constraints list list
val close_constraints : constraints list list -> unit
val create_pdf_trace : ('a -> term) -> ('a Pitypes.noninterf_test -> string) -> string -> 'a Pitypes.reduc_state -> int
|
7e1ce08303e91f4d215dad477ae1c01d1f87d0d939bfeeccdc609ba226e51412 | appleshan/cl-http | tcp-stream.lisp | ;;;
Scieneer Common Lisp stream support for the FTP client .
;;;
Copyright ( C ) 2006 , .
Copyright ( C ) 2006 , Scieneer Pty Ltd.
;;; All rights reserved.
;;;
;;;-------------------------------------------------------------------
;;;
;;; FTP SOCKETS AND STREAMS
;;;
(in-package :www-utils)
(defclass socket ()
((socket-handle :type fixnum :initarg :socket :reader socket-handle)
(port :initarg :port :reader socket-local-port :type fixnum)
(element-type :initarg :element-type :reader socket-element-type :type (member signed-byte unsigned-byte base-char))
(read-timeout :initarg :read-timeout :reader socket-read-timeout :type rational)
(local-protocol :initarg :local-protocol :accessor socket-local-protocol :type keyword)))
(defclass passive-socket (socket) ())
(defmethod print-object ((socket socket) stream)
(print-unreadable-object (socket stream :type t :identity t)
(multiple-value-bind (host port)
(socket-address socket)
(format stream "@~D on port ~D" host port))))
(defmethod socket-address ((socket socket))
(declare (values host port))
(with-slots (socket-handle) socket
(ext:get-socket-host-and-port socket-handle)))
(defgeneric stream-input-available-p (stream-or-socket)
(:documentation "Non-nil if data is waiting to be read from STREAM-OR-SOCKET ."))
(defmethod stream-input-available-p ((socket-handle fixnum))
(sys:wait-until-fd-usable socket-handle :input 0))
(defmethod stream-input-available-p ((socket socket))
(sys:wait-until-fd-usable (socket-handle socket) :input 0))
(defmethod stream-input-available-p ((stream sys:fd-stream))
(listen stream))
(defmethod close ((socket socket) &key abort)
(declare (ignore abort))
(unix:unix-close (socket-handle socket)))
(defun make-passive-socket (local-port &key element-type read-timeout no-error-p backlog (protocol :ftp))
(let ((socket-handle
(ignore-errors
(ext:create-inet-listener local-port :stream
:reuse-address t
:backlog backlog))))
(cond (socket-handle
(make-instance 'passive-socket
:port local-port
:socket socket-handle
:element-type element-type
:read-timeout read-timeout
:local-protocol protocol))
(no-error-p nil)
(t (error 'www-utils:connection-error)))))
(defmethod accept-connection ((passive-socket passive-socket))
(let ((read-timeout (socket-read-timeout passive-socket))
(socket-handle (socket-handle passive-socket)))
;; Wait until ready for input.
(let ((thread::*thread-whostate*
"Waiting for new HTTP connection"))
(mp:process-wait-until-fd-usable socket-handle :input))
(let ((new-fd (ignore-errors (ext:accept-tcp-connection socket-handle))))
(format t "* accept passive ftp connection fd=~s new-fd=~s~%"
socket-handle new-fd)
(cond (new-fd
(sys:make-fd-stream socket-handle :input t :output t
:element-type (socket-element-type passive-socket)
:timeout read-timeout))
(t (error 'www-utils:network-error))))))
(defun ftp-open-stream (host port &key (mode :text) timeout)
(let ((fd (ext:connect-to-inet-socket host port :timeout timeout)))
(system:make-fd-stream fd :input t :output t
:element-type (ecase mode
(:text 'base-char)
(:binary '(unsigned-byte 8))))))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/scl/client/tcp-stream.lisp | lisp |
All rights reserved.
-------------------------------------------------------------------
FTP SOCKETS AND STREAMS
Wait until ready for input. | Scieneer Common Lisp stream support for the FTP client .
Copyright ( C ) 2006 , .
Copyright ( C ) 2006 , Scieneer Pty Ltd.
(in-package :www-utils)
(defclass socket ()
((socket-handle :type fixnum :initarg :socket :reader socket-handle)
(port :initarg :port :reader socket-local-port :type fixnum)
(element-type :initarg :element-type :reader socket-element-type :type (member signed-byte unsigned-byte base-char))
(read-timeout :initarg :read-timeout :reader socket-read-timeout :type rational)
(local-protocol :initarg :local-protocol :accessor socket-local-protocol :type keyword)))
(defclass passive-socket (socket) ())
(defmethod print-object ((socket socket) stream)
(print-unreadable-object (socket stream :type t :identity t)
(multiple-value-bind (host port)
(socket-address socket)
(format stream "@~D on port ~D" host port))))
(defmethod socket-address ((socket socket))
(declare (values host port))
(with-slots (socket-handle) socket
(ext:get-socket-host-and-port socket-handle)))
(defgeneric stream-input-available-p (stream-or-socket)
(:documentation "Non-nil if data is waiting to be read from STREAM-OR-SOCKET ."))
(defmethod stream-input-available-p ((socket-handle fixnum))
(sys:wait-until-fd-usable socket-handle :input 0))
(defmethod stream-input-available-p ((socket socket))
(sys:wait-until-fd-usable (socket-handle socket) :input 0))
(defmethod stream-input-available-p ((stream sys:fd-stream))
(listen stream))
(defmethod close ((socket socket) &key abort)
(declare (ignore abort))
(unix:unix-close (socket-handle socket)))
(defun make-passive-socket (local-port &key element-type read-timeout no-error-p backlog (protocol :ftp))
(let ((socket-handle
(ignore-errors
(ext:create-inet-listener local-port :stream
:reuse-address t
:backlog backlog))))
(cond (socket-handle
(make-instance 'passive-socket
:port local-port
:socket socket-handle
:element-type element-type
:read-timeout read-timeout
:local-protocol protocol))
(no-error-p nil)
(t (error 'www-utils:connection-error)))))
(defmethod accept-connection ((passive-socket passive-socket))
(let ((read-timeout (socket-read-timeout passive-socket))
(socket-handle (socket-handle passive-socket)))
(let ((thread::*thread-whostate*
"Waiting for new HTTP connection"))
(mp:process-wait-until-fd-usable socket-handle :input))
(let ((new-fd (ignore-errors (ext:accept-tcp-connection socket-handle))))
(format t "* accept passive ftp connection fd=~s new-fd=~s~%"
socket-handle new-fd)
(cond (new-fd
(sys:make-fd-stream socket-handle :input t :output t
:element-type (socket-element-type passive-socket)
:timeout read-timeout))
(t (error 'www-utils:network-error))))))
(defun ftp-open-stream (host port &key (mode :text) timeout)
(let ((fd (ext:connect-to-inet-socket host port :timeout timeout)))
(system:make-fd-stream fd :input t :output t
:element-type (ecase mode
(:text 'base-char)
(:binary '(unsigned-byte 8))))))
|
67a5c8526c86c8a1f8ba4ffba96cf766208d2cb00c0d7d45543ccbd8a131e404 | Gbury/dolmen | misc.ml |
(* Option helpers *)
(* ************************************************************************ *)
module Options = struct
let map f = function
| None -> None
| Some x -> Some (f x)
end
(* List helpers *)
(* ************************************************************************ *)
module Lists = struct
let init n f =
let rec aux acc i =
if i > n then List.rev acc
else aux (f i :: acc) (i + 1)
in
aux [] 1
let replicate n x =
let rec aux x acc n =
if n <= 0 then acc else aux x (x :: acc) (n - 1)
in
aux x [] n
let take_drop n l =
let rec aux acc n = function
| r when n <= 0 -> List.rev acc, r
| [] -> raise (Invalid_argument "take_drop")
| x :: r -> aux (x :: acc) (n - 1) r
in
aux [] n l
let rec iter3 f l1 l2 l3 =
match l1, l2, l3 with
| [], [], [] -> ()
| a :: r1, b :: r2, c :: r3 -> f a b c; iter3 f r1 r2 r3
| _ -> raise (Invalid_argument "Misc.Lists.iter3")
let rec map3 f l1 l2 l3 =
match l1, l2, l3 with
| [], [], [] -> []
| a :: r1, b :: r2, c :: r3 -> (f a b c) :: (map3 f r1 r2 r3)
| _ -> raise (Invalid_argument "Misc.Lists.map3")
let fold_left_map f accu l =
let rec aux f accu l_accu = function
| [] -> accu, List.rev l_accu
| x :: l ->
let accu, x = f accu x in
aux f accu (x :: l_accu) l in
aux f accu [] l
end
(* String manipulation *)
(* ************************************************************************ *)
module Strings = struct
let to_list s =
let rec aux s i acc =
if i < 0 then acc
else aux s (i - 1) (s.[i] :: acc)
in
aux s (String.length s - 1) []
let is_suffix ~suffix s =
let k = String.length suffix in
let n = String.length s in
if n < k then false
else begin
let s' = String.sub s (n - k) k in
String.equal suffix s'
end
end
(* Bitvector manipulation *)
(* ************************************************************************ *)
module Bitv = struct
exception Invalid_char of char
(* Bitv in binary forms *)
let check_bin = function
| '0' | '1' -> ()
| c -> raise (Invalid_char c)
let parse_binary s =
assert (String.length s > 2 && s.[0] = '#' && s.[1] = 'b');
let s = String.sub s 2 (String.length s - 2) in
String.iter check_bin s;
s
(* Bitv in hexadecimal form *)
let hex_to_bin = function
| '0' -> "0000"
| '1' -> "0001"
| '2' -> "0010"
| '3' -> "0011"
| '4' -> "0100"
| '5' -> "0101"
| '6' -> "0110"
| '7' -> "0111"
| '8' -> "1000"
| '9' -> "1001"
| 'a' | 'A' -> "1010"
| 'b' | 'B' -> "1011"
| 'c' | 'C' -> "1100"
| 'd' | 'D' -> "1101"
| 'e' | 'E' -> "1110"
| 'f' | 'F' -> "1111"
| c -> raise (Invalid_char c)
let parse_hexa s =
assert (String.length s > 2 && s.[0] = '#' && s.[1] = 'x');
let s = String.sub s 2 (String.length s - 2) in
let b = Bytes.create (String.length s * 4) in
String.iteri (fun i c ->
Bytes.blit_string (hex_to_bin c) 0 b (i * 4) 4
) s;
Bytes.to_string b
(* bitv in decimal form *)
let int_of_char = function
| '0' -> 0
| '1' -> 1
| '2' -> 2
| '3' -> 3
| '4' -> 4
| '5' -> 5
| '6' -> 6
| '7' -> 7
| '8' -> 8
| '9' -> 9
| c -> raise (Invalid_char c)
let char_of_int = function
| 0 -> '0'
| 1 -> '1'
| 2 -> '2'
| 3 -> '3'
| 4 -> '4'
| 5 -> '5'
| 6 -> '6'
| 7 -> '7'
| 8 -> '8'
| 9 -> '9'
| _ -> assert false
Implementation of division by 2 on strings , and
of parsing a string - encoded decimal into a binary bitv ,
taken from
-a-very-large-number-from-decimal-string-to-binary-representation/11007021#11007021
of parsing a string-encoded decimal into a binary bitv,
taken from
-a-very-large-number-from-decimal-string-to-binary-representation/11007021#11007021 *)
let divide_string_by_2 b start =
let b' = Bytes.create (Bytes.length b - start) in
let next_additive = ref 0 in
for i = start to Bytes.length b - 1 do
let c = int_of_char (Bytes.get b i) in
let additive = !next_additive in
next_additive := if c mod 2 = 1 then 5 else 0;
let c' = c / 2 + additive in
Bytes.set b' (i - start) (char_of_int c')
done;
b'
let rec first_non_zero b start =
if start >= Bytes.length b then
None
else if Bytes.get b start = '0' then
first_non_zero b (start + 1)
else
Some start
(* Starting from a bytes full of '0', fill it with bits
coming from the given integer. *)
let rec parse_int_aux b i n =
if i < 0 || n <= 0 then b
else begin
if n mod 2 = 1 then Bytes.set b i '1';
parse_int_aux b (i - 1) (n / 2)
end
(* Size (in characters) of a decimal integer under which
int_of_string will work *)
let int_size_threshold =
match Sys.int_size with
max_int should be 2147483647 ( length 10 )
| 31 -> 9
max_int should be 9,223,372,036,854,775,807 ( length 19 )
| 63 -> 18
(* weird case, be safe before anyting *)
| _ -> 0
let rec parse_decimal_aux res idx b start =
if idx < 0 then
res
else if (Bytes.length b - start) <= int_size_threshold then begin
match int_of_string (Bytes.to_string b) with
| i -> parse_int_aux res idx i
| exception Failure _ -> assert false
end else begin
if b is odd , set the bit in res to 1
let c = int_of_char (Bytes.get b (Bytes.length b - 1)) in
if c mod 2 = 1 then Bytes.set res idx '1';
divide b by 2
let b' = divide_string_by_2 b start in
match first_non_zero b' 0 with
| Some start' -> parse_decimal_aux res (idx - 1) b' start'
| None -> res
end
let parse_decimal s n =
assert (String.length s > 2 && s.[0] = 'b' && s.[1] = 'v');
let b = Bytes.of_string (String.sub s 2 (String.length s - 2)) in
let b' = parse_decimal_aux (Bytes.make n '0') (n - 1) b 0 in
Bytes.to_string b'
end
| null | https://raw.githubusercontent.com/Gbury/dolmen/0ef0a8a09fb1122e45d66c931ab7b1706bd74495/src/typecheck/misc.ml | ocaml | Option helpers
************************************************************************
List helpers
************************************************************************
String manipulation
************************************************************************
Bitvector manipulation
************************************************************************
Bitv in binary forms
Bitv in hexadecimal form
bitv in decimal form
Starting from a bytes full of '0', fill it with bits
coming from the given integer.
Size (in characters) of a decimal integer under which
int_of_string will work
weird case, be safe before anyting |
module Options = struct
let map f = function
| None -> None
| Some x -> Some (f x)
end
module Lists = struct
let init n f =
let rec aux acc i =
if i > n then List.rev acc
else aux (f i :: acc) (i + 1)
in
aux [] 1
let replicate n x =
let rec aux x acc n =
if n <= 0 then acc else aux x (x :: acc) (n - 1)
in
aux x [] n
let take_drop n l =
let rec aux acc n = function
| r when n <= 0 -> List.rev acc, r
| [] -> raise (Invalid_argument "take_drop")
| x :: r -> aux (x :: acc) (n - 1) r
in
aux [] n l
let rec iter3 f l1 l2 l3 =
match l1, l2, l3 with
| [], [], [] -> ()
| a :: r1, b :: r2, c :: r3 -> f a b c; iter3 f r1 r2 r3
| _ -> raise (Invalid_argument "Misc.Lists.iter3")
let rec map3 f l1 l2 l3 =
match l1, l2, l3 with
| [], [], [] -> []
| a :: r1, b :: r2, c :: r3 -> (f a b c) :: (map3 f r1 r2 r3)
| _ -> raise (Invalid_argument "Misc.Lists.map3")
let fold_left_map f accu l =
let rec aux f accu l_accu = function
| [] -> accu, List.rev l_accu
| x :: l ->
let accu, x = f accu x in
aux f accu (x :: l_accu) l in
aux f accu [] l
end
module Strings = struct
let to_list s =
let rec aux s i acc =
if i < 0 then acc
else aux s (i - 1) (s.[i] :: acc)
in
aux s (String.length s - 1) []
let is_suffix ~suffix s =
let k = String.length suffix in
let n = String.length s in
if n < k then false
else begin
let s' = String.sub s (n - k) k in
String.equal suffix s'
end
end
module Bitv = struct
exception Invalid_char of char
let check_bin = function
| '0' | '1' -> ()
| c -> raise (Invalid_char c)
let parse_binary s =
assert (String.length s > 2 && s.[0] = '#' && s.[1] = 'b');
let s = String.sub s 2 (String.length s - 2) in
String.iter check_bin s;
s
let hex_to_bin = function
| '0' -> "0000"
| '1' -> "0001"
| '2' -> "0010"
| '3' -> "0011"
| '4' -> "0100"
| '5' -> "0101"
| '6' -> "0110"
| '7' -> "0111"
| '8' -> "1000"
| '9' -> "1001"
| 'a' | 'A' -> "1010"
| 'b' | 'B' -> "1011"
| 'c' | 'C' -> "1100"
| 'd' | 'D' -> "1101"
| 'e' | 'E' -> "1110"
| 'f' | 'F' -> "1111"
| c -> raise (Invalid_char c)
let parse_hexa s =
assert (String.length s > 2 && s.[0] = '#' && s.[1] = 'x');
let s = String.sub s 2 (String.length s - 2) in
let b = Bytes.create (String.length s * 4) in
String.iteri (fun i c ->
Bytes.blit_string (hex_to_bin c) 0 b (i * 4) 4
) s;
Bytes.to_string b
let int_of_char = function
| '0' -> 0
| '1' -> 1
| '2' -> 2
| '3' -> 3
| '4' -> 4
| '5' -> 5
| '6' -> 6
| '7' -> 7
| '8' -> 8
| '9' -> 9
| c -> raise (Invalid_char c)
let char_of_int = function
| 0 -> '0'
| 1 -> '1'
| 2 -> '2'
| 3 -> '3'
| 4 -> '4'
| 5 -> '5'
| 6 -> '6'
| 7 -> '7'
| 8 -> '8'
| 9 -> '9'
| _ -> assert false
Implementation of division by 2 on strings , and
of parsing a string - encoded decimal into a binary bitv ,
taken from
-a-very-large-number-from-decimal-string-to-binary-representation/11007021#11007021
of parsing a string-encoded decimal into a binary bitv,
taken from
-a-very-large-number-from-decimal-string-to-binary-representation/11007021#11007021 *)
let divide_string_by_2 b start =
let b' = Bytes.create (Bytes.length b - start) in
let next_additive = ref 0 in
for i = start to Bytes.length b - 1 do
let c = int_of_char (Bytes.get b i) in
let additive = !next_additive in
next_additive := if c mod 2 = 1 then 5 else 0;
let c' = c / 2 + additive in
Bytes.set b' (i - start) (char_of_int c')
done;
b'
let rec first_non_zero b start =
if start >= Bytes.length b then
None
else if Bytes.get b start = '0' then
first_non_zero b (start + 1)
else
Some start
let rec parse_int_aux b i n =
if i < 0 || n <= 0 then b
else begin
if n mod 2 = 1 then Bytes.set b i '1';
parse_int_aux b (i - 1) (n / 2)
end
let int_size_threshold =
match Sys.int_size with
max_int should be 2147483647 ( length 10 )
| 31 -> 9
max_int should be 9,223,372,036,854,775,807 ( length 19 )
| 63 -> 18
| _ -> 0
let rec parse_decimal_aux res idx b start =
if idx < 0 then
res
else if (Bytes.length b - start) <= int_size_threshold then begin
match int_of_string (Bytes.to_string b) with
| i -> parse_int_aux res idx i
| exception Failure _ -> assert false
end else begin
if b is odd , set the bit in res to 1
let c = int_of_char (Bytes.get b (Bytes.length b - 1)) in
if c mod 2 = 1 then Bytes.set res idx '1';
divide b by 2
let b' = divide_string_by_2 b start in
match first_non_zero b' 0 with
| Some start' -> parse_decimal_aux res (idx - 1) b' start'
| None -> res
end
let parse_decimal s n =
assert (String.length s > 2 && s.[0] = 'b' && s.[1] = 'v');
let b = Bytes.of_string (String.sub s 2 (String.length s - 2)) in
let b' = parse_decimal_aux (Bytes.make n '0') (n - 1) b 0 in
Bytes.to_string b'
end
|
86da5201a8ce208e2dfd263b2afebaabe6d7e03d4fb3811f0aa4f0659c42675c | ocamllabs/ocaml-modular-implicits | t172-pushenvacc1.ml | open Lib;;
let x = 5 in
let f _ = x + x in
if f 0 <> 10 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 16
11 ENVACC1
12 PUSHENVACC1
13 ADDINT
14 RETURN 1
16 CONSTINT 5
18
19 CLOSURE 1 , 11
22 PUSHCONSTINT 10
24 PUSHCONST0
25 PUSHACC2
26 APPLY1
27 NEQ
28 BRANCHIFNOT 35
30 GETGLOBAL Not_found
32 MAKEBLOCK1 0
34 RAISE
35 POP 2
37 ATOM0
38
40 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 16
11 ENVACC1
12 PUSHENVACC1
13 ADDINT
14 RETURN 1
16 CONSTINT 5
18 PUSHACC0
19 CLOSURE 1, 11
22 PUSHCONSTINT 10
24 PUSHCONST0
25 PUSHACC2
26 APPLY1
27 NEQ
28 BRANCHIFNOT 35
30 GETGLOBAL Not_found
32 MAKEBLOCK1 0
34 RAISE
35 POP 2
37 ATOM0
38 SETGLOBAL T172-pushenvacc1
40 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t172-pushenvacc1.ml | ocaml | open Lib;;
let x = 5 in
let f _ = x + x in
if f 0 <> 10 then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 BRANCH 16
11 ENVACC1
12 PUSHENVACC1
13 ADDINT
14 RETURN 1
16 CONSTINT 5
18
19 CLOSURE 1 , 11
22 PUSHCONSTINT 10
24 PUSHCONST0
25 PUSHACC2
26 APPLY1
27 NEQ
28 BRANCHIFNOT 35
30 GETGLOBAL Not_found
32 MAKEBLOCK1 0
34 RAISE
35 POP 2
37 ATOM0
38
40 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 BRANCH 16
11 ENVACC1
12 PUSHENVACC1
13 ADDINT
14 RETURN 1
16 CONSTINT 5
18 PUSHACC0
19 CLOSURE 1, 11
22 PUSHCONSTINT 10
24 PUSHCONST0
25 PUSHACC2
26 APPLY1
27 NEQ
28 BRANCHIFNOT 35
30 GETGLOBAL Not_found
32 MAKEBLOCK1 0
34 RAISE
35 POP 2
37 ATOM0
38 SETGLOBAL T172-pushenvacc1
40 STOP
**)
| |
ce9337a1eb3191431fed9d16db2ef80802ee510d48cb271455009602f0a0dc59 | craigl64/clim-ccl | depdefs.lisp | -*- Mode : LISP ; Syntax : Common - lisp ; Package : XLIB ; Base : 10 ; Lowercase : Yes -*-
This file contains some of the system dependent code for CLX
;;;
TEXAS INSTRUMENTS INCORPORATED
;;; P.O. BOX 2909
AUSTIN , TEXAS 78769
;;;
Copyright ( C ) 1987 Texas Instruments Incorporated .
;;;
;;; Permission is granted to any individual or institution to use, copy, modify,
;;; and distribute this software, provided that this complete copyright and
;;; permission notice is maintained, intact, in all copies and supporting
;;; documentation.
;;;
Texas Instruments Incorporated provides this software " as is " without
;;; express or implied warranty.
;;;
(in-package :xlib)
;;;-------------------------------------------------------------------------
;;; Declarations
;;;-------------------------------------------------------------------------
;;; DECLAIM
#-clx-ansi-common-lisp
(defmacro declaim (&rest decl-specs)
(if (cdr decl-specs)
`(progn
,@(mapcar #'(lambda (decl-spec) `(proclaim ',decl-spec))
decl-specs))
`(proclaim ',(car decl-specs))))
CLX - VALUES ... -- Documents the values returned by the function .
(declaim (declaration clx-values))
ARGLIST arg1 arg2 ... -- Documents the arglist of the function . Overrides
;;; the documentation that might get generated by the real arglist of the
;;; function.
(declaim (declaration arglist))
;;; DYNAMIC-EXTENT var -- Tells the compiler that the rest arg var has
;;; dynamic extent and therefore can be kept on the stack and not copied to
;;; the heap, even though the value is passed out of the function.
#-(or clx-ansi-common-lisp lcl3.0)
(declaim (declaration dynamic-extent))
IGNORABLE var -- Tells the compiler that the variable might or might not be used .
#-clx-ansi-common-lisp
(declaim (declaration ignorable))
;;; INDENTATION argpos1 arginden1 argpos2 arginden2 --- Tells the lisp editor how to
;;; indent calls to the function or macro containing the declaration.
(declaim (declaration indentation))
;;;-------------------------------------------------------------------------
;;; Declaration macros
;;;-------------------------------------------------------------------------
;;; WITH-VECTOR (variable type) &body body --- ensures the variable is a local
;;; and then does a type declaration and array register declaration
(defmacro with-vector ((var type) &body body)
`(let ((,var ,var))
(declare (type ,type ,var))
,@body))
;;; WITHIN-DEFINITION (name type) &body body --- Includes definitions for
;;; Meta-.
(defmacro within-definition ((name type) &body body)
(declare (ignore name type))
`(progn ,@body))
;;;-------------------------------------------------------------------------
CLX can maintain a mapping from X server ID 's to local data types . If
one takes the view that CLX objects will be instance variables of
;;; objects at the next higher level, then PROCESS-EVENT will typically map
;;; from resource-id to higher-level object. In that case, the lower-level
CLX mapping will almost never be used ( except in rare cases like
;;; query-tree), and only serve to consume space (which is difficult to
GC ) , in which case always - consing versions of the make-<mumble > s will
;;; be better. Even when maps are maintained, it isn't clear they are
useful for much beyond xatoms and windows ( since almost nothing else
;;; ever comes back in events).
;;;--------------------------------------------------------------------------
(defconstant +clx-cached-types+
'(drawable
window
pixmap
;; gcontext
cursor
colormap
font))
(defmacro resource-id-map-test ()
'#'eql)
( ) is not guaranteed .
(defmacro atom-cache-map-test ()
'#'eq)
(defmacro keysym->character-map-test ()
'#'eql)
;;; You must define this to match the real byte order. It is used by
;;; overlapping array and image code.
#+SBCL
(eval-when (:compile-toplevel :load-toplevel :execute)
;; FIXME: Ideally, we shouldn't end up with the internal
: CLX - LITTLE - ENDIAN decorating user - visible * FEATURES * lists .
;; This probably wants to be split up into :compile-toplevel
;; :execute and :load-toplevel clauses, so that loading the compiled
;; code doesn't push the feature.
(ecase sb-c:*backend-byte-order*
(:big-endian)
(:little-endian (pushnew :clx-little-endian *features*))))
Steele 's Common - Lisp states : " It is an error if the array specified
;;; as the :displaced-to argument does not have the same :element-type
;;; as the array being created" If this is the case on your lisp, then
;;; leave the overlapping-arrays feature turned off. Lisp machines
( Symbolics TI and LMI ) do n't have this restriction , and allow arrays
with different element types to overlap . CLX will take advantage of
;;; this to do fast array packing/unpacking when the overlapping-arrays
;;; feature is enabled.
(deftype buffer-bytes () `(simple-array (unsigned-byte 8) (*)))
#+clx-overlapping-arrays
(progn
(deftype buffer-words () `(vector overlap16))
(deftype buffer-longs () `(vector overlap32))
)
;;; This defines a type which is a subtype of the integers.
;;; This type is used to describe all variables that can be array indices.
;;; It is here because it is used below.
This is inclusive because start / end can be 1 past the end .
(deftype array-index () `(integer 0 ,array-dimension-limit))
;; this is the best place to define these?
(progn
(defun make-index-typed (form)
(if (constantp form) form `(the array-index ,form)))
(defun make-index-op (operator args)
`(the array-index
(values
,(case (length args)
(0 `(,operator))
(1 `(,operator
,(make-index-typed (first args))))
(2 `(,operator
,(make-index-typed (first args))
,(make-index-typed (second args))))
(otherwise
`(,operator
,(make-index-op operator (subseq args 0 (1- (length args))))
,(make-index-typed (first (last args)))))))))
(defmacro index+ (&rest numbers) (make-index-op '+ numbers))
(defmacro index-logand (&rest numbers) (make-index-op 'logand numbers))
(defmacro index-logior (&rest numbers) (make-index-op 'logior numbers))
(defmacro index- (&rest numbers) (make-index-op '- numbers))
(defmacro index* (&rest numbers) (make-index-op '* numbers))
(defmacro index1+ (number) (make-index-op '1+ (list number)))
(defmacro index1- (number) (make-index-op '1- (list number)))
(defmacro index-incf (place &optional (delta 1))
(make-index-op 'incf (list place delta)))
(defmacro index-decf (place &optional (delta 1))
(make-index-op 'decf (list place delta)))
(defmacro index-min (&rest numbers) (make-index-op 'min numbers))
(defmacro index-max (&rest numbers) (make-index-op 'max numbers))
(defmacro index-floor (number divisor)
(make-index-op 'floor (list number divisor)))
(defmacro index-ceiling (number divisor)
(make-index-op 'ceiling (list number divisor)))
(defmacro index-truncate (number divisor)
(make-index-op 'truncate (list number divisor)))
(defmacro index-mod (number divisor)
(make-index-op 'mod (list number divisor)))
(defmacro index-ash (number count)
(make-index-op 'ash (list number count)))
(defmacro index-plusp (number) `(plusp (the array-index ,number)))
(defmacro index-zerop (number) `(zerop (the array-index ,number)))
(defmacro index-evenp (number) `(evenp (the array-index ,number)))
(defmacro index-oddp (number) `(oddp (the array-index ,number)))
(defmacro index> (&rest numbers)
`(> ,@(mapcar #'make-index-typed numbers)))
(defmacro index= (&rest numbers)
`(= ,@(mapcar #'make-index-typed numbers)))
(defmacro index< (&rest numbers)
`(< ,@(mapcar #'make-index-typed numbers)))
(defmacro index>= (&rest numbers)
`(>= ,@(mapcar #'make-index-typed numbers)))
(defmacro index<= (&rest numbers)
`(<= ,@(mapcar #'make-index-typed numbers)))
)
;;;; Stuff for BUFFER definition
(defconstant +replysize+ 32.)
;; used in defstruct initializations to avoid compiler warnings
(defvar *empty-bytes* (make-sequence 'buffer-bytes 0))
(declaim (type buffer-bytes *empty-bytes*))
#+clx-overlapping-arrays
(progn
(defvar *empty-words* (make-sequence 'buffer-words 0))
(declaim (type buffer-words *empty-words*))
)
#+clx-overlapping-arrays
(progn
(defvar *empty-longs* (make-sequence 'buffer-longs 0))
(declaim (type buffer-longs *empty-longs*))
)
(defstruct (reply-buffer (:conc-name reply-) (:constructor make-reply-buffer-internal)
(:copier nil) (:predicate nil))
(size 0 :type array-index) ;Buffer size
Byte ( 8 bit ) input buffer
(ibuf8 *empty-bytes* :type buffer-bytes)
Word ( 16bit ) input buffer
#+clx-overlapping-arrays
(ibuf16 *empty-words* :type buffer-words)
;; Long (32bit) input buffer
#+clx-overlapping-arrays
(ibuf32 *empty-longs* :type buffer-longs)
(next nil :type (or null reply-buffer))
(data-size 0 :type array-index)
)
(defconstant +buffer-text16-size+ 256)
(deftype buffer-text16 () `(simple-array (unsigned-byte 16) (,+buffer-text16-size+)))
;; These are here because.
(defparameter *xlib-package* (find-package :xlib))
(defun xintern (&rest parts)
(intern (apply #'concatenate 'string (mapcar #'string parts)) *xlib-package*))
(defparameter *keyword-package* (find-package :keyword))
(defun kintern (name)
(intern (string name) *keyword-package*))
;;; Pseudo-class mechanism.
(eval-when (:compile-toplevel :load-toplevel :execute)
;; FIXME: maybe we should reevaluate this?
(defvar *def-clx-class-use-defclass* t
"Controls whether DEF-CLX-CLASS uses DEFCLASS.
If it is a list, it is interpreted by DEF-CLX-CLASS to be a list of
type names for which DEFCLASS should be used. If it is not a list,
then DEFCLASS is always used. If it is NIL, then DEFCLASS is never
used, since NIL is the empty list.")
)
(defmacro def-clx-class ((name &rest options) &body slots)
(if (or (not (listp *def-clx-class-use-defclass*))
(member name *def-clx-class-use-defclass*))
(let ((clos-package #+clx-ansi-common-lisp
(find-package :common-lisp)
#-clx-ansi-common-lisp
(or (find-package :clos)
(find-package :pcl)
(let ((lisp-pkg (find-package :lisp)))
(and (find-symbol (string 'defclass) lisp-pkg)
lisp-pkg))))
(constructor t)
(constructor-args t)
(include nil)
(print-function nil)
(copier t)
(predicate t))
(dolist (option options)
(ecase (pop option)
(:constructor
(setf constructor (pop option))
(setf constructor-args (if (null option) t (pop option))))
(:include
(setf include (pop option)))
(:print-function
(setf print-function (pop option)))
(:copier
(setf copier (pop option)))
(:predicate
(setf predicate (pop option)))))
(flet ((cintern (&rest symbols)
(intern (apply #'concatenate 'simple-string
(mapcar #'symbol-name symbols))
*package*))
(kintern (symbol)
(intern (symbol-name symbol) (find-package :keyword)))
(closintern (symbol)
(intern (symbol-name symbol) clos-package)))
(when (eq constructor t)
(setf constructor (cintern 'make- name)))
(when (eq copier t)
(setf copier (cintern 'copy- name)))
(when (eq predicate t)
(setf predicate (cintern name '-p)))
(when include
(setf slots (append (get include 'def-clx-class) slots)))
(let* ((n-slots (length slots))
(slot-names (make-list n-slots))
(slot-initforms (make-list n-slots))
(slot-types (make-list n-slots)))
(dotimes (i n-slots)
(let ((slot (elt slots i)))
(setf (elt slot-names i) (pop slot))
(setf (elt slot-initforms i) (pop slot))
(setf (elt slot-types i) (getf slot :type t))))
`(progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (get ',name 'def-clx-class) ',slots))
;; From here down are the system-specific expansions:
(within-definition (,name def-clx-class)
(,(closintern 'defclass)
,name ,(and include `(,include))
(,@(map 'list
#'(lambda (slot-name slot-initform slot-type)
`(,slot-name
:initform ,slot-initform :type ,slot-type
:accessor ,(cintern name '- slot-name)
,@(when (and constructor
(or (eq constructor-args t)
(member slot-name
constructor-args)))
`(:initarg ,(kintern slot-name)))
))
slot-names slot-initforms slot-types)))
,(when constructor
(if (eq constructor-args t)
`(defun ,constructor (&rest args)
(apply #',(closintern 'make-instance)
',name args))
`(defun ,constructor ,constructor-args
(,(closintern 'make-instance) ',name
,@(mapcan #'(lambda (slot-name)
(and (member slot-name slot-names)
`(,(kintern slot-name) ,slot-name)))
constructor-args)))))
,(when predicate
#+allegro
`(progn
(,(closintern 'defmethod) ,predicate (object)
(declare (ignore object))
nil)
(,(closintern 'defmethod) ,predicate ((object ,name))
t))
#-allegro
`(defun ,predicate (object)
(typep object ',name)))
,(when copier
`(,(closintern 'defmethod) ,copier ((.object. ,name))
(,(closintern 'with-slots) ,slot-names .object.
(,(closintern 'make-instance) ',name
,@(mapcan #'(lambda (slot-name)
`(,(kintern slot-name) ,slot-name))
slot-names)))))
,(when print-function
`(,(closintern 'defmethod)
,(closintern 'print-object)
((object ,name) stream)
(,print-function object stream 0))))))))
`(within-definition (,name def-clx-class)
(defstruct (,name ,@options)
,@slots))))
We need this here so we can define DISPLAY for CLX .
;;
;; This structure is :INCLUDEd in the DISPLAY structure.
;; Overlapping (displaced) arrays are provided for byte
half - word and word access on both input and output .
;;
(def-clx-class (buffer (:constructor nil) (:copier nil) (:predicate nil))
;; Lock for multi-processing systems
(lock (make-process-lock "CLX Buffer Lock"))
(output-stream nil :type (or null stream))
;; Buffer size
(size 0 :type array-index)
(request-number 0 :type (unsigned-byte 16))
Byte position of start of last request
;; used for appending requests and error recovery
(last-request nil :type (or null array-index))
Byte position of start of last flushed request
(last-flushed-request nil :type (or null array-index))
;; Current byte offset
(boffset 0 :type array-index)
Byte ( 8 bit ) output buffer
(obuf8 *empty-bytes* :type buffer-bytes)
Word ( 16bit ) output buffer
#+clx-overlapping-arrays
(obuf16 *empty-words* :type buffer-words)
;; Long (32bit) output buffer
#+clx-overlapping-arrays
(obuf32 *empty-longs* :type buffer-longs)
Holding buffer for 16 - bit text
(tbuf16 (make-sequence 'buffer-text16 +buffer-text16-size+ :initial-element 0))
;; Probably EQ to Output-Stream
(input-stream nil :type (or null stream))
;; T when the host connection has gotten errors
(dead nil :type (or null (not null)))
;; T makes buffer-flush a noop. Manipulated with with-buffer-flush-inhibited.
(flush-inhibit nil :type (or null (not null)))
;; Change these functions when using shared memory buffers to the server
;; Function to call when writing the buffer
(write-function 'buffer-write-default)
;; Function to call when flushing the buffer
(force-output-function 'buffer-force-output-default)
;; Function to call when closing a connection
(close-function 'buffer-close-default)
;; Function to call when reading the buffer
(input-function 'buffer-read-default)
;; Function to call to wait for data to be input
(input-wait-function 'buffer-input-wait-default)
;; Function to call to listen for input data
(listen-function 'buffer-listen-default)
)
;;-----------------------------------------------------------------------------
;; Printing routines.
;;-----------------------------------------------------------------------------
#-(or clx-ansi-common-lisp Genera)
(defun print-unreadable-object-function (object stream type identity function)
(declare #+lispm
(sys:downward-funarg function))
(princ "#<" stream)
(when type
(let ((type (type-of object))
(pcl-package (find-package :pcl)))
;; Handle pcl type-of lossage
(when (and pcl-package
(symbolp type)
(eq (symbol-package type) pcl-package)
(string-equal (symbol-name type) "STD-INSTANCE"))
(setq type
(funcall (intern (symbol-name 'class-name) pcl-package)
(funcall (intern (symbol-name 'class-of) pcl-package)
object))))
(prin1 type stream)))
(when (and type function) (princ " " stream))
(when function (funcall function))
(when (and (or type function) identity) (princ " " stream))
(when identity (princ "???" stream))
(princ ">" stream)
nil)
#-(or clx-ansi-common-lisp Genera)
(defmacro print-unreadable-object
((object stream &key type identity) &body body)
(if body
`(flet ((.print-unreadable-object-body. () ,@body))
(print-unreadable-object-function
,object ,stream ,type ,identity #'.print-unreadable-object-body.))
`(print-unreadable-object-function ,object ,stream ,type ,identity nil)))
;;-----------------------------------------------------------------------------
;; Image stuff
;;-----------------------------------------------------------------------------
(defconstant +image-bit-lsb-first-p+
#+clx-little-endian t
#-clx-little-endian nil)
(defconstant +image-byte-lsb-first-p+
#+clx-little-endian t
#-clx-little-endian nil)
(defconstant +image-unit+ 32)
(defconstant +image-pad+ 32)
;;-----------------------------------------------------------------------------
;; Finding the server socket
;;-----------------------------------------------------------------------------
;; These are here because dep-openmcl.lisp, dep-lispworks.lisp and
;; dependent.lisp need them
(defconstant +X-unix-socket-path+
"/tmp/.X11-unix/X"
"The location of the X socket")
(defun unix-socket-path-from-host (host display)
"Return the name of the unix domain socket for host and display, or
nil if a network socket should be opened."
(cond ((or (null host) (string= host "") (string= host "unix"))
(format nil "~A~D" +X-unix-socket-path+ display))
#+darwin
((or (and (> (length host) 10) (string= host "tmp/launch" :end1 10))
(and (> (length host) 29) (string= host "private/tmp/com.apple.launchd" :end1 29)))
(format nil "/~A:~D" host display))
(t nil)))
| null | https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/xlib/depdefs.lisp | lisp | Syntax : Common - lisp ; Package : XLIB ; Base : 10 ; Lowercase : Yes -*-
P.O. BOX 2909
Permission is granted to any individual or institution to use, copy, modify,
and distribute this software, provided that this complete copyright and
permission notice is maintained, intact, in all copies and supporting
documentation.
express or implied warranty.
-------------------------------------------------------------------------
Declarations
-------------------------------------------------------------------------
DECLAIM
the documentation that might get generated by the real arglist of the
function.
DYNAMIC-EXTENT var -- Tells the compiler that the rest arg var has
dynamic extent and therefore can be kept on the stack and not copied to
the heap, even though the value is passed out of the function.
INDENTATION argpos1 arginden1 argpos2 arginden2 --- Tells the lisp editor how to
indent calls to the function or macro containing the declaration.
-------------------------------------------------------------------------
Declaration macros
-------------------------------------------------------------------------
WITH-VECTOR (variable type) &body body --- ensures the variable is a local
and then does a type declaration and array register declaration
WITHIN-DEFINITION (name type) &body body --- Includes definitions for
Meta-.
-------------------------------------------------------------------------
objects at the next higher level, then PROCESS-EVENT will typically map
from resource-id to higher-level object. In that case, the lower-level
query-tree), and only serve to consume space (which is difficult to
be better. Even when maps are maintained, it isn't clear they are
ever comes back in events).
--------------------------------------------------------------------------
gcontext
You must define this to match the real byte order. It is used by
overlapping array and image code.
FIXME: Ideally, we shouldn't end up with the internal
This probably wants to be split up into :compile-toplevel
:execute and :load-toplevel clauses, so that loading the compiled
code doesn't push the feature.
as the :displaced-to argument does not have the same :element-type
as the array being created" If this is the case on your lisp, then
leave the overlapping-arrays feature turned off. Lisp machines
this to do fast array packing/unpacking when the overlapping-arrays
feature is enabled.
This defines a type which is a subtype of the integers.
This type is used to describe all variables that can be array indices.
It is here because it is used below.
this is the best place to define these?
Stuff for BUFFER definition
used in defstruct initializations to avoid compiler warnings
Buffer size
Long (32bit) input buffer
These are here because.
Pseudo-class mechanism.
FIXME: maybe we should reevaluate this?
From here down are the system-specific expansions:
This structure is :INCLUDEd in the DISPLAY structure.
Overlapping (displaced) arrays are provided for byte
Lock for multi-processing systems
Buffer size
used for appending requests and error recovery
Current byte offset
Long (32bit) output buffer
Probably EQ to Output-Stream
T when the host connection has gotten errors
T makes buffer-flush a noop. Manipulated with with-buffer-flush-inhibited.
Change these functions when using shared memory buffers to the server
Function to call when writing the buffer
Function to call when flushing the buffer
Function to call when closing a connection
Function to call when reading the buffer
Function to call to wait for data to be input
Function to call to listen for input data
-----------------------------------------------------------------------------
Printing routines.
-----------------------------------------------------------------------------
Handle pcl type-of lossage
-----------------------------------------------------------------------------
Image stuff
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Finding the server socket
-----------------------------------------------------------------------------
These are here because dep-openmcl.lisp, dep-lispworks.lisp and
dependent.lisp need them |
This file contains some of the system dependent code for CLX
TEXAS INSTRUMENTS INCORPORATED
AUSTIN , TEXAS 78769
Copyright ( C ) 1987 Texas Instruments Incorporated .
Texas Instruments Incorporated provides this software " as is " without
(in-package :xlib)
#-clx-ansi-common-lisp
(defmacro declaim (&rest decl-specs)
(if (cdr decl-specs)
`(progn
,@(mapcar #'(lambda (decl-spec) `(proclaim ',decl-spec))
decl-specs))
`(proclaim ',(car decl-specs))))
CLX - VALUES ... -- Documents the values returned by the function .
(declaim (declaration clx-values))
ARGLIST arg1 arg2 ... -- Documents the arglist of the function . Overrides
(declaim (declaration arglist))
#-(or clx-ansi-common-lisp lcl3.0)
(declaim (declaration dynamic-extent))
IGNORABLE var -- Tells the compiler that the variable might or might not be used .
#-clx-ansi-common-lisp
(declaim (declaration ignorable))
(declaim (declaration indentation))
(defmacro with-vector ((var type) &body body)
`(let ((,var ,var))
(declare (type ,type ,var))
,@body))
(defmacro within-definition ((name type) &body body)
(declare (ignore name type))
`(progn ,@body))
CLX can maintain a mapping from X server ID 's to local data types . If
one takes the view that CLX objects will be instance variables of
CLX mapping will almost never be used ( except in rare cases like
GC ) , in which case always - consing versions of the make-<mumble > s will
useful for much beyond xatoms and windows ( since almost nothing else
(defconstant +clx-cached-types+
'(drawable
window
pixmap
cursor
colormap
font))
(defmacro resource-id-map-test ()
'#'eql)
( ) is not guaranteed .
(defmacro atom-cache-map-test ()
'#'eq)
(defmacro keysym->character-map-test ()
'#'eql)
#+SBCL
(eval-when (:compile-toplevel :load-toplevel :execute)
: CLX - LITTLE - ENDIAN decorating user - visible * FEATURES * lists .
(ecase sb-c:*backend-byte-order*
(:big-endian)
(:little-endian (pushnew :clx-little-endian *features*))))
Steele 's Common - Lisp states : " It is an error if the array specified
( Symbolics TI and LMI ) do n't have this restriction , and allow arrays
with different element types to overlap . CLX will take advantage of
(deftype buffer-bytes () `(simple-array (unsigned-byte 8) (*)))
#+clx-overlapping-arrays
(progn
(deftype buffer-words () `(vector overlap16))
(deftype buffer-longs () `(vector overlap32))
)
This is inclusive because start / end can be 1 past the end .
(deftype array-index () `(integer 0 ,array-dimension-limit))
(progn
(defun make-index-typed (form)
(if (constantp form) form `(the array-index ,form)))
(defun make-index-op (operator args)
`(the array-index
(values
,(case (length args)
(0 `(,operator))
(1 `(,operator
,(make-index-typed (first args))))
(2 `(,operator
,(make-index-typed (first args))
,(make-index-typed (second args))))
(otherwise
`(,operator
,(make-index-op operator (subseq args 0 (1- (length args))))
,(make-index-typed (first (last args)))))))))
(defmacro index+ (&rest numbers) (make-index-op '+ numbers))
(defmacro index-logand (&rest numbers) (make-index-op 'logand numbers))
(defmacro index-logior (&rest numbers) (make-index-op 'logior numbers))
(defmacro index- (&rest numbers) (make-index-op '- numbers))
(defmacro index* (&rest numbers) (make-index-op '* numbers))
(defmacro index1+ (number) (make-index-op '1+ (list number)))
(defmacro index1- (number) (make-index-op '1- (list number)))
(defmacro index-incf (place &optional (delta 1))
(make-index-op 'incf (list place delta)))
(defmacro index-decf (place &optional (delta 1))
(make-index-op 'decf (list place delta)))
(defmacro index-min (&rest numbers) (make-index-op 'min numbers))
(defmacro index-max (&rest numbers) (make-index-op 'max numbers))
(defmacro index-floor (number divisor)
(make-index-op 'floor (list number divisor)))
(defmacro index-ceiling (number divisor)
(make-index-op 'ceiling (list number divisor)))
(defmacro index-truncate (number divisor)
(make-index-op 'truncate (list number divisor)))
(defmacro index-mod (number divisor)
(make-index-op 'mod (list number divisor)))
(defmacro index-ash (number count)
(make-index-op 'ash (list number count)))
(defmacro index-plusp (number) `(plusp (the array-index ,number)))
(defmacro index-zerop (number) `(zerop (the array-index ,number)))
(defmacro index-evenp (number) `(evenp (the array-index ,number)))
(defmacro index-oddp (number) `(oddp (the array-index ,number)))
(defmacro index> (&rest numbers)
`(> ,@(mapcar #'make-index-typed numbers)))
(defmacro index= (&rest numbers)
`(= ,@(mapcar #'make-index-typed numbers)))
(defmacro index< (&rest numbers)
`(< ,@(mapcar #'make-index-typed numbers)))
(defmacro index>= (&rest numbers)
`(>= ,@(mapcar #'make-index-typed numbers)))
(defmacro index<= (&rest numbers)
`(<= ,@(mapcar #'make-index-typed numbers)))
)
(defconstant +replysize+ 32.)
(defvar *empty-bytes* (make-sequence 'buffer-bytes 0))
(declaim (type buffer-bytes *empty-bytes*))
#+clx-overlapping-arrays
(progn
(defvar *empty-words* (make-sequence 'buffer-words 0))
(declaim (type buffer-words *empty-words*))
)
#+clx-overlapping-arrays
(progn
(defvar *empty-longs* (make-sequence 'buffer-longs 0))
(declaim (type buffer-longs *empty-longs*))
)
(defstruct (reply-buffer (:conc-name reply-) (:constructor make-reply-buffer-internal)
(:copier nil) (:predicate nil))
Byte ( 8 bit ) input buffer
(ibuf8 *empty-bytes* :type buffer-bytes)
Word ( 16bit ) input buffer
#+clx-overlapping-arrays
(ibuf16 *empty-words* :type buffer-words)
#+clx-overlapping-arrays
(ibuf32 *empty-longs* :type buffer-longs)
(next nil :type (or null reply-buffer))
(data-size 0 :type array-index)
)
(defconstant +buffer-text16-size+ 256)
(deftype buffer-text16 () `(simple-array (unsigned-byte 16) (,+buffer-text16-size+)))
(defparameter *xlib-package* (find-package :xlib))
(defun xintern (&rest parts)
(intern (apply #'concatenate 'string (mapcar #'string parts)) *xlib-package*))
(defparameter *keyword-package* (find-package :keyword))
(defun kintern (name)
(intern (string name) *keyword-package*))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *def-clx-class-use-defclass* t
"Controls whether DEF-CLX-CLASS uses DEFCLASS.
If it is a list, it is interpreted by DEF-CLX-CLASS to be a list of
type names for which DEFCLASS should be used. If it is not a list,
then DEFCLASS is always used. If it is NIL, then DEFCLASS is never
used, since NIL is the empty list.")
)
(defmacro def-clx-class ((name &rest options) &body slots)
(if (or (not (listp *def-clx-class-use-defclass*))
(member name *def-clx-class-use-defclass*))
(let ((clos-package #+clx-ansi-common-lisp
(find-package :common-lisp)
#-clx-ansi-common-lisp
(or (find-package :clos)
(find-package :pcl)
(let ((lisp-pkg (find-package :lisp)))
(and (find-symbol (string 'defclass) lisp-pkg)
lisp-pkg))))
(constructor t)
(constructor-args t)
(include nil)
(print-function nil)
(copier t)
(predicate t))
(dolist (option options)
(ecase (pop option)
(:constructor
(setf constructor (pop option))
(setf constructor-args (if (null option) t (pop option))))
(:include
(setf include (pop option)))
(:print-function
(setf print-function (pop option)))
(:copier
(setf copier (pop option)))
(:predicate
(setf predicate (pop option)))))
(flet ((cintern (&rest symbols)
(intern (apply #'concatenate 'simple-string
(mapcar #'symbol-name symbols))
*package*))
(kintern (symbol)
(intern (symbol-name symbol) (find-package :keyword)))
(closintern (symbol)
(intern (symbol-name symbol) clos-package)))
(when (eq constructor t)
(setf constructor (cintern 'make- name)))
(when (eq copier t)
(setf copier (cintern 'copy- name)))
(when (eq predicate t)
(setf predicate (cintern name '-p)))
(when include
(setf slots (append (get include 'def-clx-class) slots)))
(let* ((n-slots (length slots))
(slot-names (make-list n-slots))
(slot-initforms (make-list n-slots))
(slot-types (make-list n-slots)))
(dotimes (i n-slots)
(let ((slot (elt slots i)))
(setf (elt slot-names i) (pop slot))
(setf (elt slot-initforms i) (pop slot))
(setf (elt slot-types i) (getf slot :type t))))
`(progn
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (get ',name 'def-clx-class) ',slots))
(within-definition (,name def-clx-class)
(,(closintern 'defclass)
,name ,(and include `(,include))
(,@(map 'list
#'(lambda (slot-name slot-initform slot-type)
`(,slot-name
:initform ,slot-initform :type ,slot-type
:accessor ,(cintern name '- slot-name)
,@(when (and constructor
(or (eq constructor-args t)
(member slot-name
constructor-args)))
`(:initarg ,(kintern slot-name)))
))
slot-names slot-initforms slot-types)))
,(when constructor
(if (eq constructor-args t)
`(defun ,constructor (&rest args)
(apply #',(closintern 'make-instance)
',name args))
`(defun ,constructor ,constructor-args
(,(closintern 'make-instance) ',name
,@(mapcan #'(lambda (slot-name)
(and (member slot-name slot-names)
`(,(kintern slot-name) ,slot-name)))
constructor-args)))))
,(when predicate
#+allegro
`(progn
(,(closintern 'defmethod) ,predicate (object)
(declare (ignore object))
nil)
(,(closintern 'defmethod) ,predicate ((object ,name))
t))
#-allegro
`(defun ,predicate (object)
(typep object ',name)))
,(when copier
`(,(closintern 'defmethod) ,copier ((.object. ,name))
(,(closintern 'with-slots) ,slot-names .object.
(,(closintern 'make-instance) ',name
,@(mapcan #'(lambda (slot-name)
`(,(kintern slot-name) ,slot-name))
slot-names)))))
,(when print-function
`(,(closintern 'defmethod)
,(closintern 'print-object)
((object ,name) stream)
(,print-function object stream 0))))))))
`(within-definition (,name def-clx-class)
(defstruct (,name ,@options)
,@slots))))
We need this here so we can define DISPLAY for CLX .
half - word and word access on both input and output .
(def-clx-class (buffer (:constructor nil) (:copier nil) (:predicate nil))
(lock (make-process-lock "CLX Buffer Lock"))
(output-stream nil :type (or null stream))
(size 0 :type array-index)
(request-number 0 :type (unsigned-byte 16))
Byte position of start of last request
(last-request nil :type (or null array-index))
Byte position of start of last flushed request
(last-flushed-request nil :type (or null array-index))
(boffset 0 :type array-index)
Byte ( 8 bit ) output buffer
(obuf8 *empty-bytes* :type buffer-bytes)
Word ( 16bit ) output buffer
#+clx-overlapping-arrays
(obuf16 *empty-words* :type buffer-words)
#+clx-overlapping-arrays
(obuf32 *empty-longs* :type buffer-longs)
Holding buffer for 16 - bit text
(tbuf16 (make-sequence 'buffer-text16 +buffer-text16-size+ :initial-element 0))
(input-stream nil :type (or null stream))
(dead nil :type (or null (not null)))
(flush-inhibit nil :type (or null (not null)))
(write-function 'buffer-write-default)
(force-output-function 'buffer-force-output-default)
(close-function 'buffer-close-default)
(input-function 'buffer-read-default)
(input-wait-function 'buffer-input-wait-default)
(listen-function 'buffer-listen-default)
)
#-(or clx-ansi-common-lisp Genera)
(defun print-unreadable-object-function (object stream type identity function)
(declare #+lispm
(sys:downward-funarg function))
(princ "#<" stream)
(when type
(let ((type (type-of object))
(pcl-package (find-package :pcl)))
(when (and pcl-package
(symbolp type)
(eq (symbol-package type) pcl-package)
(string-equal (symbol-name type) "STD-INSTANCE"))
(setq type
(funcall (intern (symbol-name 'class-name) pcl-package)
(funcall (intern (symbol-name 'class-of) pcl-package)
object))))
(prin1 type stream)))
(when (and type function) (princ " " stream))
(when function (funcall function))
(when (and (or type function) identity) (princ " " stream))
(when identity (princ "???" stream))
(princ ">" stream)
nil)
#-(or clx-ansi-common-lisp Genera)
(defmacro print-unreadable-object
((object stream &key type identity) &body body)
(if body
`(flet ((.print-unreadable-object-body. () ,@body))
(print-unreadable-object-function
,object ,stream ,type ,identity #'.print-unreadable-object-body.))
`(print-unreadable-object-function ,object ,stream ,type ,identity nil)))
(defconstant +image-bit-lsb-first-p+
#+clx-little-endian t
#-clx-little-endian nil)
(defconstant +image-byte-lsb-first-p+
#+clx-little-endian t
#-clx-little-endian nil)
(defconstant +image-unit+ 32)
(defconstant +image-pad+ 32)
(defconstant +X-unix-socket-path+
"/tmp/.X11-unix/X"
"The location of the X socket")
(defun unix-socket-path-from-host (host display)
"Return the name of the unix domain socket for host and display, or
nil if a network socket should be opened."
(cond ((or (null host) (string= host "") (string= host "unix"))
(format nil "~A~D" +X-unix-socket-path+ display))
#+darwin
((or (and (> (length host) 10) (string= host "tmp/launch" :end1 10))
(and (> (length host) 29) (string= host "private/tmp/com.apple.launchd" :end1 29)))
(format nil "/~A:~D" host display))
(t nil)))
|
0e99351f1552ede094cd8e1516121a4b44815b628e2f09ee4e404ffbb078ba6d | erlang/corba | icstruct.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1997 - 2020 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%
-module(icstruct).
-export([struct_gen/4, except_gen/4, create_c_array_coding_file/5]).
%%------------------------------------------------------------
%%
%% Internal stuff
%%
%%------------------------------------------------------------
-import(ic_codegen, [emit/2, emit/3, emit/4, emit_c_enc_rpt/4, emit_c_dec_rpt/4]).
-include("icforms.hrl").
-include("ic.hrl").
%%------------------------------------------------------------
%%------------------------------------------------------------
%%
%% File handling stuff
%%
%%------------------------------------------------------------
%%------------------------------------------------------------
%%
%% Generation loop
%%
%% The idea is to traverse everything and find every struct that
%% may be hiding down in nested types. All structs that are found
%% are generated to a hrl file.
%%
%% struct_gen is entry point for structs and types, except_gen is
%% for exceptions
%%
%%------------------------------------------------------------
except_gen(G, N, X, L) when is_record(X, except) ->
N2 = [ic_forms:get_id2(X) | N],
if
L == c ->
io:format("Warning : Exception not defined for c mapping\n", []);
true ->
emit_struct(G, N, X, L)
end,
struct_gen_list(G, N2, ic_forms:get_body(X), L).
struct_gen(G, N, X, L) when is_record(X, struct) ->
N2 = [ic_forms:get_id2(X) | N],
struct_gen_list(G, N2, ic_forms:get_body(X), L),
emit_struct(G, N, X, L);
struct_gen(G, N, X, L) when is_record(X, union) ->
N2 = [ic_forms:get_id2(X) | N],
if
L == c ->
Produce the " body " first
struct_gen_list(G, N2, ic_forms:get_body(X), L),
icunion:union_gen(G, N, X, c);
true ->
struct_gen(G, N, ic_forms:get_type(X), L),
struct_gen_list(G, N2, ic_forms:get_body(X), L)
end,
emit_union(G, N, X, L);
struct_gen(G, N, X, L) when is_record(X, member) ->
struct_gen(G, N, ic_forms:get_type(X), L);
struct_gen(G, N, X, L) when is_record(X, typedef) ->
struct_gen(G, N, ic_forms:get_body(X), L),
emit_typedef(G, N, X, L);
struct_gen(G, N, X, L) when is_record(X, type_dcl) ->
struct_gen_list(G, N, ic_forms:get_type(X), L);
struct_gen(G, N, X, L) when is_record(X, case_dcl) ->
struct_gen(G, N, ic_forms:get_type(X), L);
struct_gen(G, N, X, L) when is_record(X, sequence) ->
struct_gen(G, N, ic_forms:get_type(X), L),
X;
struct_gen(G, N, X, L) when is_record(X, enum) ->
icenum:enum_gen(G, N, X, L);
struct_gen(_G, _N, _X, _L) ->
ok.
%% List clause for struct_gen
struct_gen_list(G, N, Xs, L) ->
lists:foreach(
fun(X) ->
R = struct_gen(G, N, X, L),
if
L == c ->
if
is_record(R,sequence) ->
emit_sequence_head_def(G,N,X,R,L);
true ->
ok
end;
true ->
ok
end
end, Xs).
%% emit primitive for structs.
emit_struct(G, N, X, erlang) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
%% Make a straight list of all member ids (this is a
%% variant of flatten)
EList = lists:map(
fun(XX) ->
lists:map(
fun(XXX) ->
ic_util:to_atom(ic_forms:get_id2(XXX))
end,
ic_forms:get_idlist(XX))
end,
ic_forms:get_body(X)),
ic_codegen:record(G, X,
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
ictk:get_IR_ID(G, N, X), lists:flatten(EList)),
mkFileRecObj(G,N,X,erlang);
false ->
ok
end;
emit_struct(G, N, X, c) ->
N1 = [ic_forms:get_id2(X) | N],
case ic_pragma:is_local(G,N1) of
true ->
emit_c_struct(G, N, X,local);
false ->
emit_c_struct(G, N, X,included)
end.
emit_c_struct(_G, _N, _X, included) ->
Do not generate included types att all .
ok;
emit_c_struct(G, N, X, local) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
N1 = [ic_forms:get_id2(X) | N],
StructName = ic_util:to_undersc(N1),
%% Make a straight list of all member ids (this is a
%% variant of flatten)
M = lists:map(
fun(XX) ->
lists:map(
fun(XXX) ->
if
is_record(XXX, array) ->
Type = ic_forms:get_type(XX),
Name = element(3,element(2,XXX)),
{_, _, StructTK, _} =
ic_symtab:get_full_scoped_name(
G,
N,
ic_symtab:scoped_id_new(
ic_forms:get_id2(X))),
ArrayTK =
get_structelement_tk(StructTK,
Name),
Dim = extract_dim(ArrayTK),
%% emit array file
emit(Fd, "\n#ifndef __~s__\n",
[ic_util:to_uppercase(
StructName ++ "_"
++ Name)]),
emit(Fd, "#define __~s__\n\n",
[ic_util:to_uppercase(
StructName ++ "_"
++ Name)]),
create_c_array_coding_file(
G,
N,
{StructName ++ "_" ++ Name, Dim},
Type,
no_typedef),
emit(Fd, "\n#endif\n\n"),
{{Type, XXX},
ic_forms:get_id2(XXX)};
true ->
Ugly work around to fix the ETO
%% return patch problem
Name =
case ic_forms:get_id2(XXX) of
"return" ->
"return1";
Other ->
Other
end,
{ic_forms:get_type(XX), Name}
end
end,
ic_forms:get_idlist(XX))
end,
ic_forms:get_body(X)),
EList = lists:flatten(M),
io : = ~p ~ n",[EList ] ) ,
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(StructName)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(StructName)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Struct definition: ~s",
[StructName])],
c),
emit(Fd, "typedef struct {\n"),
lists:foreach(
fun({Type, Name}) ->
emit_struct_member(Fd, G, N1, X, Name, Type)
end,
EList),
emit(Fd, "} ~s;\n\n", [StructName]),
create_c_struct_coding_file(G, N, X, nil, StructName,
EList, struct),
emit(Fd, "\n#endif\n\n");
false ->
ok
end.
%% Extracts array dimention(s)
get_structelement_tk({tk_struct, _, _, EList}, EN) ->
{value, {EN, ArrayTK}} = lists:keysearch(EN, 1, EList),
ArrayTK.
extract_dim({tk_array, {tk_array, T, D1}, D}) ->
[integer_to_list(D) | extract_dim({tk_array, T, D1})];
extract_dim({tk_array, _, D}) ->
[integer_to_list(D)].
%% Makes the array name
mk_array_name(Name,Dim) ->
Name ++ mk_array_name(Dim).
mk_array_name([]) ->
"";
mk_array_name([Dim|Dims]) ->
"[" ++ Dim ++ "]" ++ mk_array_name(Dims).
emit_struct_member(Fd, G, N, X, Name,{Type,Array}) when is_record(Array, array)->
{_, _, StructTK, _} =
ic_symtab:get_full_scoped_name(
G,
N,
ic_symtab:scoped_id_new(ic_forms:get_id2(X))),
ArrayTK = get_structelement_tk(StructTK, Name),
Dim = extract_dim(ArrayTK),
emit(Fd, " ~s ~s;\n",
[ic_cbe:mk_c_type(G, N, Type),mk_array_name(Name,Dim)]);
emit_struct_member(Fd, _G, N, _X, Name, Union) when is_record(Union, union)->
emit(Fd, " ~s ~s;\n",
[ic_util:to_undersc([ic_forms:get_id2(Union) | N]),Name]);
emit_struct_member(Fd, _G, _N, _X, Name, {string, _}) ->
emit(Fd, " CORBA_char *~s;\n",
[Name]);
emit_struct_member(Fd, _G, N, _X, Name, {sequence, _Type, _Length}) ->
%% Sequence used as struct
emit(Fd, " ~s ~s;\n",
[ic_util:to_undersc([Name | N]), Name]);
emit_struct_member(Fd, G, N, X, Name, Type)
when element(1, Type) == scoped_id ->
CType = ic_cbe:mk_c_type(G, N, Type, evaluate_not),
emit_struct_member(Fd, G, N, X, Name, CType);
emit_struct_member(Fd, G, N, _X, Name, {enum, Type}) ->
emit(Fd, " ~s ~s;\n",
[ic_cbe:mk_c_type(G, N, Type),
Name]);
emit_struct_member(Fd, _G, _N, _X, Name, "ic_erlang_term*") ->
emit(Fd, " ic_erlang_term* ~s;\n",
[Name]);
emit_struct_member(Fd, _G, _N, _X, Name, Type) when is_list(Type) ->
emit(Fd, " ~s ~s;\n",
[Type, Name]);
emit_struct_member(Fd, G, N, _X, Name, Type) ->
emit(Fd, " ~s ~s;\n",
[ic_cbe:mk_c_type(G, N, Type),
Name]).
emit_typedef(G, N, X, erlang) ->
case X of
{typedef,_,[{array,_,_}],_} -> %% Array but not a typedef of
%% an array definition
case ic_options:get_opt(G, be) of
noc ->
mkFileArrObj(G,N,X,erlang);
_ ->
%% Search the table to see if the type is local or
%% inherited.
PTab = ic_genobj:pragmatab(G),
Id = ic_forms:get_id2(X),
case ets:match(PTab,{file_data_local,'_','_',
typedef,N,Id,
ic_util:to_undersc([Id | N]),
'_','_'}) of
[[]] ->
%% Local, create erlang file for the array
mkFileArrObj(G,N,X,erlang);
_ ->
%% Inherited, do nothing
ok
end
end;
{typedef,{sequence,_,_},_,{tk_sequence,_,_}} ->
%% Sequence but not a typedef of
%% a typedef of a sequence definition
case ic_options:get_opt(G, be) of
noc ->
mkFileRecObj(G,N,X,erlang);
_ ->
%% Search the table to see if the type is local or
%% inherited.
PTab = ic_genobj:pragmatab(G),
Id = ic_forms:get_id2(X),
case ets:match(PTab,{file_data_local,'_','_',typedef,
N,Id,
ic_util:to_undersc([Id | N]),
'_','_'}) of
[[]] ->
%% Local, create erlang file for the sequence
mkFileRecObj(G,N,X,erlang);
_ ->
%% Inherited, do nothing
ok
end
end;
_ ->
ok
end;
emit_typedef(G, N, X, c) ->
B = ic_forms:get_body(X),
if
is_record(B, sequence) ->
emit_sequence_head_def(G, N, X, B, c);
true ->
lists:foreach(fun(D) ->
emit_typedef(G, N, D, B, c)
end,
ic_forms:get_idlist(X))
end.
emit_typedef(G, N, D, Type, c) when is_record(D, array) ->
emit_array(G, N, D, Type);
emit_typedef(G, N, D, Type, c) ->
Name = ic_util:to_undersc([ic_forms:get_id2(D) | N]),
CType = ic_cbe:mk_c_type(G, N, Type),
TDType = mk_base_type(G, N, Type),
ic_code:insert_typedef(G, Name, TDType),
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(Name)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(Name)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Type definition ~s "
"for type ~s",
[Name, CType])],
c),
emit(Fd, "typedef ~s ~s;\n",
[CType, Name]),
emit(Fd, "\n#endif\n\n"),
ic_codegen:nl(Fd);
false ->
ok
end.
mk_base_type(G, N, S) when element(1, S) == scoped_id ->
{FullScopedName, _T, _TK, _} = ic_symtab:get_full_scoped_name(G, N, S),
BT = ic_code:get_basetype(G, ic_util:to_undersc(FullScopedName)),
case BT of
"erlang_binary" ->
"erlang_binary";
"erlang_pid" ->
"erlang_pid";
"erlang_port" ->
"erlang_port";
"erlang_ref" ->
"erlang_ref";
"erlang_term" ->
"ic_erlang_term*";
Type ->
Type
end;
mk_base_type(_G, _N, S) ->
S.
emit_array(G, N, D, Type) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
Name = ic_util:to_undersc([ic_forms:get_id2(D) | N]),
{_, _, ArrayTK, _} =
ic_symtab:get_full_scoped_name(G, N,
ic_symtab:scoped_id_new(
ic_forms:get_id(D))),
Dim = extract_dim(ArrayTK),
CType = ic_cbe:mk_c_type(G, N, Type),
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(Name)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(Name)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Array definition ~s "
"for type ~s",
[Name, CType])],
c),
emit(Fd, "typedef ~s ~s~s;\n",
[CType, Name, ic_cbe:mk_dim(Dim)]),
emit(Fd, "typedef ~s ~s_slice~s;\n",
[CType, Name, ic_cbe:mk_slice_dim(Dim)]),
ic_codegen:nl(Fd),
create_c_array_coding_file(G, N, {Name, Dim}, Type, typedef),
emit(Fd, "\n#endif\n\n");
false ->
ok
end.
open_c_coding_file(G, Name) ->
SName = string:concat(ic_util:mk_oe_name(G, "code_"), Name),
FName =
ic_file:join(ic_options:get_opt(G, stubdir),ic_file:add_dot_c(SName)),
case file:open(FName, [write]) of
{ok, Fd} ->
{Fd, SName};
Other ->
exit(Other)
end.
create_c_array_coding_file(G, N, {Name, Dim}, Type, TypeDefFlag) ->
{Fd , SName} = open_c_coding_file(G, Name),
HFd = ic_genobj:hrlfiled(G), %% Write on stubfile header
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, c),
emit(Fd, "#include \"~s\"\n\n",[HrlFName]),
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Fd = ic_genobj : stubfiled(G ) , % % Write on stubfile
HFd = ic_genobj : ) , % % Write on stubfile header
HrlFName = filename : basename(ic_genobj : include_file(G ) ) ,
%% emit(Fd, "#include \"~s\"\n\n",[HrlFName]),
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, int*, int*);\n",
[ic_util:mk_oe_name(G, "sizecalc_"), Name]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, int* oe_size_count_index, "
"int* oe_size) {\n", [ic_util:mk_oe_name(G, "sizecalc_"), Name]),
emit(Fd, " int oe_malloc_size = 0;\n",[]),
emit(Fd, " int oe_error_code = 0;\n",[]),
emit(Fd, " int oe_type = 0;\n",[]),
emit(Fd, " int oe_array_size = 0;\n",[]),
{ok, RamFd} = ram_file:open([], [binary, write]),
emit_sizecount(array, G, N, nil, RamFd, {Name, Dim}, Type),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
%% Move data from ram file to output file.
{ok, Data} = ram_file:get_file(RamFd),
emit(Fd, Data),
ram_file:close(RamFd),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n",[]),
put(op_variable_count, 0),
put(tmp_declarations, []),
RefStr = get_refStr(Dim),
case TypeDefFlag of
typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, ~s);\n",
[ic_util:mk_oe_name(G, "encode_"), Name, Name]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, ~s oe_rec) {\n",
[ic_util:mk_oe_name(G, "encode_"), Name, Name]);
no_typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, ~s oe_rec~s);\n",
[ic_util:mk_oe_name(G, "encode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, ~s oe_rec~s) {\n",
[ic_util:mk_oe_name(G, "encode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr])
end,
emit(Fd, " int oe_error_code = 0;\n",[]),
{ok, RamFd1} = ram_file:open([], [binary, write]),
case TypeDefFlag of
typedef ->
emit_encode(array, G, N, nil, RamFd1, {Name, Dim}, Type);
no_typedef ->
emit_encode(array_no_typedef, G, N, nil, RamFd1, {Name, Dim}, Type)
end,
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
%% Move data from ram file to output file.
{ok, Data1} = ram_file:get_file(RamFd1),
emit(Fd, Data1),
ram_file:close(RamFd1),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n",[]),
put(op_variable_count, 0),
put(tmp_declarations, []),
case TypeDefFlag of
typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, char *, "
"int*, ~s);\n",
[ic_util:mk_oe_name(G, "decode_"), Name, Name]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, char *oe_first, "
"int* oe_outindex, ~s oe_out) {\n",
[ic_util:mk_oe_name(G, "decode_"), Name, Name]);
no_typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, char *, int*, "
"~s oe_rec~s);\n",
[ic_util:mk_oe_name(G, "decode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, char *oe_first, "
"int* oe_outindex, ~s oe_out~s) {\n",
[ic_util:mk_oe_name(G, "decode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr])
end,
emit(Fd, " int oe_error_code = 0;\n",[]),
emit(Fd, " int oe_array_size = 0;\n",[]),
{ok, RamFd2} = ram_file:open([], [binary, write]),
case TypeDefFlag of
typedef ->
emit_decode(array, G, N, nil, RamFd2, {Name, Dim}, Type);
no_typedef ->
emit_decode(array_no_typedef, G, N, nil, RamFd2, {Name, Dim}, Type)
end,
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
%% Move data from ram file to output file.
{ok, Data2} = ram_file:get_file(RamFd2),
emit(Fd, Data2),
ram_file:close(RamFd2),
emit(Fd, " *oe_outindex = ~s;\n\n",[align("*oe_outindex")]),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n",[]),
file:close(Fd).
get_refStr([]) ->
"";
get_refStr([X|Xs]) ->
"[" ++ X ++ "]" ++ get_refStr(Xs).
emit_sequence_head_def(G, N, X, T, c) ->
%% T is the sequence
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
SeqName = ic_util:to_undersc([ic_forms:get_id2(X) | N]),
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(SeqName)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(SeqName)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Struct definition: ~s",
[SeqName])],
c),
emit(Fd, "typedef struct {\n"),
emit(Fd, " CORBA_unsigned_long _maximum;\n"),
emit(Fd, " CORBA_unsigned_long _length;\n"),
emit_seq_buffer(Fd, G, N, T#sequence.type),
emit(Fd, "} ~s;\n\n", [SeqName]),
create_c_struct_coding_file(G, N, X, T, SeqName,
T#sequence.type, sequence_head),
emit(Fd, "\n#endif\n\n");
false ->
ok
end.
emit_seq_buffer(Fd, G, N, Type) ->
emit(Fd, " ~s* _buffer;\n",
[ic_cbe:mk_c_type(G, N, Type)]).
%%------------------------------------------------------------
%%
%% Emit decode bodies for functions in C for array, sequences and
%% structs.
%%
%%------------------------------------------------------------
emit_decode(array, G, N, _T, Fd, {_Name, Dim}, Type) ->
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
AlignName =
lists:concat(["*oe_outindex + ", dim_multiplication(Dim),
" * sizeof(", ic_cbe:mk_c_type(G, N, Type),")"]),
emit(Fd, " *oe_outindex = ~s;\n\n",[align(AlignName)]),
array_decode_dimension_loop(G, N, Fd, Dim, "", Type, array);
emit_decode(array_no_typedef, G, N, _T, Fd, {_Name, Dim}, Type) ->
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
AlignName =
lists:concat(["*oe_outindex + ", dim_multiplication(Dim),
" * sizeof(", ic_cbe:mk_c_type(G, N, Type),")"]),
emit(Fd, " *oe_outindex = ~s;\n\n",[align(AlignName)]),
array_decode_dimension_loop(G, N, Fd, Dim, "", Type, array_no_typedef);
emit_decode(sequence_head, G, N, T, Fd, SeqName, ElType) ->
ic_cbe:store_tmp_decl(" int oe_seq_len = 0;\n", []),
ic_cbe:store_tmp_decl(" int oe_seq_count = 0;\n", []),
ic_cbe:store_tmp_decl(" int oe_seq_dummy = 0;\n", []),
TmpBuf =
case ictype:isBasicTypeOrEterm(G, N, ElType) of
true ->
Tmp = "oe_seq_tmpbuf",
ic_cbe:store_tmp_decl(" char* ~s = 0;\n", [Tmp]),
Tmp;
false ->
"NOT USED"
end,
MaxSize = get_seq_max(T),
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
emit(Fd, " *oe_outindex = ~s;\n\n",
[align(["*oe_outindex + sizeof(", SeqName, ")"])]),
Ctype = ic_cbe:mk_c_type(G, N, ElType),
emit(Fd, " if ((oe_error_code = ei_decode_list_header(oe_env->_inbuf, "
"&oe_env->_iin, &oe_seq_len)) < 0) {\n"),
case ictype:isBasicTypeOrEterm(G, N, ElType) of
true ->
emit(Fd, " int oe_type = 0;\n"),
emit(Fd, " (int) ei_get_type(oe_env->_inbuf, &oe_env->_iin, "
"&oe_type, &oe_seq_len);\n\n"),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_seq_len > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, "
"CORBA_SYSTEM_EXCEPTION, DATA_CONVERSION, "
"\"Length of sequence `~s' out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
emit(Fd, " oe_out->_maximum = oe_seq_len;\n"),
emit(Fd, " oe_out->_length = oe_seq_len;\n"),
emit(Fd, " oe_out->_buffer = (void *) (oe_first + "
"*oe_outindex);\n"),
emit(Fd, " *oe_outindex = ~s;\n",
[align(["*oe_outindex + (sizeof(", Ctype, ") * "
"oe_out->_length)"])]),
emit(Fd,
" if ((~s = malloc(oe_seq_len + 1)) == NULL) {\n"
" CORBA_exc_set(oe_env, CORBA_SYSTEM_EXCEPTION, "
"NO_MEMORY, \"Cannot malloc\");\n"
" return -1;\n"
" }\n", [TmpBuf]),
emit(Fd, " if ((oe_error_code = ei_decode_string("
"oe_env->_inbuf, &oe_env->_iin, ~s)) < 0) {\n", [TmpBuf]),
emit(Fd, " CORBA_free(~s);\n\n", [TmpBuf]),
emit_c_dec_rpt(Fd, " ", "string1", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (oe_seq_count = 0; "
"oe_seq_count < oe_out->_length; oe_seq_count++) {\n"),
case ictype:isBasicType(G, N, ElType) of
true ->
emit(Fd, " oe_out->_buffer[oe_seq_count] = (unsigned char) "
"~s[oe_seq_count];\n\n", [TmpBuf]);
false -> %% Term
emit(Fd, " oe_out->_buffer[oe_seq_count]->type = ic_integer;\n", []),
emit(Fd, " oe_out->_buffer[oe_seq_count]->value.i_val = (long) ~s[oe_seq_count];\n",
[TmpBuf])
end,
emit(Fd, " }\n\n", []),
emit(Fd, " CORBA_free(~s);\n\n", [TmpBuf]);
false ->
emit(Fd, " return oe_error_code;\n")
end,
emit(Fd, " } else {\n"),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_seq_len > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, "
"CORBA_SYSTEM_EXCEPTION, DATA_CONVERSION, "
"\"Length of sequence `~s' out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
emit(Fd, " oe_out->_maximum = oe_seq_len;\n"),
emit(Fd, " oe_out->_length = oe_seq_len;\n"),
emit(Fd, " oe_out->_buffer = (void *) (oe_first + *oe_outindex);\n"),
emit(Fd, " *oe_outindex = ~s;\n\n",
[align(["*oe_outindex + (sizeof(", Ctype, ") * oe_out->_length)"])]),
if
Ctype == "CORBA_char *" ->
emit(Fd, " for (oe_seq_count = 0; "
"oe_seq_count < oe_out->_length; oe_seq_count++) {\n"),
emit(Fd, " oe_out->_buffer[oe_seq_count] = "
"(void*) (oe_first + *oe_outindex);\n\n"),
ic_cbe:emit_decoding_stmt(G, N, Fd, ElType,
"oe_out->_buffer[oe_seq_count]",
"",
"oe_env->_inbuf", 0, "", caller_dyn),
emit(Fd, " *oe_outindex = ~s;",
[align(["*oe_outindex + strlen(oe_out->_buffer["
"oe_seq_count]) + 1"])]);
true ->
emit(Fd, " for (oe_seq_count = 0; "
"oe_seq_count < oe_out->_length; oe_seq_count++) {\n"),
case ictype:isArray(G, N, ElType) of
%% XXX Silly. There is no real difference between the
%% C statements produced by the following calls.
true ->
ic_cbe:emit_decoding_stmt(G, N, Fd, ElType,
"oe_out->_buffer[oe_seq_count]",
"",
"oe_env->_inbuf",
0, "oe_outindex", generator);
false ->
ic_cbe:emit_decoding_stmt(G, N, Fd, ElType,
"oe_out->_buffer + oe_seq_count",
"",
"oe_env->_inbuf",
0, "oe_outindex", generator)
end
end,
emit(Fd, " }\n"),
emit(Fd, " if (oe_out->_length != 0) {\n"),
emit(Fd, " if ((oe_error_code = ei_decode_list_header("
"oe_env->_inbuf, &oe_env->_iin, &oe_seq_dummy)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_list_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " } else\n"),
emit(Fd, " oe_out->_buffer = NULL;\n"),
emit(Fd, " }\n");
emit_decode(struct, G, N, _T, Fd, StructName, ElTypes) ->
Length = length(ElTypes) + 1,
Tname = ic_cbe:mk_variable_name(op_variable_count),
Tname1 = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
ic_cbe:store_tmp_decl(" char ~s[256];\n\n",[Tname1]),
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
AlignName = lists:concat(["*oe_outindex + sizeof(",StructName,")"]),
emit(Fd, " *oe_outindex = ~s;\n\n", [align(AlignName)]),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"&oe_env->_iin, &~s)) < 0) {\n", [Tname]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (~s != ~p) {\n",[Tname, Length]),
emit_c_dec_rpt(Fd, " ", "tuple header size != ~p", [Length]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = ei_decode_atom(oe_env->_inbuf, "
"&oe_env->_iin, ~s)) < 0) {\n", [Tname1]),
emit_c_dec_rpt(Fd, " ", "ei_decode_atom", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (strcmp(~s, ~p) != 0)\n",[Tname1, StructName]),
emit(Fd, " return -1;\n\n"),
lists:foreach(
fun({ET, EN}) ->
case ic_cbe:is_variable_size(G, N, ET) of
true ->
case ET of
{struct, _, _, _} ->
Sequence member = a struct
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN,
"", "oe_env->_inbuf",
0,
"oe_outindex",
generator);
{sequence, _, _} ->
Sequence member = a struct XXX ? ?
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
EN,
"&oe_out->" ++ EN,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{_,{array, _, _}} ->
emit(Fd, " oe_out->~s = (void *) "
"(oe_first+*oe_outindex);\n\n",[EN]),
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
EN, "oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{union, _, _, _, _} ->
Sequence member = a union
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{string,_} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator_malloc);
{scoped_id,_,_,_} ->
case ictype:member2type(G,StructName,EN) of
array ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
struct ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN ,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
sequence ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
union ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
_ ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator)
end;
_ ->
emit(Fd, " oe_out->~s = (void *) "
"(oe_first+*oe_outindex);\n\n",[EN]),
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0, "oe_outindex",
generator)
end;
false ->
case ET of
{struct, _, _, _} ->
%% A struct member
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{_,{array, _, _}} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
EN,
"oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{union, _, _, _, _} ->
Sequence member = a union
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{_,_} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{scoped_id,_,_,_} ->
case ic_symtab:get_full_scoped_name(G, N, ET) of
{_FullScopedName, _, {tk_array,_,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
{_FullScopedName, _, {tk_string,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
{_FullScopedName, _, {tk_struct,_,_,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
{_FullScopedName, _,
{tk_union,_,_,_,_,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
_ ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator)
end
end
end
end,
ElTypes).
ref_array_static_dec(array, true) ->
Typedef , Static , Basic Type
"&(oe_out)";
ref_array_static_dec(array, false) ->
Typedef , Static , Constr Type
"&(oe_out)";
ref_array_static_dec(array_no_typedef, true) ->
No Typedef , Static , Basic Type
"&oe_out";
ref_array_static_dec(array_no_typedef, false) ->
No Typedef , Static , Constr Type
"&oe_out".
ref_array_dynamic_dec(G, N, T, array) ->
case ictype:isString(G, N, T) of
Typedef , Dynamic , String
"oe_out";
Typedef , Dynamic , No String
"&(oe_out)"
end;
ref_array_dynamic_dec(G, N, T, array_no_typedef) ->
case ictype:isString(G, N, T) of
true -> % No Typedef, Dynamic, String
"oe_out";
No Typedef , Dynamic , No String
"&oe_out"
end.
array_decode_dimension_loop(G, N, Fd, [Dim], Dimstr, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"&oe_env->_iin, &oe_array_size)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
%% This is disabled due to a bug in erl_interface :
%% tuples inside tuples hae no correct data about the size
%% of the tuple........( allways = 0 )
%%emit(Fd, " if (oe_array_size != ~s)\n",[Dim]),
%%emit(Fd, " return -1;\n\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
ArrAccess =
case ic_cbe:is_variable_size(G, N, Type) of
true ->
ref_array_dynamic_dec(G, N, Type, TDFlag) ++
Dimstr ++ "[" ++ Tname ++ "]";
false ->
ref_array_static_dec(TDFlag, ictype:isBasicType(G,N,Type)) ++
Dimstr ++ "[" ++ Tname ++ "]"
end,
ic_cbe:emit_decoding_stmt(G, N, Fd, Type,
ArrAccess,
"", "oe_env->_inbuf", 0,
"oe_outindex", generator),
%% emit(Fd, "\n *oe_outindex +=
sizeof(~s);\n",[ic_cbe : mk_c_type(G , N , Type ) ] ) ,
emit(Fd, " }\n");
array_decode_dimension_loop(G, N, Fd, [Dim | Ds], _Dimstr, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"&oe_env->_iin, &oe_array_size)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
%% This is disabled due to a bug in erl_interface :
%% tuples inside tuples hae no correct data about the size
%% of the tuple........( allways = 0 )
%%emit(Fd, " if (oe_array_size != ~s)\n",[Dim]),
%%emit(Fd, " return -1;\n\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
array_decode_dimension_loop(G, N, Fd, Ds, "[" ++ Tname ++ "]" , Type,
TDFlag),
emit(Fd, " }\n").
dim_multiplication([D]) ->
D;
dim_multiplication([D |Ds]) ->
D ++ "*" ++ dim_multiplication(Ds).
emit_encode(array, G, N, _T, Fd, {_Name, Dim}, Type) ->
array_encode_dimension_loop(G, N, Fd, Dim, {"",""}, Type, array);
emit_encode(array_no_typedef, G, N, _T, Fd, {_Name, Dim}, Type) ->
array_encode_dimension_loop(G, N, Fd, Dim, {"",""}, Type,
array_no_typedef);
emit_encode(sequence_head, G, N, T, Fd, SeqName, ElType) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n\n",[Tname]),
MaxSize = get_seq_max(T),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_rec->_length > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, CORBA_SYSTEM_EXCEPTION, "
"DATA_CONVERSION, \"Length of sequence `~s' "
"out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
emit(Fd, " if (oe_rec->_length != 0) {\n"),
emit(Fd, " if ((oe_error_code = oe_ei_encode_list_header(oe_env, "
"oe_rec->_length)) < 0) {\n",
[]),
emit_c_enc_rpt(Fd, " ", "oi_ei_encode_list_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < oe_rec->_length; ~s++) {\n",
[Tname, Tname, Tname]),
case ElType of
{_,_} -> %% ElType = elementary type or pointer type
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType, "oe_rec->_buffer[" ++
Tname ++ "]", "oe_env->_outbuf");
{scoped_id,local,_,["term","erlang"]} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType, "oe_rec->_buffer[" ++
Tname ++ "]", "oe_env->_outbuf");
{scoped_id,_,_,_} ->
case ic_symtab:get_full_scoped_name(G, N, ElType) of
{_, typedef, TDef, _} ->
case TDef of
{tk_struct,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
{tk_sequence,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
{tk_union,_,_,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf")
end;
{_,enum,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf")
end;
_ -> %% ElType = structure
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++ Tname ++ "]",
"oe_env->_outbuf")
end,
emit(Fd, " }\n"),
emit(Fd, " }\n"),
emit(Fd, " if ((oe_error_code = oe_ei_encode_empty_list(oe_env)) < 0) {\n"),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_empty_list", []),
emit(Fd, " return oe_error_code;\n }\n");
emit_encode(struct, G, N, _T, Fd, StructName, ElTypes) ->
Length = length(ElTypes) + 1,
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_tuple_header(oe_env, ~p)) < 0) {\n", [Length]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_atom(oe_env, ~p)) < 0) {\n", [StructName]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_atom", []),
emit(Fd, " return oe_error_code;\n }\n"),
lists:foreach(
fun({ET, EN}) ->
case ET of
{sequence, _, _} ->
%% Sequence = struct
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++ EN,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
{_,{array, _, _Dims}} ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++ EN,
"oe_rec->" ++ EN,
"oe_env->_outbuf");
{union,_,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
{struct,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
{scoped_id,_,_,_} ->
case ictype:member2type(G,StructName,EN) of
struct ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
sequence ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
union ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
array ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"oe_rec->" ++ EN,
"oe_env->_outbuf");
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"oe_rec->" ++ EN,
"oe_env->_outbuf")
end;
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"oe_rec->" ++ EN,
"oe_env->_outbuf")
end
end,
ElTypes).
ref_array_static_enc(array, true) ->
Typedef , Static , Basic Type
"oe_rec";
ref_array_static_enc(array, false) ->
Typedef , Static , Constr Type
"&(oe_rec)";
ref_array_static_enc(array_no_typedef, true) ->
No Typedef , Static , Basic Type
"oe_rec";
ref_array_static_enc(array_no_typedef, false) ->
No Typedef , Static , Constr Type
"&oe_rec".
ref_array_dynamic_enc(G, N, T, array) ->
case ictype:isString(G, N, T) of
Typedef , Dynamic , String
"oe_rec";
Typedef , Dynamic , No String
"&(oe_rec)"
end;
ref_array_dynamic_enc(G, N, T, array_no_typedef) ->
case ictype:isString(G, N, T) of
true -> % No Typedef, Dynamic, String
"oe_rec";
No Typedef , Dynamic , No String
"&oe_rec"
end.
array_encode_dimension_loop(G, N, Fd, [Dim], {Str1,_Str2}, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_tuple_header(oe_env, ~s)) < 0) {\n", [Dim]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
ArrAccess =
case ic_cbe:is_variable_size(G, N, Type) of
true ->
ref_array_dynamic_enc(G, N, Type, TDFlag) ++
Str1 ++ "[" ++ Tname ++ "]";
false ->
ref_array_static_enc(TDFlag, ictype:isBasicType(G,N,Type)) ++
Str1 ++ "[" ++ Tname ++ "]"
end,
ic_cbe:emit_encoding_stmt(G, N, Fd, Type, ArrAccess, "oe_env->_outbuf"),
emit(Fd, " }\n");
array_encode_dimension_loop(G, N, Fd, [Dim | Ds],{Str1,Str2}, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_tuple_header(oe_env, ~s)) < 0) {\n", [Dim]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
array_encode_dimension_loop(G, N, Fd, Ds,
{Str1 ++ "[" ++ Tname ++ "]", Str2},
Type, TDFlag),
emit(Fd, " }\n").
emit_sizecount(array, G, N, _T, Fd, {_Name, Dim}, Type) ->
emit(Fd, " if(*oe_size == 0)\n",[]),
AlignName = lists:concat(["*oe_size + ", dim_multiplication(Dim),
" * sizeof(", ic_cbe:mk_c_type(G, N, Type),")"]),
emit(Fd, " *oe_size = ~s;\n\n",[align(AlignName)]),
array_size_dimension_loop(G, N, Fd, Dim, Type),
emit(Fd, " *oe_size = ~s;\n\n",
[align("*oe_size + oe_malloc_size")]),
ic_codegen:nl(Fd);
emit_sizecount(sequence_head, G, N, T, Fd, SeqName, ElType) ->
ic_cbe:store_tmp_decl(" int oe_seq_len = 0;\n", []),
ic_cbe:store_tmp_decl(" int oe_seq_count = 0;\n", []),
emit(Fd, " if(*oe_size == 0)\n",[]),
emit(Fd, " *oe_size = ~s;\n\n",
[align(["*oe_size + sizeof(", SeqName, ")"])]),
MaxSize = get_seq_max(T),
emit(Fd, " if ((oe_error_code = ei_get_type(oe_env->_inbuf, "
"oe_size_count_index, &oe_type, &oe_seq_len)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_seq_len > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, CORBA_SYSTEM_EXCEPTION, "
"DATA_CONVERSION, \"Length of sequence `~s' "
"out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
CType = ic_cbe:mk_c_type(G, N, ElType),
emit(Fd, " if ((oe_error_code = ei_decode_list_header(oe_env->_inbuf, "
"oe_size_count_index, NULL)) < 0) {\n"),
case ictype:isBasicTypeOrEterm(G, N, ElType) of
true ->
emit(Fd, " if ((oe_error_code = ei_decode_string(oe_env->"
"_inbuf, oe_size_count_index, NULL)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_string", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " oe_malloc_size = ~s;\n\n",
[align(["sizeof(", CType, ") * oe_seq_len"])]);
false ->
emit_c_dec_rpt(Fd, " ", "non mea culpa", []),
emit(Fd, " return oe_error_code;\n\n")
end,
emit(Fd, " } else {\n"),
emit(Fd, " oe_malloc_size = ~s;\n\n",
[align(["sizeof(", CType, ") * oe_seq_len"])]),
emit(Fd, " for (oe_seq_count = 0; oe_seq_count < oe_seq_len; "
"oe_seq_count++) {\n"),
ic_cbe:emit_malloc_size_stmt(G, N, Fd, ElType,
"oe_env->_inbuf", 0, generator),
emit(Fd, " }\n"),
emit(Fd, " if (oe_seq_len != 0) \n"),
emit(Fd, " if ((oe_error_code = ei_decode_list_header(oe_env->_inbuf,"
"oe_size_count_index, NULL)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_list_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " }\n"),
emit(Fd, " *oe_size = ~s;\n\n", [align("*oe_size + oe_malloc_size")]);
emit_sizecount(struct, G, N, _T, Fd, StructName, ElTypes) ->
Length = length(ElTypes) + 1,
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n\n",[Tname]),
emit(Fd, " if(*oe_size == 0)\n",[]),
AlignName = lists:concat(["*oe_size + sizeof(",StructName,")"]),
emit(Fd, " *oe_size = ~s;\n\n", [align(AlignName)]),
ic_codegen:nl(Fd),
emit(Fd, " if ((oe_error_code = "
"ei_get_type(oe_env->_inbuf, oe_size_count_index, &oe_type, "
"&~s)) < 0) {\n", [Tname]),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (~s != ~p) {\n",[Tname, Length]),
emit_c_dec_rpt(Fd, " ", "~s != ~p", [Tname, Length]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = "
"ei_decode_tuple_header(oe_env->_inbuf, "
"oe_size_count_index, 0)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if ((oe_error_code = "
"ei_decode_atom(oe_env->_inbuf, oe_size_count_index, 0)) < 0) {\n", []),
emit_c_dec_rpt(Fd, " ", "ei_decode_atom", []),
emit(Fd, " return oe_error_code;\n }\n"),
lists:foreach(
fun({ET, EN}) ->
case ic_cbe:is_variable_size(G, N, ET) of
true ->
case ET of
{sequence, _, _} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ EN,
"oe_env->_inbuf",
0,
generator);
{_,{array, _, _}} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ EN,
"oe_env->_inbuf",
0,
generator);
{union,_,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
{struct,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
_ ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
ET,
"oe_env->_inbuf",
0,
generator)
end;
false ->
case ET of
{_,{array, _, _}} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ EN,
"oe_env->_inbuf",
0,
generator);
{union,_,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
{struct,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
_ ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
ET,
"oe_env->_inbuf",
1,
generator)
end
end
end,
ElTypes),
emit(Fd, " *oe_size = ~s;\n\n",
[align("*oe_size + oe_malloc_size")]).
array_size_dimension_loop(G, N, Fd, [Dim], Type) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"ei_get_type(oe_env->_inbuf, oe_size_count_index, "
"&oe_type, &oe_array_size)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (oe_array_size != ~s) {\n",[Dim]),
emit_c_dec_rpt(Fd, " ", "array size != ~s", [Dim]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"oe_size_count_index, 0)) < 0) {\n", []),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
ic_cbe:emit_malloc_size_stmt(G, N, Fd,
Type, "oe_env->_inbuf", 0, generator),
emit(Fd, " }\n");
array_size_dimension_loop(G, N, Fd, [Dim | Ds], Type) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"ei_get_type(oe_env->_inbuf, oe_size_count_index, "
"&oe_type, &oe_array_size)) < 0) {\n", []),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (oe_array_size != ~s) {\n",[Dim]),
emit_c_dec_rpt(Fd, " ", "array size != ~s", [Dim]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"oe_size_count_index, 0)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
array_size_dimension_loop(G, N, Fd, Ds, Type),
emit(Fd, " }\n").
create_c_struct_coding_file(G, N, _X, T, StructName, ElTypes, StructType) ->
{Fd , SName} = open_c_coding_file(G, StructName), % stub file
HFd = ic_genobj:hrlfiled(G), % stub header file
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, c),
HrlFName = filename:basename(ic_genobj:include_file(G)),
emit(Fd, "#include \"~s\"\n\n",[HrlFName]),
%% Size count
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, int*, int*);\n",
[ic_util:mk_oe_name(G, "sizecalc_"), StructName]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, "
"int* oe_size_count_index, int* oe_size)\n{\n",
[ic_util:mk_oe_name(G, "sizecalc_"), StructName]),
emit(Fd, " int oe_malloc_size = 0;\n",[]),
emit(Fd, " int oe_error_code = 0;\n",[]),
emit(Fd, " int oe_type = 0;\n",[]),
{ok, RamFd} = ram_file:open([], [binary, write]),
emit_sizecount(StructType, G, N, T, RamFd, StructName, ElTypes),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
%% Move data from ram file to output file.
{ok, Data} = ram_file:get_file(RamFd),
emit(Fd, Data),
ram_file:close(RamFd),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n\n",[]),
%% Encode
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, ~s*);\n",
[ic_util:mk_oe_name(G, "encode_"), StructName, StructName]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, ~s* oe_rec)\n{\n",
[ic_util:mk_oe_name(G, "encode_"), StructName, StructName]),
emit(Fd, " int oe_error_code = 0;\n",[]),
{ok, RamFd1} = ram_file:open([], [binary, write]),
emit_encode(StructType, G, N, T, RamFd1, StructName, ElTypes),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
%% Move data from ram file to output file.
{ok, Data1} = ram_file:get_file(RamFd1),
emit(Fd, Data1),
ram_file:close(RamFd1),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n\n",[]),
%% Decode
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, char *, int*, ~s *);\n",
[ic_util:mk_oe_name(G, "decode_"), StructName, StructName]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, char *oe_first, "
"int* oe_outindex, "
"~s *oe_out)\n{\n",
[ic_util:mk_oe_name(G, "decode_"), StructName, StructName]),
emit(Fd, " int oe_error_code = 0;\n",[]),
{ok, RamFd2} = ram_file:open([], [binary, write]),
emit_decode(StructType, G, N, T, RamFd2, StructName, ElTypes),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
%% Move data from ram file to output file.
{ok, Data2} = ram_file:get_file(RamFd2),
emit(Fd, Data2),
ram_file:close(RamFd2),
emit(Fd, " *oe_outindex = ~s;\n",[align("*oe_outindex")]),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n\n",[]),
file:close(Fd).
%%------------------------------------------------------------
%%
%% emit primitive for unions.
%%
%%------------------------------------------------------------
emit_union(G, N, X, erlang) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
ic_codegen:record(G, X,
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
nil,nil),
mkFileRecObj(G,N,X,erlang);
false -> ok
end;
emit_union(_G, _N, _X, c) -> %% Not supported in c backend
true.
%%------------------------------------------------------------
%%
%% emit erlang modules for objects with record definitions
%% (such as unions or structs), or sequences
%%
%% The record files, other than headers are only generated
for CORBA ...... If wished an option could allows even
%% for other backends ( not necessary anyway )
%%
%%------------------------------------------------------------
mkFileRecObj(G,N,X,erlang) ->
case ic_options:get_opt(G, be) of
erl_corba ->
SName =
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
FName =
ic_file:join(ic_options:get_opt(G, stubdir),
ic_file:add_dot_erl(SName)),
case file:open(FName, [write]) of
{ok, Fd} ->
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, erlang),
emit(Fd, "-include(~p).\n\n",[HrlFName]),
emit_exports(G,Fd),
emit_rec_methods(G,N,X,SName,Fd),
ic_codegen:nl(Fd),
ic_codegen:nl(Fd),
file:close(Fd);
Other ->
exit(Other)
end;
_ ->
true
end.
%%------------------------------------------------------------
%%
%% emit erlang modules for objects with array definitions..
%%
%%------------------------------------------------------------
mkFileArrObj(G,N,X,erlang) ->
SName =
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
FName =
ic_file:join(ic_options:get_opt(G, stubdir),
ic_file:add_dot_erl(SName)),
case file:open(FName, [write]) of
{ok, Fd} ->
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, erlang),
emit(Fd, "-include(~p).\n\n",[HrlFName]),
emit_exports(G,Fd),
emit_arr_methods(G,N,X,SName,Fd),
ic_codegen:nl(Fd),
ic_codegen:nl(Fd),
file:close(Fd);
Other ->
exit(Other)
end.
%%------------------------------------------------------------
%%
emit exports for erlang modules which represent records .
%%
%%------------------------------------------------------------
emit_exports(G,Fd) ->
case ic_options:get_opt(G, be) of
erl_corba ->
emit(Fd, "-export([tc/0,id/0,name/0]).\n\n\n\n",[]);
_ ->
emit(Fd, "-export([id/0,name/0]).\n\n\n\n",[])
end.
%%------------------------------------------------------------
%%
%% emit erlang module functions which represent records, yields
%% record information such as type code, identity and name.
%%
%%------------------------------------------------------------
emit_rec_methods(G,N,X,Name,Fd) ->
IR_ID = ictk:get_IR_ID(G, N, X),
case ic_options:get_opt(G, be) of
erl_corba ->
TK = ic_forms:get_tk(X),
case TK of
undefined ->
STK = ic_forms:search_tk(G,ictk:get_IR_ID(G, N, X)),
emit(Fd, "%% returns type code\n",[]),
emit(Fd, "tc() -> ~p.\n\n",[STK]),
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name]);
_ ->
emit(Fd, "%% returns type code\n",[]),
emit(Fd, "tc() -> ~p.\n\n",[TK]),
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name])
end;
_ ->
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name])
end.
%%------------------------------------------------------------
%%
%% emit erlang module functions which represent arrays, yields
%% record information such as type code, identity and name.
%%
%%------------------------------------------------------------
emit_arr_methods(G,N,X,Name,Fd) ->
IR_ID = ictk:get_IR_ID(G, N, X),
case ic_options:get_opt(G, be) of
erl_corba ->
TK = ic_forms:get_type_code(G, N, X),
emit(Fd, "%% returns type code\n",[]),
emit(Fd, "tc() -> ~p.\n\n",[TK]),
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name]);
_ ->
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name])
end.
get_seq_max(T) when is_record(T, sequence) andalso T#sequence.length == 0 ->
infinity;
get_seq_max(T) when is_record(T, sequence) andalso is_tuple(T#sequence.length) ->
list_to_integer(element(3, T#sequence.length)).
align(Cs) ->
ic_util:mk_align(Cs).
| null | https://raw.githubusercontent.com/erlang/corba/396df81473a386d0315bbba830db6f9d4b12a04f/lib/ic/src/icstruct.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
------------------------------------------------------------
Internal stuff
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
File handling stuff
------------------------------------------------------------
------------------------------------------------------------
Generation loop
The idea is to traverse everything and find every struct that
may be hiding down in nested types. All structs that are found
are generated to a hrl file.
struct_gen is entry point for structs and types, except_gen is
for exceptions
------------------------------------------------------------
List clause for struct_gen
emit primitive for structs.
Make a straight list of all member ids (this is a
variant of flatten)
Make a straight list of all member ids (this is a
variant of flatten)
emit array file
return patch problem
Extracts array dimention(s)
Makes the array name
Sequence used as struct
Array but not a typedef of
an array definition
Search the table to see if the type is local or
inherited.
Local, create erlang file for the array
Inherited, do nothing
Sequence but not a typedef of
a typedef of a sequence definition
Search the table to see if the type is local or
inherited.
Local, create erlang file for the sequence
Inherited, do nothing
Write on stubfile header
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Write on stubfile
% Write on stubfile header
emit(Fd, "#include \"~s\"\n\n",[HrlFName]),
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Move data from ram file to output file.
Move data from ram file to output file.
Move data from ram file to output file.
T is the sequence
------------------------------------------------------------
Emit decode bodies for functions in C for array, sequences and
structs.
------------------------------------------------------------
Term
XXX Silly. There is no real difference between the
C statements produced by the following calls.
A struct member
No Typedef, Dynamic, String
This is disabled due to a bug in erl_interface :
tuples inside tuples hae no correct data about the size
of the tuple........( allways = 0 )
emit(Fd, " if (oe_array_size != ~s)\n",[Dim]),
emit(Fd, " return -1;\n\n"),
emit(Fd, "\n *oe_outindex +=
This is disabled due to a bug in erl_interface :
tuples inside tuples hae no correct data about the size
of the tuple........( allways = 0 )
emit(Fd, " if (oe_array_size != ~s)\n",[Dim]),
emit(Fd, " return -1;\n\n"),
ElType = elementary type or pointer type
ElType = structure
Sequence = struct
No Typedef, Dynamic, String
stub file
stub header file
Size count
Move data from ram file to output file.
Encode
Move data from ram file to output file.
Decode
Move data from ram file to output file.
------------------------------------------------------------
emit primitive for unions.
------------------------------------------------------------
Not supported in c backend
------------------------------------------------------------
emit erlang modules for objects with record definitions
(such as unions or structs), or sequences
The record files, other than headers are only generated
for other backends ( not necessary anyway )
------------------------------------------------------------
------------------------------------------------------------
emit erlang modules for objects with array definitions..
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
emit erlang module functions which represent records, yields
record information such as type code, identity and name.
------------------------------------------------------------
------------------------------------------------------------
emit erlang module functions which represent arrays, yields
record information such as type code, identity and name.
------------------------------------------------------------ | Copyright Ericsson AB 1997 - 2020 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(icstruct).
-export([struct_gen/4, except_gen/4, create_c_array_coding_file/5]).
-import(ic_codegen, [emit/2, emit/3, emit/4, emit_c_enc_rpt/4, emit_c_dec_rpt/4]).
-include("icforms.hrl").
-include("ic.hrl").
except_gen(G, N, X, L) when is_record(X, except) ->
N2 = [ic_forms:get_id2(X) | N],
if
L == c ->
io:format("Warning : Exception not defined for c mapping\n", []);
true ->
emit_struct(G, N, X, L)
end,
struct_gen_list(G, N2, ic_forms:get_body(X), L).
struct_gen(G, N, X, L) when is_record(X, struct) ->
N2 = [ic_forms:get_id2(X) | N],
struct_gen_list(G, N2, ic_forms:get_body(X), L),
emit_struct(G, N, X, L);
struct_gen(G, N, X, L) when is_record(X, union) ->
N2 = [ic_forms:get_id2(X) | N],
if
L == c ->
Produce the " body " first
struct_gen_list(G, N2, ic_forms:get_body(X), L),
icunion:union_gen(G, N, X, c);
true ->
struct_gen(G, N, ic_forms:get_type(X), L),
struct_gen_list(G, N2, ic_forms:get_body(X), L)
end,
emit_union(G, N, X, L);
struct_gen(G, N, X, L) when is_record(X, member) ->
struct_gen(G, N, ic_forms:get_type(X), L);
struct_gen(G, N, X, L) when is_record(X, typedef) ->
struct_gen(G, N, ic_forms:get_body(X), L),
emit_typedef(G, N, X, L);
struct_gen(G, N, X, L) when is_record(X, type_dcl) ->
struct_gen_list(G, N, ic_forms:get_type(X), L);
struct_gen(G, N, X, L) when is_record(X, case_dcl) ->
struct_gen(G, N, ic_forms:get_type(X), L);
struct_gen(G, N, X, L) when is_record(X, sequence) ->
struct_gen(G, N, ic_forms:get_type(X), L),
X;
struct_gen(G, N, X, L) when is_record(X, enum) ->
icenum:enum_gen(G, N, X, L);
struct_gen(_G, _N, _X, _L) ->
ok.
struct_gen_list(G, N, Xs, L) ->
lists:foreach(
fun(X) ->
R = struct_gen(G, N, X, L),
if
L == c ->
if
is_record(R,sequence) ->
emit_sequence_head_def(G,N,X,R,L);
true ->
ok
end;
true ->
ok
end
end, Xs).
emit_struct(G, N, X, erlang) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
EList = lists:map(
fun(XX) ->
lists:map(
fun(XXX) ->
ic_util:to_atom(ic_forms:get_id2(XXX))
end,
ic_forms:get_idlist(XX))
end,
ic_forms:get_body(X)),
ic_codegen:record(G, X,
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
ictk:get_IR_ID(G, N, X), lists:flatten(EList)),
mkFileRecObj(G,N,X,erlang);
false ->
ok
end;
emit_struct(G, N, X, c) ->
N1 = [ic_forms:get_id2(X) | N],
case ic_pragma:is_local(G,N1) of
true ->
emit_c_struct(G, N, X,local);
false ->
emit_c_struct(G, N, X,included)
end.
emit_c_struct(_G, _N, _X, included) ->
Do not generate included types att all .
ok;
emit_c_struct(G, N, X, local) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
N1 = [ic_forms:get_id2(X) | N],
StructName = ic_util:to_undersc(N1),
M = lists:map(
fun(XX) ->
lists:map(
fun(XXX) ->
if
is_record(XXX, array) ->
Type = ic_forms:get_type(XX),
Name = element(3,element(2,XXX)),
{_, _, StructTK, _} =
ic_symtab:get_full_scoped_name(
G,
N,
ic_symtab:scoped_id_new(
ic_forms:get_id2(X))),
ArrayTK =
get_structelement_tk(StructTK,
Name),
Dim = extract_dim(ArrayTK),
emit(Fd, "\n#ifndef __~s__\n",
[ic_util:to_uppercase(
StructName ++ "_"
++ Name)]),
emit(Fd, "#define __~s__\n\n",
[ic_util:to_uppercase(
StructName ++ "_"
++ Name)]),
create_c_array_coding_file(
G,
N,
{StructName ++ "_" ++ Name, Dim},
Type,
no_typedef),
emit(Fd, "\n#endif\n\n"),
{{Type, XXX},
ic_forms:get_id2(XXX)};
true ->
Ugly work around to fix the ETO
Name =
case ic_forms:get_id2(XXX) of
"return" ->
"return1";
Other ->
Other
end,
{ic_forms:get_type(XX), Name}
end
end,
ic_forms:get_idlist(XX))
end,
ic_forms:get_body(X)),
EList = lists:flatten(M),
io : = ~p ~ n",[EList ] ) ,
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(StructName)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(StructName)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Struct definition: ~s",
[StructName])],
c),
emit(Fd, "typedef struct {\n"),
lists:foreach(
fun({Type, Name}) ->
emit_struct_member(Fd, G, N1, X, Name, Type)
end,
EList),
emit(Fd, "} ~s;\n\n", [StructName]),
create_c_struct_coding_file(G, N, X, nil, StructName,
EList, struct),
emit(Fd, "\n#endif\n\n");
false ->
ok
end.
get_structelement_tk({tk_struct, _, _, EList}, EN) ->
{value, {EN, ArrayTK}} = lists:keysearch(EN, 1, EList),
ArrayTK.
extract_dim({tk_array, {tk_array, T, D1}, D}) ->
[integer_to_list(D) | extract_dim({tk_array, T, D1})];
extract_dim({tk_array, _, D}) ->
[integer_to_list(D)].
mk_array_name(Name,Dim) ->
Name ++ mk_array_name(Dim).
mk_array_name([]) ->
"";
mk_array_name([Dim|Dims]) ->
"[" ++ Dim ++ "]" ++ mk_array_name(Dims).
emit_struct_member(Fd, G, N, X, Name,{Type,Array}) when is_record(Array, array)->
{_, _, StructTK, _} =
ic_symtab:get_full_scoped_name(
G,
N,
ic_symtab:scoped_id_new(ic_forms:get_id2(X))),
ArrayTK = get_structelement_tk(StructTK, Name),
Dim = extract_dim(ArrayTK),
emit(Fd, " ~s ~s;\n",
[ic_cbe:mk_c_type(G, N, Type),mk_array_name(Name,Dim)]);
emit_struct_member(Fd, _G, N, _X, Name, Union) when is_record(Union, union)->
emit(Fd, " ~s ~s;\n",
[ic_util:to_undersc([ic_forms:get_id2(Union) | N]),Name]);
emit_struct_member(Fd, _G, _N, _X, Name, {string, _}) ->
emit(Fd, " CORBA_char *~s;\n",
[Name]);
emit_struct_member(Fd, _G, N, _X, Name, {sequence, _Type, _Length}) ->
emit(Fd, " ~s ~s;\n",
[ic_util:to_undersc([Name | N]), Name]);
emit_struct_member(Fd, G, N, X, Name, Type)
when element(1, Type) == scoped_id ->
CType = ic_cbe:mk_c_type(G, N, Type, evaluate_not),
emit_struct_member(Fd, G, N, X, Name, CType);
emit_struct_member(Fd, G, N, _X, Name, {enum, Type}) ->
emit(Fd, " ~s ~s;\n",
[ic_cbe:mk_c_type(G, N, Type),
Name]);
emit_struct_member(Fd, _G, _N, _X, Name, "ic_erlang_term*") ->
emit(Fd, " ic_erlang_term* ~s;\n",
[Name]);
emit_struct_member(Fd, _G, _N, _X, Name, Type) when is_list(Type) ->
emit(Fd, " ~s ~s;\n",
[Type, Name]);
emit_struct_member(Fd, G, N, _X, Name, Type) ->
emit(Fd, " ~s ~s;\n",
[ic_cbe:mk_c_type(G, N, Type),
Name]).
emit_typedef(G, N, X, erlang) ->
case X of
case ic_options:get_opt(G, be) of
noc ->
mkFileArrObj(G,N,X,erlang);
_ ->
PTab = ic_genobj:pragmatab(G),
Id = ic_forms:get_id2(X),
case ets:match(PTab,{file_data_local,'_','_',
typedef,N,Id,
ic_util:to_undersc([Id | N]),
'_','_'}) of
[[]] ->
mkFileArrObj(G,N,X,erlang);
_ ->
ok
end
end;
{typedef,{sequence,_,_},_,{tk_sequence,_,_}} ->
case ic_options:get_opt(G, be) of
noc ->
mkFileRecObj(G,N,X,erlang);
_ ->
PTab = ic_genobj:pragmatab(G),
Id = ic_forms:get_id2(X),
case ets:match(PTab,{file_data_local,'_','_',typedef,
N,Id,
ic_util:to_undersc([Id | N]),
'_','_'}) of
[[]] ->
mkFileRecObj(G,N,X,erlang);
_ ->
ok
end
end;
_ ->
ok
end;
emit_typedef(G, N, X, c) ->
B = ic_forms:get_body(X),
if
is_record(B, sequence) ->
emit_sequence_head_def(G, N, X, B, c);
true ->
lists:foreach(fun(D) ->
emit_typedef(G, N, D, B, c)
end,
ic_forms:get_idlist(X))
end.
emit_typedef(G, N, D, Type, c) when is_record(D, array) ->
emit_array(G, N, D, Type);
emit_typedef(G, N, D, Type, c) ->
Name = ic_util:to_undersc([ic_forms:get_id2(D) | N]),
CType = ic_cbe:mk_c_type(G, N, Type),
TDType = mk_base_type(G, N, Type),
ic_code:insert_typedef(G, Name, TDType),
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(Name)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(Name)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Type definition ~s "
"for type ~s",
[Name, CType])],
c),
emit(Fd, "typedef ~s ~s;\n",
[CType, Name]),
emit(Fd, "\n#endif\n\n"),
ic_codegen:nl(Fd);
false ->
ok
end.
mk_base_type(G, N, S) when element(1, S) == scoped_id ->
{FullScopedName, _T, _TK, _} = ic_symtab:get_full_scoped_name(G, N, S),
BT = ic_code:get_basetype(G, ic_util:to_undersc(FullScopedName)),
case BT of
"erlang_binary" ->
"erlang_binary";
"erlang_pid" ->
"erlang_pid";
"erlang_port" ->
"erlang_port";
"erlang_ref" ->
"erlang_ref";
"erlang_term" ->
"ic_erlang_term*";
Type ->
Type
end;
mk_base_type(_G, _N, S) ->
S.
emit_array(G, N, D, Type) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
Name = ic_util:to_undersc([ic_forms:get_id2(D) | N]),
{_, _, ArrayTK, _} =
ic_symtab:get_full_scoped_name(G, N,
ic_symtab:scoped_id_new(
ic_forms:get_id(D))),
Dim = extract_dim(ArrayTK),
CType = ic_cbe:mk_c_type(G, N, Type),
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(Name)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(Name)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Array definition ~s "
"for type ~s",
[Name, CType])],
c),
emit(Fd, "typedef ~s ~s~s;\n",
[CType, Name, ic_cbe:mk_dim(Dim)]),
emit(Fd, "typedef ~s ~s_slice~s;\n",
[CType, Name, ic_cbe:mk_slice_dim(Dim)]),
ic_codegen:nl(Fd),
create_c_array_coding_file(G, N, {Name, Dim}, Type, typedef),
emit(Fd, "\n#endif\n\n");
false ->
ok
end.
open_c_coding_file(G, Name) ->
SName = string:concat(ic_util:mk_oe_name(G, "code_"), Name),
FName =
ic_file:join(ic_options:get_opt(G, stubdir),ic_file:add_dot_c(SName)),
case file:open(FName, [write]) of
{ok, Fd} ->
{Fd, SName};
Other ->
exit(Other)
end.
create_c_array_coding_file(G, N, {Name, Dim}, Type, TypeDefFlag) ->
{Fd , SName} = open_c_coding_file(G, Name),
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, c),
emit(Fd, "#include \"~s\"\n\n",[HrlFName]),
HrlFName = filename : basename(ic_genobj : include_file(G ) ) ,
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, int*, int*);\n",
[ic_util:mk_oe_name(G, "sizecalc_"), Name]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, int* oe_size_count_index, "
"int* oe_size) {\n", [ic_util:mk_oe_name(G, "sizecalc_"), Name]),
emit(Fd, " int oe_malloc_size = 0;\n",[]),
emit(Fd, " int oe_error_code = 0;\n",[]),
emit(Fd, " int oe_type = 0;\n",[]),
emit(Fd, " int oe_array_size = 0;\n",[]),
{ok, RamFd} = ram_file:open([], [binary, write]),
emit_sizecount(array, G, N, nil, RamFd, {Name, Dim}, Type),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
{ok, Data} = ram_file:get_file(RamFd),
emit(Fd, Data),
ram_file:close(RamFd),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n",[]),
put(op_variable_count, 0),
put(tmp_declarations, []),
RefStr = get_refStr(Dim),
case TypeDefFlag of
typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, ~s);\n",
[ic_util:mk_oe_name(G, "encode_"), Name, Name]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, ~s oe_rec) {\n",
[ic_util:mk_oe_name(G, "encode_"), Name, Name]);
no_typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, ~s oe_rec~s);\n",
[ic_util:mk_oe_name(G, "encode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, ~s oe_rec~s) {\n",
[ic_util:mk_oe_name(G, "encode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr])
end,
emit(Fd, " int oe_error_code = 0;\n",[]),
{ok, RamFd1} = ram_file:open([], [binary, write]),
case TypeDefFlag of
typedef ->
emit_encode(array, G, N, nil, RamFd1, {Name, Dim}, Type);
no_typedef ->
emit_encode(array_no_typedef, G, N, nil, RamFd1, {Name, Dim}, Type)
end,
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
{ok, Data1} = ram_file:get_file(RamFd1),
emit(Fd, Data1),
ram_file:close(RamFd1),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n",[]),
put(op_variable_count, 0),
put(tmp_declarations, []),
case TypeDefFlag of
typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, char *, "
"int*, ~s);\n",
[ic_util:mk_oe_name(G, "decode_"), Name, Name]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, char *oe_first, "
"int* oe_outindex, ~s oe_out) {\n",
[ic_util:mk_oe_name(G, "decode_"), Name, Name]);
no_typedef ->
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, char *, int*, "
"~s oe_rec~s);\n",
[ic_util:mk_oe_name(G, "decode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, char *oe_first, "
"int* oe_outindex, ~s oe_out~s) {\n",
[ic_util:mk_oe_name(G, "decode_"),
Name,
ic_cbe:mk_c_type(G, N, Type),
RefStr])
end,
emit(Fd, " int oe_error_code = 0;\n",[]),
emit(Fd, " int oe_array_size = 0;\n",[]),
{ok, RamFd2} = ram_file:open([], [binary, write]),
case TypeDefFlag of
typedef ->
emit_decode(array, G, N, nil, RamFd2, {Name, Dim}, Type);
no_typedef ->
emit_decode(array_no_typedef, G, N, nil, RamFd2, {Name, Dim}, Type)
end,
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
{ok, Data2} = ram_file:get_file(RamFd2),
emit(Fd, Data2),
ram_file:close(RamFd2),
emit(Fd, " *oe_outindex = ~s;\n\n",[align("*oe_outindex")]),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n",[]),
file:close(Fd).
get_refStr([]) ->
"";
get_refStr([X|Xs]) ->
"[" ++ X ++ "]" ++ get_refStr(Xs).
emit_sequence_head_def(G, N, X, T, c) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
Fd = ic_genobj:hrlfiled(G),
SeqName = ic_util:to_undersc([ic_forms:get_id2(X) | N]),
emit(Fd, "\n#ifndef __~s__\n",[ic_util:to_uppercase(SeqName)]),
emit(Fd, "#define __~s__\n",[ic_util:to_uppercase(SeqName)]),
ic_codegen:mcomment_light(Fd,
[io_lib:format("Struct definition: ~s",
[SeqName])],
c),
emit(Fd, "typedef struct {\n"),
emit(Fd, " CORBA_unsigned_long _maximum;\n"),
emit(Fd, " CORBA_unsigned_long _length;\n"),
emit_seq_buffer(Fd, G, N, T#sequence.type),
emit(Fd, "} ~s;\n\n", [SeqName]),
create_c_struct_coding_file(G, N, X, T, SeqName,
T#sequence.type, sequence_head),
emit(Fd, "\n#endif\n\n");
false ->
ok
end.
emit_seq_buffer(Fd, G, N, Type) ->
emit(Fd, " ~s* _buffer;\n",
[ic_cbe:mk_c_type(G, N, Type)]).
emit_decode(array, G, N, _T, Fd, {_Name, Dim}, Type) ->
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
AlignName =
lists:concat(["*oe_outindex + ", dim_multiplication(Dim),
" * sizeof(", ic_cbe:mk_c_type(G, N, Type),")"]),
emit(Fd, " *oe_outindex = ~s;\n\n",[align(AlignName)]),
array_decode_dimension_loop(G, N, Fd, Dim, "", Type, array);
emit_decode(array_no_typedef, G, N, _T, Fd, {_Name, Dim}, Type) ->
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
AlignName =
lists:concat(["*oe_outindex + ", dim_multiplication(Dim),
" * sizeof(", ic_cbe:mk_c_type(G, N, Type),")"]),
emit(Fd, " *oe_outindex = ~s;\n\n",[align(AlignName)]),
array_decode_dimension_loop(G, N, Fd, Dim, "", Type, array_no_typedef);
emit_decode(sequence_head, G, N, T, Fd, SeqName, ElType) ->
ic_cbe:store_tmp_decl(" int oe_seq_len = 0;\n", []),
ic_cbe:store_tmp_decl(" int oe_seq_count = 0;\n", []),
ic_cbe:store_tmp_decl(" int oe_seq_dummy = 0;\n", []),
TmpBuf =
case ictype:isBasicTypeOrEterm(G, N, ElType) of
true ->
Tmp = "oe_seq_tmpbuf",
ic_cbe:store_tmp_decl(" char* ~s = 0;\n", [Tmp]),
Tmp;
false ->
"NOT USED"
end,
MaxSize = get_seq_max(T),
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
emit(Fd, " *oe_outindex = ~s;\n\n",
[align(["*oe_outindex + sizeof(", SeqName, ")"])]),
Ctype = ic_cbe:mk_c_type(G, N, ElType),
emit(Fd, " if ((oe_error_code = ei_decode_list_header(oe_env->_inbuf, "
"&oe_env->_iin, &oe_seq_len)) < 0) {\n"),
case ictype:isBasicTypeOrEterm(G, N, ElType) of
true ->
emit(Fd, " int oe_type = 0;\n"),
emit(Fd, " (int) ei_get_type(oe_env->_inbuf, &oe_env->_iin, "
"&oe_type, &oe_seq_len);\n\n"),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_seq_len > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, "
"CORBA_SYSTEM_EXCEPTION, DATA_CONVERSION, "
"\"Length of sequence `~s' out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
emit(Fd, " oe_out->_maximum = oe_seq_len;\n"),
emit(Fd, " oe_out->_length = oe_seq_len;\n"),
emit(Fd, " oe_out->_buffer = (void *) (oe_first + "
"*oe_outindex);\n"),
emit(Fd, " *oe_outindex = ~s;\n",
[align(["*oe_outindex + (sizeof(", Ctype, ") * "
"oe_out->_length)"])]),
emit(Fd,
" if ((~s = malloc(oe_seq_len + 1)) == NULL) {\n"
" CORBA_exc_set(oe_env, CORBA_SYSTEM_EXCEPTION, "
"NO_MEMORY, \"Cannot malloc\");\n"
" return -1;\n"
" }\n", [TmpBuf]),
emit(Fd, " if ((oe_error_code = ei_decode_string("
"oe_env->_inbuf, &oe_env->_iin, ~s)) < 0) {\n", [TmpBuf]),
emit(Fd, " CORBA_free(~s);\n\n", [TmpBuf]),
emit_c_dec_rpt(Fd, " ", "string1", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (oe_seq_count = 0; "
"oe_seq_count < oe_out->_length; oe_seq_count++) {\n"),
case ictype:isBasicType(G, N, ElType) of
true ->
emit(Fd, " oe_out->_buffer[oe_seq_count] = (unsigned char) "
"~s[oe_seq_count];\n\n", [TmpBuf]);
emit(Fd, " oe_out->_buffer[oe_seq_count]->type = ic_integer;\n", []),
emit(Fd, " oe_out->_buffer[oe_seq_count]->value.i_val = (long) ~s[oe_seq_count];\n",
[TmpBuf])
end,
emit(Fd, " }\n\n", []),
emit(Fd, " CORBA_free(~s);\n\n", [TmpBuf]);
false ->
emit(Fd, " return oe_error_code;\n")
end,
emit(Fd, " } else {\n"),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_seq_len > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, "
"CORBA_SYSTEM_EXCEPTION, DATA_CONVERSION, "
"\"Length of sequence `~s' out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
emit(Fd, " oe_out->_maximum = oe_seq_len;\n"),
emit(Fd, " oe_out->_length = oe_seq_len;\n"),
emit(Fd, " oe_out->_buffer = (void *) (oe_first + *oe_outindex);\n"),
emit(Fd, " *oe_outindex = ~s;\n\n",
[align(["*oe_outindex + (sizeof(", Ctype, ") * oe_out->_length)"])]),
if
Ctype == "CORBA_char *" ->
emit(Fd, " for (oe_seq_count = 0; "
"oe_seq_count < oe_out->_length; oe_seq_count++) {\n"),
emit(Fd, " oe_out->_buffer[oe_seq_count] = "
"(void*) (oe_first + *oe_outindex);\n\n"),
ic_cbe:emit_decoding_stmt(G, N, Fd, ElType,
"oe_out->_buffer[oe_seq_count]",
"",
"oe_env->_inbuf", 0, "", caller_dyn),
emit(Fd, " *oe_outindex = ~s;",
[align(["*oe_outindex + strlen(oe_out->_buffer["
"oe_seq_count]) + 1"])]);
true ->
emit(Fd, " for (oe_seq_count = 0; "
"oe_seq_count < oe_out->_length; oe_seq_count++) {\n"),
case ictype:isArray(G, N, ElType) of
true ->
ic_cbe:emit_decoding_stmt(G, N, Fd, ElType,
"oe_out->_buffer[oe_seq_count]",
"",
"oe_env->_inbuf",
0, "oe_outindex", generator);
false ->
ic_cbe:emit_decoding_stmt(G, N, Fd, ElType,
"oe_out->_buffer + oe_seq_count",
"",
"oe_env->_inbuf",
0, "oe_outindex", generator)
end
end,
emit(Fd, " }\n"),
emit(Fd, " if (oe_out->_length != 0) {\n"),
emit(Fd, " if ((oe_error_code = ei_decode_list_header("
"oe_env->_inbuf, &oe_env->_iin, &oe_seq_dummy)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_list_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " } else\n"),
emit(Fd, " oe_out->_buffer = NULL;\n"),
emit(Fd, " }\n");
emit_decode(struct, G, N, _T, Fd, StructName, ElTypes) ->
Length = length(ElTypes) + 1,
Tname = ic_cbe:mk_variable_name(op_variable_count),
Tname1 = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
ic_cbe:store_tmp_decl(" char ~s[256];\n\n",[Tname1]),
emit(Fd, " if((char*) oe_out == oe_first)\n",[]),
AlignName = lists:concat(["*oe_outindex + sizeof(",StructName,")"]),
emit(Fd, " *oe_outindex = ~s;\n\n", [align(AlignName)]),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"&oe_env->_iin, &~s)) < 0) {\n", [Tname]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (~s != ~p) {\n",[Tname, Length]),
emit_c_dec_rpt(Fd, " ", "tuple header size != ~p", [Length]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = ei_decode_atom(oe_env->_inbuf, "
"&oe_env->_iin, ~s)) < 0) {\n", [Tname1]),
emit_c_dec_rpt(Fd, " ", "ei_decode_atom", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (strcmp(~s, ~p) != 0)\n",[Tname1, StructName]),
emit(Fd, " return -1;\n\n"),
lists:foreach(
fun({ET, EN}) ->
case ic_cbe:is_variable_size(G, N, ET) of
true ->
case ET of
{struct, _, _, _} ->
Sequence member = a struct
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN,
"", "oe_env->_inbuf",
0,
"oe_outindex",
generator);
{sequence, _, _} ->
Sequence member = a struct XXX ? ?
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
EN,
"&oe_out->" ++ EN,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{_,{array, _, _}} ->
emit(Fd, " oe_out->~s = (void *) "
"(oe_first+*oe_outindex);\n\n",[EN]),
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
EN, "oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{union, _, _, _, _} ->
Sequence member = a union
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{string,_} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator_malloc);
{scoped_id,_,_,_} ->
case ictype:member2type(G,StructName,EN) of
array ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
struct ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN ,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
sequence ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
union ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
_ ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator)
end;
_ ->
emit(Fd, " oe_out->~s = (void *) "
"(oe_first+*oe_outindex);\n\n",[EN]),
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0, "oe_outindex",
generator)
end;
false ->
case ET of
{struct, _, _, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{_,{array, _, _}} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
EN,
"oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{union, _, _, _, _} ->
Sequence member = a union
ic_cbe:emit_decoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{_,_} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++ EN ,
"",
"oe_env->_inbuf",
0,
"oe_outindex",
generator);
{scoped_id,_,_,_} ->
case ic_symtab:get_full_scoped_name(G, N, ET) of
{_FullScopedName, _, {tk_array,_,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
{_FullScopedName, _, {tk_string,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
{_FullScopedName, _, {tk_struct,_,_,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
{_FullScopedName, _,
{tk_union,_,_,_,_,_}, _} ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator);
_ ->
ic_cbe:emit_decoding_stmt(G, N, Fd,
ET,
"&oe_out->" ++
EN,
"",
"oe_env->"
"_inbuf",
0,
"oe_outindex",
generator)
end
end
end
end,
ElTypes).
ref_array_static_dec(array, true) ->
Typedef , Static , Basic Type
"&(oe_out)";
ref_array_static_dec(array, false) ->
Typedef , Static , Constr Type
"&(oe_out)";
ref_array_static_dec(array_no_typedef, true) ->
No Typedef , Static , Basic Type
"&oe_out";
ref_array_static_dec(array_no_typedef, false) ->
No Typedef , Static , Constr Type
"&oe_out".
ref_array_dynamic_dec(G, N, T, array) ->
case ictype:isString(G, N, T) of
Typedef , Dynamic , String
"oe_out";
Typedef , Dynamic , No String
"&(oe_out)"
end;
ref_array_dynamic_dec(G, N, T, array_no_typedef) ->
case ictype:isString(G, N, T) of
"oe_out";
No Typedef , Dynamic , No String
"&oe_out"
end.
array_decode_dimension_loop(G, N, Fd, [Dim], Dimstr, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"&oe_env->_iin, &oe_array_size)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
ArrAccess =
case ic_cbe:is_variable_size(G, N, Type) of
true ->
ref_array_dynamic_dec(G, N, Type, TDFlag) ++
Dimstr ++ "[" ++ Tname ++ "]";
false ->
ref_array_static_dec(TDFlag, ictype:isBasicType(G,N,Type)) ++
Dimstr ++ "[" ++ Tname ++ "]"
end,
ic_cbe:emit_decoding_stmt(G, N, Fd, Type,
ArrAccess,
"", "oe_env->_inbuf", 0,
"oe_outindex", generator),
sizeof(~s);\n",[ic_cbe : mk_c_type(G , N , Type ) ] ) ,
emit(Fd, " }\n");
array_decode_dimension_loop(G, N, Fd, [Dim | Ds], _Dimstr, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"&oe_env->_iin, &oe_array_size)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
array_decode_dimension_loop(G, N, Fd, Ds, "[" ++ Tname ++ "]" , Type,
TDFlag),
emit(Fd, " }\n").
dim_multiplication([D]) ->
D;
dim_multiplication([D |Ds]) ->
D ++ "*" ++ dim_multiplication(Ds).
emit_encode(array, G, N, _T, Fd, {_Name, Dim}, Type) ->
array_encode_dimension_loop(G, N, Fd, Dim, {"",""}, Type, array);
emit_encode(array_no_typedef, G, N, _T, Fd, {_Name, Dim}, Type) ->
array_encode_dimension_loop(G, N, Fd, Dim, {"",""}, Type,
array_no_typedef);
emit_encode(sequence_head, G, N, T, Fd, SeqName, ElType) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n\n",[Tname]),
MaxSize = get_seq_max(T),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_rec->_length > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, CORBA_SYSTEM_EXCEPTION, "
"DATA_CONVERSION, \"Length of sequence `~s' "
"out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
emit(Fd, " if (oe_rec->_length != 0) {\n"),
emit(Fd, " if ((oe_error_code = oe_ei_encode_list_header(oe_env, "
"oe_rec->_length)) < 0) {\n",
[]),
emit_c_enc_rpt(Fd, " ", "oi_ei_encode_list_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < oe_rec->_length; ~s++) {\n",
[Tname, Tname, Tname]),
case ElType of
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType, "oe_rec->_buffer[" ++
Tname ++ "]", "oe_env->_outbuf");
{scoped_id,local,_,["term","erlang"]} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType, "oe_rec->_buffer[" ++
Tname ++ "]", "oe_env->_outbuf");
{scoped_id,_,_,_} ->
case ic_symtab:get_full_scoped_name(G, N, ElType) of
{_, typedef, TDef, _} ->
case TDef of
{tk_struct,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
{tk_sequence,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
{tk_union,_,_,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf")
end;
{_,enum,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf");
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++
Tname ++ "]",
"oe_env->_outbuf")
end;
ic_cbe:emit_encoding_stmt(G, N, Fd, ElType,
"&oe_rec->_buffer[" ++ Tname ++ "]",
"oe_env->_outbuf")
end,
emit(Fd, " }\n"),
emit(Fd, " }\n"),
emit(Fd, " if ((oe_error_code = oe_ei_encode_empty_list(oe_env)) < 0) {\n"),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_empty_list", []),
emit(Fd, " return oe_error_code;\n }\n");
emit_encode(struct, G, N, _T, Fd, StructName, ElTypes) ->
Length = length(ElTypes) + 1,
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_tuple_header(oe_env, ~p)) < 0) {\n", [Length]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_atom(oe_env, ~p)) < 0) {\n", [StructName]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_atom", []),
emit(Fd, " return oe_error_code;\n }\n"),
lists:foreach(
fun({ET, EN}) ->
case ET of
{sequence, _, _} ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++ EN,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
{_,{array, _, _Dims}} ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++ EN,
"oe_rec->" ++ EN,
"oe_env->_outbuf");
{union,_,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
{struct,_,_,_} ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
StructName ++ "_" ++
ic_forms:get_id2(ET),
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
{scoped_id,_,_,_} ->
case ictype:member2type(G,StructName,EN) of
struct ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
sequence ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
union ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"&oe_rec->" ++ EN,
"oe_env->_outbuf");
array ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"oe_rec->" ++ EN,
"oe_env->_outbuf");
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"oe_rec->" ++ EN,
"oe_env->_outbuf")
end;
_ ->
ic_cbe:emit_encoding_stmt(G, N, Fd,
ET,
"oe_rec->" ++ EN,
"oe_env->_outbuf")
end
end,
ElTypes).
ref_array_static_enc(array, true) ->
Typedef , Static , Basic Type
"oe_rec";
ref_array_static_enc(array, false) ->
Typedef , Static , Constr Type
"&(oe_rec)";
ref_array_static_enc(array_no_typedef, true) ->
No Typedef , Static , Basic Type
"oe_rec";
ref_array_static_enc(array_no_typedef, false) ->
No Typedef , Static , Constr Type
"&oe_rec".
ref_array_dynamic_enc(G, N, T, array) ->
case ictype:isString(G, N, T) of
Typedef , Dynamic , String
"oe_rec";
Typedef , Dynamic , No String
"&(oe_rec)"
end;
ref_array_dynamic_enc(G, N, T, array_no_typedef) ->
case ictype:isString(G, N, T) of
"oe_rec";
No Typedef , Dynamic , No String
"&oe_rec"
end.
array_encode_dimension_loop(G, N, Fd, [Dim], {Str1,_Str2}, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_tuple_header(oe_env, ~s)) < 0) {\n", [Dim]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
ArrAccess =
case ic_cbe:is_variable_size(G, N, Type) of
true ->
ref_array_dynamic_enc(G, N, Type, TDFlag) ++
Str1 ++ "[" ++ Tname ++ "]";
false ->
ref_array_static_enc(TDFlag, ictype:isBasicType(G,N,Type)) ++
Str1 ++ "[" ++ Tname ++ "]"
end,
ic_cbe:emit_encoding_stmt(G, N, Fd, Type, ArrAccess, "oe_env->_outbuf"),
emit(Fd, " }\n");
array_encode_dimension_loop(G, N, Fd, [Dim | Ds],{Str1,Str2}, Type, TDFlag) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"oe_ei_encode_tuple_header(oe_env, ~s)) < 0) {\n", [Dim]),
emit_c_enc_rpt(Fd, " ", "oe_ei_encode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
array_encode_dimension_loop(G, N, Fd, Ds,
{Str1 ++ "[" ++ Tname ++ "]", Str2},
Type, TDFlag),
emit(Fd, " }\n").
emit_sizecount(array, G, N, _T, Fd, {_Name, Dim}, Type) ->
emit(Fd, " if(*oe_size == 0)\n",[]),
AlignName = lists:concat(["*oe_size + ", dim_multiplication(Dim),
" * sizeof(", ic_cbe:mk_c_type(G, N, Type),")"]),
emit(Fd, " *oe_size = ~s;\n\n",[align(AlignName)]),
array_size_dimension_loop(G, N, Fd, Dim, Type),
emit(Fd, " *oe_size = ~s;\n\n",
[align("*oe_size + oe_malloc_size")]),
ic_codegen:nl(Fd);
emit_sizecount(sequence_head, G, N, T, Fd, SeqName, ElType) ->
ic_cbe:store_tmp_decl(" int oe_seq_len = 0;\n", []),
ic_cbe:store_tmp_decl(" int oe_seq_count = 0;\n", []),
emit(Fd, " if(*oe_size == 0)\n",[]),
emit(Fd, " *oe_size = ~s;\n\n",
[align(["*oe_size + sizeof(", SeqName, ")"])]),
MaxSize = get_seq_max(T),
emit(Fd, " if ((oe_error_code = ei_get_type(oe_env->_inbuf, "
"oe_size_count_index, &oe_type, &oe_seq_len)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
if
MaxSize == infinity ->
ok;
true ->
emit(Fd, " if (oe_seq_len > ~w) {\n", [MaxSize]),
emit(Fd, " CORBA_exc_set(oe_env, CORBA_SYSTEM_EXCEPTION, "
"DATA_CONVERSION, \"Length of sequence `~s' "
"out of bound\");\n"
" return -1;\n }\n", [SeqName])
end,
CType = ic_cbe:mk_c_type(G, N, ElType),
emit(Fd, " if ((oe_error_code = ei_decode_list_header(oe_env->_inbuf, "
"oe_size_count_index, NULL)) < 0) {\n"),
case ictype:isBasicTypeOrEterm(G, N, ElType) of
true ->
emit(Fd, " if ((oe_error_code = ei_decode_string(oe_env->"
"_inbuf, oe_size_count_index, NULL)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_string", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " oe_malloc_size = ~s;\n\n",
[align(["sizeof(", CType, ") * oe_seq_len"])]);
false ->
emit_c_dec_rpt(Fd, " ", "non mea culpa", []),
emit(Fd, " return oe_error_code;\n\n")
end,
emit(Fd, " } else {\n"),
emit(Fd, " oe_malloc_size = ~s;\n\n",
[align(["sizeof(", CType, ") * oe_seq_len"])]),
emit(Fd, " for (oe_seq_count = 0; oe_seq_count < oe_seq_len; "
"oe_seq_count++) {\n"),
ic_cbe:emit_malloc_size_stmt(G, N, Fd, ElType,
"oe_env->_inbuf", 0, generator),
emit(Fd, " }\n"),
emit(Fd, " if (oe_seq_len != 0) \n"),
emit(Fd, " if ((oe_error_code = ei_decode_list_header(oe_env->_inbuf,"
"oe_size_count_index, NULL)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_list_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " }\n"),
emit(Fd, " *oe_size = ~s;\n\n", [align("*oe_size + oe_malloc_size")]);
emit_sizecount(struct, G, N, _T, Fd, StructName, ElTypes) ->
Length = length(ElTypes) + 1,
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n\n",[Tname]),
emit(Fd, " if(*oe_size == 0)\n",[]),
AlignName = lists:concat(["*oe_size + sizeof(",StructName,")"]),
emit(Fd, " *oe_size = ~s;\n\n", [align(AlignName)]),
ic_codegen:nl(Fd),
emit(Fd, " if ((oe_error_code = "
"ei_get_type(oe_env->_inbuf, oe_size_count_index, &oe_type, "
"&~s)) < 0) {\n", [Tname]),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (~s != ~p) {\n",[Tname, Length]),
emit_c_dec_rpt(Fd, " ", "~s != ~p", [Tname, Length]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = "
"ei_decode_tuple_header(oe_env->_inbuf, "
"oe_size_count_index, 0)) < 0) {\n"),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if ((oe_error_code = "
"ei_decode_atom(oe_env->_inbuf, oe_size_count_index, 0)) < 0) {\n", []),
emit_c_dec_rpt(Fd, " ", "ei_decode_atom", []),
emit(Fd, " return oe_error_code;\n }\n"),
lists:foreach(
fun({ET, EN}) ->
case ic_cbe:is_variable_size(G, N, ET) of
true ->
case ET of
{sequence, _, _} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ EN,
"oe_env->_inbuf",
0,
generator);
{_,{array, _, _}} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ EN,
"oe_env->_inbuf",
0,
generator);
{union,_,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
{struct,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
_ ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
ET,
"oe_env->_inbuf",
0,
generator)
end;
false ->
case ET of
{_,{array, _, _}} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ EN,
"oe_env->_inbuf",
0,
generator);
{union,_,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
{struct,_,_,_} ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
StructName ++ "_" ++ ic_forms:get_id2(ET),
"oe_env->_inbuf",
0,
generator);
_ ->
ic_cbe:emit_malloc_size_stmt(
G, N, Fd,
ET,
"oe_env->_inbuf",
1,
generator)
end
end
end,
ElTypes),
emit(Fd, " *oe_size = ~s;\n\n",
[align("*oe_size + oe_malloc_size")]).
array_size_dimension_loop(G, N, Fd, [Dim], Type) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"ei_get_type(oe_env->_inbuf, oe_size_count_index, "
"&oe_type, &oe_array_size)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (oe_array_size != ~s) {\n",[Dim]),
emit_c_dec_rpt(Fd, " ", "array size != ~s", [Dim]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"oe_size_count_index, 0)) < 0) {\n", []),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
ic_cbe:emit_malloc_size_stmt(G, N, Fd,
Type, "oe_env->_inbuf", 0, generator),
emit(Fd, " }\n");
array_size_dimension_loop(G, N, Fd, [Dim | Ds], Type) ->
Tname = ic_cbe:mk_variable_name(op_variable_count),
ic_cbe:store_tmp_decl(" int ~s = 0;\n",[Tname]),
emit(Fd, " if ((oe_error_code = "
"ei_get_type(oe_env->_inbuf, oe_size_count_index, "
"&oe_type, &oe_array_size)) < 0) {\n", []),
emit_c_dec_rpt(Fd, " ", "ei_get_type", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " if (oe_array_size != ~s) {\n",[Dim]),
emit_c_dec_rpt(Fd, " ", "array size != ~s", [Dim]),
emit(Fd, " return -1;\n }\n"),
emit(Fd, " if ((oe_error_code = ei_decode_tuple_header(oe_env->_inbuf, "
"oe_size_count_index, 0)) < 0) {\n",
[]),
emit_c_dec_rpt(Fd, " ", "ei_decode_tuple_header", []),
emit(Fd, " return oe_error_code;\n }\n"),
emit(Fd, " for (~s = 0; ~s < ~s; ~s++) {\n",
[Tname, Tname, Dim, Tname]),
array_size_dimension_loop(G, N, Fd, Ds, Type),
emit(Fd, " }\n").
create_c_struct_coding_file(G, N, _X, T, StructName, ElTypes, StructType) ->
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, c),
HrlFName = filename:basename(ic_genobj:include_file(G)),
emit(Fd, "#include \"~s\"\n\n",[HrlFName]),
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, int*, int*);\n",
[ic_util:mk_oe_name(G, "sizecalc_"), StructName]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, "
"int* oe_size_count_index, int* oe_size)\n{\n",
[ic_util:mk_oe_name(G, "sizecalc_"), StructName]),
emit(Fd, " int oe_malloc_size = 0;\n",[]),
emit(Fd, " int oe_error_code = 0;\n",[]),
emit(Fd, " int oe_type = 0;\n",[]),
{ok, RamFd} = ram_file:open([], [binary, write]),
emit_sizecount(StructType, G, N, T, RamFd, StructName, ElTypes),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
{ok, Data} = ram_file:get_file(RamFd),
emit(Fd, Data),
ram_file:close(RamFd),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n\n",[]),
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, ~s*);\n",
[ic_util:mk_oe_name(G, "encode_"), StructName, StructName]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, ~s* oe_rec)\n{\n",
[ic_util:mk_oe_name(G, "encode_"), StructName, StructName]),
emit(Fd, " int oe_error_code = 0;\n",[]),
{ok, RamFd1} = ram_file:open([], [binary, write]),
emit_encode(StructType, G, N, T, RamFd1, StructName, ElTypes),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
{ok, Data1} = ram_file:get_file(RamFd1),
emit(Fd, Data1),
ram_file:close(RamFd1),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n\n",[]),
put(op_variable_count, 0),
put(tmp_declarations, []),
emit(HFd, "int ~s~s(CORBA_Environment *oe_env, char *, int*, ~s *);\n",
[ic_util:mk_oe_name(G, "decode_"), StructName, StructName]),
emit(Fd, "int ~s~s(CORBA_Environment *oe_env, char *oe_first, "
"int* oe_outindex, "
"~s *oe_out)\n{\n",
[ic_util:mk_oe_name(G, "decode_"), StructName, StructName]),
emit(Fd, " int oe_error_code = 0;\n",[]),
{ok, RamFd2} = ram_file:open([], [binary, write]),
emit_decode(StructType, G, N, T, RamFd2, StructName, ElTypes),
ic_cbe:emit_tmp_variables(Fd),
ic_codegen:nl(Fd),
{ok, Data2} = ram_file:get_file(RamFd2),
emit(Fd, Data2),
ram_file:close(RamFd2),
emit(Fd, " *oe_outindex = ~s;\n",[align("*oe_outindex")]),
emit(Fd, " return 0;\n\n",[]),
emit(Fd, "}\n\n",[]),
file:close(Fd).
emit_union(G, N, X, erlang) ->
case ic_genobj:is_hrlfile_open(G) of
true ->
ic_codegen:record(G, X,
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
nil,nil),
mkFileRecObj(G,N,X,erlang);
false -> ok
end;
true.
for CORBA ...... If wished an option could allows even
mkFileRecObj(G,N,X,erlang) ->
case ic_options:get_opt(G, be) of
erl_corba ->
SName =
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
FName =
ic_file:join(ic_options:get_opt(G, stubdir),
ic_file:add_dot_erl(SName)),
case file:open(FName, [write]) of
{ok, Fd} ->
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, erlang),
emit(Fd, "-include(~p).\n\n",[HrlFName]),
emit_exports(G,Fd),
emit_rec_methods(G,N,X,SName,Fd),
ic_codegen:nl(Fd),
ic_codegen:nl(Fd),
file:close(Fd);
Other ->
exit(Other)
end;
_ ->
true
end.
mkFileArrObj(G,N,X,erlang) ->
SName =
ic_util:to_undersc([ic_forms:get_id2(X) | N]),
FName =
ic_file:join(ic_options:get_opt(G, stubdir),
ic_file:add_dot_erl(SName)),
case file:open(FName, [write]) of
{ok, Fd} ->
HrlFName = filename:basename(ic_genobj:include_file(G)),
ic_codegen:emit_stub_head(G, Fd, SName, erlang),
emit(Fd, "-include(~p).\n\n",[HrlFName]),
emit_exports(G,Fd),
emit_arr_methods(G,N,X,SName,Fd),
ic_codegen:nl(Fd),
ic_codegen:nl(Fd),
file:close(Fd);
Other ->
exit(Other)
end.
emit exports for erlang modules which represent records .
emit_exports(G,Fd) ->
case ic_options:get_opt(G, be) of
erl_corba ->
emit(Fd, "-export([tc/0,id/0,name/0]).\n\n\n\n",[]);
_ ->
emit(Fd, "-export([id/0,name/0]).\n\n\n\n",[])
end.
emit_rec_methods(G,N,X,Name,Fd) ->
IR_ID = ictk:get_IR_ID(G, N, X),
case ic_options:get_opt(G, be) of
erl_corba ->
TK = ic_forms:get_tk(X),
case TK of
undefined ->
STK = ic_forms:search_tk(G,ictk:get_IR_ID(G, N, X)),
emit(Fd, "%% returns type code\n",[]),
emit(Fd, "tc() -> ~p.\n\n",[STK]),
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name]);
_ ->
emit(Fd, "%% returns type code\n",[]),
emit(Fd, "tc() -> ~p.\n\n",[TK]),
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name])
end;
_ ->
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name])
end.
emit_arr_methods(G,N,X,Name,Fd) ->
IR_ID = ictk:get_IR_ID(G, N, X),
case ic_options:get_opt(G, be) of
erl_corba ->
TK = ic_forms:get_type_code(G, N, X),
emit(Fd, "%% returns type code\n",[]),
emit(Fd, "tc() -> ~p.\n\n",[TK]),
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name]);
_ ->
emit(Fd, "%% returns id\n",[]),
emit(Fd, "id() -> ~p.\n\n",[IR_ID]),
emit(Fd, "%% returns name\n",[]),
emit(Fd, "name() -> ~p.\n\n",[Name])
end.
get_seq_max(T) when is_record(T, sequence) andalso T#sequence.length == 0 ->
infinity;
get_seq_max(T) when is_record(T, sequence) andalso is_tuple(T#sequence.length) ->
list_to_integer(element(3, T#sequence.length)).
align(Cs) ->
ic_util:mk_align(Cs).
|
e89178e43fa159d816cb6bd5b395ec3adaef16821a1217fedcbdffadcf093b56 | mfelleisen/Acquire | auxiliaries.rkt | #lang racket
(require math)
(provide
(contract-out
(randomly-pick (-> cons? any))
(distinct
;; for small lists O(n^2)
(-> list? boolean?))
(sorted
;; is the given list sorted according to the given comparison wrt to the key
(->i ((cmp (-> any/c any/c any))) (#:key (key (-> any/c any))) (ok? (-> list? any))))
(winners
;; find the prefix that has the same value according to the [optional] key selector
(->i ([l (key) (and/c cons? (sorted >= #:key (if (unsupplied-arg? key) values key)))])
([key (-> any/c real?)]
#:info [info (-> any/c any/c)])
(list-of-winners cons?)))
(partition
;; create equal-valued partitions (sorted), assuming the list is sorted
(->i ([l (key) (and/c cons?
(or/c
(sorted <= #:key (if (unsupplied-arg? key) values key))
(sorted >= #:key (if (unsupplied-arg? key) values key))))])
([key (-> any/c real?)]
#:info (info (-> any/c any/c)))
(partitions (listof cons?))))
(combinations/no-order
;; create combinations of size at most k for list l w/o regard to order
(->i ([k natural-number/c][l (k) (and/c list? (compose (>=/c k) length))])
[result (k l) (and/c [listof list?] (compose (=/c (co-no-order# (length l) k)) length))]))))
;; (co-no-order# (-> natural-number/c natural-number/c natural-number/c))
;; number of combinations of size at most k for a collection of n items
(define (co-no-order# n k)
(for/sum ((j (range (+ k 1)))) (binomial n j)))
;; ---------------------------------------------------------------------------------------------------
(define (randomly-pick l)
(list-ref l (random (length l))))
(define ((sorted cmp #:key (key values)) l)
(or (empty? l)
(let all ([l (rest l)][pred (key (first l))])
(cond
[(empty? l) #t]
[else
(define key2 (key (first l)))
(and (cmp pred key2) (all (rest l) key2))]))))
(define (partition lo-h-size (selector values) #:info (info values))
(define one (first lo-h-size))
(let loop [(pred (selector one)) (l (rest lo-h-size)) [partition (list (info one))]]
(cond
[(empty? l) (list (reverse partition))]
[else
(define two (first l))
(if (not (= (selector two) pred))
(cons (reverse partition) (loop (selector two) (rest l) (list (info two))))
(loop pred (rest l) (cons (info two) partition)))])))
(define (winners lo-h-size (selector values) #:info (info values))
(first (partition lo-h-size selector #:info info)))
(define (distinct s)
(cond
[(empty? s) #t]
[else (and (not (member (first s) (rest s))) (distinct (rest s)))]))
(define (combinations/no-order n lox)
(cond
[(= n 0) '(())]
[(empty? lox) '(())]
[else
(define one (first lox))
(define chs (combinations/no-order (- n 1) (rest lox)))
(append (map (lambda (n-1) (cons one n-1)) chs) (combinations/no-order n (rest lox)))]))
(module+ test
(require rackunit (submod ".."))
;; testing choice
; (check-equal? (choice 3 '()) '(()))
(check-equal? (combinations/no-order 1 '(a b c)) '((a) (b) (c) ()))
(check-equal? (combinations/no-order 2 '(a b c)) '((a b) (a c) (a) (b c) (b) (c) ()))
(check-equal? (combinations/no-order 3 '(a b c)) '((a b c) (a b) (a c) (a) (b c) (b) (c) ()))
;; testing random pick
(define l (build-list 100 add1))
(define x (randomly-pick l))
(check-true (cons? (member x l)))
;; testing sorted
(check-false ((sorted <= #:key second) '((a 6) (b 4) (c 4))))
(check-true ((sorted >= #:key second) '((a 6) (b 4) (c 4))))
;; testing distinct
(check-true (distinct (build-list 10 (λ (i) (list i i)))))
(check-true (distinct (build-list 10 number->string)))
(check-false (distinct (build-list 10 (λ (_) 1))))
;; testing winners
(check-equal? (winners '(3 3 2 1)) '(3 3))
(check-equal? (winners '((a 3) (b 3) (c 2) (d 1)) second) '((a 3) (b 3)))
(check-equal? (winners '((a 3) (b 3) (c 2) (d 1)) second #:info first) '(a b))
;; testing partition
(check-equal? (partition '(1 1 2)) '((1 1) (2)))
(check-equal? (partition '(1 1 2 2 3)) '((1 1) (2 2) (3))))
| null | https://raw.githubusercontent.com/mfelleisen/Acquire/5b39df6c757c7c1cafd7ff198641c99d30072b91/Lib/auxiliaries.rkt | racket | for small lists O(n^2)
is the given list sorted according to the given comparison wrt to the key
find the prefix that has the same value according to the [optional] key selector
create equal-valued partitions (sorted), assuming the list is sorted
create combinations of size at most k for list l w/o regard to order
(co-no-order# (-> natural-number/c natural-number/c natural-number/c))
number of combinations of size at most k for a collection of n items
---------------------------------------------------------------------------------------------------
testing choice
(check-equal? (choice 3 '()) '(()))
testing random pick
testing sorted
testing distinct
testing winners
testing partition | #lang racket
(require math)
(provide
(contract-out
(randomly-pick (-> cons? any))
(distinct
(-> list? boolean?))
(sorted
(->i ((cmp (-> any/c any/c any))) (#:key (key (-> any/c any))) (ok? (-> list? any))))
(winners
(->i ([l (key) (and/c cons? (sorted >= #:key (if (unsupplied-arg? key) values key)))])
([key (-> any/c real?)]
#:info [info (-> any/c any/c)])
(list-of-winners cons?)))
(partition
(->i ([l (key) (and/c cons?
(or/c
(sorted <= #:key (if (unsupplied-arg? key) values key))
(sorted >= #:key (if (unsupplied-arg? key) values key))))])
([key (-> any/c real?)]
#:info (info (-> any/c any/c)))
(partitions (listof cons?))))
(combinations/no-order
(->i ([k natural-number/c][l (k) (and/c list? (compose (>=/c k) length))])
[result (k l) (and/c [listof list?] (compose (=/c (co-no-order# (length l) k)) length))]))))
(define (co-no-order# n k)
(for/sum ((j (range (+ k 1)))) (binomial n j)))
(define (randomly-pick l)
(list-ref l (random (length l))))
(define ((sorted cmp #:key (key values)) l)
(or (empty? l)
(let all ([l (rest l)][pred (key (first l))])
(cond
[(empty? l) #t]
[else
(define key2 (key (first l)))
(and (cmp pred key2) (all (rest l) key2))]))))
(define (partition lo-h-size (selector values) #:info (info values))
(define one (first lo-h-size))
(let loop [(pred (selector one)) (l (rest lo-h-size)) [partition (list (info one))]]
(cond
[(empty? l) (list (reverse partition))]
[else
(define two (first l))
(if (not (= (selector two) pred))
(cons (reverse partition) (loop (selector two) (rest l) (list (info two))))
(loop pred (rest l) (cons (info two) partition)))])))
(define (winners lo-h-size (selector values) #:info (info values))
(first (partition lo-h-size selector #:info info)))
(define (distinct s)
(cond
[(empty? s) #t]
[else (and (not (member (first s) (rest s))) (distinct (rest s)))]))
(define (combinations/no-order n lox)
(cond
[(= n 0) '(())]
[(empty? lox) '(())]
[else
(define one (first lox))
(define chs (combinations/no-order (- n 1) (rest lox)))
(append (map (lambda (n-1) (cons one n-1)) chs) (combinations/no-order n (rest lox)))]))
(module+ test
(require rackunit (submod ".."))
(check-equal? (combinations/no-order 1 '(a b c)) '((a) (b) (c) ()))
(check-equal? (combinations/no-order 2 '(a b c)) '((a b) (a c) (a) (b c) (b) (c) ()))
(check-equal? (combinations/no-order 3 '(a b c)) '((a b c) (a b) (a c) (a) (b c) (b) (c) ()))
(define l (build-list 100 add1))
(define x (randomly-pick l))
(check-true (cons? (member x l)))
(check-false ((sorted <= #:key second) '((a 6) (b 4) (c 4))))
(check-true ((sorted >= #:key second) '((a 6) (b 4) (c 4))))
(check-true (distinct (build-list 10 (λ (i) (list i i)))))
(check-true (distinct (build-list 10 number->string)))
(check-false (distinct (build-list 10 (λ (_) 1))))
(check-equal? (winners '(3 3 2 1)) '(3 3))
(check-equal? (winners '((a 3) (b 3) (c 2) (d 1)) second) '((a 3) (b 3)))
(check-equal? (winners '((a 3) (b 3) (c 2) (d 1)) second #:info first) '(a b))
(check-equal? (partition '(1 1 2)) '((1 1) (2)))
(check-equal? (partition '(1 1 2 2 3)) '((1 1) (2 2) (3))))
|
ee02c3d72e981843c23e2ea2d7c1d306b62a1152395a21554f9e8ecdc70f250b | fetburner/Coq2SML | mutils.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(* *)
: A reflexive tactic using the
(* *)
(* ** Utility functions ** *)
(* *)
- Modules CoqToCaml , CamlToCoq
- , Tag , TagSet
(* *)
( / ) 2006 - 2008
(* *)
(************************************************************************)
let debug = false
let rec pp_list f o l =
match l with
| [] -> ()
| e::l -> f o e ; output_string o ";" ; pp_list f o l
let finally f rst =
try
let res = f () in
rst () ; res
with reraise ->
(try rst ()
with any -> raise reraise
); raise reraise
let map_option f x =
match x with
| None -> None
| Some v -> Some (f v)
let from_option = function
| None -> failwith "from_option"
| Some v -> v
let rec try_any l x =
match l with
| [] -> None
| (f,s)::l -> match f x with
| None -> try_any l x
| x -> x
let iteri f l =
let rec xiter i l =
match l with
| [] -> ()
| e::l -> f i e ; xiter (i+1) l in
xiter 0 l
let all_sym_pairs f l =
let pair_with acc e l = List.fold_left (fun acc x -> (f e x) ::acc) acc l in
let rec xpairs acc l =
match l with
| [] -> acc
| e::l -> xpairs (pair_with acc e l) l in
xpairs [] l
let rec map3 f l1 l2 l3 =
match l1 , l2 ,l3 with
| [] , [] , [] -> []
| e1::l1 , e2::l2 , e3::l3 -> (f e1 e2 e3)::(map3 f l1 l2 l3)
| _ -> raise (Invalid_argument "map3")
let rec is_sublist l1 l2 =
match l1 ,l2 with
| [] ,_ -> true
| e::l1', [] -> false
| e::l1' , e'::l2' ->
if e = e' then is_sublist l1' l2'
else is_sublist l1 l2'
let list_try_find f =
let rec try_find_f = function
| [] -> failwith "try_find"
| h::t -> try f h with Failure _ -> try_find_f t
in
try_find_f
let rec list_fold_right_elements f l =
let rec aux = function
| [] -> invalid_arg "list_fold_right_elements"
| [x] -> x
| x::l -> f x (aux l) in
aux l
let interval n m =
let rec interval_n (l,m) =
if n > m then l else interval_n (m::l,pred m)
in
interval_n ([],m)
let extract pred l =
List.fold_left (fun (fd,sys) e ->
match fd with
| None ->
begin
match pred e with
| None -> fd, e::sys
| Some v -> Some(v,e) , sys
end
| _ -> (fd, e::sys)
) (None,[]) l
open Num
open Big_int
let ppcm x y =
let g = gcd_big_int x y in
let x' = div_big_int x g in
let y' = div_big_int y g in
mult_big_int g (mult_big_int x' y')
let denominator = function
| Int _ | Big_int _ -> unit_big_int
| Ratio r -> Ratio.denominator_ratio r
let numerator = function
| Ratio r -> Ratio.numerator_ratio r
| Int i -> Big_int.big_int_of_int i
| Big_int i -> i
let rec ppcm_list c l =
match l with
| [] -> c
| e::l -> ppcm_list (ppcm c (denominator e)) l
let rec rec_gcd_list c l =
match l with
| [] -> c
| e::l -> rec_gcd_list (gcd_big_int c (numerator e)) l
let rec gcd_list l =
let res = rec_gcd_list zero_big_int l in
if compare_big_int res zero_big_int = 0
then unit_big_int else res
let rats_to_ints l =
let c = ppcm_list unit_big_int l in
List.map (fun x -> (div_big_int (mult_big_int (numerator x) c)
(denominator x))) l
(* Nasty reordering of lists - useful to trim certificate down *)
let mapi f l =
let rec xmapi i l =
match l with
| [] -> []
| e::l -> (f e i)::(xmapi (i+1) l) in
xmapi 0 l
let concatMapi f l = List.rev (mapi (fun e i -> (i,f e)) l)
assoc_pos j [ a0 ... an ] = [ j , a0 .... an , j+n],j+n+1
let assoc_pos j l = (mapi (fun e i -> e,i+j) l, j + (List.length l))
let assoc_pos_assoc l =
let rec xpos i l =
match l with
| [] -> []
| (x,l) ::rst -> let (l',j) = assoc_pos i l in
(x,l')::(xpos j rst) in
xpos 0 l
let filter_pos f l =
(* Could sort ... take care of duplicates... *)
let rec xfilter l =
match l with
| [] -> []
| (x,e)::l ->
if List.exists (fun ee -> List.mem ee f) (List.map snd e)
then (x,e)::(xfilter l)
else xfilter l in
xfilter l
let select_pos lpos l =
let rec xselect i lpos l =
match lpos with
| [] -> []
| j::rpos ->
match l with
| [] -> failwith "select_pos"
| e::l ->
if i = j
then e:: (xselect (i+1) rpos l)
else xselect (i+1) lpos l in
xselect 0 lpos l
*
* MODULE : Coq to data - structure mappings
* MODULE: Coq to Caml data-structure mappings
*)
module CoqToCaml =
struct
open Micromega
let rec nat = function
| O -> 0
| S n -> (nat n) + 1
let rec positive p =
match p with
| XH -> 1
| XI p -> 1+ 2*(positive p)
| XO p -> 2*(positive p)
let n nt =
match nt with
| N0 -> 0
| Npos p -> positive p
let rec index i = (* Swap left-right ? *)
match i with
| XH -> 1
| XI i -> 1+(2*(index i))
| XO i -> 2*(index i)
let z x =
match x with
| Z0 -> 0
| Zpos p -> (positive p)
| Zneg p -> - (positive p)
open Big_int
let rec positive_big_int p =
match p with
| XH -> unit_big_int
| XI p -> add_int_big_int 1 (mult_int_big_int 2 (positive_big_int p))
| XO p -> (mult_int_big_int 2 (positive_big_int p))
let z_big_int x =
match x with
| Z0 -> zero_big_int
| Zpos p -> (positive_big_int p)
| Zneg p -> minus_big_int (positive_big_int p)
let num x = Num.Big_int (z_big_int x)
let q_to_num {qnum = x ; qden = y} =
Big_int (z_big_int x) // (Big_int (z_big_int (Zpos y)))
end
*
* MODULE : to Coq data - structure mappings
* MODULE: Caml to Coq data-structure mappings
*)
module CamlToCoq =
struct
open Micromega
let rec nat = function
| 0 -> O
| n -> S (nat (n-1))
let rec positive n =
if n=1 then XH
else if n land 1 = 1 then XI (positive (n lsr 1))
else XO (positive (n lsr 1))
let n nt =
if nt < 0
then assert false
else if nt = 0 then N0
else Npos (positive nt)
let rec index n =
if n=1 then XH
else if n land 1 = 1 then XI (index (n lsr 1))
else XO (index (n lsr 1))
let idx n =
(*a.k.a path_of_int *)
returns the list of digits of n in reverse order with initial 1 removed
let rec digits_of_int n =
if n=1 then []
else (n mod 2 = 1)::(digits_of_int (n lsr 1))
in
List.fold_right
(fun b c -> (if b then XI c else XO c))
(List.rev (digits_of_int n))
(XH)
let z x =
match compare x 0 with
| 0 -> Z0
| 1 -> Zpos (positive x)
| _ -> (* this should be -1 *)
Zneg (positive (-x))
open Big_int
let positive_big_int n =
let two = big_int_of_int 2 in
let rec _pos n =
if eq_big_int n unit_big_int then XH
else
let (q,m) = quomod_big_int n two in
if eq_big_int unit_big_int m
then XI (_pos q)
else XO (_pos q) in
_pos n
let bigint x =
match sign_big_int x with
| 0 -> Z0
| 1 -> Zpos (positive_big_int x)
| _ -> Zneg (positive_big_int (minus_big_int x))
let q n =
{Micromega.qnum = bigint (numerator n) ;
Micromega.qden = positive_big_int (denominator n)}
end
*
* MODULE : Comparisons on lists : by evaluating the elements in a single list ,
* between two lists given an ordering , and using a hash computation
* MODULE: Comparisons on lists: by evaluating the elements in a single list,
* between two lists given an ordering, and using a hash computation
*)
module Cmp =
struct
let rec compare_lexical l =
match l with
| [] -> 0 (* Equal *)
| f::l ->
let cmp = f () in
if cmp = 0 then compare_lexical l else cmp
let rec compare_list cmp l1 l2 =
match l1 , l2 with
| [] , [] -> 0
| [] , _ -> -1
| _ , [] -> 1
| e1::l1 , e2::l2 ->
let c = cmp e1 e2 in
if c = 0 then compare_list cmp l1 l2 else c
(**
* hash_list takes a hash function and a list, and computes an integer which
* is the hash value of the list.
*)
let hash_list hash l =
let rec _hash_list l h =
match l with
| [] -> h lxor (Hashtbl.hash [])
| e::l -> _hash_list l ((hash e) lxor h)
in _hash_list l 0
end
*
* MODULE : Labels for atoms in propositional formulas .
* Tags are used to identify unused atoms in CNFs , and propagate them back to
* the original formula . The translation back to Coq then ignores these
* superfluous items , which speeds the translation up a bit .
* MODULE: Labels for atoms in propositional formulas.
* Tags are used to identify unused atoms in CNFs, and propagate them back to
* the original formula. The translation back to Coq then ignores these
* superfluous items, which speeds the translation up a bit.
*)
module type Tag =
sig
type t
val from : int -> t
val next : t -> t
val pp : out_channel -> t -> unit
val compare : t -> t -> int
end
module Tag : Tag =
struct
type t = int
let from i = i
let next i = i + 1
let pp o i = output_string o (string_of_int i)
let compare : int -> int -> int = Pervasives.compare
end
(**
* MODULE: Ordered sets of tags.
*)
module TagSet = Set.Make(Tag)
(**
* Forking routine, plumbing the appropriate pipes where needed.
*)
let command exe_path args vl =
creating pipes for stdin , stdout , stderr
let (stdin_read,stdin_write) = Unix.pipe ()
and (stdout_read,stdout_write) = Unix.pipe ()
and (stderr_read,stderr_write) = Unix.pipe () in
(* Create the process *)
let pid = Unix.create_process exe_path args stdin_read stdout_write stderr_write in
(* Write the data on the stdin of the created process *)
let outch = Unix.out_channel_of_descr stdin_write in
output_value outch vl ;
flush outch ;
(* Wait for its completion *)
let _pid,status = Unix.waitpid [] pid in
finally
(* Recover the result *)
(fun () ->
match status with
| Unix.WEXITED 0 ->
let inch = Unix.in_channel_of_descr stdout_read in
begin try Marshal.from_channel inch
with x when x <> Sys.Break ->
failwith (Printf.sprintf "command \"%s\" exited %s" exe_path (Printexc.to_string x))
end
| Unix.WEXITED i -> failwith (Printf.sprintf "command \"%s\" exited %i" exe_path i)
| Unix.WSIGNALED i -> failwith (Printf.sprintf "command \"%s\" killed %i" exe_path i)
| Unix.WSTOPPED i -> failwith (Printf.sprintf "command \"%s\" stopped %i" exe_path i))
(* Cleanup *)
(fun () ->
List.iter (fun x -> try Unix.close x with e when e <> Sys.Break -> ())
[stdin_read; stdin_write; stdout_read; stdout_write; stderr_read; stderr_write])
(* Local Variables: *)
coding : utf-8
(* End: *)
| null | https://raw.githubusercontent.com/fetburner/Coq2SML/322d613619edbb62edafa999bff24b1993f37612/coq-8.4pl4/plugins/micromega/mutils.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
** Utility functions **
**********************************************************************
Nasty reordering of lists - useful to trim certificate down
Could sort ... take care of duplicates...
Swap left-right ?
a.k.a path_of_int
this should be -1
Equal
*
* hash_list takes a hash function and a list, and computes an integer which
* is the hash value of the list.
*
* MODULE: Ordered sets of tags.
*
* Forking routine, plumbing the appropriate pipes where needed.
Create the process
Write the data on the stdin of the created process
Wait for its completion
Recover the result
Cleanup
Local Variables:
End: | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2014
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
: A reflexive tactic using the
- Modules CoqToCaml , CamlToCoq
- , Tag , TagSet
( / ) 2006 - 2008
let debug = false
let rec pp_list f o l =
match l with
| [] -> ()
| e::l -> f o e ; output_string o ";" ; pp_list f o l
let finally f rst =
try
let res = f () in
rst () ; res
with reraise ->
(try rst ()
with any -> raise reraise
); raise reraise
let map_option f x =
match x with
| None -> None
| Some v -> Some (f v)
let from_option = function
| None -> failwith "from_option"
| Some v -> v
let rec try_any l x =
match l with
| [] -> None
| (f,s)::l -> match f x with
| None -> try_any l x
| x -> x
let iteri f l =
let rec xiter i l =
match l with
| [] -> ()
| e::l -> f i e ; xiter (i+1) l in
xiter 0 l
let all_sym_pairs f l =
let pair_with acc e l = List.fold_left (fun acc x -> (f e x) ::acc) acc l in
let rec xpairs acc l =
match l with
| [] -> acc
| e::l -> xpairs (pair_with acc e l) l in
xpairs [] l
let rec map3 f l1 l2 l3 =
match l1 , l2 ,l3 with
| [] , [] , [] -> []
| e1::l1 , e2::l2 , e3::l3 -> (f e1 e2 e3)::(map3 f l1 l2 l3)
| _ -> raise (Invalid_argument "map3")
let rec is_sublist l1 l2 =
match l1 ,l2 with
| [] ,_ -> true
| e::l1', [] -> false
| e::l1' , e'::l2' ->
if e = e' then is_sublist l1' l2'
else is_sublist l1 l2'
let list_try_find f =
let rec try_find_f = function
| [] -> failwith "try_find"
| h::t -> try f h with Failure _ -> try_find_f t
in
try_find_f
let rec list_fold_right_elements f l =
let rec aux = function
| [] -> invalid_arg "list_fold_right_elements"
| [x] -> x
| x::l -> f x (aux l) in
aux l
let interval n m =
let rec interval_n (l,m) =
if n > m then l else interval_n (m::l,pred m)
in
interval_n ([],m)
let extract pred l =
List.fold_left (fun (fd,sys) e ->
match fd with
| None ->
begin
match pred e with
| None -> fd, e::sys
| Some v -> Some(v,e) , sys
end
| _ -> (fd, e::sys)
) (None,[]) l
open Num
open Big_int
let ppcm x y =
let g = gcd_big_int x y in
let x' = div_big_int x g in
let y' = div_big_int y g in
mult_big_int g (mult_big_int x' y')
let denominator = function
| Int _ | Big_int _ -> unit_big_int
| Ratio r -> Ratio.denominator_ratio r
let numerator = function
| Ratio r -> Ratio.numerator_ratio r
| Int i -> Big_int.big_int_of_int i
| Big_int i -> i
let rec ppcm_list c l =
match l with
| [] -> c
| e::l -> ppcm_list (ppcm c (denominator e)) l
let rec rec_gcd_list c l =
match l with
| [] -> c
| e::l -> rec_gcd_list (gcd_big_int c (numerator e)) l
let rec gcd_list l =
let res = rec_gcd_list zero_big_int l in
if compare_big_int res zero_big_int = 0
then unit_big_int else res
let rats_to_ints l =
let c = ppcm_list unit_big_int l in
List.map (fun x -> (div_big_int (mult_big_int (numerator x) c)
(denominator x))) l
let mapi f l =
let rec xmapi i l =
match l with
| [] -> []
| e::l -> (f e i)::(xmapi (i+1) l) in
xmapi 0 l
let concatMapi f l = List.rev (mapi (fun e i -> (i,f e)) l)
assoc_pos j [ a0 ... an ] = [ j , a0 .... an , j+n],j+n+1
let assoc_pos j l = (mapi (fun e i -> e,i+j) l, j + (List.length l))
let assoc_pos_assoc l =
let rec xpos i l =
match l with
| [] -> []
| (x,l) ::rst -> let (l',j) = assoc_pos i l in
(x,l')::(xpos j rst) in
xpos 0 l
let filter_pos f l =
let rec xfilter l =
match l with
| [] -> []
| (x,e)::l ->
if List.exists (fun ee -> List.mem ee f) (List.map snd e)
then (x,e)::(xfilter l)
else xfilter l in
xfilter l
let select_pos lpos l =
let rec xselect i lpos l =
match lpos with
| [] -> []
| j::rpos ->
match l with
| [] -> failwith "select_pos"
| e::l ->
if i = j
then e:: (xselect (i+1) rpos l)
else xselect (i+1) lpos l in
xselect 0 lpos l
*
* MODULE : Coq to data - structure mappings
* MODULE: Coq to Caml data-structure mappings
*)
module CoqToCaml =
struct
open Micromega
let rec nat = function
| O -> 0
| S n -> (nat n) + 1
let rec positive p =
match p with
| XH -> 1
| XI p -> 1+ 2*(positive p)
| XO p -> 2*(positive p)
let n nt =
match nt with
| N0 -> 0
| Npos p -> positive p
match i with
| XH -> 1
| XI i -> 1+(2*(index i))
| XO i -> 2*(index i)
let z x =
match x with
| Z0 -> 0
| Zpos p -> (positive p)
| Zneg p -> - (positive p)
open Big_int
let rec positive_big_int p =
match p with
| XH -> unit_big_int
| XI p -> add_int_big_int 1 (mult_int_big_int 2 (positive_big_int p))
| XO p -> (mult_int_big_int 2 (positive_big_int p))
let z_big_int x =
match x with
| Z0 -> zero_big_int
| Zpos p -> (positive_big_int p)
| Zneg p -> minus_big_int (positive_big_int p)
let num x = Num.Big_int (z_big_int x)
let q_to_num {qnum = x ; qden = y} =
Big_int (z_big_int x) // (Big_int (z_big_int (Zpos y)))
end
*
* MODULE : to Coq data - structure mappings
* MODULE: Caml to Coq data-structure mappings
*)
module CamlToCoq =
struct
open Micromega
let rec nat = function
| 0 -> O
| n -> S (nat (n-1))
let rec positive n =
if n=1 then XH
else if n land 1 = 1 then XI (positive (n lsr 1))
else XO (positive (n lsr 1))
let n nt =
if nt < 0
then assert false
else if nt = 0 then N0
else Npos (positive nt)
let rec index n =
if n=1 then XH
else if n land 1 = 1 then XI (index (n lsr 1))
else XO (index (n lsr 1))
let idx n =
returns the list of digits of n in reverse order with initial 1 removed
let rec digits_of_int n =
if n=1 then []
else (n mod 2 = 1)::(digits_of_int (n lsr 1))
in
List.fold_right
(fun b c -> (if b then XI c else XO c))
(List.rev (digits_of_int n))
(XH)
let z x =
match compare x 0 with
| 0 -> Z0
| 1 -> Zpos (positive x)
Zneg (positive (-x))
open Big_int
let positive_big_int n =
let two = big_int_of_int 2 in
let rec _pos n =
if eq_big_int n unit_big_int then XH
else
let (q,m) = quomod_big_int n two in
if eq_big_int unit_big_int m
then XI (_pos q)
else XO (_pos q) in
_pos n
let bigint x =
match sign_big_int x with
| 0 -> Z0
| 1 -> Zpos (positive_big_int x)
| _ -> Zneg (positive_big_int (minus_big_int x))
let q n =
{Micromega.qnum = bigint (numerator n) ;
Micromega.qden = positive_big_int (denominator n)}
end
*
* MODULE : Comparisons on lists : by evaluating the elements in a single list ,
* between two lists given an ordering , and using a hash computation
* MODULE: Comparisons on lists: by evaluating the elements in a single list,
* between two lists given an ordering, and using a hash computation
*)
module Cmp =
struct
let rec compare_lexical l =
match l with
| f::l ->
let cmp = f () in
if cmp = 0 then compare_lexical l else cmp
let rec compare_list cmp l1 l2 =
match l1 , l2 with
| [] , [] -> 0
| [] , _ -> -1
| _ , [] -> 1
| e1::l1 , e2::l2 ->
let c = cmp e1 e2 in
if c = 0 then compare_list cmp l1 l2 else c
let hash_list hash l =
let rec _hash_list l h =
match l with
| [] -> h lxor (Hashtbl.hash [])
| e::l -> _hash_list l ((hash e) lxor h)
in _hash_list l 0
end
*
* MODULE : Labels for atoms in propositional formulas .
* Tags are used to identify unused atoms in CNFs , and propagate them back to
* the original formula . The translation back to Coq then ignores these
* superfluous items , which speeds the translation up a bit .
* MODULE: Labels for atoms in propositional formulas.
* Tags are used to identify unused atoms in CNFs, and propagate them back to
* the original formula. The translation back to Coq then ignores these
* superfluous items, which speeds the translation up a bit.
*)
module type Tag =
sig
type t
val from : int -> t
val next : t -> t
val pp : out_channel -> t -> unit
val compare : t -> t -> int
end
module Tag : Tag =
struct
type t = int
let from i = i
let next i = i + 1
let pp o i = output_string o (string_of_int i)
let compare : int -> int -> int = Pervasives.compare
end
module TagSet = Set.Make(Tag)
let command exe_path args vl =
creating pipes for stdin , stdout , stderr
let (stdin_read,stdin_write) = Unix.pipe ()
and (stdout_read,stdout_write) = Unix.pipe ()
and (stderr_read,stderr_write) = Unix.pipe () in
let pid = Unix.create_process exe_path args stdin_read stdout_write stderr_write in
let outch = Unix.out_channel_of_descr stdin_write in
output_value outch vl ;
flush outch ;
let _pid,status = Unix.waitpid [] pid in
finally
(fun () ->
match status with
| Unix.WEXITED 0 ->
let inch = Unix.in_channel_of_descr stdout_read in
begin try Marshal.from_channel inch
with x when x <> Sys.Break ->
failwith (Printf.sprintf "command \"%s\" exited %s" exe_path (Printexc.to_string x))
end
| Unix.WEXITED i -> failwith (Printf.sprintf "command \"%s\" exited %i" exe_path i)
| Unix.WSIGNALED i -> failwith (Printf.sprintf "command \"%s\" killed %i" exe_path i)
| Unix.WSTOPPED i -> failwith (Printf.sprintf "command \"%s\" stopped %i" exe_path i))
(fun () ->
List.iter (fun x -> try Unix.close x with e when e <> Sys.Break -> ())
[stdin_read; stdin_write; stdout_read; stdout_write; stderr_read; stderr_write])
coding : utf-8
|
cb45438155e3a9eca075cd7b87d2290d076ba4262c03ccac193d0b5c604b9b69 | ConsenSys/constellation | Network.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StrictData #-}
module Constellation.Util.Network where
import ClassyPrelude
import Network.Socket ( Family(AF_INET), SocketType(Stream)
, SockAddr(SockAddrInet)
, aNY_PORT, iNADDR_ANY
, socket, socketPort, bind, close
)
getUnusedPort :: IO Int
getUnusedPort = do
sock <- socket AF_INET Stream 0
bind sock $ SockAddrInet aNY_PORT iNADDR_ANY
port <- socketPort sock
close sock
return $ fromIntegral port
| null | https://raw.githubusercontent.com/ConsenSys/constellation/8fcd2d38b097da5242f511d2fb2149a9764f2f7b/Constellation/Util/Network.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData # | # LANGUAGE NoImplicitPrelude #
module Constellation.Util.Network where
import ClassyPrelude
import Network.Socket ( Family(AF_INET), SocketType(Stream)
, SockAddr(SockAddrInet)
, aNY_PORT, iNADDR_ANY
, socket, socketPort, bind, close
)
getUnusedPort :: IO Int
getUnusedPort = do
sock <- socket AF_INET Stream 0
bind sock $ SockAddrInet aNY_PORT iNADDR_ANY
port <- socketPort sock
close sock
return $ fromIntegral port
|
eb5bd4377050c57649e5891fcfc65579cdccb7d3fd941473bb17a6eb6892b130 | racket/typed-racket | contract-conversion-error.rkt | #lang racket/load
two cases of arity 1 , ok for shallow
(module a typed/racket/shallow (define v values) (provide v))
(require 'a)
v
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/contract-conversion-error.rkt | racket | #lang racket/load
two cases of arity 1 , ok for shallow
(module a typed/racket/shallow (define v values) (provide v))
(require 'a)
v
| |
c2d9a956a3904a0e6c997d17a36522448812931a2aa56e5b5cd3a62ecb16928b | w3ntao/sicp-solution | logicPuzzle.rkt | #lang racket
(require (only-in "../AbstractionOfData/list.rkt"
nil
flatmap
list-ref))
(provide (all-defined-out))
(define (apply-constrains combination constrains)
(if (null? constrains)
combination
(apply-constrains (filter (car constrains)
combination)
(cdr constrains))))
(define (all-combination raw-list)
(if (null? raw-list)
(list nil)
(flatmap (lambda (x)
(insert-item-at-every-position x
(car raw-list)))
(all-combination (cdr raw-list)))))
(define (insert-item-at-every-position raw-list item)
(define (insert-item n)
(append (list (insert-item-at raw-list
n))
(if (= n 0)
nil
(insert-item (- n 1)))))
(define (insert-item-at temp-list n)
(if (= n 0)
(cons item
temp-list)
(cons (car temp-list)
(insert-item-at (cdr temp-list)
(- n 1)))))
(insert-item (length raw-list))) | null | https://raw.githubusercontent.com/w3ntao/sicp-solution/00be3a7b4da50bb266f8a2db521a24e9f8c156be/ToolBox/LogicProgramming/logicPuzzle.rkt | racket | #lang racket
(require (only-in "../AbstractionOfData/list.rkt"
nil
flatmap
list-ref))
(provide (all-defined-out))
(define (apply-constrains combination constrains)
(if (null? constrains)
combination
(apply-constrains (filter (car constrains)
combination)
(cdr constrains))))
(define (all-combination raw-list)
(if (null? raw-list)
(list nil)
(flatmap (lambda (x)
(insert-item-at-every-position x
(car raw-list)))
(all-combination (cdr raw-list)))))
(define (insert-item-at-every-position raw-list item)
(define (insert-item n)
(append (list (insert-item-at raw-list
n))
(if (= n 0)
nil
(insert-item (- n 1)))))
(define (insert-item-at temp-list n)
(if (= n 0)
(cons item
temp-list)
(cons (car temp-list)
(insert-item-at (cdr temp-list)
(- n 1)))))
(insert-item (length raw-list))) | |
886e0703a52857a6213ea321d31293a1f48adb188b96550ac93c7a11cdcb22b2 | ruhler/smten | MiniSat.hs |
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE PatternGuards #
{-# OPTIONS_HADDOCK hide #-}
-- | Implementation of the MiniSat backend for smten.
module Smten.Compiled.Smten.Search.Solver.MiniSat (minisat) where
import qualified Data.HashTable.IO as H
import Data.Functor
import Data.Maybe
import Smten.Runtime.Build
import Smten.Runtime.Formula.Type
import Smten.Runtime.Formula.Finite
import Smten.Runtime.FreeID
import Smten.Runtime.SolverAST
import Smten.Runtime.Solver
import Smten.Runtime.MiniSat.FFI
import Smten.Runtime.Model
import Smten.Runtime.Result
import Smten.Runtime.Bits
import Smten.Runtime.Integers
type VarMap = H.BasicHashTable FreeID MSExpr
data MiniSat = MiniSat {
s_ctx :: MSSolver,
s_vars :: VarMap
}
nointegers = error "There is no native support integers in MiniSat"
nobits = error "There is no native support for bit vectors in MiniSat"
type MS_WITH_I = Integers MiniSat MSExpr MSExpr MSExpr
type MS_WITH_V = Bits MS_WITH_I MSExpr [(MSExpr, Integer)] MSExpr
# SPECIALIZE build : : BoolFF - > IO ( MSExpr , [ ( FreeID , Type ) ] ) #
# SPECIALIZE : : IO MS_WITH_V - > Solver #
minisat :: Solver
minisat = solverFromAST $ do
ptr <- c_minisat_new
vars <- H.new
let base = MiniSat ptr vars
withints <- addIntegers base
addBits withints :: IO MS_WITH_V
instance SolverAST MiniSat MSExpr MSExpr MSExpr where
declare_bool s nm = do
v <- c_minisat_var (s_ctx s)
H.insert (s_vars s) nm v
declare_integer y nm = nointegers
declare_bit y w nm = nobits
getBoolValue s nm = do
r <- H.lookup (s_vars s) nm
case r of
Just v -> do
r <- c_minisat_getvar (s_ctx s) v
case r of
0 -> return False
1 -> return True
_ -> error $ "unexpected result from getvar: " ++ show r
Nothing -> error $ "var " ++ freenm nm ++ " not found"
getIntegerValue = nointegers
getBitVectorValue = nobits
getModel s vars = sequence [BoolA <$> getBoolValue s nm | (nm, BoolT) <- vars]
check s = do
r <- c_minisat_check (s_ctx s)
case r of
0 -> return Unsat
1 -> return Sat
cleanup s = c_minisat_delete (s_ctx s)
assert s e = c_minisat_assert (s_ctx s) e
bool s True = c_minisat_true (s_ctx s)
bool s False = c_minisat_false (s_ctx s)
integer = nointegers
bit = nobits
var_bool s nm = fromJust <$> H.lookup (s_vars s) nm
var_integer s nm = nointegers
var_bit s w nm = nobits
and_bool s a b = c_minisat_and (s_ctx s) a b
or_bool s a b = c_minisat_or (s_ctx s) a b
not_bool s a = c_minisat_not (s_ctx s) a
ite_bool s p a b = c_minisat_ite (s_ctx s) p a b
ite_integer = nointegers
ite_bit = nobits
eq_integer = nointegers
leq_integer = nointegers
add_integer = nointegers
sub_integer = nointegers
eq_bit = nobits
leq_bit = nobits
add_bit = nobits
sub_bit = nobits
mul_bit = nobits
sdiv_bit = nobits
srem_bit = nobits
smod_bit = nobits
udiv_bit = nobits
urem_bit = nobits
or_bit = nobits
and_bit = nobits
concat_bit = nobits
shl_bit = nobits
lshr_bit = nobits
not_bit = nobits
sign_extend_bit = nobits
extract_bit = nobits
| null | https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-minisat/Smten/Compiled/Smten/Search/Solver/MiniSat.hs | haskell | # LANGUAGE TypeSynonymInstances #
# OPTIONS_HADDOCK hide #
| Implementation of the MiniSat backend for smten. |
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternGuards #
module Smten.Compiled.Smten.Search.Solver.MiniSat (minisat) where
import qualified Data.HashTable.IO as H
import Data.Functor
import Data.Maybe
import Smten.Runtime.Build
import Smten.Runtime.Formula.Type
import Smten.Runtime.Formula.Finite
import Smten.Runtime.FreeID
import Smten.Runtime.SolverAST
import Smten.Runtime.Solver
import Smten.Runtime.MiniSat.FFI
import Smten.Runtime.Model
import Smten.Runtime.Result
import Smten.Runtime.Bits
import Smten.Runtime.Integers
type VarMap = H.BasicHashTable FreeID MSExpr
data MiniSat = MiniSat {
s_ctx :: MSSolver,
s_vars :: VarMap
}
nointegers = error "There is no native support integers in MiniSat"
nobits = error "There is no native support for bit vectors in MiniSat"
type MS_WITH_I = Integers MiniSat MSExpr MSExpr MSExpr
type MS_WITH_V = Bits MS_WITH_I MSExpr [(MSExpr, Integer)] MSExpr
# SPECIALIZE build : : BoolFF - > IO ( MSExpr , [ ( FreeID , Type ) ] ) #
# SPECIALIZE : : IO MS_WITH_V - > Solver #
minisat :: Solver
minisat = solverFromAST $ do
ptr <- c_minisat_new
vars <- H.new
let base = MiniSat ptr vars
withints <- addIntegers base
addBits withints :: IO MS_WITH_V
instance SolverAST MiniSat MSExpr MSExpr MSExpr where
declare_bool s nm = do
v <- c_minisat_var (s_ctx s)
H.insert (s_vars s) nm v
declare_integer y nm = nointegers
declare_bit y w nm = nobits
getBoolValue s nm = do
r <- H.lookup (s_vars s) nm
case r of
Just v -> do
r <- c_minisat_getvar (s_ctx s) v
case r of
0 -> return False
1 -> return True
_ -> error $ "unexpected result from getvar: " ++ show r
Nothing -> error $ "var " ++ freenm nm ++ " not found"
getIntegerValue = nointegers
getBitVectorValue = nobits
getModel s vars = sequence [BoolA <$> getBoolValue s nm | (nm, BoolT) <- vars]
check s = do
r <- c_minisat_check (s_ctx s)
case r of
0 -> return Unsat
1 -> return Sat
cleanup s = c_minisat_delete (s_ctx s)
assert s e = c_minisat_assert (s_ctx s) e
bool s True = c_minisat_true (s_ctx s)
bool s False = c_minisat_false (s_ctx s)
integer = nointegers
bit = nobits
var_bool s nm = fromJust <$> H.lookup (s_vars s) nm
var_integer s nm = nointegers
var_bit s w nm = nobits
and_bool s a b = c_minisat_and (s_ctx s) a b
or_bool s a b = c_minisat_or (s_ctx s) a b
not_bool s a = c_minisat_not (s_ctx s) a
ite_bool s p a b = c_minisat_ite (s_ctx s) p a b
ite_integer = nointegers
ite_bit = nobits
eq_integer = nointegers
leq_integer = nointegers
add_integer = nointegers
sub_integer = nointegers
eq_bit = nobits
leq_bit = nobits
add_bit = nobits
sub_bit = nobits
mul_bit = nobits
sdiv_bit = nobits
srem_bit = nobits
smod_bit = nobits
udiv_bit = nobits
urem_bit = nobits
or_bit = nobits
and_bit = nobits
concat_bit = nobits
shl_bit = nobits
lshr_bit = nobits
not_bit = nobits
sign_extend_bit = nobits
extract_bit = nobits
|
660a7c4281c2d196dc5836dd4d3a67d485a436ed89419a92964760b0a490f95c | fragnix/fragnix | Data.Sequence.hs | # LANGUAGE Haskell98 #
{-# LINE 1 "Data/Sequence.hs" #-}
# LANGUAGE CPP #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Sequence
Copyright : ( c ) 2005
( c ) 2009
( c ) , , , and
Milan Straka 2014
-- License : BSD-style
-- Maintainer :
-- Portability : portable
--
-- General purpose finite sequences.
-- Apart from being finite and having strict operations, sequences
-- also differ from lists in supporting a wider variety of operations
-- efficiently.
--
-- An amortized running time is given for each operation, with /n/ referring
-- to the length of the sequence and /i/ being the integral index used by
-- some operations. These bounds hold even in a persistent (shared) setting.
--
The implementation uses 2 - 3 finger trees annotated with sizes ,
as described in section 4.2 of
--
* and ,
\"Finger trees : a simple general - purpose data structure\ " ,
/Journal of Functional Programming/ 16:2 ( 2006 ) pp 197 - 217 .
-- </~ross/papers/FingerTree.html>
--
-- /Note/: Many of these operations have the same names as similar
operations on lists in the " Prelude " . The ambiguity may be resolved
-- using either qualification or the @hiding@ clause.
--
/Warning/ : The size of a ' Seq ' must not exceed @maxBound::Int@. Violation
-- of this condition is not detected and if the size limit is exceeded, the
-- behaviour of the sequence is undefined. This is unlikely to occur in most
-- applications, but some care may be required when using '><', '<*>', '*>', or
-- '>>', particularly repeatedly and particularly in combination with
-- 'replicate' or 'fromFunction'.
--
-----------------------------------------------------------------------------
module Data.Sequence (
Seq (Empty, (:<|), (:|>)),
-- * Construction
empty, -- :: Seq a
singleton, -- :: a -> Seq a
(<|), -- :: a -> Seq a -> Seq a
(|>), -- :: Seq a -> a -> Seq a
(><), -- :: Seq a -> Seq a -> Seq a
fromList, -- :: [a] -> Seq a
fromFunction, -- :: Int -> (Int -> a) -> Seq a
fromArray, -- :: Ix i => Array i a -> Seq a
-- ** Repetition
replicate, -- :: Int -> a -> Seq a
replicateA, -- :: Applicative f => Int -> f a -> f (Seq a)
: : = > Int - > m a - > m ( Seq a )
cycleTaking, -- :: Int -> Seq a -> Seq a
-- ** Iterative construction
iterateN, -- :: Int -> (a -> a) -> a -> Seq a
unfoldr, -- :: (b -> Maybe (a, b)) -> b -> Seq a
unfoldl, -- :: (b -> Maybe (b, a)) -> b -> Seq a
-- * Deconstruction
-- | Additional functions for deconstructing sequences are available
-- via the 'Foldable' instance of 'Seq'.
-- ** Queries
null, -- :: Seq a -> Bool
length, -- :: Seq a -> Int
-- ** Views
ViewL(..),
: : Seq a - > ViewL a
ViewR(..),
viewr, -- :: Seq a -> ViewR a
-- * Scans
scanl, -- :: (a -> b -> a) -> a -> Seq b -> Seq a
scanl1, -- :: (a -> a -> a) -> Seq a -> Seq a
scanr, -- :: (a -> b -> b) -> b -> Seq a -> Seq b
scanr1, -- :: (a -> a -> a) -> Seq a -> Seq a
-- * Sublists
tails, -- :: Seq a -> Seq (Seq a)
inits, -- :: Seq a -> Seq (Seq a)
chunksOf, -- :: Int -> Seq a -> Seq (Seq a)
-- ** Sequential searches
takeWhileL, -- :: (a -> Bool) -> Seq a -> Seq a
takeWhileR, -- :: (a -> Bool) -> Seq a -> Seq a
dropWhileL, -- :: (a -> Bool) -> Seq a -> Seq a
dropWhileR, -- :: (a -> Bool) -> Seq a -> Seq a
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
filter, -- :: (a -> Bool) -> Seq a -> Seq a
-- * Sorting
: : a = > Seq a - > Seq a
sortBy, -- :: (a -> a -> Ordering) -> Seq a -> Seq a
: : a = > Seq a - > Seq a
unstableSortBy, -- :: (a -> a -> Ordering) -> Seq a -> Seq a
-- * Indexing
lookup, -- :: Int -> Seq a -> Maybe a
(!?), -- :: Seq a -> Int -> Maybe a
index, -- :: Seq a -> Int -> a
adjust, -- :: (a -> a) -> Int -> Seq a -> Seq a
adjust', -- :: (a -> a) -> Int -> Seq a -> Seq a
update, -- :: Int -> a -> Seq a -> Seq a
take, -- :: Int -> Seq a -> Seq a
drop, -- :: Int -> Seq a -> Seq a
insertAt, -- :: Int -> a -> Seq a -> Seq a
deleteAt, -- :: Int -> Seq a -> Seq a
: : Int - > Seq a - > ( Seq a , Seq a )
-- ** Indexing with predicates
-- | These functions perform sequential searches from the left
-- or right ends of the sequence, returning indices of matching
-- elements.
elemIndexL, -- :: Eq a => a -> Seq a -> Maybe Int
elemIndicesL, -- :: Eq a => a -> Seq a -> [Int]
elemIndexR, -- :: Eq a => a -> Seq a -> Maybe Int
elemIndicesR, -- :: Eq a => a -> Seq a -> [Int]
findIndexL, -- :: (a -> Bool) -> Seq a -> Maybe Int
findIndicesL, -- :: (a -> Bool) -> Seq a -> [Int]
findIndexR, -- :: (a -> Bool) -> Seq a -> Maybe Int
findIndicesR, -- :: (a -> Bool) -> Seq a -> [Int]
-- * Folds
-- | General folds are available via the 'Foldable' instance of 'Seq'.
foldMapWithIndex, -- :: Monoid m => (Int -> a -> m) -> Seq a -> m
foldlWithIndex, -- :: (b -> Int -> a -> b) -> b -> Seq a -> b
foldrWithIndex, -- :: (Int -> a -> b -> b) -> b -> Seq a -> b
-- * Transformations
mapWithIndex, -- :: (Int -> a -> b) -> Seq a -> Seq b
traverseWithIndex, -- :: Applicative f => (Int -> a -> f b) -> Seq a -> f (Seq b)
reverse, -- :: Seq a -> Seq a
intersperse, -- :: a -> Seq a -> Seq a
* *
zip, -- :: Seq a -> Seq b -> Seq (a, b)
zipWith, -- :: (a -> b -> c) -> Seq a -> Seq b -> Seq c
zip3, -- :: Seq a -> Seq b -> Seq c -> Seq (a, b, c)
zipWith3, -- :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d
zip4, -- :: Seq a -> Seq b -> Seq c -> Seq d -> Seq (a, b, c, d)
zipWith4, -- :: (a -> b -> c -> d -> e) -> Seq a -> Seq b -> Seq c -> Seq d -> Seq e
) where
import Data.Sequence.Internal
import Prelude ()
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/tests/packages/application/Data.Sequence.hs | haskell | # LINE 1 "Data/Sequence.hs" #
---------------------------------------------------------------------------
|
Module : Data.Sequence
License : BSD-style
Maintainer :
Portability : portable
General purpose finite sequences.
Apart from being finite and having strict operations, sequences
also differ from lists in supporting a wider variety of operations
efficiently.
An amortized running time is given for each operation, with /n/ referring
to the length of the sequence and /i/ being the integral index used by
some operations. These bounds hold even in a persistent (shared) setting.
</~ross/papers/FingerTree.html>
/Note/: Many of these operations have the same names as similar
using either qualification or the @hiding@ clause.
of this condition is not detected and if the size limit is exceeded, the
behaviour of the sequence is undefined. This is unlikely to occur in most
applications, but some care may be required when using '><', '<*>', '*>', or
'>>', particularly repeatedly and particularly in combination with
'replicate' or 'fromFunction'.
---------------------------------------------------------------------------
* Construction
:: Seq a
:: a -> Seq a
:: a -> Seq a -> Seq a
:: Seq a -> a -> Seq a
:: Seq a -> Seq a -> Seq a
:: [a] -> Seq a
:: Int -> (Int -> a) -> Seq a
:: Ix i => Array i a -> Seq a
** Repetition
:: Int -> a -> Seq a
:: Applicative f => Int -> f a -> f (Seq a)
:: Int -> Seq a -> Seq a
** Iterative construction
:: Int -> (a -> a) -> a -> Seq a
:: (b -> Maybe (a, b)) -> b -> Seq a
:: (b -> Maybe (b, a)) -> b -> Seq a
* Deconstruction
| Additional functions for deconstructing sequences are available
via the 'Foldable' instance of 'Seq'.
** Queries
:: Seq a -> Bool
:: Seq a -> Int
** Views
:: Seq a -> ViewR a
* Scans
:: (a -> b -> a) -> a -> Seq b -> Seq a
:: (a -> a -> a) -> Seq a -> Seq a
:: (a -> b -> b) -> b -> Seq a -> Seq b
:: (a -> a -> a) -> Seq a -> Seq a
* Sublists
:: Seq a -> Seq (Seq a)
:: Seq a -> Seq (Seq a)
:: Int -> Seq a -> Seq (Seq a)
** Sequential searches
:: (a -> Bool) -> Seq a -> Seq a
:: (a -> Bool) -> Seq a -> Seq a
:: (a -> Bool) -> Seq a -> Seq a
:: (a -> Bool) -> Seq a -> Seq a
:: (a -> Bool) -> Seq a -> Seq a
* Sorting
:: (a -> a -> Ordering) -> Seq a -> Seq a
:: (a -> a -> Ordering) -> Seq a -> Seq a
* Indexing
:: Int -> Seq a -> Maybe a
:: Seq a -> Int -> Maybe a
:: Seq a -> Int -> a
:: (a -> a) -> Int -> Seq a -> Seq a
:: (a -> a) -> Int -> Seq a -> Seq a
:: Int -> a -> Seq a -> Seq a
:: Int -> Seq a -> Seq a
:: Int -> Seq a -> Seq a
:: Int -> a -> Seq a -> Seq a
:: Int -> Seq a -> Seq a
** Indexing with predicates
| These functions perform sequential searches from the left
or right ends of the sequence, returning indices of matching
elements.
:: Eq a => a -> Seq a -> Maybe Int
:: Eq a => a -> Seq a -> [Int]
:: Eq a => a -> Seq a -> Maybe Int
:: Eq a => a -> Seq a -> [Int]
:: (a -> Bool) -> Seq a -> Maybe Int
:: (a -> Bool) -> Seq a -> [Int]
:: (a -> Bool) -> Seq a -> Maybe Int
:: (a -> Bool) -> Seq a -> [Int]
* Folds
| General folds are available via the 'Foldable' instance of 'Seq'.
:: Monoid m => (Int -> a -> m) -> Seq a -> m
:: (b -> Int -> a -> b) -> b -> Seq a -> b
:: (Int -> a -> b -> b) -> b -> Seq a -> b
* Transformations
:: (Int -> a -> b) -> Seq a -> Seq b
:: Applicative f => (Int -> a -> f b) -> Seq a -> f (Seq b)
:: Seq a -> Seq a
:: a -> Seq a -> Seq a
:: Seq a -> Seq b -> Seq (a, b)
:: (a -> b -> c) -> Seq a -> Seq b -> Seq c
:: Seq a -> Seq b -> Seq c -> Seq (a, b, c)
:: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d
:: Seq a -> Seq b -> Seq c -> Seq d -> Seq (a, b, c, d)
:: (a -> b -> c -> d -> e) -> Seq a -> Seq b -> Seq c -> Seq d -> Seq e | # LANGUAGE Haskell98 #
# LANGUAGE CPP #
Copyright : ( c ) 2005
( c ) 2009
( c ) , , , and
Milan Straka 2014
The implementation uses 2 - 3 finger trees annotated with sizes ,
as described in section 4.2 of
* and ,
\"Finger trees : a simple general - purpose data structure\ " ,
/Journal of Functional Programming/ 16:2 ( 2006 ) pp 197 - 217 .
operations on lists in the " Prelude " . The ambiguity may be resolved
/Warning/ : The size of a ' Seq ' must not exceed @maxBound::Int@. Violation
module Data.Sequence (
Seq (Empty, (:<|), (:|>)),
: : = > Int - > m a - > m ( Seq a )
ViewL(..),
: : Seq a - > ViewL a
ViewR(..),
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : ( a - > Bool ) - > Seq a - > ( Seq a , Seq a )
: : a = > Seq a - > Seq a
: : a = > Seq a - > Seq a
: : Int - > Seq a - > ( Seq a , Seq a )
* *
) where
import Data.Sequence.Internal
import Prelude ()
|
6f23de5a29dab450c6d6ea03ade2d008644b94644e7123f2697f2cccea1197a0 | bobatkey/foveran | Text.hs | -- |
Module : Language . Foveran . Lexing . Text
Copyright : 2012
-- License : BSD3
--
-- Maintainer :
-- Stability : experimental
-- Portability : unknown
--
-- Functions for turning `Data.Text.Text` into a stream of lexemes,
-- according to some lexical specification.
module Language.Foveran.Lexing.Text
( lex
, ErrorHandler (..) )
where
import Prelude hiding (lex)
import Data.ByteString (ByteString)
import qualified Data.Text as T
import Data.MonadicStream (Stream (..), StreamStep (..))
import qualified Data.FiniteStateMachine.Deterministic as DFA
import Language.Foveran.Lexing.Spec (CompiledLexSpec (..))
import Text.Lexeme (Lexeme (..))
import Text.Position (Span (Span), initPos, updatePos, Position)
{------------------------------------------------------------------------------}
data PositionWith a = (:-) { positionOf :: Position
, dataOf :: a
}
uncons :: PositionWith T.Text -> Maybe (PositionWith Char, PositionWith T.Text)
uncons (position :- text) =
case T.uncons text of
Nothing -> Nothing
Just (c,rest) -> Just ( position :- c
, (position `updatePos` c) :- rest)
{------------------------------------------------------------------------------}
data CurrentLexeme tok
= CurrentLexeme { curLexemeText :: !(PositionWith T.Text)
, curLexemeLen :: !Int
, curLexemeMatch :: !(CurrentMatch tok)
}
data CurrentMatch tok
= NoMatch
| Match !Int !tok !Position !(PositionWith T.Text)
advance :: CurrentLexeme tok -> CurrentLexeme tok
advance lexeme = lexeme { curLexemeLen = curLexemeLen lexeme + 1 }
(+.) :: CurrentLexeme tok -> (PositionWith tok, PositionWith T.Text) -> CurrentLexeme tok
lexeme +. (pos :- tok, rest) =
lexeme { curLexemeMatch = Match (curLexemeLen lexeme) tok pos rest }
initLexeme :: PositionWith T.Text -> CurrentLexeme tok
initLexeme text = CurrentLexeme text 0 NoMatch
{------------------------------------------------------------------------------}
data ErrorHandler m tok = OnError { onError :: Maybe (Char, Position) -> m tok }
{------------------------------------------------------------------------------}
data State tok
= BeforeLexeme ! ( PositionWith T.Text )
| InLexeme ! Int ! ( CurrentLexeme tok ) ! ( PositionWith T.Text )
step : : State tok - > m ( Maybe ( State tok , ) )
step ( BeforeLexeme text ) = undefined
step ( InLexeme q lexeme text ) = undefined
data State tok
= BeforeLexeme !(PositionWith T.Text)
| InLexeme !Int !(CurrentLexeme tok) !(PositionWith T.Text)
step :: State tok -> m (Maybe (State tok, Lexeme tok))
step (BeforeLexeme text) = undefined
step (InLexeme q lexeme text) = undefined
-}
{------------------------------------------------------------------------------}
lex :: (Ord tok, Monad m) =>
CompiledLexSpec tok
-> ErrorHandler m tok
-> ByteString
-> T.Text
-> Stream m (Lexeme tok)
lex lexSpec errorHandler sourceName text =
go (initPos sourceName :- text)
where
dfa = lexSpecDFA lexSpec
go text =
Stream $ beforeLexeme text
beforeLexeme text =
case uncons text of
Nothing -> return StreamEnd
Just step -> onChar (DFA.initialState dfa) step (initLexeme text)
inLexeme dfaState lexeme text =
case uncons text of
Nothing -> emit lexeme Nothing
Just step -> onChar dfaState step lexeme
onChar q input@(position :- c, rest) lexeme =
case DFA.transition dfa q c of
DFA.Accept t q' -> inLexeme q' (advance lexeme +. (position :- t, rest)) rest
DFA.Error -> emit lexeme (Just input)
DFA.Change q' -> inLexeme q' (advance lexeme) rest
emit lexeme input =
case curLexemeMatch lexeme of
NoMatch ->
do let input' = case input of Nothing -> Nothing; Just (p :- c, _) -> Just (c,p)
tok <- errorHandler `onError` input'
return (StreamElem (Lexeme tok span text) $ go rest)
where
endPos = case input of
Nothing -> positionOf $ curLexemeText lexeme -- FIXME: this is wrong!
Just (p :- _, _) -> p
rest = case input of
FIXME
Just (_, rest) -> rest
length = curLexemeLen lexeme + case input of Nothing -> 0; Just _ -> 1
span = Span (positionOf $ curLexemeText lexeme) endPos
text = T.take length (dataOf $ curLexemeText lexeme)
Match length tok endPos rest ->
return (StreamElem (Lexeme tok span text) $ go rest)
where
span = Span (positionOf $ curLexemeText lexeme) endPos
text = T.take length (dataOf $ curLexemeText lexeme)
| null | https://raw.githubusercontent.com/bobatkey/foveran/e57463e3f6923becdf1249cd2fd0ccfcd566f7c5/src/Language/Foveran/Lexing/Text.hs | haskell | |
License : BSD3
Maintainer :
Stability : experimental
Portability : unknown
Functions for turning `Data.Text.Text` into a stream of lexemes,
according to some lexical specification.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
FIXME: this is wrong! | Module : Language . Foveran . Lexing . Text
Copyright : 2012
module Language.Foveran.Lexing.Text
( lex
, ErrorHandler (..) )
where
import Prelude hiding (lex)
import Data.ByteString (ByteString)
import qualified Data.Text as T
import Data.MonadicStream (Stream (..), StreamStep (..))
import qualified Data.FiniteStateMachine.Deterministic as DFA
import Language.Foveran.Lexing.Spec (CompiledLexSpec (..))
import Text.Lexeme (Lexeme (..))
import Text.Position (Span (Span), initPos, updatePos, Position)
data PositionWith a = (:-) { positionOf :: Position
, dataOf :: a
}
uncons :: PositionWith T.Text -> Maybe (PositionWith Char, PositionWith T.Text)
uncons (position :- text) =
case T.uncons text of
Nothing -> Nothing
Just (c,rest) -> Just ( position :- c
, (position `updatePos` c) :- rest)
data CurrentLexeme tok
= CurrentLexeme { curLexemeText :: !(PositionWith T.Text)
, curLexemeLen :: !Int
, curLexemeMatch :: !(CurrentMatch tok)
}
data CurrentMatch tok
= NoMatch
| Match !Int !tok !Position !(PositionWith T.Text)
advance :: CurrentLexeme tok -> CurrentLexeme tok
advance lexeme = lexeme { curLexemeLen = curLexemeLen lexeme + 1 }
(+.) :: CurrentLexeme tok -> (PositionWith tok, PositionWith T.Text) -> CurrentLexeme tok
lexeme +. (pos :- tok, rest) =
lexeme { curLexemeMatch = Match (curLexemeLen lexeme) tok pos rest }
initLexeme :: PositionWith T.Text -> CurrentLexeme tok
initLexeme text = CurrentLexeme text 0 NoMatch
data ErrorHandler m tok = OnError { onError :: Maybe (Char, Position) -> m tok }
data State tok
= BeforeLexeme ! ( PositionWith T.Text )
| InLexeme ! Int ! ( CurrentLexeme tok ) ! ( PositionWith T.Text )
step : : State tok - > m ( Maybe ( State tok , ) )
step ( BeforeLexeme text ) = undefined
step ( InLexeme q lexeme text ) = undefined
data State tok
= BeforeLexeme !(PositionWith T.Text)
| InLexeme !Int !(CurrentLexeme tok) !(PositionWith T.Text)
step :: State tok -> m (Maybe (State tok, Lexeme tok))
step (BeforeLexeme text) = undefined
step (InLexeme q lexeme text) = undefined
-}
lex :: (Ord tok, Monad m) =>
CompiledLexSpec tok
-> ErrorHandler m tok
-> ByteString
-> T.Text
-> Stream m (Lexeme tok)
lex lexSpec errorHandler sourceName text =
go (initPos sourceName :- text)
where
dfa = lexSpecDFA lexSpec
go text =
Stream $ beforeLexeme text
beforeLexeme text =
case uncons text of
Nothing -> return StreamEnd
Just step -> onChar (DFA.initialState dfa) step (initLexeme text)
inLexeme dfaState lexeme text =
case uncons text of
Nothing -> emit lexeme Nothing
Just step -> onChar dfaState step lexeme
onChar q input@(position :- c, rest) lexeme =
case DFA.transition dfa q c of
DFA.Accept t q' -> inLexeme q' (advance lexeme +. (position :- t, rest)) rest
DFA.Error -> emit lexeme (Just input)
DFA.Change q' -> inLexeme q' (advance lexeme) rest
emit lexeme input =
case curLexemeMatch lexeme of
NoMatch ->
do let input' = case input of Nothing -> Nothing; Just (p :- c, _) -> Just (c,p)
tok <- errorHandler `onError` input'
return (StreamElem (Lexeme tok span text) $ go rest)
where
endPos = case input of
Just (p :- _, _) -> p
rest = case input of
FIXME
Just (_, rest) -> rest
length = curLexemeLen lexeme + case input of Nothing -> 0; Just _ -> 1
span = Span (positionOf $ curLexemeText lexeme) endPos
text = T.take length (dataOf $ curLexemeText lexeme)
Match length tok endPos rest ->
return (StreamElem (Lexeme tok span text) $ go rest)
where
span = Span (positionOf $ curLexemeText lexeme) endPos
text = T.take length (dataOf $ curLexemeText lexeme)
|
e02251c0a0185c1841c98ac78db9062b7142206e8ded49ab6f338f5ff57aac1c | geneweb/geneweb | translate.mli | $ I d : translate.mli , v 5.7 2007 - 09 - 12 09:58:44 ddr Exp $
Copyright ( c ) 1998 - 2007 INRIA
val inline : string -> char -> (char -> string) -> string -> string * bool
[ Translate.inline ] return the translation
and a boolean telling True if it is actually the English version
and a boolean telling True if it is actually the English version *)
val language_name : ?sep:char -> string -> string -> string
(* [Translate.language_name lang lang_def] *)
val eval : string -> string
[ eval str ] return a transformation of [ str ] . The input string may
contain actions between " @ ( " and " ) " whose contents are evaluated like
this :
- @(x ) set the predicate " x "
- @(xyz ... ) set the predicates x , y , z ...
- @(expr ) where expr is of the form " x?e1 : e2 " : if predicate " x " then
evaluates e1 else evaluates e2 where e1 and e2 are either another
expression " y?e3 : e4 " or a string ( whose 2nd char is not " ? " ) .
- @(n-- ) where n is a number : move the n preceding words to the end
of the string .
- @(@string ) evaluates " @string " recursively ; in particular , predicates
inside the string remain local .
Warning : this function makes obsolete many functions in " Util " taking
care of declinations using the system with :x : .
contain actions between "@(" and ")" whose contents are evaluated like
this:
- @(x) set the predicate "x"
- @(xyz...) set the predicates x, y, z...
- @(expr) where expr is of the form "x?e1:e2": if predicate "x" then
evaluates e1 else evaluates e2 where e1 and e2 are either another
expression "y?e3:e4" or a string (whose 2nd char is not "?").
- @(n--) where n is a number: move the n preceding words to the end
of the string.
- @(@string) evaluates "@string" recursively; in particular, predicates
inside the string remain local.
Warning: this function makes obsolete many functions in "Util" taking
care of declinations using the system with :x:.
*)
| null | https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/translate.mli | ocaml | [Translate.language_name lang lang_def] | $ I d : translate.mli , v 5.7 2007 - 09 - 12 09:58:44 ddr Exp $
Copyright ( c ) 1998 - 2007 INRIA
val inline : string -> char -> (char -> string) -> string -> string * bool
[ Translate.inline ] return the translation
and a boolean telling True if it is actually the English version
and a boolean telling True if it is actually the English version *)
val language_name : ?sep:char -> string -> string -> string
val eval : string -> string
[ eval str ] return a transformation of [ str ] . The input string may
contain actions between " @ ( " and " ) " whose contents are evaluated like
this :
- @(x ) set the predicate " x "
- @(xyz ... ) set the predicates x , y , z ...
- @(expr ) where expr is of the form " x?e1 : e2 " : if predicate " x " then
evaluates e1 else evaluates e2 where e1 and e2 are either another
expression " y?e3 : e4 " or a string ( whose 2nd char is not " ? " ) .
- @(n-- ) where n is a number : move the n preceding words to the end
of the string .
- @(@string ) evaluates " @string " recursively ; in particular , predicates
inside the string remain local .
Warning : this function makes obsolete many functions in " Util " taking
care of declinations using the system with :x : .
contain actions between "@(" and ")" whose contents are evaluated like
this:
- @(x) set the predicate "x"
- @(xyz...) set the predicates x, y, z...
- @(expr) where expr is of the form "x?e1:e2": if predicate "x" then
evaluates e1 else evaluates e2 where e1 and e2 are either another
expression "y?e3:e4" or a string (whose 2nd char is not "?").
- @(n--) where n is a number: move the n preceding words to the end
of the string.
- @(@string) evaluates "@string" recursively; in particular, predicates
inside the string remain local.
Warning: this function makes obsolete many functions in "Util" taking
care of declinations using the system with :x:.
*)
|
ec4954891cd1ea59e21d1e8e2a0ea1f3be340059e430c29dcf64f1e6becb2a73 | minoki/haskell-floating-point | FastFFI.hs | |
Module : Numeric . Rounded . Hardware . Backend . FastFFI
The types in this module implements interval addition and subtraction in assembly .
Currently , the only platform supported is x86_64 .
One of the following technology will be used to control rounding mode :
* SSE2 MXCSR
* AVX512 EVEX encoding
You should not need to import this module directly .
This module may not be available depending on the platform or package flags .
Module: Numeric.Rounded.Hardware.Backend.FastFFI
The types in this module implements interval addition and subtraction in assembly.
Currently, the only platform supported is x86_64.
One of the following technology will be used to control rounding mode:
* SSE2 MXCSR
* AVX512 EVEX encoding
You should not need to import this module directly.
This module may not be available depending on the platform or package flags.
-}
# LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE GHCForeignImportPrim #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MagicHash #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UnboxedTuples #
{-# LANGUAGE UnliftedFFITypes #-}
# OPTIONS_GHC -fobject - code #
module Numeric.Rounded.Hardware.Backend.FastFFI
( CDouble(..)
, fastIntervalAdd
, fastIntervalSub
, fastIntervalRecip
, VUM.MVector(MV_CFloat, MV_CDouble)
, VU.Vector(V_CFloat, V_CDouble)
) where
import Control.DeepSeq (NFData (..))
import Data.Coerce
import Data.Proxy
import Data.Tagged
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified FFIWrapper.Double as D
import Foreign.C.String (CString, peekCString)
import Foreign.Storable (Storable)
import GHC.Exts
import GHC.Generics (Generic)
import GHC.Int (Int64 (I64#))
import GHC.Word (Word64 (W64#))
import qualified Numeric.Rounded.Hardware.Backend.C as C
import Numeric.Rounded.Hardware.Internal.Class
import System.IO.Unsafe (unsafePerformIO)
import Unsafe.Coerce
#include "MachDeps.h"
--
-- Double
--
newtype CDouble = CDouble Double
deriving (Eq,Ord,Show,Generic,Num,Storable)
instance NFData CDouble
instance RoundedRing CDouble where
roundedAdd = coerce D.roundedAdd
roundedSub = coerce D.roundedSub
roundedMul = coerce D.roundedMul
roundedFusedMultiplyAdd = coerce D.roundedFMA
intervalAdd x x' y y' = coerce fastIntervalAdd x x' y y'
intervalSub x x' y y' = coerce fastIntervalSub x x' y y'
intervalMul x x' y y' = (coerce D.intervalMul_down x x' y y', coerce D.intervalMul_up x x' y y')
intervalMulAdd x x' y y' z z' = (coerce D.intervalMulAdd_down x x' y y' z, coerce D.intervalMulAdd_up x x' y y' z')
roundedFromInteger = coerce (roundedFromInteger :: RoundingMode -> Integer -> C.CDouble)
intervalFromInteger = coerce (intervalFromInteger :: Integer -> (Rounded 'TowardNegInf C.CDouble, Rounded 'TowardInf C.CDouble))
backendNameT = Tagged $ let base = backendName (Proxy :: Proxy C.CDouble)
intervals = intervalBackendName
in if base == intervals
then base ++ "+FastFFI"
else base ++ "+FastFFI(" ++ intervals ++ ")"
# INLINE roundedAdd #
# INLINE roundedSub #
# INLINE roundedMul #
# INLINE roundedFusedMultiplyAdd #
# INLINE intervalAdd #
# INLINE intervalSub #
# INLINE intervalMul #
# INLINE roundedFromInteger #
# INLINE intervalFromInteger #
instance RoundedFractional CDouble where
roundedDiv = coerce D.roundedDiv
intervalDiv x x' y y' = (coerce D.intervalDiv_down x x' y y', coerce D.intervalDiv_up x x' y y')
intervalDivAdd x x' y y' z z' = (coerce D.intervalDivAdd_down x x' y y' z, coerce D.intervalDivAdd_up x x' y y' z')
intervalRecip x x' = coerce fastIntervalRecip x x'
roundedFromRational = coerce (roundedFromRational :: RoundingMode -> Rational -> C.CDouble)
roundedFromRealFloat r x = coerce (roundedFromRealFloat r x :: C.CDouble)
intervalFromRational = coerce (intervalFromRational :: Rational -> (Rounded 'TowardNegInf C.CDouble, Rounded 'TowardInf C.CDouble))
# INLINE roundedDiv #
# INLINE intervalDiv #
# INLINE intervalRecip #
# INLINE roundedFromRational #
# INLINE roundedFromRealFloat #
# INLINE intervalFromRational #
instance RoundedSqrt CDouble where
roundedSqrt = coerce D.roundedSqrt
{-# INLINE roundedSqrt #-}
instance RoundedRing_Vector VS.Vector CDouble where
roundedSum mode vec = coerce (roundedSum mode (unsafeCoerce vec :: VS.Vector C.CDouble))
zipWith_roundedAdd mode vec vec' = unsafeCoerce (zipWith_roundedAdd mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
zipWith_roundedSub mode vec vec' = unsafeCoerce (zipWith_roundedSub mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
zipWith_roundedMul mode vec vec' = unsafeCoerce (zipWith_roundedMul mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
zipWith3_roundedFusedMultiplyAdd mode vec1 vec2 vec3 = unsafeCoerce (zipWith3_roundedFusedMultiplyAdd mode (unsafeCoerce vec1) (unsafeCoerce vec2) (unsafeCoerce vec3) :: VS.Vector C.CDouble)
{-# INLINE roundedSum #-}
# INLINE zipWith_roundedAdd #
# INLINE zipWith_roundedSub #
# INLINE zipWith_roundedMul #
# INLINE zipWith3_roundedFusedMultiplyAdd #
instance RoundedFractional_Vector VS.Vector CDouble where
zipWith_roundedDiv mode vec vec' = unsafeCoerce (zipWith_roundedDiv mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
# INLINE zipWith_roundedDiv #
instance RoundedSqrt_Vector VS.Vector CDouble where
map_roundedSqrt mode vec = unsafeCoerce (map_roundedSqrt mode (unsafeCoerce vec) :: VS.Vector C.CDouble)
# INLINE map_roundedSqrt #
deriving via C.CDouble instance RoundedRing_Vector VU.Vector CDouble
deriving via C.CDouble instance RoundedFractional_Vector VU.Vector CDouble
deriving via C.CDouble instance RoundedSqrt_Vector VU.Vector CDouble
--
FFI
--
foreign import prim "rounded_hw_interval_add"
lower 1 , % xmm1
upper 1 , % xmm2
-> Double# -- lower 2, %xmm3
upper 2 , % xmm4
-> (# Double# -- lower, %xmm1
, Double# -- upper, %xmm2
#)
foreign import prim "rounded_hw_interval_sub"
lower 1 , % xmm1
upper 1 , % xmm2
-> Double# -- lower 2, %xmm3
upper 2 , % xmm4
-> (# Double# -- lower, %xmm1
, Double# -- upper, %xmm2
#)
foreign import prim "rounded_hw_interval_recip"
lower 1 , % xmm1
upper 1 , % xmm2
-> (# Double# -- lower, %xmm1
, Double# -- upper, %xmm2
#)
foreign import prim "rounded_hw_interval_sqrt"
lower 1 , % xmm1
upper 1 , % xmm2
-> (# Double# -- lower, %xmm1
, Double# -- upper, %xmm2
#)
#if WORD_SIZE_IN_BITS >= 64 && !MIN_VERSION_base(4,17,0)
type INT64# = Int#
type WORD64# = Word#
#else
type INT64# = Int64#
type WORD64# = Word64#
#endif
foreign import prim "rounded_hw_interval_from_int64"
fastIntervalFromInt64# :: INT64# -- value
-> (# Double# -- lower, %xmm1
, Double# -- upper, %xmm2
#)
{-
foreign import prim "rounded_hw_interval_from_word64"
fastIntervalFromWord64# :: WORD64# -- value
-> (# Double# -- lower, %xmm1
, Double# -- upper, %xmm2
#)
-}
fastIntervalAdd :: Double -> Double -> Double -> Double -> (Double, Double)
fastIntervalAdd (D# l1) (D# h1) (D# l2) (D# h2) = case fastIntervalAdd# l1 h1 l2 h2 of
(# l3, h3 #) -> (D# l3, D# h3)
# INLINE fastIntervalAdd #
fastIntervalSub :: Double -> Double -> Double -> Double -> (Double, Double)
fastIntervalSub (D# l1) (D# h1) (D# l2) (D# h2) = case fastIntervalSub# l1 h1 l2 h2 of
(# l3, h3 #) -> (D# l3, D# h3)
# INLINE fastIntervalSub #
fastIntervalRecip :: Double -> Double -> (Double, Double)
fastIntervalRecip (D# l1) (D# h1) = case fastIntervalRecip# l1 h1 of
(# l2, h2 #) -> (D# l2, D# h2)
# INLINE fastIntervalRecip #
fastIntervalSqrt :: Double -> Double -> (Double, Double)
fastIntervalSqrt (D# l1) (D# h1) = case fastIntervalSqrt# l1 h1 of
(# l2, h2 #) -> (D# l2, D# h2)
# INLINE fastIntervalSqrt #
fastIntervalFromInt64 :: Int64 -> (Double, Double)
fastIntervalFromInt64 (I64# x) = case fastIntervalFromInt64# x of
(# l, h #) -> (D# l, D# h)
# INLINE fastIntervalFromInt64 #
fastIntervalFromWord64 : : Word64 - > ( Double , Double )
fastIntervalFromWord64 ( W64 # x ) = case fastIntervalFromWord64 # x of
( # l , h # ) - > ( D # l , D # h )
{ - # INLINE fastIntervalFromWord64 #
fastIntervalFromWord64 :: Word64 -> (Double, Double)
fastIntervalFromWord64 (W64# x) = case fastIntervalFromWord64# x of
(# l, h #) -> (D# l, D# h)
{-# INLINE fastIntervalFromWord64 #-}
-}
--
-- Backend name
--
foreign import ccall "&rounded_hw_interval_backend_name"
c_interval_backend_name :: CString
intervalBackendName :: String
intervalBackendName = unsafePerformIO (peekCString c_interval_backend_name)
--
instance for Data . Vector . . Unbox
--
newtype instance VUM.MVector s CDouble = MV_CDouble (VUM.MVector s Double)
newtype instance VU.Vector CDouble = V_CDouble (VU.Vector Double)
instance VGM.MVector VUM.MVector CDouble where
basicLength (MV_CDouble mv) = VGM.basicLength mv
basicUnsafeSlice i l (MV_CDouble mv) = MV_CDouble (VGM.basicUnsafeSlice i l mv)
basicOverlaps (MV_CDouble mv) (MV_CDouble mv') = VGM.basicOverlaps mv mv'
basicUnsafeNew l = MV_CDouble <$> VGM.basicUnsafeNew l
basicInitialize (MV_CDouble mv) = VGM.basicInitialize mv
basicUnsafeReplicate i x = MV_CDouble <$> VGM.basicUnsafeReplicate i (coerce x)
basicUnsafeRead (MV_CDouble mv) i = coerce <$> VGM.basicUnsafeRead mv i
basicUnsafeWrite (MV_CDouble mv) i x = VGM.basicUnsafeWrite mv i (coerce x)
basicClear (MV_CDouble mv) = VGM.basicClear mv
basicSet (MV_CDouble mv) x = VGM.basicSet mv (coerce x)
basicUnsafeCopy (MV_CDouble mv) (MV_CDouble mv') = VGM.basicUnsafeCopy mv mv'
basicUnsafeMove (MV_CDouble mv) (MV_CDouble mv') = VGM.basicUnsafeMove mv mv'
basicUnsafeGrow (MV_CDouble mv) n = MV_CDouble <$> VGM.basicUnsafeGrow mv n
instance VG.Vector VU.Vector CDouble where
basicUnsafeFreeze (MV_CDouble mv) = V_CDouble <$> VG.basicUnsafeFreeze mv
basicUnsafeThaw (V_CDouble v) = MV_CDouble <$> VG.basicUnsafeThaw v
basicLength (V_CDouble v) = VG.basicLength v
basicUnsafeSlice i l (V_CDouble v) = V_CDouble (VG.basicUnsafeSlice i l v)
basicUnsafeIndexM (V_CDouble v) i = coerce <$> VG.basicUnsafeIndexM v i
basicUnsafeCopy (MV_CDouble mv) (V_CDouble v) = VG.basicUnsafeCopy mv v
elemseq (V_CDouble v) x y = VG.elemseq v (coerce x) y
instance VU.Unbox CDouble
| null | https://raw.githubusercontent.com/minoki/haskell-floating-point/c141bc8435c556e94d51254479a8213698679261/rounded-hw/src/Numeric/Rounded/Hardware/Backend/FastFFI.hs | haskell | # LANGUAGE UnliftedFFITypes #
Double
# INLINE roundedSqrt #
# INLINE roundedSum #
lower 2, %xmm3
lower, %xmm1
upper, %xmm2
lower 2, %xmm3
lower, %xmm1
upper, %xmm2
lower, %xmm1
upper, %xmm2
lower, %xmm1
upper, %xmm2
value
lower, %xmm1
upper, %xmm2
foreign import prim "rounded_hw_interval_from_word64"
fastIntervalFromWord64# :: WORD64# -- value
-> (# Double# -- lower, %xmm1
, Double# -- upper, %xmm2
#)
# INLINE fastIntervalFromWord64 #
Backend name
| |
Module : Numeric . Rounded . Hardware . Backend . FastFFI
The types in this module implements interval addition and subtraction in assembly .
Currently , the only platform supported is x86_64 .
One of the following technology will be used to control rounding mode :
* SSE2 MXCSR
* AVX512 EVEX encoding
You should not need to import this module directly .
This module may not be available depending on the platform or package flags .
Module: Numeric.Rounded.Hardware.Backend.FastFFI
The types in this module implements interval addition and subtraction in assembly.
Currently, the only platform supported is x86_64.
One of the following technology will be used to control rounding mode:
* SSE2 MXCSR
* AVX512 EVEX encoding
You should not need to import this module directly.
This module may not be available depending on the platform or package flags.
-}
# LANGUAGE CPP #
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE GHCForeignImportPrim #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MagicHash #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE UnboxedTuples #
# OPTIONS_GHC -fobject - code #
module Numeric.Rounded.Hardware.Backend.FastFFI
( CDouble(..)
, fastIntervalAdd
, fastIntervalSub
, fastIntervalRecip
, VUM.MVector(MV_CFloat, MV_CDouble)
, VU.Vector(V_CFloat, V_CDouble)
) where
import Control.DeepSeq (NFData (..))
import Data.Coerce
import Data.Proxy
import Data.Tagged
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified FFIWrapper.Double as D
import Foreign.C.String (CString, peekCString)
import Foreign.Storable (Storable)
import GHC.Exts
import GHC.Generics (Generic)
import GHC.Int (Int64 (I64#))
import GHC.Word (Word64 (W64#))
import qualified Numeric.Rounded.Hardware.Backend.C as C
import Numeric.Rounded.Hardware.Internal.Class
import System.IO.Unsafe (unsafePerformIO)
import Unsafe.Coerce
#include "MachDeps.h"
newtype CDouble = CDouble Double
deriving (Eq,Ord,Show,Generic,Num,Storable)
instance NFData CDouble
instance RoundedRing CDouble where
roundedAdd = coerce D.roundedAdd
roundedSub = coerce D.roundedSub
roundedMul = coerce D.roundedMul
roundedFusedMultiplyAdd = coerce D.roundedFMA
intervalAdd x x' y y' = coerce fastIntervalAdd x x' y y'
intervalSub x x' y y' = coerce fastIntervalSub x x' y y'
intervalMul x x' y y' = (coerce D.intervalMul_down x x' y y', coerce D.intervalMul_up x x' y y')
intervalMulAdd x x' y y' z z' = (coerce D.intervalMulAdd_down x x' y y' z, coerce D.intervalMulAdd_up x x' y y' z')
roundedFromInteger = coerce (roundedFromInteger :: RoundingMode -> Integer -> C.CDouble)
intervalFromInteger = coerce (intervalFromInteger :: Integer -> (Rounded 'TowardNegInf C.CDouble, Rounded 'TowardInf C.CDouble))
backendNameT = Tagged $ let base = backendName (Proxy :: Proxy C.CDouble)
intervals = intervalBackendName
in if base == intervals
then base ++ "+FastFFI"
else base ++ "+FastFFI(" ++ intervals ++ ")"
# INLINE roundedAdd #
# INLINE roundedSub #
# INLINE roundedMul #
# INLINE roundedFusedMultiplyAdd #
# INLINE intervalAdd #
# INLINE intervalSub #
# INLINE intervalMul #
# INLINE roundedFromInteger #
# INLINE intervalFromInteger #
instance RoundedFractional CDouble where
roundedDiv = coerce D.roundedDiv
intervalDiv x x' y y' = (coerce D.intervalDiv_down x x' y y', coerce D.intervalDiv_up x x' y y')
intervalDivAdd x x' y y' z z' = (coerce D.intervalDivAdd_down x x' y y' z, coerce D.intervalDivAdd_up x x' y y' z')
intervalRecip x x' = coerce fastIntervalRecip x x'
roundedFromRational = coerce (roundedFromRational :: RoundingMode -> Rational -> C.CDouble)
roundedFromRealFloat r x = coerce (roundedFromRealFloat r x :: C.CDouble)
intervalFromRational = coerce (intervalFromRational :: Rational -> (Rounded 'TowardNegInf C.CDouble, Rounded 'TowardInf C.CDouble))
# INLINE roundedDiv #
# INLINE intervalDiv #
# INLINE intervalRecip #
# INLINE roundedFromRational #
# INLINE roundedFromRealFloat #
# INLINE intervalFromRational #
instance RoundedSqrt CDouble where
roundedSqrt = coerce D.roundedSqrt
instance RoundedRing_Vector VS.Vector CDouble where
roundedSum mode vec = coerce (roundedSum mode (unsafeCoerce vec :: VS.Vector C.CDouble))
zipWith_roundedAdd mode vec vec' = unsafeCoerce (zipWith_roundedAdd mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
zipWith_roundedSub mode vec vec' = unsafeCoerce (zipWith_roundedSub mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
zipWith_roundedMul mode vec vec' = unsafeCoerce (zipWith_roundedMul mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
zipWith3_roundedFusedMultiplyAdd mode vec1 vec2 vec3 = unsafeCoerce (zipWith3_roundedFusedMultiplyAdd mode (unsafeCoerce vec1) (unsafeCoerce vec2) (unsafeCoerce vec3) :: VS.Vector C.CDouble)
# INLINE zipWith_roundedAdd #
# INLINE zipWith_roundedSub #
# INLINE zipWith_roundedMul #
# INLINE zipWith3_roundedFusedMultiplyAdd #
instance RoundedFractional_Vector VS.Vector CDouble where
zipWith_roundedDiv mode vec vec' = unsafeCoerce (zipWith_roundedDiv mode (unsafeCoerce vec) (unsafeCoerce vec') :: VS.Vector C.CDouble)
# INLINE zipWith_roundedDiv #
instance RoundedSqrt_Vector VS.Vector CDouble where
map_roundedSqrt mode vec = unsafeCoerce (map_roundedSqrt mode (unsafeCoerce vec) :: VS.Vector C.CDouble)
# INLINE map_roundedSqrt #
deriving via C.CDouble instance RoundedRing_Vector VU.Vector CDouble
deriving via C.CDouble instance RoundedFractional_Vector VU.Vector CDouble
deriving via C.CDouble instance RoundedSqrt_Vector VU.Vector CDouble
FFI
foreign import prim "rounded_hw_interval_add"
lower 1 , % xmm1
upper 1 , % xmm2
upper 2 , % xmm4
#)
foreign import prim "rounded_hw_interval_sub"
lower 1 , % xmm1
upper 1 , % xmm2
upper 2 , % xmm4
#)
foreign import prim "rounded_hw_interval_recip"
lower 1 , % xmm1
upper 1 , % xmm2
#)
foreign import prim "rounded_hw_interval_sqrt"
lower 1 , % xmm1
upper 1 , % xmm2
#)
#if WORD_SIZE_IN_BITS >= 64 && !MIN_VERSION_base(4,17,0)
type INT64# = Int#
type WORD64# = Word#
#else
type INT64# = Int64#
type WORD64# = Word64#
#endif
foreign import prim "rounded_hw_interval_from_int64"
#)
fastIntervalAdd :: Double -> Double -> Double -> Double -> (Double, Double)
fastIntervalAdd (D# l1) (D# h1) (D# l2) (D# h2) = case fastIntervalAdd# l1 h1 l2 h2 of
(# l3, h3 #) -> (D# l3, D# h3)
# INLINE fastIntervalAdd #
fastIntervalSub :: Double -> Double -> Double -> Double -> (Double, Double)
fastIntervalSub (D# l1) (D# h1) (D# l2) (D# h2) = case fastIntervalSub# l1 h1 l2 h2 of
(# l3, h3 #) -> (D# l3, D# h3)
# INLINE fastIntervalSub #
fastIntervalRecip :: Double -> Double -> (Double, Double)
fastIntervalRecip (D# l1) (D# h1) = case fastIntervalRecip# l1 h1 of
(# l2, h2 #) -> (D# l2, D# h2)
# INLINE fastIntervalRecip #
fastIntervalSqrt :: Double -> Double -> (Double, Double)
fastIntervalSqrt (D# l1) (D# h1) = case fastIntervalSqrt# l1 h1 of
(# l2, h2 #) -> (D# l2, D# h2)
# INLINE fastIntervalSqrt #
fastIntervalFromInt64 :: Int64 -> (Double, Double)
fastIntervalFromInt64 (I64# x) = case fastIntervalFromInt64# x of
(# l, h #) -> (D# l, D# h)
# INLINE fastIntervalFromInt64 #
fastIntervalFromWord64 : : Word64 - > ( Double , Double )
fastIntervalFromWord64 ( W64 # x ) = case fastIntervalFromWord64 # x of
( # l , h # ) - > ( D # l , D # h )
{ - # INLINE fastIntervalFromWord64 #
fastIntervalFromWord64 :: Word64 -> (Double, Double)
fastIntervalFromWord64 (W64# x) = case fastIntervalFromWord64# x of
(# l, h #) -> (D# l, D# h)
-}
foreign import ccall "&rounded_hw_interval_backend_name"
c_interval_backend_name :: CString
intervalBackendName :: String
intervalBackendName = unsafePerformIO (peekCString c_interval_backend_name)
instance for Data . Vector . . Unbox
newtype instance VUM.MVector s CDouble = MV_CDouble (VUM.MVector s Double)
newtype instance VU.Vector CDouble = V_CDouble (VU.Vector Double)
instance VGM.MVector VUM.MVector CDouble where
basicLength (MV_CDouble mv) = VGM.basicLength mv
basicUnsafeSlice i l (MV_CDouble mv) = MV_CDouble (VGM.basicUnsafeSlice i l mv)
basicOverlaps (MV_CDouble mv) (MV_CDouble mv') = VGM.basicOverlaps mv mv'
basicUnsafeNew l = MV_CDouble <$> VGM.basicUnsafeNew l
basicInitialize (MV_CDouble mv) = VGM.basicInitialize mv
basicUnsafeReplicate i x = MV_CDouble <$> VGM.basicUnsafeReplicate i (coerce x)
basicUnsafeRead (MV_CDouble mv) i = coerce <$> VGM.basicUnsafeRead mv i
basicUnsafeWrite (MV_CDouble mv) i x = VGM.basicUnsafeWrite mv i (coerce x)
basicClear (MV_CDouble mv) = VGM.basicClear mv
basicSet (MV_CDouble mv) x = VGM.basicSet mv (coerce x)
basicUnsafeCopy (MV_CDouble mv) (MV_CDouble mv') = VGM.basicUnsafeCopy mv mv'
basicUnsafeMove (MV_CDouble mv) (MV_CDouble mv') = VGM.basicUnsafeMove mv mv'
basicUnsafeGrow (MV_CDouble mv) n = MV_CDouble <$> VGM.basicUnsafeGrow mv n
instance VG.Vector VU.Vector CDouble where
basicUnsafeFreeze (MV_CDouble mv) = V_CDouble <$> VG.basicUnsafeFreeze mv
basicUnsafeThaw (V_CDouble v) = MV_CDouble <$> VG.basicUnsafeThaw v
basicLength (V_CDouble v) = VG.basicLength v
basicUnsafeSlice i l (V_CDouble v) = V_CDouble (VG.basicUnsafeSlice i l v)
basicUnsafeIndexM (V_CDouble v) i = coerce <$> VG.basicUnsafeIndexM v i
basicUnsafeCopy (MV_CDouble mv) (V_CDouble v) = VG.basicUnsafeCopy mv v
elemseq (V_CDouble v) x y = VG.elemseq v (coerce x) y
instance VU.Unbox CDouble
|
66e67d0d755c8d04195fc81fd3bcbcde75545ccbadaf180aa9d8a5c8e1571ed1 | bytekid/mkbtt | processIsomorphism.ml | Copyright 2010
* GNU Lesser General Public License
*
* This file is part of MKBtt .
*
* 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 .
*
* 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 MKBtt . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of MKBtt.
*
* MKBtt 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.
*
* MKBtt 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 MKBtt. If not, see </>.
*)
* Switch isomorphism checks
@author
@since 2009/08/11
@author Sarah Winkler
@since 2009/08/11
*)
(*** OPENS ***************************************************************)
open Util;;
(*** SUBMODULES **********************************************************)
module Rewriting = Processors.Rewritingx;;
module Trs = U.Trs;;
module C = Completion;;
module St = Statistics;;
module NS = NodeState;;
module CP = CompletionProcessx;;
module N = IndexedNode;;
module R = TrsRenaming;;
module P = TermPermutation;;
module W = World;;
module Monad = W.Monad;;
(*** OPENS ***************************************************************)
open Monad;;
open World;;
(*** FUNCTIONS ***********************************************************)
let symmetric_for_renaming rule n trs p nodeset =
(lift Option.the <.> N.pattern_by_id) n >>= fun (i,j) ->
N.to_stringm n > > = fun s - >
if i <> j then (
" Not symmetric % i , % i : % s\n% ! " i j s ;
return false)
else (
" Symmetric % i , % i : % s\n% ! " i j s ;
NodeSet.project_e_with_class nodeset p >>= fun e_p ->
NodeSet.project_r_with_class nodeset p >>= fun r_p ->
W.M.Rule.to_stringm rule >>= fun rs ->
let renamable =
try
let theta = R.orientation_symmetric rule trs in
let es,trs = List.map fst e_p, Trs.of_list (List.map fst r_p) in
let b = (R.eqns_invariant es theta) && (R.trs_invariant trs theta) in
if b then " Orientation of % s is symmetric\n% ! " rs
else " Orientation of % s is not symmetric\n% ! " rs ;
else Format.printf "Orientation of %s is not symmetric\n%!" rs;*)
b
with
| R.Not_renamable -> false
in return renamable)
;;
let symmetric_for_permutation rule _ trs p nodeset =
NodeSet.project_e nodeset p >>= fun e_p ->
NodeSet.project_r nodeset p >>= fun r_p ->
let permutable =
try
let pi = P.orientation_symmetric rule trs in
(P.eqns_invariant e_p pi) && (P.trs_invariant r_p pi)
with
| P.Not_permutable -> false
in return permutable
;;
let orientation_symmetric rule n trs p =
let t_start = Unix.gettimeofday () in
NS.all_nodes >>= fun nodeset ->
let answer =
W.get_options >>= fun options ->
match C.check_isomorphism options with
| C.NoChecks -> return false
| C.Renamings -> symmetric_for_renaming rule n trs p nodeset
| C.Permutations -> symmetric_for_permutation rule n trs p nodeset
in
St.add_t_isomorphisms (Unix.gettimeofday () -. t_start) >>
answer
;;
let print_iso (p,(e, r, c),_) (p',(e', r', c'),_) =
let e,(r,c) = List.map fst e, Pair.map (List.map fst) (r,c) in
let e',(r',c') = List.map fst e', Pair.map (List.map fst) (r',c') in
project W.M.Equation.list_to_stringm (e,e') >>= fun (es,es') ->
project (W.M.Trsx.to_stringm <.> Trs.of_list) (r,r') >>= fun (rs,rs') ->
project (W.M.Trsx.to_stringm <.> Trs.of_list) (c,c') >>= fun (cs,cs') ->
Format.printf "%s and %s are isomorphic:\n"
(CP.to_string p) (CP.to_string p');
Format.printf " E1:%s\n R1:%s\n C1:%s\n" es rs cs;
Format.printf " E2:%s\n R2:%s\n C2:%s\n%!" es' rs' cs';
return ()
;;
checks whether an isomorphism between these two processes exists
let exists (p,d,s) (p',d',s') =
if s <> s' then return false
else
W.get_options >>= function o ->
match C.check_isomorphism o with
| C.NoChecks -> return false
| C.Renamings -> R.processes_match (p,d) (p',d')
| C.Permutations -> return (P.processes_match (p,d) (p',d'))
;;
let compute_stamp (e, r, c) =
let equations_stamp = List.foldl (fun s (_,(i,j)) -> s+i+j) 0 in
let lhs_stamp = List.foldl (fun s (_,(i,_)) -> i+s) 0 in
let rhs_stamp = List.foldl (fun s (_,(_,i)) -> i+s) 0 in
let es = equations_stamp e in
let rls,rrs = lhs_stamp r, rhs_stamp r in
let cls,crs = lhs_stamp c, rhs_stamp c in
(es,rls,rrs,cls,crs)
;;
returns all processes that are subsumed by others .
exist - checks
n(n-1)/2 exist-checks *)
let filter_subsumed ps =
let t_start = Unix.gettimeofday () in
let rec filter_subsumed' = function
[] -> return []
| p :: ps ->
filter (fun p' -> exists p p') ps >>= fun subsumed ->
(*(if not (List.is_empty subsumed)
then iter (print_iso p) subsumed
else return ()) >>*)
let ps' = List.diff ps subsumed in
filter_subsumed' ps' >>= fun ps'' ->
return (List.union (List.map Triple.fst subsumed) ps'')
in
let state p =
NodeState.get_projections_with_class p >>= fun state ->
let s = compute_stamp state in
return (p,state,s)
in
map state ps >>= fun states ->
filter_subsumed' states >>= fun res ->
St.add_t_isomorphisms (Unix.gettimeofday () -. t_start) >>
return res
;;
let every_second_time () = let r = Random.float 1.0 in (r < 0.5)
let every_third_time () = let r = Random.float 1.0 in (r < 0.33)
perform periodical isomorphism checks only sometimes , currently
every second iteration
every second iteration *)
let filter_subsumed_sometimes pset =
if every_second_time () then filter_subsumed pset else return []
;;
let isomorphism_possible eqs =
W.get_options >>= function o ->
if R.renaming_possible eqs then
return (C.Renamings, true)
else if P.permutation_possible eqs then
return (C.Permutations, true)
else
return (C.NoChecks, false)
;;
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mkbtt/isomorphisms/processIsomorphism.ml | ocaml | ** OPENS **************************************************************
** SUBMODULES *********************************************************
** OPENS **************************************************************
** FUNCTIONS **********************************************************
(if not (List.is_empty subsumed)
then iter (print_iso p) subsumed
else return ()) >> | Copyright 2010
* GNU Lesser General Public License
*
* This file is part of MKBtt .
*
* 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 .
*
* 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 MKBtt . If not , see < / > .
* GNU Lesser General Public License
*
* This file is part of MKBtt.
*
* MKBtt 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.
*
* MKBtt 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 MKBtt. If not, see </>.
*)
* Switch isomorphism checks
@author
@since 2009/08/11
@author Sarah Winkler
@since 2009/08/11
*)
open Util;;
module Rewriting = Processors.Rewritingx;;
module Trs = U.Trs;;
module C = Completion;;
module St = Statistics;;
module NS = NodeState;;
module CP = CompletionProcessx;;
module N = IndexedNode;;
module R = TrsRenaming;;
module P = TermPermutation;;
module W = World;;
module Monad = W.Monad;;
open Monad;;
open World;;
let symmetric_for_renaming rule n trs p nodeset =
(lift Option.the <.> N.pattern_by_id) n >>= fun (i,j) ->
N.to_stringm n > > = fun s - >
if i <> j then (
" Not symmetric % i , % i : % s\n% ! " i j s ;
return false)
else (
" Symmetric % i , % i : % s\n% ! " i j s ;
NodeSet.project_e_with_class nodeset p >>= fun e_p ->
NodeSet.project_r_with_class nodeset p >>= fun r_p ->
W.M.Rule.to_stringm rule >>= fun rs ->
let renamable =
try
let theta = R.orientation_symmetric rule trs in
let es,trs = List.map fst e_p, Trs.of_list (List.map fst r_p) in
let b = (R.eqns_invariant es theta) && (R.trs_invariant trs theta) in
if b then " Orientation of % s is symmetric\n% ! " rs
else " Orientation of % s is not symmetric\n% ! " rs ;
else Format.printf "Orientation of %s is not symmetric\n%!" rs;*)
b
with
| R.Not_renamable -> false
in return renamable)
;;
let symmetric_for_permutation rule _ trs p nodeset =
NodeSet.project_e nodeset p >>= fun e_p ->
NodeSet.project_r nodeset p >>= fun r_p ->
let permutable =
try
let pi = P.orientation_symmetric rule trs in
(P.eqns_invariant e_p pi) && (P.trs_invariant r_p pi)
with
| P.Not_permutable -> false
in return permutable
;;
let orientation_symmetric rule n trs p =
let t_start = Unix.gettimeofday () in
NS.all_nodes >>= fun nodeset ->
let answer =
W.get_options >>= fun options ->
match C.check_isomorphism options with
| C.NoChecks -> return false
| C.Renamings -> symmetric_for_renaming rule n trs p nodeset
| C.Permutations -> symmetric_for_permutation rule n trs p nodeset
in
St.add_t_isomorphisms (Unix.gettimeofday () -. t_start) >>
answer
;;
let print_iso (p,(e, r, c),_) (p',(e', r', c'),_) =
let e,(r,c) = List.map fst e, Pair.map (List.map fst) (r,c) in
let e',(r',c') = List.map fst e', Pair.map (List.map fst) (r',c') in
project W.M.Equation.list_to_stringm (e,e') >>= fun (es,es') ->
project (W.M.Trsx.to_stringm <.> Trs.of_list) (r,r') >>= fun (rs,rs') ->
project (W.M.Trsx.to_stringm <.> Trs.of_list) (c,c') >>= fun (cs,cs') ->
Format.printf "%s and %s are isomorphic:\n"
(CP.to_string p) (CP.to_string p');
Format.printf " E1:%s\n R1:%s\n C1:%s\n" es rs cs;
Format.printf " E2:%s\n R2:%s\n C2:%s\n%!" es' rs' cs';
return ()
;;
checks whether an isomorphism between these two processes exists
let exists (p,d,s) (p',d',s') =
if s <> s' then return false
else
W.get_options >>= function o ->
match C.check_isomorphism o with
| C.NoChecks -> return false
| C.Renamings -> R.processes_match (p,d) (p',d')
| C.Permutations -> return (P.processes_match (p,d) (p',d'))
;;
let compute_stamp (e, r, c) =
let equations_stamp = List.foldl (fun s (_,(i,j)) -> s+i+j) 0 in
let lhs_stamp = List.foldl (fun s (_,(i,_)) -> i+s) 0 in
let rhs_stamp = List.foldl (fun s (_,(_,i)) -> i+s) 0 in
let es = equations_stamp e in
let rls,rrs = lhs_stamp r, rhs_stamp r in
let cls,crs = lhs_stamp c, rhs_stamp c in
(es,rls,rrs,cls,crs)
;;
returns all processes that are subsumed by others .
exist - checks
n(n-1)/2 exist-checks *)
let filter_subsumed ps =
let t_start = Unix.gettimeofday () in
let rec filter_subsumed' = function
[] -> return []
| p :: ps ->
filter (fun p' -> exists p p') ps >>= fun subsumed ->
let ps' = List.diff ps subsumed in
filter_subsumed' ps' >>= fun ps'' ->
return (List.union (List.map Triple.fst subsumed) ps'')
in
let state p =
NodeState.get_projections_with_class p >>= fun state ->
let s = compute_stamp state in
return (p,state,s)
in
map state ps >>= fun states ->
filter_subsumed' states >>= fun res ->
St.add_t_isomorphisms (Unix.gettimeofday () -. t_start) >>
return res
;;
let every_second_time () = let r = Random.float 1.0 in (r < 0.5)
let every_third_time () = let r = Random.float 1.0 in (r < 0.33)
perform periodical isomorphism checks only sometimes , currently
every second iteration
every second iteration *)
let filter_subsumed_sometimes pset =
if every_second_time () then filter_subsumed pset else return []
;;
let isomorphism_possible eqs =
W.get_options >>= function o ->
if R.renaming_possible eqs then
return (C.Renamings, true)
else if P.permutation_possible eqs then
return (C.Permutations, true)
else
return (C.NoChecks, false)
;;
|
f3074a931383e2d2b94943b2ed67f2a5671c49fbcca33d6c79b0f58fe6ffee62 | nikodemus/SBCL | utils.lisp | ;;;; utility functions and macros needed by the back end to generate
;;;; code
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB!VM")
Make a fixnum out of NUM . ( I.e. shift by two bits if it will fit . )
(defun fixnumize (num)
(if (fixnump num)
(ash num n-fixnum-tag-bits)
(error "~W is too big for a fixnum." num)))
;;; Determining whether a constant offset fits in an addressing mode.
#!+(or x86 x86-64)
(defun foldable-constant-offset-p (element-size lowtag data-offset offset)
(if (< element-size n-byte-bits)
nil
(multiple-value-bind (min max)
(sb!impl::displacement-bounds lowtag element-size data-offset)
(<= min offset max))))
;;;; routines for dealing with static symbols
(defun static-symbol-p (symbol)
(or (null symbol)
(and (member symbol *static-symbols*) t)))
;;; the byte offset of the static symbol SYMBOL
(defun static-symbol-offset (symbol)
(if symbol
(let ((posn (position symbol *static-symbols*)))
(unless posn (error "~S is not a static symbol." symbol))
(+ (* posn (pad-data-block symbol-size))
(pad-data-block (1- symbol-size))
other-pointer-lowtag
(- list-pointer-lowtag)))
0))
Given a byte offset , OFFSET , return the appropriate static symbol .
(defun offset-static-symbol (offset)
(if (zerop offset)
nil
(multiple-value-bind (n rem)
(truncate (+ offset list-pointer-lowtag (- other-pointer-lowtag)
(- (pad-data-block (1- symbol-size))))
(pad-data-block symbol-size))
(unless (and (zerop rem) (<= 0 n (1- (length *static-symbols*))))
(error "The byte offset ~W is not valid." offset))
(elt *static-symbols* n))))
Return the ( byte ) offset from NIL to the start of the fdefn object
;;; for the static function NAME.
(defun static-fdefn-offset (name)
(let ((static-syms (length *static-symbols*))
(static-fun-index (position name *static-funs*)))
(unless static-fun-index
(error "~S isn't a static function." name))
(+ (* static-syms (pad-data-block symbol-size))
(pad-data-block (1- symbol-size))
(- list-pointer-lowtag)
(* static-fun-index (pad-data-block fdefn-size))
other-pointer-lowtag)))
Return the ( byte ) offset from NIL to the raw - addr slot of the
;;; fdefn object for the static function NAME.
(defun static-fun-offset (name)
(+ (static-fdefn-offset name)
(- other-pointer-lowtag)
(* fdefn-raw-addr-slot n-word-bytes)))
;;; Various error-code generating helpers
(defvar *adjustable-vectors* nil)
(defmacro with-adjustable-vector ((var) &rest body)
`(let ((,var (or (pop *adjustable-vectors*)
(make-array 16
:element-type '(unsigned-byte 8)
:fill-pointer 0
:adjustable t))))
(declare (type (vector (unsigned-byte 8) 16) ,var))
(setf (fill-pointer ,var) 0)
(unwind-protect
(progn
,@body)
(push ,var *adjustable-vectors*))))
| null | https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/src/compiler/generic/utils.lisp | lisp | utility functions and macros needed by the back end to generate
code
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
Determining whether a constant offset fits in an addressing mode.
routines for dealing with static symbols
the byte offset of the static symbol SYMBOL
for the static function NAME.
fdefn object for the static function NAME.
Various error-code generating helpers |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB!VM")
Make a fixnum out of NUM . ( I.e. shift by two bits if it will fit . )
(defun fixnumize (num)
(if (fixnump num)
(ash num n-fixnum-tag-bits)
(error "~W is too big for a fixnum." num)))
#!+(or x86 x86-64)
(defun foldable-constant-offset-p (element-size lowtag data-offset offset)
(if (< element-size n-byte-bits)
nil
(multiple-value-bind (min max)
(sb!impl::displacement-bounds lowtag element-size data-offset)
(<= min offset max))))
(defun static-symbol-p (symbol)
(or (null symbol)
(and (member symbol *static-symbols*) t)))
(defun static-symbol-offset (symbol)
(if symbol
(let ((posn (position symbol *static-symbols*)))
(unless posn (error "~S is not a static symbol." symbol))
(+ (* posn (pad-data-block symbol-size))
(pad-data-block (1- symbol-size))
other-pointer-lowtag
(- list-pointer-lowtag)))
0))
Given a byte offset , OFFSET , return the appropriate static symbol .
(defun offset-static-symbol (offset)
(if (zerop offset)
nil
(multiple-value-bind (n rem)
(truncate (+ offset list-pointer-lowtag (- other-pointer-lowtag)
(- (pad-data-block (1- symbol-size))))
(pad-data-block symbol-size))
(unless (and (zerop rem) (<= 0 n (1- (length *static-symbols*))))
(error "The byte offset ~W is not valid." offset))
(elt *static-symbols* n))))
Return the ( byte ) offset from NIL to the start of the fdefn object
(defun static-fdefn-offset (name)
(let ((static-syms (length *static-symbols*))
(static-fun-index (position name *static-funs*)))
(unless static-fun-index
(error "~S isn't a static function." name))
(+ (* static-syms (pad-data-block symbol-size))
(pad-data-block (1- symbol-size))
(- list-pointer-lowtag)
(* static-fun-index (pad-data-block fdefn-size))
other-pointer-lowtag)))
Return the ( byte ) offset from NIL to the raw - addr slot of the
(defun static-fun-offset (name)
(+ (static-fdefn-offset name)
(- other-pointer-lowtag)
(* fdefn-raw-addr-slot n-word-bytes)))
(defvar *adjustable-vectors* nil)
(defmacro with-adjustable-vector ((var) &rest body)
`(let ((,var (or (pop *adjustable-vectors*)
(make-array 16
:element-type '(unsigned-byte 8)
:fill-pointer 0
:adjustable t))))
(declare (type (vector (unsigned-byte 8) 16) ,var))
(setf (fill-pointer ,var) 0)
(unwind-protect
(progn
,@body)
(push ,var *adjustable-vectors*))))
|
69e6ba1b51a93a07a6a29d4ef5de68512544238f337f12b0a47eb1294b4bff0d | janestreet/memtrace_viewer_with_deps | kind.mli | * A module internal to Incremental . Users should see { ! Incremental_intf } .
[ Kind.t ] is a variant type with one constructor for each kind of node ( const , var ,
map , bind , etc . ) .
[Kind.t] is a variant type with one constructor for each kind of node (const, var,
map, bind, etc.). *)
open! Core_kernel
open! Import
include module type of struct
include Types.Kind
end
include Invariant.S1 with type 'a t := 'a t
include Sexp_of.S1 with type 'a t := 'a t
val name : _ t -> string
val initial_num_children : _ t -> int
(** [slow_get_child t ~index] raises unless [0 <= index < max_num_children t]. It will
also raise if the [index]'th child is currently undefined (e.g. a bind node with no
current rhs). *)
val slow_get_child : _ t -> index:int -> Types.Node.Packed.t
val bind_rhs_child_index : int
val freeze_child_index : int
val if_branch_child_index : int
val join_rhs_child_index : int
val iteri_children : _ t -> f:(int -> Types.Node.Packed.t -> unit) -> unit
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/incremental/src/kind.mli | ocaml | * [slow_get_child t ~index] raises unless [0 <= index < max_num_children t]. It will
also raise if the [index]'th child is currently undefined (e.g. a bind node with no
current rhs). | * A module internal to Incremental . Users should see { ! Incremental_intf } .
[ Kind.t ] is a variant type with one constructor for each kind of node ( const , var ,
map , bind , etc . ) .
[Kind.t] is a variant type with one constructor for each kind of node (const, var,
map, bind, etc.). *)
open! Core_kernel
open! Import
include module type of struct
include Types.Kind
end
include Invariant.S1 with type 'a t := 'a t
include Sexp_of.S1 with type 'a t := 'a t
val name : _ t -> string
val initial_num_children : _ t -> int
val slow_get_child : _ t -> index:int -> Types.Node.Packed.t
val bind_rhs_child_index : int
val freeze_child_index : int
val if_branch_child_index : int
val join_rhs_child_index : int
val iteri_children : _ t -> f:(int -> Types.Node.Packed.t -> unit) -> unit
|
08b525a88962b175ae3e4007c68e02dbc8a6c7190dbc952ed745de5364e6a601 | rohitjha/DiMPL | Relation.hs | |
Module : Relation
Description : Relation module for the MPL DSL
Copyright : ( c ) , 2015
License : :
Stability : Stable
Functionality for
* Generating element set
* Obtaining list of first element values
* Obtaining list of second element values
* Obtaining list of first element values for a specified element as a second element
* Obtaining list of second element values for a specified element as a first element
* Checking for reflexivity , symmetricity , anti - symmetricity , transitivity
* Union , intersection and difference of two relations
* Relation composition
* Power of relations
* Reflexive , Symmetric and Transitive closures
Module : Relation
Description : Relation module for the MPL DSL
Copyright : (c) Rohit Jha, 2015
License : BSD2
Maintainer :
Stability : Stable
Functionality for
* Generating element set
* Obtaining list of first element values
* Obtaining list of second element values
* Obtaining list of first element values for a specified element as a second element
* Obtaining list of second element values for a specified element as a first element
* Checking for reflexivity, symmetricity, anti-symmetricity, transitivity
* Union, intersection and difference of two relations
* Relation composition
* Power of relations
* Reflexive, Symmetric and Transitive closures
-}
module Relation
(
Relation(..),
relationToList,
listToRelation,
inverse,
getDomain,
getRange,
elements,
returnDomainElems,
returnRangeElems,
isReflexive,
isIrreflexive,
isSymmetric,
isAsymmetric,
isAntiSymmetric,
isTransitive,
rUnion,
rUnionL,
rIntersection,
rIntersectionL,
rDifference,
composite,
rPower,
reflClosure,
symmClosure,
tranClosure,
isEquivalent,
isWeakPartialOrder,
isWeakTotalOrder,
isStrictPartialOrder,
isStrictTotalOrder
)
where
import qualified Data.List as L
|
The ' Relation ' data type is used for represnting relations ( discrete mathematics ) .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
The 'Relation' data type is used for represnting relations (discrete mathematics).
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
-}
newtype Relation a = Relation [(a,a)] deriving (Eq)
instance (Show a) => Show (Relation a) where
showsPrec _ (Relation s) = showRelation s
showRelation [] str = showString "{}" str
showRelation (x:xs) str = showChar '{' (shows x (showl xs str))
where
showl [] str = showChar '}' str
showl (x:xs) str = showChar ',' (shows x (showl xs str))
{-|
The 'relationToList' function converts a 'Relation' to a list representation.
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> relationToList r2
[(1,1),(2,2),(3,3)]
-}
relationToList :: Relation t -> [(t, t)]
relationToList (Relation r) = r
{-|
The 'listToRelation' function converts a list to a relation.
For example:
>>> let l = [(1,2),(2,3),(1,3)]
>>> let r = listToRelation l
>>> r
{(1,2),(2,3),(1,3)}
-}
listToRelation :: [(a, a)] -> Relation a
listToRelation r = Relation r
|
The ' inverse ' function returns the inverse ' Relation ' of a specified ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > inverse r1
{ ( 1,1),(2,1),(3,1),(1,2),(2,2),(3,2),(1,3),(2,3),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > inverse r2
{ ( 1,1),(2,2),(3,3 ) }
The 'inverse' function returns the inverse 'Relation' of a specified 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> inverse r1
{(1,1),(2,1),(3,1),(1,2),(2,2),(3,2),(1,3),(2,3),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> inverse r2
{(1,1),(2,2),(3,3)}
-}
inverse :: Relation a -> Relation a
inverse (Relation a) = listToRelation [ (y,x) | (x,y) <- a ]
|
The ' getDomain ' function returns the list of all " a " where ( a , b ) < - ' Relation ' .
For example :
> > > ( Relation [ ( 1,2),(3,4),(2,5 ) ] )
[ 1,3,2 ]
> > > ( Relation [ ] )
[ ]
The 'getDomain' function returns the list of all "a" where (a,b) <- 'Relation'.
For example:
>>> getDomain (Relation [(1,2),(3,4),(2,5)])
[1,3,2]
>>> getDomain (Relation [])
[]
-}
getDomain :: Eq a => Relation a -> [a]
getDomain (Relation r) = L.nub [fst x | x <- r]
|
The ' getRange ' function returns the list of all " b " where ( a , b ) < - ' Relation ' .
For example :
> > > getRange ( Relation [ ( 1,2),(3,4),(2,5 ) ] )
[ 2,4,5 ]
> > > getRange ( Relation [ ] )
[ ]
The 'getRange' function returns the list of all "b" where (a,b) <- 'Relation'.
For example:
>>> getRange (Relation [(1,2),(3,4),(2,5)])
[2,4,5]
>>> getRange (Relation [])
[]
-}
getRange :: Eq a => Relation a -> [a]
getRange (Relation r) = L.nub [snd x | x <- r]
|
The ' elements ' function returns a list of all elements in a ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > elements r1
[ 1,2,3 ]
The 'elements' function returns a list of all elements in a 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> elements r1
[1,2,3]
-}
elements :: Eq a => Relation a -> [a]
elements (Relation r) = getDomain (Relation r) `L.union` getRange (Relation r)
|
The ' returnFirstElems ' function returns alist of all " a " where ( a , b ) < - ' Relation ' and " b " is specified
For example :
> > > returnFirstElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 1
[ ]
> > > returnFirstElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 4
[ 3 ]
> > > returnFirstElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 3
[ 1,2,3 ]
The 'returnFirstElems' function returns alist of all "a" where (a,b) <- 'Relation' and "b" is specified
For example:
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 1
[]
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 4
[3]
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 3
[1,2,3]
-}
returnDomainElems :: Eq a => Relation a -> a -> [a]
returnDomainElems (Relation r) x = L.nub [a | a <- getDomain (Relation r), (a,x) `elem` r]
|
The ' returnSecondElems ' function returns list of all ' b ' where ( a , b ) < - Relation and ' a ' is specified/
For example :
> > > returnSecondElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 3
[ 3,4 ]
> > > returnSecondElems ( Relation [ ( 1,2),(1,3),(2,5 ) ] ) 1
[ 2,3 ]
The 'returnSecondElems' function returns list of all 'b' where (a,b) <- Relation and 'a' is specified/
For example:
>>> returnSecondElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 3
[3,4]
>>> returnSecondElems (Relation [(1,2),(1,3),(2,5)]) 1
[2,3]
-}
returnRangeElems :: Eq a => Relation a -> a -> [a]
returnRangeElems (Relation r) x = L.nub [b | b <- getRange (Relation r), (x,b) `elem` r]
|
The ' isReflexive ' function checks if a ' Relation ' is reflexive or not .
For example :
> > > isReflexive ( Relation [ ( 1,1),(1,2),(2,2),(2,3 ) ] )
False
> > > isReflexive ( Relation [ ( ) ] )
True
The 'isReflexive' function checks if a 'Relation' is reflexive or not.
For example:
>>> isReflexive (Relation [(1,1),(1,2),(2,2),(2,3)])
False
>>> isReflexive (Relation [(1,1),(1,2),(2,2)])
True
-}
isReflexive :: Eq t => Relation t -> Bool
isReflexive (Relation r) = and [(a,a) `elem` r | a <- elements (Relation r)]
|
The ' isIrreflexive ' function checks if a ' Relation ' is irreflexive or not .
For example :
> > > isIrreflexive ( Relation [ ( 1,1),(1,2),(2,2),(2,3 ) ] )
True
> > > isIrreflexive ( Relation [ ( ) ] )
False
The 'isIrreflexive' function checks if a 'Relation' is irreflexive or not.
For example:
>>> isIrreflexive (Relation [(1,1),(1,2),(2,2),(2,3)])
True
>>> isIrreflexive (Relation [(1,1),(1,2),(2,2)])
False
-}
isIrreflexive :: Eq t => Relation t -> Bool
isIrreflexive (Relation r) = not $ isReflexive (Relation r)
|
The ' isSymmetric ' function checks if a ' Relation ' is symmetric or not .
For example :
> > > isSymmetric ( Relation [ ( ) ] )
False
> > > isSymmetric ( Relation [ ( ) ] )
True
The 'isSymmetric' function checks if a 'Relation' is symmetric or not.
For example:
>>> isSymmetric (Relation [(1,1),(1,2),(2,2)])
False
>>> isSymmetric (Relation [(1,1),(1,2),(2,2),(2,1)])
True
-}
isSymmetric :: Eq a => Relation a -> Bool
isSymmetric (Relation r) = and [(b, a) `elem` r | a <- elements (Relation r), b <- elements (Relation r), (a, b) `elem` r]
|
The ' isAsymmetric ' function checks if a ' Relation ' is asymmetric or not .
For example :
> > > isAntiSymmetric ( Relation [ ( 1,2),(2,1 ) ] )
False
> > > isAntiSymmetric ( Relation [ ( 1,2),(1,3 ) ] )
True
The 'isAsymmetric' function checks if a 'Relation' is asymmetric or not.
For example:
>>> isAntiSymmetric (Relation [(1,2),(2,1)])
False
>>> isAntiSymmetric (Relation [(1,2),(1,3)])
True
-}
isAsymmetric :: Eq t => Relation t -> Bool
isAsymmetric (Relation r) = and [ (b,a) `notElem` r | a <- elements (Relation r), b <- elements (Relation r), (a,b) `elem` r]
|
The ' isAntiSymmetric ' function checks if a ' Relation ' is anti - symmetric or not .
For example :
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > isAntiSymmetric r2
True
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > isAntiSymmetric r1
False
The 'isAntiSymmetric' function checks if a 'Relation' is anti-symmetric or not.
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> isAntiSymmetric r2
True
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isAntiSymmetric r1
False
-}
isAntiSymmetric :: Eq a => Relation a -> Bool
isAntiSymmetric (Relation r) = and [ a == b | a <- elements (Relation r), b <- elements (Relation r), (a,b) `elem` r, (b,a) `elem` r]
{-|
The 'isTransitive' function checks if a 'Relation' is transitive or not.
For example:
>>> isTransitive (Relation [(1,1),(1,2),(2,1)])
False
>>> isTransitive (Relation [(1,1),(1,2),(2,1),(2,2)])
True
>>> isTransitive (Relation [(1,1),(2,2)])
True
-}
isTransitive :: Eq a => Relation a -> Bool
isTransitive (Relation r) = and [(a,c) `elem` r | a <- elements (Relation r), b <- elements (Relation r), c <- elements (Relation r), (a,b) `elem` r, (b,c) `elem` r]
|
The ' rUnion ' function returns the union of two relations .
For example :
> > > rUnion ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ ( 1,1),(1,2),(2,2),(2,3 ) }
> > > rUnion ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,1),(1,2 ) }
The 'rUnion' function returns the union of two relations.
For example:
>>> rUnion (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,1),(1,2),(2,2),(2,3)}
>>> rUnion (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1),(1,2)}
-}
rUnion :: Ord a => Relation a -> Relation a -> Relation a
rUnion (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) (r1 ++ [e | e <- r2, e `notElem` r1]))
|
The ' rUnionL ' function returns the union of a list of ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > rUnionL [ r1,r2 ]
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
The 'rUnionL' function returns the union of a list of 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> rUnionL [r1,r2]
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
-}
: : ( t1 , Foldable t ) = > t ( Relation t1 ) - > Relation t1
rUnionL :: (Ord t) => [Relation t] -> Relation t
rUnionL = foldl1 rUnion
|
The ' rIntersection ' function returns the intersection of two relations .
For example :
> > > rIntersection ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,1 ) }
> > > rIntersection ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ }
The 'rIntersection' function returns the intersection of two relations.
For example:
>>> rIntersection (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1)}
>>> rIntersection (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{}
-}
rIntersection :: Ord a => Relation a -> Relation a -> Relation a
rIntersection (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) [e | e <- r1, e `elem` r2])
|
The ' rIntersectionL ' function returns the intersection of a list of ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > rIntersectionL [ r1,r2 ]
{ ( 1,1),(2,2),(3,3 ) }
The 'rIntersectionL' function returns the intersection of a list of 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> rIntersectionL [r1,r2]
{(1,1),(2,2),(3,3)}
-}
rIntersectionL : : ( a , Foldable t ) = > t ( Relation a ) - > Relation a
rIntersectionL :: (Ord a) => [Relation a] -> Relation a
rIntersectionL = foldl1 rIntersection
|
The ' rDifference ' function returns the difference of two relations .
For example :
> > > rDifference ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,2 ) }
> > > rDifference ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ ( 1,1),(1,2 ) }
The 'rDifference' function returns the difference of two relations.
For example:
>>> rDifference (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,2)}
>>> rDifference (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,1),(1,2)}
-}
rDifference :: Ord a => Relation a -> Relation a -> Relation a
rDifference (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) [e | e <- r1, e `notElem` r2])
|
The ' composite ' function returns the composite / concatenation of two relations .
For example :
> > > composite ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ ( 1,2),(1,3 ) }
> > > composite ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,1 ) }
The 'composite' function returns the composite / concatenation of two relations.
For example:
>>> composite (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,2),(1,3)}
>>> composite (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1)}
-}
composite :: Eq a => Relation a -> Relation a -> Relation a
composite (Relation r1) (Relation r2) = Relation $ L.nub [(a,c) | a <- elements (Relation r1), b <- elements (Relation r1), b <- elements (Relation r2), c <- elements (Relation r2), (a,b) `elem` r1, (b,c) `elem` r2]
|
The ' rPower ' function returns the power of a ' Relation ' .
For example :
> > > let [ ( 1,2 ) , ( 2,3 ) , ( 2,4 ) , ( 3,3 ) ]
> > > r4
{ ( 1,2),(2,3),(2,4),(3,3 ) }
> > > rPower r4 2
{ ( 1,3),(1,4),(2,3),(3,3 ) }
> > > rPower r4 ( -2 )
{ ( 3,1),(3,2),(3,3),(4,1 ) }
--| pow < 0 = rPower ( Relation [ ( b , a ) | ( a , b ) < - r ] ) ( -pow )
The 'rPower' function returns the power of a 'Relation'.
For example:
>>> let r4 = Relation [(1,2), (2,3), (2,4), (3,3)]
>>> r4
{(1,2),(2,3),(2,4),(3,3)}
>>> rPower r4 2
{(1,3),(1,4),(2,3),(3,3)}
>>> rPower r4 (-2)
{(3,1),(3,2),(3,3),(4,1)}
--| pow < 0 = rPower (Relation [(b, a) | (a, b) <- r]) (-pow)
-}
rPower :: (Eq a, Eq a1, Integral a1) => Relation a -> a1 -> Relation a
rPower (Relation r) pow
| pow < 0 = rPower (inverse (Relation r)) (-pow)
| pow == 1 = Relation r
| otherwise = composite (rPower (Relation r) (pow - 1)) (Relation r)
{-|
The 'reflClosure' function returns the Reflecive Closure of a 'Relation'.
For example:
>>> reflClosure (Relation [(1,1),(1,2),(4,5)])
{(1,1),(1,2),(2,2),(4,4),(4,5),(5,5)}
>>> reflClosure (Relation [(1,1),(1,3)])
{(1,1),(1,3),(3,3)}
-}
reflClosure :: Ord a => Relation a -> Relation a
reflClosure (Relation r) = rUnion (Relation r) (delta (Relation r))
where
delta (Relation r) = Relation [(a,b) | a <- elements (Relation r), b <- elements (Relation r), a == b]
|
The ' symmClosure ' function returns the Symmetric Closure of a ' Relation ' .
For example :
> > > symmClosure ( Relation [ ( 1,1),(1,2),(4,5 ) ] )
{ ( 1,1),(1,2),(2,1),(4,5),(5,4 ) }
> > > symmClosure ( Relation [ ( 1,1),(1,3 ) ] )
{ ( 1,1),(1,3),(3,1 ) }
The 'symmClosure' function returns the Symmetric Closure of a 'Relation'.
For example:
>>> symmClosure (Relation [(1,1),(1,2),(4,5)])
{(1,1),(1,2),(2,1),(4,5),(5,4)}
>>> symmClosure (Relation [(1,1),(1,3)])
{(1,1),(1,3),(3,1)}
-}
symmClosure :: Ord a => Relation a -> Relation a
symmClosure (Relation r) = rUnion (Relation r) (rPower (Relation r) (-1))
|
The ' tranClosure ' function returns the Transitive Closure of a ' Relation ' .
For example :
> > > tranClosure ( Relation [ ( 1,1),(1,2),(2,1 ) ] )
{ ( 1,1),(1,2),(2,1),(2,2 ) }
> > > tranClosure ( Relation [ ( 1,1),(1,2),(1,3),(2,2),(3,1),(3,2 ) ] )
{ ( 1,1),(1,2),(1,3),(2,2),(3,1),(3,2),(3,3 ) }
The 'tranClosure' function returns the Transitive Closure of a 'Relation'.
For example:
>>> tranClosure (Relation [(1,1),(1,2),(2,1)])
{(1,1),(1,2),(2,1),(2,2)}
>>> tranClosure (Relation [(1,1),(1,2),(1,3),(2,2),(3,1),(3,2)])
{(1,1),(1,2),(1,3),(2,2),(3,1),(3,2),(3,3)}
-}
tranClosure :: Ord a => Relation a -> Relation a
tranClosure (Relation r) = foldl1 rUnion [ rPower (Relation r) n | n <- [1 .. length (elements (Relation r)) ]]
|
The ' isEquivalent ' function checks if a ' Relation ' is equivalent ( reflexive , symmetric and transitive ) .
For example :
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > isEquivalent r2
True
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > isEquivalent r1
True
> > > isEquivalent ( Relation [ ( 1,2 ) , ( 2,3 ) ] )
False
The 'isEquivalent' function checks if a 'Relation' is equivalent (reflexive, symmetric and transitive).
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> isEquivalent r2
True
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isEquivalent r1
True
>>> isEquivalent (Relation [(1,2), (2,3)])
False
-}
isEquivalent :: Eq a => Relation a -> Bool
isEquivalent (Relation r) = isReflexive (Relation r) && isSymmetric (Relation r) && isTransitive (Relation r)
|
The ' isWeakPartialOrder ' function checks if a ' Relation ' is a weak partial order ( reflexive , anti - symmetric and transitive ) .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > isWeakPartialOrder r1
False
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > isWeakPartialOrder r2
True
The 'isWeakPartialOrder' function checks if a 'Relation' is a weak partial order (reflexive, anti-symmetric and transitive).
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isWeakPartialOrder r1
False
>>> r2
{(1,1),(2,2),(3,3)}
>>> isWeakPartialOrder r2
True
-}
isWeakPartialOrder :: Eq a => Relation a -> Bool
isWeakPartialOrder (Relation r) = isReflexive (Relation r) && isAntiSymmetric (Relation r) && isTransitive (Relation r)
{-|
The 'isWeakTotalOrder' function checks if a 'Relation' is a Weak Total Order, i.e. it is a Weak Partial Order and for all "a" and "b" in 'Relation' "r", (a,b) or (b,a) are elements of r.
-}
isWeakTotalOrder :: Eq a => Relation a -> Bool
isWeakTotalOrder (Relation r) = isWeakPartialOrder (Relation r) && and [ ((a,b) `elem` r) || ((b,a) `elem` r) | a <- elements (Relation r), b <- elements (Relation r) ]
|
The ' isStrictPartialOrder ' function checks if a ' Relation ' is a Strict Partial Order , i.e. it is irreflexive , asymmetric and transitive .
The 'isStrictPartialOrder' function checks if a 'Relation' is a Strict Partial Order, i.e. it is irreflexive, asymmetric and transitive.
-}
isStrictPartialOrder :: Eq a => Relation a -> Bool
isStrictPartialOrder (Relation r) = isIrreflexive (Relation r) && isAsymmetric (Relation r) && isTransitive (Relation r)
|
The ' isStrictTotalOrder ' function checks if a ' Relation ' is a Strict Total Order , i.e. it is a Strict Partial Order , and for all " a " and " b " in ' Relation ' " r " , either ( a , b ) or ( b , a ) are elements of r or a = = b.
The 'isStrictTotalOrder' function checks if a 'Relation' is a Strict Total Order, i.e. it is a Strict Partial Order, and for all "a" and "b" in 'Relation' "r", either (a,b) or (b,a) are elements of r or a == b.
-}
isStrictTotalOrder :: Eq a => Relation a -> Bool
isStrictTotalOrder (Relation r) = isStrictPartialOrder (Relation r) && and [ ((a,b) `elem` r) || ((b,a) `elem` r) || a==b | a <- elements (Relation r), b <- elements (Relation r) ]
-- SAMPLE RELATIONS --
r1 = Relation [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
r2 = Relation [(1,1),(2,2),(3,3)]
r3 = Relation []
| null | https://raw.githubusercontent.com/rohitjha/DiMPL/087c499ba104dec897fe325f86580e6d623c86ee/src/Relation.hs | haskell | |
The 'relationToList' function converts a 'Relation' to a list representation.
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> relationToList r2
[(1,1),(2,2),(3,3)]
|
The 'listToRelation' function converts a list to a relation.
For example:
>>> let l = [(1,2),(2,3),(1,3)]
>>> let r = listToRelation l
>>> r
{(1,2),(2,3),(1,3)}
|
The 'isTransitive' function checks if a 'Relation' is transitive or not.
For example:
>>> isTransitive (Relation [(1,1),(1,2),(2,1)])
False
>>> isTransitive (Relation [(1,1),(1,2),(2,1),(2,2)])
True
>>> isTransitive (Relation [(1,1),(2,2)])
True
| pow < 0 = rPower ( Relation [ ( b , a ) | ( a , b ) < - r ] ) ( -pow )
| pow < 0 = rPower (Relation [(b, a) | (a, b) <- r]) (-pow)
|
The 'reflClosure' function returns the Reflecive Closure of a 'Relation'.
For example:
>>> reflClosure (Relation [(1,1),(1,2),(4,5)])
{(1,1),(1,2),(2,2),(4,4),(4,5),(5,5)}
>>> reflClosure (Relation [(1,1),(1,3)])
{(1,1),(1,3),(3,3)}
|
The 'isWeakTotalOrder' function checks if a 'Relation' is a Weak Total Order, i.e. it is a Weak Partial Order and for all "a" and "b" in 'Relation' "r", (a,b) or (b,a) are elements of r.
SAMPLE RELATIONS --
| |
Module : Relation
Description : Relation module for the MPL DSL
Copyright : ( c ) , 2015
License : :
Stability : Stable
Functionality for
* Generating element set
* Obtaining list of first element values
* Obtaining list of second element values
* Obtaining list of first element values for a specified element as a second element
* Obtaining list of second element values for a specified element as a first element
* Checking for reflexivity , symmetricity , anti - symmetricity , transitivity
* Union , intersection and difference of two relations
* Relation composition
* Power of relations
* Reflexive , Symmetric and Transitive closures
Module : Relation
Description : Relation module for the MPL DSL
Copyright : (c) Rohit Jha, 2015
License : BSD2
Maintainer :
Stability : Stable
Functionality for
* Generating element set
* Obtaining list of first element values
* Obtaining list of second element values
* Obtaining list of first element values for a specified element as a second element
* Obtaining list of second element values for a specified element as a first element
* Checking for reflexivity, symmetricity, anti-symmetricity, transitivity
* Union, intersection and difference of two relations
* Relation composition
* Power of relations
* Reflexive, Symmetric and Transitive closures
-}
module Relation
(
Relation(..),
relationToList,
listToRelation,
inverse,
getDomain,
getRange,
elements,
returnDomainElems,
returnRangeElems,
isReflexive,
isIrreflexive,
isSymmetric,
isAsymmetric,
isAntiSymmetric,
isTransitive,
rUnion,
rUnionL,
rIntersection,
rIntersectionL,
rDifference,
composite,
rPower,
reflClosure,
symmClosure,
tranClosure,
isEquivalent,
isWeakPartialOrder,
isWeakTotalOrder,
isStrictPartialOrder,
isStrictTotalOrder
)
where
import qualified Data.List as L
|
The ' Relation ' data type is used for represnting relations ( discrete mathematics ) .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
The 'Relation' data type is used for represnting relations (discrete mathematics).
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
-}
newtype Relation a = Relation [(a,a)] deriving (Eq)
instance (Show a) => Show (Relation a) where
showsPrec _ (Relation s) = showRelation s
showRelation [] str = showString "{}" str
showRelation (x:xs) str = showChar '{' (shows x (showl xs str))
where
showl [] str = showChar '}' str
showl (x:xs) str = showChar ',' (shows x (showl xs str))
relationToList :: Relation t -> [(t, t)]
relationToList (Relation r) = r
listToRelation :: [(a, a)] -> Relation a
listToRelation r = Relation r
|
The ' inverse ' function returns the inverse ' Relation ' of a specified ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > inverse r1
{ ( 1,1),(2,1),(3,1),(1,2),(2,2),(3,2),(1,3),(2,3),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > inverse r2
{ ( 1,1),(2,2),(3,3 ) }
The 'inverse' function returns the inverse 'Relation' of a specified 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> inverse r1
{(1,1),(2,1),(3,1),(1,2),(2,2),(3,2),(1,3),(2,3),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> inverse r2
{(1,1),(2,2),(3,3)}
-}
inverse :: Relation a -> Relation a
inverse (Relation a) = listToRelation [ (y,x) | (x,y) <- a ]
|
The ' getDomain ' function returns the list of all " a " where ( a , b ) < - ' Relation ' .
For example :
> > > ( Relation [ ( 1,2),(3,4),(2,5 ) ] )
[ 1,3,2 ]
> > > ( Relation [ ] )
[ ]
The 'getDomain' function returns the list of all "a" where (a,b) <- 'Relation'.
For example:
>>> getDomain (Relation [(1,2),(3,4),(2,5)])
[1,3,2]
>>> getDomain (Relation [])
[]
-}
getDomain :: Eq a => Relation a -> [a]
getDomain (Relation r) = L.nub [fst x | x <- r]
|
The ' getRange ' function returns the list of all " b " where ( a , b ) < - ' Relation ' .
For example :
> > > getRange ( Relation [ ( 1,2),(3,4),(2,5 ) ] )
[ 2,4,5 ]
> > > getRange ( Relation [ ] )
[ ]
The 'getRange' function returns the list of all "b" where (a,b) <- 'Relation'.
For example:
>>> getRange (Relation [(1,2),(3,4),(2,5)])
[2,4,5]
>>> getRange (Relation [])
[]
-}
getRange :: Eq a => Relation a -> [a]
getRange (Relation r) = L.nub [snd x | x <- r]
|
The ' elements ' function returns a list of all elements in a ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > elements r1
[ 1,2,3 ]
The 'elements' function returns a list of all elements in a 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> elements r1
[1,2,3]
-}
elements :: Eq a => Relation a -> [a]
elements (Relation r) = getDomain (Relation r) `L.union` getRange (Relation r)
|
The ' returnFirstElems ' function returns alist of all " a " where ( a , b ) < - ' Relation ' and " b " is specified
For example :
> > > returnFirstElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 1
[ ]
> > > returnFirstElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 4
[ 3 ]
> > > returnFirstElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 3
[ 1,2,3 ]
The 'returnFirstElems' function returns alist of all "a" where (a,b) <- 'Relation' and "b" is specified
For example:
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 1
[]
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 4
[3]
>>> returnFirstElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 3
[1,2,3]
-}
returnDomainElems :: Eq a => Relation a -> a -> [a]
returnDomainElems (Relation r) x = L.nub [a | a <- getDomain (Relation r), (a,x) `elem` r]
|
The ' returnSecondElems ' function returns list of all ' b ' where ( a , b ) < - Relation and ' a ' is specified/
For example :
> > > returnSecondElems ( Relation [ ( 1,2),(1,3),(2,3),(3,3),(3,4 ) ] ) 3
[ 3,4 ]
> > > returnSecondElems ( Relation [ ( 1,2),(1,3),(2,5 ) ] ) 1
[ 2,3 ]
The 'returnSecondElems' function returns list of all 'b' where (a,b) <- Relation and 'a' is specified/
For example:
>>> returnSecondElems (Relation [(1,2),(1,3),(2,3),(3,3),(3,4)]) 3
[3,4]
>>> returnSecondElems (Relation [(1,2),(1,3),(2,5)]) 1
[2,3]
-}
returnRangeElems :: Eq a => Relation a -> a -> [a]
returnRangeElems (Relation r) x = L.nub [b | b <- getRange (Relation r), (x,b) `elem` r]
|
The ' isReflexive ' function checks if a ' Relation ' is reflexive or not .
For example :
> > > isReflexive ( Relation [ ( 1,1),(1,2),(2,2),(2,3 ) ] )
False
> > > isReflexive ( Relation [ ( ) ] )
True
The 'isReflexive' function checks if a 'Relation' is reflexive or not.
For example:
>>> isReflexive (Relation [(1,1),(1,2),(2,2),(2,3)])
False
>>> isReflexive (Relation [(1,1),(1,2),(2,2)])
True
-}
isReflexive :: Eq t => Relation t -> Bool
isReflexive (Relation r) = and [(a,a) `elem` r | a <- elements (Relation r)]
|
The ' isIrreflexive ' function checks if a ' Relation ' is irreflexive or not .
For example :
> > > isIrreflexive ( Relation [ ( 1,1),(1,2),(2,2),(2,3 ) ] )
True
> > > isIrreflexive ( Relation [ ( ) ] )
False
The 'isIrreflexive' function checks if a 'Relation' is irreflexive or not.
For example:
>>> isIrreflexive (Relation [(1,1),(1,2),(2,2),(2,3)])
True
>>> isIrreflexive (Relation [(1,1),(1,2),(2,2)])
False
-}
isIrreflexive :: Eq t => Relation t -> Bool
isIrreflexive (Relation r) = not $ isReflexive (Relation r)
|
The ' isSymmetric ' function checks if a ' Relation ' is symmetric or not .
For example :
> > > isSymmetric ( Relation [ ( ) ] )
False
> > > isSymmetric ( Relation [ ( ) ] )
True
The 'isSymmetric' function checks if a 'Relation' is symmetric or not.
For example:
>>> isSymmetric (Relation [(1,1),(1,2),(2,2)])
False
>>> isSymmetric (Relation [(1,1),(1,2),(2,2),(2,1)])
True
-}
isSymmetric :: Eq a => Relation a -> Bool
isSymmetric (Relation r) = and [(b, a) `elem` r | a <- elements (Relation r), b <- elements (Relation r), (a, b) `elem` r]
|
The ' isAsymmetric ' function checks if a ' Relation ' is asymmetric or not .
For example :
> > > isAntiSymmetric ( Relation [ ( 1,2),(2,1 ) ] )
False
> > > isAntiSymmetric ( Relation [ ( 1,2),(1,3 ) ] )
True
The 'isAsymmetric' function checks if a 'Relation' is asymmetric or not.
For example:
>>> isAntiSymmetric (Relation [(1,2),(2,1)])
False
>>> isAntiSymmetric (Relation [(1,2),(1,3)])
True
-}
isAsymmetric :: Eq t => Relation t -> Bool
isAsymmetric (Relation r) = and [ (b,a) `notElem` r | a <- elements (Relation r), b <- elements (Relation r), (a,b) `elem` r]
|
The ' isAntiSymmetric ' function checks if a ' Relation ' is anti - symmetric or not .
For example :
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > isAntiSymmetric r2
True
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > isAntiSymmetric r1
False
The 'isAntiSymmetric' function checks if a 'Relation' is anti-symmetric or not.
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> isAntiSymmetric r2
True
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isAntiSymmetric r1
False
-}
isAntiSymmetric :: Eq a => Relation a -> Bool
isAntiSymmetric (Relation r) = and [ a == b | a <- elements (Relation r), b <- elements (Relation r), (a,b) `elem` r, (b,a) `elem` r]
isTransitive :: Eq a => Relation a -> Bool
isTransitive (Relation r) = and [(a,c) `elem` r | a <- elements (Relation r), b <- elements (Relation r), c <- elements (Relation r), (a,b) `elem` r, (b,c) `elem` r]
|
The ' rUnion ' function returns the union of two relations .
For example :
> > > rUnion ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ ( 1,1),(1,2),(2,2),(2,3 ) }
> > > rUnion ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,1),(1,2 ) }
The 'rUnion' function returns the union of two relations.
For example:
>>> rUnion (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,1),(1,2),(2,2),(2,3)}
>>> rUnion (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1),(1,2)}
-}
rUnion :: Ord a => Relation a -> Relation a -> Relation a
rUnion (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) (r1 ++ [e | e <- r2, e `notElem` r1]))
|
The ' rUnionL ' function returns the union of a list of ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > rUnionL [ r1,r2 ]
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
The 'rUnionL' function returns the union of a list of 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> rUnionL [r1,r2]
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
-}
: : ( t1 , Foldable t ) = > t ( Relation t1 ) - > Relation t1
rUnionL :: (Ord t) => [Relation t] -> Relation t
rUnionL = foldl1 rUnion
|
The ' rIntersection ' function returns the intersection of two relations .
For example :
> > > rIntersection ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,1 ) }
> > > rIntersection ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ }
The 'rIntersection' function returns the intersection of two relations.
For example:
>>> rIntersection (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1)}
>>> rIntersection (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{}
-}
rIntersection :: Ord a => Relation a -> Relation a -> Relation a
rIntersection (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) [e | e <- r1, e `elem` r2])
|
The ' rIntersectionL ' function returns the intersection of a list of ' Relation ' .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > rIntersectionL [ r1,r2 ]
{ ( 1,1),(2,2),(3,3 ) }
The 'rIntersectionL' function returns the intersection of a list of 'Relation'.
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> r2
{(1,1),(2,2),(3,3)}
>>> rIntersectionL [r1,r2]
{(1,1),(2,2),(3,3)}
-}
rIntersectionL : : ( a , Foldable t ) = > t ( Relation a ) - > Relation a
rIntersectionL :: (Ord a) => [Relation a] -> Relation a
rIntersectionL = foldl1 rIntersection
|
The ' rDifference ' function returns the difference of two relations .
For example :
> > > rDifference ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,2 ) }
> > > rDifference ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ ( 1,1),(1,2 ) }
The 'rDifference' function returns the difference of two relations.
For example:
>>> rDifference (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,2)}
>>> rDifference (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,1),(1,2)}
-}
rDifference :: Ord a => Relation a -> Relation a -> Relation a
rDifference (Relation r1) (Relation r2) = Relation ((L.sort . L.nub) [e | e <- r1, e `notElem` r2])
|
The ' composite ' function returns the composite / concatenation of two relations .
For example :
> > > composite ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 2,3),(2,2 ) ] )
{ ( 1,2),(1,3 ) }
> > > composite ( Relation [ ( 1,1),(1,2 ) ] ) ( Relation [ ( 1,1 ) ] )
{ ( 1,1 ) }
The 'composite' function returns the composite / concatenation of two relations.
For example:
>>> composite (Relation [(1,1),(1,2)]) (Relation [(2,3),(2,2)])
{(1,2),(1,3)}
>>> composite (Relation [(1,1),(1,2)]) (Relation [(1,1)])
{(1,1)}
-}
composite :: Eq a => Relation a -> Relation a -> Relation a
composite (Relation r1) (Relation r2) = Relation $ L.nub [(a,c) | a <- elements (Relation r1), b <- elements (Relation r1), b <- elements (Relation r2), c <- elements (Relation r2), (a,b) `elem` r1, (b,c) `elem` r2]
|
The ' rPower ' function returns the power of a ' Relation ' .
For example :
> > > let [ ( 1,2 ) , ( 2,3 ) , ( 2,4 ) , ( 3,3 ) ]
> > > r4
{ ( 1,2),(2,3),(2,4),(3,3 ) }
> > > rPower r4 2
{ ( 1,3),(1,4),(2,3),(3,3 ) }
> > > rPower r4 ( -2 )
{ ( 3,1),(3,2),(3,3),(4,1 ) }
The 'rPower' function returns the power of a 'Relation'.
For example:
>>> let r4 = Relation [(1,2), (2,3), (2,4), (3,3)]
>>> r4
{(1,2),(2,3),(2,4),(3,3)}
>>> rPower r4 2
{(1,3),(1,4),(2,3),(3,3)}
>>> rPower r4 (-2)
{(3,1),(3,2),(3,3),(4,1)}
-}
rPower :: (Eq a, Eq a1, Integral a1) => Relation a -> a1 -> Relation a
rPower (Relation r) pow
| pow < 0 = rPower (inverse (Relation r)) (-pow)
| pow == 1 = Relation r
| otherwise = composite (rPower (Relation r) (pow - 1)) (Relation r)
reflClosure :: Ord a => Relation a -> Relation a
reflClosure (Relation r) = rUnion (Relation r) (delta (Relation r))
where
delta (Relation r) = Relation [(a,b) | a <- elements (Relation r), b <- elements (Relation r), a == b]
|
The ' symmClosure ' function returns the Symmetric Closure of a ' Relation ' .
For example :
> > > symmClosure ( Relation [ ( 1,1),(1,2),(4,5 ) ] )
{ ( 1,1),(1,2),(2,1),(4,5),(5,4 ) }
> > > symmClosure ( Relation [ ( 1,1),(1,3 ) ] )
{ ( 1,1),(1,3),(3,1 ) }
The 'symmClosure' function returns the Symmetric Closure of a 'Relation'.
For example:
>>> symmClosure (Relation [(1,1),(1,2),(4,5)])
{(1,1),(1,2),(2,1),(4,5),(5,4)}
>>> symmClosure (Relation [(1,1),(1,3)])
{(1,1),(1,3),(3,1)}
-}
symmClosure :: Ord a => Relation a -> Relation a
symmClosure (Relation r) = rUnion (Relation r) (rPower (Relation r) (-1))
|
The ' tranClosure ' function returns the Transitive Closure of a ' Relation ' .
For example :
> > > tranClosure ( Relation [ ( 1,1),(1,2),(2,1 ) ] )
{ ( 1,1),(1,2),(2,1),(2,2 ) }
> > > tranClosure ( Relation [ ( 1,1),(1,2),(1,3),(2,2),(3,1),(3,2 ) ] )
{ ( 1,1),(1,2),(1,3),(2,2),(3,1),(3,2),(3,3 ) }
The 'tranClosure' function returns the Transitive Closure of a 'Relation'.
For example:
>>> tranClosure (Relation [(1,1),(1,2),(2,1)])
{(1,1),(1,2),(2,1),(2,2)}
>>> tranClosure (Relation [(1,1),(1,2),(1,3),(2,2),(3,1),(3,2)])
{(1,1),(1,2),(1,3),(2,2),(3,1),(3,2),(3,3)}
-}
tranClosure :: Ord a => Relation a -> Relation a
tranClosure (Relation r) = foldl1 rUnion [ rPower (Relation r) n | n <- [1 .. length (elements (Relation r)) ]]
|
The ' isEquivalent ' function checks if a ' Relation ' is equivalent ( reflexive , symmetric and transitive ) .
For example :
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > isEquivalent r2
True
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > isEquivalent r1
True
> > > isEquivalent ( Relation [ ( 1,2 ) , ( 2,3 ) ] )
False
The 'isEquivalent' function checks if a 'Relation' is equivalent (reflexive, symmetric and transitive).
For example:
>>> r2
{(1,1),(2,2),(3,3)}
>>> isEquivalent r2
True
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isEquivalent r1
True
>>> isEquivalent (Relation [(1,2), (2,3)])
False
-}
isEquivalent :: Eq a => Relation a -> Bool
isEquivalent (Relation r) = isReflexive (Relation r) && isSymmetric (Relation r) && isTransitive (Relation r)
|
The ' isWeakPartialOrder ' function checks if a ' Relation ' is a weak partial order ( reflexive , anti - symmetric and transitive ) .
For example :
> > > r1
{ ( 1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3 ) }
> > > isWeakPartialOrder r1
False
> > > r2
{ ( 1,1),(2,2),(3,3 ) }
> > > isWeakPartialOrder r2
True
The 'isWeakPartialOrder' function checks if a 'Relation' is a weak partial order (reflexive, anti-symmetric and transitive).
For example:
>>> r1
{(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)}
>>> isWeakPartialOrder r1
False
>>> r2
{(1,1),(2,2),(3,3)}
>>> isWeakPartialOrder r2
True
-}
isWeakPartialOrder :: Eq a => Relation a -> Bool
isWeakPartialOrder (Relation r) = isReflexive (Relation r) && isAntiSymmetric (Relation r) && isTransitive (Relation r)
isWeakTotalOrder :: Eq a => Relation a -> Bool
isWeakTotalOrder (Relation r) = isWeakPartialOrder (Relation r) && and [ ((a,b) `elem` r) || ((b,a) `elem` r) | a <- elements (Relation r), b <- elements (Relation r) ]
|
The ' isStrictPartialOrder ' function checks if a ' Relation ' is a Strict Partial Order , i.e. it is irreflexive , asymmetric and transitive .
The 'isStrictPartialOrder' function checks if a 'Relation' is a Strict Partial Order, i.e. it is irreflexive, asymmetric and transitive.
-}
isStrictPartialOrder :: Eq a => Relation a -> Bool
isStrictPartialOrder (Relation r) = isIrreflexive (Relation r) && isAsymmetric (Relation r) && isTransitive (Relation r)
|
The ' isStrictTotalOrder ' function checks if a ' Relation ' is a Strict Total Order , i.e. it is a Strict Partial Order , and for all " a " and " b " in ' Relation ' " r " , either ( a , b ) or ( b , a ) are elements of r or a = = b.
The 'isStrictTotalOrder' function checks if a 'Relation' is a Strict Total Order, i.e. it is a Strict Partial Order, and for all "a" and "b" in 'Relation' "r", either (a,b) or (b,a) are elements of r or a == b.
-}
isStrictTotalOrder :: Eq a => Relation a -> Bool
isStrictTotalOrder (Relation r) = isStrictPartialOrder (Relation r) && and [ ((a,b) `elem` r) || ((b,a) `elem` r) || a==b | a <- elements (Relation r), b <- elements (Relation r) ]
r1 = Relation [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
r2 = Relation [(1,1),(2,2),(3,3)]
r3 = Relation []
|
8227d0bf49c05f29776b4e5ac16ec8d2ad01e154c98c6159ddc3a2236ee853db | scrintal/heroicons-reagent | arrow_right.cljs | (ns com.scrintal.heroicons.mini.arrow-right)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M3 10a.75.75 0 01.75-.75h10.638L10.23 5.29a.75.75 0 111.04-1.08l5.5 5.25a.75.75 0 010 1.08l-5.5 5.25a.75.75 0 11-1.04-1.08l4.158-3.96H3.75A.75.75 0 013 10z"
:clipRule "evenodd"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/arrow_right.cljs | clojure | (ns com.scrintal.heroicons.mini.arrow-right)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M3 10a.75.75 0 01.75-.75h10.638L10.23 5.29a.75.75 0 111.04-1.08l5.5 5.25a.75.75 0 010 1.08l-5.5 5.25a.75.75 0 11-1.04-1.08l4.158-3.96H3.75A.75.75 0 013 10z"
:clipRule "evenodd"}]]) | |
76d618cca199de2c95bb2f7322456485766cb76e8d25b5b1bfe98074235ad912 | fluent/fluent-logger-ocaml | stream_sender.ml | module U = Unix
type dst_info = INET of string * int | UNIX of string
type t = {
dst_info:dst_info;
conn_timeout:int;
(* TODO: change these ones to immutable *)
mutable socket:U.file_descr option;
mutable last_conn_err_time:int option;
mutable conn_err_count:int;
dummy_one_byte:string;
}
let create dst_info conn_timeout =
{
dst_info=dst_info;
conn_timeout=conn_timeout;
socket=None;
(* TODO: extract this and conn_err_count to a module *)
last_conn_err_time=None;
conn_err_count=0;
dummy_one_byte=String.create 1
}
let print_unix_error label e fn param =
Printf.eprintf "%s: [%s] [%s] [%s]\n" label (U.error_message e) fn param
let connect t =
let s =
U.socket
(match t.dst_info with INET _ -> U.PF_INET | UNIX _ -> U.PF_UNIX)
U.SOCK_STREAM 0 in
let conn_success () =
t.last_conn_err_time <- None;
t.conn_err_count <- 0;
t.socket <- Some s in
let conn_failed () =
t.last_conn_err_time <- Some (int_of_float (U.time ()));
t.conn_err_count <- t.conn_err_count + 1;
t.socket <- None in
match t.dst_info with
| INET(host, port) -> (
U.setsockopt s U.TCP_NODELAY true;
U.set_close_on_exec s;
let server_addresses =
Array.to_list((U.gethostbyname host).U.h_addr_list) in
try (
ignore (
List.find (
fun addr ->
try (
U.connect s (U.ADDR_INET(addr, port));
true
)
with U.Unix_error (e, fn, p) -> (
print_unix_error "connect error" e fn p;
false
)
) server_addresses
);
conn_success ()
)
with Not_found -> conn_failed ()
)
| UNIX(path) ->
try (
U.connect s (U.ADDR_UNIX(path));
conn_success ()
)
with U.Unix_error (e, fn, p) -> (
print_unix_error "connect error" e fn p;
conn_failed ()
)
let connect_if_needed t =
match t.socket with
| Some _ -> ()
| None -> (
match t.last_conn_err_time with
| Some tm -> (
let now = int_of_float (U.time ()) in
let interval =
int_of_float (2.0 ** (float_of_int t.conn_err_count)) in
let max_conn_retain_interval = 60 in
let interval =
if interval < max_conn_retain_interval then interval
else max_conn_retain_interval in
if tm < now - interval then connect t
)
| None -> connect t
)
let close t =
match t.socket with
| Some s -> (
try U.close s
with U.Unix_error (e, fn, p) ->
print_unix_error "close error" e fn p
);
t.socket <- None
| None -> ()
let update_conn t =
match t.socket with
| Some s -> (
U.set_nonblock s;
let connected =
try U.read s t.dummy_one_byte 0 1 != 0
with
| U.Unix_error (U.EAGAIN, _, _) -> true
| _ -> false
in (
U.clear_nonblock s;
if not connected then close t
)
)
| None -> ()
let write t buf start offset =
update_conn t;
connect_if_needed t;
match t.socket with
| Some s -> (
try Some (U.single_write s buf start offset)
with U.Unix_error (e, fn, p) -> (
print_unix_error "write error" e fn p;
close t;
None
)
)
| None -> (
prerr_endline "write error: not connected";
close t;
None
)
| null | https://raw.githubusercontent.com/fluent/fluent-logger-ocaml/3905bec43e5bdd40871bf994f0b98c23fa06d5cd/lib/stream_sender.ml | ocaml | TODO: change these ones to immutable
TODO: extract this and conn_err_count to a module | module U = Unix
type dst_info = INET of string * int | UNIX of string
type t = {
dst_info:dst_info;
conn_timeout:int;
mutable socket:U.file_descr option;
mutable last_conn_err_time:int option;
mutable conn_err_count:int;
dummy_one_byte:string;
}
let create dst_info conn_timeout =
{
dst_info=dst_info;
conn_timeout=conn_timeout;
socket=None;
last_conn_err_time=None;
conn_err_count=0;
dummy_one_byte=String.create 1
}
let print_unix_error label e fn param =
Printf.eprintf "%s: [%s] [%s] [%s]\n" label (U.error_message e) fn param
let connect t =
let s =
U.socket
(match t.dst_info with INET _ -> U.PF_INET | UNIX _ -> U.PF_UNIX)
U.SOCK_STREAM 0 in
let conn_success () =
t.last_conn_err_time <- None;
t.conn_err_count <- 0;
t.socket <- Some s in
let conn_failed () =
t.last_conn_err_time <- Some (int_of_float (U.time ()));
t.conn_err_count <- t.conn_err_count + 1;
t.socket <- None in
match t.dst_info with
| INET(host, port) -> (
U.setsockopt s U.TCP_NODELAY true;
U.set_close_on_exec s;
let server_addresses =
Array.to_list((U.gethostbyname host).U.h_addr_list) in
try (
ignore (
List.find (
fun addr ->
try (
U.connect s (U.ADDR_INET(addr, port));
true
)
with U.Unix_error (e, fn, p) -> (
print_unix_error "connect error" e fn p;
false
)
) server_addresses
);
conn_success ()
)
with Not_found -> conn_failed ()
)
| UNIX(path) ->
try (
U.connect s (U.ADDR_UNIX(path));
conn_success ()
)
with U.Unix_error (e, fn, p) -> (
print_unix_error "connect error" e fn p;
conn_failed ()
)
let connect_if_needed t =
match t.socket with
| Some _ -> ()
| None -> (
match t.last_conn_err_time with
| Some tm -> (
let now = int_of_float (U.time ()) in
let interval =
int_of_float (2.0 ** (float_of_int t.conn_err_count)) in
let max_conn_retain_interval = 60 in
let interval =
if interval < max_conn_retain_interval then interval
else max_conn_retain_interval in
if tm < now - interval then connect t
)
| None -> connect t
)
let close t =
match t.socket with
| Some s -> (
try U.close s
with U.Unix_error (e, fn, p) ->
print_unix_error "close error" e fn p
);
t.socket <- None
| None -> ()
let update_conn t =
match t.socket with
| Some s -> (
U.set_nonblock s;
let connected =
try U.read s t.dummy_one_byte 0 1 != 0
with
| U.Unix_error (U.EAGAIN, _, _) -> true
| _ -> false
in (
U.clear_nonblock s;
if not connected then close t
)
)
| None -> ()
let write t buf start offset =
update_conn t;
connect_if_needed t;
match t.socket with
| Some s -> (
try Some (U.single_write s buf start offset)
with U.Unix_error (e, fn, p) -> (
print_unix_error "write error" e fn p;
close t;
None
)
)
| None -> (
prerr_endline "write error: not connected";
close t;
None
)
|
681dd700e0050367af61383eb07c6a867f36d018bf6d540c98d7e28863856865 | hstreamdb/hstream | Compression.hs | module HStream.Utils.Compression
( decompress
, compress
)
where
import qualified Codec.Compression.GZip as GZ
import qualified Codec.Compression.Zstd as Z
import Control.Exception (throw)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Proto3.Suite (Enumerated (..))
import HStream.Exception
import HStream.Server.HStreamApi (CompressionType (..))
getCompressionType :: Enumerated CompressionType -> Either String CompressionType
getCompressionType tp = case tp of
(Enumerated (Right CompressionTypeGzip)) -> Right CompressionTypeGzip
(Enumerated (Right CompressionTypeNone)) -> Right CompressionTypeNone
(Enumerated (Right CompressionTypeZstd)) -> Right CompressionTypeZstd
_ -> Left "unknown type"
decompress :: Enumerated CompressionType -> BS.ByteString -> BSL.ByteString
decompress tp payload =
let compressTp = getCompressionType tp
in case compressTp of
Right CompressionTypeGzip -> GZ.decompress . BSL.fromStrict $ payload
Right CompressionTypeNone -> BSL.fromStrict payload
Right CompressionTypeZstd -> case Z.decompress payload of
Z.Skip -> BSL.empty
Z.Error e -> throw $ ZstdCompresstionErr (show e)
Z.Decompress s -> BSL.fromStrict s
Left _ -> throw UnknownCompressionType
compress :: Enumerated CompressionType -> BSL.ByteString -> BS.ByteString
compress tp payload =
let compressTp = getCompressionType tp
in case compressTp of
Right CompressionTypeGzip -> BSL.toStrict $ GZ.compress payload
Right CompressionTypeNone -> BSL.toStrict payload
Right CompressionTypeZstd -> Z.compress 1 $ BSL.toStrict payload
Left _ -> throw UnknownCompressionType
| null | https://raw.githubusercontent.com/hstreamdb/hstream/125d9982d47874aee5e33324b55689d64bd664c2/common/hstream/HStream/Utils/Compression.hs | haskell | module HStream.Utils.Compression
( decompress
, compress
)
where
import qualified Codec.Compression.GZip as GZ
import qualified Codec.Compression.Zstd as Z
import Control.Exception (throw)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Proto3.Suite (Enumerated (..))
import HStream.Exception
import HStream.Server.HStreamApi (CompressionType (..))
getCompressionType :: Enumerated CompressionType -> Either String CompressionType
getCompressionType tp = case tp of
(Enumerated (Right CompressionTypeGzip)) -> Right CompressionTypeGzip
(Enumerated (Right CompressionTypeNone)) -> Right CompressionTypeNone
(Enumerated (Right CompressionTypeZstd)) -> Right CompressionTypeZstd
_ -> Left "unknown type"
decompress :: Enumerated CompressionType -> BS.ByteString -> BSL.ByteString
decompress tp payload =
let compressTp = getCompressionType tp
in case compressTp of
Right CompressionTypeGzip -> GZ.decompress . BSL.fromStrict $ payload
Right CompressionTypeNone -> BSL.fromStrict payload
Right CompressionTypeZstd -> case Z.decompress payload of
Z.Skip -> BSL.empty
Z.Error e -> throw $ ZstdCompresstionErr (show e)
Z.Decompress s -> BSL.fromStrict s
Left _ -> throw UnknownCompressionType
compress :: Enumerated CompressionType -> BSL.ByteString -> BS.ByteString
compress tp payload =
let compressTp = getCompressionType tp
in case compressTp of
Right CompressionTypeGzip -> BSL.toStrict $ GZ.compress payload
Right CompressionTypeNone -> BSL.toStrict payload
Right CompressionTypeZstd -> Z.compress 1 $ BSL.toStrict payload
Left _ -> throw UnknownCompressionType
| |
f4fcfbfe196842dd1f486ff077dddf150630f2676b4f83bea017e95a91beb089 | EveryTian/Haskell-Codewars | beginner-lost-without-a-map.hs | -- -lost-without-a-map
module Codewars.Kata.LostWithout where
maps :: [Int] -> [Int]
maps = map (* 2)
| null | https://raw.githubusercontent.com/EveryTian/Haskell-Codewars/dc48d95c676ce1a59f697d07672acb6d4722893b/8kyu/beginner-lost-without-a-map.hs | haskell | -lost-without-a-map |
module Codewars.Kata.LostWithout where
maps :: [Int] -> [Int]
maps = map (* 2)
|
7f2e668d4599ec1b825cfe6fd330fcdd57540b0e884429b919fd6b5d57ef8ca2 | Quid2/zm | Flat.hs | {-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE StandaloneDeriving #
module Test.E.Flat() where
import Flat
import Flat.Decoder()
import Flat.Encoder()
import Test.E
t = putStrLn $ gen 4
-- Test only, incorrect instances
-- Not faster than generated ones (at least up to E16)
gen :: Int -> String
gen numBits =
let dt = "E"++show n
n = 2 ^ numBits
cs = zip [1..] $ map ((\n -> dt ++ "_" ++ n) . show) [1 .. n]
dec n c = unwords [" ",n,"-> return",c]
in unlines [
unwords ["instance Flat",dt,"where"]
," size _ n = n+"++ show numBits
," encode a = case a of"
,unlines $ map (\(n,c) -> unwords [" ",c,"-> eBits16",show numBits,show n]) cs
," decode = do"
," tag <- dBEBits8 " ++ show numBits
," case tag of"
,unlines $ map (\(n,c) -> dec (show n) c) cs
,dec "_" (snd $ last cs)
]
deriving instance Flat S3
deriving instance Flat E2
deriving instance Flat E3
deriving instance Flat E4
deriving instance Flat E8
deriving instance Flat E16
deriving instance Flat E17
deriving instance Flat E32
#ifdef ENUM_LARGE
deriving instance Flat E256
deriving instance Flat E258
#endif
-- fs =
[ flat
, flat E4_1
, flat E8_1
, flat E16_1
-- , flat E32_1
, flat E256_255
-- , flat E256_254
-- , flat E256_253
, flat E256_256
-- ]
| null | https://raw.githubusercontent.com/Quid2/zm/02c0514777a75ac054bfd6251edd884372faddea/test/Test/E/Flat.hs | haskell | # LANGUAGE CPP #
# LANGUAGE DeriveAnyClass #
Test only, incorrect instances
Not faster than generated ones (at least up to E16)
fs =
, flat E32_1
, flat E256_254
, flat E256_253
] | # LANGUAGE StandaloneDeriving #
module Test.E.Flat() where
import Flat
import Flat.Decoder()
import Flat.Encoder()
import Test.E
t = putStrLn $ gen 4
gen :: Int -> String
gen numBits =
let dt = "E"++show n
n = 2 ^ numBits
cs = zip [1..] $ map ((\n -> dt ++ "_" ++ n) . show) [1 .. n]
dec n c = unwords [" ",n,"-> return",c]
in unlines [
unwords ["instance Flat",dt,"where"]
," size _ n = n+"++ show numBits
," encode a = case a of"
,unlines $ map (\(n,c) -> unwords [" ",c,"-> eBits16",show numBits,show n]) cs
," decode = do"
," tag <- dBEBits8 " ++ show numBits
," case tag of"
,unlines $ map (\(n,c) -> dec (show n) c) cs
,dec "_" (snd $ last cs)
]
deriving instance Flat S3
deriving instance Flat E2
deriving instance Flat E3
deriving instance Flat E4
deriving instance Flat E8
deriving instance Flat E16
deriving instance Flat E17
deriving instance Flat E32
#ifdef ENUM_LARGE
deriving instance Flat E256
deriving instance Flat E258
#endif
[ flat
, flat E4_1
, flat E8_1
, flat E16_1
, flat E256_255
, flat E256_256
|
dc5d5438d327cd3d0f81a81996fa69f5aac84be95143e7a9db26442787cfcefe | stackbuilders/cis194-templates | AParser.hs | # LANGUAGE InstanceSigs #
----------------------------------------------------------------------
-- |
--
CIS 194 Spring 2013 : Homework 10
--
----------------------------------------------------------------------
module Homework10.AParser where
-- base
import Control.Applicative
import Data.Char
newtype Parser a =
Parser { runParser :: String -> Maybe (a, String) }
-- |
--
> > > runParser ( satisfy isUpper ) " ABC "
-- Just ('A',"BC")
> > > runParser ( satisfy isUpper ) " abc "
-- Nothing
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
where
f [] = Nothing
f (x:xs)
| p x = Just (x, xs)
| otherwise = Nothing
-- |
--
-- >>> runParser (char 'x') "xyz"
-- Just ('x',"yz")
char :: Char -> Parser Char
char c = satisfy (== c)
posInt :: Parser Integer
posInt = Parser f
where
f xs
| null ns = Nothing
| otherwise = Just (read ns, rest)
where (ns, rest) = span isDigit xs
----------------------------------------------------------------------
Exercise 1
----------------------------------------------------------------------
instance Functor Parser where
fmap :: (a -> b) -> Parser a -> Parser b
fmap = undefined
first :: (a -> b) -> (a, c) -> (b, c)
first = undefined
----------------------------------------------------------------------
Exercise 2
----------------------------------------------------------------------
instance Applicative Parser where
pure :: a -> Parser a
pure = undefined
(<*>) :: Parser (a -> b) -> Parser a -> Parser b
(<*>) = undefined
----------------------------------------------------------------------
Exercise 3
----------------------------------------------------------------------
-- |
--
> > > " abcdef "
-- Just (('a','b'),"cdef")
> > > " aebcdf "
-- Nothing
abParser :: Parser (Char, Char)
abParser = undefined
-- |
--
> > > _ " abcdef "
Just ( ( ) , " " )
> > > _ " aebcdf "
-- Nothing
abParser_ :: Parser ()
abParser_ = undefined
-- |
--
> > > runParser intPair " 12 34 "
-- Just ([12,34],"")
intPair :: Parser [Integer]
intPair = undefined
----------------------------------------------------------------------
Exercise 4
----------------------------------------------------------------------
instance Alternative Parser where
empty :: Parser a
empty = undefined
(<|>) :: Parser a -> Parser a -> Parser a
(<|>) = undefined
----------------------------------------------------------------------
Exercise 5
----------------------------------------------------------------------
-- |
--
> > > runParser intOrUppercase " 342abcd "
-- Just ((),"abcd")
> > > " XYZ "
-- Just ((),"YZ")
> > > " foo "
-- Nothing
intOrUppercase :: Parser ()
intOrUppercase = undefined
| null | https://raw.githubusercontent.com/stackbuilders/cis194-templates/f41b9f0b9945afd387f433ff40fa8988b6a9fe8b/src/Homework10/AParser.hs | haskell | --------------------------------------------------------------------
|
--------------------------------------------------------------------
base
|
Just ('A',"BC")
Nothing
|
>>> runParser (char 'x') "xyz"
Just ('x',"yz")
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
|
Just (('a','b'),"cdef")
Nothing
|
Nothing
|
Just ([12,34],"")
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
|
Just ((),"abcd")
Just ((),"YZ")
Nothing | # LANGUAGE InstanceSigs #
CIS 194 Spring 2013 : Homework 10
module Homework10.AParser where
import Control.Applicative
import Data.Char
newtype Parser a =
Parser { runParser :: String -> Maybe (a, String) }
> > > runParser ( satisfy isUpper ) " ABC "
> > > runParser ( satisfy isUpper ) " abc "
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = Parser f
where
f [] = Nothing
f (x:xs)
| p x = Just (x, xs)
| otherwise = Nothing
char :: Char -> Parser Char
char c = satisfy (== c)
posInt :: Parser Integer
posInt = Parser f
where
f xs
| null ns = Nothing
| otherwise = Just (read ns, rest)
where (ns, rest) = span isDigit xs
Exercise 1
instance Functor Parser where
fmap :: (a -> b) -> Parser a -> Parser b
fmap = undefined
first :: (a -> b) -> (a, c) -> (b, c)
first = undefined
Exercise 2
instance Applicative Parser where
pure :: a -> Parser a
pure = undefined
(<*>) :: Parser (a -> b) -> Parser a -> Parser b
(<*>) = undefined
Exercise 3
> > > " abcdef "
> > > " aebcdf "
abParser :: Parser (Char, Char)
abParser = undefined
> > > _ " abcdef "
Just ( ( ) , " " )
> > > _ " aebcdf "
abParser_ :: Parser ()
abParser_ = undefined
> > > runParser intPair " 12 34 "
intPair :: Parser [Integer]
intPair = undefined
Exercise 4
instance Alternative Parser where
empty :: Parser a
empty = undefined
(<|>) :: Parser a -> Parser a -> Parser a
(<|>) = undefined
Exercise 5
> > > runParser intOrUppercase " 342abcd "
> > > " XYZ "
> > > " foo "
intOrUppercase :: Parser ()
intOrUppercase = undefined
|
64aaf4258cbb567c7a9d1e16df570dff3355a919d0ef92023e9a3b5b9919cdb2 | silkapp/rest | Util.hs | module Rest.StringMap.Util
( pickleStringMap
, pickleMap
, mapSchema
) where
import Data.JSON.Schema (JSONSchema, Schema (Map), schema)
import Data.Proxy (Proxy)
import Data.String (IsString (..))
import Data.String.ToString (ToString (..))
import Text.XML.HXT.Arrow.Pickle (PU, XmlPickler, xpElem, xpList, xpPair, xpTextAttr, xpWrap, xpickle)
pickleStringMap :: XmlPickler b => ([(String, b)] -> m) -> (m -> [(String, b)]) -> PU m
pickleStringMap fromList toList =
xpElem "map"
$ xpWrap (fromList, toList)
$ xpList (xpElem "value" (xpPair (xpTextAttr "key") xpickle))
pickleMap :: (XmlPickler m, ToString k, IsString k) => ((String -> k) -> m -> m') -> ((k -> String) -> m' -> m) -> PU m'
pickleMap mapKeys mapKeys' = xpWrap (mapKeys fromString, mapKeys' toString) xpickle
mapSchema :: JSONSchema a => Proxy a -> Schema
mapSchema = Map . schema
| null | https://raw.githubusercontent.com/silkapp/rest/f0462fc36709407f236f57064d8e37c77bdf8a79/rest-stringmap/src/Rest/StringMap/Util.hs | haskell | module Rest.StringMap.Util
( pickleStringMap
, pickleMap
, mapSchema
) where
import Data.JSON.Schema (JSONSchema, Schema (Map), schema)
import Data.Proxy (Proxy)
import Data.String (IsString (..))
import Data.String.ToString (ToString (..))
import Text.XML.HXT.Arrow.Pickle (PU, XmlPickler, xpElem, xpList, xpPair, xpTextAttr, xpWrap, xpickle)
pickleStringMap :: XmlPickler b => ([(String, b)] -> m) -> (m -> [(String, b)]) -> PU m
pickleStringMap fromList toList =
xpElem "map"
$ xpWrap (fromList, toList)
$ xpList (xpElem "value" (xpPair (xpTextAttr "key") xpickle))
pickleMap :: (XmlPickler m, ToString k, IsString k) => ((String -> k) -> m -> m') -> ((k -> String) -> m' -> m) -> PU m'
pickleMap mapKeys mapKeys' = xpWrap (mapKeys fromString, mapKeys' toString) xpickle
mapSchema :: JSONSchema a => Proxy a -> Schema
mapSchema = Map . schema
| |
6ea4f12e1fe550d869578e4e269d9721b5cff6402ca629269847cbda6c24b8e6 | fakedata-haskell/fakedata | Adjective.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Faker.Provider.Adjective where
import Config
import Control.Monad.Catch
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Monoid ((<>))
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseAdjective :: FromJSON a => FakerSettings -> Value -> Parser a
parseAdjective settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
adjective <- faker .: "adjective"
pure adjective
parseAdjective settings val = fail $ "expected Object, but got " <> (show val)
parseAdjectiveField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseAdjectiveField settings txt val = do
adjective <- parseAdjective settings val
field <- adjective .:? txt .!= mempty
pure field
parseAdjectiveFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseAdjectiveFields settings txts val = do
adjective <- parseAdjective settings val
helper adjective 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)
parseUnresolvedAdjectiveFields ::
(FromJSON a, Monoid a)
=> FakerSettings
-> [AesonKey]
-> Value
-> Parser (Unresolved a)
parseUnresolvedAdjectiveFields settings txts val = do
adjective <- parseAdjective settings val
helper adjective txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser (Unresolved a)
helper a [] = do
v <- parseJSON a
pure $ pure v
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a _ = fail $ "expect Object, but got " <> (show a)
$(genParser "adjective" "positive")
$(genProvider "adjective" "positive")
$(genParser "adjective" "negative")
$(genProvider "adjective" "negative")
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/Adjective.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.Provider.Adjective where
import Config
import Control.Monad.Catch
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Monoid ((<>))
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseAdjective :: FromJSON a => FakerSettings -> Value -> Parser a
parseAdjective settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
adjective <- faker .: "adjective"
pure adjective
parseAdjective settings val = fail $ "expected Object, but got " <> (show val)
parseAdjectiveField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseAdjectiveField settings txt val = do
adjective <- parseAdjective settings val
field <- adjective .:? txt .!= mempty
pure field
parseAdjectiveFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseAdjectiveFields settings txts val = do
adjective <- parseAdjective settings val
helper adjective 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)
parseUnresolvedAdjectiveFields ::
(FromJSON a, Monoid a)
=> FakerSettings
-> [AesonKey]
-> Value
-> Parser (Unresolved a)
parseUnresolvedAdjectiveFields settings txts val = do
adjective <- parseAdjective settings val
helper adjective txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser (Unresolved a)
helper a [] = do
v <- parseJSON a
pure $ pure v
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a _ = fail $ "expect Object, but got " <> (show a)
$(genParser "adjective" "positive")
$(genProvider "adjective" "positive")
$(genParser "adjective" "negative")
$(genProvider "adjective" "negative")
|
eb6ccfe37060efc6c187d95ae609699e092f742b3140fdf3fe1a8b7c8404c05e | DevExpress/gimp-dx-screenshot | dx-screenshot.scm | (define (script-fu-dx-screenshotv2 image
drawable
drop-shadow
shadow-distance
shadow-angle
shadow-blur
shadow-color
shadow-opacity
amplitude
reverse-phase
scale-percent
erase-top-corners
erase-bottom-corners
radius
flatten
background-color
)
(let* (
(shadow-blur (max shadow-blur 0))
(shadow-opacity (min shadow-opacity 100))
(shadow-opacity (max shadow-opacity 0))
(type (car (gimp-drawable-type-with-alpha drawable)))
(image-width (car (gimp-image-width image)))
(image-height (car (gimp-image-height image)))
(from-selection 0)
(active-selection 0)
(shadow-layer 0)
(points 0)
(point 0)
(shadow-transl-y (* shadow-distance (sin (/ (- 180 shadow-angle) 57.32))))
(shadow-transl-x (* shadow-distance (cos (/ (- 180 shadow-angle) 57.32))))
(diam (* radius 2))
(sel-exists FALSE)
(x1 0)
(y1 0)
(x2 0)
(y2 0)
(x 0)
(y 0)
(phase 0)
)
(gimp-context-push)
(gimp-image-set-active-layer image drawable)
(gimp-image-undo-group-start image)
(gimp-layer-add-alpha drawable)
;wave cropper prepare code begin
(set! sel-exists (car (gimp-selection-bounds image)))
(if (= sel-exists TRUE)
(begin
(set! x1 (car (cdr (gimp-selection-bounds image))))
(set! y1 (car (cdr (cdr (gimp-selection-bounds image)))))
(set! x2 (car (cdr (cdr (cdr (gimp-selection-bounds image))))))
(set! y2 (car (cdr (cdr (cdr (cdr (gimp-selection-bounds image)))))))
remove selection if one exists
(set! points (cons-array (* (+ (* 2 (- x2 x1)) (* 2 (- y2 y1))) 2) 'double)) ; amount of points for points array
(set! x x1)
(set! y y1)
(set! amplitude (/ amplitude 200))
(if (= reverse-phase TRUE) (set! phase 3.1415))
; moving from top-left to top-right
(while (< x x2)
(aset points point x) ;x
(set! point (+ point 1))
(if (> y1 0)
(aset points point (+ y1 (* (* (- x2 x1) amplitude ) (sin (+ phase (* 6.2832 (/ (- x x1) (- x2 x1)))))))) ;y
)
(if (<= y1 0)
(aset points point 0) ;y
)
(set! point (+ point 1))
(set! x (+ x 1))
)
; moving from top-right to bottom-right
(while (< y y2)
(if (< x2 image-width)
(aset points point (+ x2 (* (* (- y2 y1) amplitude) (sin (+ phase (* -6.2832 (/ (- y y1) (- y2 y1)))))))) ;x
)
(if (>= x2 image-width)
(aset points point image-width) ;x
)
(set! point (+ point 1))
(aset points point y) ;y
(set! point (+ point 1))
(set! y (+ y 1))
)
; moving from bottom-right to bottom-left
(while (> x x1)
(aset points point x) ;x
(set! point (+ point 1))
(if (< y2 image-height)
(aset points point (+ y2 (* (* (- x2 x1) amplitude) (sin (+ phase (* 6.2832 (/ (- x x1) (- x2 x1)))))))) ;y
)
(if (>= y2 image-height)
(aset points point image-height)
)
(set! point (+ point 1))
(set! x (- x 1))
)
; moving from bottom-left to top-right
(while (> y y1)
(if (> x1 0)
(aset points point (+ x1 (* (* (- y2 y1) amplitude) (sin (+ phase (* -6.2832 (/ (- y y1) (- y2 y1))))))))
)
(if (<= x1 0)
(aset points point 0)
)
(set! point (+ point 1))
(aset points point y)
(set! point (+ point 1))
(set! y (- y 1))
)
;(gimp-pencil drawable point points)
)
)
;wave cropper prepare code end
remove selection if one exists
;eraser code begin
(if (= erase-top-corners TRUE)
(begin
(gimp-image-select-rectangle image CHANNEL-OP-ADD 0 0 radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT 0 0 diam diam)
(gimp-image-select-rectangle image CHANNEL-OP-ADD (- image-width radius) 0 radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT (- image-width diam) 0 diam diam)
(gimp-edit-clear drawable)
(gimp-selection-none image)
)
)
(if (= erase-bottom-corners TRUE)
(begin
(gimp-image-select-rectangle image CHANNEL-OP-ADD 0 (- image-height radius) radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT 0 (- image-height diam) diam diam)
(gimp-image-select-rectangle image CHANNEL-OP-ADD (- image-width radius) (- image-height radius) radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT (- image-width diam) (- image-height diam) diam diam)
(gimp-edit-clear drawable)
(gimp-selection-none image)
)
)
;eraser code end
crooper main code
(if (= sel-exists TRUE)
(begin
;(gimp-pencil drawable point points)
(gimp-image-select-polygon image CHANNEL-OP-ADD point points)
(gimp-selection-invert image)
(gimp-edit-clear drawable)
(gimp-selection-none image)
(plug-in-autocrop 1 image drawable)
)
)
;end of cropper main code
;resizer code begin
(if (< scale-percent 100)
(begin
(set! image-width (car (gimp-image-width image))) ; re-get wodth ang height
(set! image-height (car (gimp-image-height image))) ; for further resizing
(plug-in-sharpen 1 image drawable 30) ; sharpen before scale
(set! image-width (* (/ scale-percent 100) image-width))
(set! image-height (* (/ scale-percent 100) image-height))
- LANCZOS ( 3 )
(plug-in-gauss 1 image drawable 0.3 0.3 0)
)
)
;resizer code end
;SHADOW CODE
(if (= drop-shadow TRUE)
(script-fu-drop-shadow image
drawable
shadow-transl-x
shadow-transl-y
shadow-blur
shadow-color
shadow-opacity
TRUE)
)
;SHADOW CODE END
FLATTEN CODE
(if (= flatten TRUE)
(begin
(gimp-context-set-background background-color)
(gimp-image-flatten image)
(gimp-image-convert-indexed image 0 0 256 FALSE FALSE "")
)
)
;END
(gimp-image-undo-group-end image)
(gimp-displays-flush)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-dx-screenshotv2"
_"_Screenshot processing..."
_"Erases XP/Vista style window corners, makes wavy crop, adds shadow, flattens image and converts it to 256 indexed colors."
"Konstantin Beliakov <>"
"Developer Express Inc."
"2009/10/19"
"RGB* GRAY*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-TOGGLE _"Drop shadow" TRUE
SF-ADJUSTMENT _"Shadow distance (0-20 pixels)" '(5 0 20 1 10 0 )
SF-ADJUSTMENT _"Shadow angle (0-360 degrees)" '(120 0 360 1 10 0 0)
SF-ADJUSTMENT _"Shadow blur radius (0-40 pixels)" '(10 0 40 1 10 0 0)
SF-COLOR _"Shadow color" "black"
SF-ADJUSTMENT _"Shadow opacity (0-100%)" '(40 0 100 1 10 0 0)
SF-ADJUSTMENT _"Waves strength (0 - calm, 10 - tsunami)" '(3 0 10 1 0 0)
SF-TOGGLE _"Reverse wave phase" FALSE
SF-ADJUSTMENT _"Reduce image size (50-100%)" '(100 50 100 1 10 0 0)
SF-TOGGLE _"Erase upper corners" FALSE
SF-TOGGLE _"Erase bottom corners" FALSE
SF-ADJUSTMENT _"Corner radius (0-20 pixels)" '(7 0 20 1 10 0 0)
SF-TOGGLE _"Flatten image and convert to 256 indexed colors" FALSE
SF-COLOR _"Background color for flat image" "white"
)
(script-fu-menu-register "script-fu-dx-screenshotv2"
"<Image>/DX")
| null | https://raw.githubusercontent.com/DevExpress/gimp-dx-screenshot/a691687e24b18ce8d0c6d0ec78933bcd56ae3492/dx-screenshot.scm | scheme | wave cropper prepare code begin
amount of points for points array
moving from top-left to top-right
x
y
y
moving from top-right to bottom-right
x
x
y
moving from bottom-right to bottom-left
x
y
moving from bottom-left to top-right
(gimp-pencil drawable point points)
wave cropper prepare code end
eraser code begin
eraser code end
(gimp-pencil drawable point points)
end of cropper main code
resizer code begin
re-get wodth ang height
for further resizing
sharpen before scale
resizer code end
SHADOW CODE
SHADOW CODE END
END | (define (script-fu-dx-screenshotv2 image
drawable
drop-shadow
shadow-distance
shadow-angle
shadow-blur
shadow-color
shadow-opacity
amplitude
reverse-phase
scale-percent
erase-top-corners
erase-bottom-corners
radius
flatten
background-color
)
(let* (
(shadow-blur (max shadow-blur 0))
(shadow-opacity (min shadow-opacity 100))
(shadow-opacity (max shadow-opacity 0))
(type (car (gimp-drawable-type-with-alpha drawable)))
(image-width (car (gimp-image-width image)))
(image-height (car (gimp-image-height image)))
(from-selection 0)
(active-selection 0)
(shadow-layer 0)
(points 0)
(point 0)
(shadow-transl-y (* shadow-distance (sin (/ (- 180 shadow-angle) 57.32))))
(shadow-transl-x (* shadow-distance (cos (/ (- 180 shadow-angle) 57.32))))
(diam (* radius 2))
(sel-exists FALSE)
(x1 0)
(y1 0)
(x2 0)
(y2 0)
(x 0)
(y 0)
(phase 0)
)
(gimp-context-push)
(gimp-image-set-active-layer image drawable)
(gimp-image-undo-group-start image)
(gimp-layer-add-alpha drawable)
(set! sel-exists (car (gimp-selection-bounds image)))
(if (= sel-exists TRUE)
(begin
(set! x1 (car (cdr (gimp-selection-bounds image))))
(set! y1 (car (cdr (cdr (gimp-selection-bounds image)))))
(set! x2 (car (cdr (cdr (cdr (gimp-selection-bounds image))))))
(set! y2 (car (cdr (cdr (cdr (cdr (gimp-selection-bounds image)))))))
remove selection if one exists
(set! x x1)
(set! y y1)
(set! amplitude (/ amplitude 200))
(if (= reverse-phase TRUE) (set! phase 3.1415))
(while (< x x2)
(set! point (+ point 1))
(if (> y1 0)
)
(if (<= y1 0)
)
(set! point (+ point 1))
(set! x (+ x 1))
)
(while (< y y2)
(if (< x2 image-width)
)
(if (>= x2 image-width)
)
(set! point (+ point 1))
(set! point (+ point 1))
(set! y (+ y 1))
)
(while (> x x1)
(set! point (+ point 1))
(if (< y2 image-height)
)
(if (>= y2 image-height)
(aset points point image-height)
)
(set! point (+ point 1))
(set! x (- x 1))
)
(while (> y y1)
(if (> x1 0)
(aset points point (+ x1 (* (* (- y2 y1) amplitude) (sin (+ phase (* -6.2832 (/ (- y y1) (- y2 y1))))))))
)
(if (<= x1 0)
(aset points point 0)
)
(set! point (+ point 1))
(aset points point y)
(set! point (+ point 1))
(set! y (- y 1))
)
)
)
remove selection if one exists
(if (= erase-top-corners TRUE)
(begin
(gimp-image-select-rectangle image CHANNEL-OP-ADD 0 0 radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT 0 0 diam diam)
(gimp-image-select-rectangle image CHANNEL-OP-ADD (- image-width radius) 0 radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT (- image-width diam) 0 diam diam)
(gimp-edit-clear drawable)
(gimp-selection-none image)
)
)
(if (= erase-bottom-corners TRUE)
(begin
(gimp-image-select-rectangle image CHANNEL-OP-ADD 0 (- image-height radius) radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT 0 (- image-height diam) diam diam)
(gimp-image-select-rectangle image CHANNEL-OP-ADD (- image-width radius) (- image-height radius) radius radius)
(gimp-image-select-ellipse image CHANNEL-OP-SUBTRACT (- image-width diam) (- image-height diam) diam diam)
(gimp-edit-clear drawable)
(gimp-selection-none image)
)
)
crooper main code
(if (= sel-exists TRUE)
(begin
(gimp-image-select-polygon image CHANNEL-OP-ADD point points)
(gimp-selection-invert image)
(gimp-edit-clear drawable)
(gimp-selection-none image)
(plug-in-autocrop 1 image drawable)
)
)
(if (< scale-percent 100)
(begin
(set! image-width (* (/ scale-percent 100) image-width))
(set! image-height (* (/ scale-percent 100) image-height))
- LANCZOS ( 3 )
(plug-in-gauss 1 image drawable 0.3 0.3 0)
)
)
(if (= drop-shadow TRUE)
(script-fu-drop-shadow image
drawable
shadow-transl-x
shadow-transl-y
shadow-blur
shadow-color
shadow-opacity
TRUE)
)
FLATTEN CODE
(if (= flatten TRUE)
(begin
(gimp-context-set-background background-color)
(gimp-image-flatten image)
(gimp-image-convert-indexed image 0 0 256 FALSE FALSE "")
)
)
(gimp-image-undo-group-end image)
(gimp-displays-flush)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-dx-screenshotv2"
_"_Screenshot processing..."
_"Erases XP/Vista style window corners, makes wavy crop, adds shadow, flattens image and converts it to 256 indexed colors."
"Konstantin Beliakov <>"
"Developer Express Inc."
"2009/10/19"
"RGB* GRAY*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-TOGGLE _"Drop shadow" TRUE
SF-ADJUSTMENT _"Shadow distance (0-20 pixels)" '(5 0 20 1 10 0 )
SF-ADJUSTMENT _"Shadow angle (0-360 degrees)" '(120 0 360 1 10 0 0)
SF-ADJUSTMENT _"Shadow blur radius (0-40 pixels)" '(10 0 40 1 10 0 0)
SF-COLOR _"Shadow color" "black"
SF-ADJUSTMENT _"Shadow opacity (0-100%)" '(40 0 100 1 10 0 0)
SF-ADJUSTMENT _"Waves strength (0 - calm, 10 - tsunami)" '(3 0 10 1 0 0)
SF-TOGGLE _"Reverse wave phase" FALSE
SF-ADJUSTMENT _"Reduce image size (50-100%)" '(100 50 100 1 10 0 0)
SF-TOGGLE _"Erase upper corners" FALSE
SF-TOGGLE _"Erase bottom corners" FALSE
SF-ADJUSTMENT _"Corner radius (0-20 pixels)" '(7 0 20 1 10 0 0)
SF-TOGGLE _"Flatten image and convert to 256 indexed colors" FALSE
SF-COLOR _"Background color for flat image" "white"
)
(script-fu-menu-register "script-fu-dx-screenshotv2"
"<Image>/DX")
|
25f28f9a5a3bcd999b1f3088a732c22cfcbe0c07998a3b90c3c49221b5bda5e8 | ammarhakim/gkylcas | basisTensor1x3v.lisp | ;;; -*- Mode: LISP; package:maxima; syntax:common-lisp; -*-
(in-package :maxima)
(DSKSETQ |$varsC| '((MLIST SIMP) $X))
(ADD2LNC '|$varsC| $VALUES)
(DSKSETQ |$varsP| '((MLIST SIMP) $X $VX $VY $VZ))
(ADD2LNC '|$varsP| $VALUES)
(DSKSETQ |$basisC|
'((MLIST SIMP
(10.
"/Users/JunoRavin/gkyl/cas-scripts/basis-precalc/basis-pre-calc.mac"
SRC |$writeBasisToFile| 7.))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MTIMES SIMP) ((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MTIMES SIMP) ((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X)
((MTIMES SIMP) 3. ((MEXPT SIMP) 2. ((RAT SIMP) -3. 2.))
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
(ADD2LNC '|$basisC| $VALUES)
(DSKSETQ |$basisP|
'((MLIST SIMP
(10.
"/Users/JunoRavin/gkyl/cas-scripts/basis-precalc/basis-pre-calc.mac"
SRC |$writeBasisToFile| 7.))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((RAT SIMP) 1. 4.)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VX)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VY)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VY)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VY $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 9. 4.) $VX $VY $VZ $X))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((RAT SIMP) 1. 4.)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VX)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VY)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VY)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VY $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 4.) $VX $VY $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP) $VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY $VZ)
((MTIMES SIMP) $VX $VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY $X)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP) $VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$VZ)))))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
$X)))))))
((MTIMES SIMP) ((RAT SIMP) 2025. 64.)
((MPLUS SIMP) ((RAT SIMP) -1. 81.)
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))))))))))
(ADD2LNC '|$basisP| $VALUES) | null | https://raw.githubusercontent.com/ammarhakim/gkylcas/1f8adad4f344ce8e3663451e16fdf1c32107ceed/maxima/g2/basis-precalc/basisTensor1x3v.lisp | lisp | -*- Mode: LISP; package:maxima; syntax:common-lisp; -*- | (in-package :maxima)
(DSKSETQ |$varsC| '((MLIST SIMP) $X))
(ADD2LNC '|$varsC| $VALUES)
(DSKSETQ |$varsP| '((MLIST SIMP) $X $VX $VY $VZ))
(ADD2LNC '|$varsP| $VALUES)
(DSKSETQ |$basisC|
'((MLIST SIMP
(10.
"/Users/JunoRavin/gkyl/cas-scripts/basis-precalc/basis-pre-calc.mac"
SRC |$writeBasisToFile| 7.))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MTIMES SIMP) ((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MTIMES SIMP) ((MEXPT SIMP) 2. ((RAT SIMP) -1. 2.))
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X)
((MTIMES SIMP) 3. ((MEXPT SIMP) 2. ((RAT SIMP) -3. 2.))
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
(ADD2LNC '|$basisC| $VALUES)
(DSKSETQ |$basisP|
'((MLIST SIMP
(10.
"/Users/JunoRavin/gkyl/cas-scripts/basis-precalc/basis-pre-calc.mac"
SRC |$writeBasisToFile| 7.))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((RAT SIMP) 1. 4.)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VX)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VY)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VY)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VY $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 9. 4.) $VX $VY $VZ $X))
((MLIST SIMP
(32. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$gsOrthoNorm| 30.))
((RAT SIMP) 1. 4.)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VX)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VY)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 1. 2.)) $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VY)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VX $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 4.) $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VY $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 1. 4.)
((MEXPT SIMP) 3. ((RAT SIMP) 3. 2.)) $VX $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 3. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 4.) $VX $VY $VZ $X)
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP) $VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 5. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 45. 16.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY $VZ)
((MTIMES SIMP) $VX $VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) 9. 8.)
((MEXPT SIMP) 15. ((RAT SIMP) 1. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY $X)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 5. 16.)
((MEXPT SIMP) 3. ((RAT SIMP) 5. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $VZ)
((MTIMES SIMP) $VY $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VZ)
((MTIMES SIMP) $VX $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ $X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ $X)))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $VY)
((MTIMES SIMP) $VX $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY $X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY $X)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 135. 16.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX $X)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) 27. 32.)
((MEXPT SIMP) 5. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$VZ)))))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VZ)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$VZ)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VZ)
((MTIMES SIMP) $VZ
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$VY)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VY)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VY)
((MTIMES SIMP) $VY
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $VX)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $VX)
((MTIMES SIMP) $VX
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))))
((MTIMES SIMP) ((RAT SIMP) 9. 32.)
((MEXPT SIMP) 15. ((RAT SIMP) 3. 2.))
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 27.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
$X)))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 9.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
$X)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
$X)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((MTIMES SIMP) ((RAT SIMP) -1. 3.) $X)
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
$X)))))))
((MTIMES SIMP) ((RAT SIMP) 2025. 64.)
((MPLUS SIMP) ((RAT SIMP) -1. 81.)
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 27.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VX 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 27.)
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 9.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac" SRC
|$calcPowers| 62.))
$X 2.))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VY 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.))))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 9.)
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)))
((MTIMES SIMP) ((RAT SIMP) -1. 3.)
((MPLUS SIMP) ((RAT SIMP) -1. 3.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))
((MTIMES SIMP)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$VZ 2.)
((MEXPT SIMP
(62. "/Users/JunoRavin/gkyl/cas-scripts/modal-basis.mac"
SRC |$calcPowers| 62.))
$X 2.)))))))))))
(ADD2LNC '|$basisP| $VALUES) |
a93ac9d908a7817c5fe55474e0136263ce01d6f999eb841540d53d61377ccd59 | sgbj/MaximaSharp | fdump.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 46c1f6a93b0d 2012/05/03 04:40:28 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
;;; "f2cl5.l,v 46c1f6a93b0d 2012/05/03 04:40:28 toy $"
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v fceac530ef0c 2011/11/26 04:02:26 toy $ " )
Using Lisp CMU Common Lisp snapshot-2012 - 04 ( )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':simple-array)
;;; (:array-slicing nil) (:declare-common nil)
;;; (:float-format double-float))
(in-package :slatec)
(defun fdump () (prog () (declare) (go end_label) end_label (return (values))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::fdump fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo :arg-types 'nil
:return-values 'nil
:calls 'nil)))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/numerical/slatec/fdump.lisp | lisp | Compiled by f2cl version:
"f2cl5.l,v 46c1f6a93b0d 2012/05/03 04:40:28 toy $"
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':simple-array)
(:array-slicing nil) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 46c1f6a93b0d 2012/05/03 04:40:28 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v fceac530ef0c 2011/11/26 04:02:26 toy $ " )
Using Lisp CMU Common Lisp snapshot-2012 - 04 ( )
(in-package :slatec)
(defun fdump () (prog () (declare) (go end_label) end_label (return (values))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::fdump fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo :arg-types 'nil
:return-values 'nil
:calls 'nil)))
|
36686e62518822dad69e3d9904c46f5d1214f0e4cd1d2ea8bcd1cf7bb17f032c | mikera/orculje | materials.clj | (ns mikera.orculje.materials)
;; ========================================================
;; material lists and attributes
(def wood-names ["alder" "applewood" "ash" "balsawood" "beech" "birch" "bloodwood"
"cedar" "cherrywood" "corkwood" "cypress" "elm" "eucalyptus" "gumtree"
"hickory" "hornbeam" "ironwood" "larch" "laurel" "mahogany" "maple" "oak"
"pine" "poplar" "redwood" "rosewood" "sandalwood" "snakewood"
"spruce" "sycamore" "teak" "walnut" "willow"])
(def primary-metal-names ["copper" "iron" "steel" "silver" "titanium"])
(def secondary-metal-names ["gold" "bronze" "platinum"
"nickel" "cobalt" "manganese" "molybdenum" "magnesium"
"tungsten" "zinc" "billion" "brass" "electrum" "rose gold"
"palladium" "tin" "aluminium" "lead"])
(def special-metal-names ["black steel" "red steel" "elvish steel" "dwarven steel"
"krythium" "eternium" "adamantium" "parrilite"])
(def all-metal-names)
(def precious-stone-names ["emerald" "ruby" "sapphire" "diamond" "red diamond"
"starstone" "moonstone" "sunstone"])
(def METALS nil)
(def WOODS
(reduce
(fn [mats name]
(let [mk (keyword name)]
(assoc mats mk {:key mk
:name name
:is-wood true
:material-type :is-wood})))
{} wood-names))
(let [mats (merge WOODS
METALS)]
(def MATERIALS (reduce
(fn [mats [k mat]]
(assoc mats k mat))
mats mats))) | null | https://raw.githubusercontent.com/mikera/orculje/4c7f9af78f9a8744e1ab3aef3ded151306883083/src/main/clojure/mikera/orculje/materials.clj | clojure | ========================================================
material lists and attributes | (ns mikera.orculje.materials)
(def wood-names ["alder" "applewood" "ash" "balsawood" "beech" "birch" "bloodwood"
"cedar" "cherrywood" "corkwood" "cypress" "elm" "eucalyptus" "gumtree"
"hickory" "hornbeam" "ironwood" "larch" "laurel" "mahogany" "maple" "oak"
"pine" "poplar" "redwood" "rosewood" "sandalwood" "snakewood"
"spruce" "sycamore" "teak" "walnut" "willow"])
(def primary-metal-names ["copper" "iron" "steel" "silver" "titanium"])
(def secondary-metal-names ["gold" "bronze" "platinum"
"nickel" "cobalt" "manganese" "molybdenum" "magnesium"
"tungsten" "zinc" "billion" "brass" "electrum" "rose gold"
"palladium" "tin" "aluminium" "lead"])
(def special-metal-names ["black steel" "red steel" "elvish steel" "dwarven steel"
"krythium" "eternium" "adamantium" "parrilite"])
(def all-metal-names)
(def precious-stone-names ["emerald" "ruby" "sapphire" "diamond" "red diamond"
"starstone" "moonstone" "sunstone"])
(def METALS nil)
(def WOODS
(reduce
(fn [mats name]
(let [mk (keyword name)]
(assoc mats mk {:key mk
:name name
:is-wood true
:material-type :is-wood})))
{} wood-names))
(let [mats (merge WOODS
METALS)]
(def MATERIALS (reduce
(fn [mats [k mat]]
(assoc mats k mat))
mats mats))) |
d5aafdabfb42243640a8e9c50af732f07e1de57ab75791e1c627c424fee97e70 | aimyskk/competitive-haskell | BellmanFord.hs | module Graph.BellmanFord (
bellmanFord
) where
import WeightedGraph
import qualified Data.Set as S
import qualified Data.IntMap.Strict as M
type Memo = M.IntMap Weight
bellmanFord :: Graph -> Vertex -> Memo
bellmanFord g s = _bellmanFord g n m0
where
n = size g
m0 = M.singleton s 0
_bellmanFord :: Graph -> Int -> Memo -> Memo
_bellmanFord g n m
| n == 0 = m
| otherwise = _bellmanFord g (pred n) (M.foldrWithKey (move g) m m)
move :: Graph -> Vertex -> Weight -> Memo -> Memo
move g s aw m = S.foldr update m (target g s)
where
update (t, w) acc
| M.notMember t acc || acc M.! t < aw + w = M.insert t (aw + w) acc
| otherwise = acc
| null | https://raw.githubusercontent.com/aimyskk/competitive-haskell/703f78e29060459d8d857d785e473e9696e2d67f/Graph/BellmanFord.hs | haskell | module Graph.BellmanFord (
bellmanFord
) where
import WeightedGraph
import qualified Data.Set as S
import qualified Data.IntMap.Strict as M
type Memo = M.IntMap Weight
bellmanFord :: Graph -> Vertex -> Memo
bellmanFord g s = _bellmanFord g n m0
where
n = size g
m0 = M.singleton s 0
_bellmanFord :: Graph -> Int -> Memo -> Memo
_bellmanFord g n m
| n == 0 = m
| otherwise = _bellmanFord g (pred n) (M.foldrWithKey (move g) m m)
move :: Graph -> Vertex -> Weight -> Memo -> Memo
move g s aw m = S.foldr update m (target g s)
where
update (t, w) acc
| M.notMember t acc || acc M.! t < aw + w = M.insert t (aw + w) acc
| otherwise = acc
| |
3ae65be5d6124a92dc9e196777bb4b71cb690380706116f2cfe61e4837c3ccd0 | tsloughter/kuberl | kuberl_v1beta1_volume_attachment_source.erl | -module(kuberl_v1beta1_volume_attachment_source).
-export([encode/1]).
-export_type([kuberl_v1beta1_volume_attachment_source/0]).
-type kuberl_v1beta1_volume_attachment_source() ::
#{ 'inlineVolumeSpec' => kuberl_v1_persistent_volume_spec:kuberl_v1_persistent_volume_spec(),
'persistentVolumeName' => binary()
}.
encode(#{ 'inlineVolumeSpec' := InlineVolumeSpec,
'persistentVolumeName' := PersistentVolumeName
}) ->
#{ 'inlineVolumeSpec' => InlineVolumeSpec,
'persistentVolumeName' => PersistentVolumeName
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_volume_attachment_source.erl | erlang | -module(kuberl_v1beta1_volume_attachment_source).
-export([encode/1]).
-export_type([kuberl_v1beta1_volume_attachment_source/0]).
-type kuberl_v1beta1_volume_attachment_source() ::
#{ 'inlineVolumeSpec' => kuberl_v1_persistent_volume_spec:kuberl_v1_persistent_volume_spec(),
'persistentVolumeName' => binary()
}.
encode(#{ 'inlineVolumeSpec' := InlineVolumeSpec,
'persistentVolumeName' := PersistentVolumeName
}) ->
#{ 'inlineVolumeSpec' => InlineVolumeSpec,
'persistentVolumeName' => PersistentVolumeName
}.
| |
add6274b2261216e39399d6bbc892c108336f77a9c73c889aab7a6c6cabd1813 | hslua/hslua | test-hslua-packaging.hs | |
Module : Main
Copyright : © 2020 - 2023 : MIT
Maintainer : < tarleb+ >
Tests for hslua - packaging .
Module : Main
Copyright : © 2020-2023 Albert Krewinkel
License : MIT
Maintainer : Albert Krewinkel <tarleb+>
Tests for hslua-packaging.
-}
import Test.Tasty (TestTree, defaultMain, testGroup)
import qualified HsLua.PackagingTests
main :: IO ()
main = defaultMain tests
-- | Lua module packaging tests.
tests :: TestTree
tests = testGroup "Packaging" [HsLua.PackagingTests.tests]
| null | https://raw.githubusercontent.com/hslua/hslua/178c225f3da193f09fc27877a5a30e66eef069fb/hslua-packaging/test/test-hslua-packaging.hs | haskell | | Lua module packaging tests. | |
Module : Main
Copyright : © 2020 - 2023 : MIT
Maintainer : < tarleb+ >
Tests for hslua - packaging .
Module : Main
Copyright : © 2020-2023 Albert Krewinkel
License : MIT
Maintainer : Albert Krewinkel <tarleb+>
Tests for hslua-packaging.
-}
import Test.Tasty (TestTree, defaultMain, testGroup)
import qualified HsLua.PackagingTests
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Packaging" [HsLua.PackagingTests.tests]
|
b139daf9758b020199e906ec0ee2350184c42b424ae268eb0200c3a0d6edb0a1 | yapsterapp/er-cassandra | mock.clj | (ns er-cassandra.session.mock
(:require
[plumbing.core :refer :all]
[taoensso.timbre :refer [trace debug info warn error]]
[clojure.pprint :refer [pprint]]
[manifold.deferred :as d]
[er-cassandra.session :as s])
(:import
[er_cassandra.session Session]))
(defn deferred-value
[v]
(let [d (d/deferred)]
(if (instance? Throwable v)
(d/error! d v)
(d/success! d v))
d))
(defrecord MapMockSession [statement-responses statement-log-atom]
Session
(execute [_ statement opts]
(swap! statement-log-atom conj statement)
(if (contains? statement-responses statement)
(deferred-value
(get statement-responses statement))
(throw (ex-info "no matching response" {:statement statement}))))
(close [_]))
(defn create-map-mock-session
[statement-responses]
(->MapMockSession statement-responses (atom [])))
(defn requirement-match-unordered
[requirement-matchers statement]
(let [i-rms (keep-indexed vector requirement-matchers)
[i-r resp] (some (fn [[i rm]]
(when-let [r (rm statement)]
[i r]))
i-rms)]
(when i-r
[(->> i-rms
(remove (fn [[i rm]] (not= i i-r)))
(map last))
resp])))
(defn requirement-match-ordered
[requirement-matchers statement]
(let [[frm & rem] requirement-matchers
resp (frm statement)]
(when resp
[rem resp])))
(defn find-requirement-match
"match required statements
returns [updated-requirement-matchers response] or nil
if there was no match"
[requirement-matchers statement]
(if (vector? requirement-matchers)
(requirement-match-ordered requirement-matchers statement)
(requirement-match-unordered requirement-matchers statement)))
(defn find-support-match
"match supporting statements
returns response or nil"
[support-matchers statement]
(some (fn [sm] (sm statement))
support-matchers))
;; need a statement-matcher, not just a literal statement...
;; maybe there should be a bunch of "query matchers" and
one or more expectation statements which have to be given
;; for the test to pass
(defrecord MatchMockSession [support-matchers
requirement-matchers-atom
statement-log-atom
response-log-atom
print?]
Session
(execute [_ statement opts]
(swap! statement-log-atom conj statement)
(if-let [[urms resp] (find-requirement-match
@requirement-matchers-atom
statement)]
(do
(reset! requirement-matchers-atom urms)
(swap! response-log-atom conj resp)
(when print? (pprint ["requirement match" statement]))
(deferred-value resp))
(if-let [resp (find-support-match support-matchers statement)]
(do
(swap! response-log-atom conj resp)
(when print? (pprint ["support match" statement]))
(deferred-value resp))
(do
(when print? (pprint ["failed match" statement]))
(throw (ex-info "statment match failed"
{:statement statement
:statement-log @statement-log-atom}))))))
(execute-buffered [this statement opts]
(throw (ex-info "not implemented" {})))
(close [_]
(when (not-empty @requirement-matchers-atom)
(throw (ex-info "some required statements not executed"
{:statement-log @statement-log-atom
:response-log @response-log-atom})))))
(defnk create-match-mock-session
[{support-matchers nil} {requirement-matchers nil} {print? false}]
(map->MatchMockSession
{:support-matchers (flatten support-matchers)
:requirement-matchers-atom (atom (flatten requirement-matchers))
:statement-log-atom (atom [])
:response-log-atom (atom [])
:print? print?}))
| null | https://raw.githubusercontent.com/yapsterapp/er-cassandra/1d059f47bdf8654c7a4dd6f0759f1a114fdeba81/src/er_cassandra/session/mock.clj | clojure | need a statement-matcher, not just a literal statement...
maybe there should be a bunch of "query matchers" and
for the test to pass | (ns er-cassandra.session.mock
(:require
[plumbing.core :refer :all]
[taoensso.timbre :refer [trace debug info warn error]]
[clojure.pprint :refer [pprint]]
[manifold.deferred :as d]
[er-cassandra.session :as s])
(:import
[er_cassandra.session Session]))
(defn deferred-value
[v]
(let [d (d/deferred)]
(if (instance? Throwable v)
(d/error! d v)
(d/success! d v))
d))
(defrecord MapMockSession [statement-responses statement-log-atom]
Session
(execute [_ statement opts]
(swap! statement-log-atom conj statement)
(if (contains? statement-responses statement)
(deferred-value
(get statement-responses statement))
(throw (ex-info "no matching response" {:statement statement}))))
(close [_]))
(defn create-map-mock-session
[statement-responses]
(->MapMockSession statement-responses (atom [])))
(defn requirement-match-unordered
[requirement-matchers statement]
(let [i-rms (keep-indexed vector requirement-matchers)
[i-r resp] (some (fn [[i rm]]
(when-let [r (rm statement)]
[i r]))
i-rms)]
(when i-r
[(->> i-rms
(remove (fn [[i rm]] (not= i i-r)))
(map last))
resp])))
(defn requirement-match-ordered
[requirement-matchers statement]
(let [[frm & rem] requirement-matchers
resp (frm statement)]
(when resp
[rem resp])))
(defn find-requirement-match
"match required statements
returns [updated-requirement-matchers response] or nil
if there was no match"
[requirement-matchers statement]
(if (vector? requirement-matchers)
(requirement-match-ordered requirement-matchers statement)
(requirement-match-unordered requirement-matchers statement)))
(defn find-support-match
"match supporting statements
returns response or nil"
[support-matchers statement]
(some (fn [sm] (sm statement))
support-matchers))
one or more expectation statements which have to be given
(defrecord MatchMockSession [support-matchers
requirement-matchers-atom
statement-log-atom
response-log-atom
print?]
Session
(execute [_ statement opts]
(swap! statement-log-atom conj statement)
(if-let [[urms resp] (find-requirement-match
@requirement-matchers-atom
statement)]
(do
(reset! requirement-matchers-atom urms)
(swap! response-log-atom conj resp)
(when print? (pprint ["requirement match" statement]))
(deferred-value resp))
(if-let [resp (find-support-match support-matchers statement)]
(do
(swap! response-log-atom conj resp)
(when print? (pprint ["support match" statement]))
(deferred-value resp))
(do
(when print? (pprint ["failed match" statement]))
(throw (ex-info "statment match failed"
{:statement statement
:statement-log @statement-log-atom}))))))
(execute-buffered [this statement opts]
(throw (ex-info "not implemented" {})))
(close [_]
(when (not-empty @requirement-matchers-atom)
(throw (ex-info "some required statements not executed"
{:statement-log @statement-log-atom
:response-log @response-log-atom})))))
(defnk create-match-mock-session
[{support-matchers nil} {requirement-matchers nil} {print? false}]
(map->MatchMockSession
{:support-matchers (flatten support-matchers)
:requirement-matchers-atom (atom (flatten requirement-matchers))
:statement-log-atom (atom [])
:response-log-atom (atom [])
:print? print?}))
|
9fb2d1e6fec9db8afd94b8524c134c59cb66f0e69e28b1321f8652891acf6830 | clojure/core.typed | core.clj | (ns clojure.core.typed.test.CTYP-234.core
(:require [clojure.core.typed :as t]
[clojure.core.typed.test.CTYP-234.dep :as other]))
(t/ann foo [other/MyType -> t/AnyInteger])
(defn foo
[x]
(:bar x))
| null | https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/test/clojure/core/typed/test/CTYP_234/core.clj | clojure | (ns clojure.core.typed.test.CTYP-234.core
(:require [clojure.core.typed :as t]
[clojure.core.typed.test.CTYP-234.dep :as other]))
(t/ann foo [other/MyType -> t/AnyInteger])
(defn foo
[x]
(:bar x))
| |
56b394c5c169376cbc03023274c65e25740babf8cbf21c03fb1909bfc635a9aa | b0-system/brzo | dhash.ml |
let md5 = Digestif.MD5.digest_string
| null | https://raw.githubusercontent.com/b0-system/brzo/79d316a5024025a0112a8569a6335241b4620da8/examples/ocaml-amb/dhash.ml | ocaml |
let md5 = Digestif.MD5.digest_string
| |
b5ee8da829592d2ccae5132f26166d3e9da9475ec9f8491f2596b6bb25b2c8d6 | monadfix/ormolu-live | VarSet.hs |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
# LANGUAGE CPP #
module VarSet (
* , I d and TyVar set types
VarSet, IdSet, TyVarSet, CoVarSet, TyCoVarSet,
-- ** Manipulating these sets
emptyVarSet, unitVarSet, mkVarSet,
extendVarSet, extendVarSetList,
elemVarSet, subVarSet,
unionVarSet, unionVarSets, mapUnionVarSet,
intersectVarSet, intersectsVarSet, disjointVarSet,
isEmptyVarSet, delVarSet, delVarSetList, delVarSetByKey,
minusVarSet, filterVarSet, mapVarSet,
anyVarSet, allVarSet,
transCloVarSet, fixVarSet,
lookupVarSet_Directly, lookupVarSet, lookupVarSetByName,
sizeVarSet, seqVarSet,
elemVarSetByKey, partitionVarSet,
pluralVarSet, pprVarSet,
* Deterministic set types
DVarSet, DIdSet, DTyVarSet, DTyCoVarSet,
-- ** Manipulating these sets
emptyDVarSet, unitDVarSet, mkDVarSet,
extendDVarSet, extendDVarSetList,
elemDVarSet, dVarSetElems, subDVarSet,
unionDVarSet, unionDVarSets, mapUnionDVarSet,
intersectDVarSet, dVarSetIntersectVarSet,
intersectsDVarSet, disjointDVarSet,
isEmptyDVarSet, delDVarSet, delDVarSetList,
minusDVarSet, foldDVarSet, filterDVarSet, mapDVarSet,
dVarSetMinusVarSet, anyDVarSet, allDVarSet,
transCloDVarSet,
sizeDVarSet, seqDVarSet,
partitionDVarSet,
dVarSetToVarSet,
) where
#include "HsVersions2.h"
import GhcPrelude
import Var ( Var, TyVar, CoVar, TyCoVar, Id )
import Unique
import Name ( Name )
import UniqSet
import UniqDSet
import UniqFM( disjointUFM, pluralUFM, pprUFM )
import UniqDFM( disjointUDFM, udfmToUfm, anyUDFM, allUDFM )
import Outputable (SDoc)
-- | A non-deterministic Variable Set
--
-- A non-deterministic set of variables.
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why it's not
-- deterministic and why it matters. Use DVarSet if the set eventually
-- gets converted into a list or folded over in a way where the order
-- changes the generated code, for example when abstracting variables.
type VarSet = UniqSet Var
-- | Identifier Set
type IdSet = UniqSet Id
-- | Type Variable Set
type TyVarSet = UniqSet TyVar
-- | Coercion Variable Set
type CoVarSet = UniqSet CoVar
-- | Type or Coercion Variable Set
type TyCoVarSet = UniqSet TyCoVar
emptyVarSet :: VarSet
intersectVarSet :: VarSet -> VarSet -> VarSet
unionVarSet :: VarSet -> VarSet -> VarSet
unionVarSets :: [VarSet] -> VarSet
mapUnionVarSet :: (a -> VarSet) -> [a] -> VarSet
-- ^ map the function over the list, and union the results
unitVarSet :: Var -> VarSet
extendVarSet :: VarSet -> Var -> VarSet
extendVarSetList:: VarSet -> [Var] -> VarSet
elemVarSet :: Var -> VarSet -> Bool
delVarSet :: VarSet -> Var -> VarSet
delVarSetList :: VarSet -> [Var] -> VarSet
minusVarSet :: VarSet -> VarSet -> VarSet
isEmptyVarSet :: VarSet -> Bool
mkVarSet :: [Var] -> VarSet
lookupVarSet_Directly :: VarSet -> Unique -> Maybe Var
lookupVarSet :: VarSet -> Var -> Maybe Var
-- Returns the set element, which may be
-- (==) to the argument, but not the same as
lookupVarSetByName :: VarSet -> Name -> Maybe Var
sizeVarSet :: VarSet -> Int
filterVarSet :: (Var -> Bool) -> VarSet -> VarSet
delVarSetByKey :: VarSet -> Unique -> VarSet
elemVarSetByKey :: Unique -> VarSet -> Bool
partitionVarSet :: (Var -> Bool) -> VarSet -> (VarSet, VarSet)
emptyVarSet = emptyUniqSet
unitVarSet = unitUniqSet
extendVarSet = addOneToUniqSet
extendVarSetList= addListToUniqSet
intersectVarSet = intersectUniqSets
intersectsVarSet:: VarSet -> VarSet -> Bool -- True if non-empty intersection
disjointVarSet :: VarSet -> VarSet -> Bool -- True if empty intersection
True if first arg is subset of second
-- (s1 `intersectsVarSet` s2) doesn't compute s2 if s1 is empty;
-- ditto disjointVarSet, subVarSet
unionVarSet = unionUniqSets
unionVarSets = unionManyUniqSets
elemVarSet = elementOfUniqSet
minusVarSet = minusUniqSet
delVarSet = delOneFromUniqSet
delVarSetList = delListFromUniqSet
isEmptyVarSet = isEmptyUniqSet
mkVarSet = mkUniqSet
lookupVarSet_Directly = lookupUniqSet_Directly
lookupVarSet = lookupUniqSet
lookupVarSetByName = lookupUniqSet
sizeVarSet = sizeUniqSet
filterVarSet = filterUniqSet
delVarSetByKey = delOneFromUniqSet_Directly
elemVarSetByKey = elemUniqSet_Directly
partitionVarSet = partitionUniqSet
mapUnionVarSet get_set xs = foldr (unionVarSet . get_set) emptyVarSet xs
-- See comments with type signatures
intersectsVarSet s1 s2 = not (s1 `disjointVarSet` s2)
disjointVarSet s1 s2 = disjointUFM (getUniqSet s1) (getUniqSet s2)
subVarSet s1 s2 = isEmptyVarSet (s1 `minusVarSet` s2)
anyVarSet :: (Var -> Bool) -> VarSet -> Bool
anyVarSet = uniqSetAny
allVarSet :: (Var -> Bool) -> VarSet -> Bool
allVarSet = uniqSetAll
mapVarSet :: Uniquable b => (a -> b) -> UniqSet a -> UniqSet b
mapVarSet = mapUniqSet
fixVarSet :: (VarSet -> VarSet) -- Map the current set to a new set
-> VarSet -> VarSet
( fixVarSet f s ) repeatedly applies f to the set s ,
-- until it reaches a fixed point.
fixVarSet fn vars
| new_vars `subVarSet` vars = vars
| otherwise = fixVarSet fn new_vars
where
new_vars = fn vars
transCloVarSet :: (VarSet -> VarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> VarSet -> VarSet
-- (transCloVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
The function fn could be ( Var - > VarSet ) , but we use ( VarSet - > VarSet )
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
-- Use fixVarSet if the function needs to see the whole set all at once
transCloVarSet fn seeds
= go seeds seeds
where
go :: VarSet -- Accumulating result
Work - list ; un - processed subset of accumulating result
-> VarSet
Specification : go acc vs = acc ` union ` transClo fn vs
go acc candidates
| isEmptyVarSet new_vs = acc
| otherwise = go (acc `unionVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusVarSet` acc
seqVarSet :: VarSet -> ()
seqVarSet s = sizeVarSet s `seq` ()
-- | Determines the pluralisation suffix appropriate for the length of a set
in the same way that plural from Outputable does for lists .
pluralVarSet :: VarSet -> SDoc
pluralVarSet = pluralUFM . getUniqSet
-- | Pretty-print a non-deterministic set.
-- The order of variables is non-deterministic and for pretty-printing that
-- shouldn't be a problem.
-- Having this function helps contain the non-determinism created with
-- nonDetEltsUFM.
-- Passing a list to the pretty-printing function allows the caller
to decide on the order of Vars ( eg . toposort them ) without them having
-- to use nonDetEltsUFM at the call site. This prevents from let-binding
-- non-deterministically ordered lists and reusing them where determinism
-- matters.
pprVarSet :: VarSet -- ^ The things to be pretty printed
-> ([Var] -> SDoc) -- ^ The pretty printing function to use on the
-- elements
-> SDoc -- ^ 'SDoc' where the things have been pretty
-- printed
pprVarSet = pprUFM . getUniqSet
Deterministic VarSet
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
-- DVarSet.
-- | Deterministic Variable Set
type DVarSet = UniqDSet Var
-- | Deterministic Identifier Set
type DIdSet = UniqDSet Id
-- | Deterministic Type Variable Set
type DTyVarSet = UniqDSet TyVar
-- | Deterministic Type or Coercion Variable Set
type DTyCoVarSet = UniqDSet TyCoVar
emptyDVarSet :: DVarSet
emptyDVarSet = emptyUniqDSet
unitDVarSet :: Var -> DVarSet
unitDVarSet = unitUniqDSet
mkDVarSet :: [Var] -> DVarSet
mkDVarSet = mkUniqDSet
-- The new element always goes to the right of existing ones.
extendDVarSet :: DVarSet -> Var -> DVarSet
extendDVarSet = addOneToUniqDSet
elemDVarSet :: Var -> DVarSet -> Bool
elemDVarSet = elementOfUniqDSet
dVarSetElems :: DVarSet -> [Var]
dVarSetElems = uniqDSetToList
subDVarSet :: DVarSet -> DVarSet -> Bool
subDVarSet s1 s2 = isEmptyDVarSet (s1 `minusDVarSet` s2)
unionDVarSet :: DVarSet -> DVarSet -> DVarSet
unionDVarSet = unionUniqDSets
unionDVarSets :: [DVarSet] -> DVarSet
unionDVarSets = unionManyUniqDSets
-- | Map the function over the list, and union the results
mapUnionDVarSet :: (a -> DVarSet) -> [a] -> DVarSet
mapUnionDVarSet get_set xs = foldr (unionDVarSet . get_set) emptyDVarSet xs
intersectDVarSet :: DVarSet -> DVarSet -> DVarSet
intersectDVarSet = intersectUniqDSets
dVarSetIntersectVarSet :: DVarSet -> VarSet -> DVarSet
dVarSetIntersectVarSet = uniqDSetIntersectUniqSet
-- | True if empty intersection
disjointDVarSet :: DVarSet -> DVarSet -> Bool
disjointDVarSet s1 s2 = disjointUDFM (getUniqDSet s1) (getUniqDSet s2)
-- | True if non-empty intersection
intersectsDVarSet :: DVarSet -> DVarSet -> Bool
intersectsDVarSet s1 s2 = not (s1 `disjointDVarSet` s2)
isEmptyDVarSet :: DVarSet -> Bool
isEmptyDVarSet = isEmptyUniqDSet
delDVarSet :: DVarSet -> Var -> DVarSet
delDVarSet = delOneFromUniqDSet
minusDVarSet :: DVarSet -> DVarSet -> DVarSet
minusDVarSet = minusUniqDSet
dVarSetMinusVarSet :: DVarSet -> VarSet -> DVarSet
dVarSetMinusVarSet = uniqDSetMinusUniqSet
foldDVarSet :: (Var -> a -> a) -> a -> DVarSet -> a
foldDVarSet = foldUniqDSet
anyDVarSet :: (Var -> Bool) -> DVarSet -> Bool
anyDVarSet p = anyUDFM p . getUniqDSet
allDVarSet :: (Var -> Bool) -> DVarSet -> Bool
allDVarSet p = allUDFM p . getUniqDSet
mapDVarSet :: Uniquable b => (a -> b) -> UniqDSet a -> UniqDSet b
mapDVarSet = mapUniqDSet
filterDVarSet :: (Var -> Bool) -> DVarSet -> DVarSet
filterDVarSet = filterUniqDSet
sizeDVarSet :: DVarSet -> Int
sizeDVarSet = sizeUniqDSet
-- | Partition DVarSet according to the predicate given
partitionDVarSet :: (Var -> Bool) -> DVarSet -> (DVarSet, DVarSet)
partitionDVarSet = partitionUniqDSet
-- | Delete a list of variables from DVarSet
delDVarSetList :: DVarSet -> [Var] -> DVarSet
delDVarSetList = delListFromUniqDSet
seqDVarSet :: DVarSet -> ()
seqDVarSet s = sizeDVarSet s `seq` ()
-- | Add a list of variables to DVarSet
extendDVarSetList :: DVarSet -> [Var] -> DVarSet
extendDVarSetList = addListToUniqDSet
| Convert a DVarSet to a VarSet by forgeting the order of insertion
dVarSetToVarSet :: DVarSet -> VarSet
dVarSetToVarSet = unsafeUFMToUniqSet . udfmToUfm . getUniqDSet
-- | transCloVarSet for DVarSet
transCloDVarSet :: (DVarSet -> DVarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> DVarSet -> DVarSet
-- (transCloDVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
-- The function fn could be (Var -> DVarSet), but we use (DVarSet -> DVarSet)
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
transCloDVarSet fn seeds
= go seeds seeds
where
go :: DVarSet -- Accumulating result
Work - list ; un - processed subset of accumulating result
-> DVarSet
Specification : go acc vs = acc ` union ` transClo fn vs
go acc candidates
| isEmptyDVarSet new_vs = acc
| otherwise = go (acc `unionDVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusDVarSet` acc
| null | https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/basicTypes/VarSet.hs | haskell | ** Manipulating these sets
** Manipulating these sets
| A non-deterministic Variable Set
A non-deterministic set of variables.
See Note [Deterministic UniqFM] in UniqDFM for explanation why it's not
deterministic and why it matters. Use DVarSet if the set eventually
gets converted into a list or folded over in a way where the order
changes the generated code, for example when abstracting variables.
| Identifier Set
| Type Variable Set
| Coercion Variable Set
| Type or Coercion Variable Set
^ map the function over the list, and union the results
Returns the set element, which may be
(==) to the argument, but not the same as
True if non-empty intersection
True if empty intersection
(s1 `intersectsVarSet` s2) doesn't compute s2 if s1 is empty;
ditto disjointVarSet, subVarSet
See comments with type signatures
Map the current set to a new set
until it reaches a fixed point.
Map some variables in the set to
extra variables that should be in it
(transCloVarSet f s) repeatedly applies f to new candidates, adding any
new variables to s that it finds thereby, until it reaches a fixed point.
for efficiency, so that the test can be batched up.
It's essential that fn will work fine if given new candidates
one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
Use fixVarSet if the function needs to see the whole set all at once
Accumulating result
| Determines the pluralisation suffix appropriate for the length of a set
| Pretty-print a non-deterministic set.
The order of variables is non-deterministic and for pretty-printing that
shouldn't be a problem.
Having this function helps contain the non-determinism created with
nonDetEltsUFM.
Passing a list to the pretty-printing function allows the caller
to use nonDetEltsUFM at the call site. This prevents from let-binding
non-deterministically ordered lists and reusing them where determinism
matters.
^ The things to be pretty printed
^ The pretty printing function to use on the
elements
^ 'SDoc' where the things have been pretty
printed
See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
DVarSet.
| Deterministic Variable Set
| Deterministic Identifier Set
| Deterministic Type Variable Set
| Deterministic Type or Coercion Variable Set
The new element always goes to the right of existing ones.
| Map the function over the list, and union the results
| True if empty intersection
| True if non-empty intersection
| Partition DVarSet according to the predicate given
| Delete a list of variables from DVarSet
| Add a list of variables to DVarSet
| transCloVarSet for DVarSet
Map some variables in the set to
extra variables that should be in it
(transCloDVarSet f s) repeatedly applies f to new candidates, adding any
new variables to s that it finds thereby, until it reaches a fixed point.
The function fn could be (Var -> DVarSet), but we use (DVarSet -> DVarSet)
for efficiency, so that the test can be batched up.
It's essential that fn will work fine if given new candidates
one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
Accumulating result |
( c ) The University of Glasgow 2006
( c ) The GRASP / AQUA Project , Glasgow University , 1992 - 1998
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
# LANGUAGE CPP #
module VarSet (
* , I d and TyVar set types
VarSet, IdSet, TyVarSet, CoVarSet, TyCoVarSet,
emptyVarSet, unitVarSet, mkVarSet,
extendVarSet, extendVarSetList,
elemVarSet, subVarSet,
unionVarSet, unionVarSets, mapUnionVarSet,
intersectVarSet, intersectsVarSet, disjointVarSet,
isEmptyVarSet, delVarSet, delVarSetList, delVarSetByKey,
minusVarSet, filterVarSet, mapVarSet,
anyVarSet, allVarSet,
transCloVarSet, fixVarSet,
lookupVarSet_Directly, lookupVarSet, lookupVarSetByName,
sizeVarSet, seqVarSet,
elemVarSetByKey, partitionVarSet,
pluralVarSet, pprVarSet,
* Deterministic set types
DVarSet, DIdSet, DTyVarSet, DTyCoVarSet,
emptyDVarSet, unitDVarSet, mkDVarSet,
extendDVarSet, extendDVarSetList,
elemDVarSet, dVarSetElems, subDVarSet,
unionDVarSet, unionDVarSets, mapUnionDVarSet,
intersectDVarSet, dVarSetIntersectVarSet,
intersectsDVarSet, disjointDVarSet,
isEmptyDVarSet, delDVarSet, delDVarSetList,
minusDVarSet, foldDVarSet, filterDVarSet, mapDVarSet,
dVarSetMinusVarSet, anyDVarSet, allDVarSet,
transCloDVarSet,
sizeDVarSet, seqDVarSet,
partitionDVarSet,
dVarSetToVarSet,
) where
#include "HsVersions2.h"
import GhcPrelude
import Var ( Var, TyVar, CoVar, TyCoVar, Id )
import Unique
import Name ( Name )
import UniqSet
import UniqDSet
import UniqFM( disjointUFM, pluralUFM, pprUFM )
import UniqDFM( disjointUDFM, udfmToUfm, anyUDFM, allUDFM )
import Outputable (SDoc)
type VarSet = UniqSet Var
type IdSet = UniqSet Id
type TyVarSet = UniqSet TyVar
type CoVarSet = UniqSet CoVar
type TyCoVarSet = UniqSet TyCoVar
emptyVarSet :: VarSet
intersectVarSet :: VarSet -> VarSet -> VarSet
unionVarSet :: VarSet -> VarSet -> VarSet
unionVarSets :: [VarSet] -> VarSet
mapUnionVarSet :: (a -> VarSet) -> [a] -> VarSet
unitVarSet :: Var -> VarSet
extendVarSet :: VarSet -> Var -> VarSet
extendVarSetList:: VarSet -> [Var] -> VarSet
elemVarSet :: Var -> VarSet -> Bool
delVarSet :: VarSet -> Var -> VarSet
delVarSetList :: VarSet -> [Var] -> VarSet
minusVarSet :: VarSet -> VarSet -> VarSet
isEmptyVarSet :: VarSet -> Bool
mkVarSet :: [Var] -> VarSet
lookupVarSet_Directly :: VarSet -> Unique -> Maybe Var
lookupVarSet :: VarSet -> Var -> Maybe Var
lookupVarSetByName :: VarSet -> Name -> Maybe Var
sizeVarSet :: VarSet -> Int
filterVarSet :: (Var -> Bool) -> VarSet -> VarSet
delVarSetByKey :: VarSet -> Unique -> VarSet
elemVarSetByKey :: Unique -> VarSet -> Bool
partitionVarSet :: (Var -> Bool) -> VarSet -> (VarSet, VarSet)
emptyVarSet = emptyUniqSet
unitVarSet = unitUniqSet
extendVarSet = addOneToUniqSet
extendVarSetList= addListToUniqSet
intersectVarSet = intersectUniqSets
True if first arg is subset of second
unionVarSet = unionUniqSets
unionVarSets = unionManyUniqSets
elemVarSet = elementOfUniqSet
minusVarSet = minusUniqSet
delVarSet = delOneFromUniqSet
delVarSetList = delListFromUniqSet
isEmptyVarSet = isEmptyUniqSet
mkVarSet = mkUniqSet
lookupVarSet_Directly = lookupUniqSet_Directly
lookupVarSet = lookupUniqSet
lookupVarSetByName = lookupUniqSet
sizeVarSet = sizeUniqSet
filterVarSet = filterUniqSet
delVarSetByKey = delOneFromUniqSet_Directly
elemVarSetByKey = elemUniqSet_Directly
partitionVarSet = partitionUniqSet
mapUnionVarSet get_set xs = foldr (unionVarSet . get_set) emptyVarSet xs
intersectsVarSet s1 s2 = not (s1 `disjointVarSet` s2)
disjointVarSet s1 s2 = disjointUFM (getUniqSet s1) (getUniqSet s2)
subVarSet s1 s2 = isEmptyVarSet (s1 `minusVarSet` s2)
anyVarSet :: (Var -> Bool) -> VarSet -> Bool
anyVarSet = uniqSetAny
allVarSet :: (Var -> Bool) -> VarSet -> Bool
allVarSet = uniqSetAll
mapVarSet :: Uniquable b => (a -> b) -> UniqSet a -> UniqSet b
mapVarSet = mapUniqSet
-> VarSet -> VarSet
( fixVarSet f s ) repeatedly applies f to the set s ,
fixVarSet fn vars
| new_vars `subVarSet` vars = vars
| otherwise = fixVarSet fn new_vars
where
new_vars = fn vars
transCloVarSet :: (VarSet -> VarSet)
-> VarSet -> VarSet
The function fn could be ( Var - > VarSet ) , but we use ( VarSet - > VarSet )
transCloVarSet fn seeds
= go seeds seeds
where
Work - list ; un - processed subset of accumulating result
-> VarSet
Specification : go acc vs = acc ` union ` transClo fn vs
go acc candidates
| isEmptyVarSet new_vs = acc
| otherwise = go (acc `unionVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusVarSet` acc
seqVarSet :: VarSet -> ()
seqVarSet s = sizeVarSet s `seq` ()
in the same way that plural from Outputable does for lists .
pluralVarSet :: VarSet -> SDoc
pluralVarSet = pluralUFM . getUniqSet
to decide on the order of Vars ( eg . toposort them ) without them having
pprVarSet = pprUFM . getUniqSet
Deterministic VarSet
type DVarSet = UniqDSet Var
type DIdSet = UniqDSet Id
type DTyVarSet = UniqDSet TyVar
type DTyCoVarSet = UniqDSet TyCoVar
emptyDVarSet :: DVarSet
emptyDVarSet = emptyUniqDSet
unitDVarSet :: Var -> DVarSet
unitDVarSet = unitUniqDSet
mkDVarSet :: [Var] -> DVarSet
mkDVarSet = mkUniqDSet
extendDVarSet :: DVarSet -> Var -> DVarSet
extendDVarSet = addOneToUniqDSet
elemDVarSet :: Var -> DVarSet -> Bool
elemDVarSet = elementOfUniqDSet
dVarSetElems :: DVarSet -> [Var]
dVarSetElems = uniqDSetToList
subDVarSet :: DVarSet -> DVarSet -> Bool
subDVarSet s1 s2 = isEmptyDVarSet (s1 `minusDVarSet` s2)
unionDVarSet :: DVarSet -> DVarSet -> DVarSet
unionDVarSet = unionUniqDSets
unionDVarSets :: [DVarSet] -> DVarSet
unionDVarSets = unionManyUniqDSets
mapUnionDVarSet :: (a -> DVarSet) -> [a] -> DVarSet
mapUnionDVarSet get_set xs = foldr (unionDVarSet . get_set) emptyDVarSet xs
intersectDVarSet :: DVarSet -> DVarSet -> DVarSet
intersectDVarSet = intersectUniqDSets
dVarSetIntersectVarSet :: DVarSet -> VarSet -> DVarSet
dVarSetIntersectVarSet = uniqDSetIntersectUniqSet
disjointDVarSet :: DVarSet -> DVarSet -> Bool
disjointDVarSet s1 s2 = disjointUDFM (getUniqDSet s1) (getUniqDSet s2)
intersectsDVarSet :: DVarSet -> DVarSet -> Bool
intersectsDVarSet s1 s2 = not (s1 `disjointDVarSet` s2)
isEmptyDVarSet :: DVarSet -> Bool
isEmptyDVarSet = isEmptyUniqDSet
delDVarSet :: DVarSet -> Var -> DVarSet
delDVarSet = delOneFromUniqDSet
minusDVarSet :: DVarSet -> DVarSet -> DVarSet
minusDVarSet = minusUniqDSet
dVarSetMinusVarSet :: DVarSet -> VarSet -> DVarSet
dVarSetMinusVarSet = uniqDSetMinusUniqSet
foldDVarSet :: (Var -> a -> a) -> a -> DVarSet -> a
foldDVarSet = foldUniqDSet
anyDVarSet :: (Var -> Bool) -> DVarSet -> Bool
anyDVarSet p = anyUDFM p . getUniqDSet
allDVarSet :: (Var -> Bool) -> DVarSet -> Bool
allDVarSet p = allUDFM p . getUniqDSet
mapDVarSet :: Uniquable b => (a -> b) -> UniqDSet a -> UniqDSet b
mapDVarSet = mapUniqDSet
filterDVarSet :: (Var -> Bool) -> DVarSet -> DVarSet
filterDVarSet = filterUniqDSet
sizeDVarSet :: DVarSet -> Int
sizeDVarSet = sizeUniqDSet
partitionDVarSet :: (Var -> Bool) -> DVarSet -> (DVarSet, DVarSet)
partitionDVarSet = partitionUniqDSet
delDVarSetList :: DVarSet -> [Var] -> DVarSet
delDVarSetList = delListFromUniqDSet
seqDVarSet :: DVarSet -> ()
seqDVarSet s = sizeDVarSet s `seq` ()
extendDVarSetList :: DVarSet -> [Var] -> DVarSet
extendDVarSetList = addListToUniqDSet
| Convert a DVarSet to a VarSet by forgeting the order of insertion
dVarSetToVarSet :: DVarSet -> VarSet
dVarSetToVarSet = unsafeUFMToUniqSet . udfmToUfm . getUniqDSet
transCloDVarSet :: (DVarSet -> DVarSet)
-> DVarSet -> DVarSet
transCloDVarSet fn seeds
= go seeds seeds
where
Work - list ; un - processed subset of accumulating result
-> DVarSet
Specification : go acc vs = acc ` union ` transClo fn vs
go acc candidates
| isEmptyDVarSet new_vs = acc
| otherwise = go (acc `unionDVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusDVarSet` acc
|
daaa807e3f6c025fd3b2102a59d4cb46352564c3a9f7f63edee5ed47634b65dd | pyr/cyanite | utils.clj | (ns io.cyanite.utils
"These didn't fit anywhere else"
(:import org.cliffc.high_scale_lib.NonBlockingHashMap))
(defprotocol MutableMap
"Mutable map functionality"
(entries [this] "Return a set of entries")
(keyset [this] "Return the keyset")
(remove! [this k] "Atomically remove and return an element")
(contains-key [this key] "Checks if map contains the key")
(assoc-if-absent! [this k v] "CAS type put"))
(defn nbhm
"Yield a NonBlockingHashMap"
[]
(let [db (NonBlockingHashMap.)]
(reify
clojure.lang.ITransientMap
(assoc [this k v]
(.put db k v)
this)
MutableMap
(entries [this]
(.entrySet db))
(keyset [this]
(.keySet db))
(contains-key [this key]
(.containsKey db key))
(remove! [this k]
(.remove db k))
(assoc-if-absent! [this k v]
(.putIfAbsent db k v))
clojure.lang.Seqable
(seq [this]
(let [keys (.keySet db)]
(map #(.get db %) (.keySet db))))
clojure.lang.ILookup
(valAt [this k]
(.get db k))
(valAt [this k def]
(or (.get db k) def))
java.lang.Object
(toString [this]
(.toString db)))))
| null | https://raw.githubusercontent.com/pyr/cyanite/2b9a1f26df808abdad3465dd1946036749b93000/src/io/cyanite/utils.clj | clojure | (ns io.cyanite.utils
"These didn't fit anywhere else"
(:import org.cliffc.high_scale_lib.NonBlockingHashMap))
(defprotocol MutableMap
"Mutable map functionality"
(entries [this] "Return a set of entries")
(keyset [this] "Return the keyset")
(remove! [this k] "Atomically remove and return an element")
(contains-key [this key] "Checks if map contains the key")
(assoc-if-absent! [this k v] "CAS type put"))
(defn nbhm
"Yield a NonBlockingHashMap"
[]
(let [db (NonBlockingHashMap.)]
(reify
clojure.lang.ITransientMap
(assoc [this k v]
(.put db k v)
this)
MutableMap
(entries [this]
(.entrySet db))
(keyset [this]
(.keySet db))
(contains-key [this key]
(.containsKey db key))
(remove! [this k]
(.remove db k))
(assoc-if-absent! [this k v]
(.putIfAbsent db k v))
clojure.lang.Seqable
(seq [this]
(let [keys (.keySet db)]
(map #(.get db %) (.keySet db))))
clojure.lang.ILookup
(valAt [this k]
(.get db k))
(valAt [this k def]
(or (.get db k) def))
java.lang.Object
(toString [this]
(.toString db)))))
| |
183a8b85cbece994d73cdcc830d816a2ee26d7cf1b606e0edc85309a1261f4da | ocurrent/bun | files.ml | afl - fuzz needs for there to be at least one file in its input directory .
if the input directory does n't exist , or it 's empty , fix that for the user
by creating it and making an empty file .
if the input directory doesn't exist, or it's empty, fix that for the user
by creating it and making an empty file. *)
let fixup_input input =
let open Rresult.R in
Bos.OS.Dir.create input >>= fun _created -> (* Ok anything will do *)
Bos.OS.Dir.contents input >>= function
| _::_ -> Ok () (* any file will do! *)
| [] -> Bos.OS.File.write Fpath.(input / "bun_autogenerated_seed")
"'rabbit rabbit rabbit'is one variant of a superstition found in Britain and North America that states that a person should say or repeat the word 'rabbit' or 'rabbits', or 'white rabbits', or some combination of these elements, out loud upon waking on the first day of the month, because doing so will ensure good luck for the duration of that month. -- en.wikipedia.org/wiki/Rabbit_rabbit_rabbit"
module Parse = struct
let get_stats lines =
(* did someone say shotgun parsers? *)
List.map (Astring.String.fields ~empty:false ~is_sep:((=) ':')) lines |>
List.map (List.map Astring.String.trim) |>
List.fold_left (fun acc -> function | hd::tl::[]-> (hd, tl)::acc
| _ -> acc) [] |> List.rev
let lookup s l =
try Some (List.find (fun (a,_) -> Astring.String.equal a s) l) with Not_found -> None
let lookup_int s l = match lookup s l with
| None -> None
| Some (_, i) -> try Some (int_of_string i) with Invalid_argument _ -> None
let lookup_crashes l = lookup_int "unique_crashes" l
let lookup_pid l = lookup_int "fuzzer_pid" l
let get_crash_files ?(id = "$(file)") output_dir =
let crashes = Fpath.(output_dir / id / "crashes" / "id$(file)" ) in
Bos.OS.Path.matches crashes
let get_stats_lines ~id output =
Bos.OS.File.read_lines Fpath.(output / id / "fuzzer_stats")
let get_cores cpu =
let aux gotcpus =
let process_preamble = "more processes on " in
let more_processes = Bos.Cmd.(v "grep" % process_preamble) in
let (>>=) = Rresult.R.bind in
Bos.OS.Cmd.(run_io more_processes gotcpus |> to_lines) >>= fun l ->
match List.map (Astring.String.cut ~sep:process_preamble) l
|> List.find (function | Some _ -> true | None -> false) with
| None -> Ok 0
| Some (_, cores) ->
Logs.debug (fun f -> f "cores line: %s" cores);
let words = Astring.String.fields cores in
(* afl-gotcpu sometimes tells us that some CPUs *might* be overcommitted.
it's usually too conservative; we want to try to use the CPUs that it's
not sure about. *)
match Astring.String.compare (List.nth words 1) "to" with
| 0 -> Ok (List.nth words 2 |> int_of_string)
| _ -> Ok (List.hd words |> int_of_string)
in
let er = Rresult.R.error_msg_to_invalid_arg in
try
Bos.OS.Cmd.(run_out ~err:err_run_out (Bos.Cmd.v cpu) |> out_run_in |> er) |>
aux |> er
with
| Not_found | Invalid_argument _ | Failure _ -> 0
end
module Print = struct
let base64 f =
Bos.OS.Cmd.run_out @@
Bos.Cmd.(v "base64" % "-w" % "0" % (Fpath.to_string f)) |>
Bos.OS.Cmd.to_string
let output_pasteable str id =
Printf.sprintf "echo %s | base64 -d > crash_%d.$(date -u +%%s)" str id
let print_crashes output_dir =
match Parse.get_crash_files output_dir with
| Error (`Msg e) ->
Error (`Msg (Format.asprintf "Failure finding crashes in \
directory %a: %s" Fpath.pp output_dir e))
| Ok [] ->
Printf.printf "No crashes found!\n%!"; Ok ()
| Ok crashes ->
Printf.printf "Crashes found! Take a look; copy/paste to save for \
reproduction:\n%!";
try
List.iteri (fun i c ->
match base64 c with
| Error _ -> ()
| Ok base64 ->
Printf.printf "%s\n%!" (output_pasteable base64 i)
) crashes;
Ok ()
with
| Invalid_argument e -> Error (`Msg (Format.asprintf "Failed to base64 a \
crash file: %s" e))
end
| null | https://raw.githubusercontent.com/ocurrent/bun/ded6358225b03b29e2604a528299328060bdc0a7/src/files.ml | ocaml | Ok anything will do
any file will do!
did someone say shotgun parsers?
afl-gotcpu sometimes tells us that some CPUs *might* be overcommitted.
it's usually too conservative; we want to try to use the CPUs that it's
not sure about. | afl - fuzz needs for there to be at least one file in its input directory .
if the input directory does n't exist , or it 's empty , fix that for the user
by creating it and making an empty file .
if the input directory doesn't exist, or it's empty, fix that for the user
by creating it and making an empty file. *)
let fixup_input input =
let open Rresult.R in
Bos.OS.Dir.contents input >>= function
| [] -> Bos.OS.File.write Fpath.(input / "bun_autogenerated_seed")
"'rabbit rabbit rabbit'is one variant of a superstition found in Britain and North America that states that a person should say or repeat the word 'rabbit' or 'rabbits', or 'white rabbits', or some combination of these elements, out loud upon waking on the first day of the month, because doing so will ensure good luck for the duration of that month. -- en.wikipedia.org/wiki/Rabbit_rabbit_rabbit"
module Parse = struct
let get_stats lines =
List.map (Astring.String.fields ~empty:false ~is_sep:((=) ':')) lines |>
List.map (List.map Astring.String.trim) |>
List.fold_left (fun acc -> function | hd::tl::[]-> (hd, tl)::acc
| _ -> acc) [] |> List.rev
let lookup s l =
try Some (List.find (fun (a,_) -> Astring.String.equal a s) l) with Not_found -> None
let lookup_int s l = match lookup s l with
| None -> None
| Some (_, i) -> try Some (int_of_string i) with Invalid_argument _ -> None
let lookup_crashes l = lookup_int "unique_crashes" l
let lookup_pid l = lookup_int "fuzzer_pid" l
let get_crash_files ?(id = "$(file)") output_dir =
let crashes = Fpath.(output_dir / id / "crashes" / "id$(file)" ) in
Bos.OS.Path.matches crashes
let get_stats_lines ~id output =
Bos.OS.File.read_lines Fpath.(output / id / "fuzzer_stats")
let get_cores cpu =
let aux gotcpus =
let process_preamble = "more processes on " in
let more_processes = Bos.Cmd.(v "grep" % process_preamble) in
let (>>=) = Rresult.R.bind in
Bos.OS.Cmd.(run_io more_processes gotcpus |> to_lines) >>= fun l ->
match List.map (Astring.String.cut ~sep:process_preamble) l
|> List.find (function | Some _ -> true | None -> false) with
| None -> Ok 0
| Some (_, cores) ->
Logs.debug (fun f -> f "cores line: %s" cores);
let words = Astring.String.fields cores in
match Astring.String.compare (List.nth words 1) "to" with
| 0 -> Ok (List.nth words 2 |> int_of_string)
| _ -> Ok (List.hd words |> int_of_string)
in
let er = Rresult.R.error_msg_to_invalid_arg in
try
Bos.OS.Cmd.(run_out ~err:err_run_out (Bos.Cmd.v cpu) |> out_run_in |> er) |>
aux |> er
with
| Not_found | Invalid_argument _ | Failure _ -> 0
end
module Print = struct
let base64 f =
Bos.OS.Cmd.run_out @@
Bos.Cmd.(v "base64" % "-w" % "0" % (Fpath.to_string f)) |>
Bos.OS.Cmd.to_string
let output_pasteable str id =
Printf.sprintf "echo %s | base64 -d > crash_%d.$(date -u +%%s)" str id
let print_crashes output_dir =
match Parse.get_crash_files output_dir with
| Error (`Msg e) ->
Error (`Msg (Format.asprintf "Failure finding crashes in \
directory %a: %s" Fpath.pp output_dir e))
| Ok [] ->
Printf.printf "No crashes found!\n%!"; Ok ()
| Ok crashes ->
Printf.printf "Crashes found! Take a look; copy/paste to save for \
reproduction:\n%!";
try
List.iteri (fun i c ->
match base64 c with
| Error _ -> ()
| Ok base64 ->
Printf.printf "%s\n%!" (output_pasteable base64 i)
) crashes;
Ok ()
with
| Invalid_argument e -> Error (`Msg (Format.asprintf "Failed to base64 a \
crash file: %s" e))
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.