_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 |
|---|---|---|---|---|---|---|---|---|
93ad2c2cc03da712c8d6e7001ac6fc041876c6b92615f5c052896a388f0dce16 | janestreet/memtrace_viewer | filtered_trace.ml | open! Core
open Memtrace_viewer_common
let predicate_matches ~loc_cache (pred : Filter.Location_predicate.t) call_site =
let data = Location.Cache.get_call_site_data loc_cache call_site in
let defname = Data.Call_site.defname data in
match pred with
| Defname_related { relation; rhs } ->
(match relation with
| Equals -> String.equal defname rhs
| Contains -> String.is_substring defname ~substring:rhs)
;;
module Filtered_location_cache = struct
type t =
| Trivial of Location.Cache.t
| Nontrivial of
{ loc_cache : Location.Cache.t
; hidden_locations : Filter.Location_predicate.t list
; cache : Call_site.t list Location.Code.Table.t
}
let create ~filter:({ hidden_locations; _ } : Filter.t) ~loc_cache () =
match hidden_locations with
| [] -> Trivial loc_cache
| _ ->
Nontrivial { loc_cache; hidden_locations; cache = Location.Code.Table.create () }
;;
let loc_cache (Trivial loc_cache | Nontrivial { loc_cache; _ }) = loc_cache
let call_sites_from_code t code =
match t with
| Trivial loc_cache -> Location.Cache.call_sites_from_code loc_cache code
| Nontrivial { loc_cache; hidden_locations; cache } ->
Hashtbl.find_or_add cache code ~default:(fun () ->
let call_sites = Location.Cache.call_sites_from_code loc_cache code in
List.filter call_sites ~f:(fun call_site ->
not
(List.exists hidden_locations ~f:(fun pred ->
predicate_matches ~loc_cache pred call_site))))
;;
let last_call_site_is_hidden t code =
match t with
| Trivial _ -> false
| Nontrivial { loc_cache; _ } ->
let filtered_call_sites = call_sites_from_code t code in
let all_call_sites = Location.Cache.call_sites_from_code loc_cache code in
not
(Option.equal
Call_site.equal
(List.last filtered_call_sites)
(List.last all_call_sites))
;;
let get_function_of_call_site t call_site =
Location.Cache.get_function_of_call_site (loc_cache t) call_site
;;
let get_allocation_site_of_call_site t call_site =
Location.Cache.get_allocation_site_of_call_site (loc_cache t) call_site
;;
end
module Cached_predicate : sig
type t
val wrap : loc_cache:Location.Cache.t -> Filter.Location_predicate.t -> t
val matches : t -> Call_site.t -> bool
end = struct
type t =
{ pred : Filter.Location_predicate.t
; cache : bool Call_site.Table.t
; loc_cache : Location.Cache.t
}
let wrap ~loc_cache pred = { pred; cache = Call_site.Table.create (); loc_cache }
let matches { pred; cache; loc_cache } call_site =
Hashtbl.find_or_add cache call_site ~default:(fun () ->
predicate_matches ~loc_cache pred call_site)
;;
end
(** Is an object allocated at this time eligible to pass the filter? *)
let should_record_allocation_at time ({ allocated_range; _ } : Filter.t) =
Range.Time_ns_span.compare_point time allocated_range = 0
;;
(** Is an allocation with the given size eligible to pass the filter? *)
let should_record_allocation_of_size size ({ size_range; _ } : Filter.t) =
Range.Byte_units.compare_point size size_range = 0
;;
(** Is an object with the given lifetime eligible to pass the filter? *)
let should_keep_object_with_lifetime lifetime ({ lifetime_range; _ } : Filter.t) =
Range.Time_ns_span.compare_point lifetime lifetime_range = 0
;;
module Location_filterer : sig
type t
val create : filter:Filter.t -> loc_cache:Location.Cache.t -> unit -> t
val always_passes : t -> bool
val should_record_allocation_with_backtrace : t -> Location.Code.t array -> int -> bool
end = struct
type t =
{ required_locations : Cached_predicate.t list
; forbidden_locations : Cached_predicate.t list
; loc_cache : Location.Cache.t
; always_passes : bool
}
let create ~(filter : Filter.t) ~loc_cache () =
let always_passes =
match filter with
| { required_locations = []
; forbidden_locations = []
; hidden_locations = _
; allocated_range = _
; collected_range = _
; size_range = _
; lifetime_range = _
; include_major_heap = _
; include_minor_heap = _
} -> true
| _ -> false
in
let required_locations =
List.map ~f:(Cached_predicate.wrap ~loc_cache) filter.required_locations
in
let forbidden_locations =
List.map ~f:(Cached_predicate.wrap ~loc_cache) filter.forbidden_locations
in
{ required_locations; forbidden_locations; loc_cache; always_passes }
;;
let always_passes t = t.always_passes
(** Is an allocation with the given backtrace eligible to pass the filter? *)
let should_record_allocation_with_backtrace t buffer length =
let holds_somewhere pred =
let rec holds_somewhere_from i =
if i >= length
then false
else (
let call_sites = Location.Cache.call_sites_from_code t.loc_cache buffer.(i) in
List.exists ~f:(Cached_predicate.matches pred) call_sites
|| holds_somewhere_from (i + 1))
in
holds_somewhere_from 0
in
let interesting = List.for_all ~f:holds_somewhere t.required_locations in
let forbidden () = List.exists ~f:holds_somewhere t.forbidden_locations in
interesting && not (forbidden ())
;;
end
(** Is an object collected at this time eligible to pass the filter? *)
let should_keep_object_collected_at time ({ collected_range; _ } : Filter.t) =
Range.Time_ns_span.Or_empty.contains_point collected_range time
;;
(** Are objects that are never collected eligible to pass the filter? (This counts objects
that are live at the end as collected at the end, unless the filter specifies "never
collected". In other words, "collected at or after" includes "collected never". This
is important because "live at t" is interpreted as "allocated at or before t and
collected after t". *)
let should_keep_objects_that_are_never_collected
~time_at_end
({ collected_range; _ } : Filter.t)
=
Range.Time_ns_span.Or_empty.(
is_empty collected_range || contains_point collected_range time_at_end)
;;
let obj_ids_matching_filter ~trace ~loc_cache (filter : Filter.t) =
assert (filter.include_minor_heap || filter.include_major_heap);
(* Objects that are live in an interesting heap *)
let live = Obj_id.Table.create () in
(* Objects that will become live if promoted *)
let prelive = Obj_id.Hash_set.create () in
let passing = Obj_id.Hash_set.create () in
let location_filterer = Location_filterer.create ~filter ~loc_cache () in
let filtering_by_backtrace = not (Location_filterer.always_passes location_filterer) in
let parse_backtraces = filtering_by_backtrace in
Raw_trace.iter ~parse_backtraces trace (fun time event ->
let defer obj_id = Hash_set.strict_add_exn prelive obj_id in
let is_deferred obj_id = Hash_set.mem prelive obj_id in
let allocate obj_id =
Hash_set.remove prelive obj_id;
if should_record_allocation_at time filter
then Hashtbl.add_exn live ~key:obj_id ~data:time
in
let deallocate obj_id =
if Hash_set.mem prelive obj_id
then (
Hash_set.strict_remove_exn prelive obj_id;
assert (not (Hashtbl.mem live obj_id)))
else (
match Hashtbl.find live obj_id with
| None -> ()
| Some alloc_time ->
Hashtbl.remove live obj_id;
let lifetime = Time_ns.Span.( - ) time alloc_time in
if should_keep_object_collected_at time filter
&& should_keep_object_with_lifetime lifetime filter
then Hash_set.strict_add_exn passing obj_id)
in
match event with
| Alloc
{ obj_id
; single_allocation_size
; source
; backtrace_length
; backtrace_buffer
; _
} ->
let deferring =
match source with
| Minor -> not filter.include_minor_heap
| Major | External -> false
in
let definitely_wrong_heap =
match source with
| Minor ->
(* Could become interesting later (when promoted), so it's only possibly wrong
*)
false
| Major -> not filter.include_major_heap
| External ->
not filter.include_major_heap
in
let correct_size =
should_record_allocation_of_size single_allocation_size filter
in
let interesting_backtrace () =
(not filtering_by_backtrace)
|| Location_filterer.should_record_allocation_with_backtrace
location_filterer
backtrace_buffer
backtrace_length
in
let eligible =
(not definitely_wrong_heap) && correct_size && interesting_backtrace ()
in
if not eligible then () else if deferring then defer obj_id else allocate obj_id
| Promote obj_id ->
if is_deferred obj_id
then allocate obj_id
else if not filter.include_major_heap
then deallocate obj_id
| Collect obj_id ->
(* Might already have been filtered out, but [deallocate] is harmless then *)
deallocate obj_id
| End ->
let time_at_end = time in
if should_keep_objects_that_are_never_collected filter ~time_at_end
then
Hashtbl.iteri live ~f:(fun ~key:obj_id ~data:alloc_time ->
let lifetime = Time_ns.Span.( - ) time_at_end alloc_time in
if should_keep_object_with_lifetime lifetime filter
then Hash_set.strict_add_exn passing obj_id));
passing
;;
type t =
{ trace : Raw_trace.t
; loc_cache : Filtered_location_cache.t
; interesting : Obj_id.t -> bool
; defer_minor_allocations : bool
; collect_on_promotion : bool
}
let word_size t = (Raw_trace.info t.trace).word_size
let sample_rate t = (Raw_trace.info t.trace).sample_rate
let create ~trace ~loc_cache ~filter =
let interesting =
if Filter.is_always_true filter
then fun _ -> true
else (
let interesting = obj_ids_matching_filter ~trace ~loc_cache filter in
fun obj_id -> Hash_set.mem interesting obj_id)
in
let filtered_loc_cache = Filtered_location_cache.create ~filter ~loc_cache () in
let defer_minor_allocations = not filter.include_minor_heap in
let collect_on_promotion = not filter.include_major_heap in
{ trace
; loc_cache = filtered_loc_cache
; interesting
; defer_minor_allocations
; collect_on_promotion
}
;;
module Event = struct
type t = Location.t Event.t [@@deriving sexp_of]
end
module Call_sites = struct
module Callees_from_call_site = struct
(* The set of locations that a particular call site invokes. (There can be
multiple locations only if it's an indirect call.) *)
type t = Location.Hash_set.t
end
module Calls_from_location = struct
The [ Callees_from_call_site.t ] for each call site within a particular
location .
location. *)
type t = Callees_from_call_site.t Call_site.Table.t
end
type t = Calls_from_location.t Location.Table.t
let of_list (l : (Location.t * Call_site.t * Location.t list) list) =
let t = Location.Table.create () in
List.iter l ~f:(fun (loc, call_site, callees) ->
let calls_from_location =
Hashtbl.find_or_add t loc ~default:Call_site.Table.create
in
Hashtbl.add_exn
calls_from_location
~key:call_site
~data:(callees |> Location.Hash_set.of_list));
t
;;
end
module Mode = struct
type t =
| Preserve_backtraces
| Preserve_times
end
module Interpreter : sig
type filtered_trace := t
type t
val create
: filtered_trace:filtered_trace
-> callback:(Time_ns.Span.t -> Event.t -> unit)
-> mode:Mode.t
-> record_call_sites:bool
-> unit
-> t
val interpret_event : t -> Time_ns.Span.t -> Raw_trace.Event.t -> unit
val call_sites : t -> Call_sites.t
end = struct
module Location_state = struct
type t =
{ location : Location.t
; mutable seen : bool
}
let dummy = { location = Location.dummy; seen = false }
end
module Call_site_state = struct
type t =
{ call_site : Call_site.t
; location_state : Location_state.t
; mutable callees : Location.t list
}
let dummy =
{ call_site = Call_site.dummy; location_state = Location_state.dummy; callees = [] }
;;
let rec insert list a =
match list with
| [] -> [ a ]
| b :: rest ->
(match Location.compare a b with
| -1 -> a :: list
| 0 ->
It 's tempting to use [ raise_notrace ] to exit early here , but in the
_ overwhelming _ majority of cases , the list has at most one element , so
there 's nothing to be gained ( in particular , we do n't avoid any
allocation )
_overwhelming_ majority of cases, the list has at most one element, so
there's nothing to be gained (in particular, we don't avoid any
allocation) *)
list
| 1 -> b :: insert rest a
| _ -> assert false)
;;
let add_callee t callee =
let new_callees =
(* Be sure to inline [insert] so it specializes [compare] to a cheap [Int.compare]
This actually seems to be significantly better than just writing
[insert] as a recursive function with [compare] hard-coded to [Location.compare].
I'm not sure why.
*)
insert t.callees callee
in
if not (phys_equal new_callees t.callees) then t.callees <- new_callees
;;
end
module Location_code_state = struct
type t =
{ call_site_states : Call_site_state.t array
; mutable seen : bool
}
let dummy = { call_site_states = [||]; seen = false }
end
type filtered_trace = t
type t =
{ filtered_trace : filtered_trace
; callback : Time_ns.Span.t -> Event.t -> unit
; mode : Mode.t
; record_call_sites : bool
; deferring : Raw_trace.Event.t Obj_id.Table.t
; collected_early : Obj_id.Hash_set.t
; call_sites : Call_site_state.t Call_site.Table.t
; locations : Location_state.t Location.Table.t
; location_codes : Location_code_state.t Location.Code.Table.t
; (* For each index [i] in the input array, the index into [current_location_codes] of
the state of the last unskipped location code as of input [i]. (If the input
location code at [i] wasn't skipped, this will be the state of that location
code.) *)
mutable input_to_location_code : int array
; mutable current_location_codes : Location_code_state.t array
; (* For each index [i] into [current_location_codes], the index into
[current_call_sites] (and into [backtrace_buffer]) of the state of the last
unskipped call site as of the location code at [i]. *)
mutable location_code_to_last_call_site : int array
; mutable current_call_sites : Call_site_state.t array
; mutable backtrace_buffer : Location.t array
; mutable prev_in_length : int
; mutable prev_out_length : int
; mutable max_next_common_prefix : int
}
let create ~filtered_trace ~callback ~mode ~record_call_sites () =
{ filtered_trace
; callback
; mode
; record_call_sites
; deferring = Obj_id.Table.create ()
; collected_early = Obj_id.Hash_set.create ()
; call_sites = Call_site.Table.create ()
; locations = Location.Table.create ()
; location_codes = Location.Code.Table.create ()
; input_to_location_code = Array.create ~len:10 ~-1
; current_location_codes = Array.create ~len:10 Location_code_state.dummy
; location_code_to_last_call_site = Array.create ~len:10 ~-1
; current_call_sites = Array.create ~len:10 Call_site_state.dummy
; backtrace_buffer = Array.create ~len:10 Location.dummy
; prev_in_length = 0
; prev_out_length = 0
; max_next_common_prefix = Int.max_value
}
;;
let loc_cache t = t.filtered_trace.loc_cache
let find_location_state t loc =
Hashtbl.find_or_add t.locations loc ~default:(fun () ->
{ location = loc; seen = false })
;;
let find_call_site_state t call_site =
Hashtbl.find_or_add t.call_sites call_site ~default:(fun () : Call_site_state.t ->
let loc =
Filtered_location_cache.get_function_of_call_site (loc_cache t) call_site
in
let location_state = find_location_state t loc in
let callees = [] in
{ call_site; location_state; callees })
;;
let find_location_code_state t loc_code =
Hashtbl.find_or_add t.location_codes loc_code ~default:(fun () ->
let call_sites =
Filtered_location_cache.call_sites_from_code (loc_cache t) loc_code
in
let call_site_states = Array.of_list_map ~f:(find_call_site_state t) call_sites in
let seen = false in
{ call_site_states; seen })
;;
let call_sites t =
t.call_sites
|> Hashtbl.to_alist
|> List.map ~f:(fun (call_site, state) ->
let loc = state.location_state.location in
let callees = state.callees in
loc, call_site, callees)
|> Call_sites.of_list
;;
let enlarge array ~index ~default =
let len = index + 1 in
let old_len = Array.length array in
let new_len = max len (2 * old_len) in
let new_array = Array.create ~len:new_len default in
Array.blito ~src:array ~dst:new_array ();
new_array
;;
let write_to_backtrace t ~index loc =
(* We could use the [growable_array] library to guard this, but that doesn't let us
get back the underlying array when producing an event. *)
if index >= Array.length t.backtrace_buffer
then t.backtrace_buffer <- enlarge t.backtrace_buffer ~index ~default:Location.dummy;
t.backtrace_buffer.(index) <- loc
;;
let set_input_to_location_code t ~index state =
if index >= Array.length t.input_to_location_code
then t.input_to_location_code <- enlarge t.input_to_location_code ~index ~default:~-1;
t.input_to_location_code.(index) <- state
;;
let set_current_location_code t ~index state =
if index >= Array.length t.current_location_codes
then
t.current_location_codes
<- enlarge t.current_location_codes ~index ~default:Location_code_state.dummy;
t.current_location_codes.(index) <- state
;;
let set_location_code_to_last_call_site t ~index state =
if index >= Array.length t.location_code_to_last_call_site
then
t.location_code_to_last_call_site
<- enlarge t.location_code_to_last_call_site ~index ~default:~-1;
t.location_code_to_last_call_site.(index) <- state
;;
let set_current_call_site t ~index state =
if index >= Array.length t.current_call_sites
then
t.current_call_sites
<- enlarge t.current_call_sites ~index ~default:Call_site_state.dummy;
t.current_call_sites.(index) <- state
;;
let input_to_location_code t idx =
if idx < 0 then -1 else t.input_to_location_code.(idx)
;;
let location_code_to_last_call_site t idx =
if idx < 0 then -1 else t.location_code_to_last_call_site.(idx)
;;
let record_call_site t ~call_site_state ~callee =
if t.record_call_sites then Call_site_state.add_callee call_site_state callee
;;
let conv_event (t : t) (event : Raw_trace.Event.t) : Event.t =
match event with
| Alloc
{ obj_id
; source
; single_allocation_size
; nsamples
; size
; backtrace_buffer = in_backtrace_buffer
; backtrace_length = in_backtrace_length
; common_prefix = in_common_prefix
} ->
let backtrace_known_to_be_truncated = in_common_prefix > in_backtrace_length in
let in_common_prefix =
The backtrace may in fact be truncated to the first [ in_backtrace_length ]
frames . [ in_common_prefix ] will nonetheless be the number of frames in
common between the two _ true _ backtraces . We do n't treat the truncated
backtrace any differently , so for our purposes the common prefix is just the
entire backtrace in this case .
frames. [in_common_prefix] will nonetheless be the number of frames in
common between the two _true_ backtraces. We don't treat the truncated
backtrace any differently, so for our purposes the common prefix is just the
entire backtrace in this case. *)
min in_common_prefix in_backtrace_length
in
let backtrace_length, common_prefix =
match t.mode with
| Preserve_times -> 0, 0
| Preserve_backtraces ->
let last_prev_location_code = input_to_location_code t (t.prev_in_length - 1) in
let last_prev_call_site =
location_code_to_last_call_site t last_prev_location_code
in
let in_common_prefix = min in_common_prefix t.max_next_common_prefix in
let last_common_location_code =
input_to_location_code t (in_common_prefix - 1)
in
let last_common_call_site =
location_code_to_last_call_site t last_common_location_code
in
for i = last_prev_location_code downto last_common_location_code + 1 do
let state = t.current_location_codes.(i) in
state.seen <- false
done;
for i = last_prev_call_site downto last_common_call_site + 1 do
let state = t.current_call_sites.(i) in
state.location_state.seen <- false
done;
let next_location_code = ref (last_common_location_code + 1) in
let next_call_site = ref (last_common_call_site + 1) in
for i = in_common_prefix to in_backtrace_length - 1 do
let location_code = in_backtrace_buffer.(i) in
let location_code_state = find_location_code_state t location_code in
if not location_code_state.seen
then (
set_current_location_code t ~index:!next_location_code location_code_state;
location_code_state.seen <- true;
let call_sites = location_code_state.call_site_states in
for j = 0 to Array.length call_sites - 1 do
let call_site_state = call_sites.(j) in
let location_state = call_site_state.location_state in
if not location_state.seen
then (
set_current_call_site t ~index:!next_call_site call_site_state;
location_state.seen <- true;
write_to_backtrace t ~index:!next_call_site location_state.location;
if !next_call_site > 0
then (
let prev_call_site = t.current_call_sites.(!next_call_site - 1) in
record_call_site
t
~call_site_state:prev_call_site
~callee:location_state.location);
incr next_call_site)
done;
set_location_code_to_last_call_site
t
~index:!next_location_code
(!next_call_site - 1);
incr next_location_code);
set_input_to_location_code t ~index:i (!next_location_code - 1)
done;
(* Assume the last location code is for the allocation since those codes should
only appear once in the backtrace. Exceptions: If the backtrace is obviously
truncated (since the common prefix is too big), assume it doesn't include an
allocation site; and if the last call site of the last location code was
hidden by the filter, treat the allocation site as having been filtered out.
*)
if not (in_backtrace_length = 0 || backtrace_known_to_be_truncated)
then (
let last_location_code = in_backtrace_buffer.(in_backtrace_length - 1) in
if not
(Filtered_location_cache.last_call_site_is_hidden
(loc_cache t)
last_location_code)
then (
let last_location_code_state =
find_location_code_state t last_location_code
in
let call_sites = last_location_code_state.call_site_states in
if not (Array.is_empty call_sites)
then (
let allocation_call_site = Array.last call_sites in
let allocation_site =
Filtered_location_cache.get_allocation_site_of_call_site
(loc_cache t)
allocation_call_site.call_site
in
write_to_backtrace t ~index:!next_call_site allocation_site;
if !next_call_site > 0
then (
let prev_call_site = t.current_call_sites.(!next_call_site - 1) in
record_call_site
t
~call_site_state:prev_call_site
~callee:allocation_site);
incr next_call_site)));
!next_call_site, last_common_call_site + 1
in
let backtrace_buffer = t.backtrace_buffer in
Alloc
{ obj_id
; source
; single_allocation_size
; nsamples
; size
; backtrace_buffer
; backtrace_length
; common_prefix
}
| (Promote _ | Collect _ | End) as ev -> ev
;;
let interpret_event t time (event : Raw_trace.Event.t) =
match event with
| End -> t.callback time End
| Alloc { obj_id; _ } | Promote obj_id | Collect obj_id ->
let { interesting; defer_minor_allocations; collect_on_promotion; _ } =
t.filtered_trace
in
let return (out_event : Event.t) =
let () =
match t.mode with
| Preserve_times -> ()
| Preserve_backtraces ->
(match event, out_event with
| ( Alloc { backtrace_length = in_length; _ }
, Alloc { backtrace_length = out_length; _ } ) ->
t.prev_in_length <- in_length;
t.prev_out_length <- out_length;
t.max_next_common_prefix <- Int.max_value
| Alloc _, _ | _, Alloc _ -> assert false
| (Promote _ | Collect _ | End), (Promote _ | Collect _ | End) -> ())
in
t.callback time out_event
in
let skip () =
(* If we don't pass the event through, we need to make sure the next common prefix
is no larger than this one so that the next event will know to go back far enough
to copy the backtrace from this event.
*)
let () =
match t.mode with
| Preserve_times -> ()
| Preserve_backtraces ->
(match event with
| Alloc { common_prefix; _ } ->
t.max_next_common_prefix <- min common_prefix t.max_next_common_prefix
* Do n't * update prev_in_length , since its purpose is to know how to move the
out cursor * from the last event we interpreted *
out cursor *from the last event we interpreted* *)
| Promote _ | Collect _ | End -> ())
in
()
in
let interesting = interesting obj_id in
if not interesting
then skip ()
else (
match t.mode with
| Preserve_backtraces -> return (event |> conv_event t)
| Preserve_times ->
(match event with
| Alloc ({ obj_id; source = Minor; _ } as alloc) when defer_minor_allocations ->
Hashtbl.add_exn
t.deferring
~key:obj_id
~data:(Alloc { alloc with source = Major });
skip ()
| Promote obj_id when collect_on_promotion ->
Hash_set.strict_add_exn t.collected_early obj_id;
return (Collect obj_id)
| Promote obj_id when defer_minor_allocations ->
(match Hashtbl.find_and_remove t.deferring obj_id with
| None ->
raise
(Not_found_s
[%message "Missing deferred object" ~obj_id:((obj_id :> int) : int)])
| Some event -> return (event |> conv_event t))
| Collect obj_id
when collect_on_promotion && Hash_set.mem t.collected_early obj_id ->
Hash_set.remove t.collected_early obj_id
| Collect obj_id when defer_minor_allocations && Hashtbl.mem t.deferring obj_id
-> Hashtbl.remove t.deferring obj_id
| _ -> return (event |> conv_event t)))
;;
end
let iter_and_return_interpreter t ~mode ~record_call_sites f =
let interpreter =
Interpreter.create ~filtered_trace:t ~callback:f ~mode ~record_call_sites ()
in
let parse_backtraces =
match mode with
| Mode.Preserve_backtraces -> true
| Preserve_times -> false
in
Raw_trace.iter t.trace ~parse_backtraces (fun time event ->
Interpreter.interpret_event interpreter time event);
interpreter
;;
let iter t ~mode f =
let interpreter = iter_and_return_interpreter t ~mode ~record_call_sites:false f in
ignore (interpreter : Interpreter.t)
;;
let iter_and_gather_call_sites t ~mode f =
let interpreter = iter_and_return_interpreter t ~mode ~record_call_sites:true f in
Interpreter.call_sites interpreter
;;
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer/280d57dd520ed755497169e46b5fd0b11401d482/server/src/filtered_trace.ml | ocaml | * Is an object allocated at this time eligible to pass the filter?
* Is an allocation with the given size eligible to pass the filter?
* Is an object with the given lifetime eligible to pass the filter?
* Is an allocation with the given backtrace eligible to pass the filter?
* Is an object collected at this time eligible to pass the filter?
* Are objects that are never collected eligible to pass the filter? (This counts objects
that are live at the end as collected at the end, unless the filter specifies "never
collected". In other words, "collected at or after" includes "collected never". This
is important because "live at t" is interpreted as "allocated at or before t and
collected after t".
Objects that are live in an interesting heap
Objects that will become live if promoted
Could become interesting later (when promoted), so it's only possibly wrong
Might already have been filtered out, but [deallocate] is harmless then
The set of locations that a particular call site invokes. (There can be
multiple locations only if it's an indirect call.)
Be sure to inline [insert] so it specializes [compare] to a cheap [Int.compare]
This actually seems to be significantly better than just writing
[insert] as a recursive function with [compare] hard-coded to [Location.compare].
I'm not sure why.
For each index [i] in the input array, the index into [current_location_codes] of
the state of the last unskipped location code as of input [i]. (If the input
location code at [i] wasn't skipped, this will be the state of that location
code.)
For each index [i] into [current_location_codes], the index into
[current_call_sites] (and into [backtrace_buffer]) of the state of the last
unskipped call site as of the location code at [i].
We could use the [growable_array] library to guard this, but that doesn't let us
get back the underlying array when producing an event.
Assume the last location code is for the allocation since those codes should
only appear once in the backtrace. Exceptions: If the backtrace is obviously
truncated (since the common prefix is too big), assume it doesn't include an
allocation site; and if the last call site of the last location code was
hidden by the filter, treat the allocation site as having been filtered out.
If we don't pass the event through, we need to make sure the next common prefix
is no larger than this one so that the next event will know to go back far enough
to copy the backtrace from this event.
| open! Core
open Memtrace_viewer_common
let predicate_matches ~loc_cache (pred : Filter.Location_predicate.t) call_site =
let data = Location.Cache.get_call_site_data loc_cache call_site in
let defname = Data.Call_site.defname data in
match pred with
| Defname_related { relation; rhs } ->
(match relation with
| Equals -> String.equal defname rhs
| Contains -> String.is_substring defname ~substring:rhs)
;;
module Filtered_location_cache = struct
type t =
| Trivial of Location.Cache.t
| Nontrivial of
{ loc_cache : Location.Cache.t
; hidden_locations : Filter.Location_predicate.t list
; cache : Call_site.t list Location.Code.Table.t
}
let create ~filter:({ hidden_locations; _ } : Filter.t) ~loc_cache () =
match hidden_locations with
| [] -> Trivial loc_cache
| _ ->
Nontrivial { loc_cache; hidden_locations; cache = Location.Code.Table.create () }
;;
let loc_cache (Trivial loc_cache | Nontrivial { loc_cache; _ }) = loc_cache
let call_sites_from_code t code =
match t with
| Trivial loc_cache -> Location.Cache.call_sites_from_code loc_cache code
| Nontrivial { loc_cache; hidden_locations; cache } ->
Hashtbl.find_or_add cache code ~default:(fun () ->
let call_sites = Location.Cache.call_sites_from_code loc_cache code in
List.filter call_sites ~f:(fun call_site ->
not
(List.exists hidden_locations ~f:(fun pred ->
predicate_matches ~loc_cache pred call_site))))
;;
let last_call_site_is_hidden t code =
match t with
| Trivial _ -> false
| Nontrivial { loc_cache; _ } ->
let filtered_call_sites = call_sites_from_code t code in
let all_call_sites = Location.Cache.call_sites_from_code loc_cache code in
not
(Option.equal
Call_site.equal
(List.last filtered_call_sites)
(List.last all_call_sites))
;;
let get_function_of_call_site t call_site =
Location.Cache.get_function_of_call_site (loc_cache t) call_site
;;
let get_allocation_site_of_call_site t call_site =
Location.Cache.get_allocation_site_of_call_site (loc_cache t) call_site
;;
end
module Cached_predicate : sig
type t
val wrap : loc_cache:Location.Cache.t -> Filter.Location_predicate.t -> t
val matches : t -> Call_site.t -> bool
end = struct
type t =
{ pred : Filter.Location_predicate.t
; cache : bool Call_site.Table.t
; loc_cache : Location.Cache.t
}
let wrap ~loc_cache pred = { pred; cache = Call_site.Table.create (); loc_cache }
let matches { pred; cache; loc_cache } call_site =
Hashtbl.find_or_add cache call_site ~default:(fun () ->
predicate_matches ~loc_cache pred call_site)
;;
end
let should_record_allocation_at time ({ allocated_range; _ } : Filter.t) =
Range.Time_ns_span.compare_point time allocated_range = 0
;;
let should_record_allocation_of_size size ({ size_range; _ } : Filter.t) =
Range.Byte_units.compare_point size size_range = 0
;;
let should_keep_object_with_lifetime lifetime ({ lifetime_range; _ } : Filter.t) =
Range.Time_ns_span.compare_point lifetime lifetime_range = 0
;;
module Location_filterer : sig
type t
val create : filter:Filter.t -> loc_cache:Location.Cache.t -> unit -> t
val always_passes : t -> bool
val should_record_allocation_with_backtrace : t -> Location.Code.t array -> int -> bool
end = struct
type t =
{ required_locations : Cached_predicate.t list
; forbidden_locations : Cached_predicate.t list
; loc_cache : Location.Cache.t
; always_passes : bool
}
let create ~(filter : Filter.t) ~loc_cache () =
let always_passes =
match filter with
| { required_locations = []
; forbidden_locations = []
; hidden_locations = _
; allocated_range = _
; collected_range = _
; size_range = _
; lifetime_range = _
; include_major_heap = _
; include_minor_heap = _
} -> true
| _ -> false
in
let required_locations =
List.map ~f:(Cached_predicate.wrap ~loc_cache) filter.required_locations
in
let forbidden_locations =
List.map ~f:(Cached_predicate.wrap ~loc_cache) filter.forbidden_locations
in
{ required_locations; forbidden_locations; loc_cache; always_passes }
;;
let always_passes t = t.always_passes
let should_record_allocation_with_backtrace t buffer length =
let holds_somewhere pred =
let rec holds_somewhere_from i =
if i >= length
then false
else (
let call_sites = Location.Cache.call_sites_from_code t.loc_cache buffer.(i) in
List.exists ~f:(Cached_predicate.matches pred) call_sites
|| holds_somewhere_from (i + 1))
in
holds_somewhere_from 0
in
let interesting = List.for_all ~f:holds_somewhere t.required_locations in
let forbidden () = List.exists ~f:holds_somewhere t.forbidden_locations in
interesting && not (forbidden ())
;;
end
let should_keep_object_collected_at time ({ collected_range; _ } : Filter.t) =
Range.Time_ns_span.Or_empty.contains_point collected_range time
;;
let should_keep_objects_that_are_never_collected
~time_at_end
({ collected_range; _ } : Filter.t)
=
Range.Time_ns_span.Or_empty.(
is_empty collected_range || contains_point collected_range time_at_end)
;;
let obj_ids_matching_filter ~trace ~loc_cache (filter : Filter.t) =
assert (filter.include_minor_heap || filter.include_major_heap);
let live = Obj_id.Table.create () in
let prelive = Obj_id.Hash_set.create () in
let passing = Obj_id.Hash_set.create () in
let location_filterer = Location_filterer.create ~filter ~loc_cache () in
let filtering_by_backtrace = not (Location_filterer.always_passes location_filterer) in
let parse_backtraces = filtering_by_backtrace in
Raw_trace.iter ~parse_backtraces trace (fun time event ->
let defer obj_id = Hash_set.strict_add_exn prelive obj_id in
let is_deferred obj_id = Hash_set.mem prelive obj_id in
let allocate obj_id =
Hash_set.remove prelive obj_id;
if should_record_allocation_at time filter
then Hashtbl.add_exn live ~key:obj_id ~data:time
in
let deallocate obj_id =
if Hash_set.mem prelive obj_id
then (
Hash_set.strict_remove_exn prelive obj_id;
assert (not (Hashtbl.mem live obj_id)))
else (
match Hashtbl.find live obj_id with
| None -> ()
| Some alloc_time ->
Hashtbl.remove live obj_id;
let lifetime = Time_ns.Span.( - ) time alloc_time in
if should_keep_object_collected_at time filter
&& should_keep_object_with_lifetime lifetime filter
then Hash_set.strict_add_exn passing obj_id)
in
match event with
| Alloc
{ obj_id
; single_allocation_size
; source
; backtrace_length
; backtrace_buffer
; _
} ->
let deferring =
match source with
| Minor -> not filter.include_minor_heap
| Major | External -> false
in
let definitely_wrong_heap =
match source with
| Minor ->
false
| Major -> not filter.include_major_heap
| External ->
not filter.include_major_heap
in
let correct_size =
should_record_allocation_of_size single_allocation_size filter
in
let interesting_backtrace () =
(not filtering_by_backtrace)
|| Location_filterer.should_record_allocation_with_backtrace
location_filterer
backtrace_buffer
backtrace_length
in
let eligible =
(not definitely_wrong_heap) && correct_size && interesting_backtrace ()
in
if not eligible then () else if deferring then defer obj_id else allocate obj_id
| Promote obj_id ->
if is_deferred obj_id
then allocate obj_id
else if not filter.include_major_heap
then deallocate obj_id
| Collect obj_id ->
deallocate obj_id
| End ->
let time_at_end = time in
if should_keep_objects_that_are_never_collected filter ~time_at_end
then
Hashtbl.iteri live ~f:(fun ~key:obj_id ~data:alloc_time ->
let lifetime = Time_ns.Span.( - ) time_at_end alloc_time in
if should_keep_object_with_lifetime lifetime filter
then Hash_set.strict_add_exn passing obj_id));
passing
;;
type t =
{ trace : Raw_trace.t
; loc_cache : Filtered_location_cache.t
; interesting : Obj_id.t -> bool
; defer_minor_allocations : bool
; collect_on_promotion : bool
}
let word_size t = (Raw_trace.info t.trace).word_size
let sample_rate t = (Raw_trace.info t.trace).sample_rate
let create ~trace ~loc_cache ~filter =
let interesting =
if Filter.is_always_true filter
then fun _ -> true
else (
let interesting = obj_ids_matching_filter ~trace ~loc_cache filter in
fun obj_id -> Hash_set.mem interesting obj_id)
in
let filtered_loc_cache = Filtered_location_cache.create ~filter ~loc_cache () in
let defer_minor_allocations = not filter.include_minor_heap in
let collect_on_promotion = not filter.include_major_heap in
{ trace
; loc_cache = filtered_loc_cache
; interesting
; defer_minor_allocations
; collect_on_promotion
}
;;
module Event = struct
type t = Location.t Event.t [@@deriving sexp_of]
end
module Call_sites = struct
module Callees_from_call_site = struct
type t = Location.Hash_set.t
end
module Calls_from_location = struct
The [ Callees_from_call_site.t ] for each call site within a particular
location .
location. *)
type t = Callees_from_call_site.t Call_site.Table.t
end
type t = Calls_from_location.t Location.Table.t
let of_list (l : (Location.t * Call_site.t * Location.t list) list) =
let t = Location.Table.create () in
List.iter l ~f:(fun (loc, call_site, callees) ->
let calls_from_location =
Hashtbl.find_or_add t loc ~default:Call_site.Table.create
in
Hashtbl.add_exn
calls_from_location
~key:call_site
~data:(callees |> Location.Hash_set.of_list));
t
;;
end
module Mode = struct
type t =
| Preserve_backtraces
| Preserve_times
end
module Interpreter : sig
type filtered_trace := t
type t
val create
: filtered_trace:filtered_trace
-> callback:(Time_ns.Span.t -> Event.t -> unit)
-> mode:Mode.t
-> record_call_sites:bool
-> unit
-> t
val interpret_event : t -> Time_ns.Span.t -> Raw_trace.Event.t -> unit
val call_sites : t -> Call_sites.t
end = struct
module Location_state = struct
type t =
{ location : Location.t
; mutable seen : bool
}
let dummy = { location = Location.dummy; seen = false }
end
module Call_site_state = struct
type t =
{ call_site : Call_site.t
; location_state : Location_state.t
; mutable callees : Location.t list
}
let dummy =
{ call_site = Call_site.dummy; location_state = Location_state.dummy; callees = [] }
;;
let rec insert list a =
match list with
| [] -> [ a ]
| b :: rest ->
(match Location.compare a b with
| -1 -> a :: list
| 0 ->
It 's tempting to use [ raise_notrace ] to exit early here , but in the
_ overwhelming _ majority of cases , the list has at most one element , so
there 's nothing to be gained ( in particular , we do n't avoid any
allocation )
_overwhelming_ majority of cases, the list has at most one element, so
there's nothing to be gained (in particular, we don't avoid any
allocation) *)
list
| 1 -> b :: insert rest a
| _ -> assert false)
;;
let add_callee t callee =
let new_callees =
insert t.callees callee
in
if not (phys_equal new_callees t.callees) then t.callees <- new_callees
;;
end
module Location_code_state = struct
type t =
{ call_site_states : Call_site_state.t array
; mutable seen : bool
}
let dummy = { call_site_states = [||]; seen = false }
end
type filtered_trace = t
type t =
{ filtered_trace : filtered_trace
; callback : Time_ns.Span.t -> Event.t -> unit
; mode : Mode.t
; record_call_sites : bool
; deferring : Raw_trace.Event.t Obj_id.Table.t
; collected_early : Obj_id.Hash_set.t
; call_sites : Call_site_state.t Call_site.Table.t
; locations : Location_state.t Location.Table.t
; location_codes : Location_code_state.t Location.Code.Table.t
mutable input_to_location_code : int array
; mutable current_location_codes : Location_code_state.t array
mutable location_code_to_last_call_site : int array
; mutable current_call_sites : Call_site_state.t array
; mutable backtrace_buffer : Location.t array
; mutable prev_in_length : int
; mutable prev_out_length : int
; mutable max_next_common_prefix : int
}
let create ~filtered_trace ~callback ~mode ~record_call_sites () =
{ filtered_trace
; callback
; mode
; record_call_sites
; deferring = Obj_id.Table.create ()
; collected_early = Obj_id.Hash_set.create ()
; call_sites = Call_site.Table.create ()
; locations = Location.Table.create ()
; location_codes = Location.Code.Table.create ()
; input_to_location_code = Array.create ~len:10 ~-1
; current_location_codes = Array.create ~len:10 Location_code_state.dummy
; location_code_to_last_call_site = Array.create ~len:10 ~-1
; current_call_sites = Array.create ~len:10 Call_site_state.dummy
; backtrace_buffer = Array.create ~len:10 Location.dummy
; prev_in_length = 0
; prev_out_length = 0
; max_next_common_prefix = Int.max_value
}
;;
let loc_cache t = t.filtered_trace.loc_cache
let find_location_state t loc =
Hashtbl.find_or_add t.locations loc ~default:(fun () ->
{ location = loc; seen = false })
;;
let find_call_site_state t call_site =
Hashtbl.find_or_add t.call_sites call_site ~default:(fun () : Call_site_state.t ->
let loc =
Filtered_location_cache.get_function_of_call_site (loc_cache t) call_site
in
let location_state = find_location_state t loc in
let callees = [] in
{ call_site; location_state; callees })
;;
let find_location_code_state t loc_code =
Hashtbl.find_or_add t.location_codes loc_code ~default:(fun () ->
let call_sites =
Filtered_location_cache.call_sites_from_code (loc_cache t) loc_code
in
let call_site_states = Array.of_list_map ~f:(find_call_site_state t) call_sites in
let seen = false in
{ call_site_states; seen })
;;
let call_sites t =
t.call_sites
|> Hashtbl.to_alist
|> List.map ~f:(fun (call_site, state) ->
let loc = state.location_state.location in
let callees = state.callees in
loc, call_site, callees)
|> Call_sites.of_list
;;
let enlarge array ~index ~default =
let len = index + 1 in
let old_len = Array.length array in
let new_len = max len (2 * old_len) in
let new_array = Array.create ~len:new_len default in
Array.blito ~src:array ~dst:new_array ();
new_array
;;
let write_to_backtrace t ~index loc =
if index >= Array.length t.backtrace_buffer
then t.backtrace_buffer <- enlarge t.backtrace_buffer ~index ~default:Location.dummy;
t.backtrace_buffer.(index) <- loc
;;
let set_input_to_location_code t ~index state =
if index >= Array.length t.input_to_location_code
then t.input_to_location_code <- enlarge t.input_to_location_code ~index ~default:~-1;
t.input_to_location_code.(index) <- state
;;
let set_current_location_code t ~index state =
if index >= Array.length t.current_location_codes
then
t.current_location_codes
<- enlarge t.current_location_codes ~index ~default:Location_code_state.dummy;
t.current_location_codes.(index) <- state
;;
let set_location_code_to_last_call_site t ~index state =
if index >= Array.length t.location_code_to_last_call_site
then
t.location_code_to_last_call_site
<- enlarge t.location_code_to_last_call_site ~index ~default:~-1;
t.location_code_to_last_call_site.(index) <- state
;;
let set_current_call_site t ~index state =
if index >= Array.length t.current_call_sites
then
t.current_call_sites
<- enlarge t.current_call_sites ~index ~default:Call_site_state.dummy;
t.current_call_sites.(index) <- state
;;
let input_to_location_code t idx =
if idx < 0 then -1 else t.input_to_location_code.(idx)
;;
let location_code_to_last_call_site t idx =
if idx < 0 then -1 else t.location_code_to_last_call_site.(idx)
;;
let record_call_site t ~call_site_state ~callee =
if t.record_call_sites then Call_site_state.add_callee call_site_state callee
;;
let conv_event (t : t) (event : Raw_trace.Event.t) : Event.t =
match event with
| Alloc
{ obj_id
; source
; single_allocation_size
; nsamples
; size
; backtrace_buffer = in_backtrace_buffer
; backtrace_length = in_backtrace_length
; common_prefix = in_common_prefix
} ->
let backtrace_known_to_be_truncated = in_common_prefix > in_backtrace_length in
let in_common_prefix =
The backtrace may in fact be truncated to the first [ in_backtrace_length ]
frames . [ in_common_prefix ] will nonetheless be the number of frames in
common between the two _ true _ backtraces . We do n't treat the truncated
backtrace any differently , so for our purposes the common prefix is just the
entire backtrace in this case .
frames. [in_common_prefix] will nonetheless be the number of frames in
common between the two _true_ backtraces. We don't treat the truncated
backtrace any differently, so for our purposes the common prefix is just the
entire backtrace in this case. *)
min in_common_prefix in_backtrace_length
in
let backtrace_length, common_prefix =
match t.mode with
| Preserve_times -> 0, 0
| Preserve_backtraces ->
let last_prev_location_code = input_to_location_code t (t.prev_in_length - 1) in
let last_prev_call_site =
location_code_to_last_call_site t last_prev_location_code
in
let in_common_prefix = min in_common_prefix t.max_next_common_prefix in
let last_common_location_code =
input_to_location_code t (in_common_prefix - 1)
in
let last_common_call_site =
location_code_to_last_call_site t last_common_location_code
in
for i = last_prev_location_code downto last_common_location_code + 1 do
let state = t.current_location_codes.(i) in
state.seen <- false
done;
for i = last_prev_call_site downto last_common_call_site + 1 do
let state = t.current_call_sites.(i) in
state.location_state.seen <- false
done;
let next_location_code = ref (last_common_location_code + 1) in
let next_call_site = ref (last_common_call_site + 1) in
for i = in_common_prefix to in_backtrace_length - 1 do
let location_code = in_backtrace_buffer.(i) in
let location_code_state = find_location_code_state t location_code in
if not location_code_state.seen
then (
set_current_location_code t ~index:!next_location_code location_code_state;
location_code_state.seen <- true;
let call_sites = location_code_state.call_site_states in
for j = 0 to Array.length call_sites - 1 do
let call_site_state = call_sites.(j) in
let location_state = call_site_state.location_state in
if not location_state.seen
then (
set_current_call_site t ~index:!next_call_site call_site_state;
location_state.seen <- true;
write_to_backtrace t ~index:!next_call_site location_state.location;
if !next_call_site > 0
then (
let prev_call_site = t.current_call_sites.(!next_call_site - 1) in
record_call_site
t
~call_site_state:prev_call_site
~callee:location_state.location);
incr next_call_site)
done;
set_location_code_to_last_call_site
t
~index:!next_location_code
(!next_call_site - 1);
incr next_location_code);
set_input_to_location_code t ~index:i (!next_location_code - 1)
done;
if not (in_backtrace_length = 0 || backtrace_known_to_be_truncated)
then (
let last_location_code = in_backtrace_buffer.(in_backtrace_length - 1) in
if not
(Filtered_location_cache.last_call_site_is_hidden
(loc_cache t)
last_location_code)
then (
let last_location_code_state =
find_location_code_state t last_location_code
in
let call_sites = last_location_code_state.call_site_states in
if not (Array.is_empty call_sites)
then (
let allocation_call_site = Array.last call_sites in
let allocation_site =
Filtered_location_cache.get_allocation_site_of_call_site
(loc_cache t)
allocation_call_site.call_site
in
write_to_backtrace t ~index:!next_call_site allocation_site;
if !next_call_site > 0
then (
let prev_call_site = t.current_call_sites.(!next_call_site - 1) in
record_call_site
t
~call_site_state:prev_call_site
~callee:allocation_site);
incr next_call_site)));
!next_call_site, last_common_call_site + 1
in
let backtrace_buffer = t.backtrace_buffer in
Alloc
{ obj_id
; source
; single_allocation_size
; nsamples
; size
; backtrace_buffer
; backtrace_length
; common_prefix
}
| (Promote _ | Collect _ | End) as ev -> ev
;;
let interpret_event t time (event : Raw_trace.Event.t) =
match event with
| End -> t.callback time End
| Alloc { obj_id; _ } | Promote obj_id | Collect obj_id ->
let { interesting; defer_minor_allocations; collect_on_promotion; _ } =
t.filtered_trace
in
let return (out_event : Event.t) =
let () =
match t.mode with
| Preserve_times -> ()
| Preserve_backtraces ->
(match event, out_event with
| ( Alloc { backtrace_length = in_length; _ }
, Alloc { backtrace_length = out_length; _ } ) ->
t.prev_in_length <- in_length;
t.prev_out_length <- out_length;
t.max_next_common_prefix <- Int.max_value
| Alloc _, _ | _, Alloc _ -> assert false
| (Promote _ | Collect _ | End), (Promote _ | Collect _ | End) -> ())
in
t.callback time out_event
in
let skip () =
let () =
match t.mode with
| Preserve_times -> ()
| Preserve_backtraces ->
(match event with
| Alloc { common_prefix; _ } ->
t.max_next_common_prefix <- min common_prefix t.max_next_common_prefix
* Do n't * update prev_in_length , since its purpose is to know how to move the
out cursor * from the last event we interpreted *
out cursor *from the last event we interpreted* *)
| Promote _ | Collect _ | End -> ())
in
()
in
let interesting = interesting obj_id in
if not interesting
then skip ()
else (
match t.mode with
| Preserve_backtraces -> return (event |> conv_event t)
| Preserve_times ->
(match event with
| Alloc ({ obj_id; source = Minor; _ } as alloc) when defer_minor_allocations ->
Hashtbl.add_exn
t.deferring
~key:obj_id
~data:(Alloc { alloc with source = Major });
skip ()
| Promote obj_id when collect_on_promotion ->
Hash_set.strict_add_exn t.collected_early obj_id;
return (Collect obj_id)
| Promote obj_id when defer_minor_allocations ->
(match Hashtbl.find_and_remove t.deferring obj_id with
| None ->
raise
(Not_found_s
[%message "Missing deferred object" ~obj_id:((obj_id :> int) : int)])
| Some event -> return (event |> conv_event t))
| Collect obj_id
when collect_on_promotion && Hash_set.mem t.collected_early obj_id ->
Hash_set.remove t.collected_early obj_id
| Collect obj_id when defer_minor_allocations && Hashtbl.mem t.deferring obj_id
-> Hashtbl.remove t.deferring obj_id
| _ -> return (event |> conv_event t)))
;;
end
let iter_and_return_interpreter t ~mode ~record_call_sites f =
let interpreter =
Interpreter.create ~filtered_trace:t ~callback:f ~mode ~record_call_sites ()
in
let parse_backtraces =
match mode with
| Mode.Preserve_backtraces -> true
| Preserve_times -> false
in
Raw_trace.iter t.trace ~parse_backtraces (fun time event ->
Interpreter.interpret_event interpreter time event);
interpreter
;;
let iter t ~mode f =
let interpreter = iter_and_return_interpreter t ~mode ~record_call_sites:false f in
ignore (interpreter : Interpreter.t)
;;
let iter_and_gather_call_sites t ~mode f =
let interpreter = iter_and_return_interpreter t ~mode ~record_call_sites:true f in
Interpreter.call_sites interpreter
;;
|
5bf89253e0ad160e96f4e4e8fceae0ae39aff17ca3cc68b8347251de1e82f4aa | alanz/ghc-exactprint | Common.hs | {-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ViewPatterns #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# OPTIONS_GHC -fno - warn - orphans #
module Test.Common (
RoundtripReport (..)
, Report
, ParseFailure(..)
, ReportType(..)
, roundTripTest
, roundTripTestBC
, roundTripTestMD
, mkParsingTest
, getModSummaryForFile
, testList
, testPrefix
, Changer
, genTest
, noChange
, changeMakeDelta
, mkDebugOutput
, showErrorMessages
, LibDir
) where
import Language.Haskell.GHC.ExactPrint
import Language . Haskell . GHC.ExactPrint . ExactPrint
import Language.Haskell.GHC.ExactPrint.Utils
import Language.Haskell.GHC.ExactPrint.Parsers
import Language.Haskell.GHC.ExactPrint.Preprocess
import qualified Control.Monad.IO.Class as GHC
import qualified GHC as GHC hiding (parseModule)
import qualified GHC.Data . Bag as GHC
import qualified GHC.Driver.Session as GHC
import qualified GHC.Utils . Error as GHC
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import Data.List hiding (find)
import System.Directory
import Test.HUnit
import System.FilePath
testPrefix :: FilePath
testPrefix = "." </> "tests" </> "examples"
testList :: String -> [Test] -> Test
testList s ts = TestLabel s (TestList ts)
-- ---------------------------------------------------------------------
Roundtrip machinery
type Report = Either ParseFailure RoundtripReport
data RoundtripReport =
Report
{ debugTxt :: String
, status :: ReportType
Result of CPP if invoked
, inconsistent : : Maybe [ ( AnnSpan , ( , [ AnnSpan ] ) ) ]
}
data ParseFailure = ParseFailure String
data ReportType =
Success
| RoundTripFailure deriving (Eq, Show)
roundTripTest :: LibDir -> FilePath -> IO Report
roundTripTest libdir f = genTest libdir noChange f f
roundTripTestBC :: LibDir -> FilePath -> IO Report
roundTripTestBC libdir f = genTest libdir changeBalanceComments f f
roundTripTestMD :: LibDir -> FilePath -> IO Report
roundTripTestMD libdir f = genTest libdir changeMakeDelta f f
mkParsingTest :: (FilePath -> IO Report) -> FilePath -> FilePath -> Test
mkParsingTest tester dir fp =
let basename = testPrefix </> dir </> fp
writeFailure = writeFile (basename <.> "out")
writeHsPP = writeFile (basename <.> "hspp")
writeIncons s = writeFile ( basename < . > " incons " ) ( showGhc s )
in
TestCase (do r <- either (\(ParseFailure s) -> error (s ++ basename)) id
<$> tester basename
writeFailure (debugTxt r)
forM _ ( inconsistent r ) writeIncons
forM_ (cppStatus r) writeHsPP
assertBool fp (status r == Success))
type Changer = LibDir -> (GHC.ParsedSource -> IO GHC.ParsedSource)
noChange :: Changer
noChange _libdir parsed = return parsed
changeBalanceComments :: Changer
changeBalanceComments _libdir top = do
let (GHC.L l p) = makeDeltaAst top
-- let (GHC.L l p) = top
let decls0 = GHC.hsmodDecls p
(decls,_,w) = runTransform (balanceCommentsList decls0)
let p2 = p { GHC.hsmodDecls = decls}
debugM $ "changeBalanceComments:\n" ++ unlines w
return (GHC.L l p2)
changeMakeDelta :: Changer
changeMakeDelta _libdir m = do
return (makeDeltaAst m)
genTest :: LibDir -> Changer -> FilePath -> FilePath -> IO Report
genTest libdir f origFile expectedFile = do
res <- parseModuleEpAnnsWithCpp libdir defaultCppOptions origFile
expected <- GHC.liftIO $ readFileGhc expectedFile
orig <- GHC.liftIO $ readFileGhc origFile
-- let pristine = removeSpaces expected
let pristine = expected
case res of
Left m -> return . Left $ ParseFailure (showErrorMessages m)
Right (injectedComments, dflags, pmod) -> do
(printed', pmod') <- GHC.liftIO (runRoundTrip libdir f pmod injectedComments)
let useCpp = GHC.xopt LangExt.Cpp dflags
printed = trimPrinted printed'
adds an extra newline character
-- Do not remove this line!
trimPrinted p = if useCpp
then unlines $ take (length (lines pristine)) (lines p)
else p
debugTxt = mkDebugOutput origFile printed pristine pmod'
consistency = pmod
-- inconsistent = if null consistency then Nothing else Just consistency
status = if printed == pristine then Success else RoundTripFailure
cppStatus = if useCpp then Just orig else Nothing
return $ Right Report {..}
mkDebugOutput :: FilePath -> String -> String
-> GHC.ParsedSource -> String
mkDebugOutput filename printed original parsed =
intercalate sep [ printed
, filename
, "lengths:" ++ show (length printed,length original) ++ "\n"
, parsed
, showAst parsed
,
]
where
sep = "\n==============\n"
runRoundTrip :: LibDir
-> Changer
-> GHC.Located GHC.HsModule
-> [GHC.LEpaComment]
-> IO (String, GHC.ParsedSource)
runRoundTrip libdir f !parsedOrig cs = do
let !parsedOrigWithComments = insertCppComments parsedOrig cs
pmod <- f libdir parsedOrigWithComments
let !printed = exactPrint pmod
return (printed, pmod)
-- ---------------------------------------------------------------------`
canonicalizeGraph ::
[GHC.ModSummary] -> IO [(Maybe (FilePath), GHC.ModSummary)]
canonicalizeGraph graph = do
let mm = map (\m -> (GHC.ml_hs_file $ GHC.ms_location m, m)) graph
canon ((Just fp),m) = do
fp' <- canonicalizePath fp
return $ (Just fp',m)
canon (Nothing,m) = return (Nothing,m)
mm' <- mapM canon mm
return mm'
-- ---------------------------------------------------------------------
getModSummaryForFile :: (GHC.GhcMonad m) => FilePath -> m (Maybe GHC.ModSummary)
getModSummaryForFile fileName = do
cfileName <- GHC.liftIO $ canonicalizePath fileName
graph <- GHC.getModuleGraph
cgraph <- GHC.liftIO $ canonicalizeGraph (GHC.mgModSummaries graph)
let mm = filter (\(mfn,_ms) -> mfn == Just cfileName) cgraph
case mm of
[] -> return Nothing
fs -> return (Just (snd $ head fs))
-- ---------------------------------------------------------------------
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/3b36f5d0a498e31d882fe111304b2cf5ca6cad22/tests/Test/Common.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings #
---------------------------------------------------------------------
let (GHC.L l p) = top
let pristine = removeSpaces expected
Do not remove this line!
inconsistent = if null consistency then Nothing else Just consistency
---------------------------------------------------------------------`
---------------------------------------------------------------------
--------------------------------------------------------------------- | # LANGUAGE FlexibleContexts #
# LANGUAGE ViewPatterns #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# OPTIONS_GHC -fno - warn - orphans #
module Test.Common (
RoundtripReport (..)
, Report
, ParseFailure(..)
, ReportType(..)
, roundTripTest
, roundTripTestBC
, roundTripTestMD
, mkParsingTest
, getModSummaryForFile
, testList
, testPrefix
, Changer
, genTest
, noChange
, changeMakeDelta
, mkDebugOutput
, showErrorMessages
, LibDir
) where
import Language.Haskell.GHC.ExactPrint
import Language . Haskell . GHC.ExactPrint . ExactPrint
import Language.Haskell.GHC.ExactPrint.Utils
import Language.Haskell.GHC.ExactPrint.Parsers
import Language.Haskell.GHC.ExactPrint.Preprocess
import qualified Control.Monad.IO.Class as GHC
import qualified GHC as GHC hiding (parseModule)
import qualified GHC.Data . Bag as GHC
import qualified GHC.Driver.Session as GHC
import qualified GHC.Utils . Error as GHC
import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import Data.List hiding (find)
import System.Directory
import Test.HUnit
import System.FilePath
testPrefix :: FilePath
testPrefix = "." </> "tests" </> "examples"
testList :: String -> [Test] -> Test
testList s ts = TestLabel s (TestList ts)
Roundtrip machinery
type Report = Either ParseFailure RoundtripReport
data RoundtripReport =
Report
{ debugTxt :: String
, status :: ReportType
Result of CPP if invoked
, inconsistent : : Maybe [ ( AnnSpan , ( , [ AnnSpan ] ) ) ]
}
data ParseFailure = ParseFailure String
data ReportType =
Success
| RoundTripFailure deriving (Eq, Show)
roundTripTest :: LibDir -> FilePath -> IO Report
roundTripTest libdir f = genTest libdir noChange f f
roundTripTestBC :: LibDir -> FilePath -> IO Report
roundTripTestBC libdir f = genTest libdir changeBalanceComments f f
roundTripTestMD :: LibDir -> FilePath -> IO Report
roundTripTestMD libdir f = genTest libdir changeMakeDelta f f
mkParsingTest :: (FilePath -> IO Report) -> FilePath -> FilePath -> Test
mkParsingTest tester dir fp =
let basename = testPrefix </> dir </> fp
writeFailure = writeFile (basename <.> "out")
writeHsPP = writeFile (basename <.> "hspp")
writeIncons s = writeFile ( basename < . > " incons " ) ( showGhc s )
in
TestCase (do r <- either (\(ParseFailure s) -> error (s ++ basename)) id
<$> tester basename
writeFailure (debugTxt r)
forM _ ( inconsistent r ) writeIncons
forM_ (cppStatus r) writeHsPP
assertBool fp (status r == Success))
type Changer = LibDir -> (GHC.ParsedSource -> IO GHC.ParsedSource)
noChange :: Changer
noChange _libdir parsed = return parsed
changeBalanceComments :: Changer
changeBalanceComments _libdir top = do
let (GHC.L l p) = makeDeltaAst top
let decls0 = GHC.hsmodDecls p
(decls,_,w) = runTransform (balanceCommentsList decls0)
let p2 = p { GHC.hsmodDecls = decls}
debugM $ "changeBalanceComments:\n" ++ unlines w
return (GHC.L l p2)
changeMakeDelta :: Changer
changeMakeDelta _libdir m = do
return (makeDeltaAst m)
genTest :: LibDir -> Changer -> FilePath -> FilePath -> IO Report
genTest libdir f origFile expectedFile = do
res <- parseModuleEpAnnsWithCpp libdir defaultCppOptions origFile
expected <- GHC.liftIO $ readFileGhc expectedFile
orig <- GHC.liftIO $ readFileGhc origFile
let pristine = expected
case res of
Left m -> return . Left $ ParseFailure (showErrorMessages m)
Right (injectedComments, dflags, pmod) -> do
(printed', pmod') <- GHC.liftIO (runRoundTrip libdir f pmod injectedComments)
let useCpp = GHC.xopt LangExt.Cpp dflags
printed = trimPrinted printed'
adds an extra newline character
trimPrinted p = if useCpp
then unlines $ take (length (lines pristine)) (lines p)
else p
debugTxt = mkDebugOutput origFile printed pristine pmod'
consistency = pmod
status = if printed == pristine then Success else RoundTripFailure
cppStatus = if useCpp then Just orig else Nothing
return $ Right Report {..}
mkDebugOutput :: FilePath -> String -> String
-> GHC.ParsedSource -> String
mkDebugOutput filename printed original parsed =
intercalate sep [ printed
, filename
, "lengths:" ++ show (length printed,length original) ++ "\n"
, parsed
, showAst parsed
,
]
where
sep = "\n==============\n"
runRoundTrip :: LibDir
-> Changer
-> GHC.Located GHC.HsModule
-> [GHC.LEpaComment]
-> IO (String, GHC.ParsedSource)
runRoundTrip libdir f !parsedOrig cs = do
let !parsedOrigWithComments = insertCppComments parsedOrig cs
pmod <- f libdir parsedOrigWithComments
let !printed = exactPrint pmod
return (printed, pmod)
canonicalizeGraph ::
[GHC.ModSummary] -> IO [(Maybe (FilePath), GHC.ModSummary)]
canonicalizeGraph graph = do
let mm = map (\m -> (GHC.ml_hs_file $ GHC.ms_location m, m)) graph
canon ((Just fp),m) = do
fp' <- canonicalizePath fp
return $ (Just fp',m)
canon (Nothing,m) = return (Nothing,m)
mm' <- mapM canon mm
return mm'
getModSummaryForFile :: (GHC.GhcMonad m) => FilePath -> m (Maybe GHC.ModSummary)
getModSummaryForFile fileName = do
cfileName <- GHC.liftIO $ canonicalizePath fileName
graph <- GHC.getModuleGraph
cgraph <- GHC.liftIO $ canonicalizeGraph (GHC.mgModSummaries graph)
let mm = filter (\(mfn,_ms) -> mfn == Just cfileName) cgraph
case mm of
[] -> return Nothing
fs -> return (Just (snd $ head fs))
|
0cdeddc6c21a7ba5e3b6fa783e7a27f2072d76acde1b1a46852f9fca5101737b | openmusic-project/openmusic | edition.lisp | ;=========================================================================
OpenMusic : Visual Programming Language for Music Composition
;
Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France .
;
This file is part of the OpenMusic environment sources
;
OpenMusic 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.
;
OpenMusic 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 OpenMusic . If not , see < / > .
;
;=========================================================================
Music package
authors , ,
;=========================================================================
(in-package :om)
(defmethod editor-compatible-params-p ((ed1 scoreeditor) (ed2 scoreeditor)) t)
(defmethod default-edition-params ((self simple-container))
(get-default-score-params self))
(defmethod get-default-score-params ((self t))
(pairlis '(approx fontsize staff cmnpref deltapict outport inport player
zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)
(list *global-midi-approx* *music-fontsize* *default-satff* (make-instance 'edition-values) (om-make-point 0 0)
nil nil *default-score-player*
1 nil 1000 0 (om-make-point 370 280) (om-make-point 400 20) 0 1 :normal t nil)))
(defmethod get-default-score-params ((self chord))
(pairlis '(approx fontsize staff cmnpref deltapict outport inport player
zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)
(list *global-midi-approx* *music-fontsize* *default-satff* (make-instance 'edition-values) (om-make-point 0 0)
nil nil *default-score-player*
1 nil 1000 0 (om-make-point 370 280) (om-make-point 400 20) 0 0 :normal t nil)))
(defmethod get-default-score-params ((self note))
(pairlis '(approx fontsize staff cmnpref deltapict outport inport player
zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)
(list *global-midi-approx* *music-fontsize* *default-satff* (make-instance 'edition-values) (om-make-point 0 0) nil nil *default-score-player*
1 nil 1000 0 (om-make-point 370 280) (om-make-point 300 20) 0 0 :normal t nil)))
( defmethod set - edition - params ( ( self simple - container ) box )
( setf ( edition - params box ) ( get - default - score - params self ) ) )
(defmethod corrige-edition-params ((self simple-container) params)
(let ((rep params))
(unless (assoc 'deltapict params)
(setf rep (pairlis (list 'deltapict) (list (om-make-point 0 0)) rep)))
;(unless (assoc 'player params)
( setf rep ( pairlis ( list ' player ) ( list : midishare ) rep ) ) )
(unless (assoc 'zoom params)
(setf rep (pairlis (list 'zoom) (list 1) rep)))
(unless (assoc 'obj-mode params)
(setf rep (pairlis (list 'obj-mode) (list 0) rep)))
(unless (assoc 'cmnpref params)
(setf rep (pairlis (list 'cmnpref) (list (make-instance 'edition-values)) rep)))
(unless (new-ed-params? (cdr (assoc 'cmnpref rep)))
(rplacd (assoc 'cmnpref rep) (make-instance 'edition-values)))
(unless (assoc 'notechancolor? params)
(setf rep (pairlis (list 'notechancolor?) (list nil) rep)))
(unless (assoc 'grillestep params)
(setf rep (pairlis (list 'grillestep) (list 1000) rep)))
(unless (assoc 'mode params)
(setf rep (pairlis (list 'mode) (list 0) rep)))
(unless (assoc 'winsize params)
(setf rep (pairlis (list 'winsize) (list (om-make-point 370 280)) rep)))
(unless (assoc 'winpos params)
(setf rep (pairlis (list 'winpos) (list (om-make-point 10 40)) rep)))
(unless (assoc 'show-stems params)
(setf rep (pairlis (list 'show-stems) (list t) rep)))
(unless (assoc 'scale params)
(setf rep (pairlis (list 'scale) (list nil) rep)))
(rplacd (assoc 'deltapict rep) (om-correct-point (cdr (assoc 'deltapict rep))))
rep))
(defmethod corrige-edition-params ((self score-element) params)
(when (and *force-score-player* (assoc 'player params)
(not (equal (cdr (assoc 'player params)) *default-score-player*)))
(print (format nil "Warning: replacing player of ~A with default player: ~A (see 'force player' options in the MIDI preferences)." self *default-score-player*))
(rplacd (assoc 'player params) *default-score-player*))
(call-next-method self params))
;=====================================================================
;PARAMETRES D'EDITION
;=====================================================================
(defclas fdoc ()
((page-list :initform nil)))
(defmethod howmany-pages ((self fdoc))
(length (page-list self)))
(defmethod howmany-lines ((self fdoc) i)
(length (line-list (nth i (page-list self)))))
(defclas fpage ()
((line-list :initform nil)))
(defclas fline ()
((line-info :initform nil)))
; line-info = ( (voice #) ... (voice #) )
(defclass edition-values ()
((paper-size :initform (om-make-point 600 800) :accessor paper-size :initarg :paper-size)
(top-margin :initform 2 :accessor top-margin :initarg :top-margin)
(left-margin :initform 1 :accessor left-margin :initarg :left-margin)
(right-margin :initform 1 :accessor right-margin :initarg :right-margin)
(bottom-margin :initform 1 :accessor bottom-margin :initarg :bottom-margin)
(orientation :initform nil :accessor orientation :initarg :orientation)
(scale :initform nil :accessor scale :initarg :scale)
(system-space :initform '(1) :accessor system-space :initarg :system-space)
(system-color :initform nil :accessor system-color :initarg :system-color)
(line-space :initform 1 :accessor line-space :initarg :line-space)
(fdoc :initform (make-instance 'fdoc) :accessor fdoc :initarg :fdoc)
(title :initform nil :accessor title :initarg :title)
(picts-list :initform nil :accessor picts-list :initarg :picts-list)
(show-title? :initform nil :accessor show-title? :initarg :show-title?)
(show-page? :initform nil :accessor show-page? :initarg :show-page?)
(sheet-id :initform nil :accessor sheet-id :initarg :sheet-id)
(page-mode :initform nil :accessor page-mode :initarg :page-mode)))
(defmethod new-ed-params? ((self edition-values)) t)
(defmethod new-ed-params? ((self t)) nil)
(defmethod omNG-save ((self edition-values) &optional (values? nil))
`(let ((newobj (make-instance ',(type-of self))))
(setf (paper-size newobj) ,(om-save-point (paper-size self)))
(setf (top-margin newobj) ,(top-margin self))
(setf (left-margin newobj) ,(left-margin self))
(setf (right-margin newobj) ,(right-margin self))
(setf (bottom-margin newobj) ,(bottom-margin self))
(setf (orientation newobj) ,(orientation self))
(setf (scale newobj) ,(scale self))
(setf (system-space newobj) ',(system-space self))
(setf (system-color newobj) ',(omng-save (system-color self)))
(setf (line-space newobj) ,(line-space self))
(setf (title newobj) ,(title self))
(setf (show-title? newobj) ,(show-title? self))
(setf (show-page? newobj) ,(show-page? self))
(setf (sheet-id newobj) ,(sheet-id self))
(setf (page-mode newobj) ,(page-mode self))
newobj))
;==============
(defmethod score-paper-size ((self t) &optional val)
(om-score-paper-size))
(defmethod score-top-margin ((self t) &optional val)
(if val
(setf (top-margin (edition-values self)) val)
(top-margin (edition-values self))))
(defmethod score-left-margin ((self t) &optional val)
(if val
(setf (left-margin (edition-values self)) val)
(if (not *old-print-mode*) 0 (left-margin (edition-values self)))))
(defmethod score-right-margin ((self t) &optional val)
(if val
(setf (right-margin (edition-values self)) val)
(if (not *old-print-mode*) 0 (right-margin (edition-values self)))))
(defmethod score-bottom-margin ((self t) &optional val)
(if val
(setf (bottom-margin (edition-values self)) val)
(bottom-margin (edition-values self))))
(defmethod score-orientation ((self t) &optional val)
(if val
(setf (orientation (edition-values self)) val)
(orientation (edition-values self))))
(defmethod score-scale ((self t) &optional val)
(if val
(setf (scale (edition-values self)) val)
(scale (edition-values self))))
(defmethod score-system-space ((self t) &optional val)
(if val
(setf (system-space (edition-values self)) val)
(system-space (edition-values self))))
(defmethod score-line-space ((self t) &optional val)
(if val
(setf (line-space (edition-values self)) val)
(line-space (edition-values self))))
(defmethod score-fdoc ((self t) &optional val)
(if val
(setf (fdoc (edition-values self)) val)
(fdoc (edition-values self))))
(defmethod score-title ((self t) &optional val)
(if val
(setf (title (edition-values self)) val)
(title (edition-values self))))
(defmethod score-show-title? ((self t) &optional val)
(if val
(setf (show-title? (edition-values self)) val)
(show-title? (edition-values self))))
(defmethod score-show-page? ((self t) &optional val)
(if val
(setf (show-page? (edition-values self)) val)
(show-page? (edition-values self))))
(defmethod score-sheet-id ((self t) &optional val)
(if val
(setf (sheet-id (edition-values self)) val)
(sheet-id (edition-values self))))
(defmethod score-page-mode ((self t))
(page-mode (edition-values self)))
(defmethod set-score-page-mode ((self t) val)
(setf (page-mode (edition-values self)) val))
(defmethod score-picts-list ((self t) &optional val)
(if val
(setf (picts-list (edition-values self)) val)
(picts-list (edition-values self))))
(defmethod score-widht ((self t) size)
(- (om-point-h (score-paper-size self)) (* size (score-left-margin self)) (* size (score-right-margin self))))
(defmethod score-height ((self t) size)
(- (om-point-v (score-paper-size self)) (* size (score-bottom-margin self)) (* size (score-top-margin self))))
;==============
(defmethod correct-page-par ((self scoreEditor) par)
(if (new-ed-params? par) par
(let ((rep (make-instance 'edition-values)))
(set-edit-param self 'cmnpref rep)
rep)))
(defclass page-pointer ()
((curpage :initform 0 :accessor curpage)
(curline :initform 0 :accessor curline)
(curelem :initform 0 :accessor curelem)
(score :initform nil :accessor score :initarg :score)
(page-voice :initform nil :accessor page-voice :initarg :page-voice)
(view :initform nil :accessor view :initarg :view)
(linesizex :initform nil :accessor linesizex :initarg :linesizex)
(linesizey :initform nil :accessor linesizey :initarg :linesizey)))
(defmethod move-page-pointer ((self page-pointer))
(let* ((fdoc (score-fdoc (score self)))
(curpage (nth (curpage self) (page-list fdoc)))
(curline (nth (curline self) (line-list curpage)))
(hmlines (length (line-list curpage)))
(hmelem (nth (page-voice self) (line-info curline))))
(setf (curelem self) (+ (curelem self) 1))
(if (= (curelem self) hmelem)
(progn
(setf (curelem self) 0)
(setf (curline self) (+ (curline self) 1))
(if (and (= (curline self) hmlines) )
(progn
(setf (curline self) 0)
(setf (curpage self) (+ (curpage self) 1))
(setf (view self) (nth (curpage self) (score-picts-list (score self))))))))))
(defmethod compute-delat-x-y ((self page-pointer))
(let* ((score (score self))
(fdoc (score-fdoc score))
(linesizex (linesizex self))
(linesizey (linesizey self))
(repx 0) (repy 0))
(loop for i from 0 to (- (curpage self) 1) do
(setf repx (+ repx (* linesizex (length (line-list (nth i (page-list fdoc))))))))
(setf repx (+ repx (* linesizex (curline self))))
(setf repy (* linesizey (curline self)))
(list repx repy)))
;ca sert a rien ???
(defmethod compute-delat-x-y-zoom ((self page-pointer))
(let* ((score (score self))
(fdoc (score-fdoc score))
(linesizex (linesizex self))
(linesizey (linesizey self))
(repx 0) (repy 0))
(loop for i from 0 to (- (curpage self) 1) do
(setf repx (+ repx (* linesizex (length (line-list (nth i (page-list fdoc))))))))
(setf repx (+ repx (* linesizex (curline self))))
(setf repy (* linesizey (curline self)))
(list repx repy)))
(defmethod editor-page-setup ((panel scorepanel))
(let* ((rep (show-page-score-dialog panel)))
(when (and rep (eval `(and ,.rep)))
(score-top-margin panel (first rep))
(score-left-margin panel (second rep))
(score-bottom-margin panel (third rep))
(score-right-margin panel (fourth rep))
(score-line-space panel (fifth rep))
(update-panel panel))))
(defmethod show-page-score-dialog ((self scorepanel))
(let* ((params (list (score-top-margin self) (score-left-margin self) (score-bottom-margin self) (score-right-margin self) (score-line-space self) ))
(font *om-default-font1*)
(win (om-make-window 'om-dialog
:window-title "Page Setup"
:position :centered
:close t
:resizable nil
:maximize nil
:size (om-make-point 290 175)))
(y 0)
(defvals '("2" "1" "1" "1" "1"))
paramtxt valtxt intertxt top left bottom right inter okb annulerb defb
)
(setf paramtxt (om-make-dialog-item 'om-static-text (om-make-point 20 y) (om-make-point 120 20)
"Top: Left:" :font font))
(incf y 26)
(setf top (om-make-dialog-item 'om-editable-text (om-make-point 20 y)
(om-make-point 50 30) (num2string (first params))))
(setf left (om-make-dialog-item 'om-editable-text (om-make-point 100 y)
(om-make-point 50 30) (num2string (second params))))
(incf y 40)
(setf valtxt (om-make-dialog-item 'om-static-text (om-make-point 20 y) (om-make-point 140 20)
"Bottom: Right:" :font font))
(incf y 26)
(setf bottom (om-make-dialog-item 'om-editable-text (om-make-point 20 y)
(om-make-point 50 30) (num2string (third defvals))))
(setf right (om-make-dialog-item 'om-editable-text (om-make-point 100 y)
(om-make-point 50 30) (num2string (fourth params))))
(setf y 66)
(setf intertxt (om-make-dialog-item 'om-static-text (om-make-point 200 y) (om-make-point 130 40)
(str-check "Inter-line:")
:font font))
(incf y 26)
(setf inter (om-make-dialog-item 'om-editable-text (om-make-point 200 y)
(om-make-point 50 30) (num2string (fifth params))))
(incf y 40)
(setf defb (om-make-dialog-item 'om-button
(om-make-point 20 y)
(om-make-point 70 25)
"Defaults"
:font font
:di-action (om-dialog-item-act item
(declare (ignore item))
(om-set-dialog-item-text top (first defvals))
(om-set-dialog-item-text left (second defvals))
(om-set-dialog-item-text bottom (third defvals))
(om-set-dialog-item-text right (fourth defvals))
(om-set-dialog-item-text inter (fifth defvals)))))
(setf okb (om-make-dialog-item 'om-button
(om-make-point 200 y)
(om-make-point 70 25)
"OK"
:font font
:di-action (om-dialog-item-act item
(declare (ignore item))
(om-return-from-modal-dialog win
(list (string2num (om-dialog-item-text top))
(string2num (om-dialog-item-text left))
(string2num (om-dialog-item-text bottom))
(string2num (om-dialog-item-text right))
(string2num (om-dialog-item-text inter)))))))
(setf annulerb (om-make-dialog-item 'om-button
(om-make-point 110 y)
(om-make-point 70 25)
"Annuler"
:font font
:di-action (om-dialog-item-act item
(declare (ignore item))
(om-return-from-modal-dialog win nil))))
(om-add-subviews win paramtxt valtxt intertxt inter top left bottom right okb annulerb defb)
(om-modal-dialog win)))
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/projects/musicproject/editor/scoreeditor/edition.lisp | lisp | =========================================================================
(at your option) any later version.
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.
=========================================================================
=========================================================================
(unless (assoc 'player params)
=====================================================================
PARAMETRES D'EDITION
=====================================================================
line-info = ( (voice #) ... (voice #) )
==============
==============
ca sert a rien ???
| OpenMusic : Visual Programming Language for Music Composition
Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France .
This file is part of the OpenMusic environment sources
OpenMusic 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
OpenMusic is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with OpenMusic . If not , see < / > .
Music package
authors , ,
(in-package :om)
(defmethod editor-compatible-params-p ((ed1 scoreeditor) (ed2 scoreeditor)) t)
(defmethod default-edition-params ((self simple-container))
(get-default-score-params self))
(defmethod get-default-score-params ((self t))
(pairlis '(approx fontsize staff cmnpref deltapict outport inport player
zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)
(list *global-midi-approx* *music-fontsize* *default-satff* (make-instance 'edition-values) (om-make-point 0 0)
nil nil *default-score-player*
1 nil 1000 0 (om-make-point 370 280) (om-make-point 400 20) 0 1 :normal t nil)))
(defmethod get-default-score-params ((self chord))
(pairlis '(approx fontsize staff cmnpref deltapict outport inport player
zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)
(list *global-midi-approx* *music-fontsize* *default-satff* (make-instance 'edition-values) (om-make-point 0 0)
nil nil *default-score-player*
1 nil 1000 0 (om-make-point 370 280) (om-make-point 400 20) 0 0 :normal t nil)))
(defmethod get-default-score-params ((self note))
(pairlis '(approx fontsize staff cmnpref deltapict outport inport player
zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)
(list *global-midi-approx* *music-fontsize* *default-satff* (make-instance 'edition-values) (om-make-point 0 0) nil nil *default-score-player*
1 nil 1000 0 (om-make-point 370 280) (om-make-point 300 20) 0 0 :normal t nil)))
( defmethod set - edition - params ( ( self simple - container ) box )
( setf ( edition - params box ) ( get - default - score - params self ) ) )
(defmethod corrige-edition-params ((self simple-container) params)
(let ((rep params))
(unless (assoc 'deltapict params)
(setf rep (pairlis (list 'deltapict) (list (om-make-point 0 0)) rep)))
( setf rep ( pairlis ( list ' player ) ( list : midishare ) rep ) ) )
(unless (assoc 'zoom params)
(setf rep (pairlis (list 'zoom) (list 1) rep)))
(unless (assoc 'obj-mode params)
(setf rep (pairlis (list 'obj-mode) (list 0) rep)))
(unless (assoc 'cmnpref params)
(setf rep (pairlis (list 'cmnpref) (list (make-instance 'edition-values)) rep)))
(unless (new-ed-params? (cdr (assoc 'cmnpref rep)))
(rplacd (assoc 'cmnpref rep) (make-instance 'edition-values)))
(unless (assoc 'notechancolor? params)
(setf rep (pairlis (list 'notechancolor?) (list nil) rep)))
(unless (assoc 'grillestep params)
(setf rep (pairlis (list 'grillestep) (list 1000) rep)))
(unless (assoc 'mode params)
(setf rep (pairlis (list 'mode) (list 0) rep)))
(unless (assoc 'winsize params)
(setf rep (pairlis (list 'winsize) (list (om-make-point 370 280)) rep)))
(unless (assoc 'winpos params)
(setf rep (pairlis (list 'winpos) (list (om-make-point 10 40)) rep)))
(unless (assoc 'show-stems params)
(setf rep (pairlis (list 'show-stems) (list t) rep)))
(unless (assoc 'scale params)
(setf rep (pairlis (list 'scale) (list nil) rep)))
(rplacd (assoc 'deltapict rep) (om-correct-point (cdr (assoc 'deltapict rep))))
rep))
(defmethod corrige-edition-params ((self score-element) params)
(when (and *force-score-player* (assoc 'player params)
(not (equal (cdr (assoc 'player params)) *default-score-player*)))
(print (format nil "Warning: replacing player of ~A with default player: ~A (see 'force player' options in the MIDI preferences)." self *default-score-player*))
(rplacd (assoc 'player params) *default-score-player*))
(call-next-method self params))
(defclas fdoc ()
((page-list :initform nil)))
(defmethod howmany-pages ((self fdoc))
(length (page-list self)))
(defmethod howmany-lines ((self fdoc) i)
(length (line-list (nth i (page-list self)))))
(defclas fpage ()
((line-list :initform nil)))
(defclas fline ()
((line-info :initform nil)))
(defclass edition-values ()
((paper-size :initform (om-make-point 600 800) :accessor paper-size :initarg :paper-size)
(top-margin :initform 2 :accessor top-margin :initarg :top-margin)
(left-margin :initform 1 :accessor left-margin :initarg :left-margin)
(right-margin :initform 1 :accessor right-margin :initarg :right-margin)
(bottom-margin :initform 1 :accessor bottom-margin :initarg :bottom-margin)
(orientation :initform nil :accessor orientation :initarg :orientation)
(scale :initform nil :accessor scale :initarg :scale)
(system-space :initform '(1) :accessor system-space :initarg :system-space)
(system-color :initform nil :accessor system-color :initarg :system-color)
(line-space :initform 1 :accessor line-space :initarg :line-space)
(fdoc :initform (make-instance 'fdoc) :accessor fdoc :initarg :fdoc)
(title :initform nil :accessor title :initarg :title)
(picts-list :initform nil :accessor picts-list :initarg :picts-list)
(show-title? :initform nil :accessor show-title? :initarg :show-title?)
(show-page? :initform nil :accessor show-page? :initarg :show-page?)
(sheet-id :initform nil :accessor sheet-id :initarg :sheet-id)
(page-mode :initform nil :accessor page-mode :initarg :page-mode)))
(defmethod new-ed-params? ((self edition-values)) t)
(defmethod new-ed-params? ((self t)) nil)
(defmethod omNG-save ((self edition-values) &optional (values? nil))
`(let ((newobj (make-instance ',(type-of self))))
(setf (paper-size newobj) ,(om-save-point (paper-size self)))
(setf (top-margin newobj) ,(top-margin self))
(setf (left-margin newobj) ,(left-margin self))
(setf (right-margin newobj) ,(right-margin self))
(setf (bottom-margin newobj) ,(bottom-margin self))
(setf (orientation newobj) ,(orientation self))
(setf (scale newobj) ,(scale self))
(setf (system-space newobj) ',(system-space self))
(setf (system-color newobj) ',(omng-save (system-color self)))
(setf (line-space newobj) ,(line-space self))
(setf (title newobj) ,(title self))
(setf (show-title? newobj) ,(show-title? self))
(setf (show-page? newobj) ,(show-page? self))
(setf (sheet-id newobj) ,(sheet-id self))
(setf (page-mode newobj) ,(page-mode self))
newobj))
(defmethod score-paper-size ((self t) &optional val)
(om-score-paper-size))
(defmethod score-top-margin ((self t) &optional val)
(if val
(setf (top-margin (edition-values self)) val)
(top-margin (edition-values self))))
(defmethod score-left-margin ((self t) &optional val)
(if val
(setf (left-margin (edition-values self)) val)
(if (not *old-print-mode*) 0 (left-margin (edition-values self)))))
(defmethod score-right-margin ((self t) &optional val)
(if val
(setf (right-margin (edition-values self)) val)
(if (not *old-print-mode*) 0 (right-margin (edition-values self)))))
(defmethod score-bottom-margin ((self t) &optional val)
(if val
(setf (bottom-margin (edition-values self)) val)
(bottom-margin (edition-values self))))
(defmethod score-orientation ((self t) &optional val)
(if val
(setf (orientation (edition-values self)) val)
(orientation (edition-values self))))
(defmethod score-scale ((self t) &optional val)
(if val
(setf (scale (edition-values self)) val)
(scale (edition-values self))))
(defmethod score-system-space ((self t) &optional val)
(if val
(setf (system-space (edition-values self)) val)
(system-space (edition-values self))))
(defmethod score-line-space ((self t) &optional val)
(if val
(setf (line-space (edition-values self)) val)
(line-space (edition-values self))))
(defmethod score-fdoc ((self t) &optional val)
(if val
(setf (fdoc (edition-values self)) val)
(fdoc (edition-values self))))
(defmethod score-title ((self t) &optional val)
(if val
(setf (title (edition-values self)) val)
(title (edition-values self))))
(defmethod score-show-title? ((self t) &optional val)
(if val
(setf (show-title? (edition-values self)) val)
(show-title? (edition-values self))))
(defmethod score-show-page? ((self t) &optional val)
(if val
(setf (show-page? (edition-values self)) val)
(show-page? (edition-values self))))
(defmethod score-sheet-id ((self t) &optional val)
(if val
(setf (sheet-id (edition-values self)) val)
(sheet-id (edition-values self))))
(defmethod score-page-mode ((self t))
(page-mode (edition-values self)))
(defmethod set-score-page-mode ((self t) val)
(setf (page-mode (edition-values self)) val))
(defmethod score-picts-list ((self t) &optional val)
(if val
(setf (picts-list (edition-values self)) val)
(picts-list (edition-values self))))
(defmethod score-widht ((self t) size)
(- (om-point-h (score-paper-size self)) (* size (score-left-margin self)) (* size (score-right-margin self))))
(defmethod score-height ((self t) size)
(- (om-point-v (score-paper-size self)) (* size (score-bottom-margin self)) (* size (score-top-margin self))))
(defmethod correct-page-par ((self scoreEditor) par)
(if (new-ed-params? par) par
(let ((rep (make-instance 'edition-values)))
(set-edit-param self 'cmnpref rep)
rep)))
(defclass page-pointer ()
((curpage :initform 0 :accessor curpage)
(curline :initform 0 :accessor curline)
(curelem :initform 0 :accessor curelem)
(score :initform nil :accessor score :initarg :score)
(page-voice :initform nil :accessor page-voice :initarg :page-voice)
(view :initform nil :accessor view :initarg :view)
(linesizex :initform nil :accessor linesizex :initarg :linesizex)
(linesizey :initform nil :accessor linesizey :initarg :linesizey)))
(defmethod move-page-pointer ((self page-pointer))
(let* ((fdoc (score-fdoc (score self)))
(curpage (nth (curpage self) (page-list fdoc)))
(curline (nth (curline self) (line-list curpage)))
(hmlines (length (line-list curpage)))
(hmelem (nth (page-voice self) (line-info curline))))
(setf (curelem self) (+ (curelem self) 1))
(if (= (curelem self) hmelem)
(progn
(setf (curelem self) 0)
(setf (curline self) (+ (curline self) 1))
(if (and (= (curline self) hmlines) )
(progn
(setf (curline self) 0)
(setf (curpage self) (+ (curpage self) 1))
(setf (view self) (nth (curpage self) (score-picts-list (score self))))))))))
(defmethod compute-delat-x-y ((self page-pointer))
(let* ((score (score self))
(fdoc (score-fdoc score))
(linesizex (linesizex self))
(linesizey (linesizey self))
(repx 0) (repy 0))
(loop for i from 0 to (- (curpage self) 1) do
(setf repx (+ repx (* linesizex (length (line-list (nth i (page-list fdoc))))))))
(setf repx (+ repx (* linesizex (curline self))))
(setf repy (* linesizey (curline self)))
(list repx repy)))
(defmethod compute-delat-x-y-zoom ((self page-pointer))
(let* ((score (score self))
(fdoc (score-fdoc score))
(linesizex (linesizex self))
(linesizey (linesizey self))
(repx 0) (repy 0))
(loop for i from 0 to (- (curpage self) 1) do
(setf repx (+ repx (* linesizex (length (line-list (nth i (page-list fdoc))))))))
(setf repx (+ repx (* linesizex (curline self))))
(setf repy (* linesizey (curline self)))
(list repx repy)))
(defmethod editor-page-setup ((panel scorepanel))
(let* ((rep (show-page-score-dialog panel)))
(when (and rep (eval `(and ,.rep)))
(score-top-margin panel (first rep))
(score-left-margin panel (second rep))
(score-bottom-margin panel (third rep))
(score-right-margin panel (fourth rep))
(score-line-space panel (fifth rep))
(update-panel panel))))
(defmethod show-page-score-dialog ((self scorepanel))
(let* ((params (list (score-top-margin self) (score-left-margin self) (score-bottom-margin self) (score-right-margin self) (score-line-space self) ))
(font *om-default-font1*)
(win (om-make-window 'om-dialog
:window-title "Page Setup"
:position :centered
:close t
:resizable nil
:maximize nil
:size (om-make-point 290 175)))
(y 0)
(defvals '("2" "1" "1" "1" "1"))
paramtxt valtxt intertxt top left bottom right inter okb annulerb defb
)
(setf paramtxt (om-make-dialog-item 'om-static-text (om-make-point 20 y) (om-make-point 120 20)
"Top: Left:" :font font))
(incf y 26)
(setf top (om-make-dialog-item 'om-editable-text (om-make-point 20 y)
(om-make-point 50 30) (num2string (first params))))
(setf left (om-make-dialog-item 'om-editable-text (om-make-point 100 y)
(om-make-point 50 30) (num2string (second params))))
(incf y 40)
(setf valtxt (om-make-dialog-item 'om-static-text (om-make-point 20 y) (om-make-point 140 20)
"Bottom: Right:" :font font))
(incf y 26)
(setf bottom (om-make-dialog-item 'om-editable-text (om-make-point 20 y)
(om-make-point 50 30) (num2string (third defvals))))
(setf right (om-make-dialog-item 'om-editable-text (om-make-point 100 y)
(om-make-point 50 30) (num2string (fourth params))))
(setf y 66)
(setf intertxt (om-make-dialog-item 'om-static-text (om-make-point 200 y) (om-make-point 130 40)
(str-check "Inter-line:")
:font font))
(incf y 26)
(setf inter (om-make-dialog-item 'om-editable-text (om-make-point 200 y)
(om-make-point 50 30) (num2string (fifth params))))
(incf y 40)
(setf defb (om-make-dialog-item 'om-button
(om-make-point 20 y)
(om-make-point 70 25)
"Defaults"
:font font
:di-action (om-dialog-item-act item
(declare (ignore item))
(om-set-dialog-item-text top (first defvals))
(om-set-dialog-item-text left (second defvals))
(om-set-dialog-item-text bottom (third defvals))
(om-set-dialog-item-text right (fourth defvals))
(om-set-dialog-item-text inter (fifth defvals)))))
(setf okb (om-make-dialog-item 'om-button
(om-make-point 200 y)
(om-make-point 70 25)
"OK"
:font font
:di-action (om-dialog-item-act item
(declare (ignore item))
(om-return-from-modal-dialog win
(list (string2num (om-dialog-item-text top))
(string2num (om-dialog-item-text left))
(string2num (om-dialog-item-text bottom))
(string2num (om-dialog-item-text right))
(string2num (om-dialog-item-text inter)))))))
(setf annulerb (om-make-dialog-item 'om-button
(om-make-point 110 y)
(om-make-point 70 25)
"Annuler"
:font font
:di-action (om-dialog-item-act item
(declare (ignore item))
(om-return-from-modal-dialog win nil))))
(om-add-subviews win paramtxt valtxt intertxt inter top left bottom right okb annulerb defb)
(om-modal-dialog win)))
|
aafcd9a332755007900b610b191f1cedc76a1f91f67242447d5002182ba2d725 | camllight/camllight | eval.mli | #open "syntaxe";;
type valeur =
Val_nombre of int
| Val_booléenne of bool
| Val_paire of valeur * valeur
| Val_nil
| Val_cons of valeur * valeur
| Val_fermeture of fermeture
| Val_primitive of valeur -> valeur
and fermeture =
{ Définition: (motif * expression) list;
mutable Environnement: environnement }
and environnement == (string * valeur) list;;
value évalue: environnement -> expression -> valeur
and évalue_définition: environnement -> définition -> environnement
and imprime_valeur: valeur -> unit;;
exception Erreur of string;;
| null | https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/examples/minicaml/eval.mli | ocaml | #open "syntaxe";;
type valeur =
Val_nombre of int
| Val_booléenne of bool
| Val_paire of valeur * valeur
| Val_nil
| Val_cons of valeur * valeur
| Val_fermeture of fermeture
| Val_primitive of valeur -> valeur
and fermeture =
{ Définition: (motif * expression) list;
mutable Environnement: environnement }
and environnement == (string * valeur) list;;
value évalue: environnement -> expression -> valeur
and évalue_définition: environnement -> définition -> environnement
and imprime_valeur: valeur -> unit;;
exception Erreur of string;;
| |
423fb0b00ff4901f9c000e16e823c4a8f3f7a0f92a007d9e117a2bbee1c440f4 | ShamoX/cash | delim_7.ml | (***********************************************************************)
(* Cash *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
(* under the terms of the GNU Lesser General Public License. *)
(* *)
Cash is based on , by .
(***********************************************************************)
type handle_delim =
[ Trim
| Peek
| Concat ]
; (* | Split: would give incompatible results, so we define special <fun>_split *)
(* For Rec_field_8. *)
value no_peek name = invalid_arg (name ^ ": ~handle_delim:Peek is illegal");
XX fournir une interface avec délimiteur = regexp est ( awk sait
faire , perl non ) , mais assez compliqué : on ,
si on trouve , c'est OK , sinon , , et chercher là , car le
délimiteur buffers du channel ( dans le buffer est utile , et reculer , on espère dans le
, ... Ooouupps ) .
faire, perl non), mais assez compliqué: on peut scanner le buffer du channel,
si on trouve, c'est OK, sinon, il faut accumuler, et chercher là, car le
délimiteur peut être à cheval sur 2 buffers du channel (donc un seul scan
dans le buffer est utile, et il faut pouvoir reculer, on espère dans le
dernier paquet lu, sauf Peek... Ooouupps). *)
; ; ( % read - delimited ! delims buf gobble ? [ port start end ] )
; ; This low - level routine uses a different interface . It returns two values :
; ; - TERMINATOR : A value describing why the read was terminated :
; ; + character or eof - object = > read terminated by this value ;
; ; + # f = > filled buffer w/o terminating read .
; ; - NUM - READ : Number of chars read into buf .
; ;
; ; Note :
; ; - Invariant : TERMINATOR = # f = > NUM - READ = END - START .
; ; - Invariant : TERMINATOR = eof - object and NUM - READ = 0 = > at EOF .
; ; - When determining the TERMINATOR return value , ties are broken
; ; favoring character or the eof - object over # f. That is , if the buffer
; ; fills up , % READ - DELIMITED ! will peek at one more character from the
; ; input stream to determine if it terminates the input . If so , that
; ; is returned , not # f.
; ;
; ; If GOBBLE ? is true , then a terminator character is removed from
; ; the input stream . Otherwise , it is left in place for a following input
; ; operation .
;; This low-level routine uses a different interface. It returns two values:
;; - TERMINATOR: A value describing why the read was terminated:
;; + character or eof-object => read terminated by this value;
;; + #f => filled buffer w/o terminating read.
;; - NUM-READ: Number of chars read into buf.
;;
;; Note:
;; - Invariant: TERMINATOR = #f => NUM-READ = END - START.
;; - Invariant: TERMINATOR = eof-object and NUM-READ = 0 => at EOF.
;; - When determining the TERMINATOR return value, ties are broken
;; favoring character or the eof-object over #f. That is, if the buffer
;; fills up, %READ-DELIMITED! will peek at one more character from the
;; input stream to determine if it terminates the input. If so, that
;; is returned, not #f.
;;
;; If GOBBLE? is true, then a terminator character is removed from
;; the input stream. Otherwise, it is left in place for a following input
;; operation.
*)
(* NOTE: do we break ties like scsh ? *)
type termination_kind =
[ Eof
| Read of char
| Full_buffer ]
;
external unsafe_input : in_channel -> string -> int -> int -> int = "caml_input";
external read_delimited_scan :
in_channel -> Charset_14.t -> int = "cash_read_delimited_scan";
This way is from Pervasives .
(* XXX Mettre unsafe_input quand tout aura été couvert ? *)
value unsafe_low_read_delimited_bang chan start end_ delims buf handle_delim =
let end_1 = if handle_delim = Concat then end_ else succ end_ in
let rec loop start total =
let n = read_delimited_scan chan delims in
if n = 0 then (Eof, total)
else if if n > 0 then n > end_1 - start else - n >= end_ - start then
(* Not enough space: Full. *)
let _ = input chan buf start (end_ - start) in
(Full_buffer, total + end_ - start)
else if n > 0 then do {
let len =(* There's enough space. *)
if handle_delim = Concat then n else pred n;
ignore (input chan buf start len);
let total = total + len;
let delim = if handle_delim = Concat then buf.[pred len] else input_char chan;
if handle_delim = Peek then seek_in chan (pred (pos_in chan)) else ();
(Read delim, total)
}
else
Found no delim , buf not full , must loop .
let _ = input chan buf start (- n) in
loop (start - n) (total - n)
in
loop start 0
;
value low_read_delimited_bang ?(chan = stdin) ?(start = 0) ?end_ delims buf handle_delim =
let end_ = Strings_5_1.opt_end buf end_
and delims = Charset_14.to_charset delims in
do {
Strings_5_1.check_substring_spec buf start end_ "low_read_delimited_bang";
unsafe_low_read_delimited_bang chan start end_ delims buf handle_delim
}
;
; ; ( read - delimited ! delims buf [ port delim - action start end ] )
; ; Returns :
; ; - EOF if at end of file , and a non - zero read was requested .
; ; - Integer j if that many chars read into BUF .
; ; - # f if the buffer was filled w/o finding a delimiter .
; ;
; ; DELIM - ACTION determines what to do with the terminating delimiter ;
; ; it is as in READ - DELIMITED .
; ;
; ; In determining the return value , there is an ambiguous case : when the
; ; buffer is full , * and * the following char is a delimiter char or EOF .
; ; Ties are broken favoring termination over # f -- after filling the buffer ,
; ; READ - DELIMITED ! wo n't return # f until it has peeked one past the end
; ; of the buffer to ensure the next char does n't terminate input ( or is EOF ) .
; ; However , this rule is relaxed with delim - action = CONCAT -- if the buffer
; ; is full , READ - DELIMITED ! wo n't wait around trying to peek at the following
; ; char to determine whether or not it is a delimiter char , since it does n't
; ; have space to store the character anyway . It simply immediately returns # f ;
; ; a following read can pick up the delimiter char .
;; Returns:
;; - EOF if at end of file, and a non-zero read was requested.
;; - Integer j if that many chars read into BUF.
;; - #f if the buffer was filled w/o finding a delimiter.
;;
;; DELIM-ACTION determines what to do with the terminating delimiter;
;; it is as in READ-DELIMITED.
;;
;; In determining the return value, there is an ambiguous case: when the
;; buffer is full, *and* the following char is a delimiter char or EOF.
;; Ties are broken favoring termination over #f -- after filling the buffer,
;; READ-DELIMITED! won't return #f until it has peeked one past the end
;; of the buffer to ensure the next char doesn't terminate input (or is EOF).
;; However, this rule is relaxed with delim-action = CONCAT -- if the buffer
;; is full, READ-DELIMITED! won't wait around trying to peek at the following
;; char to determine whether or not it is a delimiter char, since it doesn't
;; have space to store the character anyway. It simply immediately returns #f;
;; a following read can pick up the delimiter char.
*)
(* NOTE: do we break ties like scsh ? *)
value read_delimited_bang_split ?chan ?start ?end_ delims buf =
match low_read_delimited_bang ?chan ?start ?end_ delims buf Trim with
[ (Eof, 0) -> raise End_of_file
| (Full_buffer, _) -> None
| (term, n) -> Some (n, term) ]
;
value read_delimited_bang ?chan ?(handle_delim = Trim) ?(start = 0) ?end_ delims buf =
let end_ =
We 'll try to add one char if Full_buffer .
if handle_delim <> Concat then end_ else Some (pred (Strings_5_1.opt_end buf end_))
in
match low_read_delimited_bang ?chan ~start ?end_ delims buf handle_delim with
[ (Eof, 0) -> raise End_of_file
| (Eof, n) -> Some n
| (Read c, nread) -> Some nread
| (Full_buffer, nread) ->
match handle_delim with
[ Concat ->
try
let c = input_char (Arg_3_7.default_value chan stdin) in
do {
buf.[start + nread] := c;
if Charset_14.contains (Charset_14.to_charset delims) c then
Some (succ nread)
else None
}
with
[ End_of_file -> Some nread ]
| _ -> None ] ]
;
value cons_revconc s =
fun
[ [] -> (* ; Gratuitous opt. *) s
| [str] -> (* More gratuitous opt. *) str ^ s
| strs -> String.concat "" (List.rev [s :: strs]) ]
;
; ; ( read - delimited delims [ port delim - action ] )
; ; Returns a string or the EOF object . DELIM - ACTION determines what to do
; ; with the terminating delimiter :
; ; - PEEK
; ; Leave it in the input stream for later reading .
; ; - TRIM ( the default )
; ; Drop it on the floor .
; ; - CONCAT
; ; Append it to the returned string .
; ; - SPLIT
; ; Return it as a second return value .
; ;
; ; We repeatedly allocate a buffer and fill it with READ - DELIMITED !
; ; until we hit a delimiter or EOF . Each time through the loop , we
; ; double the total buffer space , so the loop terminates with a log
; ; number of reads , but uses at most double the optimal buffer space .
;; Returns a string or the EOF object. DELIM-ACTION determines what to do
;; with the terminating delimiter:
;; - PEEK
;; Leave it in the input stream for later reading.
;; - TRIM (the default)
;; Drop it on the floor.
;; - CONCAT
;; Append it to the returned string.
;; - SPLIT
;; Return it as a second return value.
;;
;; We repeatedly allocate a buffer and fill it with READ-DELIMITED!
;; until we hit a delimiter or EOF. Each time through the loop, we
;; double the total buffer space, so the loop terminates with a log
;; number of reads, but uses at most double the optimal buffer space.
*)
This way is from Pervasives .
(* As read_delimited_scan tries to make the line fit in the i/o buffer, n < 0
happens when the line length is over the buffer's one; this is very uncommon.
But: we don't want quadratic behavior if there's no delimiter in the file. *)
value by_chunks chan handle_delim delims len =
let make_chunk len =
let chunk = String.create len in
do { ignore (unsafe_input chan chunk 0 len); chunk }
in
let rec loop prev_chunk chunks =
let n = read_delimited_scan chan delims in
if n = 0 then cons_revconc prev_chunk chunks
else if n > 0 then do {
let len = if handle_delim = Concat then n else pred n in
let last_chunk = String.create len in
ignore (unsafe_input chan last_chunk 0 len);
if handle_delim = Trim then ignore (input_char chan) else ();
cons_revconc last_chunk [prev_chunk :: chunks]
}
else loop (make_chunk (- n)) [prev_chunk :: chunks]
in
loop (make_chunk len) []
;
value one_rec delims handle_delim chan =
let n = read_delimited_scan chan delims in
if n = 0 then raise End_of_file
else if n > 0 then do {
let len = if handle_delim = Concat then n else pred n in
let line = String.create len in
ignore (unsafe_input chan line 0 len);
if handle_delim = Trim then ignore (input_char chan) else ();
line
}
else by_chunks chan handle_delim delims (- n)
;
value one_rec_split delims chan =
try
let line = one_rec delims Peek chan in
try (line, Read (input_char chan)) with [ End_of_file -> (line, Eof) ]
with
[ End_of_file -> ("", Eof) ]
;
value read_delimited ?(chan = stdin) ?(handle_delim = Trim) delims =
one_rec (Charset_14.to_charset delims) handle_delim chan
;
value read_delimited_split ?(chan = stdin) delims =
one_rec_split (Charset_14.to_charset delims) chan
;
value cs_newline_i = Charset_14.of_char '\n';
(* For Rec_field_8. *)
value cs_newline = Charset_14.Cset cs_newline_i;
(* Don't use unnecessary optionals, nor force conversion to_charset; so use
cs_newline_i, and don't call read_delimited. This is *way* cheaper. *)
value read_line_split = one_rec_split cs_newline_i;
(* For Rec_field_8. *)
value one_line = one_rec cs_newline_i;
value read_line ?(handle_newline = Trim) = one_line handle_newline;
XXX fournir une interface pour passer la définition de la ligne délimiteur
( par défaut la proc is_white ) .
(par défaut la proc is_white). *)
value (read_paragraph_split, read_paragraph) =
Est - ce bien efficace ? Si non , revoir read_line aussi
let one_line_c = one_line Concat
and skip = Charset_14.skip Charset_14.whitespace in
let is_white line =
let len = String.length line in
skip line 0 len = len
in
let rec skip_blank_lines chan =
let line = one_line_c chan in
(* End_of_file OK here. *)
if is_white line then skip_blank_lines chan else line
in
let low_read_paragraph make_res chan =
collect (skip_blank_lines chan) [] where rec collect prev_line lines =
let line = try one_line_c chan with [ End_of_file -> "" ] in
if is_white line then make_res line prev_line lines
else collect line [prev_line :: lines]
in
(fun chan ->
low_read_paragraph (fun line prev_line lines -> (cons_revconc prev_line lines, line))
chan,
fun ?(handle_delim = Trim) chan ->
low_read_paragraph
(fun line prev_line lines ->
match handle_delim with
[ Trim -> cons_revconc prev_line lines
| Concat ->
if line = "" then cons_revconc prev_line lines
else cons_revconc line [prev_line :: lines]
| Peek -> no_peek "read_paragraph" ])
chan)
;
value skip_char_set ?(chan = stdin) skip_chars =
let cset = Charset_14.to_charset skip_chars
and pos = pos_in chan
and buf = String.create 200 in
let rec loop total =
let upto = input chan buf 0 200 in
let delim_index = Charset_14.skip cset buf 0 upto in
let total = total + delim_index in
if upto = 0 || delim_index < upto then do { seek_in chan (pos + total); total }
else loop total
in
loop 0
;
| null | https://raw.githubusercontent.com/ShamoX/cash/aa97231154c3f64c9d0a62823e1ed71e32ab8718/delim_7.ml | ocaml | *********************************************************************
Cash
under the terms of the GNU Lesser General Public License.
*********************************************************************
| Split: would give incompatible results, so we define special <fun>_split
For Rec_field_8.
NOTE: do we break ties like scsh ?
XXX Mettre unsafe_input quand tout aura été couvert ?
Not enough space: Full.
There's enough space.
NOTE: do we break ties like scsh ?
; Gratuitous opt.
More gratuitous opt.
As read_delimited_scan tries to make the line fit in the i/o buffer, n < 0
happens when the line length is over the buffer's one; this is very uncommon.
But: we don't want quadratic behavior if there's no delimiter in the file.
For Rec_field_8.
Don't use unnecessary optionals, nor force conversion to_charset; so use
cs_newline_i, and don't call read_delimited. This is *way* cheaper.
For Rec_field_8.
End_of_file OK here. | , projet Cristal , INRIA Rocquencourt
Copyright 2002 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
Cash is based on , by .
type handle_delim =
[ Trim
| Peek
| Concat ]
value no_peek name = invalid_arg (name ^ ": ~handle_delim:Peek is illegal");
XX fournir une interface avec délimiteur = regexp est ( awk sait
faire , perl non ) , mais assez compliqué : on ,
si on trouve , c'est OK , sinon , , et chercher là , car le
délimiteur buffers du channel ( dans le buffer est utile , et reculer , on espère dans le
, ... Ooouupps ) .
faire, perl non), mais assez compliqué: on peut scanner le buffer du channel,
si on trouve, c'est OK, sinon, il faut accumuler, et chercher là, car le
délimiteur peut être à cheval sur 2 buffers du channel (donc un seul scan
dans le buffer est utile, et il faut pouvoir reculer, on espère dans le
dernier paquet lu, sauf Peek... Ooouupps). *)
; ; ( % read - delimited ! delims buf gobble ? [ port start end ] )
; ; This low - level routine uses a different interface . It returns two values :
; ; - TERMINATOR : A value describing why the read was terminated :
; ; + character or eof - object = > read terminated by this value ;
; ; + # f = > filled buffer w/o terminating read .
; ; - NUM - READ : Number of chars read into buf .
; ;
; ; Note :
; ; - Invariant : TERMINATOR = # f = > NUM - READ = END - START .
; ; - Invariant : TERMINATOR = eof - object and NUM - READ = 0 = > at EOF .
; ; - When determining the TERMINATOR return value , ties are broken
; ; favoring character or the eof - object over # f. That is , if the buffer
; ; fills up , % READ - DELIMITED ! will peek at one more character from the
; ; input stream to determine if it terminates the input . If so , that
; ; is returned , not # f.
; ;
; ; If GOBBLE ? is true , then a terminator character is removed from
; ; the input stream . Otherwise , it is left in place for a following input
; ; operation .
;; This low-level routine uses a different interface. It returns two values:
;; - TERMINATOR: A value describing why the read was terminated:
;; + character or eof-object => read terminated by this value;
;; + #f => filled buffer w/o terminating read.
;; - NUM-READ: Number of chars read into buf.
;;
;; Note:
;; - Invariant: TERMINATOR = #f => NUM-READ = END - START.
;; - Invariant: TERMINATOR = eof-object and NUM-READ = 0 => at EOF.
;; - When determining the TERMINATOR return value, ties are broken
;; favoring character or the eof-object over #f. That is, if the buffer
;; fills up, %READ-DELIMITED! will peek at one more character from the
;; input stream to determine if it terminates the input. If so, that
;; is returned, not #f.
;;
;; If GOBBLE? is true, then a terminator character is removed from
;; the input stream. Otherwise, it is left in place for a following input
;; operation.
*)
type termination_kind =
[ Eof
| Read of char
| Full_buffer ]
;
external unsafe_input : in_channel -> string -> int -> int -> int = "caml_input";
external read_delimited_scan :
in_channel -> Charset_14.t -> int = "cash_read_delimited_scan";
This way is from Pervasives .
value unsafe_low_read_delimited_bang chan start end_ delims buf handle_delim =
let end_1 = if handle_delim = Concat then end_ else succ end_ in
let rec loop start total =
let n = read_delimited_scan chan delims in
if n = 0 then (Eof, total)
else if if n > 0 then n > end_1 - start else - n >= end_ - start then
let _ = input chan buf start (end_ - start) in
(Full_buffer, total + end_ - start)
else if n > 0 then do {
if handle_delim = Concat then n else pred n;
ignore (input chan buf start len);
let total = total + len;
let delim = if handle_delim = Concat then buf.[pred len] else input_char chan;
if handle_delim = Peek then seek_in chan (pred (pos_in chan)) else ();
(Read delim, total)
}
else
Found no delim , buf not full , must loop .
let _ = input chan buf start (- n) in
loop (start - n) (total - n)
in
loop start 0
;
value low_read_delimited_bang ?(chan = stdin) ?(start = 0) ?end_ delims buf handle_delim =
let end_ = Strings_5_1.opt_end buf end_
and delims = Charset_14.to_charset delims in
do {
Strings_5_1.check_substring_spec buf start end_ "low_read_delimited_bang";
unsafe_low_read_delimited_bang chan start end_ delims buf handle_delim
}
;
; ; ( read - delimited ! delims buf [ port delim - action start end ] )
; ; Returns :
; ; - EOF if at end of file , and a non - zero read was requested .
; ; - Integer j if that many chars read into BUF .
; ; - # f if the buffer was filled w/o finding a delimiter .
; ;
; ; DELIM - ACTION determines what to do with the terminating delimiter ;
; ; it is as in READ - DELIMITED .
; ;
; ; In determining the return value , there is an ambiguous case : when the
; ; buffer is full , * and * the following char is a delimiter char or EOF .
; ; Ties are broken favoring termination over # f -- after filling the buffer ,
; ; READ - DELIMITED ! wo n't return # f until it has peeked one past the end
; ; of the buffer to ensure the next char does n't terminate input ( or is EOF ) .
; ; However , this rule is relaxed with delim - action = CONCAT -- if the buffer
; ; is full , READ - DELIMITED ! wo n't wait around trying to peek at the following
; ; char to determine whether or not it is a delimiter char , since it does n't
; ; have space to store the character anyway . It simply immediately returns # f ;
; ; a following read can pick up the delimiter char .
;; Returns:
;; - EOF if at end of file, and a non-zero read was requested.
;; - Integer j if that many chars read into BUF.
;; - #f if the buffer was filled w/o finding a delimiter.
;;
;; DELIM-ACTION determines what to do with the terminating delimiter;
;; it is as in READ-DELIMITED.
;;
;; In determining the return value, there is an ambiguous case: when the
;; buffer is full, *and* the following char is a delimiter char or EOF.
;; Ties are broken favoring termination over #f -- after filling the buffer,
;; READ-DELIMITED! won't return #f until it has peeked one past the end
;; of the buffer to ensure the next char doesn't terminate input (or is EOF).
;; However, this rule is relaxed with delim-action = CONCAT -- if the buffer
;; is full, READ-DELIMITED! won't wait around trying to peek at the following
;; char to determine whether or not it is a delimiter char, since it doesn't
;; have space to store the character anyway. It simply immediately returns #f;
;; a following read can pick up the delimiter char.
*)
value read_delimited_bang_split ?chan ?start ?end_ delims buf =
match low_read_delimited_bang ?chan ?start ?end_ delims buf Trim with
[ (Eof, 0) -> raise End_of_file
| (Full_buffer, _) -> None
| (term, n) -> Some (n, term) ]
;
value read_delimited_bang ?chan ?(handle_delim = Trim) ?(start = 0) ?end_ delims buf =
let end_ =
We 'll try to add one char if Full_buffer .
if handle_delim <> Concat then end_ else Some (pred (Strings_5_1.opt_end buf end_))
in
match low_read_delimited_bang ?chan ~start ?end_ delims buf handle_delim with
[ (Eof, 0) -> raise End_of_file
| (Eof, n) -> Some n
| (Read c, nread) -> Some nread
| (Full_buffer, nread) ->
match handle_delim with
[ Concat ->
try
let c = input_char (Arg_3_7.default_value chan stdin) in
do {
buf.[start + nread] := c;
if Charset_14.contains (Charset_14.to_charset delims) c then
Some (succ nread)
else None
}
with
[ End_of_file -> Some nread ]
| _ -> None ] ]
;
value cons_revconc s =
fun
| strs -> String.concat "" (List.rev [s :: strs]) ]
;
; ; ( read - delimited delims [ port delim - action ] )
; ; Returns a string or the EOF object . DELIM - ACTION determines what to do
; ; with the terminating delimiter :
; ; - PEEK
; ; Leave it in the input stream for later reading .
; ; - TRIM ( the default )
; ; Drop it on the floor .
; ; - CONCAT
; ; Append it to the returned string .
; ; - SPLIT
; ; Return it as a second return value .
; ;
; ; We repeatedly allocate a buffer and fill it with READ - DELIMITED !
; ; until we hit a delimiter or EOF . Each time through the loop , we
; ; double the total buffer space , so the loop terminates with a log
; ; number of reads , but uses at most double the optimal buffer space .
;; Returns a string or the EOF object. DELIM-ACTION determines what to do
;; with the terminating delimiter:
;; - PEEK
;; Leave it in the input stream for later reading.
;; - TRIM (the default)
;; Drop it on the floor.
;; - CONCAT
;; Append it to the returned string.
;; - SPLIT
;; Return it as a second return value.
;;
;; We repeatedly allocate a buffer and fill it with READ-DELIMITED!
;; until we hit a delimiter or EOF. Each time through the loop, we
;; double the total buffer space, so the loop terminates with a log
;; number of reads, but uses at most double the optimal buffer space.
*)
This way is from Pervasives .
value by_chunks chan handle_delim delims len =
let make_chunk len =
let chunk = String.create len in
do { ignore (unsafe_input chan chunk 0 len); chunk }
in
let rec loop prev_chunk chunks =
let n = read_delimited_scan chan delims in
if n = 0 then cons_revconc prev_chunk chunks
else if n > 0 then do {
let len = if handle_delim = Concat then n else pred n in
let last_chunk = String.create len in
ignore (unsafe_input chan last_chunk 0 len);
if handle_delim = Trim then ignore (input_char chan) else ();
cons_revconc last_chunk [prev_chunk :: chunks]
}
else loop (make_chunk (- n)) [prev_chunk :: chunks]
in
loop (make_chunk len) []
;
value one_rec delims handle_delim chan =
let n = read_delimited_scan chan delims in
if n = 0 then raise End_of_file
else if n > 0 then do {
let len = if handle_delim = Concat then n else pred n in
let line = String.create len in
ignore (unsafe_input chan line 0 len);
if handle_delim = Trim then ignore (input_char chan) else ();
line
}
else by_chunks chan handle_delim delims (- n)
;
value one_rec_split delims chan =
try
let line = one_rec delims Peek chan in
try (line, Read (input_char chan)) with [ End_of_file -> (line, Eof) ]
with
[ End_of_file -> ("", Eof) ]
;
value read_delimited ?(chan = stdin) ?(handle_delim = Trim) delims =
one_rec (Charset_14.to_charset delims) handle_delim chan
;
value read_delimited_split ?(chan = stdin) delims =
one_rec_split (Charset_14.to_charset delims) chan
;
value cs_newline_i = Charset_14.of_char '\n';
value cs_newline = Charset_14.Cset cs_newline_i;
value read_line_split = one_rec_split cs_newline_i;
value one_line = one_rec cs_newline_i;
value read_line ?(handle_newline = Trim) = one_line handle_newline;
XXX fournir une interface pour passer la définition de la ligne délimiteur
( par défaut la proc is_white ) .
(par défaut la proc is_white). *)
value (read_paragraph_split, read_paragraph) =
Est - ce bien efficace ? Si non , revoir read_line aussi
let one_line_c = one_line Concat
and skip = Charset_14.skip Charset_14.whitespace in
let is_white line =
let len = String.length line in
skip line 0 len = len
in
let rec skip_blank_lines chan =
let line = one_line_c chan in
if is_white line then skip_blank_lines chan else line
in
let low_read_paragraph make_res chan =
collect (skip_blank_lines chan) [] where rec collect prev_line lines =
let line = try one_line_c chan with [ End_of_file -> "" ] in
if is_white line then make_res line prev_line lines
else collect line [prev_line :: lines]
in
(fun chan ->
low_read_paragraph (fun line prev_line lines -> (cons_revconc prev_line lines, line))
chan,
fun ?(handle_delim = Trim) chan ->
low_read_paragraph
(fun line prev_line lines ->
match handle_delim with
[ Trim -> cons_revconc prev_line lines
| Concat ->
if line = "" then cons_revconc prev_line lines
else cons_revconc line [prev_line :: lines]
| Peek -> no_peek "read_paragraph" ])
chan)
;
value skip_char_set ?(chan = stdin) skip_chars =
let cset = Charset_14.to_charset skip_chars
and pos = pos_in chan
and buf = String.create 200 in
let rec loop total =
let upto = input chan buf 0 200 in
let delim_index = Charset_14.skip cset buf 0 upto in
let total = total + delim_index in
if upto = 0 || delim_index < upto then do { seek_in chan (pos + total); total }
else loop total
in
loop 0
;
|
94a0ce7b1f6c8e167888fc18c46a547dc4b26844616848b9172b92a829218292 | cedlemo/OCaml-GI-ctypes-bindings-generator | Notebook.mli | open Ctypes
type t
val t_typ : t typ
val create :
unit -> Widget.t ptr
val append_page :
t -> Widget.t ptr -> Widget.t ptr option -> int32
val append_page_menu :
t -> Widget.t ptr -> Widget.t ptr option -> Widget.t ptr option -> int32
val detach_tab :
t -> Widget.t ptr -> unit
val get_action_widget :
t -> Pack_type.t -> Widget.t ptr option
val get_current_page :
t -> int32
val get_group_name :
t -> string option
val get_menu_label :
t -> Widget.t ptr -> Widget.t ptr option
val get_menu_label_text :
t -> Widget.t ptr -> string option
val get_n_pages :
t -> int32
val get_nth_page :
t -> int32 -> Widget.t ptr option
val get_scrollable :
t -> bool
val get_show_border :
t -> bool
val get_show_tabs :
t -> bool
val get_tab_detachable :
t -> Widget.t ptr -> bool
val get_tab_hborder :
t -> Unsigned.uint16
val get_tab_label :
t -> Widget.t ptr -> Widget.t ptr option
val get_tab_label_text :
t -> Widget.t ptr -> string option
val get_tab_pos :
t -> Position_type.t
val get_tab_reorderable :
t -> Widget.t ptr -> bool
val get_tab_vborder :
t -> Unsigned.uint16
val insert_page :
t -> Widget.t ptr -> Widget.t ptr option -> int32 -> int32
val insert_page_menu :
t -> Widget.t ptr -> Widget.t ptr option -> Widget.t ptr option -> int32 -> int32
val next_page :
t -> unit
val page_num :
t -> Widget.t ptr -> int32
val popup_disable :
t -> unit
val popup_enable :
t -> unit
val prepend_page :
t -> Widget.t ptr -> Widget.t ptr option -> int32
val prepend_page_menu :
t -> Widget.t ptr -> Widget.t ptr option -> Widget.t ptr option -> int32
val prev_page :
t -> unit
val remove_page :
t -> int32 -> unit
val reorder_child :
t -> Widget.t ptr -> int32 -> unit
val set_action_widget :
t -> Widget.t ptr -> Pack_type.t -> unit
val set_current_page :
t -> int32 -> unit
val set_group_name :
t -> string option -> unit
val set_menu_label :
t -> Widget.t ptr -> Widget.t ptr option -> unit
val set_menu_label_text :
t -> Widget.t ptr -> string -> unit
val set_scrollable :
t -> bool -> unit
val set_show_border :
t -> bool -> unit
val set_show_tabs :
t -> bool -> unit
val set_tab_detachable :
t -> Widget.t ptr -> bool -> unit
val set_tab_label :
t -> Widget.t ptr -> Widget.t ptr option -> unit
val set_tab_label_text :
t -> Widget.t ptr -> string -> unit
val set_tab_pos :
t -> Position_type.t -> unit
val set_tab_reorderable :
t -> Widget.t ptr -> bool -> unit
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Notebook.mli | ocaml | open Ctypes
type t
val t_typ : t typ
val create :
unit -> Widget.t ptr
val append_page :
t -> Widget.t ptr -> Widget.t ptr option -> int32
val append_page_menu :
t -> Widget.t ptr -> Widget.t ptr option -> Widget.t ptr option -> int32
val detach_tab :
t -> Widget.t ptr -> unit
val get_action_widget :
t -> Pack_type.t -> Widget.t ptr option
val get_current_page :
t -> int32
val get_group_name :
t -> string option
val get_menu_label :
t -> Widget.t ptr -> Widget.t ptr option
val get_menu_label_text :
t -> Widget.t ptr -> string option
val get_n_pages :
t -> int32
val get_nth_page :
t -> int32 -> Widget.t ptr option
val get_scrollable :
t -> bool
val get_show_border :
t -> bool
val get_show_tabs :
t -> bool
val get_tab_detachable :
t -> Widget.t ptr -> bool
val get_tab_hborder :
t -> Unsigned.uint16
val get_tab_label :
t -> Widget.t ptr -> Widget.t ptr option
val get_tab_label_text :
t -> Widget.t ptr -> string option
val get_tab_pos :
t -> Position_type.t
val get_tab_reorderable :
t -> Widget.t ptr -> bool
val get_tab_vborder :
t -> Unsigned.uint16
val insert_page :
t -> Widget.t ptr -> Widget.t ptr option -> int32 -> int32
val insert_page_menu :
t -> Widget.t ptr -> Widget.t ptr option -> Widget.t ptr option -> int32 -> int32
val next_page :
t -> unit
val page_num :
t -> Widget.t ptr -> int32
val popup_disable :
t -> unit
val popup_enable :
t -> unit
val prepend_page :
t -> Widget.t ptr -> Widget.t ptr option -> int32
val prepend_page_menu :
t -> Widget.t ptr -> Widget.t ptr option -> Widget.t ptr option -> int32
val prev_page :
t -> unit
val remove_page :
t -> int32 -> unit
val reorder_child :
t -> Widget.t ptr -> int32 -> unit
val set_action_widget :
t -> Widget.t ptr -> Pack_type.t -> unit
val set_current_page :
t -> int32 -> unit
val set_group_name :
t -> string option -> unit
val set_menu_label :
t -> Widget.t ptr -> Widget.t ptr option -> unit
val set_menu_label_text :
t -> Widget.t ptr -> string -> unit
val set_scrollable :
t -> bool -> unit
val set_show_border :
t -> bool -> unit
val set_show_tabs :
t -> bool -> unit
val set_tab_detachable :
t -> Widget.t ptr -> bool -> unit
val set_tab_label :
t -> Widget.t ptr -> Widget.t ptr option -> unit
val set_tab_label_text :
t -> Widget.t ptr -> string -> unit
val set_tab_pos :
t -> Position_type.t -> unit
val set_tab_reorderable :
t -> Widget.t ptr -> bool -> unit
| |
e2128c6db9d765920c83648dfd0c6bed20bb21152949927cc802632436d889b5 | mit-plv/riscv-semantics | ExecuteA64.hs | # LANGUAGE ScopedTypeVariables #
module Spec.ExecuteA64 where
import Spec.Decode
import Spec.Machine
import Utility.Utility
import Spec.VirtualMemory
import Control.Monad
import Data.Bits
import Prelude
execute :: forall p t. (RiscvMachine p t) => InstructionA64 -> p ()
-- begin ast
execute (Lr_d rd rs1 aqrl) = do
a <- getRegister rs1
addr <- translate Load 8 a
makeReservation addr
x <- loadDouble Execute addr
setRegister rd (int64ToReg x)
execute (Sc_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 8 a
valid <- checkReservation addr
if valid
then do
x <- getRegister rs2
storeDouble Execute addr (regToInt64 x)
setRegister rd 0
else setRegister rd 1
-- TODO: Eventually stop cheating.
execute (Amoswap_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 y)
execute (Amoadd_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (int64ToReg x + y))
execute (Amoand_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (int64ToReg x .&. y))
execute (Amoor_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (int64ToReg x .|. y))
execute (Amoxor_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (xor (int64ToReg x) y))
execute (Amomax_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if y < (int64ToReg x) then x else regToInt64 y)
execute (Amomaxu_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if ltu y (uInt64ToReg x) then x else regToInt64 y)
execute (Amomin_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if (int64ToReg x) < y then x else regToInt64 y)
execute (Amominu_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if ltu (uInt64ToReg x) y then x else regToInt64 y)
-- end ast
execute inst = error $ "dispatch bug: " ++ show inst
| null | https://raw.githubusercontent.com/mit-plv/riscv-semantics/1c0da3cac9d3f8dd813d26c0d2fbaccbb2210313/src/Spec/ExecuteA64.hs | haskell | begin ast
TODO: Eventually stop cheating.
end ast | # LANGUAGE ScopedTypeVariables #
module Spec.ExecuteA64 where
import Spec.Decode
import Spec.Machine
import Utility.Utility
import Spec.VirtualMemory
import Control.Monad
import Data.Bits
import Prelude
execute :: forall p t. (RiscvMachine p t) => InstructionA64 -> p ()
execute (Lr_d rd rs1 aqrl) = do
a <- getRegister rs1
addr <- translate Load 8 a
makeReservation addr
x <- loadDouble Execute addr
setRegister rd (int64ToReg x)
execute (Sc_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 8 a
valid <- checkReservation addr
if valid
then do
x <- getRegister rs2
storeDouble Execute addr (regToInt64 x)
setRegister rd 0
else setRegister rd 1
execute (Amoswap_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 y)
execute (Amoadd_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (int64ToReg x + y))
execute (Amoand_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (int64ToReg x .&. y))
execute (Amoor_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (int64ToReg x .|. y))
execute (Amoxor_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (regToInt64 (xor (int64ToReg x) y))
execute (Amomax_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if y < (int64ToReg x) then x else regToInt64 y)
execute (Amomaxu_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if ltu y (uInt64ToReg x) then x else regToInt64 y)
execute (Amomin_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if (int64ToReg x) < y then x else regToInt64 y)
execute (Amominu_d rd rs1 rs2 aqrl) = do
a <- getRegister rs1
addr <- translate Store 4 a
x <- loadDouble Execute addr
y <- getRegister rs2
setRegister rd (int64ToReg x)
storeDouble Execute addr (if ltu (uInt64ToReg x) y then x else regToInt64 y)
execute inst = error $ "dispatch bug: " ++ show inst
|
063659e91ff1fc640c12f9ccff9a61259614087a7d8b1c50ea0dfc57034469ef | koto-bank/lbge | render-asset-handlers.lisp | (in-package :lbge.asset)
;;; Shader source
(define-asset shader-source ()
((source :initarg :source)))
(define-asset-handler shader-source (manager key)
(let ((file-path (find-path-by-path-key manager key)))
(log:debug "File path ~S" file-path)
(log:debug "Asset key ~S" key)
(unless file-path
(return (make-asset key
:state :error)))
(let ((shader-lines nil))
(with-open-file (shader-file
file-path
:direction :input
:if-does-not-exist :error)
(do ((line (read-line shader-file nil)
(read-line shader-file nil)))
((null line))
(unless (string= "" (u:trim-newlines line))
(setf shader-lines (cons (format nil "~a~%" line)
shader-lines)))))
(make-asset key
:source (reverse shader-lines)
:state :loaded))))
;;; Image
(define-asset image-asset (lbge.image:image) ())
(define-asset-handler image-asset (manager key)
(let ((file-path (lbge.asset:find-path-by-path-key manager key))
(image-asset (make-asset key :state :error)))
(log:debug "File path ~S" file-path)
(log:debug "Asset key ~S" key)
(unless file-path
(return image-asset))
(let ((image (lbge.image:load-image file-path)))
(when image
(lbge.image:copy-image image-asset image)
[image-asset.state setf :loaded])
image-asset)))
;;; Texture
(define-asset texture-asset ()
((image-asset :type image-asset :dep t)
(backend-texture
:accessor backend-texture
:documentation "Texture object created and managed by rendering
backend")))
(define-asset-handler texture-asset (manager key)
(let ((file-path (find-path-by-path-key manager key))
(texture (make-asset key :state :error)))
(unless file-path
(return texture))
(s:deserialize-file texture file-path)
[texture.state setf :loaded]
texture))
;;; Material
(define-asset material-asset ()
((vertex-shader-source :dep t :type shader-source)
(fragment-shader-source :dep t :type shader-source)
(backend-material
:accessor backend-material
:documentation "Material created and managed by the rendering backend")))
(define-asset-handler material-asset (manager key)
(let ((file-path (find-path-by-path-key manager key))
(material (make-asset key :state :error)))
(unless file-path
(return material))
(s:deserialize-file material file-path)
[material.state setf :loaded]
material))
(defun build-shader (backend sources)
;; Sources is a list in format
;; (:vertex <vertex-source>
;; :fragment <fragment-source>)
(let ((shader (b:make-shader backend)))
(sh:add-stage shader sources)
(sh:compile-shader shader)
shader))
(defun make-sampler-keyword (num)
(alexandria:make-keyword (format nil "SAMPLER~A" num)))
(defun build-material (backend material textures uniforms)
(let ((shader (build-shader
backend
(list :vertex [material.vertex-shader-source.source]
:fragment [material.fragment-shader-source.source])))
(backend-material (make-instance 'mat:material)))
(setf [material.backend-material] backend-material
[backend-material.mat:shader] shader)
(loop
for (name slot-name) on uniforms by #'cddr
do (mat:add-uniform backend-material name
(slot-value material slot-name)))
(loop
for texture-slot in textures
for i from 0
do (let ((texture (slot-value material texture-slot)))
(setf [texture.backend-texture]
(b:make-texture backend
:image [texture.image-asset]
:target :texture-2d
:format [texture.image-asset.image:channels]))
(mat:add-texture backend-material (make-sampler-keyword i)
[texture.backend-texture])))
material))
| null | https://raw.githubusercontent.com/koto-bank/lbge/6be4b3212ea87288b1ee2a655e9a1bb30a74dd27/src/base/asset/render-asset-handlers.lisp | lisp | Shader source
Image
Texture
Material
Sources is a list in format
(:vertex <vertex-source>
:fragment <fragment-source>) | (in-package :lbge.asset)
(define-asset shader-source ()
((source :initarg :source)))
(define-asset-handler shader-source (manager key)
(let ((file-path (find-path-by-path-key manager key)))
(log:debug "File path ~S" file-path)
(log:debug "Asset key ~S" key)
(unless file-path
(return (make-asset key
:state :error)))
(let ((shader-lines nil))
(with-open-file (shader-file
file-path
:direction :input
:if-does-not-exist :error)
(do ((line (read-line shader-file nil)
(read-line shader-file nil)))
((null line))
(unless (string= "" (u:trim-newlines line))
(setf shader-lines (cons (format nil "~a~%" line)
shader-lines)))))
(make-asset key
:source (reverse shader-lines)
:state :loaded))))
(define-asset image-asset (lbge.image:image) ())
(define-asset-handler image-asset (manager key)
(let ((file-path (lbge.asset:find-path-by-path-key manager key))
(image-asset (make-asset key :state :error)))
(log:debug "File path ~S" file-path)
(log:debug "Asset key ~S" key)
(unless file-path
(return image-asset))
(let ((image (lbge.image:load-image file-path)))
(when image
(lbge.image:copy-image image-asset image)
[image-asset.state setf :loaded])
image-asset)))
(define-asset texture-asset ()
((image-asset :type image-asset :dep t)
(backend-texture
:accessor backend-texture
:documentation "Texture object created and managed by rendering
backend")))
(define-asset-handler texture-asset (manager key)
(let ((file-path (find-path-by-path-key manager key))
(texture (make-asset key :state :error)))
(unless file-path
(return texture))
(s:deserialize-file texture file-path)
[texture.state setf :loaded]
texture))
(define-asset material-asset ()
((vertex-shader-source :dep t :type shader-source)
(fragment-shader-source :dep t :type shader-source)
(backend-material
:accessor backend-material
:documentation "Material created and managed by the rendering backend")))
(define-asset-handler material-asset (manager key)
(let ((file-path (find-path-by-path-key manager key))
(material (make-asset key :state :error)))
(unless file-path
(return material))
(s:deserialize-file material file-path)
[material.state setf :loaded]
material))
(defun build-shader (backend sources)
(let ((shader (b:make-shader backend)))
(sh:add-stage shader sources)
(sh:compile-shader shader)
shader))
(defun make-sampler-keyword (num)
(alexandria:make-keyword (format nil "SAMPLER~A" num)))
(defun build-material (backend material textures uniforms)
(let ((shader (build-shader
backend
(list :vertex [material.vertex-shader-source.source]
:fragment [material.fragment-shader-source.source])))
(backend-material (make-instance 'mat:material)))
(setf [material.backend-material] backend-material
[backend-material.mat:shader] shader)
(loop
for (name slot-name) on uniforms by #'cddr
do (mat:add-uniform backend-material name
(slot-value material slot-name)))
(loop
for texture-slot in textures
for i from 0
do (let ((texture (slot-value material texture-slot)))
(setf [texture.backend-texture]
(b:make-texture backend
:image [texture.image-asset]
:target :texture-2d
:format [texture.image-asset.image:channels]))
(mat:add-texture backend-material (make-sampler-keyword i)
[texture.backend-texture])))
material))
|
782891cb27d8a557a388f6ee4e1c89d269cc04fa2eb6409d39abd4c1276442af | taylorwood/advent-of-code | 5.clj | (ns advent-of-code.2016.5
(:require [clojure.string :as cs])
(:import (java.security MessageDigest)))
(defn md5 [txt]
(->> (.digest (doto (MessageDigest/getInstance "MD5")
(.update (.getBytes txt))))
(map #(format "%02x" %))
(apply str)))
solve part 1
(pmap #(md5 (str "abbhdwsy" %)))
(filter #(cs/starts-with? % "00000"))
(take 8)
(map #(nth % 5)))
(defn valid-pos? [pos ans]
is ` pos ` in ASCII 0 ... 7 ?
(not (ans pos))) ;; is `pos` not already figured out?
pos))
(def unsolved-mystery (zipmap (map char (range 48 56)) (repeat \_)))
(defn print-answer [m] ;; extra credit progressive answer printing
(->> (into (sorted-map) (merge unsolved-mystery m))
(vals)
(apply str)
(println)))
(defn reduce-hashes [ans hash]
(if-let [p (valid-pos? (nth hash 5) ans)]
(let [c (nth hash 6)
m (assoc ans p c)
n (count m)]
(print-answer m)
(if (< 7 n) (reduced m) m))
ans))
solve part 2
(pmap #(md5 (str "abbhdwsy" %)))
(filter #(cs/starts-with? % "00000"))
(reduce reduce-hashes {}))
| null | https://raw.githubusercontent.com/taylorwood/advent-of-code/c6b08f4b618875a45c8083a04ae2c669626c43bf/src/advent_of_code/2016/5.clj | clojure | is `pos` not already figured out?
extra credit progressive answer printing | (ns advent-of-code.2016.5
(:require [clojure.string :as cs])
(:import (java.security MessageDigest)))
(defn md5 [txt]
(->> (.digest (doto (MessageDigest/getInstance "MD5")
(.update (.getBytes txt))))
(map #(format "%02x" %))
(apply str)))
solve part 1
(pmap #(md5 (str "abbhdwsy" %)))
(filter #(cs/starts-with? % "00000"))
(take 8)
(map #(nth % 5)))
(defn valid-pos? [pos ans]
is ` pos ` in ASCII 0 ... 7 ?
pos))
(def unsolved-mystery (zipmap (map char (range 48 56)) (repeat \_)))
(->> (into (sorted-map) (merge unsolved-mystery m))
(vals)
(apply str)
(println)))
(defn reduce-hashes [ans hash]
(if-let [p (valid-pos? (nth hash 5) ans)]
(let [c (nth hash 6)
m (assoc ans p c)
n (count m)]
(print-answer m)
(if (< 7 n) (reduced m) m))
ans))
solve part 2
(pmap #(md5 (str "abbhdwsy" %)))
(filter #(cs/starts-with? % "00000"))
(reduce reduce-hashes {}))
|
f97b1d0b90785ca4f6cb6dfc043e6ba1d18df44f452ff17877f36a80379da8c0 | ralph-schleicher/open-location-code | tests.lisp | ;;; tests.lisp --- test procedure.
Copyright ( C ) 2019
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in
;; the documentation and/or other materials provided with the
;; distribution.
;;
;; * Neither the name of the copyright holder nor the names of its
;; contributors may be used to endorse or promote products derived
;; from this software without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR 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.
;;; Code:
(in-package :common-lisp-user)
(ql:quickload :open-location-code)
(ql:quickload :lisp-unit)
(ql:quickload :cl-csv)
(ql:quickload :read-number)
(defpackage :open-location-code-tests
(:use :common-lisp
:lisp-unit
:iterate))
(in-package :open-location-code-tests)
(defun float-equal* (a b)
(if (or (floatp a) (floatp b))
(float-equal a b)
(= a b)))
(defun fixme ()
(error "Should not happen."))
(defun boolean-from-string (string)
(cond ((or (string-equal string "true")
(string-equal string "yes")
(string-equal string "on"))
t)
((or (string-equal string "false")
(string-equal string "no")
(string-equal string "off"))
nil)
(t
(fixme))))
(defun number-from-string (string)
(with-input-from-string (stream string)
(read-number:read-float stream t nil nil :float-format 'double-float)))
(define-test length-from-precision
(assert-true (olc:code-length 1) 2)
(assert-true (olc:code-length 2) 4)
(assert-true (olc:code-length 3) 6)
(assert-true (olc:code-length 4) 8)
(assert-true (olc:code-length 5) 10)
(assert-true (olc:code-length 6) 11)
(assert-true (olc:code-length 7) 12)
(assert-true (olc:code-length 8) 13)
(assert-true (olc:code-length 9) 14)
(assert-true (olc:code-length 10) 15)
(assert-true (olc:code-length 11) 15))
(define-test precision-from-length
(assert-true (olc:precision 2) 1)
(assert-true (olc:precision 4) 2)
(assert-true (olc:precision 6) 3)
(assert-true (olc:precision 8) 4)
(assert-true (olc:precision 10) 5)
(assert-true (olc:precision 11) 6)
(assert-true (olc:precision 12) 7)
(assert-true (olc:precision 13) 8)
(assert-true (olc:precision 14) 9)
(assert-true (olc:precision 15) 10)
(assert-true (olc:precision 16) 10))
(defun validity-test (code valid short full)
(declare (ignore valid))
(assert-true
(eq (olc:validp code)
(cond (short
:short)
(full
:full)))))
(define-test validity-tests
(with-open-file (stream "t/validityTests.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 4)
(validity-test
(first row)
(boolean-from-string (second row))
(boolean-from-string (third row))
(boolean-from-string (fourth row))))
(t (fixme))))))
;; Test encoding and decoding codes.
(defun encoding-test (code len lat lon)
(let ((prec (olc:precision (or len (olc:decode code)))))
(assert-true
(string= (olc:encode lat lon prec) code))))
(defun decoding-test (code len lat-low lon-low lat-high lon-high)
(let ((area (olc:decode code)))
(assert-true
(and (if len (= (olc:code-length (olc:precision area)) len) t)
(multiple-value-bind (south west)
(olc:south-west-corner area)
(and (float-equal* lat-low south)
(float-equal* lon-low west)))
(multiple-value-bind (north east)
(olc:north-east-corner area)
(and (float-equal* lat-high north)
(float-equal* lon-high east)))))))
(define-test encoding-tests
(with-open-file (stream "t/encoding.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 4)
(encoding-test
(fourth row)
(number-from-string (third row))
(number-from-string (first row))
(number-from-string (second row))))
(t (fixme))))))
(define-test decoding-tests
(with-open-file (stream "t/decoding.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 6)
(decoding-test
(first row)
(number-from-string (second row))
(number-from-string (third row))
(number-from-string (fourth row))
(number-from-string (fifth row))
(number-from-string (sixth row))))
(t (fixme))))))
;; Test shortening and extending codes.
(defun short-code-test (full-code lat lon short-code test-type)
(assert-true
(and (if (member test-type '(:both :shorten))
(string= (olc:shorten full-code lat lon) short-code)
t)
(if (member test-type '(:both :recover))
(string= (olc:recover short-code lat lon) full-code)
t))))
(define-test short-code-tests
(with-open-file (stream "t/shortCodeTests.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 5)
(short-code-test
(first row)
(number-from-string (second row))
(number-from-string (third row))
(fourth row)
(let ((test-type (fifth row)))
(cond ((string= test-type "B") :both)
((string= test-type "S") :shorten)
((string= test-type "R") :recover)
(t (fixme))))))
(t (fixme))))))
(let ((lisp-unit:*print-errors* t)
(lisp-unit:*print-failures* t)
(lisp-unit:*print-summary* t)
(lisp-unit:*epsilon* 1D-10))
(run-tests))
;;; tests.lisp ends here
| null | https://raw.githubusercontent.com/ralph-schleicher/open-location-code/69c30b9f8e711c25e7a90c1de87501f845f5ca79/tests.lisp | lisp | tests.lisp --- test procedure.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
OR BUSINESS INTERRUPTION ) HOWEVER
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.
Code:
Test encoding and decoding codes.
Test shortening and extending codes.
tests.lisp ends here |
Copyright ( C ) 2019
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING ,
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(in-package :common-lisp-user)
(ql:quickload :open-location-code)
(ql:quickload :lisp-unit)
(ql:quickload :cl-csv)
(ql:quickload :read-number)
(defpackage :open-location-code-tests
(:use :common-lisp
:lisp-unit
:iterate))
(in-package :open-location-code-tests)
(defun float-equal* (a b)
(if (or (floatp a) (floatp b))
(float-equal a b)
(= a b)))
(defun fixme ()
(error "Should not happen."))
(defun boolean-from-string (string)
(cond ((or (string-equal string "true")
(string-equal string "yes")
(string-equal string "on"))
t)
((or (string-equal string "false")
(string-equal string "no")
(string-equal string "off"))
nil)
(t
(fixme))))
(defun number-from-string (string)
(with-input-from-string (stream string)
(read-number:read-float stream t nil nil :float-format 'double-float)))
(define-test length-from-precision
(assert-true (olc:code-length 1) 2)
(assert-true (olc:code-length 2) 4)
(assert-true (olc:code-length 3) 6)
(assert-true (olc:code-length 4) 8)
(assert-true (olc:code-length 5) 10)
(assert-true (olc:code-length 6) 11)
(assert-true (olc:code-length 7) 12)
(assert-true (olc:code-length 8) 13)
(assert-true (olc:code-length 9) 14)
(assert-true (olc:code-length 10) 15)
(assert-true (olc:code-length 11) 15))
(define-test precision-from-length
(assert-true (olc:precision 2) 1)
(assert-true (olc:precision 4) 2)
(assert-true (olc:precision 6) 3)
(assert-true (olc:precision 8) 4)
(assert-true (olc:precision 10) 5)
(assert-true (olc:precision 11) 6)
(assert-true (olc:precision 12) 7)
(assert-true (olc:precision 13) 8)
(assert-true (olc:precision 14) 9)
(assert-true (olc:precision 15) 10)
(assert-true (olc:precision 16) 10))
(defun validity-test (code valid short full)
(declare (ignore valid))
(assert-true
(eq (olc:validp code)
(cond (short
:short)
(full
:full)))))
(define-test validity-tests
(with-open-file (stream "t/validityTests.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 4)
(validity-test
(first row)
(boolean-from-string (second row))
(boolean-from-string (third row))
(boolean-from-string (fourth row))))
(t (fixme))))))
(defun encoding-test (code len lat lon)
(let ((prec (olc:precision (or len (olc:decode code)))))
(assert-true
(string= (olc:encode lat lon prec) code))))
(defun decoding-test (code len lat-low lon-low lat-high lon-high)
(let ((area (olc:decode code)))
(assert-true
(and (if len (= (olc:code-length (olc:precision area)) len) t)
(multiple-value-bind (south west)
(olc:south-west-corner area)
(and (float-equal* lat-low south)
(float-equal* lon-low west)))
(multiple-value-bind (north east)
(olc:north-east-corner area)
(and (float-equal* lat-high north)
(float-equal* lon-high east)))))))
(define-test encoding-tests
(with-open-file (stream "t/encoding.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 4)
(encoding-test
(fourth row)
(number-from-string (third row))
(number-from-string (first row))
(number-from-string (second row))))
(t (fixme))))))
(define-test decoding-tests
(with-open-file (stream "t/decoding.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 6)
(decoding-test
(first row)
(number-from-string (second row))
(number-from-string (third row))
(number-from-string (fourth row))
(number-from-string (fifth row))
(number-from-string (sixth row))))
(t (fixme))))))
(defun short-code-test (full-code lat lon short-code test-type)
(assert-true
(and (if (member test-type '(:both :shorten))
(string= (olc:shorten full-code lat lon) short-code)
t)
(if (member test-type '(:both :recover))
(string= (olc:recover short-code lat lon) full-code)
t))))
(define-test short-code-tests
(with-open-file (stream "t/shortCodeTests.csv")
(iter (for row :in (cl-csv:read-csv stream))
(for columns = (length row))
(cond ((zerop columns)
(next-iteration))
((char= (aref (first row) 0) #\#)
(next-iteration))
((= columns 5)
(short-code-test
(first row)
(number-from-string (second row))
(number-from-string (third row))
(fourth row)
(let ((test-type (fifth row)))
(cond ((string= test-type "B") :both)
((string= test-type "S") :shorten)
((string= test-type "R") :recover)
(t (fixme))))))
(t (fixme))))))
(let ((lisp-unit:*print-errors* t)
(lisp-unit:*print-failures* t)
(lisp-unit:*print-summary* t)
(lisp-unit:*epsilon* 1D-10))
(run-tests))
|
253c971ad501307432982920ea2cd8a4c35880fac44ccbe70263126db41dfbf1 | facebookincubator/hsthrift | HsStdTuple.hs | Copyright ( c ) Facebook , Inc. and its affiliates .
# LANGUAGE TemplateHaskell #
module Foreign.CPP.HsStruct.HsStdTuple
( deriveHsStdTupleUnsafe
, HsStdTuple(..)
) where
import Data.List (foldl')
import Control.Monad (forM, unless)
import Foreign
import Language.Haskell.TH
import Foreign.CPP.Addressable
import Foreign.CPP.Marshallable
newtype HsStdTuple a = HsStdTuple { unHsStdTuple :: a }
deriveHsStdTupleUnsafe
:: String -> Int -> TypeQ -> Q [Dec]
deriveHsStdTupleUnsafe cppType sizeVal hsType = do
hsStdTupleType <- [t| HsStdTuple |]
hsTRaw <- hsType
let
(hsT, tupleType) = case hsTRaw of
(AppT a b) | a == hsStdTupleType -> (b, hsType)
_ -> (hsTRaw, [t| HsStdTuple $hsType |])
(numTypes, hsTypes) = unfoldTupleT hsT
unless (numTypes > 0) $
fail "StdTuple must be a tuple with 1 or more underlying types"
hsTypesDestructible <-
forM hsTypes $ \t -> isInstance (mkName "Destructible") [t]
addressableInst <- instanceD
(cxt [])
[t| Addressable $tupleType |]
[]
let
sizeOfFn = funD (mkName "sizeOf")
[ clause [wildP] (normalB $ litE $ integerL $ fromIntegral sizeVal) [] ]
alignmentFn = funD (mkName "alignment")
[ clause [wildP] (normalB $
litE $ integerL $ fromIntegral sizeVal) []
]
ptrN = mkName "ptr"
pNames = take numTypes $ idxNames "p"
vNames = take numTypes $ idxNames "v"
pvZipped = zip pNames vNames
pCasted = map (\p -> parensE $ varE castPtrN `appE` varE p) pNames
hsPokeName = mkName $ "c_poke_" ++ cppName
cppPokeName = "std_tuple_poke_" ++ cppName
nestedPokeFns = nestPokeFns (zip3 vNames pNames hsTypesDestructible) $ doE
c_poke * FFI call
[ noBindS (foldl' appE
(varE hsPokeName `appE` [| castPtr ptr|] `appE` [|nullPtr|])
pCasted
)
]
pokeFn = funD (mkName "poke")
[ clause [varP ptrN, conP (mkName "HsStdTuple") [tupP (map varP vNames)]]
(normalB nestedPokeFns) []
]
hsPeekName = mkName $ "c_peek_" ++ cppName
cppPeekName = "std_tuple_peek_" ++ cppName
nestedPeekFns = nestPeekFns (zip pNames hsTypesDestructible) $
doE $
-- c_peek* FFI call
[noBindS (foldl' appE
(varE hsPeekName `appE` [| castPtr ptr|] `appE` [|nullPtr|])
pCasted
)
] ++
-- N peeks
map (\(p, v) -> bindS (varP v) (varE (mkName "peek") `appE` varE p))
pvZipped ++
-- tuple construction
[noBindS (varE (mkName "return") `appE`
parensE (conE (mkName "HsStdTuple") `appE` tupE (map varE vNames)))
]
peekFn = funD (mkName "peek")
[ clause [varP ptrN] (normalB nestedPeekFns) []
]
storableInst <- instanceD
(cxt [])
[t| Storable $tupleType |]
[sizeOfFn, alignmentFn, pokeFn, peekFn]
peekImport <- forImpD cCall unsafe cppPeekName hsPeekName $
-- Ptr () -> Ptr () -> <<< all tuple types >>> -> IO ()
foldl' (\b a -> [t| $a -> $b |]) [t| IO () |] $
map (\a -> [t| Ptr $a |]) ([t|()|] : [t| ()|] : map return hsTypes)
pokeImport <- forImpD cCall unsafe cppPokeName hsPokeName $
-- Ptr () -> Ptr () -> <<< all tuple types >>> -> IO ()
foldl' (\b a -> [t| $a -> $b |]) [t| IO () |] $
map (\a -> [t| Ptr $a |]) ([t|()|] : [t| ()|] : map return hsTypes)
constructibleInst <- instanceD
(cxt [])
[t| Constructible $tupleType |]
[]
return
[ addressableInst
, storableInst
, constructibleInst
, peekImport
, pokeImport
]
where
unfoldTupleT :: Type -> (Int, [Type])
unfoldTupleT (AppT a b) = let
(i, ts) = unfoldTupleT a
in (i, ts ++ [b])
unfoldTupleT (TupleT i) = (i, [])
unfoldTupleT n = (1, [n])
castPtrN = mkName "castPtr"
cppName = cppType
idxNames c = map (\i -> mkName (c ++ show i)) [0::Int ..]
nestPeekFns :: [(Name, Bool)] -> ExpQ -> ExpQ
nestPeekFns [] base = base
nestPeekFns ((p, isDestructible):ts) base =
varE (mkName allocFn) `appE` lamE [varP p] (nestPeekFns ts base)
where
allocFn = if isDestructible then "withDefaultCxxObject" else "alloca"
nestPokeFns :: [(Name, Name, Bool)] -> ExpQ -> ExpQ
nestPokeFns [] base = base
nestPokeFns ((v, p, isDestructible):ts) base =
varE (mkName withObjFn) `appE` varE v `appE`
lamE [varP p] (nestPokeFns ts base)
where
withObjFn = if isDestructible then "withCxxObject" else "with"
| null | https://raw.githubusercontent.com/facebookincubator/hsthrift/8816d3fdd03c4d15ee8cde4ef2e88eeb0b2be1bb/common/util/Foreign/CPP/HsStruct/HsStdTuple.hs | haskell | c_peek* FFI call
N peeks
tuple construction
Ptr () -> Ptr () -> <<< all tuple types >>> -> IO ()
Ptr () -> Ptr () -> <<< all tuple types >>> -> IO () | Copyright ( c ) Facebook , Inc. and its affiliates .
# LANGUAGE TemplateHaskell #
module Foreign.CPP.HsStruct.HsStdTuple
( deriveHsStdTupleUnsafe
, HsStdTuple(..)
) where
import Data.List (foldl')
import Control.Monad (forM, unless)
import Foreign
import Language.Haskell.TH
import Foreign.CPP.Addressable
import Foreign.CPP.Marshallable
newtype HsStdTuple a = HsStdTuple { unHsStdTuple :: a }
deriveHsStdTupleUnsafe
:: String -> Int -> TypeQ -> Q [Dec]
deriveHsStdTupleUnsafe cppType sizeVal hsType = do
hsStdTupleType <- [t| HsStdTuple |]
hsTRaw <- hsType
let
(hsT, tupleType) = case hsTRaw of
(AppT a b) | a == hsStdTupleType -> (b, hsType)
_ -> (hsTRaw, [t| HsStdTuple $hsType |])
(numTypes, hsTypes) = unfoldTupleT hsT
unless (numTypes > 0) $
fail "StdTuple must be a tuple with 1 or more underlying types"
hsTypesDestructible <-
forM hsTypes $ \t -> isInstance (mkName "Destructible") [t]
addressableInst <- instanceD
(cxt [])
[t| Addressable $tupleType |]
[]
let
sizeOfFn = funD (mkName "sizeOf")
[ clause [wildP] (normalB $ litE $ integerL $ fromIntegral sizeVal) [] ]
alignmentFn = funD (mkName "alignment")
[ clause [wildP] (normalB $
litE $ integerL $ fromIntegral sizeVal) []
]
ptrN = mkName "ptr"
pNames = take numTypes $ idxNames "p"
vNames = take numTypes $ idxNames "v"
pvZipped = zip pNames vNames
pCasted = map (\p -> parensE $ varE castPtrN `appE` varE p) pNames
hsPokeName = mkName $ "c_poke_" ++ cppName
cppPokeName = "std_tuple_poke_" ++ cppName
nestedPokeFns = nestPokeFns (zip3 vNames pNames hsTypesDestructible) $ doE
c_poke * FFI call
[ noBindS (foldl' appE
(varE hsPokeName `appE` [| castPtr ptr|] `appE` [|nullPtr|])
pCasted
)
]
pokeFn = funD (mkName "poke")
[ clause [varP ptrN, conP (mkName "HsStdTuple") [tupP (map varP vNames)]]
(normalB nestedPokeFns) []
]
hsPeekName = mkName $ "c_peek_" ++ cppName
cppPeekName = "std_tuple_peek_" ++ cppName
nestedPeekFns = nestPeekFns (zip pNames hsTypesDestructible) $
doE $
[noBindS (foldl' appE
(varE hsPeekName `appE` [| castPtr ptr|] `appE` [|nullPtr|])
pCasted
)
] ++
map (\(p, v) -> bindS (varP v) (varE (mkName "peek") `appE` varE p))
pvZipped ++
[noBindS (varE (mkName "return") `appE`
parensE (conE (mkName "HsStdTuple") `appE` tupE (map varE vNames)))
]
peekFn = funD (mkName "peek")
[ clause [varP ptrN] (normalB nestedPeekFns) []
]
storableInst <- instanceD
(cxt [])
[t| Storable $tupleType |]
[sizeOfFn, alignmentFn, pokeFn, peekFn]
peekImport <- forImpD cCall unsafe cppPeekName hsPeekName $
foldl' (\b a -> [t| $a -> $b |]) [t| IO () |] $
map (\a -> [t| Ptr $a |]) ([t|()|] : [t| ()|] : map return hsTypes)
pokeImport <- forImpD cCall unsafe cppPokeName hsPokeName $
foldl' (\b a -> [t| $a -> $b |]) [t| IO () |] $
map (\a -> [t| Ptr $a |]) ([t|()|] : [t| ()|] : map return hsTypes)
constructibleInst <- instanceD
(cxt [])
[t| Constructible $tupleType |]
[]
return
[ addressableInst
, storableInst
, constructibleInst
, peekImport
, pokeImport
]
where
unfoldTupleT :: Type -> (Int, [Type])
unfoldTupleT (AppT a b) = let
(i, ts) = unfoldTupleT a
in (i, ts ++ [b])
unfoldTupleT (TupleT i) = (i, [])
unfoldTupleT n = (1, [n])
castPtrN = mkName "castPtr"
cppName = cppType
idxNames c = map (\i -> mkName (c ++ show i)) [0::Int ..]
nestPeekFns :: [(Name, Bool)] -> ExpQ -> ExpQ
nestPeekFns [] base = base
nestPeekFns ((p, isDestructible):ts) base =
varE (mkName allocFn) `appE` lamE [varP p] (nestPeekFns ts base)
where
allocFn = if isDestructible then "withDefaultCxxObject" else "alloca"
nestPokeFns :: [(Name, Name, Bool)] -> ExpQ -> ExpQ
nestPokeFns [] base = base
nestPokeFns ((v, p, isDestructible):ts) base =
varE (mkName withObjFn) `appE` varE v `appE`
lamE [varP p] (nestPokeFns ts base)
where
withObjFn = if isDestructible then "withCxxObject" else "with"
|
2331e8707267d4b74896074ac655e58e72a1d1248a2cf717be5b91a69c238e89 | Concordium/concordium-client | Spec.hs | module Main where
import Test.Hspec
import qualified DataTests.DoubleWordSpec
import qualified SimpleClientTests.CliSpec
main :: IO ()
main = hspec $ parallel $ do
SimpleClientTests.CliSpec.tests
DataTests.DoubleWordSpec.tests
| null | https://raw.githubusercontent.com/Concordium/concordium-client/2ae3b56c384ac6803ec96a078e5d99de14b42ce2/test/Spec.hs | haskell | module Main where
import Test.Hspec
import qualified DataTests.DoubleWordSpec
import qualified SimpleClientTests.CliSpec
main :: IO ()
main = hspec $ parallel $ do
SimpleClientTests.CliSpec.tests
DataTests.DoubleWordSpec.tests
| |
140f5b7830902164154979c8438eaf0ada87278c07337431553960e99ab829b8 | albertoruiz/easyVision | graph.hs | # LANGUAGE TupleSections #
-- experiments with spectral graph matching
import Classifier.ToyProblems ( sshape )
import Classifier ( addNoise, boxAttr, preprocess )
import Util.Misc ( vec )
import Util.Debug(debug)
import Util.Gaussian ()
import Numeric.LinearAlgebra
import Vision.GUI.Simple
import Image ( Point(Point) )
import Graphics.UI.GLUT
( vertex, renderPrimitive, PrimitiveMode(Lines) )
import Control.Monad ( when )
import qualified Classifier.GP as GP ( gaussK )
scw title p = browser title xs (const id)
where
xs = [scatter p (0,1) [] (Draw())]
scw3 name ps = browser3D name xs (const id)
where
xs = map (\p-> scatter3D p (0,1,2) [] (Draw())) ps
scwgraph title p g = browser title [d] (const id)
where
d = scatter p (0,1) [black] x
x = color black $ Raw $ do
renderPrimitive Lines $ mapMatrixWithIndexM_ h g
indexSample p
h (i,j) w = when (w>0) (vertex (fst(p!!i)) >> vertex (fst(p!!j)))
indexSample p = mapM_ (\((v,_),k)-> textAt (Point (v@>0) (v@>1)) (show k)) (zip p [0..])
---------------------------------------------------------------------------
main = test sshape 0.1 0.8
sigma = 1
lap adj = d - adj
where
d = diag $ vec $ map sumElements $ toRows adj
lapSym adj = sd <> (d - adj) <> sd
where
vd = vec $ map sumElements $ toRows adj
d = diag vd
sd = diag (sqrt . recip $ vd)
lapRW adj = id <> (d-adj)
where
vd = vec $ map sumElements $ toRows adj
d = diag vd
id = diag . recip $ vd
lapDL adj = (d,(d-adj))
where
d = diag $ vec $ map sumElements $ toRows adj
eigSorted (l,v) = fromColumns $ sortWith (negate . magnitude) (toList l) (toColumns v)
sortWith f k v = map snd $ sortBy (compare `on` (f.fst)) $ zip k v
test prob noise threshold = do
seed <- return 66666 -- randomIO
let p = filter ((==snd(head (prob 200))).snd) $ addNoise seed noise $ prob 200
x = fromRows (map fst p) -- data matrix
s = GP.gaussK sigma x x -- similarity matrix
g = step (s-threshold) -- graph (or s)
l = ; u = snd ( dbgeig $ eigSH l ) -- laplacian and eigenvectors in columns
l = lap g ; u = snd ( dbgeig $ eigSH l )
l = ; u = fst . fromComplex . eigSorted . eig $ l
(d,l) = lapDL g; u = snd (dbgeig $ geigSH' l d) -- RW
e.g. 2 principal components
y' = takeColumns 3 . snd . eigSH' $ g
runIt $ do
scwgraph "graph" p g
scw "clusters" (map (,"?") (toRows y))
scw "spectral embedding" (toRows y `zip` map snd p)
scw3 "spectral embedding" [(ba (toRows y `zip` map snd p))]
scw3 "naive embedding" [(ba (toRows y' `zip` map snd p))]
ba p = boxAttr p `preprocess` p
dbgeig x = debug "eig" (take 10.reverse.toList.fst) x
dbgeig' x = debug "eig" (take 10.toList.fst) x
----------------------------------------------------------------------
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/patrec/graph.hs | haskell | experiments with spectral graph matching
-------------------------------------------------------------------------
randomIO
data matrix
similarity matrix
graph (or s)
laplacian and eigenvectors in columns
RW
-------------------------------------------------------------------- | # LANGUAGE TupleSections #
import Classifier.ToyProblems ( sshape )
import Classifier ( addNoise, boxAttr, preprocess )
import Util.Misc ( vec )
import Util.Debug(debug)
import Util.Gaussian ()
import Numeric.LinearAlgebra
import Vision.GUI.Simple
import Image ( Point(Point) )
import Graphics.UI.GLUT
( vertex, renderPrimitive, PrimitiveMode(Lines) )
import Control.Monad ( when )
import qualified Classifier.GP as GP ( gaussK )
scw title p = browser title xs (const id)
where
xs = [scatter p (0,1) [] (Draw())]
scw3 name ps = browser3D name xs (const id)
where
xs = map (\p-> scatter3D p (0,1,2) [] (Draw())) ps
scwgraph title p g = browser title [d] (const id)
where
d = scatter p (0,1) [black] x
x = color black $ Raw $ do
renderPrimitive Lines $ mapMatrixWithIndexM_ h g
indexSample p
h (i,j) w = when (w>0) (vertex (fst(p!!i)) >> vertex (fst(p!!j)))
indexSample p = mapM_ (\((v,_),k)-> textAt (Point (v@>0) (v@>1)) (show k)) (zip p [0..])
main = test sshape 0.1 0.8
sigma = 1
lap adj = d - adj
where
d = diag $ vec $ map sumElements $ toRows adj
lapSym adj = sd <> (d - adj) <> sd
where
vd = vec $ map sumElements $ toRows adj
d = diag vd
sd = diag (sqrt . recip $ vd)
lapRW adj = id <> (d-adj)
where
vd = vec $ map sumElements $ toRows adj
d = diag vd
id = diag . recip $ vd
lapDL adj = (d,(d-adj))
where
d = diag $ vec $ map sumElements $ toRows adj
eigSorted (l,v) = fromColumns $ sortWith (negate . magnitude) (toList l) (toColumns v)
sortWith f k v = map snd $ sortBy (compare `on` (f.fst)) $ zip k v
test prob noise threshold = do
let p = filter ((==snd(head (prob 200))).snd) $ addNoise seed noise $ prob 200
l = lap g ; u = snd ( dbgeig $ eigSH l )
l = ; u = fst . fromComplex . eigSorted . eig $ l
e.g. 2 principal components
y' = takeColumns 3 . snd . eigSH' $ g
runIt $ do
scwgraph "graph" p g
scw "clusters" (map (,"?") (toRows y))
scw "spectral embedding" (toRows y `zip` map snd p)
scw3 "spectral embedding" [(ba (toRows y `zip` map snd p))]
scw3 "naive embedding" [(ba (toRows y' `zip` map snd p))]
ba p = boxAttr p `preprocess` p
dbgeig x = debug "eig" (take 10.reverse.toList.fst) x
dbgeig' x = debug "eig" (take 10.toList.fst) x
|
c4eaab13befdde85e27ca5c65f0712572af1c0bd5ffe074520d986e821f80f11 | mirage/alcotest | fail_with.ml | let test_lwt _switch () = Lwt.fail_with "should fail"
let () =
let open Alcotest_lwt in
Lwt_main.run
@@ run ~record_backtrace:false __FILE__
[
( "all",
[
test_case "one" `Quick test_lwt;
test_case "two" `Quick (fun _ () -> Lwt.return_unit);
] );
]
| null | https://raw.githubusercontent.com/mirage/alcotest/bb3492901dea03c72b4de6b5660852a020283921/test/e2e/alcotest-lwt/failing/fail_with.ml | ocaml | let test_lwt _switch () = Lwt.fail_with "should fail"
let () =
let open Alcotest_lwt in
Lwt_main.run
@@ run ~record_backtrace:false __FILE__
[
( "all",
[
test_case "one" `Quick test_lwt;
test_case "two" `Quick (fun _ () -> Lwt.return_unit);
] );
]
| |
353d415540521911ed35b15f81642b2f7aa2ab07ebd142a2f028fd13c948cb5a | ublubu/shapes | Contact.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
|
This is the backbone of the physics engine .
The functions here find contacts between objects and generate and solve constraints for these contacts .
It exploits temporal coherence of the scene by caching constraint solutions between frames .
This way , it can accumulate stability over time instead of requiring many solver iterations each frame .
The functions in this module are designed to be used in this order :
1 . ' prepareFrame ' - Which contacts are creating constraints for us to solve this frame ?
2 . ' applyCachedSlns ' - Build this frame 's Lagrangian and constraint caches . Apply relevant Lagrangians from the previous frame .
3 . ' improveWorld ' - Iteratively solve the constraints and update the cached Lagrangians . ( Can do this step multiple times . )
The cache of Lagrangians should be retained for the next frame 's ' applyCachedSlns ' .
This is the backbone of the physics engine.
The functions here find contacts between objects and generate and solve constraints for these contacts.
It exploits temporal coherence of the scene by caching constraint solutions between frames.
This way, it can accumulate stability over time instead of requiring many solver iterations each frame.
The functions in this module are designed to be used in this order:
1. 'prepareFrame' - Which contacts are creating constraints for us to solve this frame?
2. 'applyCachedSlns' - Build this frame's Lagrangian and constraint caches. Apply relevant Lagrangians from the previous frame.
3. 'improveWorld' - Iteratively solve the constraints and update the cached Lagrangians. (Can do this step multiple times.)
The cache of Lagrangians should be retained for the next frame's 'applyCachedSlns'.
-}
module Physics.Solvers.Contact where
import Control.Lens
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import qualified Data.Vector.Generic.Mutable as MV
import qualified Data.Vector.Unboxed as V
import Physics.Constraint
import Physics.Constraints.Contact
import Physics.Constraints.Types
import Physics.Contact.Types
import Physics.World
import Utils.Descending
import Utils.Utils
-- | Calculate all contacts for the current frame.
prepareFrame ::
^ broadphase - filtered pairs of shapes to check for contact
-> World s label -- ^ the world
-> ST s (Descending (ObjectFeatureKey Int, Flipping Contact)) -- ^ list of contacts between shapes (in descending order of 'ObjectFeatureKey' because the caches are ordered)
prepareFrame (Descending pairKeys) world = do
contacts <- mapM findContacts pairKeys
return . Descending $ join contacts
where
findContacts (i, j) = do
shape_i <- readShape world i
shape_j <- readShape world j
return . _descList $ keyedContacts (i, j) (shape_i, shape_j)
# INLINE prepareFrame #
-- | Update a pair of shapes based on the solution to their constraint.
applySln ::
ContactLagrangian -- ^ the solution
-> ContactConstraint -- ^ the constraint
-> (PhysicalObj, PhysicalObj)
-> (PhysicalObj, PhysicalObj)
applySln ContactLagrangian {..} ContactConstraint {..} =
applyFriction . applyNonPen
where
applyNonPen = applyLagrangian _clNonPen _ccNonPen
applyFriction = applyLagrangian _clFriction _ccFriction
# INLINE applySln #
|
Calculate all new constraints from the contacts .
Apply cached lagrangians using new constraints .
Build new lagrangians cache with either zero or previously cached value .
TODO : reader monad for stuff that 's const between frames ( beh , dt )
Calculate all new constraints from the contacts.
Apply cached lagrangians using new constraints.
Build new lagrangians cache with either zero or previously cached value.
TODO: reader monad for stuff that's const between frames (beh, dt)
-}
applyCachedSlns ::
forall s label.
ContactBehavior
-> Double -- ^ dt
-> Descending (ObjectFeatureKey Int, Flipping Contact) -- ^ list of contacts between shapes
-> V.MVector s (ObjectFeatureKey Int, ContactLagrangian) -- ^ list of constraint solutions from the previous frame
-> World s label -- ^ the world
-> ST s ( V.MVector s (ObjectFeatureKey Int, ContactLagrangian)
, V.Vector ContactConstraint)
-- ^ (this frame's constraint solutions, this frame's constraints)
applyCachedSlns beh dt kContacts oldLagrangians world = do
lagrangians <- MV.new contactCount
constraints <- MV.new contactCount
let newCache ::
Int -- ^ current index in cache
-> (ObjectFeatureKey Int, Flipping Contact) -- ^ the contact to store at this index in the cache
-> ST s Int -- ^ next index in cache
newCache i (key@ObjectFeatureKey {..}, fContact) = do
ab <- readPhysObjPair world _ofkObjKeys
let constraint = constraintGen beh dt fContact ab
-- no previously-cached lagrangian, so start with 0.
MV.write lagrangians i (key, ContactLagrangian 0 0)
-- save the constraint so we can solve it (calculate/apply lagrangian)
MV.write constraints i constraint
return (i + 1)
# INLINE newCache #
useCache ::
Int -- ^ current index in cache
-> (ObjectFeatureKey Int, Flipping Contact) -- ^ the contact to store at this index in the cache
-> (ObjectFeatureKey Int, ContactLagrangian) -- ^ the previous frame's solution for the last frame's corresponding contact
-> ST s Int -- ^ next index in cache
useCache i (ObjectFeatureKey {..}, fContact) kLagr@(_, lagr) = do
ab <- readPhysObjPair world _ofkObjKeys
let constraint = constraintGen beh dt fContact ab
modifyPhysObjPair world (applySln lagr constraint) _ofkObjKeys
-- propagate the previously-cached lagrangian to the current frame's cache
MV.write lagrangians i kLagr
-- save the constraint so we can solve it (calculate/apply lagrangian)
MV.write constraints i constraint
return (i + 1)
# INLINE useCache #
-- zip the previous frame's cached solutions into this frame's contacts, applying cached solutions as we go
_ <- descZipVector fst fst useCache newCache 0 kContacts oldLagrangians
frozenConstraints <- V.unsafeFreeze constraints
return (lagrangians, frozenConstraints)
where
contactCount = length kContacts
# INLINE applyCachedSlns #
-- | Solve the constraints for a given contact. (And apply the solution.)
improveContactSln ::
SolutionProcessor (Double, Double) (ContactLagrangian)
-> ObjectFeatureKey Int
-> Int
-> V.MVector s (ObjectFeatureKey Int, ContactLagrangian)
-> V.Vector ContactConstraint
-> World s label
-> ST s ()
improveContactSln slnProc key@ObjectFeatureKey{..} i lagrangians constraints world = do
(_, cached_l) <- MV.read lagrangians i
let constraint = constraints V.! i
phys_ab <- readPhysObjPair world _ofkObjKeys
mat_ab <- readMaterialPair world _ofkObjKeys
let new_l = contactLagrangian bounce_ab constraint phys_ab
mu_ab = pairMap _mMu mat_ab
bounce_ab = pairMap _mBounce mat_ab
Processed {..} = slnProc mu_ab cached_l new_l
modifyPhysObjPair world (applySln _processedToApply constraint) _ofkObjKeys
MV.write lagrangians i (key, _processedToCache)
# INLINE improveContactSln #
-- | Run `improveSln` on every constraint in the world.
improveWorld ::
SolutionProcessor (Double, Double) (ContactLagrangian)
-> Descending (ObjectFeatureKey Int, Flipping Contact)
-> V.MVector s (ObjectFeatureKey Int, ContactLagrangian)
-> V.Vector ContactConstraint
-> World s label
-> ST s ()
improveWorld slnProc (Descending kContacts) lagrangians constraints world =
mapM_ f $ zip [0..] kContacts
where
f (i, (key, _)) = improveContactSln slnProc key i lagrangians constraints world
# INLINE improveWorld #
| null | https://raw.githubusercontent.com/ublubu/shapes/fa5d959c17224a851d517826deeae097f1583392/shapes/src/Physics/Solvers/Contact.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
| Calculate all contacts for the current frame.
^ the world
^ list of contacts between shapes (in descending order of 'ObjectFeatureKey' because the caches are ordered)
| Update a pair of shapes based on the solution to their constraint.
^ the solution
^ the constraint
^ dt
^ list of contacts between shapes
^ list of constraint solutions from the previous frame
^ the world
^ (this frame's constraint solutions, this frame's constraints)
^ current index in cache
^ the contact to store at this index in the cache
^ next index in cache
no previously-cached lagrangian, so start with 0.
save the constraint so we can solve it (calculate/apply lagrangian)
^ current index in cache
^ the contact to store at this index in the cache
^ the previous frame's solution for the last frame's corresponding contact
^ next index in cache
propagate the previously-cached lagrangian to the current frame's cache
save the constraint so we can solve it (calculate/apply lagrangian)
zip the previous frame's cached solutions into this frame's contacts, applying cached solutions as we go
| Solve the constraints for a given contact. (And apply the solution.)
| Run `improveSln` on every constraint in the world. | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
|
This is the backbone of the physics engine .
The functions here find contacts between objects and generate and solve constraints for these contacts .
It exploits temporal coherence of the scene by caching constraint solutions between frames .
This way , it can accumulate stability over time instead of requiring many solver iterations each frame .
The functions in this module are designed to be used in this order :
1 . ' prepareFrame ' - Which contacts are creating constraints for us to solve this frame ?
2 . ' applyCachedSlns ' - Build this frame 's Lagrangian and constraint caches . Apply relevant Lagrangians from the previous frame .
3 . ' improveWorld ' - Iteratively solve the constraints and update the cached Lagrangians . ( Can do this step multiple times . )
The cache of Lagrangians should be retained for the next frame 's ' applyCachedSlns ' .
This is the backbone of the physics engine.
The functions here find contacts between objects and generate and solve constraints for these contacts.
It exploits temporal coherence of the scene by caching constraint solutions between frames.
This way, it can accumulate stability over time instead of requiring many solver iterations each frame.
The functions in this module are designed to be used in this order:
1. 'prepareFrame' - Which contacts are creating constraints for us to solve this frame?
2. 'applyCachedSlns' - Build this frame's Lagrangian and constraint caches. Apply relevant Lagrangians from the previous frame.
3. 'improveWorld' - Iteratively solve the constraints and update the cached Lagrangians. (Can do this step multiple times.)
The cache of Lagrangians should be retained for the next frame's 'applyCachedSlns'.
-}
module Physics.Solvers.Contact where
import Control.Lens
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import qualified Data.Vector.Generic.Mutable as MV
import qualified Data.Vector.Unboxed as V
import Physics.Constraint
import Physics.Constraints.Contact
import Physics.Constraints.Types
import Physics.Contact.Types
import Physics.World
import Utils.Descending
import Utils.Utils
prepareFrame ::
^ broadphase - filtered pairs of shapes to check for contact
prepareFrame (Descending pairKeys) world = do
contacts <- mapM findContacts pairKeys
return . Descending $ join contacts
where
findContacts (i, j) = do
shape_i <- readShape world i
shape_j <- readShape world j
return . _descList $ keyedContacts (i, j) (shape_i, shape_j)
# INLINE prepareFrame #
applySln ::
-> (PhysicalObj, PhysicalObj)
-> (PhysicalObj, PhysicalObj)
applySln ContactLagrangian {..} ContactConstraint {..} =
applyFriction . applyNonPen
where
applyNonPen = applyLagrangian _clNonPen _ccNonPen
applyFriction = applyLagrangian _clFriction _ccFriction
# INLINE applySln #
|
Calculate all new constraints from the contacts .
Apply cached lagrangians using new constraints .
Build new lagrangians cache with either zero or previously cached value .
TODO : reader monad for stuff that 's const between frames ( beh , dt )
Calculate all new constraints from the contacts.
Apply cached lagrangians using new constraints.
Build new lagrangians cache with either zero or previously cached value.
TODO: reader monad for stuff that's const between frames (beh, dt)
-}
applyCachedSlns ::
forall s label.
ContactBehavior
-> ST s ( V.MVector s (ObjectFeatureKey Int, ContactLagrangian)
, V.Vector ContactConstraint)
applyCachedSlns beh dt kContacts oldLagrangians world = do
lagrangians <- MV.new contactCount
constraints <- MV.new contactCount
let newCache ::
newCache i (key@ObjectFeatureKey {..}, fContact) = do
ab <- readPhysObjPair world _ofkObjKeys
let constraint = constraintGen beh dt fContact ab
MV.write lagrangians i (key, ContactLagrangian 0 0)
MV.write constraints i constraint
return (i + 1)
# INLINE newCache #
useCache ::
useCache i (ObjectFeatureKey {..}, fContact) kLagr@(_, lagr) = do
ab <- readPhysObjPair world _ofkObjKeys
let constraint = constraintGen beh dt fContact ab
modifyPhysObjPair world (applySln lagr constraint) _ofkObjKeys
MV.write lagrangians i kLagr
MV.write constraints i constraint
return (i + 1)
# INLINE useCache #
_ <- descZipVector fst fst useCache newCache 0 kContacts oldLagrangians
frozenConstraints <- V.unsafeFreeze constraints
return (lagrangians, frozenConstraints)
where
contactCount = length kContacts
# INLINE applyCachedSlns #
improveContactSln ::
SolutionProcessor (Double, Double) (ContactLagrangian)
-> ObjectFeatureKey Int
-> Int
-> V.MVector s (ObjectFeatureKey Int, ContactLagrangian)
-> V.Vector ContactConstraint
-> World s label
-> ST s ()
improveContactSln slnProc key@ObjectFeatureKey{..} i lagrangians constraints world = do
(_, cached_l) <- MV.read lagrangians i
let constraint = constraints V.! i
phys_ab <- readPhysObjPair world _ofkObjKeys
mat_ab <- readMaterialPair world _ofkObjKeys
let new_l = contactLagrangian bounce_ab constraint phys_ab
mu_ab = pairMap _mMu mat_ab
bounce_ab = pairMap _mBounce mat_ab
Processed {..} = slnProc mu_ab cached_l new_l
modifyPhysObjPair world (applySln _processedToApply constraint) _ofkObjKeys
MV.write lagrangians i (key, _processedToCache)
# INLINE improveContactSln #
improveWorld ::
SolutionProcessor (Double, Double) (ContactLagrangian)
-> Descending (ObjectFeatureKey Int, Flipping Contact)
-> V.MVector s (ObjectFeatureKey Int, ContactLagrangian)
-> V.Vector ContactConstraint
-> World s label
-> ST s ()
improveWorld slnProc (Descending kContacts) lagrangians constraints world =
mapM_ f $ zip [0..] kContacts
where
f (i, (key, _)) = improveContactSln slnProc key i lagrangians constraints world
# INLINE improveWorld #
|
54ba241bdd63f56a2b56d50f5d0838cd06649bd3cc058f152c6ad1e4ce8d5110 | tuscland/lw-dns-sd | browse.lisp | -*- encoding : utf-8 ; mode : LISP ; syntax : COMMON - LISP ; indent - tabs - mode : nil -*-
DNS Service Discovery for LispWorks .
Copyright ( c ) 2013 , . 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.
Example code for asynchronous service browsing using the CAPI
;; This example demonstrates the use of asynchronous operation and how
to integrate DNS - SD with the CAPI .
;;
;; To try it, compile and load this file and execute:
;;
( CL - USER::BROWSER - EXAMPLE )
(load (current-pathname "../defsystem"))
(compile-system "DNS-SD" :load t)
(defun callback-with-interface (interface function)
(lambda (operation result)
(capi:execute-with-interface-if-alive
interface
function interface operation result)))
(defun enumerate-service-types (&key callback
interface-index)
(dns-sd:query-record "_services._dns-sd._udp.local." :PTR
:callback callback
:interface-index interface-index))
(defun display-message (message interface)
(setf (capi:titled-object-message interface)
message))
(defun first-elt (sequence)
(when (plusp (length sequence))
(elt sequence 0)))
(capi:define-interface browser ()
((query-operation
:initform nil
:accessor browser-query-operation)
(service-types
:initform nil
:accessor browser-service-types)
(browse-operation
:initform nil
:accessor browser-browse-operation)
(services
:initform nil
:accessor browser-services))
(:panes
(types-menu
capi:option-pane
:selection-callback 'browser-select-type
:reader browser-types-pane)
(services-list
capi:list-panel
:reader browser-services-list))
(:layouts
(main
capi:column-layout
'(types-menu services-list)
:default t))
(:default-initargs
:create-callback 'browser-create
:destroy-callback 'browser-destroy
:best-height 200
:best-width 300
:message-area t))
(defun browser-select-type (type interface)
(display-message (format nil "Browsing ~A services ..." type)
interface)
(with-accessors ((operation browser-browse-operation)
(services browser-services)
(services-list browser-services-list)) interface
(when operation
(dns-sd:cancel operation)
(setf (capi:collection-items services-list) nil
services nil))
(when type
(setf operation
(dns-sd:browse type
:callback (callback-with-interface interface
#'browse-callback))))))
(defun update-service-types (interface)
(with-accessors ((types-pane browser-types-pane)
(types browser-service-types)) interface
(setf (capi:collection-items types-pane)
(sort types #'string-lessp))
(unless (browser-browse-operation interface)
(when-let (type (first-elt
(capi:collection-items types-pane)))
(setf (capi:choice-selected-item types-pane) type)
(browser-select-type type interface)))))
(defun update-services (interface)
(with-accessors ((services-list browser-services-list)) interface
(setf (capi:collection-items services-list)
(sort (browser-services interface)
#'string-lessp))))
(defun handle-error (interface operation error)
(dns-sd:cancel operation)
(display-message (format nil "Error occurred: ~A" error)
interface))
(defmethod browse-callback (interface operation (error error))
(handle-error interface operation error))
(defmethod browse-callback (interface operation result)
(let ((name (dns-sd:result-value result :name)))
(with-accessors ((services browser-services)) interface
(case (dns-sd:result-value result :presence)
(:add
(pushnew name services :test 'string=))
(:remove
(setf services
(remove name services :test 'string=))))))
(unless (dns-sd:result-more-coming-p result)
(update-services interface)))
(defmethod enumerate-service-types-callback (interface operation (error error))
(handle-error interface operation error))
(defmethod enumerate-service-types-callback (interface operation result)
(let* ((record (mapcar #'car
(dns-sd:parse-txt-record
(dns-sd:result-value result :rdata))))
(type (format nil "~A.~A"
(first record)
(second record))))
(with-accessors ((types browser-service-types)) interface
(case (dns-sd:result-value result :presence)
(:add
(pushnew type types :test 'string=))
(:remove
(setf types
(remove type types :test 'string=))))))
(unless (dns-sd:result-more-coming-p result)
(update-service-types interface)))
(defun browser-create (interface)
(setf (browser-query-operation interface)
(enumerate-service-types
:callback (callback-with-interface interface
#'enumerate-service-types-callback))))
(defun browser-destroy (interface)
(browser-select-type nil interface)
(dns-sd:cancel
(browser-query-operation interface)))
(defun browser-example ()
(capi:contain 'browser))
| null | https://raw.githubusercontent.com/tuscland/lw-dns-sd/2ae7e54b8bc3a89d267c2e91b083cd154bb1187d/examples/browse.lisp | lisp | mode : LISP ; syntax : COMMON - LISP ; indent - tabs - mode : nil -*-
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,
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.
This example demonstrates the use of asynchronous operation and how
To try it, compile and load this file and execute:
|
DNS Service Discovery for LispWorks .
Copyright ( c ) 2013 , . All rights reserved .
software distributed under the License is distributed on an " AS
Example code for asynchronous service browsing using the CAPI
to integrate DNS - SD with the CAPI .
( CL - USER::BROWSER - EXAMPLE )
(load (current-pathname "../defsystem"))
(compile-system "DNS-SD" :load t)
(defun callback-with-interface (interface function)
(lambda (operation result)
(capi:execute-with-interface-if-alive
interface
function interface operation result)))
(defun enumerate-service-types (&key callback
interface-index)
(dns-sd:query-record "_services._dns-sd._udp.local." :PTR
:callback callback
:interface-index interface-index))
(defun display-message (message interface)
(setf (capi:titled-object-message interface)
message))
(defun first-elt (sequence)
(when (plusp (length sequence))
(elt sequence 0)))
(capi:define-interface browser ()
((query-operation
:initform nil
:accessor browser-query-operation)
(service-types
:initform nil
:accessor browser-service-types)
(browse-operation
:initform nil
:accessor browser-browse-operation)
(services
:initform nil
:accessor browser-services))
(:panes
(types-menu
capi:option-pane
:selection-callback 'browser-select-type
:reader browser-types-pane)
(services-list
capi:list-panel
:reader browser-services-list))
(:layouts
(main
capi:column-layout
'(types-menu services-list)
:default t))
(:default-initargs
:create-callback 'browser-create
:destroy-callback 'browser-destroy
:best-height 200
:best-width 300
:message-area t))
(defun browser-select-type (type interface)
(display-message (format nil "Browsing ~A services ..." type)
interface)
(with-accessors ((operation browser-browse-operation)
(services browser-services)
(services-list browser-services-list)) interface
(when operation
(dns-sd:cancel operation)
(setf (capi:collection-items services-list) nil
services nil))
(when type
(setf operation
(dns-sd:browse type
:callback (callback-with-interface interface
#'browse-callback))))))
(defun update-service-types (interface)
(with-accessors ((types-pane browser-types-pane)
(types browser-service-types)) interface
(setf (capi:collection-items types-pane)
(sort types #'string-lessp))
(unless (browser-browse-operation interface)
(when-let (type (first-elt
(capi:collection-items types-pane)))
(setf (capi:choice-selected-item types-pane) type)
(browser-select-type type interface)))))
(defun update-services (interface)
(with-accessors ((services-list browser-services-list)) interface
(setf (capi:collection-items services-list)
(sort (browser-services interface)
#'string-lessp))))
(defun handle-error (interface operation error)
(dns-sd:cancel operation)
(display-message (format nil "Error occurred: ~A" error)
interface))
(defmethod browse-callback (interface operation (error error))
(handle-error interface operation error))
(defmethod browse-callback (interface operation result)
(let ((name (dns-sd:result-value result :name)))
(with-accessors ((services browser-services)) interface
(case (dns-sd:result-value result :presence)
(:add
(pushnew name services :test 'string=))
(:remove
(setf services
(remove name services :test 'string=))))))
(unless (dns-sd:result-more-coming-p result)
(update-services interface)))
(defmethod enumerate-service-types-callback (interface operation (error error))
(handle-error interface operation error))
(defmethod enumerate-service-types-callback (interface operation result)
(let* ((record (mapcar #'car
(dns-sd:parse-txt-record
(dns-sd:result-value result :rdata))))
(type (format nil "~A.~A"
(first record)
(second record))))
(with-accessors ((types browser-service-types)) interface
(case (dns-sd:result-value result :presence)
(:add
(pushnew type types :test 'string=))
(:remove
(setf types
(remove type types :test 'string=))))))
(unless (dns-sd:result-more-coming-p result)
(update-service-types interface)))
(defun browser-create (interface)
(setf (browser-query-operation interface)
(enumerate-service-types
:callback (callback-with-interface interface
#'enumerate-service-types-callback))))
(defun browser-destroy (interface)
(browser-select-type nil interface)
(dns-sd:cancel
(browser-query-operation interface)))
(defun browser-example ()
(capi:contain 'browser))
|
eb5c5272868d6bba3453a223cfbf3579476a4b74715e35f5e4d3bbe753892c26 | 5outh/textlunky | Player.hs | # LANGUAGE TemplateHaskell #
module Types.Player(
Player(..),
playerSnippet,
alive,
moveToEntity
) where
import Data.Default
import Control.Lens
import Data.List(intercalate)
import Data.Direction
import Types.Consumable
import Types.Item
import Types.Block
import Types.Enemy
import Types.Jewel
import Types.GroundItem
import Types.Entity
import Data.Vectors
import Types.PState
data Player = Player{
_loc :: Vector3 Int,
_hp :: Int,
_bombs :: Int,
_ropes :: Int,
_gold :: Int,
_items :: [Item], -- | Passive items
_holding :: Maybe Entity, -- | Current Item in hands
_favor :: Int, -- | Kali favor
_p_state :: PState
} deriving Eq
-- | Starting Player
instance Default Player where
def = Player (fromTriple (0,0,0)) 4 4 4 0 [] Nothing 0 Standing
makeLenses ''Player
-- | Full show, exclude favor since it's a hidden stat
instance Show Player where
show p = unlines $ filter (not . null)
[ "You are in the "
++ (showRelativeDirection (fromVector3 $ p^.loc))
++ " of the room."
, "You have " ++ show (p^.hp) ++ " hp remaining."
, "You have " ++ show (p^.bombs) ++ " bombs remaining."
, "You have " ++ show (p^.ropes) ++ " ropes remaining."
, "You have collected " ++ show (p^.gold) ++ " gold so far."
, if null (p^.items) then []
else "You have collected the following items: "
++ (intercalate ", " $ map show (p^.items))
, case (p^.holding) of
Nothing -> []
Just a -> "You are holding : " ++ show a
]
-- | Information to show on each round
playerSnippet :: Player -> String
playerSnippet p =
"You are in the "
++ (showRelativeDirection (fromVector3 $ p^.loc)) ++ "."
++ case p^.holding of
Just x -> "\nYou are holding a " ++ show x ++ "."
_ -> []
----- Extras -----
alive :: Player -> Bool
alive = (<=0) . view hp
pickupConsumbale :: Consumable -> Player -> Player
pickupConsumbale BombBox = bombs +~ 12
pickupConsumbale BombBag = bombs +~ 4
pickupConsumable RopePile = ropes +~ 4
-- What when the player moves onto another an entity?
NB . This should happen LAST : player should have the opportunity to
-- whip or whatever on the current spot and move out of the way
-- before this fires.
moveToEntity :: Vector3 Int -- | Location
-> Entity -- | Target
-> Player -- | Source
-> Player -- | Result
moveToEntity v (Jewel' j) = (loc .~ v) . (gold +~ value j)
moveToEntity v (Block' b) = case b of
Spikes -> (loc .~ v) . (p_state .~ Falling)
Web -> (loc .~ v) . (p_state .~ Stunned)
PowderKeg -> hp .~ 0
Exit -> loc .~ v
_ -> id
moveToEntity v (Enemy' e) = case e of
(BigSpider _ _) -> hp -~ 2
(Arrow True _ _) -> hp -~ 2
(Arrow False _ _) -> id
(Shopkeeper True _ _) -> (hp -~ 1) . (p_state .~ Stunned)
(Boulder True _ _) -> hp -~ 5
(Boulder False _ _) -> id
_ -> hp -~ 1
moveToEntity v (GroundItem' g) = case g of
Floor c -> pickupConsumable c . (loc .~ v)
_ -> loc .~ v
moveToEntity v _ = loc .~ v | null | https://raw.githubusercontent.com/5outh/textlunky/8dd4d975ed86b761262e3026dd4c22a36b532104/src/Types/Player.hs | haskell | | Passive items
| Current Item in hands
| Kali favor
| Starting Player
| Full show, exclude favor since it's a hidden stat
| Information to show on each round
--- Extras -----
What when the player moves onto another an entity?
whip or whatever on the current spot and move out of the way
before this fires.
| Location
| Target
| Source
| Result | # LANGUAGE TemplateHaskell #
module Types.Player(
Player(..),
playerSnippet,
alive,
moveToEntity
) where
import Data.Default
import Control.Lens
import Data.List(intercalate)
import Data.Direction
import Types.Consumable
import Types.Item
import Types.Block
import Types.Enemy
import Types.Jewel
import Types.GroundItem
import Types.Entity
import Data.Vectors
import Types.PState
data Player = Player{
_loc :: Vector3 Int,
_hp :: Int,
_bombs :: Int,
_ropes :: Int,
_gold :: Int,
_p_state :: PState
} deriving Eq
instance Default Player where
def = Player (fromTriple (0,0,0)) 4 4 4 0 [] Nothing 0 Standing
makeLenses ''Player
instance Show Player where
show p = unlines $ filter (not . null)
[ "You are in the "
++ (showRelativeDirection (fromVector3 $ p^.loc))
++ " of the room."
, "You have " ++ show (p^.hp) ++ " hp remaining."
, "You have " ++ show (p^.bombs) ++ " bombs remaining."
, "You have " ++ show (p^.ropes) ++ " ropes remaining."
, "You have collected " ++ show (p^.gold) ++ " gold so far."
, if null (p^.items) then []
else "You have collected the following items: "
++ (intercalate ", " $ map show (p^.items))
, case (p^.holding) of
Nothing -> []
Just a -> "You are holding : " ++ show a
]
playerSnippet :: Player -> String
playerSnippet p =
"You are in the "
++ (showRelativeDirection (fromVector3 $ p^.loc)) ++ "."
++ case p^.holding of
Just x -> "\nYou are holding a " ++ show x ++ "."
_ -> []
alive :: Player -> Bool
alive = (<=0) . view hp
pickupConsumbale :: Consumable -> Player -> Player
pickupConsumbale BombBox = bombs +~ 12
pickupConsumbale BombBag = bombs +~ 4
pickupConsumable RopePile = ropes +~ 4
NB . This should happen LAST : player should have the opportunity to
moveToEntity v (Jewel' j) = (loc .~ v) . (gold +~ value j)
moveToEntity v (Block' b) = case b of
Spikes -> (loc .~ v) . (p_state .~ Falling)
Web -> (loc .~ v) . (p_state .~ Stunned)
PowderKeg -> hp .~ 0
Exit -> loc .~ v
_ -> id
moveToEntity v (Enemy' e) = case e of
(BigSpider _ _) -> hp -~ 2
(Arrow True _ _) -> hp -~ 2
(Arrow False _ _) -> id
(Shopkeeper True _ _) -> (hp -~ 1) . (p_state .~ Stunned)
(Boulder True _ _) -> hp -~ 5
(Boulder False _ _) -> id
_ -> hp -~ 1
moveToEntity v (GroundItem' g) = case g of
Floor c -> pickupConsumable c . (loc .~ v)
_ -> loc .~ v
moveToEntity v _ = loc .~ v |
a7f8a319211c33108e07f93566cd7242611c15a5251a680c2b9ce52ad31963d4 | mu-chaco/ReWire | Mangle.hs | # LANGUAGE Trustworthy #
module ReWire.Core.Mangle (mangle) where
this is from the ghc package
import Data.Text (Text, pack, unpack)
-- TODO: text version of this?
mangle :: Text -> Text
mangle = pack . zEncodeString . unpack
| null | https://raw.githubusercontent.com/mu-chaco/ReWire/b04686a4cd6cb36ca9976a4b6c42bc195ce69462/src/ReWire/Core/Mangle.hs | haskell | TODO: text version of this? | # LANGUAGE Trustworthy #
module ReWire.Core.Mangle (mangle) where
this is from the ghc package
import Data.Text (Text, pack, unpack)
mangle :: Text -> Text
mangle = pack . zEncodeString . unpack
|
45699297d99ba5b0bdad8ce69aa382b11ec63066a03d1731b8fae7af5a1271ca | awakesecurity/language-ninja | DocTests.hs | -*- coding : utf-8 ; mode : ; -*-
-- File: tests/Tests.hs
--
-- License:
-- Copyright 2017 Awake Security
--
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- -2.0
--
-- Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- |
-- Module : Main
-- Copyright : Copyright 2017 Awake Security
-- License : Apache-2.0
-- Maintainer :
-- Stability : experimental
--
-- The @language-ninja@ documentation tests.
module Main (main) where
import qualified Build_doctests as DC
import Data.Foldable (traverse_)
import Test.DocTest (doctest)
--------------------------------------------------------------------------------
main :: IO ()
main = let args = DC.flags ++ DC.pkgs ++ DC.module_sources
in traverse_ putStrLn args >> doctest args
--------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/awakesecurity/language-ninja/e7badf49b45d9c28b558376be3152d51f5d2d437/tests/DocTests.hs | haskell | File: tests/Tests.hs
License:
Copyright 2017 Awake Security
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.
|
Module : Main
Copyright : Copyright 2017 Awake Security
License : Apache-2.0
Maintainer :
Stability : experimental
The @language-ninja@ documentation tests.
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | -*- coding : utf-8 ; mode : ; -*-
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
module Main (main) where
import qualified Build_doctests as DC
import Data.Foldable (traverse_)
import Test.DocTest (doctest)
main :: IO ()
main = let args = DC.flags ++ DC.pkgs ++ DC.module_sources
in traverse_ putStrLn args >> doctest args
|
e12357efb6b5f3ed848bbaf31496f10d3bd6065cceda09d5d3b27c2686321019 | alex-hhh/data-frame | histogram.rkt | #lang racket/base
;; histogram.rkt -- histograms and histogram plots for data frames
;;
;; This file is part of data-frame -- -hhh/data-frame
Copyright ( c ) 2018 < >
;;
;; This program is free software: you can redistribute it and/or modify it
;; under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation , either version 3 of the License , or ( at your
;; option) any later version.
;;
;; This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
;; License for more details.
;;
You should have received a copy of the GNU Lesser General Public License
;; along with this program. If not, see </>.
(require plot/no-gui
plot/utils
racket/contract
racket/list
racket/match
racket/math
"df.rkt"
"exn.rkt"
"statistics.rkt")
;; Return a hash table mapping each sample in the data-frame% DF SERIES to the
;; number of times it appears in the series. If WEIGHT is not #f, this is
used as the weight of the samples ( instead of 1 ) . INITIAL - BUCKETS
determines the hash table that is updated , BUCKET - WIDTH allows grouping the
samples into intervals ( can be less than 1 ) . INCLUDE - ZEROES ? if # f will
;; cause values that are equal to 0 to be discarded.
(define (samples->buckets df series
#:start start
#:stop stop
#:weight-series (weight #f)
#:initial-buckets [initial-buckets (make-hash)]
#:bucket-width [bucket-width 1]
#:include-zeroes? [include-zeroes? #t])
;; NOTE: using `exact-truncate' instead of `exact-round' works more
;; correctly for distributing values into buckets for zones. The bucket
;; value is the start of the interval (as opposed to the middle of the
;; interval if `exact-round` would be used.
(define (val->bucket v)
;; NOTE: has to work for non real values (e.g. strings!)
(if (real? v) (exact-truncate (/ v bucket-width)) v))
(define (weighted-binning buckets prev-val val)
(when prev-val
(match-define (list pws pv) prev-val)
(match-define (list ws v) val)
(when (and pws pv ws v)
(let* ([dx (- ws pws)]
[dy (/ (+ v pv) 2)]
[bucket (val->bucket dy)])
(when (or (not (number? bucket))
(not (zero? bucket))
include-zeroes?)
(let ([pval (hash-ref buckets bucket 0)])
(hash-set! buckets bucket (+ dx pval)))))))
buckets)
(define (unweighted-binning buckets val)
(match-define (list v) val)
(when v
(let ([bucket (val->bucket v)])
(when (or (not (number? bucket))
(not (zero? bucket))
include-zeroes?)
(let ([pval (hash-ref buckets bucket 0)])
(hash-set! buckets bucket (+ 1 pval))))))
buckets)
(df-fold
df
(if weight (list weight series) (list series))
initial-buckets
(if weight weighted-binning unweighted-binning)
#:start start #:stop stop))
;; Create a histogram from BUCKETS (a hash table mapping sample value to its
;; rank), as produced by `samples->buckets`. A histogram is a vector where
each value is a vector of sample and rank . Entries will be created for
;; missing sample value (with 0 rank), so the vector contains all possible
sample values . BUCKET - WIDTH is the width of the sample slot ( should be the
;; same value as passed to `samples->buckets`. When AS-PERCENTAGE? is #t, the
;; ranks are converted to a percentage of the total.
(define (buckets->histogram buckets
#:bucket-width (bucket-width 1)
#:as-percentage? (as-percentage? #f))
(define total (for/sum ([v (in-hash-values buckets)]) v))
(define unsorted (hash-keys buckets))
(define real-keys? #f)
;; Try to sort the keys, if we can (we know how to sort reals and strings
;; only)
(define keys
(cond ((for/and ([k (in-list unsorted)]) (real? k))
(set! real-keys? #t)
(sort unsorted <))
((for/and ([k (in-list unsorted)]) (string? k))
(sort unsorted string<?))
(#t
unsorted)))
(define (bucket->val b)
do n't touch b , if the bucket - width is 1 , this allows working with
;; non-number bucket keys.
(if (eqv? bucket-width 1) b (* b bucket-width)))
(if (> (length keys) 0)
;; If the keys are all real numbers, we create the histogram with empty
;; slots in it as well (this looks nicer when plotted.
(if real-keys?
(let ([min (first keys)]
[max (last keys)])
(for/vector #:length (add1 (- max min))
([bucket (in-range min (add1 max))])
(vector (bucket->val bucket)
(let ((val (hash-ref buckets bucket 0)))
(if (and as-percentage? (> total 0))
(* 100 (/ val total))
val)))))
(for/vector #:length (length keys)
([bucket (in-list keys)])
(vector bucket
(let ((val (hash-ref buckets bucket 0)))
(if (and as-percentage? (> total 0))
(* 100 (/ val total))
val)))))
#f))
Drop buckets from boths ends of HISTOGRAM which have elements less than
PERCENT of the total . We stop at the first bucket which has more than
;; PERCENT elements. Note that empty buckets in the middle are still kept.
;; This is used to make the histogram look nicer on a graph.
(define (trim-histogram-outliers histogram [percent 0.001])
(define total (for/sum ([b histogram]) (vector-ref b 1)))
(define min (for/first ([b histogram]
[index (vector-length histogram)]
#:when (> (/ (vector-ref b 1) total) percent))
index))
(define max (for/last ([b histogram]
[index (vector-length histogram)]
#:when (> (/ (vector-ref b 1) total) percent))
index))
(if (and min max)
(for/vector ([index (in-range min (add1 max))])
(vector-ref histogram index))
histogram))
Create a histogram of the data frame DF SERIES . A histogram is a vector of
;; values, each value is a (Vectorof SAMPLE-SLOT RANK).
;;
;; #:weight-series specifies the series to be used for weighting the samples
;; (by default it it uses the weight property stored in the data-frame). Use
# f for no weighting ( each sample will have a weight of 1 in that case ) .
;;
;; #:bucket-width specifies the width of each histogram slot. Samples are
grouped into slots ( can be less than 0.1 )
;;
;; #:trim-outliers specifies to remove slots from both ends of the histogram
;; that contain less than the specified percentage of values.
;;
# : include - zeroes ? specifies whether samples with a slot of 0 are included
;; in the histogram or not.
;;
;; #:as-percentage? determines if the data in the histogram represents a
percentage ( adding up to 100 ) or it is the rank of each slot .
;;
;; In the resulting histogram, samples that are numbers or strings will be
;; sorted. In addition, if the samples are numbers, empty slots will be
;; created so that the buckets are also consecutive.
;;
(define (df-histogram df series
#:start (start 0)
#:stop (stop (df-row-count df))
#:weight-series [weight (df-get-default-weight-series df)]
#:bucket-width [bwidth 1]
#:trim-outliers [trim #f]
#:include-zeroes? [zeroes? #t]
#:as-percentage? [as-pct? #f])
(if (and (df-contains? df series)
(or (not weight) (df-contains? df weight)))
(let ()
(define buckets
(samples->buckets df series
#:start start
#:stop stop
#:weight-series weight
#:bucket-width bwidth
#:include-zeroes? zeroes?))
(define histogram (buckets->histogram buckets
#:bucket-width bwidth
#:as-percentage? as-pct?))
(if (and trim histogram)
(trim-histogram-outliers histogram trim)
histogram))
#f))
Put an empty label every NTH item in DATA ( a histogram / c ) ( which is a
;; histogram data to be plotted). The function tries to find a suitable
anchor , so that the labels look nice ( for example , if every second label is
;; to be dropped, the labels with even values will be kept).
(define (blank-nth data nth)
(define anchor
(or (for/or (((item index) (in-indexed (in-vector data))))
(let ((label (vector-ref item 0)))
(and (integer? label) (zero? (remainder label nth)) index)))
(for/or (((item index) (in-indexed (in-vector data))))
(let ((label (vector-ref item 0)))
(and (integer? label) index)))
0))
(for/vector #:length (vector-length data)
(((data index) (in-indexed (in-vector data))))
(match-define (vector label value) data)
(vector (if (= 0 (remainder (- index anchor) nth)) label "") value)))
;; Empty some labels in DATA (a histogram/c), which is to be plotted as a
;; histogram. The number of blanked labels depends on how many items are in
;; the data set.
(define (blank-some-labels data)
(define nitems (vector-length data))
(cond ((< nitems 25) data) ; no simplification needed
((< nitems 50) (blank-nth data 2))
((< nitems 100) (blank-nth data 5))
((< nitems 200) (blank-nth data 10))
((< nitems 400) (blank-nth data 20))
((< nitems 800) (blank-nth data 50))
(#t (blank-nth data 100))))
Format the bucket values by calling function on them . This is used for
example to convert a pace value like 300 sec / min into 5:00 ( min / km )
(define (format-values fmt data)
(for/vector #:length (vector-length data)
((item (in-vector data)))
(match-define (vector label value) item)
(vector (if (number? label) (fmt label) label) value)))
Create a histogram plot renderer from DATA ( a sequence of [ BUCKET
NUM - SAMPLES ] ) , as received from ` df - histogram ` ( which see ) .
;;
;; #:color determines the color of the plot.
;;
# : skip and # :x - min are used to plot dual histograms ,
;;
;; #:label prints the label of the plot.
;;
;; All the above arguments are sent directly to the `discrete-histogram' call,
;; which see
;;
;; #:blank-some-labels, controls if some of the labels are blanked out if the
;; plot contains too many values (see `blank-some-labels`)
;;
# :x - value - formatter which controls how the histogram values are displayed
;; (see `format-values`)
(define (histogram-renderer data
#:color [color #f]
#:alpha [alpha 0.8]
#:skip [skip (discrete-histogram-skip)]
#:x-min [x-min 0]
#:label [label #f]
#:x-value-formatter [xfmt #f]
#:blank-some-labels [blank? #t])
(let ((kwd '())
(val '()))
(define (add-arg k v) (set! kwd (cons k kwd)) (set! val (cons v val)))
(let ((max-val #f))
Determine the value in the plot
(for ((d (in-vector data)))
(let ((v (vector-ref d 1)))
(when (or (not max-val) (> v max-val))
(set! max-val v))))
Make the value of the plot larger , so the top value does not
;; reach the top of the plot area.
(add-arg '#:y-max (* max-val 1.1)))
(add-arg '#:x-min x-min)
(add-arg '#:skip skip)
(add-arg '#:line-width 1.5)
(when color
(add-arg '#:line-color color))
(add-arg '#:label label)
(add-arg '#:gap 0.15)
(when color
(add-arg '#:color color)
(add-arg '#:alpha alpha))
Blank some of the labels , and format the remaining ones .
(define bdata (if blank? (blank-some-labels data) data))
(define fdata (if xfmt (format-values xfmt bdata) bdata))
(keyword-apply discrete-histogram kwd val fdata '())))
;; Return a list of the buckets in a histogram (as made by `df-histogram`).
(define (get-histogram-buckets h)
(for/list ([e (in-vector h)])
(vector-ref e 0)))
;; Merge two sorted lists.
(define (merge-lists l1 l2)
(let loop ((l1 l1)
(l2 l2)
(result '()))
(cond ((null? l1) (append (reverse result) l2))
((null? l2) (append (reverse result) l1))
((= (car l1) (car l2)) (loop (cdr l1) (cdr l2) (cons (car l1) result)))
((< (car l1) (car l2)) (loop (cdr l1) l2 (cons (car l1) result)))
(#t (loop l1 (cdr l2) (cons (car l2) result))))))
Ensure that HISTOGRAM has all buckets in ( a sorted list ) . This is
;; done by adding buckets with 0 elements if needed. This is used when
histograms for two data series need to be displayed on a single plot .
(define (normalize-histogram histogram buckets)
(for/vector #:length (length buckets) ([b (in-list buckets)])
(or (for/first ([h (in-vector histogram)] #:when (eqv? b (vector-ref h 0))) h)
(vector b 0))))
Combine two histograms H1 , H2 into a single one . The combined histogram is
in the format ( vectorof ( vector slot ) )
(define (combine-histograms h1 h2)
(let* ((nbuckets (merge-lists (get-histogram-buckets h1) (get-histogram-buckets h2)))
(n1 (normalize-histogram h1 nbuckets))
(n2 (normalize-histogram h2 nbuckets)))
(unless (= (vector-length n1) (vector-length n2))
(df-raise "combine-histograms: bad length"))
(for/vector #:length (vector-length n1)
([e1 (in-vector n1)]
[e2 (in-vector n2)])
(unless (equal? (vector-ref e1 0) (vector-ref e2 0))
(df-raise "combine-histograms: bad value"))
(vector (vector-ref e1 0) (vector-ref e1 1) (vector-ref e2 1)))))
Create a plot renderer with two histograms .
(define (histogram-renderer/dual combined-histogram
label1 label2
#:x-value-formatter [xfmt #f]
#:color1 [color1 #f]
#:color2 [color2 #f]
#:alpha [alpha 0.8])
(define data1 (make-vector (vector-length combined-histogram) #f))
(define data2 (make-vector (vector-length combined-histogram) #f))
(for ([(e index) (in-indexed (in-vector combined-histogram))])
(vector-set! data1 index (vector (vector-ref e 0) (vector-ref e 1)))
(vector-set! data2 index (vector (vector-ref e 0) (vector-ref e 2))))
(list
(histogram-renderer
data1
#:color color1 #:alpha alpha
#:skip 2.5 #:x-min 0 #:label label1 #:x-value-formatter xfmt)
(histogram-renderer
data2
#:color color2 #:alpha alpha
#:skip 2.5 #:x-min 1 #:label label2 #:x-value-formatter xfmt)))
Split the histogram HIST into sub - histograms using FACTOR - FN ( which maps
;; the histogram value to a symbol). Returns a list of (cons TAG SUB-HIST).
;; The items in sub-histograms are kept in order with only adjacent values
;; being collapsed together under the same tag, so the same tag can appear
;; multiple times in the list (for an example of this, see splitting a
;; left-right-balance histogram)
;;
WARNING : ` blank - some - labels ' will also be called on the HIST data
(define (factor-histogram hist factor-fn)
(define result '())
(define tag #f)
(define batch '())
;; We need to find out which labels are to be blanked out before we split
;; them. Also we cannot use the blanked data itself, as we would not be
;; able to classify items that have been blanked out.
(define blanked (blank-some-labels hist))
(for ((item hist) (blanked-item blanked))
(match-define (vector val rank) item)
(let ((factor (factor-fn val)))
(unless (eq? tag factor)
(when tag
(set! result (cons (cons tag (list->vector (reverse batch))) result)))
(set! tag factor)
(set! batch '())))
(set! batch (cons blanked-item batch)))
(when tag ; last one
(set! result (cons (cons tag (list->vector (reverse batch))) result)))
(reverse result))
;; Create a plot rendered where DATA (a histogram) is split into sections by
FACTOR - FN and each section is colored according to FACTOR - COLORS
(define (histogram-renderer/factors data factor-fn factor-colors
#:alpha [alpha 0.8]
#:x-value-formatter [xfmt #f])
(define factored-data (factor-histogram data factor-fn))
(define x 0)
(for/list ((factor (in-list factored-data)))
(match-define (cons ftag fdata) factor)
(define color (cdr (assq ftag factor-colors)))
(begin0
(histogram-renderer fdata
#:color color
#:alpha alpha
#:x-min x
#:x-value-formatter xfmt
#:blank-some-labels #f ; we already blanked them
)
(set! x (+ x (vector-length fdata))))))
;;................................................. contract definitions ....
(define histogram/c (vectorof (vector/c (or/c real? string?) real?)))
(define combined-histogram/c (vectorof (vector/c (or/c real? string?) real? real?)))
;;............................................................. provides ....
(provide histogram/c combined-histogram/c)
(provide/contract
(df-histogram (->* (data-frame? string?)
(#:start index/c
#:stop index/c
#:weight-series (or/c #f string?)
#:bucket-width real?
#:trim-outliers (or/c #f (between/c 0 1))
#:include-zeroes? boolean?
#:as-percentage? boolean?)
(or/c #f histogram/c)))
(trim-histogram-outliers (->* (histogram/c) (real?) histogram/c))
(combine-histograms (-> histogram/c histogram/c combined-histogram/c))
(histogram-renderer (->* (histogram/c)
(#:color any/c
#:alpha (between/c 0 1)
#:skip real?
#:x-min real?
#:label (or/c #f string?)
#:blank-some-labels boolean?
#:x-value-formatter (or/c #f (-> number? string?)))
(treeof renderer2d?)))
(histogram-renderer/dual (->* (combined-histogram/c string? string?)
(#:color1 any/c
#:color2 any/c
#:alpha (between/c 0 1)
#:x-value-formatter (or/c #f (-> number? string?)))
(treeof renderer2d?)))
(histogram-renderer/factors (->* (histogram/c
(-> real? symbol?) ; factor function
(listof (cons/c symbol? color/c)))
(#:alpha (between/c 0 1)
#:x-value-formatter (or/c #f (-> number? string?)))
(treeof renderer2d?))))
| null | https://raw.githubusercontent.com/alex-hhh/data-frame/70e6e274e3c207ca22eeefda00f3af9f30c8282a/private/histogram.rkt | racket | histogram.rkt -- histograms and histogram plots for data frames
This file is part of data-frame -- -hhh/data-frame
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
option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
along with this program. If not, see </>.
Return a hash table mapping each sample in the data-frame% DF SERIES to the
number of times it appears in the series. If WEIGHT is not #f, this is
cause values that are equal to 0 to be discarded.
NOTE: using `exact-truncate' instead of `exact-round' works more
correctly for distributing values into buckets for zones. The bucket
value is the start of the interval (as opposed to the middle of the
interval if `exact-round` would be used.
NOTE: has to work for non real values (e.g. strings!)
Create a histogram from BUCKETS (a hash table mapping sample value to its
rank), as produced by `samples->buckets`. A histogram is a vector where
missing sample value (with 0 rank), so the vector contains all possible
same value as passed to `samples->buckets`. When AS-PERCENTAGE? is #t, the
ranks are converted to a percentage of the total.
Try to sort the keys, if we can (we know how to sort reals and strings
only)
non-number bucket keys.
If the keys are all real numbers, we create the histogram with empty
slots in it as well (this looks nicer when plotted.
PERCENT elements. Note that empty buckets in the middle are still kept.
This is used to make the histogram look nicer on a graph.
values, each value is a (Vectorof SAMPLE-SLOT RANK).
#:weight-series specifies the series to be used for weighting the samples
(by default it it uses the weight property stored in the data-frame). Use
#:bucket-width specifies the width of each histogram slot. Samples are
#:trim-outliers specifies to remove slots from both ends of the histogram
that contain less than the specified percentage of values.
in the histogram or not.
#:as-percentage? determines if the data in the histogram represents a
In the resulting histogram, samples that are numbers or strings will be
sorted. In addition, if the samples are numbers, empty slots will be
created so that the buckets are also consecutive.
histogram data to be plotted). The function tries to find a suitable
to be dropped, the labels with even values will be kept).
Empty some labels in DATA (a histogram/c), which is to be plotted as a
histogram. The number of blanked labels depends on how many items are in
the data set.
no simplification needed
#:color determines the color of the plot.
#:label prints the label of the plot.
All the above arguments are sent directly to the `discrete-histogram' call,
which see
#:blank-some-labels, controls if some of the labels are blanked out if the
plot contains too many values (see `blank-some-labels`)
(see `format-values`)
reach the top of the plot area.
Return a list of the buckets in a histogram (as made by `df-histogram`).
Merge two sorted lists.
done by adding buckets with 0 elements if needed. This is used when
the histogram value to a symbol). Returns a list of (cons TAG SUB-HIST).
The items in sub-histograms are kept in order with only adjacent values
being collapsed together under the same tag, so the same tag can appear
multiple times in the list (for an example of this, see splitting a
left-right-balance histogram)
We need to find out which labels are to be blanked out before we split
them. Also we cannot use the blanked data itself, as we would not be
able to classify items that have been blanked out.
last one
Create a plot rendered where DATA (a histogram) is split into sections by
we already blanked them
................................................. contract definitions ....
............................................................. provides ....
factor function | #lang racket/base
Copyright ( c ) 2018 < >
the Free Software Foundation , either version 3 of the License , or ( at your
You should have received a copy of the GNU Lesser General Public License
(require plot/no-gui
plot/utils
racket/contract
racket/list
racket/match
racket/math
"df.rkt"
"exn.rkt"
"statistics.rkt")
used as the weight of the samples ( instead of 1 ) . INITIAL - BUCKETS
determines the hash table that is updated , BUCKET - WIDTH allows grouping the
samples into intervals ( can be less than 1 ) . INCLUDE - ZEROES ? if # f will
(define (samples->buckets df series
#:start start
#:stop stop
#:weight-series (weight #f)
#:initial-buckets [initial-buckets (make-hash)]
#:bucket-width [bucket-width 1]
#:include-zeroes? [include-zeroes? #t])
(define (val->bucket v)
(if (real? v) (exact-truncate (/ v bucket-width)) v))
(define (weighted-binning buckets prev-val val)
(when prev-val
(match-define (list pws pv) prev-val)
(match-define (list ws v) val)
(when (and pws pv ws v)
(let* ([dx (- ws pws)]
[dy (/ (+ v pv) 2)]
[bucket (val->bucket dy)])
(when (or (not (number? bucket))
(not (zero? bucket))
include-zeroes?)
(let ([pval (hash-ref buckets bucket 0)])
(hash-set! buckets bucket (+ dx pval)))))))
buckets)
(define (unweighted-binning buckets val)
(match-define (list v) val)
(when v
(let ([bucket (val->bucket v)])
(when (or (not (number? bucket))
(not (zero? bucket))
include-zeroes?)
(let ([pval (hash-ref buckets bucket 0)])
(hash-set! buckets bucket (+ 1 pval))))))
buckets)
(df-fold
df
(if weight (list weight series) (list series))
initial-buckets
(if weight weighted-binning unweighted-binning)
#:start start #:stop stop))
each value is a vector of sample and rank . Entries will be created for
sample values . BUCKET - WIDTH is the width of the sample slot ( should be the
(define (buckets->histogram buckets
#:bucket-width (bucket-width 1)
#:as-percentage? (as-percentage? #f))
(define total (for/sum ([v (in-hash-values buckets)]) v))
(define unsorted (hash-keys buckets))
(define real-keys? #f)
(define keys
(cond ((for/and ([k (in-list unsorted)]) (real? k))
(set! real-keys? #t)
(sort unsorted <))
((for/and ([k (in-list unsorted)]) (string? k))
(sort unsorted string<?))
(#t
unsorted)))
(define (bucket->val b)
do n't touch b , if the bucket - width is 1 , this allows working with
(if (eqv? bucket-width 1) b (* b bucket-width)))
(if (> (length keys) 0)
(if real-keys?
(let ([min (first keys)]
[max (last keys)])
(for/vector #:length (add1 (- max min))
([bucket (in-range min (add1 max))])
(vector (bucket->val bucket)
(let ((val (hash-ref buckets bucket 0)))
(if (and as-percentage? (> total 0))
(* 100 (/ val total))
val)))))
(for/vector #:length (length keys)
([bucket (in-list keys)])
(vector bucket
(let ((val (hash-ref buckets bucket 0)))
(if (and as-percentage? (> total 0))
(* 100 (/ val total))
val)))))
#f))
Drop buckets from boths ends of HISTOGRAM which have elements less than
PERCENT of the total . We stop at the first bucket which has more than
(define (trim-histogram-outliers histogram [percent 0.001])
(define total (for/sum ([b histogram]) (vector-ref b 1)))
(define min (for/first ([b histogram]
[index (vector-length histogram)]
#:when (> (/ (vector-ref b 1) total) percent))
index))
(define max (for/last ([b histogram]
[index (vector-length histogram)]
#:when (> (/ (vector-ref b 1) total) percent))
index))
(if (and min max)
(for/vector ([index (in-range min (add1 max))])
(vector-ref histogram index))
histogram))
Create a histogram of the data frame DF SERIES . A histogram is a vector of
# f for no weighting ( each sample will have a weight of 1 in that case ) .
grouped into slots ( can be less than 0.1 )
# : include - zeroes ? specifies whether samples with a slot of 0 are included
percentage ( adding up to 100 ) or it is the rank of each slot .
(define (df-histogram df series
#:start (start 0)
#:stop (stop (df-row-count df))
#:weight-series [weight (df-get-default-weight-series df)]
#:bucket-width [bwidth 1]
#:trim-outliers [trim #f]
#:include-zeroes? [zeroes? #t]
#:as-percentage? [as-pct? #f])
(if (and (df-contains? df series)
(or (not weight) (df-contains? df weight)))
(let ()
(define buckets
(samples->buckets df series
#:start start
#:stop stop
#:weight-series weight
#:bucket-width bwidth
#:include-zeroes? zeroes?))
(define histogram (buckets->histogram buckets
#:bucket-width bwidth
#:as-percentage? as-pct?))
(if (and trim histogram)
(trim-histogram-outliers histogram trim)
histogram))
#f))
Put an empty label every NTH item in DATA ( a histogram / c ) ( which is a
anchor , so that the labels look nice ( for example , if every second label is
(define (blank-nth data nth)
(define anchor
(or (for/or (((item index) (in-indexed (in-vector data))))
(let ((label (vector-ref item 0)))
(and (integer? label) (zero? (remainder label nth)) index)))
(for/or (((item index) (in-indexed (in-vector data))))
(let ((label (vector-ref item 0)))
(and (integer? label) index)))
0))
(for/vector #:length (vector-length data)
(((data index) (in-indexed (in-vector data))))
(match-define (vector label value) data)
(vector (if (= 0 (remainder (- index anchor) nth)) label "") value)))
(define (blank-some-labels data)
(define nitems (vector-length data))
((< nitems 50) (blank-nth data 2))
((< nitems 100) (blank-nth data 5))
((< nitems 200) (blank-nth data 10))
((< nitems 400) (blank-nth data 20))
((< nitems 800) (blank-nth data 50))
(#t (blank-nth data 100))))
Format the bucket values by calling function on them . This is used for
example to convert a pace value like 300 sec / min into 5:00 ( min / km )
(define (format-values fmt data)
(for/vector #:length (vector-length data)
((item (in-vector data)))
(match-define (vector label value) item)
(vector (if (number? label) (fmt label) label) value)))
Create a histogram plot renderer from DATA ( a sequence of [ BUCKET
NUM - SAMPLES ] ) , as received from ` df - histogram ` ( which see ) .
# : skip and # :x - min are used to plot dual histograms ,
# :x - value - formatter which controls how the histogram values are displayed
(define (histogram-renderer data
#:color [color #f]
#:alpha [alpha 0.8]
#:skip [skip (discrete-histogram-skip)]
#:x-min [x-min 0]
#:label [label #f]
#:x-value-formatter [xfmt #f]
#:blank-some-labels [blank? #t])
(let ((kwd '())
(val '()))
(define (add-arg k v) (set! kwd (cons k kwd)) (set! val (cons v val)))
(let ((max-val #f))
Determine the value in the plot
(for ((d (in-vector data)))
(let ((v (vector-ref d 1)))
(when (or (not max-val) (> v max-val))
(set! max-val v))))
Make the value of the plot larger , so the top value does not
(add-arg '#:y-max (* max-val 1.1)))
(add-arg '#:x-min x-min)
(add-arg '#:skip skip)
(add-arg '#:line-width 1.5)
(when color
(add-arg '#:line-color color))
(add-arg '#:label label)
(add-arg '#:gap 0.15)
(when color
(add-arg '#:color color)
(add-arg '#:alpha alpha))
Blank some of the labels , and format the remaining ones .
(define bdata (if blank? (blank-some-labels data) data))
(define fdata (if xfmt (format-values xfmt bdata) bdata))
(keyword-apply discrete-histogram kwd val fdata '())))
(define (get-histogram-buckets h)
(for/list ([e (in-vector h)])
(vector-ref e 0)))
(define (merge-lists l1 l2)
(let loop ((l1 l1)
(l2 l2)
(result '()))
(cond ((null? l1) (append (reverse result) l2))
((null? l2) (append (reverse result) l1))
((= (car l1) (car l2)) (loop (cdr l1) (cdr l2) (cons (car l1) result)))
((< (car l1) (car l2)) (loop (cdr l1) l2 (cons (car l1) result)))
(#t (loop l1 (cdr l2) (cons (car l2) result))))))
Ensure that HISTOGRAM has all buckets in ( a sorted list ) . This is
histograms for two data series need to be displayed on a single plot .
(define (normalize-histogram histogram buckets)
(for/vector #:length (length buckets) ([b (in-list buckets)])
(or (for/first ([h (in-vector histogram)] #:when (eqv? b (vector-ref h 0))) h)
(vector b 0))))
Combine two histograms H1 , H2 into a single one . The combined histogram is
in the format ( vectorof ( vector slot ) )
(define (combine-histograms h1 h2)
(let* ((nbuckets (merge-lists (get-histogram-buckets h1) (get-histogram-buckets h2)))
(n1 (normalize-histogram h1 nbuckets))
(n2 (normalize-histogram h2 nbuckets)))
(unless (= (vector-length n1) (vector-length n2))
(df-raise "combine-histograms: bad length"))
(for/vector #:length (vector-length n1)
([e1 (in-vector n1)]
[e2 (in-vector n2)])
(unless (equal? (vector-ref e1 0) (vector-ref e2 0))
(df-raise "combine-histograms: bad value"))
(vector (vector-ref e1 0) (vector-ref e1 1) (vector-ref e2 1)))))
Create a plot renderer with two histograms .
(define (histogram-renderer/dual combined-histogram
label1 label2
#:x-value-formatter [xfmt #f]
#:color1 [color1 #f]
#:color2 [color2 #f]
#:alpha [alpha 0.8])
(define data1 (make-vector (vector-length combined-histogram) #f))
(define data2 (make-vector (vector-length combined-histogram) #f))
(for ([(e index) (in-indexed (in-vector combined-histogram))])
(vector-set! data1 index (vector (vector-ref e 0) (vector-ref e 1)))
(vector-set! data2 index (vector (vector-ref e 0) (vector-ref e 2))))
(list
(histogram-renderer
data1
#:color color1 #:alpha alpha
#:skip 2.5 #:x-min 0 #:label label1 #:x-value-formatter xfmt)
(histogram-renderer
data2
#:color color2 #:alpha alpha
#:skip 2.5 #:x-min 1 #:label label2 #:x-value-formatter xfmt)))
Split the histogram HIST into sub - histograms using FACTOR - FN ( which maps
WARNING : ` blank - some - labels ' will also be called on the HIST data
(define (factor-histogram hist factor-fn)
(define result '())
(define tag #f)
(define batch '())
(define blanked (blank-some-labels hist))
(for ((item hist) (blanked-item blanked))
(match-define (vector val rank) item)
(let ((factor (factor-fn val)))
(unless (eq? tag factor)
(when tag
(set! result (cons (cons tag (list->vector (reverse batch))) result)))
(set! tag factor)
(set! batch '())))
(set! batch (cons blanked-item batch)))
(set! result (cons (cons tag (list->vector (reverse batch))) result)))
(reverse result))
FACTOR - FN and each section is colored according to FACTOR - COLORS
(define (histogram-renderer/factors data factor-fn factor-colors
#:alpha [alpha 0.8]
#:x-value-formatter [xfmt #f])
(define factored-data (factor-histogram data factor-fn))
(define x 0)
(for/list ((factor (in-list factored-data)))
(match-define (cons ftag fdata) factor)
(define color (cdr (assq ftag factor-colors)))
(begin0
(histogram-renderer fdata
#:color color
#:alpha alpha
#:x-min x
#:x-value-formatter xfmt
)
(set! x (+ x (vector-length fdata))))))
(define histogram/c (vectorof (vector/c (or/c real? string?) real?)))
(define combined-histogram/c (vectorof (vector/c (or/c real? string?) real? real?)))
(provide histogram/c combined-histogram/c)
(provide/contract
(df-histogram (->* (data-frame? string?)
(#:start index/c
#:stop index/c
#:weight-series (or/c #f string?)
#:bucket-width real?
#:trim-outliers (or/c #f (between/c 0 1))
#:include-zeroes? boolean?
#:as-percentage? boolean?)
(or/c #f histogram/c)))
(trim-histogram-outliers (->* (histogram/c) (real?) histogram/c))
(combine-histograms (-> histogram/c histogram/c combined-histogram/c))
(histogram-renderer (->* (histogram/c)
(#:color any/c
#:alpha (between/c 0 1)
#:skip real?
#:x-min real?
#:label (or/c #f string?)
#:blank-some-labels boolean?
#:x-value-formatter (or/c #f (-> number? string?)))
(treeof renderer2d?)))
(histogram-renderer/dual (->* (combined-histogram/c string? string?)
(#:color1 any/c
#:color2 any/c
#:alpha (between/c 0 1)
#:x-value-formatter (or/c #f (-> number? string?)))
(treeof renderer2d?)))
(histogram-renderer/factors (->* (histogram/c
(listof (cons/c symbol? color/c)))
(#:alpha (between/c 0 1)
#:x-value-formatter (or/c #f (-> number? string?)))
(treeof renderer2d?))))
|
c8d4fb0f078bc7ed00efc2b360ad744b3d2933e6c59cc87bf514f359ccd31e40 | skrah/minicaml | test12.ml | Example from 's " Modern Compiler Implementation in ML " , translated
to .
to Caml. *)
let _ =
let a = ref 0
in for i = 0 to 100 do
a := !a + 1; ()
done
| null | https://raw.githubusercontent.com/skrah/minicaml/e5f5cad7fdbcfc11561f717042fae73fa743823f/test/test12.ml | ocaml | Example from 's " Modern Compiler Implementation in ML " , translated
to .
to Caml. *)
let _ =
let a = ref 0
in for i = 0 to 100 do
a := !a + 1; ()
done
| |
afd8320a5c418226358e9e79bd9d6e0db312638c838ac562f3f259505b338c0b | peterholko/pax_server | army.erl | Author :
Created : Feb 4 , 2009
%% Description: TODO: Add description to army
-module(army).
-behaviour(gen_server).
%%
%% Include files
%%
-include("game.hrl").
-include("common.hrl").
-include("schema.hrl").
-include_lib("stdlib/include/qlc.hrl").
%%
%% Exported Functions
%%
-export([move/3, attack/2, claim/2, battle_get_info/1, destroyed/1,
unit_transfered/1, combat/2, get_state/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([start/2, stop/1]).
-record(module_data, {army,
player_id,
self,
visible = [],
observed_by = []}).
%%
%% API Functions
%%
move(ArmyId, DestX, DestY) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_MOVE', DestX, DestY}).
attack(ArmyId, TargetId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_ATTACK', TargetId}).
claim(ArmyId, ClaimId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_CLAIM', ClaimId}).
destroyed(ArmyId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_DEAD'}).
unit_transfered(ArmyId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'UNIT_TRANSFERED'}).
combat(ArmyId, BattleId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_COMBAT', BattleId}).
get_state(ArmyId) ->
gen_server:call(global:whereis_name({army, ArmyId}), {'GET_STATE', ArmyId}).
battle_get_info(ArmyId) ->
gen_server:call(global:whereis_name({army, ArmyId}), {'BATTLE_GET_INFO'}).
start(ArmyId, PlayerId) ->
case db:read(army, ArmyId) of
[Army] ->
gen_server:start({global, {army, ArmyId}}, army, [Army, PlayerId], []);
Any ->
{error, Any}
end.
init([Army, PlayerId])
when is_tuple(Army),
is_integer(PlayerId) ->
process_flag(trap_exit, true),
log4erl:debug("{~w} army_id: ~w player_id: ~w", [?MODULE, Army#army.id, PlayerId]),
{ok, #module_data{army = Army, player_id = PlayerId, self = self()}}.
terminate(_Reason, _) ->
ok.
stop(ProcessId)
when is_pid(ProcessId) ->
gen_server:cast(ProcessId, stop).
handle_cast({'SET_STATE_MOVE', DestX, DestY}, Data) ->
log4erl:info("{~w} SET_STATE_MOVE", [?MODULE]),
Army = Data#module_data.army,
{NextX, NextY} = next_pos(Army#army.x, Army#army.y, DestX, DestY),
case Army#army.state of
S when S =:= ?STATE_NONE;
S =:= ?STATE_ATTACK;
S =:= ?STATE_MOVE ->
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
add_event_move(Data#module_data.self, ArmySpeed),
NewArmy = state_move(Army, DestX, DestY);
?STATE_CLAIM ->
claim:cancel(Army#army.id),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
add_event_move(Data#module_data.self, ArmySpeed),
NewArmy = state_move(Army, DestX, DestY);
_ ->
%Do nothing
NewArmy = Army
end,
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_ATTACK', TargetId}, Data) ->
log4erl:info("{~w} SET_STATE_ATTACK", [?MODULE]),
Army = Data#module_data.army,
TargetState = gen_server:call(global:whereis_name({army, TargetId}), {'GET_STATE', Army#army.id}),
{NextX, NextY} = next_pos(Army#army.x, Army#army.y, TargetState#state.x, TargetState#state.y),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
case Army#army.state of
S when S =:= ?STATE_NONE;
S =:= ?STATE_ATTACK;
S =:= ?STATE_MOVE ->
add_event_attack(Data#module_data.self, ArmySpeed),
NewArmy = state_attack(Army, TargetId);
?STATE_CLAIM ->
claim:cancel(Army#army.id),
add_event_attack(Data#module_data.self, ArmySpeed),
NewArmy = state_attack(Army, TargetId);
_ ->
%Do nothing
NewArmy = Army
end,
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_RETREAT_MOVE'}, Data) ->
?INFO("SET_STATE_RETREAT_MOVE"),
Army = Data#module_data.army,
?INFO("LastPos: ", Army#army.last_pos),
{LastX, LastY} = Army#army.last_pos,
ArmySpeed = get_army_speed(Army#army.id, LastX, LastY),
if
Army#army.state =:= ?STATE_RETREAT ->
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
gen_server:cast(global:whereis_name(game_pid), {'ADD_EVENT', Data#module_data.self, ?EVENT_RETREAT_MOVE, none, speed_to_ticks(ArmySpeed)});
true ->
ok
end,
NewArmy = state_retreat_move(Data#module_data.army, LastX, LastY),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_LEAVE_MOVE'}, Data) ->
log4erl:info("{~w} SET_STATE_LEAVE_MOVE", [?MODULE]),
Army = Data#module_data.army,
{LastX, LastY} = Army#army.last_pos,
ArmySpeed = get_army_speed(Army#army.id, LastX, LastY),
if
Army#army.state =:= ?STATE_LEAVE ->
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
gen_server:cast(global:whereis_name(game_pid), {'ADD_EVENT', Data#module_data.self, ?EVENT_LEAVE_MOVE, none, speed_to_ticks(ArmySpeed)});
true ->
ok
end,
NewArmy = state_leave_move(Data#module_data.army, LastX, LastY),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_COMBAT', BattleId}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_combat(Army, BattleId),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_RETREAT', BattleId}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_retreat(Army, BattleId),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
VisibleList = Data#module_data.visible,
ObservedByList = Data#module_data.observed_by,
%% Update subscription model
{ok, SubscriptionPid} = subscription:start(Army#army.id),
subscription:update_perception(SubscriptionPid, Army#army.id, self(), Army#army.x, Army#army.y, VisibleList, ObservedByList),
Toggle player 's perception has been updated .
update_perception(Army#army.player_id),
%% Toggle observedByList perception has been updated due to state change.
entity_update_perception(ObservedByList),
{noreply, NewData};
handle_cast({'SET_STATE_LEAVE', BattleId}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_leave(Army, BattleId),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_CLAIM', ClaimId}, Data) ->
?INFO("Set State Claim Id", ClaimId),
Army = Data#module_data.army,
add_event_claim(Data#module_data.self, ClaimId),
NewArmy = state_claim(Army),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_DEAD'}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_dead(Army),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_NONE'}, Data) ->
NewArmy = state_none(Data#module_data.army),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'ADD_WAYPOINT', X, Y}, Data) ->
NewArmy = add_waypoint(Data#module_data.army, X, Y),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'PROCESS_EVENT', _EventTick, EventData, EventType}, Data) ->
?INFO("Processing Event Type", EventType),
Army = Data#module_data.army,
case EventType of
?EVENT_MOVE ->
NewArmy = do_move(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_ATTACK ->
NewArmy = do_attack(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_RETREAT_MOVE ->
battle:remove_army(Army#army.battle, Army#army.id),
NewArmy = do_move(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_LEAVE_MOVE ->
battle:remove_army(Army#army.battle, Army#army.id),
NewArmy = do_move(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_CLAIM ->
ClaimId = EventData,
claim:complete(ClaimId),
NewArmy = state_none(Army);
?EVENT_NONE ->
NewArmy = Army
end,
?INFO("Army: ", NewArmy),
NewData = Data#module_data {army = NewArmy},
save_army(NewData#module_data.army),
{noreply, NewData};
handle_cast({'ADD_VISIBLE', _ArmyId, EntityId, EntityPid}, Data) ->
VisibleList = Data#module_data.visible,
NewVisibleList = [{EntityId, EntityPid} | VisibleList],
NewData = Data#module_data { visible = NewVisibleList },
update_perception(Data#module_data.player_id),
{noreply, NewData};
handle_cast({'REMOVE_VISIBLE', _ArmyId, EntityId, EntityPid}, Data) ->
VisibleList = Data#module_data.visible,
NewVisibleList = lists:delete({EntityId, EntityPid}, VisibleList),
NewData = Data#module_data { visible = NewVisibleList },
update_perception(Data#module_data.player_id),
{noreply, NewData};
handle_cast({'ADD_OBSERVED_BY', _ArmyId, EntityId, EntityPid}, Data) ->
ObservedByList = Data#module_data.observed_by,
NewObservedByList = [{EntityId, EntityPid} | ObservedByList],
NewData = Data#module_data { observed_by = NewObservedByList },
{noreply, NewData};
handle_cast({'REMOVE_OBSERVED_BY', _ArmyId, EntityId, EntityPid}, Data) ->
ObservedByList = Data#module_data.observed_by,
NewObservedByList = lists:delete({EntityId, EntityPid}, ObservedByList),
NewData = Data#module_data { observed_by = NewObservedByList },
{noreply, NewData};
handle_cast({'UNIT_TRANSFERED'}, Data) ->
Army = Data#module_data.army,
Units = unit:get_units(Army#army.id),
NumUnits = length(Units),
case NumUnits > 0 of
true -> State = ?STATE_NONE;
false -> State = ?STATE_EMPTY
end,
NewArmy = Army#army { state = State},
NewData = Data#module_data {army = NewArmy},
{noreply, NewData};
handle_cast(stop, Data) ->
{stop, normal, Data}.
handle_call({'GET_INFO', PlayerId}, _From, Data) ->
Army = Data#module_data.army,
case Army#army.player_id =:= PlayerId of
true ->
UnitsInfoTuple = unit:tuple_form_items(PlayerId, Army#army.id),
ArmyInfo = {detailed,
Army#army.id,
Army#army.name,
UnitsInfoTuple};
false ->
ArmyInfo = {generic,
Army#army.id,
Army#army.player_id,
Army#army.name,
kingdom:get_name(Army#army.player_id)}
end,
io:fwrite("army - ArmyInfo: ~w~n", [ArmyInfo]),
{reply, ArmyInfo , Data};
handle_call({'BATTLE_GET_INFO'}, _From, Data) ->
Army = Data#module_data.army,
UnitsInfoTuple = unit:tuple_form(Army#army.id),
ArmyInfo = {Army#army.id,
Army#army.player_id,
Army#army.name,
kingdom:get_name(Army#army.player_id),
UnitsInfoTuple},
{reply, ArmyInfo, Data};
handle_call({'GET_UNITS'}, _From, Data) ->
Army = Data#module_data.army,
Units = db:dirty_index_read(unit, Army#army.id, #unit.entity_id),
{reply, Units, Data};
handle_call({'GET_UNIT', UnitId}, _From, Data) ->
?INFO("Get Unit"),
Unit = unit:get_unit(UnitId),
{reply, Unit, Data};
handle_call({'GET_STATE', _ArmyId}, _From, Data) ->
Army = Data#module_data.army,
State = #state { id = Army#army.id,
player_id = Army#army.player_id,
type = ?OBJECT_ARMY,
subtype = ?OBJECT_BASIC,
state = Army#army.state,
x = Army#army.x,
y = Army#army.y},
?INFO("State: ", State),
{reply, State, Data};
handle_call({'GET_ID'}, _From, Data) ->
Army = Data#module_data.army,
{reply, Army#army.id, Data};
handle_call({'GET_PLAYER_ID'}, _From, Data) ->
{reply, Data#module_data.player_id, Data};
handle_call({'GET_TYPE', _ArmyId}, _From, Data) ->
{reply, ?OBJECT_ARMY, Data};
handle_call('GET_VISIBLE', _From, Data) ->
{reply, Data#module_data.visible, Data};
handle_call('GET_OBSERVED_BY', _From, Data) ->
{reply, Data#module_data.observed_by, Data};
handle_call('GET_SUBSCRIPTION_DATA', _From, Data) ->
Army = Data#module_data.army,
{reply, {Army#army.x, Army#army.y, Data#module_data.visible, Data#module_data.observed_by}, Data};
handle_call({'ON_SAME_TILE', X, Y}, _From, Data) ->
Army = Data#module_data.army,
{reply, (Army#army.x =:= X) and (Army#army.y =:= Y), Data};
handle_call(Event, From, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event},
{from, From}
]),
{noreply, Data}.
handle_info(Info, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Info}]),
{noreply, Data}.
code_change(_OldVsn, Data, _Extra) ->
{ok, Data}.
%%
%% Local Functions
%%
do_move(Army, ArmyPid, VisibleList, ObservedByList) ->
%% Move army coordinates
io:fwrite("Army#army.dest: ~w~n", [Army#army.dest]),
[{DestX, DestY} | DestRest] = Army#army.dest,
{NewArmyX, NewArmyY} = next_pos(Army#army.x, Army#army.y, DestX, DestY),
%Add a trigger due to move
add_move_trigger(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
%% Set any newly discovered tiles
set_discovered_tiles(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
%% Update subscription model
{ok, SubscriptionPid} = subscription:start(Army#army.id),
subscription:update_perception(SubscriptionPid, Army#army.id, ArmyPid, NewArmyX, NewArmyY, VisibleList, ObservedByList),
Toggle player 's perception has been updated .
update_perception(Army#army.player_id),
%% Toggle observedByList perception has been updated due to army move.
entity_update_perception(ObservedByList),
%% Check if destination has been reached and if destination list is empty
case check_destination(NewArmyX =:= DestX, NewArmyY =:= DestY, length(DestRest)) of
final ->
io:fwrite("Final destination reached.~n"),
NewArmy = state_none(Army, NewArmyX, NewArmyY);
waypoint ->
io:fwrite("Next Waypoint.~n"),
{NextX, NextY} = next_pos(NewArmyX, NewArmyY, DestX, DestY),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
game:add_event(ArmyPid, ?EVENT_MOVE, none, speed_to_ticks(ArmySpeed)),
NewArmy = event_move_next_dest(Army, NewArmyX, NewArmyY, DestRest);
moving ->
io:fwrite("Moving.~n"),
{NextX, NextY} = next_pos(NewArmyX, NewArmyY, DestX, DestY),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
game:add_event(ArmyPid, ?EVENT_MOVE, none, speed_to_ticks(ArmySpeed)),
NewArmy = event_move(Army, NewArmyX, NewArmyY)
end,
NewArmy.
do_attack(Army, ArmyPid, VisibleList, ObservedByList) ->
TargetState = gen_server:call(global:whereis_name({army, Army#army.target}), {'GET_STATE', Army#army.id}),
{NewArmyX, NewArmyY} = next_pos(Army#army.x, Army#army.y, TargetState#state.x, TargetState#state.y),
if
(NewArmyX =:= TargetState#state.x) and (NewArmyY =:= TargetState#state.y) ->
?INFO("Creating battle"),
%FIXME Move counter into battle process
BattleId = counter:increment(battle) + 1000000,
battle:create(BattleId, TargetState#state.x, TargetState#state.y),
battle:setup(BattleId, Army#army.id, Army#army.target),
army:combat(Army#army.target, BattleId),
NewArmy = state_combat_move(Army, BattleId, NewArmyX, NewArmyY);
true ->
{NextX, NextY} = next_pos(NewArmyX, NewArmyY, TargetState#state.x, TargetState#state.y),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
game:add_event(ArmyPid, ?EVENT_ATTACK, none, speed_to_ticks(ArmySpeed)),
NewArmy = event_move(Army, NewArmyX, NewArmyY)
end,
%Add a trigger due to move
add_move_trigger(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
%% Set any newly discovered tiles
set_discovered_tiles(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
%% Update subscription model
{ok, SubscriptionPid} = subscription:start(Army#army.id),
subscription:update_perception(SubscriptionPid, Army#army.id, ArmyPid, NewArmyX, NewArmyY, VisibleList, ObservedByList),
%Toggle player's perception has been updated.
update_perception(Army#army.player_id),
%Toggle observedByList perception has been updated due to army move.
entity_update_perception(ObservedByList),
NewArmy.
next_pos(ArmyX, ArmyY, DestX, DestY) ->
DiffX = DestX - ArmyX,
DiffY = DestY - ArmyY,
if
DiffX > 0 ->
NewArmyX = ArmyX + 1;
DiffX < 0 ->
NewArmyX = ArmyX - 1;
true ->
NewArmyX = ArmyX
end,
if
DiffY > 0 ->
NewArmyY = ArmyY + 1;
DiffY < 0 ->
NewArmyY = ArmyY - 1;
true ->
NewArmyY = ArmyY
end,
{NewArmyX, NewArmyY}.
event_move(Army, NewX, NewY) ->
LastPos = {Army#army.x, Army#army.y},
Army#army{x = NewX,
y = NewY,
last_pos = LastPos}.
event_move_next_dest(Army, NewX, NewY, NextDest) ->
LastPos = {Army#army.x, Army#army.y},
Army#army{x = NewX,
y = NewY,
last_pos = LastPos,
dest = NextDest}.
add_event_move(Pid, ArmySpeed) ->
game:clear_events(Pid),
game:add_event(Pid, ?EVENT_MOVE, none, speed_to_ticks(ArmySpeed)).
add_event_claim(Pid, ClaimId) ->
game:clear_events(Pid),
game:add_event(Pid, ?EVENT_CLAIM, ClaimId, ?CLAIM_TICK).
add_event_attack(Pid, ArmySpeed) ->
game:clear_events(Pid),
game:add_event(Pid, ?EVENT_ATTACK, non, speed_to_ticks(ArmySpeed)).
state_move(Army, DestX, DestY) ->
Army#army{dest = [{DestX, DestY}],
state = ?STATE_MOVE}.
state_attack(Army, TargetId) ->
Army#army{state = ?STATE_ATTACK,
target = TargetId}.
state_retreat(Army, BattleId) ->
Army#army{state = ?STATE_RETREAT,
battle = BattleId}.
state_retreat_move(Army, LastX, LastY) ->
Army#army{dest = [{LastX, LastY}],
state = ?STATE_RETREAT_MOVE}.
state_leave(Army, BattleId) ->
Army#army{state = ?STATE_LEAVE,
battle = BattleId}.
state_leave_move(Army, LastX, LastY) ->
Army#army{dest = [{LastX, LastY}],
state = ?STATE_LEAVE_MOVE}.
state_combat(Army, BattleId) ->
Army#army{state = ?STATE_COMBAT,
battle = BattleId}.
state_combat_move(Army, BattleId, X, Y) ->
LastPos = {Army#army.x, Army#army.y},
Army#army{state = ?STATE_COMBAT,
battle = BattleId,
x = X,
y = Y,
last_pos = LastPos}.
state_dead(Army) ->
Army#army{state = ?STATE_DEAD}.
state_claim(Army) ->
Army#army{state = ?STATE_CLAIM}.
state_none(Army, X, Y) ->
Army#army{state = ?STATE_NONE,
x = X,
y = Y}.
state_none(Army) ->
Army#army{state = ?STATE_NONE}.
get_army_speed(ArmyId, X, Y) ->
ArmySpeed = unit:highest_unit_movement(ArmyId),
TileType = map:get_tile_type(X,Y),
Speed = ArmySpeed * tile_modifier(TileType),
io:fwrite("Speed: ~w~n",[Speed]),
Speed.
speed_to_ticks(Speed) ->
(1000 div ?GAME_LOOP_TICK) * 1.
tile_modifier(?TILE_MOUNTAIN) ->
?TILE_MOUNTAIN_SPEED;
tile_modifier(?TILE_FOREST) ->
?TILE_FOREST_SPEED;
tile_modifier(?TILE_PLAINS) ->
?TILE_PLAINS_SPEED;
tile_modifier(?TILE_SWAMP) ->
?TILE_SWAMP_SPEED;
tile_modifier(_) ->
1.
entity_update_perception(EntityList) ->
F = fun({EntityId, EntityPid}) ->
case gen_server:call(EntityPid, {'GET_TYPE', EntityId}) of
?OBJECT_ARMY ->
check_player_online(EntityPid);
?OBJECT_CITY ->
check_player_online(EntityPid);
_OtherTypes ->
no_update
end
end,
lists:foreach(F, EntityList).
check_player_online(EntityPid) ->
PlayerId = gen_server:call(EntityPid, {'GET_PLAYER_ID'}),
case gen_server:call(global:whereis_name(game_pid), {'IS_PLAYER_ONLINE', PlayerId}) of
true ->
update_perception(PlayerId);
false ->
no_update
end.
update_perception(PlayerId) ->
case player:get_type(PlayerId) of
?PLAYER_HUMAN ->
%Toggle within game state that player's perception has been updated.
gen_server:cast(global:whereis_name(game_pid),{'UPDATE_PERCEPTION', PlayerId});
?PLAYER_COMPUTER ->
no_update
end.
set_discovered_tiles(PlayerId, ArmyId, X, Y) ->
case player:get_type(PlayerId) of
?PLAYER_HUMAN ->
gen_server:cast(global:whereis_name({player, PlayerId}), {'SET_DISCOVERED_TILES', ArmyId, X, Y});
?PLAYER_COMPUTER ->
ok
end.
add_move_trigger(PlayerId, ArmyId, X, Y) ->
%Only add trigger for human players
case player:get_type(PlayerId) of
?PLAYER_HUMAN ->
TriggerData = {ArmyId, X, Y},
trigger:add(?TRIGGER_MOVE, TriggerData);
?PLAYER_COMPUTER ->
no_trigger
end.
check_destination(_X = true, _Y = true, _DestList = 0) ->
final;
check_destination(_X = true, _Y = true, _DestList) ->
waypoint;
check_destination(_X, _Y, _DestList) ->
moving.
add_waypoint(Army, X, Y) ->
NewDest = [{X, Y} | Army#army.dest],
Army#army {dest = NewDest}.
save_army(Army) ->
db:dirty_write(Army).
| null | https://raw.githubusercontent.com/peterholko/pax_server/62b2ec1fae195ff915d19af06e56a7c4567fd4b8/src/army.erl | erlang | Description: TODO: Add description to army
Include files
Exported Functions
API Functions
Do nothing
Do nothing
Update subscription model
Toggle observedByList perception has been updated due to state change.
Local Functions
Move army coordinates
Add a trigger due to move
Set any newly discovered tiles
Update subscription model
Toggle observedByList perception has been updated due to army move.
Check if destination has been reached and if destination list is empty
FIXME Move counter into battle process
Add a trigger due to move
Set any newly discovered tiles
Update subscription model
Toggle player's perception has been updated.
Toggle observedByList perception has been updated due to army move.
Toggle within game state that player's perception has been updated.
Only add trigger for human players | Author :
Created : Feb 4 , 2009
-module(army).
-behaviour(gen_server).
-include("game.hrl").
-include("common.hrl").
-include("schema.hrl").
-include_lib("stdlib/include/qlc.hrl").
-export([move/3, attack/2, claim/2, battle_get_info/1, destroyed/1,
unit_transfered/1, combat/2, get_state/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([start/2, stop/1]).
-record(module_data, {army,
player_id,
self,
visible = [],
observed_by = []}).
move(ArmyId, DestX, DestY) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_MOVE', DestX, DestY}).
attack(ArmyId, TargetId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_ATTACK', TargetId}).
claim(ArmyId, ClaimId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_CLAIM', ClaimId}).
destroyed(ArmyId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_DEAD'}).
unit_transfered(ArmyId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'UNIT_TRANSFERED'}).
combat(ArmyId, BattleId) ->
gen_server:cast(global:whereis_name({army, ArmyId}), {'SET_STATE_COMBAT', BattleId}).
get_state(ArmyId) ->
gen_server:call(global:whereis_name({army, ArmyId}), {'GET_STATE', ArmyId}).
battle_get_info(ArmyId) ->
gen_server:call(global:whereis_name({army, ArmyId}), {'BATTLE_GET_INFO'}).
start(ArmyId, PlayerId) ->
case db:read(army, ArmyId) of
[Army] ->
gen_server:start({global, {army, ArmyId}}, army, [Army, PlayerId], []);
Any ->
{error, Any}
end.
init([Army, PlayerId])
when is_tuple(Army),
is_integer(PlayerId) ->
process_flag(trap_exit, true),
log4erl:debug("{~w} army_id: ~w player_id: ~w", [?MODULE, Army#army.id, PlayerId]),
{ok, #module_data{army = Army, player_id = PlayerId, self = self()}}.
terminate(_Reason, _) ->
ok.
stop(ProcessId)
when is_pid(ProcessId) ->
gen_server:cast(ProcessId, stop).
handle_cast({'SET_STATE_MOVE', DestX, DestY}, Data) ->
log4erl:info("{~w} SET_STATE_MOVE", [?MODULE]),
Army = Data#module_data.army,
{NextX, NextY} = next_pos(Army#army.x, Army#army.y, DestX, DestY),
case Army#army.state of
S when S =:= ?STATE_NONE;
S =:= ?STATE_ATTACK;
S =:= ?STATE_MOVE ->
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
add_event_move(Data#module_data.self, ArmySpeed),
NewArmy = state_move(Army, DestX, DestY);
?STATE_CLAIM ->
claim:cancel(Army#army.id),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
add_event_move(Data#module_data.self, ArmySpeed),
NewArmy = state_move(Army, DestX, DestY);
_ ->
NewArmy = Army
end,
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_ATTACK', TargetId}, Data) ->
log4erl:info("{~w} SET_STATE_ATTACK", [?MODULE]),
Army = Data#module_data.army,
TargetState = gen_server:call(global:whereis_name({army, TargetId}), {'GET_STATE', Army#army.id}),
{NextX, NextY} = next_pos(Army#army.x, Army#army.y, TargetState#state.x, TargetState#state.y),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
case Army#army.state of
S when S =:= ?STATE_NONE;
S =:= ?STATE_ATTACK;
S =:= ?STATE_MOVE ->
add_event_attack(Data#module_data.self, ArmySpeed),
NewArmy = state_attack(Army, TargetId);
?STATE_CLAIM ->
claim:cancel(Army#army.id),
add_event_attack(Data#module_data.self, ArmySpeed),
NewArmy = state_attack(Army, TargetId);
_ ->
NewArmy = Army
end,
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_RETREAT_MOVE'}, Data) ->
?INFO("SET_STATE_RETREAT_MOVE"),
Army = Data#module_data.army,
?INFO("LastPos: ", Army#army.last_pos),
{LastX, LastY} = Army#army.last_pos,
ArmySpeed = get_army_speed(Army#army.id, LastX, LastY),
if
Army#army.state =:= ?STATE_RETREAT ->
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
gen_server:cast(global:whereis_name(game_pid), {'ADD_EVENT', Data#module_data.self, ?EVENT_RETREAT_MOVE, none, speed_to_ticks(ArmySpeed)});
true ->
ok
end,
NewArmy = state_retreat_move(Data#module_data.army, LastX, LastY),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_LEAVE_MOVE'}, Data) ->
log4erl:info("{~w} SET_STATE_LEAVE_MOVE", [?MODULE]),
Army = Data#module_data.army,
{LastX, LastY} = Army#army.last_pos,
ArmySpeed = get_army_speed(Army#army.id, LastX, LastY),
if
Army#army.state =:= ?STATE_LEAVE ->
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
gen_server:cast(global:whereis_name(game_pid), {'ADD_EVENT', Data#module_data.self, ?EVENT_LEAVE_MOVE, none, speed_to_ticks(ArmySpeed)});
true ->
ok
end,
NewArmy = state_leave_move(Data#module_data.army, LastX, LastY),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_COMBAT', BattleId}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_combat(Army, BattleId),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_RETREAT', BattleId}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_retreat(Army, BattleId),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
VisibleList = Data#module_data.visible,
ObservedByList = Data#module_data.observed_by,
{ok, SubscriptionPid} = subscription:start(Army#army.id),
subscription:update_perception(SubscriptionPid, Army#army.id, self(), Army#army.x, Army#army.y, VisibleList, ObservedByList),
Toggle player 's perception has been updated .
update_perception(Army#army.player_id),
entity_update_perception(ObservedByList),
{noreply, NewData};
handle_cast({'SET_STATE_LEAVE', BattleId}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_leave(Army, BattleId),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_CLAIM', ClaimId}, Data) ->
?INFO("Set State Claim Id", ClaimId),
Army = Data#module_data.army,
add_event_claim(Data#module_data.self, ClaimId),
NewArmy = state_claim(Army),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_DEAD'}, Data) ->
Army = Data#module_data.army,
gen_server:cast(global:whereis_name(game_pid), {'CLEAR_EVENTS', Data#module_data.self}),
NewArmy = state_dead(Army),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'SET_STATE_NONE'}, Data) ->
NewArmy = state_none(Data#module_data.army),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'ADD_WAYPOINT', X, Y}, Data) ->
NewArmy = add_waypoint(Data#module_data.army, X, Y),
NewData = Data#module_data {army = NewArmy},
save_army(NewArmy),
{noreply, NewData};
handle_cast({'PROCESS_EVENT', _EventTick, EventData, EventType}, Data) ->
?INFO("Processing Event Type", EventType),
Army = Data#module_data.army,
case EventType of
?EVENT_MOVE ->
NewArmy = do_move(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_ATTACK ->
NewArmy = do_attack(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_RETREAT_MOVE ->
battle:remove_army(Army#army.battle, Army#army.id),
NewArmy = do_move(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_LEAVE_MOVE ->
battle:remove_army(Army#army.battle, Army#army.id),
NewArmy = do_move(Army, Data#module_data.self, Data#module_data.visible, Data#module_data.observed_by);
?EVENT_CLAIM ->
ClaimId = EventData,
claim:complete(ClaimId),
NewArmy = state_none(Army);
?EVENT_NONE ->
NewArmy = Army
end,
?INFO("Army: ", NewArmy),
NewData = Data#module_data {army = NewArmy},
save_army(NewData#module_data.army),
{noreply, NewData};
handle_cast({'ADD_VISIBLE', _ArmyId, EntityId, EntityPid}, Data) ->
VisibleList = Data#module_data.visible,
NewVisibleList = [{EntityId, EntityPid} | VisibleList],
NewData = Data#module_data { visible = NewVisibleList },
update_perception(Data#module_data.player_id),
{noreply, NewData};
handle_cast({'REMOVE_VISIBLE', _ArmyId, EntityId, EntityPid}, Data) ->
VisibleList = Data#module_data.visible,
NewVisibleList = lists:delete({EntityId, EntityPid}, VisibleList),
NewData = Data#module_data { visible = NewVisibleList },
update_perception(Data#module_data.player_id),
{noreply, NewData};
handle_cast({'ADD_OBSERVED_BY', _ArmyId, EntityId, EntityPid}, Data) ->
ObservedByList = Data#module_data.observed_by,
NewObservedByList = [{EntityId, EntityPid} | ObservedByList],
NewData = Data#module_data { observed_by = NewObservedByList },
{noreply, NewData};
handle_cast({'REMOVE_OBSERVED_BY', _ArmyId, EntityId, EntityPid}, Data) ->
ObservedByList = Data#module_data.observed_by,
NewObservedByList = lists:delete({EntityId, EntityPid}, ObservedByList),
NewData = Data#module_data { observed_by = NewObservedByList },
{noreply, NewData};
handle_cast({'UNIT_TRANSFERED'}, Data) ->
Army = Data#module_data.army,
Units = unit:get_units(Army#army.id),
NumUnits = length(Units),
case NumUnits > 0 of
true -> State = ?STATE_NONE;
false -> State = ?STATE_EMPTY
end,
NewArmy = Army#army { state = State},
NewData = Data#module_data {army = NewArmy},
{noreply, NewData};
handle_cast(stop, Data) ->
{stop, normal, Data}.
handle_call({'GET_INFO', PlayerId}, _From, Data) ->
Army = Data#module_data.army,
case Army#army.player_id =:= PlayerId of
true ->
UnitsInfoTuple = unit:tuple_form_items(PlayerId, Army#army.id),
ArmyInfo = {detailed,
Army#army.id,
Army#army.name,
UnitsInfoTuple};
false ->
ArmyInfo = {generic,
Army#army.id,
Army#army.player_id,
Army#army.name,
kingdom:get_name(Army#army.player_id)}
end,
io:fwrite("army - ArmyInfo: ~w~n", [ArmyInfo]),
{reply, ArmyInfo , Data};
handle_call({'BATTLE_GET_INFO'}, _From, Data) ->
Army = Data#module_data.army,
UnitsInfoTuple = unit:tuple_form(Army#army.id),
ArmyInfo = {Army#army.id,
Army#army.player_id,
Army#army.name,
kingdom:get_name(Army#army.player_id),
UnitsInfoTuple},
{reply, ArmyInfo, Data};
handle_call({'GET_UNITS'}, _From, Data) ->
Army = Data#module_data.army,
Units = db:dirty_index_read(unit, Army#army.id, #unit.entity_id),
{reply, Units, Data};
handle_call({'GET_UNIT', UnitId}, _From, Data) ->
?INFO("Get Unit"),
Unit = unit:get_unit(UnitId),
{reply, Unit, Data};
handle_call({'GET_STATE', _ArmyId}, _From, Data) ->
Army = Data#module_data.army,
State = #state { id = Army#army.id,
player_id = Army#army.player_id,
type = ?OBJECT_ARMY,
subtype = ?OBJECT_BASIC,
state = Army#army.state,
x = Army#army.x,
y = Army#army.y},
?INFO("State: ", State),
{reply, State, Data};
handle_call({'GET_ID'}, _From, Data) ->
Army = Data#module_data.army,
{reply, Army#army.id, Data};
handle_call({'GET_PLAYER_ID'}, _From, Data) ->
{reply, Data#module_data.player_id, Data};
handle_call({'GET_TYPE', _ArmyId}, _From, Data) ->
{reply, ?OBJECT_ARMY, Data};
handle_call('GET_VISIBLE', _From, Data) ->
{reply, Data#module_data.visible, Data};
handle_call('GET_OBSERVED_BY', _From, Data) ->
{reply, Data#module_data.observed_by, Data};
handle_call('GET_SUBSCRIPTION_DATA', _From, Data) ->
Army = Data#module_data.army,
{reply, {Army#army.x, Army#army.y, Data#module_data.visible, Data#module_data.observed_by}, Data};
handle_call({'ON_SAME_TILE', X, Y}, _From, Data) ->
Army = Data#module_data.army,
{reply, (Army#army.x =:= X) and (Army#army.y =:= Y), Data};
handle_call(Event, From, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Event},
{from, From}
]),
{noreply, Data}.
handle_info(Info, Data) ->
error_logger:info_report([{module, ?MODULE},
{line, ?LINE},
{self, self()},
{message, Info}]),
{noreply, Data}.
code_change(_OldVsn, Data, _Extra) ->
{ok, Data}.
do_move(Army, ArmyPid, VisibleList, ObservedByList) ->
io:fwrite("Army#army.dest: ~w~n", [Army#army.dest]),
[{DestX, DestY} | DestRest] = Army#army.dest,
{NewArmyX, NewArmyY} = next_pos(Army#army.x, Army#army.y, DestX, DestY),
add_move_trigger(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
set_discovered_tiles(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
{ok, SubscriptionPid} = subscription:start(Army#army.id),
subscription:update_perception(SubscriptionPid, Army#army.id, ArmyPid, NewArmyX, NewArmyY, VisibleList, ObservedByList),
Toggle player 's perception has been updated .
update_perception(Army#army.player_id),
entity_update_perception(ObservedByList),
case check_destination(NewArmyX =:= DestX, NewArmyY =:= DestY, length(DestRest)) of
final ->
io:fwrite("Final destination reached.~n"),
NewArmy = state_none(Army, NewArmyX, NewArmyY);
waypoint ->
io:fwrite("Next Waypoint.~n"),
{NextX, NextY} = next_pos(NewArmyX, NewArmyY, DestX, DestY),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
game:add_event(ArmyPid, ?EVENT_MOVE, none, speed_to_ticks(ArmySpeed)),
NewArmy = event_move_next_dest(Army, NewArmyX, NewArmyY, DestRest);
moving ->
io:fwrite("Moving.~n"),
{NextX, NextY} = next_pos(NewArmyX, NewArmyY, DestX, DestY),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
game:add_event(ArmyPid, ?EVENT_MOVE, none, speed_to_ticks(ArmySpeed)),
NewArmy = event_move(Army, NewArmyX, NewArmyY)
end,
NewArmy.
do_attack(Army, ArmyPid, VisibleList, ObservedByList) ->
TargetState = gen_server:call(global:whereis_name({army, Army#army.target}), {'GET_STATE', Army#army.id}),
{NewArmyX, NewArmyY} = next_pos(Army#army.x, Army#army.y, TargetState#state.x, TargetState#state.y),
if
(NewArmyX =:= TargetState#state.x) and (NewArmyY =:= TargetState#state.y) ->
?INFO("Creating battle"),
BattleId = counter:increment(battle) + 1000000,
battle:create(BattleId, TargetState#state.x, TargetState#state.y),
battle:setup(BattleId, Army#army.id, Army#army.target),
army:combat(Army#army.target, BattleId),
NewArmy = state_combat_move(Army, BattleId, NewArmyX, NewArmyY);
true ->
{NextX, NextY} = next_pos(NewArmyX, NewArmyY, TargetState#state.x, TargetState#state.y),
ArmySpeed = get_army_speed(Army#army.id, NextX, NextY),
game:add_event(ArmyPid, ?EVENT_ATTACK, none, speed_to_ticks(ArmySpeed)),
NewArmy = event_move(Army, NewArmyX, NewArmyY)
end,
add_move_trigger(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
set_discovered_tiles(Army#army.player_id, Army#army.id, NewArmyX, NewArmyY),
{ok, SubscriptionPid} = subscription:start(Army#army.id),
subscription:update_perception(SubscriptionPid, Army#army.id, ArmyPid, NewArmyX, NewArmyY, VisibleList, ObservedByList),
update_perception(Army#army.player_id),
entity_update_perception(ObservedByList),
NewArmy.
next_pos(ArmyX, ArmyY, DestX, DestY) ->
DiffX = DestX - ArmyX,
DiffY = DestY - ArmyY,
if
DiffX > 0 ->
NewArmyX = ArmyX + 1;
DiffX < 0 ->
NewArmyX = ArmyX - 1;
true ->
NewArmyX = ArmyX
end,
if
DiffY > 0 ->
NewArmyY = ArmyY + 1;
DiffY < 0 ->
NewArmyY = ArmyY - 1;
true ->
NewArmyY = ArmyY
end,
{NewArmyX, NewArmyY}.
event_move(Army, NewX, NewY) ->
LastPos = {Army#army.x, Army#army.y},
Army#army{x = NewX,
y = NewY,
last_pos = LastPos}.
event_move_next_dest(Army, NewX, NewY, NextDest) ->
LastPos = {Army#army.x, Army#army.y},
Army#army{x = NewX,
y = NewY,
last_pos = LastPos,
dest = NextDest}.
add_event_move(Pid, ArmySpeed) ->
game:clear_events(Pid),
game:add_event(Pid, ?EVENT_MOVE, none, speed_to_ticks(ArmySpeed)).
add_event_claim(Pid, ClaimId) ->
game:clear_events(Pid),
game:add_event(Pid, ?EVENT_CLAIM, ClaimId, ?CLAIM_TICK).
add_event_attack(Pid, ArmySpeed) ->
game:clear_events(Pid),
game:add_event(Pid, ?EVENT_ATTACK, non, speed_to_ticks(ArmySpeed)).
state_move(Army, DestX, DestY) ->
Army#army{dest = [{DestX, DestY}],
state = ?STATE_MOVE}.
state_attack(Army, TargetId) ->
Army#army{state = ?STATE_ATTACK,
target = TargetId}.
state_retreat(Army, BattleId) ->
Army#army{state = ?STATE_RETREAT,
battle = BattleId}.
state_retreat_move(Army, LastX, LastY) ->
Army#army{dest = [{LastX, LastY}],
state = ?STATE_RETREAT_MOVE}.
state_leave(Army, BattleId) ->
Army#army{state = ?STATE_LEAVE,
battle = BattleId}.
state_leave_move(Army, LastX, LastY) ->
Army#army{dest = [{LastX, LastY}],
state = ?STATE_LEAVE_MOVE}.
state_combat(Army, BattleId) ->
Army#army{state = ?STATE_COMBAT,
battle = BattleId}.
state_combat_move(Army, BattleId, X, Y) ->
LastPos = {Army#army.x, Army#army.y},
Army#army{state = ?STATE_COMBAT,
battle = BattleId,
x = X,
y = Y,
last_pos = LastPos}.
state_dead(Army) ->
Army#army{state = ?STATE_DEAD}.
state_claim(Army) ->
Army#army{state = ?STATE_CLAIM}.
state_none(Army, X, Y) ->
Army#army{state = ?STATE_NONE,
x = X,
y = Y}.
state_none(Army) ->
Army#army{state = ?STATE_NONE}.
get_army_speed(ArmyId, X, Y) ->
ArmySpeed = unit:highest_unit_movement(ArmyId),
TileType = map:get_tile_type(X,Y),
Speed = ArmySpeed * tile_modifier(TileType),
io:fwrite("Speed: ~w~n",[Speed]),
Speed.
speed_to_ticks(Speed) ->
(1000 div ?GAME_LOOP_TICK) * 1.
tile_modifier(?TILE_MOUNTAIN) ->
?TILE_MOUNTAIN_SPEED;
tile_modifier(?TILE_FOREST) ->
?TILE_FOREST_SPEED;
tile_modifier(?TILE_PLAINS) ->
?TILE_PLAINS_SPEED;
tile_modifier(?TILE_SWAMP) ->
?TILE_SWAMP_SPEED;
tile_modifier(_) ->
1.
entity_update_perception(EntityList) ->
F = fun({EntityId, EntityPid}) ->
case gen_server:call(EntityPid, {'GET_TYPE', EntityId}) of
?OBJECT_ARMY ->
check_player_online(EntityPid);
?OBJECT_CITY ->
check_player_online(EntityPid);
_OtherTypes ->
no_update
end
end,
lists:foreach(F, EntityList).
check_player_online(EntityPid) ->
PlayerId = gen_server:call(EntityPid, {'GET_PLAYER_ID'}),
case gen_server:call(global:whereis_name(game_pid), {'IS_PLAYER_ONLINE', PlayerId}) of
true ->
update_perception(PlayerId);
false ->
no_update
end.
update_perception(PlayerId) ->
case player:get_type(PlayerId) of
?PLAYER_HUMAN ->
gen_server:cast(global:whereis_name(game_pid),{'UPDATE_PERCEPTION', PlayerId});
?PLAYER_COMPUTER ->
no_update
end.
set_discovered_tiles(PlayerId, ArmyId, X, Y) ->
case player:get_type(PlayerId) of
?PLAYER_HUMAN ->
gen_server:cast(global:whereis_name({player, PlayerId}), {'SET_DISCOVERED_TILES', ArmyId, X, Y});
?PLAYER_COMPUTER ->
ok
end.
add_move_trigger(PlayerId, ArmyId, X, Y) ->
case player:get_type(PlayerId) of
?PLAYER_HUMAN ->
TriggerData = {ArmyId, X, Y},
trigger:add(?TRIGGER_MOVE, TriggerData);
?PLAYER_COMPUTER ->
no_trigger
end.
check_destination(_X = true, _Y = true, _DestList = 0) ->
final;
check_destination(_X = true, _Y = true, _DestList) ->
waypoint;
check_destination(_X, _Y, _DestList) ->
moving.
add_waypoint(Army, X, Y) ->
NewDest = [{X, Y} | Army#army.dest],
Army#army {dest = NewDest}.
save_army(Army) ->
db:dirty_write(Army).
|
9fb4fc3ac57ef49b44743b91fbe654c59e46f32d079d0296d5efd07447fad7d2 | jumper149/go | Message.hs | module Message ( handleWS
) where
import Miso.WebSocket
import qualified Go.Run.Message as G
import Lobby.Operation
import Operation
handleWS :: WebSocket G.ServerMessage -> Operation
handleWS (WebSocketMessage msg) = case msg of
G.ServerMessageFail m -> WriteErrorLog (m <> "\n")
G.ServerMessageGameStateRep gs -> GameSetStateRep gs
G.ServerMessagePlayerRep mbP -> GameSetPlayerRep mbP
G.ServerMessageLobby gs -> LobbyOp $ UpdateGames gs
G.ServerMessageApproveConfig c -> LobbyOp $ ApproveConfig c
handleWS _ = NoOp
| null | https://raw.githubusercontent.com/jumper149/go/603e61f64e8e7c890bbc914fef6033b5ed7dd005/client/Message.hs | haskell | module Message ( handleWS
) where
import Miso.WebSocket
import qualified Go.Run.Message as G
import Lobby.Operation
import Operation
handleWS :: WebSocket G.ServerMessage -> Operation
handleWS (WebSocketMessage msg) = case msg of
G.ServerMessageFail m -> WriteErrorLog (m <> "\n")
G.ServerMessageGameStateRep gs -> GameSetStateRep gs
G.ServerMessagePlayerRep mbP -> GameSetPlayerRep mbP
G.ServerMessageLobby gs -> LobbyOp $ UpdateGames gs
G.ServerMessageApproveConfig c -> LobbyOp $ ApproveConfig c
handleWS _ = NoOp
| |
73b6fd6c95ed89a1d7644e2a87c89028ae03b2842ebbd1504564fb04aaaeb2c7 | RedPRL/asai | FileReader.mli | include Reader.S
| null | https://raw.githubusercontent.com/RedPRL/asai/51f3350b19f9214370d65edfc5c61fe92df1fbb7/src/file/FileReader.mli | ocaml | include Reader.S
| |
e97839fc9cd3cb089d488692c0dbf7b450edbd76c42419226ecdebc776c92f0e | jrm-code-project/LISP-Machine | nupi-tape.lisp | ;;; -*- Mode:LISP; Package:SYSTEM-INTERNALS; Base:8 -*-
(defvar nupi-tape-physical-unit #x18)
(defun nupi-tape-rewind ()
(let ((rqb (get-disk-rqb)))
(nupi-disk-command rqb #x20 nupi-tape-physical-unit 0 0 nil)
(return-disk-rqb rqb)))
(defun nupi-tape-write-filemark ()
(let ((rqb (get-disk-rqb)))
(nupi-disk-command rqb #x25 nupi-tape-physical-unit 0 0 nil)))
(defun nupi-tape-read (rqb n-bytes)
(if (> n-bytes (* 1024. (rqb-npages rqb))) (ferror nil "too big"))
(nupi-tape-command rqb #x12 nupi-tape-physical-unit 0 n-bytes)
(nupi-transfer-count rqb)
)
(defun nupi-tape-write (rqb n-bytes)
(if (> n-bytes (* 1024. (rqb-npages rqb))) (ferror nil "too big"))
(nupi-tape-command rqb #x13 nupi-tape-physical-unit 0 n-bytes)
(nupi-transfer-count rqb))
(defflavor nupi-simple-tape-input-stream
(rqb
(n-bytes-per-operation 10240.)
(eof-p nil)
buffer-8b
)
(si:buffered-input-stream)
:settable-instance-variables
)
(defmethod (nupi-simple-tape-input-stream :after :init) (ignore)
(if (not (zerop (ldb (byte 10. 0) n-bytes-per-operation)))
(ferror nil "n-bytes-per-operation must be multiple of 1024."))
(setq rqb (get-disk-rqb (floor n-bytes-per-operation 1024.)))
(setq buffer-8b (make-array n-bytes-per-operation
:type :art-8b
:displaced-to (rqb-8-bit-buffer rqb)
))
)
(defmethod (nupi-simple-tape-input-stream :next-input-buffer) (no-hang-p)
no-hang-p
(cond ((null eof-p)
(let* ((n-bytes (nupi-tape-read rqb n-bytes-per-operation))
(status (ldb (byte 8 8) (nupi-disk-status rqb))))
(format t "~&nupi tape status ~d. xfer ~d. " status n-bytes)
(cond ((or (= status 114.) (= status 76.))
;;got file mark before finishing transfer, or something like that
(setq eof-p t)
(values buffer-8b 0 n-bytes))
((zerop status)
(values buffer-8b 0 n-bytes))
(t
(ferror nil "unknown status ~d." status)))))
(t
(setq eof-p nil)
nil)))
(defmethod (nupi-simple-tape-input-stream :discard-input-buffer) (ignore)
nil)
(defmethod (nupi-simple-tape-input-stream :after :close) (&rest ignore)
(return-disk-rqb rqb))
(defflavor nupi-simple-tape-output-stream
(rqb
(n-bytes-per-operation 10240.)
(done-a-write-p nil)
)
(si:buffered-output-stream)
)
(defmethod (nupi-simple-tape-output-stream :after :init) (ignore)
(if (not (zerop (ldb (byte 10. 0) n-bytes-per-operation)))
(ferror nil "n-bytes-per-operation must be multiple of 1024."))
(setq rqb (get-disk-rqb (floor n-bytes-per-operation 1024.))))
(defmethod (nupi-simple-tape-output-stream :new-output-buffer) ()
(values (si:rqb-8-bit-buffer rqb) 0 n-bytes-per-operation))
(defmethod (nupi-simple-tape-output-stream :send-output-buffer) (buffer ending-index)
(if (not (zerop (ldb (byte 10. 0) ending-index)))
(ferror nil "can't flush the buffer except on 1K boundaries"))
(if (not (eq buffer (rqb-8-bit-buffer rqb)))
(ferror nil "trying to write wrong buffer"))
(setq done-a-write-p t)
(nupi-tape-write rqb ending-index)
)
(defmethod (nupi-simple-tape-output-stream :discard-output-buffer) (buffer)
buffer
)
(defmethod (nupi-simple-tape-output-stream :after :close) (&rest ignore)
(if done-a-write-p
(nupi-tape-write-filemark))
(return-disk-rqb rqb))
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/io/nupi-tape.lisp | lisp | -*- Mode:LISP; Package:SYSTEM-INTERNALS; Base:8 -*-
got file mark before finishing transfer, or something like that |
(defvar nupi-tape-physical-unit #x18)
(defun nupi-tape-rewind ()
(let ((rqb (get-disk-rqb)))
(nupi-disk-command rqb #x20 nupi-tape-physical-unit 0 0 nil)
(return-disk-rqb rqb)))
(defun nupi-tape-write-filemark ()
(let ((rqb (get-disk-rqb)))
(nupi-disk-command rqb #x25 nupi-tape-physical-unit 0 0 nil)))
(defun nupi-tape-read (rqb n-bytes)
(if (> n-bytes (* 1024. (rqb-npages rqb))) (ferror nil "too big"))
(nupi-tape-command rqb #x12 nupi-tape-physical-unit 0 n-bytes)
(nupi-transfer-count rqb)
)
(defun nupi-tape-write (rqb n-bytes)
(if (> n-bytes (* 1024. (rqb-npages rqb))) (ferror nil "too big"))
(nupi-tape-command rqb #x13 nupi-tape-physical-unit 0 n-bytes)
(nupi-transfer-count rqb))
(defflavor nupi-simple-tape-input-stream
(rqb
(n-bytes-per-operation 10240.)
(eof-p nil)
buffer-8b
)
(si:buffered-input-stream)
:settable-instance-variables
)
(defmethod (nupi-simple-tape-input-stream :after :init) (ignore)
(if (not (zerop (ldb (byte 10. 0) n-bytes-per-operation)))
(ferror nil "n-bytes-per-operation must be multiple of 1024."))
(setq rqb (get-disk-rqb (floor n-bytes-per-operation 1024.)))
(setq buffer-8b (make-array n-bytes-per-operation
:type :art-8b
:displaced-to (rqb-8-bit-buffer rqb)
))
)
(defmethod (nupi-simple-tape-input-stream :next-input-buffer) (no-hang-p)
no-hang-p
(cond ((null eof-p)
(let* ((n-bytes (nupi-tape-read rqb n-bytes-per-operation))
(status (ldb (byte 8 8) (nupi-disk-status rqb))))
(format t "~&nupi tape status ~d. xfer ~d. " status n-bytes)
(cond ((or (= status 114.) (= status 76.))
(setq eof-p t)
(values buffer-8b 0 n-bytes))
((zerop status)
(values buffer-8b 0 n-bytes))
(t
(ferror nil "unknown status ~d." status)))))
(t
(setq eof-p nil)
nil)))
(defmethod (nupi-simple-tape-input-stream :discard-input-buffer) (ignore)
nil)
(defmethod (nupi-simple-tape-input-stream :after :close) (&rest ignore)
(return-disk-rqb rqb))
(defflavor nupi-simple-tape-output-stream
(rqb
(n-bytes-per-operation 10240.)
(done-a-write-p nil)
)
(si:buffered-output-stream)
)
(defmethod (nupi-simple-tape-output-stream :after :init) (ignore)
(if (not (zerop (ldb (byte 10. 0) n-bytes-per-operation)))
(ferror nil "n-bytes-per-operation must be multiple of 1024."))
(setq rqb (get-disk-rqb (floor n-bytes-per-operation 1024.))))
(defmethod (nupi-simple-tape-output-stream :new-output-buffer) ()
(values (si:rqb-8-bit-buffer rqb) 0 n-bytes-per-operation))
(defmethod (nupi-simple-tape-output-stream :send-output-buffer) (buffer ending-index)
(if (not (zerop (ldb (byte 10. 0) ending-index)))
(ferror nil "can't flush the buffer except on 1K boundaries"))
(if (not (eq buffer (rqb-8-bit-buffer rqb)))
(ferror nil "trying to write wrong buffer"))
(setq done-a-write-p t)
(nupi-tape-write rqb ending-index)
)
(defmethod (nupi-simple-tape-output-stream :discard-output-buffer) (buffer)
buffer
)
(defmethod (nupi-simple-tape-output-stream :after :close) (&rest ignore)
(if done-a-write-p
(nupi-tape-write-filemark))
(return-disk-rqb rqb))
|
7e5d7bb7eacf38626d3145ccbcd549126479489b2ee9026b6ec5ebf7aeb75e3d | andorp/bead | I18N.hs | module Bead.View.Translation.I18N where
import Text.Printf (printf)
import Bead.View.Translation.Base
-- The I18N is a mapping from a given translation key
-- to the actual translation of the message
type I18N = Translation String -> String
-- | The Translation Message represents a message that
-- can be rendered out the the UI, the message could
be a normal message or a parametrized one
data TransMsg
= TransMsg (Translation String)
| TransPrmMsg (Translation String) String
| TransPrm2Msg (Translation String) String String
| TransPrm3Msg (Translation String) String String String
deriving (Show)
Template method for TransMsg function
transMsgCata
transMsg f
transPrmMsg g
transPrm2Msg h
transPrm3Msg i
tm = case tm of
TransMsg t -> transMsg (f t)
TransPrmMsg t p1 -> transPrmMsg (g t) p1
TransPrm2Msg t p1 p2 -> transPrm2Msg (h t) p1 p2
TransPrm3Msg t p1 p2 p3 -> transPrm3Msg (i t) p1 p2 p3
-- Translate the parametrized message with the given localization
translateMessage :: I18N -> TransMsg -> String
translateMessage i18n = transMsgCata
id i18n
printf i18n
printf i18n
printf i18n
| null | https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/src/Bead/View/Translation/I18N.hs | haskell | The I18N is a mapping from a given translation key
to the actual translation of the message
| The Translation Message represents a message that
can be rendered out the the UI, the message could
Translate the parametrized message with the given localization | module Bead.View.Translation.I18N where
import Text.Printf (printf)
import Bead.View.Translation.Base
type I18N = Translation String -> String
be a normal message or a parametrized one
data TransMsg
= TransMsg (Translation String)
| TransPrmMsg (Translation String) String
| TransPrm2Msg (Translation String) String String
| TransPrm3Msg (Translation String) String String String
deriving (Show)
Template method for TransMsg function
transMsgCata
transMsg f
transPrmMsg g
transPrm2Msg h
transPrm3Msg i
tm = case tm of
TransMsg t -> transMsg (f t)
TransPrmMsg t p1 -> transPrmMsg (g t) p1
TransPrm2Msg t p1 p2 -> transPrm2Msg (h t) p1 p2
TransPrm3Msg t p1 p2 p3 -> transPrm3Msg (i t) p1 p2 p3
translateMessage :: I18N -> TransMsg -> String
translateMessage i18n = transMsgCata
id i18n
printf i18n
printf i18n
printf i18n
|
0737e0356056ae4caeb6815e51350e89b4afda1c3e61437581739a75d6e26167 | dreixel/syb | Paradise.hs | module Paradise (tests) where
{-
This test runs the infamous PARADISE benchmark,
which is the HELLO WORLD example of generic programming,
i.e., the "increase salary" function is applied to
a typical company just as shown in the boilerplate paper.
-}
import Test.Tasty.HUnit
import Data.Generics
import CompanyDatatypes
-- Increase salary by percentage
increase :: Double -> Company -> Company
increase k = everywhere (mkT (incS k))
-- "interesting" code for increase
incS :: Double -> Salary -> Salary
incS k (S s) = S (s * (1+k))
tests = increase 0.125 genCom @=? output
output = C [D "Research" (E (P "Laemmel" "Amsterdam") (S 9000)) [PU (E (P "Joost" "Amsterdam") (S 1125)),PU (E (P "Marlow" "Cambridge") (S 2250))],D "Strategy" (E (P "Blair" "London") (S 112500)) []]
| null | https://raw.githubusercontent.com/dreixel/syb/4806afeb2ea824a3ea9969e23ca2c9569cd20d84/tests/Paradise.hs | haskell |
This test runs the infamous PARADISE benchmark,
which is the HELLO WORLD example of generic programming,
i.e., the "increase salary" function is applied to
a typical company just as shown in the boilerplate paper.
Increase salary by percentage
"interesting" code for increase | module Paradise (tests) where
import Test.Tasty.HUnit
import Data.Generics
import CompanyDatatypes
increase :: Double -> Company -> Company
increase k = everywhere (mkT (incS k))
incS :: Double -> Salary -> Salary
incS k (S s) = S (s * (1+k))
tests = increase 0.125 genCom @=? output
output = C [D "Research" (E (P "Laemmel" "Amsterdam") (S 9000)) [PU (E (P "Joost" "Amsterdam") (S 1125)),PU (E (P "Marlow" "Cambridge") (S 2250))],D "Strategy" (E (P "Blair" "London") (S 112500)) []]
|
36ce7c79503d543f717c21daefde6b37f9f0ed6295ea0efb3fb45c40086201aa | zadean/xqerl | fn_QName_SUITE.erl | -module('fn_QName_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['ExpandedQNameConstructFunc001'/1]).
-export(['ExpandedQNameConstructFunc002'/1]).
-export(['ExpandedQNameConstructFunc003'/1]).
-export(['ExpandedQNameConstructFunc004'/1]).
-export(['ExpandedQNameConstructFunc005'/1]).
-export(['ExpandedQNameConstructFunc006'/1]).
-export(['ExpandedQNameConstructFunc007'/1]).
-export(['ExpandedQNameConstructFunc008'/1]).
-export(['ExpandedQNameConstructFunc009'/1]).
-export(['ExpandedQNameConstructFunc010'/1]).
-export(['ExpandedQNameConstructFunc011'/1]).
-export(['ExpandedQNameConstructFunc012'/1]).
-export(['ExpandedQNameConstructFunc013'/1]).
-export(['ExpandedQNameConstructFunc014'/1]).
-export(['ExpandedQNameConstructFunc015'/1]).
-export(['ExpandedQNameConstructFunc016'/1]).
-export(['ExpandedQNameConstructFunc017'/1]).
-export(['ExpandedQNameConstructFunc018'/1]).
-export(['ExpandedQNameConstructFunc019'/1]).
-export(['ExpandedQNameConstructFunc020'/1]).
-export(['ExpandedQNameConstructFunc021'/1]).
-export(['qName-1'/1]).
-export(['K-ExpandedQNameConstructFunc-1'/1]).
-export(['K-ExpandedQNameConstructFunc-2'/1]).
-export(['K-ExpandedQNameConstructFunc-3'/1]).
-export(['K-ExpandedQNameConstructFunc-4'/1]).
-export(['K-ExpandedQNameConstructFunc-5'/1]).
-export(['K-ExpandedQNameConstructFunc-6'/1]).
-export(['K-ExpandedQNameConstructFunc-7'/1]).
-export(['K-ExpandedQNameConstructFunc-8'/1]).
-export(['K-ExpandedQNameConstructFunc-9'/1]).
-export(['K-ExpandedQNameConstructFunc-10'/1]).
-export(['K2-ExpandedQNameConstructFunc-1'/1]).
-export(['cbcl-qname-001'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "fn"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1}
].
groups() ->
[
{group_0, [parallel], [
'ExpandedQNameConstructFunc001',
'ExpandedQNameConstructFunc002',
'ExpandedQNameConstructFunc003',
'ExpandedQNameConstructFunc004',
'ExpandedQNameConstructFunc005',
'ExpandedQNameConstructFunc006',
'ExpandedQNameConstructFunc007',
'ExpandedQNameConstructFunc008',
'ExpandedQNameConstructFunc009',
'ExpandedQNameConstructFunc010',
'ExpandedQNameConstructFunc011',
'ExpandedQNameConstructFunc012',
'ExpandedQNameConstructFunc013',
'ExpandedQNameConstructFunc014',
'ExpandedQNameConstructFunc015',
'ExpandedQNameConstructFunc016',
'ExpandedQNameConstructFunc017',
'ExpandedQNameConstructFunc018',
'ExpandedQNameConstructFunc019',
'ExpandedQNameConstructFunc020',
'ExpandedQNameConstructFunc021',
'qName-1',
'K-ExpandedQNameConstructFunc-1'
]},
{group_1, [parallel], [
'K-ExpandedQNameConstructFunc-2',
'K-ExpandedQNameConstructFunc-3',
'K-ExpandedQNameConstructFunc-4',
'K-ExpandedQNameConstructFunc-5',
'K-ExpandedQNameConstructFunc-6',
'K-ExpandedQNameConstructFunc-7',
'K-ExpandedQNameConstructFunc-8',
'K-ExpandedQNameConstructFunc-9',
'K-ExpandedQNameConstructFunc-10',
'K2-ExpandedQNameConstructFunc-1',
'cbcl-qname-001'
]}
].
environment('fsx', __BaseDir) ->
[
{'decimal-formats', []},
{sources, [{filename:join(__BaseDir, "../prod/ForClause/fsx.xml"), ".", []}]},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
].
'ExpandedQNameConstructFunc001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName(\"\", \"person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc001.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<person xmlns=\"\">test</person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName(\"\", \"ht:person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc002.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<ht:person xmlns:ht=\"\">test</ht:person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName(\"\", \"person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc003.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<person>test</person>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName((), \"person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc004.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<person>test</person>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"ht:person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc005.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName((), \"ht:person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc006.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"1person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc007.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"@person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc008.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"-person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc009.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"<person>\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc010.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \":person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc011.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"person:\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc012.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc013.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc014.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", xs:integer(\"100\"))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc015.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName( xs:integer(\"100\"), \"person\" )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc016.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"element {fn:QName( \"\", string((//FolderName)[2]) )}{ \"test\" }",
{Env, Opts} = xqerl_test:handle_environment(environment('fsx', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc017.xq"),
Qry1
),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<Folder00000000001 xmlns=\"\">test</Folder00000000001>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"element {fn:QName( concat('/', string((//FolderName)[2])), \"people\" )}{ \"test\" }",
{Env, Opts} = xqerl_test:handle_environment(environment('fsx', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc018.xq"),
Qry1
),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<people xmlns=\"\">test</people>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName( \"\", \"\" )}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc019.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc020'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"declare namespace ht=\"\"; element {fn:QName( \"-example\", \"ht:person\" )}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc020.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<ht:person xmlns:ht=\"-example\">test</ht:person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"declare namespace ht=\"\"; element {fn:QName( \"\", \"ht2:person\" )}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc021.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<ht2:person xmlns:ht2=\"\">test</ht2:person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'qName-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "xs:QName(20)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "qName-1.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName()",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"/\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"/\", \"ncname\", \"error\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"QName(\"-functions\", \"prefix:local\") eq xs:QName(\"fn:local\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"/\", \"1asd:error\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"\", \"error:ncname\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName((), \"error:ncname\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"my:qName\", \"\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"\", \"local\") eq xs:QName(\"local\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName((), \"local\") eq xs:QName(\"local\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K2-ExpandedQNameConstructFunc-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName((), ())",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K2-ExpandedQNameConstructFunc-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-qname-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName('', ' ')",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "cbcl-qname-001.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| null | https://raw.githubusercontent.com/zadean/xqerl/1a94833e996435495922346010ce918b4b0717f2/test/fn/fn_QName_SUITE.erl | erlang | -module('fn_QName_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['ExpandedQNameConstructFunc001'/1]).
-export(['ExpandedQNameConstructFunc002'/1]).
-export(['ExpandedQNameConstructFunc003'/1]).
-export(['ExpandedQNameConstructFunc004'/1]).
-export(['ExpandedQNameConstructFunc005'/1]).
-export(['ExpandedQNameConstructFunc006'/1]).
-export(['ExpandedQNameConstructFunc007'/1]).
-export(['ExpandedQNameConstructFunc008'/1]).
-export(['ExpandedQNameConstructFunc009'/1]).
-export(['ExpandedQNameConstructFunc010'/1]).
-export(['ExpandedQNameConstructFunc011'/1]).
-export(['ExpandedQNameConstructFunc012'/1]).
-export(['ExpandedQNameConstructFunc013'/1]).
-export(['ExpandedQNameConstructFunc014'/1]).
-export(['ExpandedQNameConstructFunc015'/1]).
-export(['ExpandedQNameConstructFunc016'/1]).
-export(['ExpandedQNameConstructFunc017'/1]).
-export(['ExpandedQNameConstructFunc018'/1]).
-export(['ExpandedQNameConstructFunc019'/1]).
-export(['ExpandedQNameConstructFunc020'/1]).
-export(['ExpandedQNameConstructFunc021'/1]).
-export(['qName-1'/1]).
-export(['K-ExpandedQNameConstructFunc-1'/1]).
-export(['K-ExpandedQNameConstructFunc-2'/1]).
-export(['K-ExpandedQNameConstructFunc-3'/1]).
-export(['K-ExpandedQNameConstructFunc-4'/1]).
-export(['K-ExpandedQNameConstructFunc-5'/1]).
-export(['K-ExpandedQNameConstructFunc-6'/1]).
-export(['K-ExpandedQNameConstructFunc-7'/1]).
-export(['K-ExpandedQNameConstructFunc-8'/1]).
-export(['K-ExpandedQNameConstructFunc-9'/1]).
-export(['K-ExpandedQNameConstructFunc-10'/1]).
-export(['K2-ExpandedQNameConstructFunc-1'/1]).
-export(['cbcl-qname-001'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "fn"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0},
{group, group_1}
].
groups() ->
[
{group_0, [parallel], [
'ExpandedQNameConstructFunc001',
'ExpandedQNameConstructFunc002',
'ExpandedQNameConstructFunc003',
'ExpandedQNameConstructFunc004',
'ExpandedQNameConstructFunc005',
'ExpandedQNameConstructFunc006',
'ExpandedQNameConstructFunc007',
'ExpandedQNameConstructFunc008',
'ExpandedQNameConstructFunc009',
'ExpandedQNameConstructFunc010',
'ExpandedQNameConstructFunc011',
'ExpandedQNameConstructFunc012',
'ExpandedQNameConstructFunc013',
'ExpandedQNameConstructFunc014',
'ExpandedQNameConstructFunc015',
'ExpandedQNameConstructFunc016',
'ExpandedQNameConstructFunc017',
'ExpandedQNameConstructFunc018',
'ExpandedQNameConstructFunc019',
'ExpandedQNameConstructFunc020',
'ExpandedQNameConstructFunc021',
'qName-1',
'K-ExpandedQNameConstructFunc-1'
]},
{group_1, [parallel], [
'K-ExpandedQNameConstructFunc-2',
'K-ExpandedQNameConstructFunc-3',
'K-ExpandedQNameConstructFunc-4',
'K-ExpandedQNameConstructFunc-5',
'K-ExpandedQNameConstructFunc-6',
'K-ExpandedQNameConstructFunc-7',
'K-ExpandedQNameConstructFunc-8',
'K-ExpandedQNameConstructFunc-9',
'K-ExpandedQNameConstructFunc-10',
'K2-ExpandedQNameConstructFunc-1',
'cbcl-qname-001'
]}
].
environment('fsx', __BaseDir) ->
[
{'decimal-formats', []},
{sources, [{filename:join(__BaseDir, "../prod/ForClause/fsx.xml"), ".", []}]},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
].
'ExpandedQNameConstructFunc001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName(\"\", \"person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc001.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<person xmlns=\"\">test</person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName(\"\", \"ht:person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc002.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<ht:person xmlns:ht=\"\">test</ht:person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName(\"\", \"person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc003.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<person>test</person>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName((), \"person\")}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc004.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<person>test</person>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"ht:person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc005.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName((), \"ht:person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc006.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"1person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc007.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"@person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc008.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"-person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc009.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"<person>\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc010.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \":person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc011.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", \"person:\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc012.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"person\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc013.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc014.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName(\"\", xs:integer(\"100\"))",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc015.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName( xs:integer(\"100\"), \"person\" )",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc016.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"element {fn:QName( \"\", string((//FolderName)[2]) )}{ \"test\" }",
{Env, Opts} = xqerl_test:handle_environment(environment('fsx', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc017.xq"),
Qry1
),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<Folder00000000001 xmlns=\"\">test</Folder00000000001>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc018'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"element {fn:QName( concat('/', string((//FolderName)[2])), \"people\" )}{ \"test\" }",
{Env, Opts} = xqerl_test:handle_environment(environment('fsx', __BaseDir)),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc018.xq"),
Qry1
),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<people xmlns=\"\">test</people>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc019'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "element {fn:QName( \"\", \"\" )}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc019.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc020'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"declare namespace ht=\"\"; element {fn:QName( \"-example\", \"ht:person\" )}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc020.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<ht:person xmlns:ht=\"-example\">test</ht:person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'ExpandedQNameConstructFunc021'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"declare namespace ht=\"\"; element {fn:QName( \"\", \"ht2:person\" )}{ \"test\" }",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "ExpandedQNameConstructFunc021.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case
xqerl_test:assert_xml(
Res,
"<ht2:person xmlns:ht2=\"\">test</ht2:person>"
)
of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'qName-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "xs:QName(20)",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "qName-1.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName()",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-2'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"/\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-2.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-3'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"/\", \"ncname\", \"error\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-3.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-4'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"QName(\"-functions\", \"prefix:local\") eq xs:QName(\"fn:local\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-4.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-5'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"/\", \"1asd:error\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-5.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-6'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"\", \"error:ncname\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-6.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-7'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName((), \"error:ncname\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-7.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-8'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"my:qName\", \"\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-8.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-9'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName(\"\", \"local\") eq xs:QName(\"local\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-9.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K-ExpandedQNameConstructFunc-10'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "QName((), \"local\") eq xs:QName(\"local\")",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K-ExpandedQNameConstructFunc-10.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'K2-ExpandedQNameConstructFunc-1'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName((), ())",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(
filename:join(__BaseDir, "K2-ExpandedQNameConstructFunc-1.xq"),
Qry1
),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPTY0004") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPTY0004 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'cbcl-qname-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "fn:QName('', ' ')",
Qry1 = Qry,
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "cbcl-qname-001.xq"), Qry1),
xqerl:run(Mod)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FOCA0002") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FOCA0002 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| |
95055e50db1c2972562eac31a34aec224dfcc944a5ca64d5c27027fd48c5efc5 | vasyaod/parental-control | WindowsHomeCommand.hs | {-# LANGUAGE OverloadedStrings #-}
module WindowsHomeCommand where
import Config
import Exec
import System.Process
import System.Exit
import System.IO
import Text.Format
import Text.Printf
import Hledger.Utils.String
import Data.List
-- Thanks to
-- and PR -control/issues/4
--
-- The next command returns list of authorized in the system
-- > wmic COMPUTERSYSTEM GET USERNAME
--
-- the command returns
-- UserName
-- nellie-book\yasha
-- The next command allows to log out a user
-- > shutdown /l
-- The following command allows to send a message to user
> msg : 10 " Test "
runKillCommand :: Exec m => Commands -> String -> m ()
runKillCommand commands userName = do
let command = format (kill commands) [userName]
let args = words' command
(errCode1, stdout1, stderr1) <- exec (head args) (tail args)
loggg (printf "User %s has been killed" userName)
return ()
runMessageCommand :: Exec m => Commands -> String -> m ()
runMessageCommand commands userName = do
let command = format (message commands) [userName]
let args = words' command
(errCode1, stdout1, stderr1) <- exec (head args) (tail args)
loggg (printf "Message command for user %s has been executed" userName)
return ()
runCheckCommand :: Exec m => String -> m Bool
runCheckCommand userName = do
(errCode1, stdout1, stderr1) <- exec "wmic" ["COMPUTERSYSTEM", "GET", "USERNAME"]
let filteredLines = filter (\line -> isInfixOf userName line) (lines stdout1)
return $ (length filteredLines) > 0
| null | https://raw.githubusercontent.com/vasyaod/parental-control/b51b0c8b7e5983b266fdcd59d8d1c5e657bb1156/schedule-daemon/src/WindowsHomeCommand.hs | haskell | # LANGUAGE OverloadedStrings #
Thanks to
and PR -control/issues/4
The next command returns list of authorized in the system
> wmic COMPUTERSYSTEM GET USERNAME
the command returns
UserName
nellie-book\yasha
The next command allows to log out a user
> shutdown /l
The following command allows to send a message to user |
module WindowsHomeCommand where
import Config
import Exec
import System.Process
import System.Exit
import System.IO
import Text.Format
import Text.Printf
import Hledger.Utils.String
import Data.List
> msg : 10 " Test "
runKillCommand :: Exec m => Commands -> String -> m ()
runKillCommand commands userName = do
let command = format (kill commands) [userName]
let args = words' command
(errCode1, stdout1, stderr1) <- exec (head args) (tail args)
loggg (printf "User %s has been killed" userName)
return ()
runMessageCommand :: Exec m => Commands -> String -> m ()
runMessageCommand commands userName = do
let command = format (message commands) [userName]
let args = words' command
(errCode1, stdout1, stderr1) <- exec (head args) (tail args)
loggg (printf "Message command for user %s has been executed" userName)
return ()
runCheckCommand :: Exec m => String -> m Bool
runCheckCommand userName = do
(errCode1, stdout1, stderr1) <- exec "wmic" ["COMPUTERSYSTEM", "GET", "USERNAME"]
let filteredLines = filter (\line -> isInfixOf userName line) (lines stdout1)
return $ (length filteredLines) > 0
|
5dc0d71aff2615cfbd109b7e2180848b319629d7c59a85f4361fa79c0a1c0a46 | mbenke/zpf2013 | IORef2.hs | import Data.IORef
import Control.Concurrent
incRef :: IORef Int -> IO ()
incRef var = do { val <- readIORef var
; threadDelay 1000
; writeIORef var (val+1) }
main = do
px <- newIORef 0
forkIO $ incRef px
forkIO $ incRef px
threadDelay 3000
readIORef px >>= print | null | https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Code/Concur/IORef2.hs | haskell | import Data.IORef
import Control.Concurrent
incRef :: IORef Int -> IO ()
incRef var = do { val <- readIORef var
; threadDelay 1000
; writeIORef var (val+1) }
main = do
px <- newIORef 0
forkIO $ incRef px
forkIO $ incRef px
threadDelay 3000
readIORef px >>= print | |
dbcae78d9dbf6ad619b4fe74f56e87ed30feee0d156c0687d264ef1238fd7766 | janestreet/ppx_csv_conv | ppx_csv_conv_deprecated.ml | open Base
open Ppxlib
open Ast_builder.Default
let extension_name = "csv"
let unsupported_type_error_msg ~name =
Printf.sprintf "The type %s is not natively supported in the csv camlp4 extension" name
;;
let useless_merge_recursive _log ~field_name:_ ~tp:_ ast = ast
let edot ~loc path_opt id =
pexp_ident
~loc
(Located.mk
~loc
(match path_opt with
| None -> Longident.Lident id
| Some p -> Longident.Ldot (p, id)))
;;
(** Generate the list of fields contained in a flattened record type *)
module Rev_headers = Ppx_conv_func.Of_simple (struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> "rev_csv_header'"
| Some param -> Printf.sprintf "rev_csv_header_of_%s'" param
;;
let atoms loc ~field_name = [%expr fun acc _ -> [%e estring ~loc field_name] :: acc]
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name ~type_name:_ ~path =
let tns = function_name None in
let recursive = edot ~loc path tns in
let is_csv_atom = edot ~loc path "is_csv_atom" in
[%expr
fun acc _ ->
if [%e is_csv_atom]
then [%e estring ~loc field_name] :: acc
else [%e recursive] acc () ()]
;;
end)
(* Generate the specification of the headers as a tree. This is useful to generate headers
consisting of multiple rows, each field grouping those below. *)
module Spec_of_headers = Ppx_conv_func.Of_simple (struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> "rev_csv_header_spec'"
| Some param -> Printf.sprintf "rev_csv_header_spec_of_%s'" param
;;
let atoms loc ~field_name =
[%expr fun acc _ -> Csvfields.Csv.Spec.Leaf [%e estring ~loc field_name] :: acc]
;;
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name ~type_name:_ ~path =
let tns = function_name None in
let recursive = edot ~loc path tns in
let is_csv_atom = edot ~loc path "is_csv_atom" in
[%expr
fun acc _ ->
if [%e is_csv_atom]
then Csvfields.Csv.Spec.Leaf [%e estring ~loc field_name] :: acc
else
Csvfields.Csv.Spec.Tree ([%e estring ~loc field_name], [%e recursive] [] () ())
:: acc]
;;
end)
(** Generate the some type using a csv row (a list of strings) *)
module Type_of_csv_row = Ppx_conv_func.Of_complete (struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> failwith "Csv conversion of_row requires some name"
| Some param -> Printf.sprintf "%s_of_row'" param
;;
let unit loc ~field_name:_ = [%expr Csvfields.Csv.unit_of_row]
let bool loc ~field_name:_ = [%expr Csvfields.Csv.bool_of_row]
let string loc ~field_name:_ = [%expr Csvfields.Csv.string_of_row]
let char loc ~field_name:_ = [%expr Csvfields.Csv.char_of_row]
let int loc ~field_name:_ = [%expr Csvfields.Csv.int_of_row]
let float loc ~field_name:_ = [%expr Csvfields.Csv.float_of_row]
let int32 loc ~field_name:_ = [%expr Csvfields.Csv.int32_of_row]
let int64 loc ~field_name:_ = [%expr Csvfields.Csv.int64_of_row]
let nativeint loc ~field_name:_ = [%expr Csvfields.Csv.nativeint_of_row]
let big_int loc ~field_name:_ = [%expr Csvfields.Csv.big_int_of_row]
let nat loc ~field_name:_ = [%expr Csvfields.Csv.nat_of_row]
let num loc ~field_name:_ = [%expr Csvfields.Csv.num_of_row]
let ratio loc ~field_name:_ = [%expr Csvfields.Csv.ratio_of_row]
let list loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "list"
let array loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "list"
let option loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "option"
let lazy_t loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "lazy_t"
let ref loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "ref"
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name:_ ~type_name ~path =
let tns = function_name (Some type_name) in
edot ~loc path tns
;;
end)
module type B = sig
val writer : Location.t -> arg_label * expression
val is_first : Location.t -> arg_label * expression
val is_last : Location.t -> arg_label * expression
end
module Make_row_of (S : B) = struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> failwith "Csv conversion write_row_of_ requires some name"
| Some param -> Printf.sprintf "write_row_of_%s'" param
;;
let add_arguments expr loc =
pexp_apply ~loc expr [ S.is_first loc; S.is_last loc; S.writer loc ]
;;
let unit loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_unit] loc
let bool loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_bool] loc
let string loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_string] loc
let char loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_char] loc
let int loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_int] loc
let float loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_float] loc
let int32 loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_int32] loc
let int64 loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_int64] loc
let nativeint loc ~field_name:_ =
add_arguments [%expr Csvfields.Csv.row_of_nativeint] loc
;;
let big_int loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_big_int] loc
let nat loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_nat] loc
let num loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_num] loc
let ratio loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_ratio] loc
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name:_ ~type_name ~path =
let tns = function_name (Some type_name) in
add_arguments (edot ~loc path tns) loc
;;
let list loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "list"
let array loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "array"
let option loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "option"
let lazy_t loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "lazy_t"
let ref loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "ref"
end
let falseexpr loc = [%expr false]
module Unique_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", [%expr is_first]
let is_last loc = Labelled "is_last", [%expr is_last]
end))
module First_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", [%expr is_first]
let is_last loc = Labelled "is_last", falseexpr loc
end))
module Middle_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", falseexpr loc
let is_last loc = Labelled "is_last", falseexpr loc
end))
module Last_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", falseexpr loc
let is_last loc = Labelled "is_last", [%expr is_last]
end))
let csv_record_sig loc ~record_name =
let st =
psig_include
~loc
(include_infos
~loc
(pmty_with
~loc
(pmty_ident ~loc (Located.lident ~loc "Csvfields.Csv.Csvable"))
[ Pwith_typesubst
( Located.lident ~loc "t"
, type_declaration
~loc
~name:(Located.mk ~loc "t")
~params:[]
~manifest:
(Some (ptyp_constr ~loc (Located.lident ~loc record_name) []))
~cstrs:[]
~kind:Ptype_abstract
~private_:Public )
]))
in
[ st ]
;;
let rev_csv_header' ~record_name ~lds loc =
let name = [%pat? rev_csv_header'] in
let conversion_of_type = Rev_headers.conversion_of_type in
Ppx_conv_func.Gen_struct.generate_using_fold
~record_name
~pass_acc:true
~pass_anonymous:true
~conversion_of_type
~name
~lds
loc
;;
let rev_csv_header_spec' ~record_name ~lds loc =
let name = [%pat? rev_csv_header_spec'] in
let conversion_of_type = Spec_of_headers.conversion_of_type in
Ppx_conv_func.Gen_struct.generate_using_fold
~record_name
~pass_acc:true
~pass_anonymous:true
~conversion_of_type
~name
~lds
loc
;;
let fields_module ~record_name ~loc ~suffix =
Ast_helper.Exp.ident
{ loc
; txt =
Longident.parse
(Printf.sprintf
"%s.%s"
(match String.equal record_name "t" with
| true -> "Fields"
| false -> Printf.sprintf "Fields_of_%s" record_name)
suffix)
}
;;
let row_of_t' ~record_name ~lds loc =
let init = [%expr [%e fields_module ~record_name ~loc ~suffix:"Direct.iter"] t] in
let body =
Ppx_conv_func.Gen_struct.make_body
~lds
~init
loc
~unique_f:Unique_row_of.conversion_of_type
~first_f:First_row_of.conversion_of_type
~last_f:Last_row_of.conversion_of_type
Middle_row_of.conversion_of_type
in
let anonymous = Ppx_conv_func.Gen_struct.anonymous loc in
let func =
[%expr fun ~is_first ~is_last ~writer [%p anonymous] [%p anonymous] t -> [%e body]]
in
[%stri let write_row_of_t' = [%e func]]
;;
let t_of_row' ~record_name ~lds loc =
let init =
[%expr [%e fields_module ~record_name ~loc ~suffix:"make_creator"] strings]
in
let body =
let f = Type_of_csv_row.conversion_of_type in
Ppx_conv_func.Gen_struct.make_body ~lds ~init loc f
in
let func =
Ppx_conv_func.lambda
loc
[ Ppx_conv_func.Gen_struct.anonymous loc; [%pat? strings] ]
body
in
[%stri let t_of_row' = [%e func]]
;;
let csv_record ~tps:_ ~record_name loc lds =
let t_of_row' = t_of_row' ~record_name ~lds loc in
let is_csv_atom = [%stri let is_csv_atom = false] in
let row_of_t' = row_of_t' ~record_name ~lds loc in
let rev_csv_header' = rev_csv_header' ~record_name ~lds loc in
let rev_csv_header_spec' = rev_csv_header_spec' ~record_name ~lds loc in
let t =
if String.( <> ) record_name "t"
then [%str type t = [%t ptyp_constr ~loc (Located.lident ~loc record_name) []]]
else
[%str
type _t = t
type t = _t]
in
let with_constraints =
[ Pwith_typesubst
( Located.lident ~loc "t"
, type_declaration
~loc
~name:(Located.mk ~loc "t")
~manifest:(Some (ptyp_constr ~loc (Located.lident ~loc record_name) []))
~kind:Ptype_abstract
~private_:Public
~params:[]
~cstrs:[] )
]
in
let applied_functor =
pmod_apply
~loc
(pmod_ident ~loc (Located.lident ~loc "Csvfields.Csv.Record"))
(pmod_structure
~loc
(t @ [ is_csv_atom; rev_csv_header'; rev_csv_header_spec'; t_of_row'; row_of_t' ]))
in
let st =
pstr_include
~loc
(include_infos
~loc
(pmod_constraint
~loc
applied_functor
(pmty_with
~loc
(pmty_ident ~loc (Located.lident ~loc "Csvfields.Csv.Csvable"))
with_constraints)))
in
[ st
; [%stri let [%p pvar ~loc (record_name ^ "_of_row")] = t_of_row]
; [%stri let [%p pvar ~loc ("row_of_" ^ record_name)] = row_of_t]
; [%stri let [%p pvar ~loc (record_name ^ "_of_row'")] = t_of_row']
; [%stri let [%p pvar ~loc ("write_row_of_" ^ record_name ^ "'")] = write_row_of_t']
]
;;
let csv =
let str_type_decl =
Deriving.Generator.make
Deriving.Args.empty
(Ppx_conv_func.Gen_struct.generate ~extension_name ~record:csv_record)
~deps:[ Ppx_fields_conv.fields ]
in
let sig_type_decl =
Deriving.Generator.make
Deriving.Args.empty
(Ppx_conv_func.Gen_sig.generate
~extension_name
~nil:(fun ~tps:_ ~record_name loc -> csv_record_sig loc ~record_name)
~record:(fun ~tps:_ ~record_name loc _ -> csv_record_sig loc ~record_name))
in
Deriving.add extension_name ~str_type_decl ~sig_type_decl
;;
| null | https://raw.githubusercontent.com/janestreet/ppx_csv_conv/9f7628490dcb83098b46295d7b3db8b5230c2029/src/ppx_csv_conv_deprecated.ml | ocaml | * Generate the list of fields contained in a flattened record type
Generate the specification of the headers as a tree. This is useful to generate headers
consisting of multiple rows, each field grouping those below.
* Generate the some type using a csv row (a list of strings) | open Base
open Ppxlib
open Ast_builder.Default
let extension_name = "csv"
let unsupported_type_error_msg ~name =
Printf.sprintf "The type %s is not natively supported in the csv camlp4 extension" name
;;
let useless_merge_recursive _log ~field_name:_ ~tp:_ ast = ast
let edot ~loc path_opt id =
pexp_ident
~loc
(Located.mk
~loc
(match path_opt with
| None -> Longident.Lident id
| Some p -> Longident.Ldot (p, id)))
;;
module Rev_headers = Ppx_conv_func.Of_simple (struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> "rev_csv_header'"
| Some param -> Printf.sprintf "rev_csv_header_of_%s'" param
;;
let atoms loc ~field_name = [%expr fun acc _ -> [%e estring ~loc field_name] :: acc]
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name ~type_name:_ ~path =
let tns = function_name None in
let recursive = edot ~loc path tns in
let is_csv_atom = edot ~loc path "is_csv_atom" in
[%expr
fun acc _ ->
if [%e is_csv_atom]
then [%e estring ~loc field_name] :: acc
else [%e recursive] acc () ()]
;;
end)
module Spec_of_headers = Ppx_conv_func.Of_simple (struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> "rev_csv_header_spec'"
| Some param -> Printf.sprintf "rev_csv_header_spec_of_%s'" param
;;
let atoms loc ~field_name =
[%expr fun acc _ -> Csvfields.Csv.Spec.Leaf [%e estring ~loc field_name] :: acc]
;;
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name ~type_name:_ ~path =
let tns = function_name None in
let recursive = edot ~loc path tns in
let is_csv_atom = edot ~loc path "is_csv_atom" in
[%expr
fun acc _ ->
if [%e is_csv_atom]
then Csvfields.Csv.Spec.Leaf [%e estring ~loc field_name] :: acc
else
Csvfields.Csv.Spec.Tree ([%e estring ~loc field_name], [%e recursive] [] () ())
:: acc]
;;
end)
module Type_of_csv_row = Ppx_conv_func.Of_complete (struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> failwith "Csv conversion of_row requires some name"
| Some param -> Printf.sprintf "%s_of_row'" param
;;
let unit loc ~field_name:_ = [%expr Csvfields.Csv.unit_of_row]
let bool loc ~field_name:_ = [%expr Csvfields.Csv.bool_of_row]
let string loc ~field_name:_ = [%expr Csvfields.Csv.string_of_row]
let char loc ~field_name:_ = [%expr Csvfields.Csv.char_of_row]
let int loc ~field_name:_ = [%expr Csvfields.Csv.int_of_row]
let float loc ~field_name:_ = [%expr Csvfields.Csv.float_of_row]
let int32 loc ~field_name:_ = [%expr Csvfields.Csv.int32_of_row]
let int64 loc ~field_name:_ = [%expr Csvfields.Csv.int64_of_row]
let nativeint loc ~field_name:_ = [%expr Csvfields.Csv.nativeint_of_row]
let big_int loc ~field_name:_ = [%expr Csvfields.Csv.big_int_of_row]
let nat loc ~field_name:_ = [%expr Csvfields.Csv.nat_of_row]
let num loc ~field_name:_ = [%expr Csvfields.Csv.num_of_row]
let ratio loc ~field_name:_ = [%expr Csvfields.Csv.ratio_of_row]
let list loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "list"
let array loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "list"
let option loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "option"
let lazy_t loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "lazy_t"
let ref loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "ref"
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name:_ ~type_name ~path =
let tns = function_name (Some type_name) in
edot ~loc path tns
;;
end)
module type B = sig
val writer : Location.t -> arg_label * expression
val is_first : Location.t -> arg_label * expression
val is_last : Location.t -> arg_label * expression
end
module Make_row_of (S : B) = struct
let unsupported_type_error_msg = unsupported_type_error_msg
let conversion_name = extension_name
let function_name = function
| None -> failwith "Csv conversion write_row_of_ requires some name"
| Some param -> Printf.sprintf "write_row_of_%s'" param
;;
let add_arguments expr loc =
pexp_apply ~loc expr [ S.is_first loc; S.is_last loc; S.writer loc ]
;;
let unit loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_unit] loc
let bool loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_bool] loc
let string loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_string] loc
let char loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_char] loc
let int loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_int] loc
let float loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_float] loc
let int32 loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_int32] loc
let int64 loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_int64] loc
let nativeint loc ~field_name:_ =
add_arguments [%expr Csvfields.Csv.row_of_nativeint] loc
;;
let big_int loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_big_int] loc
let nat loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_nat] loc
let num loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_num] loc
let ratio loc ~field_name:_ = add_arguments [%expr Csvfields.Csv.row_of_ratio] loc
let merge_recursive = useless_merge_recursive
let recursive loc ~field_name:_ ~type_name ~path =
let tns = function_name (Some type_name) in
add_arguments (edot ~loc path tns) loc
;;
let list loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "list"
let array loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "array"
let option loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "option"
let lazy_t loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "lazy_t"
let ref loc ~field_name:_ = Ppx_conv_func.raise_unsupported ~loc "ref"
end
let falseexpr loc = [%expr false]
module Unique_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", [%expr is_first]
let is_last loc = Labelled "is_last", [%expr is_last]
end))
module First_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", [%expr is_first]
let is_last loc = Labelled "is_last", falseexpr loc
end))
module Middle_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", falseexpr loc
let is_last loc = Labelled "is_last", falseexpr loc
end))
module Last_row_of = Ppx_conv_func.Of_complete (Make_row_of (struct
let writer loc = Labelled "writer", [%expr writer]
let is_first loc = Labelled "is_first", falseexpr loc
let is_last loc = Labelled "is_last", [%expr is_last]
end))
let csv_record_sig loc ~record_name =
let st =
psig_include
~loc
(include_infos
~loc
(pmty_with
~loc
(pmty_ident ~loc (Located.lident ~loc "Csvfields.Csv.Csvable"))
[ Pwith_typesubst
( Located.lident ~loc "t"
, type_declaration
~loc
~name:(Located.mk ~loc "t")
~params:[]
~manifest:
(Some (ptyp_constr ~loc (Located.lident ~loc record_name) []))
~cstrs:[]
~kind:Ptype_abstract
~private_:Public )
]))
in
[ st ]
;;
let rev_csv_header' ~record_name ~lds loc =
let name = [%pat? rev_csv_header'] in
let conversion_of_type = Rev_headers.conversion_of_type in
Ppx_conv_func.Gen_struct.generate_using_fold
~record_name
~pass_acc:true
~pass_anonymous:true
~conversion_of_type
~name
~lds
loc
;;
let rev_csv_header_spec' ~record_name ~lds loc =
let name = [%pat? rev_csv_header_spec'] in
let conversion_of_type = Spec_of_headers.conversion_of_type in
Ppx_conv_func.Gen_struct.generate_using_fold
~record_name
~pass_acc:true
~pass_anonymous:true
~conversion_of_type
~name
~lds
loc
;;
let fields_module ~record_name ~loc ~suffix =
Ast_helper.Exp.ident
{ loc
; txt =
Longident.parse
(Printf.sprintf
"%s.%s"
(match String.equal record_name "t" with
| true -> "Fields"
| false -> Printf.sprintf "Fields_of_%s" record_name)
suffix)
}
;;
let row_of_t' ~record_name ~lds loc =
let init = [%expr [%e fields_module ~record_name ~loc ~suffix:"Direct.iter"] t] in
let body =
Ppx_conv_func.Gen_struct.make_body
~lds
~init
loc
~unique_f:Unique_row_of.conversion_of_type
~first_f:First_row_of.conversion_of_type
~last_f:Last_row_of.conversion_of_type
Middle_row_of.conversion_of_type
in
let anonymous = Ppx_conv_func.Gen_struct.anonymous loc in
let func =
[%expr fun ~is_first ~is_last ~writer [%p anonymous] [%p anonymous] t -> [%e body]]
in
[%stri let write_row_of_t' = [%e func]]
;;
let t_of_row' ~record_name ~lds loc =
let init =
[%expr [%e fields_module ~record_name ~loc ~suffix:"make_creator"] strings]
in
let body =
let f = Type_of_csv_row.conversion_of_type in
Ppx_conv_func.Gen_struct.make_body ~lds ~init loc f
in
let func =
Ppx_conv_func.lambda
loc
[ Ppx_conv_func.Gen_struct.anonymous loc; [%pat? strings] ]
body
in
[%stri let t_of_row' = [%e func]]
;;
let csv_record ~tps:_ ~record_name loc lds =
let t_of_row' = t_of_row' ~record_name ~lds loc in
let is_csv_atom = [%stri let is_csv_atom = false] in
let row_of_t' = row_of_t' ~record_name ~lds loc in
let rev_csv_header' = rev_csv_header' ~record_name ~lds loc in
let rev_csv_header_spec' = rev_csv_header_spec' ~record_name ~lds loc in
let t =
if String.( <> ) record_name "t"
then [%str type t = [%t ptyp_constr ~loc (Located.lident ~loc record_name) []]]
else
[%str
type _t = t
type t = _t]
in
let with_constraints =
[ Pwith_typesubst
( Located.lident ~loc "t"
, type_declaration
~loc
~name:(Located.mk ~loc "t")
~manifest:(Some (ptyp_constr ~loc (Located.lident ~loc record_name) []))
~kind:Ptype_abstract
~private_:Public
~params:[]
~cstrs:[] )
]
in
let applied_functor =
pmod_apply
~loc
(pmod_ident ~loc (Located.lident ~loc "Csvfields.Csv.Record"))
(pmod_structure
~loc
(t @ [ is_csv_atom; rev_csv_header'; rev_csv_header_spec'; t_of_row'; row_of_t' ]))
in
let st =
pstr_include
~loc
(include_infos
~loc
(pmod_constraint
~loc
applied_functor
(pmty_with
~loc
(pmty_ident ~loc (Located.lident ~loc "Csvfields.Csv.Csvable"))
with_constraints)))
in
[ st
; [%stri let [%p pvar ~loc (record_name ^ "_of_row")] = t_of_row]
; [%stri let [%p pvar ~loc ("row_of_" ^ record_name)] = row_of_t]
; [%stri let [%p pvar ~loc (record_name ^ "_of_row'")] = t_of_row']
; [%stri let [%p pvar ~loc ("write_row_of_" ^ record_name ^ "'")] = write_row_of_t']
]
;;
let csv =
let str_type_decl =
Deriving.Generator.make
Deriving.Args.empty
(Ppx_conv_func.Gen_struct.generate ~extension_name ~record:csv_record)
~deps:[ Ppx_fields_conv.fields ]
in
let sig_type_decl =
Deriving.Generator.make
Deriving.Args.empty
(Ppx_conv_func.Gen_sig.generate
~extension_name
~nil:(fun ~tps:_ ~record_name loc -> csv_record_sig loc ~record_name)
~record:(fun ~tps:_ ~record_name loc _ -> csv_record_sig loc ~record_name))
in
Deriving.add extension_name ~str_type_decl ~sig_type_decl
;;
|
7b06d9e6f17675aaa52f0228bc860a31842e5a7ceb99066e6690f9b10bf79e51 | yesodweb/serversession | Internal.hs | -- | Internal module exposing the guts of the package. Use at
-- your own risk. No API stability guarantees apply.
--
-- @UndecidableInstances@ is required in order to implement @Eq@,
@Ord@ , @Show@ , etc . on data types that have @Decomposed@
-- fields, and should be fairly safe.
module Web.ServerSession.Core.Internal
( SessionId(..)
, checkSessionId
, generateSessionId
, AuthId
, Session(..)
, SessionMap(..)
, IsSessionData(..)
, DecomposedSession(..)
, Storage(..)
, StorageException(..)
, State(..)
, createState
, setCookieName
, setAuthKey
, setIdleTimeout
, setAbsoluteTimeout
, setTimeoutResolution
, setPersistentCookies
, setHttpOnlyCookies
, setSecureCookies
, getCookieName
, getHttpOnlyCookies
, getSecureCookies
, loadSession
, checkExpired
, nextExpires
, cookieExpires
, saveSession
, SaveSessionToken(..)
, invalidateIfNeeded
, saveSessionOnDb
, forceInvalidateKey
, ForceInvalidate(..)
) where
import Control.Applicative as A
import Control.Monad (guard, when)
import Control.Monad.IO.Class (MonadIO(..))
import Data.ByteString (ByteString)
import Data.Hashable (Hashable(..))
import Data.Kind (Type)
import Data.Maybe (catMaybes, fromMaybe, isJust)
import Data.Text (Text)
import Data.Time (UTCTime, getCurrentTime)
import Data.Time.Clock (NominalDiffTime, addUTCTime, diffUTCTime)
import Data.Typeable (Typeable)
import Web.PathPieces (PathPiece(..))
import qualified Control.Exception as E
import qualified Crypto.Nonce as N
import qualified Data.Aeson as A
import qualified Data.ByteString.Base64.URL as B64URL
import qualified Data.ByteString.Char8 as B8
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
----------------------------------------------------------------------
| The ID of a session . Always 18 bytes base64url - encoded as
24 characters . The @sess@ type variable is a phantom type for
-- the session data type this session ID points to.
--
-- Implementation notes:
--
-- * Use 'fromPathPiece' for parsing untrusted input.
--
-- * Use 'generateSessionId' for securely generating new
-- session IDs.
newtype SessionId sess = S { unS :: Text }
deriving (Eq, Ord, Show, Read, Typeable)
-- | Sanity checks input on 'fromPathPiece' (untrusted input).
instance PathPiece (SessionId sess) where
toPathPiece = unS
fromPathPiece = checkSessionId
instance A.FromJSON (SessionId sess) where
parseJSON = fmap S . A.parseJSON
instance A.ToJSON (SessionId sess) where
toJSON = A.toJSON . unS
instance Hashable (SessionId sess) where
hashWithSalt s = hashWithSalt s . unS
-- | (Internal) Check that the given text is a base64url-encoded
representation of 18 bytes .
checkSessionId :: Text -> Maybe (SessionId sess)
checkSessionId text = do
guard (T.length text == 24)
let bs = TE.encodeUtf8 text
decoded <- either (const Nothing) Just $ B64URL.decode bs
guard (B8.length decoded == 18)
return $ S text
| Securely generate a new SessionId .
generateSessionId :: N.Generator -> IO (SessionId sess)
generateSessionId = fmap S . N.nonce128urlT
----------------------------------------------------------------------
-- | Value of the 'authKey' session key.
type AuthId = ByteString
-- | Representation of a saved session.
--
-- This representation is used by the @serversession@ family of
-- packages, transferring data between this core package and
storage backend packages . The @sess@ type variable describes
-- the session data type.
data Session sess =
Session
{ sessionKey :: SessionId sess
-- ^ Session ID, primary key.
, sessionAuthId :: Maybe AuthId
-- ^ Value of 'authKey' session key, separate from the rest.
, sessionData :: Decomposed sess
-- ^ Rest of the session data.
, sessionCreatedAt :: UTCTime
-- ^ When this session was created.
, sessionAccessedAt :: UTCTime
-- ^ When this session was last accessed.
} deriving (Typeable)
deriving instance Eq (Decomposed sess) => Eq (Session sess)
deriving instance Ord (Decomposed sess) => Ord (Session sess)
deriving instance Show (Decomposed sess) => Show (Session sess)
-- | A @newtype@ for a common session map.
--
-- This is a common representation of a session. Although
-- @serversession@ has generalized session data types, you can
-- use this one if you don't want to worry about it. We strive
-- to support this session data type on all frontends and storage
-- backends.
newtype SessionMap =
SessionMap { unSessionMap :: HM.HashMap Text ByteString }
deriving (Eq, Show, Read, Typeable)
----------------------------------------------------------------------
-- | Class for data types to be used as session data
( cf . ' sessionData ' , ' SessionData ' ) .
--
-- The @Show@ constrain is needed for 'StorageException'.
class ( Show (Decomposed sess)
, Typeable (Decomposed sess)
, Typeable sess
) => IsSessionData sess where
-- | The type of the session data after being decomposed. This
-- may be the same as @sess@.
type Decomposed sess :: Type
-- | Empty session data.
emptySession :: sess
| Decompose session data into :
--
-- * The auth ID of the logged in user (cf. 'setAuthKey',
-- 'dsAuthId').
--
-- * If the session is being forced to be invalidated
( cf . ' forceInvalidateKey ' , ' ForceInvalidate ' ) .
--
-- * The rest of the session data (cf. 'Decomposed').
decomposeSession
:: Text -- ^ The auth key (cf. 'setAuthKey').
-> sess -- ^ Session data to be decomposed.
-> DecomposedSession sess -- ^ Decomposed session data.
-- | Recompose a decomposed session again into a proper @sess@.
recomposeSession
:: Text -- ^ The auth key (cf. 'setAuthKey').
^ The @AuthId@ , if any .
-> Decomposed sess -- ^ Decomposed session data to be recomposed.
-> sess -- ^ Recomposed session data.
-- | Returns @True@ when both session datas are to be
-- considered the same.
--
-- This is used to optimize storage calls
-- (cf. 'setTimeoutResolution'). Always returning @False@ will
-- disable the optimization but won't have any other adverse
-- effects.
--
-- For data types implementing 'Eq', this is usually a good
-- implementation:
--
-- @
-- isSameDecomposed _ = (==)
-- @
isSameDecomposed :: proxy sess -> Decomposed sess -> Decomposed sess -> Bool
-- | Returns @True@ if the decomposed session data is to be
-- considered @empty@.
--
-- This is used to avoid storing empty session data if at all
-- possible. Always returning @False@ will disable the
-- optimization but won't have any other adverse effects.
isDecomposedEmpty :: proxy sess -> Decomposed sess -> Bool
-- | A 'SessionMap' decomposes into a 'SessionMap' minus the keys
-- that were removed. The auth key is added back when
-- recomposing.
instance IsSessionData SessionMap where
type Decomposed SessionMap = SessionMap
emptySession = SessionMap HM.empty
isSameDecomposed _ = (==)
decomposeSession authKey_ (SessionMap sm1) =
let authId = HM.lookup authKey_ sm1
force = maybe DoNotForceInvalidate (read . B8.unpack) $
HM.lookup forceInvalidateKey sm1
sm2 = HM.delete authKey_ $
HM.delete forceInvalidateKey sm1
in DecomposedSession
{ dsAuthId = authId
, dsForceInvalidate = force
, dsDecomposed = SessionMap sm2 }
recomposeSession authKey_ mauthId (SessionMap sm) =
SessionMap $ maybe id (HM.insert authKey_) mauthId sm
isDecomposedEmpty _ = HM.null . unSessionMap
| A session data type @sess@ with its special variables taken apart .
data DecomposedSession sess =
DecomposedSession
{ dsAuthId :: !(Maybe ByteString)
, dsForceInvalidate :: !ForceInvalidate
, dsDecomposed :: !(Decomposed sess)
} deriving (Typeable)
deriving instance Eq (Decomposed sess) => Eq (DecomposedSession sess)
deriving instance Ord (Decomposed sess) => Ord (DecomposedSession sess)
deriving instance Show (Decomposed sess) => Show (DecomposedSession sess)
----------------------------------------------------------------------
-- | A storage backend @sto@ for server-side sessions. The
@sess@ session data type and\/or its ' Decomposed ' version may
-- be constrained depending on the storage backend capabilities.
class ( Typeable sto
, MonadIO (TransactionM sto)
, IsSessionData (SessionData sto)
) => Storage sto where
-- | The session data type used by this storage.
type SessionData sto :: Type
-- | Monad where transactions happen for this backend.
We do not require transactions to be ACID .
type TransactionM sto :: Type -> Type
| Run a transaction on the IO monad .
runTransactionM :: sto -> TransactionM sto a -> IO a
-- | Get the session for the given session ID. Returns
-- @Nothing@ if the session is not found.
getSession
:: sto
-> SessionId (SessionData sto)
-> TransactionM sto (Maybe (Session (SessionData sto)))
-- | Delete the session with given session ID. Does not do
-- anything if the session is not found.
deleteSession :: sto -> SessionId (SessionData sto) -> TransactionM sto ()
-- | Delete all sessions of the given auth ID. Does not do
-- anything if there are no sessions of the given auth ID.
deleteAllSessionsOfAuthId :: sto -> AuthId -> TransactionM sto ()
-- | Insert a new session. Throws 'SessionAlreadyExists' if
-- there already exists a session with the same session ID (we
-- only call this method after generating a fresh session ID).
insertSession :: sto -> Session (SessionData sto) -> TransactionM sto ()
-- | Replace the contents of a session. Throws
' SessionDoesNotExist ' if there is no session with the given
-- session ID (we only call this method when updating a session
-- that is known to exist).
--
-- It is possible to have concurrent requests using the same
-- session ID such that:
--
-- @
request 1 :
request 2 : loadSession
request 2 : forceInvalidate
request 2 : saveSession
request 1 : saveSession
-- @
--
The request 2 's call to ' saveSession ' will have called
-- 'deleteSession' as invalidation was forced. However,
request 1 has no idea and will try to @replaceSession@. The
-- following behaviors are possible:
--
-- 1. Make @replaceSession@ insert the session again.
However , this will undo the invalidation of request 2 . As
-- invalidations are done for security reasons, this is a bad
-- idea.
--
-- 2. Make @replaceSession@ silently discard the session.
-- The reasoning is that, as the session was going to be
invalidated if request 2 came after request 1 , we can
-- discard its contents. However, we can't be sure that
request 2 would have had the same effect if it had seen
the session changes made by request 1 ( and vice versa ) .
--
-- 3. Make @replaceSession@ throw an error. This error is
-- going to be unrecoverable since usually the session
-- processing is done at the end of the request processing by
the web framework , thus leading to a 500 Internal Server
-- Error. However, this signals to the caller that something
-- went wrong, which is correct.
--
-- Most of the time this discussion does not matter.
Invalidations usually occur at times where only one request
-- is flying.
replaceSession :: sto -> Session (SessionData sto) -> TransactionM sto ()
-- | Common exceptions that may be thrown by any storage.
data StorageException sto =
-- | Exception thrown by 'insertSession' whenever a session
-- with same ID already exists.
SessionAlreadyExists
{ seExistingSession :: Session (SessionData sto)
, seNewSession :: Session (SessionData sto) }
-- | Exception thrown by 'replaceSession' whenever trying to
-- replace a session that is not present on the storage.
| SessionDoesNotExist
{ seNewSession :: Session (SessionData sto) }
deriving (Typeable)
deriving instance Eq (Decomposed (SessionData sto)) => Eq (StorageException sto)
deriving instance Ord (Decomposed (SessionData sto)) => Ord (StorageException sto)
deriving instance Show (Decomposed (SessionData sto)) => Show (StorageException sto)
instance Storage sto => E.Exception (StorageException sto) where
----------------------------------------------------------------------
-- TODO: delete expired sessions.
-- | The server-side session backend needs to maintain some state
-- in order to work:
--
-- * A nonce generator for the session IDs.
--
-- * A reference to the storage backend.
--
-- * The name of cookie where the session ID will be saved ('setCookieName').
--
-- * Authentication session variable ('setAuthKey').
--
-- * Idle and absolute timeouts ('setIdleTimeout' and 'setAbsoluteTimeout').
--
-- * Timeout resolution ('setTimeoutResolution').
--
-- * Whether cookies should be persistent
-- ('setPersistentCookies'), HTTP-only ('setHTTPOnlyCookies')
-- and/or secure ('setSecureCookies').
--
Create a new ' State ' using ' createState ' .
data State sto =
State
{ generator :: !N.Generator
, storage :: !sto
, cookieName :: !Text
, authKey :: !Text
, idleTimeout :: !(Maybe NominalDiffTime)
, absoluteTimeout :: !(Maybe NominalDiffTime)
, timeoutResolution :: !(Maybe NominalDiffTime)
, persistentCookies :: !Bool
, httpOnlyCookies :: !Bool
, secureCookies :: !Bool
} deriving (Typeable)
| Create a new ' State ' for the server - side session backend
-- using the given storage backend.
createState :: MonadIO m => sto -> m (State sto)
createState sto = do
gen <- N.new
return State
{ generator = gen
, storage = sto
, cookieName = "JSESSIONID"
, authKey = "_ID"
7 days
60 days
10 minutes
, persistentCookies = True
, httpOnlyCookies = True
, secureCookies = False
}
-- | Set the name of cookie where the session ID will be saved.
Defaults to " , which is a generic cookie name
-- used by many frameworks thus making it harder to fingerprint
-- this implementation.
setCookieName :: Text -> State sto -> State sto
setCookieName val state = state { cookieName = val }
-- | Set the name of the session variable that keeps track of the
-- logged user.
--
-- This setting is used by session data types that are
-- @Map@-alike, using a @lookup@ function. However, the
-- 'IsSessionData' instance of a session data type may choose not
-- to use it. For example, if you implemented a custom data
type , you could return the @AuthId@ without needing a lookup .
--
Defaults to \"_ID\ " ( used by @yesod - auth@ ) .
setAuthKey :: Text -> State sto -> State sto
setAuthKey val state = state { authKey = val }
-- | Set the idle timeout for all sessions. This is used both on
-- the client side (by setting the cookie expires fields) and on
-- the server side (the idle timeout is enforced even if the
-- cookie expiration is ignored). Setting to @Nothing@ removes
-- the idle timeout entirely.
--
-- \"[The idle timemout] defines the amount of time a session
-- will remain active in case there is no activity in the
-- session, closing and invalidating the session upon the defined
-- idle period since the last HTTP request received by the web
-- application for a given session ID.\"
-- (<#Idle_Timeout Source>)
--
Defaults to 7 days .
setIdleTimeout :: Maybe NominalDiffTime -> State sto -> State sto
setIdleTimeout (Just d) _ | d <= 0 = error "serversession/setIdleTimeout: Timeout should be positive."
setIdleTimeout val state = state { idleTimeout = val }
-- | Set the absolute timeout for all sessions. This is used both on
-- the client side (by setting the cookie expires fields) and on
-- the server side (the absolute timeout is enforced even if the
-- cookie expiration is ignored). Setting to @Nothing@ removes
-- the absolute timeout entirely.
--
\"[The absolute timeout ] defines the maximum amount of time a
-- session can be active, closing and invalidating the session
-- upon the defined absolute period since the given session was
-- initially created by the web application. After invalidating
-- the session, the user is forced to (re)authenticate again in
-- the web application and establish a new session.\"
-- (<#Absolute_Timeout Source>)
--
Defaults to 60 days .
setAbsoluteTimeout :: Maybe NominalDiffTime -> State sto -> State sto
setAbsoluteTimeout (Just d) _ | d <= 0 = error "serversession/setAbsoluteTimeout: Timeout should be positive."
setAbsoluteTimeout val state = state { absoluteTimeout = val }
-- | Set the timeout resolution.
--
-- We need to save both the creation and last access times on
-- sessions in order to implement idle and absolute timeouts.
-- This means that we have to save the updated session on the
-- storage backend even if the request didn't change any session
-- variable, if only to update the last access time.
--
-- This setting provides an optimization where the session is not
-- updated on the storage backend provided that:
--
-- * No session variables were changed.
--
-- * The difference between the /current/ time and the last
-- /saved/ access time is less than the timeout resolution.
--
For example , with a timeout resolution of 1 minute , every
request that does not change the session variables within 1
-- minute of the last update will not generate any updates on the
-- storage backend.
--
-- If the timeout resolution is @Nothing@, then this optimization
-- becomes disabled and the session will always be updated.
--
Defaults to 10 minutes .
setTimeoutResolution :: Maybe NominalDiffTime -> State sto -> State sto
setTimeoutResolution (Just d) _ | d <= 0 = error "serversession/setTimeoutResolution: Resolution should be positive."
setTimeoutResolution val state = state { timeoutResolution = val }
| Set whether by default cookies should be persistent ( @True@ ) or
-- non-persistent (@False@). Persistent cookies are saved across
-- browser sessions. Non-persistent cookies are discarded when
-- the browser is closed.
--
-- If you set cookies to be persistent and do not define any
-- timeouts ('setIdleTimeout' or 'setAbsoluteTimeout'), then the
cookie is set to expire in 10 years .
--
-- Defaults to @True@.
setPersistentCookies :: Bool -> State sto -> State sto
setPersistentCookies val state = state { persistentCookies = val }
| Set whether cookies should be HTTP - only ( @True@ ) or not
-- (@False@). Cookies marked as HTTP-only (\"HttpOnly\") are not
-- accessible from client-side scripting languages such as
JavaScript , thus preventing a large class of XSS attacks .
-- It's highly recommended to set this attribute to @True@.
--
-- Defaults to @True@.
setHttpOnlyCookies :: Bool -> State sto -> State sto
setHttpOnlyCookies val state = state { httpOnlyCookies = val }
| Set whether cookies should be mared \"Secure\ " ( @True@ ) or not
-- (@False@). Cookies marked as \"Secure\" are not sent via
-- plain HTTP connections, only via HTTPS connections. It's
-- highly recommended to set this attribute to @True@. However,
-- since many sites do not operate over HTTPS, the default is
--
Defaults to
setSecureCookies :: Bool -> State sto -> State sto
setSecureCookies val state = state { secureCookies = val }
-- | Cf. 'setCookieName'.
getCookieName :: State sto -> Text
getCookieName = cookieName
-- | Cf. 'setHttpOnlyCookies'.
getHttpOnlyCookies :: State sto -> Bool
getHttpOnlyCookies = httpOnlyCookies
-- | Cf. 'setSecureCookies'.
getSecureCookies :: State sto -> Bool
getSecureCookies = secureCookies
----------------------------------------------------------------------
-- | Load the session map from the storage backend. The value of
-- the session cookie should be given as argument if present.
--
-- Returns:
--
* The session data @sess@ to be used by the frontend as the
-- current session's value.
--
-- * Information to be passed back to 'saveSession' on the end
-- of the request in order to save the session.
loadSession
:: Storage sto
=> State sto
-> Maybe ByteString
-> IO (SessionData sto, SaveSessionToken sto)
loadSession state mcookieVal = do
now <- getCurrentTime
let maybeInputId = mcookieVal >>= fromPathPiece . TE.decodeUtf8
get = runTransactionM (storage state) . getSession (storage state)
checkedGet = fmap (>>= checkExpired now state) . get
maybeInput <- maybe (return Nothing) checkedGet maybeInputId
let inputData =
maybe
emptySession
(\s -> recomposeSession (authKey state) (sessionAuthId s) (sessionData s))
maybeInput
return (inputData, SaveSessionToken maybeInput now)
-- | Check if a session @s@ has expired. Returns the @Just s@ if
-- not expired, or @Nothing@ if expired.
checkExpired :: UTCTime {-^ Now. -} -> State sto -> Session sess -> Maybe (Session sess)
checkExpired now state session =
let expired = maybe False (< now) (nextExpires state session)
in guard (not expired) >> return session
-- | Calculate the next point in time where the given session
-- will expire assuming that it sees no activity until then.
-- Returns @Nothing@ iff the state does not have any expirations
-- set to @Just@.
nextExpires :: State sto -> Session sess -> Maybe UTCTime
nextExpires State {..} Session {..} =
let viaIdle = flip addUTCTime sessionAccessedAt <$> idleTimeout
viaAbsolute = flip addUTCTime sessionCreatedAt <$> absoluteTimeout
minimum' [] = Nothing
minimum' xs = Just $ minimum xs
in minimum' $ catMaybes [viaIdle, viaAbsolute]
-- | Calculate the date that should be used for the cookie's
-- \"Expires\" field.
cookieExpires :: State sto -> Session sess -> Maybe UTCTime
cookieExpires State {..} _ | not persistentCookies = Nothing
cookieExpires state session =
Just $ fromMaybe tenYearsFromNow $ nextExpires state session
where tenYearsFromNow = addUTCTime (60*60*24*3652) now
now = sessionAccessedAt session -- :)
-- | Opaque token containing the necessary information for
-- 'saveSession' to save the session.
data SaveSessionToken sto =
SaveSessionToken (Maybe (Session (SessionData sto))) UTCTime
deriving (Typeable)
deriving instance Eq (Decomposed (SessionData sto)) => Eq (SaveSessionToken sto)
deriving instance Ord (Decomposed (SessionData sto)) => Ord (SaveSessionToken sto)
deriving instance Show (Decomposed (SessionData sto)) => Show (SaveSessionToken sto)
-- | Save the session on the storage backend. A
-- 'SaveSessionToken' given by 'loadSession' is expected besides
-- the new contents of the session.
--
-- Returns @Nothing@ if the session was empty and didn't need to
be saved . Note that this does /not/ necessarily means that
-- nothing was done. If you ask for a session to be invalidated
-- and clear every other sesssion variable, then 'saveSession'
-- will invalidate the older session but will avoid creating a
-- new, empty one.
saveSession
:: Storage sto
=> State sto
-> SaveSessionToken sto
-> SessionData sto
-> IO (Maybe (Session (SessionData sto)))
saveSession state (SaveSessionToken maybeInput now) outputData =
runTransactionM (storage state) $ do
let outputDecomp = decomposeSession (authKey state) outputData
newMaybeInput <- invalidateIfNeeded state maybeInput outputDecomp
saveSessionOnDb state now newMaybeInput outputDecomp
-- | Invalidates an old session ID if needed. Returns the
-- 'Session' that should be replaced when saving the session, if any.
--
-- Currently we invalidate whenever the auth ID has changed
-- (login, logout, different user) in order to prevent session
-- fixation attacks. We also invalidate when asked to via
-- 'forceInvalidate'.
invalidateIfNeeded
:: Storage sto
=> State sto
-> Maybe (Session (SessionData sto))
-> DecomposedSession (SessionData sto)
-> TransactionM sto (Maybe (Session (SessionData sto)))
invalidateIfNeeded state maybeInput DecomposedSession {..} = do
-- Decide which action to take.
-- "invalidateOthers implies invalidateCurrent" should be true below.
let inputAuthId = sessionAuthId =<< maybeInput
invalidateCurrent = dsForceInvalidate /= DoNotForceInvalidate || inputAuthId /= dsAuthId
invalidateOthers = dsForceInvalidate == AllSessionIdsOfLoggedUser && isJust dsAuthId
whenMaybe b m f = when b $ maybe (return ()) f m
-- Delete current and others, as requested.
whenMaybe invalidateCurrent maybeInput $ deleteSession (storage state) . sessionKey
whenMaybe invalidateOthers dsAuthId $ deleteAllSessionsOfAuthId (storage state)
-- Remember the input only if not invalidated.
return $ guard (not invalidateCurrent) >> maybeInput
-- | Save a session on the database. If an old session is
-- supplied, it is replaced, otherwise a new session is
-- generated. If the session is empty, it is not saved and
-- @Nothing@ is returned. If the timeout resolution optimization
-- is applied (cf. 'setTimeoutResolution'), the old session is
-- returned and no update is made.
saveSessionOnDb
:: forall sto. Storage sto
=> State sto
-> UTCTime -- ^ Now.
-> Maybe (Session (SessionData sto)) -- ^ The old session, if any.
-> DecomposedSession (SessionData sto) -- ^ The session data to be saved.
-> TransactionM sto (Maybe (Session (SessionData sto))) -- ^ Copy of saved session.
saveSessionOnDb _ _ Nothing (DecomposedSession Nothing _ m)
-- Return Nothing without doing anything whenever the session
-- is empty (including auth ID) and there was no prior session.
| isDecomposedEmpty proxy m = return Nothing
where
proxy :: Maybe (SessionData sto)
proxy = Nothing
saveSessionOnDb State { timeoutResolution = Just res } now (Just old) (DecomposedSession authId _ newSession)
-- If the data is the same and the old access time is within
-- the timeout resolution, just return the old session without
-- doing anything else.
| sessionAuthId old == authId &&
isSameDecomposed proxy (sessionData old) newSession &&
abs (diffUTCTime now (sessionAccessedAt old)) < res =
return (Just old)
where
proxy :: Maybe (SessionData sto)
proxy = Nothing
saveSessionOnDb state now maybeInput DecomposedSession {..} = do
-- Generate properties if needed or take them from previous
-- saved session.
(saveToDb, key, createdAt) <-
case maybeInput of
Nothing -> liftIO $
(,,) A.<$> return (insertSession $ storage state)
<*> generateSessionId (generator state)
<*> return now
Just Session {..} ->
return ( replaceSession (storage state)
, sessionKey
, sessionCreatedAt)
-- Save to the database.
let session = Session
{ sessionKey = key
, sessionAuthId = dsAuthId
, sessionData = dsDecomposed
, sessionCreatedAt = createdAt
, sessionAccessedAt = now
}
saveToDb session
return (Just session)
-- | The session key used to signal that the session ID should be
-- invalidated.
forceInvalidateKey :: Text
forceInvalidateKey = "serversession-force-invalidate"
-- | Which session IDs should be invalidated.
--
-- Note that this is not the same concept of invalidation as used
on . In this context , invalidation means creating a fresh
-- session ID for this user's session and disabling the old ID.
-- Its purpose is to avoid session fixation attacks.
data ForceInvalidate =
CurrentSessionId
^ Invalidate the current session ID . The current session
-- ID is automatically invalidated on login and logout
-- (cf. 'setAuthKey').
| AllSessionIdsOfLoggedUser
^ Invalidate all session IDs beloging to the currently
-- logged in user. Only the current session ID will be
-- renewed (the only one for which a cookie can be set).
--
-- This is useful, for example, if the user asks to change
-- their password. It's also useful to provide a button to
-- clear all other sessions.
--
-- If the user is not logged in, this option behaves exactly
-- as 'CurrentSessionId' (i.e., it /does not/ invalidate the
-- sessions of all logged out users).
--
-- Note that, for the purposes of
-- 'AllSessionIdsOfLoggedUser', we consider \"logged user\"
-- the one that is logged in at the *end* of the handler
-- processing. For example, if the user was logged in but
-- the current handler logged him out, the session IDs of the
-- user who was logged in will not be invalidated.
| DoNotForceInvalidate
^ Do not force invalidate . Invalidate only if
-- automatically. This is the default.
deriving (Eq, Ord, Show, Read, Bounded, Enum, Typeable)
| null | https://raw.githubusercontent.com/yesodweb/serversession/bdede5fb660890df670f103d64a5e69024b13e57/serversession/src/Web/ServerSession/Core/Internal.hs | haskell | | Internal module exposing the guts of the package. Use at
your own risk. No API stability guarantees apply.
@UndecidableInstances@ is required in order to implement @Eq@,
fields, and should be fairly safe.
--------------------------------------------------------------------
the session data type this session ID points to.
Implementation notes:
* Use 'fromPathPiece' for parsing untrusted input.
* Use 'generateSessionId' for securely generating new
session IDs.
| Sanity checks input on 'fromPathPiece' (untrusted input).
| (Internal) Check that the given text is a base64url-encoded
--------------------------------------------------------------------
| Value of the 'authKey' session key.
| Representation of a saved session.
This representation is used by the @serversession@ family of
packages, transferring data between this core package and
the session data type.
^ Session ID, primary key.
^ Value of 'authKey' session key, separate from the rest.
^ Rest of the session data.
^ When this session was created.
^ When this session was last accessed.
| A @newtype@ for a common session map.
This is a common representation of a session. Although
@serversession@ has generalized session data types, you can
use this one if you don't want to worry about it. We strive
to support this session data type on all frontends and storage
backends.
--------------------------------------------------------------------
| Class for data types to be used as session data
The @Show@ constrain is needed for 'StorageException'.
| The type of the session data after being decomposed. This
may be the same as @sess@.
| Empty session data.
* The auth ID of the logged in user (cf. 'setAuthKey',
'dsAuthId').
* If the session is being forced to be invalidated
* The rest of the session data (cf. 'Decomposed').
^ The auth key (cf. 'setAuthKey').
^ Session data to be decomposed.
^ Decomposed session data.
| Recompose a decomposed session again into a proper @sess@.
^ The auth key (cf. 'setAuthKey').
^ Decomposed session data to be recomposed.
^ Recomposed session data.
| Returns @True@ when both session datas are to be
considered the same.
This is used to optimize storage calls
(cf. 'setTimeoutResolution'). Always returning @False@ will
disable the optimization but won't have any other adverse
effects.
For data types implementing 'Eq', this is usually a good
implementation:
@
isSameDecomposed _ = (==)
@
| Returns @True@ if the decomposed session data is to be
considered @empty@.
This is used to avoid storing empty session data if at all
possible. Always returning @False@ will disable the
optimization but won't have any other adverse effects.
| A 'SessionMap' decomposes into a 'SessionMap' minus the keys
that were removed. The auth key is added back when
recomposing.
--------------------------------------------------------------------
| A storage backend @sto@ for server-side sessions. The
be constrained depending on the storage backend capabilities.
| The session data type used by this storage.
| Monad where transactions happen for this backend.
| Get the session for the given session ID. Returns
@Nothing@ if the session is not found.
| Delete the session with given session ID. Does not do
anything if the session is not found.
| Delete all sessions of the given auth ID. Does not do
anything if there are no sessions of the given auth ID.
| Insert a new session. Throws 'SessionAlreadyExists' if
there already exists a session with the same session ID (we
only call this method after generating a fresh session ID).
| Replace the contents of a session. Throws
session ID (we only call this method when updating a session
that is known to exist).
It is possible to have concurrent requests using the same
session ID such that:
@
@
'deleteSession' as invalidation was forced. However,
following behaviors are possible:
1. Make @replaceSession@ insert the session again.
invalidations are done for security reasons, this is a bad
idea.
2. Make @replaceSession@ silently discard the session.
The reasoning is that, as the session was going to be
discard its contents. However, we can't be sure that
3. Make @replaceSession@ throw an error. This error is
going to be unrecoverable since usually the session
processing is done at the end of the request processing by
Error. However, this signals to the caller that something
went wrong, which is correct.
Most of the time this discussion does not matter.
is flying.
| Common exceptions that may be thrown by any storage.
| Exception thrown by 'insertSession' whenever a session
with same ID already exists.
| Exception thrown by 'replaceSession' whenever trying to
replace a session that is not present on the storage.
--------------------------------------------------------------------
TODO: delete expired sessions.
| The server-side session backend needs to maintain some state
in order to work:
* A nonce generator for the session IDs.
* A reference to the storage backend.
* The name of cookie where the session ID will be saved ('setCookieName').
* Authentication session variable ('setAuthKey').
* Idle and absolute timeouts ('setIdleTimeout' and 'setAbsoluteTimeout').
* Timeout resolution ('setTimeoutResolution').
* Whether cookies should be persistent
('setPersistentCookies'), HTTP-only ('setHTTPOnlyCookies')
and/or secure ('setSecureCookies').
using the given storage backend.
| Set the name of cookie where the session ID will be saved.
used by many frameworks thus making it harder to fingerprint
this implementation.
| Set the name of the session variable that keeps track of the
logged user.
This setting is used by session data types that are
@Map@-alike, using a @lookup@ function. However, the
'IsSessionData' instance of a session data type may choose not
to use it. For example, if you implemented a custom data
| Set the idle timeout for all sessions. This is used both on
the client side (by setting the cookie expires fields) and on
the server side (the idle timeout is enforced even if the
cookie expiration is ignored). Setting to @Nothing@ removes
the idle timeout entirely.
\"[The idle timemout] defines the amount of time a session
will remain active in case there is no activity in the
session, closing and invalidating the session upon the defined
idle period since the last HTTP request received by the web
application for a given session ID.\"
(<#Idle_Timeout Source>)
| Set the absolute timeout for all sessions. This is used both on
the client side (by setting the cookie expires fields) and on
the server side (the absolute timeout is enforced even if the
cookie expiration is ignored). Setting to @Nothing@ removes
the absolute timeout entirely.
session can be active, closing and invalidating the session
upon the defined absolute period since the given session was
initially created by the web application. After invalidating
the session, the user is forced to (re)authenticate again in
the web application and establish a new session.\"
(<#Absolute_Timeout Source>)
| Set the timeout resolution.
We need to save both the creation and last access times on
sessions in order to implement idle and absolute timeouts.
This means that we have to save the updated session on the
storage backend even if the request didn't change any session
variable, if only to update the last access time.
This setting provides an optimization where the session is not
updated on the storage backend provided that:
* No session variables were changed.
* The difference between the /current/ time and the last
/saved/ access time is less than the timeout resolution.
minute of the last update will not generate any updates on the
storage backend.
If the timeout resolution is @Nothing@, then this optimization
becomes disabled and the session will always be updated.
non-persistent (@False@). Persistent cookies are saved across
browser sessions. Non-persistent cookies are discarded when
the browser is closed.
If you set cookies to be persistent and do not define any
timeouts ('setIdleTimeout' or 'setAbsoluteTimeout'), then the
Defaults to @True@.
(@False@). Cookies marked as HTTP-only (\"HttpOnly\") are not
accessible from client-side scripting languages such as
It's highly recommended to set this attribute to @True@.
Defaults to @True@.
(@False@). Cookies marked as \"Secure\" are not sent via
plain HTTP connections, only via HTTPS connections. It's
highly recommended to set this attribute to @True@. However,
since many sites do not operate over HTTPS, the default is
| Cf. 'setCookieName'.
| Cf. 'setHttpOnlyCookies'.
| Cf. 'setSecureCookies'.
--------------------------------------------------------------------
| Load the session map from the storage backend. The value of
the session cookie should be given as argument if present.
Returns:
current session's value.
* Information to be passed back to 'saveSession' on the end
of the request in order to save the session.
| Check if a session @s@ has expired. Returns the @Just s@ if
not expired, or @Nothing@ if expired.
^ Now.
| Calculate the next point in time where the given session
will expire assuming that it sees no activity until then.
Returns @Nothing@ iff the state does not have any expirations
set to @Just@.
| Calculate the date that should be used for the cookie's
\"Expires\" field.
:)
| Opaque token containing the necessary information for
'saveSession' to save the session.
| Save the session on the storage backend. A
'SaveSessionToken' given by 'loadSession' is expected besides
the new contents of the session.
Returns @Nothing@ if the session was empty and didn't need to
nothing was done. If you ask for a session to be invalidated
and clear every other sesssion variable, then 'saveSession'
will invalidate the older session but will avoid creating a
new, empty one.
| Invalidates an old session ID if needed. Returns the
'Session' that should be replaced when saving the session, if any.
Currently we invalidate whenever the auth ID has changed
(login, logout, different user) in order to prevent session
fixation attacks. We also invalidate when asked to via
'forceInvalidate'.
Decide which action to take.
"invalidateOthers implies invalidateCurrent" should be true below.
Delete current and others, as requested.
Remember the input only if not invalidated.
| Save a session on the database. If an old session is
supplied, it is replaced, otherwise a new session is
generated. If the session is empty, it is not saved and
@Nothing@ is returned. If the timeout resolution optimization
is applied (cf. 'setTimeoutResolution'), the old session is
returned and no update is made.
^ Now.
^ The old session, if any.
^ The session data to be saved.
^ Copy of saved session.
Return Nothing without doing anything whenever the session
is empty (including auth ID) and there was no prior session.
If the data is the same and the old access time is within
the timeout resolution, just return the old session without
doing anything else.
Generate properties if needed or take them from previous
saved session.
Save to the database.
| The session key used to signal that the session ID should be
invalidated.
| Which session IDs should be invalidated.
Note that this is not the same concept of invalidation as used
session ID for this user's session and disabling the old ID.
Its purpose is to avoid session fixation attacks.
ID is automatically invalidated on login and logout
(cf. 'setAuthKey').
logged in user. Only the current session ID will be
renewed (the only one for which a cookie can be set).
This is useful, for example, if the user asks to change
their password. It's also useful to provide a button to
clear all other sessions.
If the user is not logged in, this option behaves exactly
as 'CurrentSessionId' (i.e., it /does not/ invalidate the
sessions of all logged out users).
Note that, for the purposes of
'AllSessionIdsOfLoggedUser', we consider \"logged user\"
the one that is logged in at the *end* of the handler
processing. For example, if the user was logged in but
the current handler logged him out, the session IDs of the
user who was logged in will not be invalidated.
automatically. This is the default. | @Ord@ , @Show@ , etc . on data types that have @Decomposed@
module Web.ServerSession.Core.Internal
( SessionId(..)
, checkSessionId
, generateSessionId
, AuthId
, Session(..)
, SessionMap(..)
, IsSessionData(..)
, DecomposedSession(..)
, Storage(..)
, StorageException(..)
, State(..)
, createState
, setCookieName
, setAuthKey
, setIdleTimeout
, setAbsoluteTimeout
, setTimeoutResolution
, setPersistentCookies
, setHttpOnlyCookies
, setSecureCookies
, getCookieName
, getHttpOnlyCookies
, getSecureCookies
, loadSession
, checkExpired
, nextExpires
, cookieExpires
, saveSession
, SaveSessionToken(..)
, invalidateIfNeeded
, saveSessionOnDb
, forceInvalidateKey
, ForceInvalidate(..)
) where
import Control.Applicative as A
import Control.Monad (guard, when)
import Control.Monad.IO.Class (MonadIO(..))
import Data.ByteString (ByteString)
import Data.Hashable (Hashable(..))
import Data.Kind (Type)
import Data.Maybe (catMaybes, fromMaybe, isJust)
import Data.Text (Text)
import Data.Time (UTCTime, getCurrentTime)
import Data.Time.Clock (NominalDiffTime, addUTCTime, diffUTCTime)
import Data.Typeable (Typeable)
import Web.PathPieces (PathPiece(..))
import qualified Control.Exception as E
import qualified Crypto.Nonce as N
import qualified Data.Aeson as A
import qualified Data.ByteString.Base64.URL as B64URL
import qualified Data.ByteString.Char8 as B8
import qualified Data.HashMap.Strict as HM
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
| The ID of a session . Always 18 bytes base64url - encoded as
24 characters . The @sess@ type variable is a phantom type for
newtype SessionId sess = S { unS :: Text }
deriving (Eq, Ord, Show, Read, Typeable)
instance PathPiece (SessionId sess) where
toPathPiece = unS
fromPathPiece = checkSessionId
instance A.FromJSON (SessionId sess) where
parseJSON = fmap S . A.parseJSON
instance A.ToJSON (SessionId sess) where
toJSON = A.toJSON . unS
instance Hashable (SessionId sess) where
hashWithSalt s = hashWithSalt s . unS
representation of 18 bytes .
checkSessionId :: Text -> Maybe (SessionId sess)
checkSessionId text = do
guard (T.length text == 24)
let bs = TE.encodeUtf8 text
decoded <- either (const Nothing) Just $ B64URL.decode bs
guard (B8.length decoded == 18)
return $ S text
| Securely generate a new SessionId .
generateSessionId :: N.Generator -> IO (SessionId sess)
generateSessionId = fmap S . N.nonce128urlT
type AuthId = ByteString
storage backend packages . The @sess@ type variable describes
data Session sess =
Session
{ sessionKey :: SessionId sess
, sessionAuthId :: Maybe AuthId
, sessionData :: Decomposed sess
, sessionCreatedAt :: UTCTime
, sessionAccessedAt :: UTCTime
} deriving (Typeable)
deriving instance Eq (Decomposed sess) => Eq (Session sess)
deriving instance Ord (Decomposed sess) => Ord (Session sess)
deriving instance Show (Decomposed sess) => Show (Session sess)
newtype SessionMap =
SessionMap { unSessionMap :: HM.HashMap Text ByteString }
deriving (Eq, Show, Read, Typeable)
( cf . ' sessionData ' , ' SessionData ' ) .
class ( Show (Decomposed sess)
, Typeable (Decomposed sess)
, Typeable sess
) => IsSessionData sess where
type Decomposed sess :: Type
emptySession :: sess
| Decompose session data into :
( cf . ' forceInvalidateKey ' , ' ForceInvalidate ' ) .
decomposeSession
recomposeSession
^ The @AuthId@ , if any .
isSameDecomposed :: proxy sess -> Decomposed sess -> Decomposed sess -> Bool
isDecomposedEmpty :: proxy sess -> Decomposed sess -> Bool
instance IsSessionData SessionMap where
type Decomposed SessionMap = SessionMap
emptySession = SessionMap HM.empty
isSameDecomposed _ = (==)
decomposeSession authKey_ (SessionMap sm1) =
let authId = HM.lookup authKey_ sm1
force = maybe DoNotForceInvalidate (read . B8.unpack) $
HM.lookup forceInvalidateKey sm1
sm2 = HM.delete authKey_ $
HM.delete forceInvalidateKey sm1
in DecomposedSession
{ dsAuthId = authId
, dsForceInvalidate = force
, dsDecomposed = SessionMap sm2 }
recomposeSession authKey_ mauthId (SessionMap sm) =
SessionMap $ maybe id (HM.insert authKey_) mauthId sm
isDecomposedEmpty _ = HM.null . unSessionMap
| A session data type @sess@ with its special variables taken apart .
data DecomposedSession sess =
DecomposedSession
{ dsAuthId :: !(Maybe ByteString)
, dsForceInvalidate :: !ForceInvalidate
, dsDecomposed :: !(Decomposed sess)
} deriving (Typeable)
deriving instance Eq (Decomposed sess) => Eq (DecomposedSession sess)
deriving instance Ord (Decomposed sess) => Ord (DecomposedSession sess)
deriving instance Show (Decomposed sess) => Show (DecomposedSession sess)
@sess@ session data type and\/or its ' Decomposed ' version may
class ( Typeable sto
, MonadIO (TransactionM sto)
, IsSessionData (SessionData sto)
) => Storage sto where
type SessionData sto :: Type
We do not require transactions to be ACID .
type TransactionM sto :: Type -> Type
| Run a transaction on the IO monad .
runTransactionM :: sto -> TransactionM sto a -> IO a
getSession
:: sto
-> SessionId (SessionData sto)
-> TransactionM sto (Maybe (Session (SessionData sto)))
deleteSession :: sto -> SessionId (SessionData sto) -> TransactionM sto ()
deleteAllSessionsOfAuthId :: sto -> AuthId -> TransactionM sto ()
insertSession :: sto -> Session (SessionData sto) -> TransactionM sto ()
' SessionDoesNotExist ' if there is no session with the given
request 1 :
request 2 : loadSession
request 2 : forceInvalidate
request 2 : saveSession
request 1 : saveSession
The request 2 's call to ' saveSession ' will have called
request 1 has no idea and will try to @replaceSession@. The
However , this will undo the invalidation of request 2 . As
invalidated if request 2 came after request 1 , we can
request 2 would have had the same effect if it had seen
the session changes made by request 1 ( and vice versa ) .
the web framework , thus leading to a 500 Internal Server
Invalidations usually occur at times where only one request
replaceSession :: sto -> Session (SessionData sto) -> TransactionM sto ()
data StorageException sto =
SessionAlreadyExists
{ seExistingSession :: Session (SessionData sto)
, seNewSession :: Session (SessionData sto) }
| SessionDoesNotExist
{ seNewSession :: Session (SessionData sto) }
deriving (Typeable)
deriving instance Eq (Decomposed (SessionData sto)) => Eq (StorageException sto)
deriving instance Ord (Decomposed (SessionData sto)) => Ord (StorageException sto)
deriving instance Show (Decomposed (SessionData sto)) => Show (StorageException sto)
instance Storage sto => E.Exception (StorageException sto) where
Create a new ' State ' using ' createState ' .
data State sto =
State
{ generator :: !N.Generator
, storage :: !sto
, cookieName :: !Text
, authKey :: !Text
, idleTimeout :: !(Maybe NominalDiffTime)
, absoluteTimeout :: !(Maybe NominalDiffTime)
, timeoutResolution :: !(Maybe NominalDiffTime)
, persistentCookies :: !Bool
, httpOnlyCookies :: !Bool
, secureCookies :: !Bool
} deriving (Typeable)
| Create a new ' State ' for the server - side session backend
createState :: MonadIO m => sto -> m (State sto)
createState sto = do
gen <- N.new
return State
{ generator = gen
, storage = sto
, cookieName = "JSESSIONID"
, authKey = "_ID"
7 days
60 days
10 minutes
, persistentCookies = True
, httpOnlyCookies = True
, secureCookies = False
}
Defaults to " , which is a generic cookie name
setCookieName :: Text -> State sto -> State sto
setCookieName val state = state { cookieName = val }
type , you could return the @AuthId@ without needing a lookup .
Defaults to \"_ID\ " ( used by @yesod - auth@ ) .
setAuthKey :: Text -> State sto -> State sto
setAuthKey val state = state { authKey = val }
Defaults to 7 days .
setIdleTimeout :: Maybe NominalDiffTime -> State sto -> State sto
setIdleTimeout (Just d) _ | d <= 0 = error "serversession/setIdleTimeout: Timeout should be positive."
setIdleTimeout val state = state { idleTimeout = val }
\"[The absolute timeout ] defines the maximum amount of time a
Defaults to 60 days .
setAbsoluteTimeout :: Maybe NominalDiffTime -> State sto -> State sto
setAbsoluteTimeout (Just d) _ | d <= 0 = error "serversession/setAbsoluteTimeout: Timeout should be positive."
setAbsoluteTimeout val state = state { absoluteTimeout = val }
For example , with a timeout resolution of 1 minute , every
request that does not change the session variables within 1
Defaults to 10 minutes .
setTimeoutResolution :: Maybe NominalDiffTime -> State sto -> State sto
setTimeoutResolution (Just d) _ | d <= 0 = error "serversession/setTimeoutResolution: Resolution should be positive."
setTimeoutResolution val state = state { timeoutResolution = val }
| Set whether by default cookies should be persistent ( @True@ ) or
cookie is set to expire in 10 years .
setPersistentCookies :: Bool -> State sto -> State sto
setPersistentCookies val state = state { persistentCookies = val }
| Set whether cookies should be HTTP - only ( @True@ ) or not
JavaScript , thus preventing a large class of XSS attacks .
setHttpOnlyCookies :: Bool -> State sto -> State sto
setHttpOnlyCookies val state = state { httpOnlyCookies = val }
| Set whether cookies should be mared \"Secure\ " ( @True@ ) or not
Defaults to
setSecureCookies :: Bool -> State sto -> State sto
setSecureCookies val state = state { secureCookies = val }
getCookieName :: State sto -> Text
getCookieName = cookieName
getHttpOnlyCookies :: State sto -> Bool
getHttpOnlyCookies = httpOnlyCookies
getSecureCookies :: State sto -> Bool
getSecureCookies = secureCookies
* The session data @sess@ to be used by the frontend as the
loadSession
:: Storage sto
=> State sto
-> Maybe ByteString
-> IO (SessionData sto, SaveSessionToken sto)
loadSession state mcookieVal = do
now <- getCurrentTime
let maybeInputId = mcookieVal >>= fromPathPiece . TE.decodeUtf8
get = runTransactionM (storage state) . getSession (storage state)
checkedGet = fmap (>>= checkExpired now state) . get
maybeInput <- maybe (return Nothing) checkedGet maybeInputId
let inputData =
maybe
emptySession
(\s -> recomposeSession (authKey state) (sessionAuthId s) (sessionData s))
maybeInput
return (inputData, SaveSessionToken maybeInput now)
checkExpired now state session =
let expired = maybe False (< now) (nextExpires state session)
in guard (not expired) >> return session
nextExpires :: State sto -> Session sess -> Maybe UTCTime
nextExpires State {..} Session {..} =
let viaIdle = flip addUTCTime sessionAccessedAt <$> idleTimeout
viaAbsolute = flip addUTCTime sessionCreatedAt <$> absoluteTimeout
minimum' [] = Nothing
minimum' xs = Just $ minimum xs
in minimum' $ catMaybes [viaIdle, viaAbsolute]
cookieExpires :: State sto -> Session sess -> Maybe UTCTime
cookieExpires State {..} _ | not persistentCookies = Nothing
cookieExpires state session =
Just $ fromMaybe tenYearsFromNow $ nextExpires state session
where tenYearsFromNow = addUTCTime (60*60*24*3652) now
data SaveSessionToken sto =
SaveSessionToken (Maybe (Session (SessionData sto))) UTCTime
deriving (Typeable)
deriving instance Eq (Decomposed (SessionData sto)) => Eq (SaveSessionToken sto)
deriving instance Ord (Decomposed (SessionData sto)) => Ord (SaveSessionToken sto)
deriving instance Show (Decomposed (SessionData sto)) => Show (SaveSessionToken sto)
be saved . Note that this does /not/ necessarily means that
saveSession
:: Storage sto
=> State sto
-> SaveSessionToken sto
-> SessionData sto
-> IO (Maybe (Session (SessionData sto)))
saveSession state (SaveSessionToken maybeInput now) outputData =
runTransactionM (storage state) $ do
let outputDecomp = decomposeSession (authKey state) outputData
newMaybeInput <- invalidateIfNeeded state maybeInput outputDecomp
saveSessionOnDb state now newMaybeInput outputDecomp
invalidateIfNeeded
:: Storage sto
=> State sto
-> Maybe (Session (SessionData sto))
-> DecomposedSession (SessionData sto)
-> TransactionM sto (Maybe (Session (SessionData sto)))
invalidateIfNeeded state maybeInput DecomposedSession {..} = do
let inputAuthId = sessionAuthId =<< maybeInput
invalidateCurrent = dsForceInvalidate /= DoNotForceInvalidate || inputAuthId /= dsAuthId
invalidateOthers = dsForceInvalidate == AllSessionIdsOfLoggedUser && isJust dsAuthId
whenMaybe b m f = when b $ maybe (return ()) f m
whenMaybe invalidateCurrent maybeInput $ deleteSession (storage state) . sessionKey
whenMaybe invalidateOthers dsAuthId $ deleteAllSessionsOfAuthId (storage state)
return $ guard (not invalidateCurrent) >> maybeInput
saveSessionOnDb
:: forall sto. Storage sto
=> State sto
saveSessionOnDb _ _ Nothing (DecomposedSession Nothing _ m)
| isDecomposedEmpty proxy m = return Nothing
where
proxy :: Maybe (SessionData sto)
proxy = Nothing
saveSessionOnDb State { timeoutResolution = Just res } now (Just old) (DecomposedSession authId _ newSession)
| sessionAuthId old == authId &&
isSameDecomposed proxy (sessionData old) newSession &&
abs (diffUTCTime now (sessionAccessedAt old)) < res =
return (Just old)
where
proxy :: Maybe (SessionData sto)
proxy = Nothing
saveSessionOnDb state now maybeInput DecomposedSession {..} = do
(saveToDb, key, createdAt) <-
case maybeInput of
Nothing -> liftIO $
(,,) A.<$> return (insertSession $ storage state)
<*> generateSessionId (generator state)
<*> return now
Just Session {..} ->
return ( replaceSession (storage state)
, sessionKey
, sessionCreatedAt)
let session = Session
{ sessionKey = key
, sessionAuthId = dsAuthId
, sessionData = dsDecomposed
, sessionCreatedAt = createdAt
, sessionAccessedAt = now
}
saveToDb session
return (Just session)
forceInvalidateKey :: Text
forceInvalidateKey = "serversession-force-invalidate"
on . In this context , invalidation means creating a fresh
data ForceInvalidate =
CurrentSessionId
^ Invalidate the current session ID . The current session
| AllSessionIdsOfLoggedUser
^ Invalidate all session IDs beloging to the currently
| DoNotForceInvalidate
^ Do not force invalidate . Invalidate only if
deriving (Eq, Ord, Show, Read, Bounded, Enum, Typeable)
|
7c55189d998e41e408cf8a9f21ceb18011b1cdb5f1a66949dcbd7ce0b9f8cc9b | clojure-emacs/refactor-nrepl | s_expressions_test.clj | (ns refactor-nrepl.s-expressions-test
(:require
[clojure.test :as t]
[refactor-nrepl.s-expressions :as sut]))
(def file-content (slurp "testproject/src/com/example/sexp_test.clj"))
(def weird-file-content ";; some weird file
;; not even clojure
;; perhaps? no parens!")
(def file-content-with-set ";; with set
#{foo bar baz}
;; some other stuff
(foobar baz)")
(def file-content-with-uneval "#_ foo
(foobar baz)")
(def binding-location [3 8])
(def set-location [7 35])
(def map-location [7 28])
(def weird-location [1 5])
(def println-location [5 8])
(def when-not-location [10 9])
(t/deftest get-enclosing-sexp-test
(t/is (= "[some :bindings
more :bindings]"
(apply sut/get-enclosing-sexp file-content binding-location)))
(t/is (= "(println #{some}
;; unhelpful comment )
(prn {\"foo\" {:qux [#{more}]}}))"
(apply sut/get-enclosing-sexp file-content println-location)))
(t/is (= "#{more}" (apply sut/get-enclosing-sexp file-content set-location)))
(t/is (= "{:qux [#{more}]}" (apply sut/get-enclosing-sexp file-content map-location)))
(t/is (= nil (apply sut/get-enclosing-sexp weird-file-content weird-location)))
(t/is (= "(when-not (= true true)
(= 5 (* 2 2)))"
(apply sut/get-enclosing-sexp file-content when-not-location)))
(t/is (= nil (sut/get-first-sexp weird-file-content)))
(t/is (= "#{foo bar baz}" (sut/get-first-sexp file-content-with-set))))
(t/deftest get-first-sexp
(t/is (= "(ns com.example.sexp-test)"
(sut/get-first-sexp file-content)))
(t/is (= "(foobar baz)"
(sut/get-first-sexp file-content-with-uneval))))
| null | https://raw.githubusercontent.com/clojure-emacs/refactor-nrepl/f7858784220ccd354a19155a9044cc3ceb34660e/test/refactor_nrepl/s_expressions_test.clj | clojure | some weird file
not even clojure
perhaps? no parens!")
with set
some other stuff
unhelpful comment ) | (ns refactor-nrepl.s-expressions-test
(:require
[clojure.test :as t]
[refactor-nrepl.s-expressions :as sut]))
(def file-content (slurp "testproject/src/com/example/sexp_test.clj"))
#{foo bar baz}
(foobar baz)")
(def file-content-with-uneval "#_ foo
(foobar baz)")
(def binding-location [3 8])
(def set-location [7 35])
(def map-location [7 28])
(def weird-location [1 5])
(def println-location [5 8])
(def when-not-location [10 9])
(t/deftest get-enclosing-sexp-test
(t/is (= "[some :bindings
more :bindings]"
(apply sut/get-enclosing-sexp file-content binding-location)))
(t/is (= "(println #{some}
(prn {\"foo\" {:qux [#{more}]}}))"
(apply sut/get-enclosing-sexp file-content println-location)))
(t/is (= "#{more}" (apply sut/get-enclosing-sexp file-content set-location)))
(t/is (= "{:qux [#{more}]}" (apply sut/get-enclosing-sexp file-content map-location)))
(t/is (= nil (apply sut/get-enclosing-sexp weird-file-content weird-location)))
(t/is (= "(when-not (= true true)
(= 5 (* 2 2)))"
(apply sut/get-enclosing-sexp file-content when-not-location)))
(t/is (= nil (sut/get-first-sexp weird-file-content)))
(t/is (= "#{foo bar baz}" (sut/get-first-sexp file-content-with-set))))
(t/deftest get-first-sexp
(t/is (= "(ns com.example.sexp-test)"
(sut/get-first-sexp file-content)))
(t/is (= "(foobar baz)"
(sut/get-first-sexp file-content-with-uneval))))
|
81433c9bf8be83098bace9f904eb2a5cffcd895398aac9dc5f3453daaee7ed04 | facebook/infer | Subtype.mli |
* Copyright ( c ) 2009 - 2013 , Monoidics ltd .
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) 2009-2013, Monoidics ltd.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(** The Smallfoot Intermediate Language: Subtypes *)
open! IStd
module F = Format
type t [@@deriving compare, equal]
val pp : F.formatter -> t -> unit
val exact : t
val subtypes : t
(** denotes the current type only *)
val subtypes_cast : t
(** denotes the current type and any subtypes *)
val subtypes_instof : t
val join : t -> t -> t
val case_analysis : Tenv.t -> Typ.Name.t * t -> Typ.Name.t * t -> t option * t option
* [ case_analysis tenv ( c1 , st1 ) ( c2 , st2 ) ] performs case analysis on [ c1 < : c2 ] according to [ st1 ]
and [ st2 ] . [ case_analysis ] returns a pair :
- whether [ st1 ] and [ st2 ] admit [ c1 < : c2 ] , and in case returns the updated subtype [ st1 ]
- whether [ st1 ] and [ st2 ] admit [ not(c1 < : c2 ) ] , and in case returns the updated subtype [ st1 ]
and [st2]. [case_analysis] returns a pair:
- whether [st1] and [st2] admit [c1 <: c2], and in case returns the updated subtype [st1]
- whether [st1] and [st2] admit [not(c1 <: c2)], and in case returns the updated subtype [st1] *)
val is_known_subtype : Tenv.t -> Typ.Name.t -> Typ.Name.t -> bool
* [ is_known_subtype tenv c1 c2 ] returns true if there is enough information in [ tenv ] to prove
that [ c1 ] is a subtype of [ c2 ] . Note that [ not ( is_known_subtype tenv c1 c2 ) = = true ] does not
imply that [ c1 c2 = = true ]
that [c1] is a subtype of [c2]. Note that [not (is_known_subtype tenv c1 c2) == true] does not
imply that [is_known_not_subtype tenv c1 c2 == true] *)
val is_cast : t -> bool
val is_instof : t -> bool [@@warning "-unused-value-declaration"]
val equal_modulo_flag : t -> t -> bool
(** equality ignoring flags in the subtype *)
| null | https://raw.githubusercontent.com/facebook/infer/4ee1c2a8e783ee770b61547a38ff1715d6ed75fe/infer/src/IR/Subtype.mli | ocaml | * The Smallfoot Intermediate Language: Subtypes
* denotes the current type only
* denotes the current type and any subtypes
* equality ignoring flags in the subtype |
* Copyright ( c ) 2009 - 2013 , Monoidics ltd .
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) 2009-2013, Monoidics ltd.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
module F = Format
type t [@@deriving compare, equal]
val pp : F.formatter -> t -> unit
val exact : t
val subtypes : t
val subtypes_cast : t
val subtypes_instof : t
val join : t -> t -> t
val case_analysis : Tenv.t -> Typ.Name.t * t -> Typ.Name.t * t -> t option * t option
* [ case_analysis tenv ( c1 , st1 ) ( c2 , st2 ) ] performs case analysis on [ c1 < : c2 ] according to [ st1 ]
and [ st2 ] . [ case_analysis ] returns a pair :
- whether [ st1 ] and [ st2 ] admit [ c1 < : c2 ] , and in case returns the updated subtype [ st1 ]
- whether [ st1 ] and [ st2 ] admit [ not(c1 < : c2 ) ] , and in case returns the updated subtype [ st1 ]
and [st2]. [case_analysis] returns a pair:
- whether [st1] and [st2] admit [c1 <: c2], and in case returns the updated subtype [st1]
- whether [st1] and [st2] admit [not(c1 <: c2)], and in case returns the updated subtype [st1] *)
val is_known_subtype : Tenv.t -> Typ.Name.t -> Typ.Name.t -> bool
* [ is_known_subtype tenv c1 c2 ] returns true if there is enough information in [ tenv ] to prove
that [ c1 ] is a subtype of [ c2 ] . Note that [ not ( is_known_subtype tenv c1 c2 ) = = true ] does not
imply that [ c1 c2 = = true ]
that [c1] is a subtype of [c2]. Note that [not (is_known_subtype tenv c1 c2) == true] does not
imply that [is_known_not_subtype tenv c1 c2 == true] *)
val is_cast : t -> bool
val is_instof : t -> bool [@@warning "-unused-value-declaration"]
val equal_modulo_flag : t -> t -> bool
|
c4346cf405c622e3c89653cf166b3ccc1e50f22aa2356909143d1837df3beee5 | tezos/tezos-mirror | commitment_sig.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 TriliTech < >
(* *)
(* 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. *)
(* *)
(*****************************************************************************)
* The rollup node stores and publishes commitments for the PVM
every ` Commitment.sc_rollup_commitment_period ` levels .
Every time a finalized block is processed by the rollup node ,
the latter determines whether the last commitment that the node
has produced referred to ` Commitment.sc_rollup_commitment_period ` blocks
earlier . In this case , it computes and stores a new commitment in a
level - indexed map .
Stored commitments are signed by the rollup node operator
and published on the layer1 chain . To ensure that commitments
produced by the rollup node are eventually published ,
storing and publishing commitments are decoupled . Every time
a new head is processed , the node tries to publish the oldest
commitment that was not published already .
every `Commitment.sc_rollup_commitment_period` levels.
Every time a finalized block is processed by the rollup node,
the latter determines whether the last commitment that the node
has produced referred to `Commitment.sc_rollup_commitment_period` blocks
earlier. In this case, it computes and stores a new commitment in a
level-indexed map.
Stored commitments are signed by the rollup node operator
and published on the layer1 chain. To ensure that commitments
produced by the rollup node are eventually published,
storing and publishing commitments are decoupled. Every time
a new head is processed, the node tries to publish the oldest
commitment that was not published already.
*)
module type S = sig
module PVM : Pvm.S
* [ process_head node_ctxt ~predecessor head ] builds a new commitment if
needed , by looking at the level of [ head ] and checking whether it is a
multiple of ` Commitment.sc_rollup_commitment_period ` levels away from
[ node_ctxt.initial_level ] . It uses the functionalities of [ PVM ] to compute
the hash of to be included in the commitment .
needed, by looking at the level of [head] and checking whether it is a
multiple of `Commitment.sc_rollup_commitment_period` levels away from
[node_ctxt.initial_level]. It uses the functionalities of [PVM] to compute
the hash of to be included in the commitment. *)
val process_head :
Node_context.rw ->
predecessor:Block_hash.t ->
Layer1.head ->
Context.rw ->
Protocol.Alpha_context.Sc_rollup.Commitment.Hash.t option tzresult Lwt.t
(** [publish_single_commitment node_ctxt commitment] publishes a single
[commitment] if it is missing. This function is meant to be used by the {e
accuser} mode to sparingly publish commitments when it detects a
conflict. *)
val publish_single_commitment :
_ Node_context.t ->
Protocol.Alpha_context.Sc_rollup.Commitment.t ->
unit tzresult Lwt.t
(** Worker for publishing and cementing commitments. *)
module Publisher : sig
val init : _ Node_context.t -> unit tzresult Lwt.t
(** [publish_commitments node_ctxt] publishes the commitments that were not
yet published up to the finalized head and which are after the last
cemented commitment. *)
val publish_commitments : unit -> unit tzresult Lwt.t
* [ cement_commitments node_ctxt ] cements the commitments that can be
cemented , i.e. the commitments that are after the current last cemented
commitment and which have [ sc_rollup_challenge_period ] levels on top of
them since they were originally published .
cemented, i.e. the commitments that are after the current last cemented
commitment and which have [sc_rollup_challenge_period] levels on top of
them since they were originally published. *)
val cement_commitments : unit -> unit tzresult Lwt.t
val shutdown : unit -> unit Lwt.t
end
end
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/1b26ce0f9c2a9c508a65c45641a0a146d9b52fc7/src/proto_016_PtMumbai/lib_sc_rollup_node/commitment_sig.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* [publish_single_commitment node_ctxt commitment] publishes a single
[commitment] if it is missing. This function is meant to be used by the {e
accuser} mode to sparingly publish commitments when it detects a
conflict.
* Worker for publishing and cementing commitments.
* [publish_commitments node_ctxt] publishes the commitments that were not
yet published up to the finalized head and which are after the last
cemented commitment. | Copyright ( c ) 2022 TriliTech < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
* The rollup node stores and publishes commitments for the PVM
every ` Commitment.sc_rollup_commitment_period ` levels .
Every time a finalized block is processed by the rollup node ,
the latter determines whether the last commitment that the node
has produced referred to ` Commitment.sc_rollup_commitment_period ` blocks
earlier . In this case , it computes and stores a new commitment in a
level - indexed map .
Stored commitments are signed by the rollup node operator
and published on the layer1 chain . To ensure that commitments
produced by the rollup node are eventually published ,
storing and publishing commitments are decoupled . Every time
a new head is processed , the node tries to publish the oldest
commitment that was not published already .
every `Commitment.sc_rollup_commitment_period` levels.
Every time a finalized block is processed by the rollup node,
the latter determines whether the last commitment that the node
has produced referred to `Commitment.sc_rollup_commitment_period` blocks
earlier. In this case, it computes and stores a new commitment in a
level-indexed map.
Stored commitments are signed by the rollup node operator
and published on the layer1 chain. To ensure that commitments
produced by the rollup node are eventually published,
storing and publishing commitments are decoupled. Every time
a new head is processed, the node tries to publish the oldest
commitment that was not published already.
*)
module type S = sig
module PVM : Pvm.S
* [ process_head node_ctxt ~predecessor head ] builds a new commitment if
needed , by looking at the level of [ head ] and checking whether it is a
multiple of ` Commitment.sc_rollup_commitment_period ` levels away from
[ node_ctxt.initial_level ] . It uses the functionalities of [ PVM ] to compute
the hash of to be included in the commitment .
needed, by looking at the level of [head] and checking whether it is a
multiple of `Commitment.sc_rollup_commitment_period` levels away from
[node_ctxt.initial_level]. It uses the functionalities of [PVM] to compute
the hash of to be included in the commitment. *)
val process_head :
Node_context.rw ->
predecessor:Block_hash.t ->
Layer1.head ->
Context.rw ->
Protocol.Alpha_context.Sc_rollup.Commitment.Hash.t option tzresult Lwt.t
val publish_single_commitment :
_ Node_context.t ->
Protocol.Alpha_context.Sc_rollup.Commitment.t ->
unit tzresult Lwt.t
module Publisher : sig
val init : _ Node_context.t -> unit tzresult Lwt.t
val publish_commitments : unit -> unit tzresult Lwt.t
* [ cement_commitments node_ctxt ] cements the commitments that can be
cemented , i.e. the commitments that are after the current last cemented
commitment and which have [ sc_rollup_challenge_period ] levels on top of
them since they were originally published .
cemented, i.e. the commitments that are after the current last cemented
commitment and which have [sc_rollup_challenge_period] levels on top of
them since they were originally published. *)
val cement_commitments : unit -> unit tzresult Lwt.t
val shutdown : unit -> unit Lwt.t
end
end
|
6b80897c557c41ae2e27f77a43d2c0f29c0c3912d064b8e951ff9a24e9620b0d | mirage/ocaml-rpc | client_server_test.ml | (** This test verifies that the client and server functions generated by the
IDL interoperate correctly *)
open Idl.Exn
let test_call_core () =
let server =
let module Server = Test_common.Test_interface.Interface (GenServer ()) in
Server.add (fun a b -> a + b);
Server.sub (fun a b -> a - b);
Server.mul (fun a b -> a * b);
Server.div (fun a b -> a / b);
Server.ping (fun () -> "OK");
server Server.implementation
in
let module Client =
Test_common.Test_interface.Interface (GenClient (struct
let rpc = server
end))
in
Alcotest.(check int) "add" 4 (Client.add 1 3);
Alcotest.(check int) "sub" 2 (Client.sub 3 1);
Alcotest.(check int) "mul" 6 (Client.mul 2 3);
Alcotest.(check int) "div" 4 (Client.div 8 2);
Alcotest.(check string) "ping" "OK" (Client.ping ())
let tests = [ "test_call_core", `Quick, test_call_core ]
| null | https://raw.githubusercontent.com/mirage/ocaml-rpc/2ac81a2fb20775fdd7637a193a3c573f34a9cb08/tests/lib/client_server_test.ml | ocaml | * This test verifies that the client and server functions generated by the
IDL interoperate correctly | open Idl.Exn
let test_call_core () =
let server =
let module Server = Test_common.Test_interface.Interface (GenServer ()) in
Server.add (fun a b -> a + b);
Server.sub (fun a b -> a - b);
Server.mul (fun a b -> a * b);
Server.div (fun a b -> a / b);
Server.ping (fun () -> "OK");
server Server.implementation
in
let module Client =
Test_common.Test_interface.Interface (GenClient (struct
let rpc = server
end))
in
Alcotest.(check int) "add" 4 (Client.add 1 3);
Alcotest.(check int) "sub" 2 (Client.sub 3 1);
Alcotest.(check int) "mul" 6 (Client.mul 2 3);
Alcotest.(check int) "div" 4 (Client.div 8 2);
Alcotest.(check string) "ping" "OK" (Client.ping ())
let tests = [ "test_call_core", `Quick, test_call_core ]
|
dd3c00825b6282f9ca5929d44b9ae28852b837454ff8faa5f7f4936ae001c6eb | mistupv/cauder | cauder_wx_dialog.erl | -module(cauder_wx_dialog).
%% API
-export([start_session/2, stop_session/1]).
-export([edit_binding/2]).
-export([choose_message/2]).
-export([drop_files/2]).
-export([about/1]).
% TODO Remove
-elvis([{elvis_style, nesting_level, #{ignore => [cauder_wx_dialog, start_session, 2]}}]).
-include("cauder.hrl").
-include("cauder_message.hrl").
-include("cauder_wx.hrl").
-include_lib("wx/include/wx.hrl").
%%------------------------------------------------------------------------------
%% @doc Shows a dialog where the use can choose the execution mode, with the
%% required information in each case.
-spec start_session(Parent, EntryPoints) ->
{manual, {Node, Module, Function, Args}} | {replay, TracePath} | false
when
Parent :: wxWindow:wxWindow(),
EntryPoints :: [mfa()],
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: cauder_syntax:af_args(),
TracePath :: file:filename().
start_session(Parent, MFAs) ->
Dialog = wxDialog:new(Parent, ?wxID_ANY, ?DIALOG_StartSession_Title),
Content = wxBoxSizer:new(?wxVERTICAL),
wxDialog:setSizer(Dialog, Content),
%% ----- Content ----- %%
Grid = wxFlexGridSizer:new(2, 2, ?SPACER_LARGE, ?SPACER_MEDIUM),
wxBoxSizer:add(Content, Grid, [{flag, ?wxEXPAND bor ?wxALL}, {border, ?SPACER_LARGE}]),
Manual Radio
ManualRadio = wxRadioButton:new(Dialog, ?wxID_ANY, "Manual"),
wxFlexGridSizer:add(Grid, ManualRadio, [{flag, ?wxALIGN_CENTER_VERTICAL}]),
wxRadioButton:setValue(ManualRadio, true),
Manual Panel
ManualPanel = wxPanel:new(Dialog),
wxFlexGridSizer:add(Grid, ManualPanel),
ManualSizer = wxBoxSizer:new(?wxHORIZONTAL),
wxPanel:setSizer(ManualPanel, ManualSizer),
FunChoice = wxChoice:new(ManualPanel, ?wxID_ANY, [{size, {250, -1}}]),
wxBoxSizer:add(ManualSizer, FunChoice),
lists:foreach(
fun({M, F, A} = MFA) -> wxChoice:append(FunChoice, io_lib:format("~p:~p/~b", [M, F, A]), MFA) end,
MFAs
),
case lists:keyfind(start, 2, MFAs) of
{M, F, A} ->
wxChoice:setStringSelection(FunChoice, io_lib:format("~p:~p/~b", [M, F, A]));
false ->
case lists:keyfind(main, 2, MFAs) of
{M, F, A} -> wxChoice:setStringSelection(FunChoice, io_lib:format("~p:~p/~b", [M, F, A]));
false -> wxChoice:setSelection(FunChoice, 0)
end
end,
wxBoxSizer:addSpacer(ManualSizer, ?SPACER_SMALL),
ArgsLabel = wxStaticText:new(ManualPanel, ?wxID_ANY, "Arguments: "),
wxBoxSizer:add(ManualSizer, ArgsLabel),
ArgsCtrl = wxTextCtrl:new(ManualPanel, ?wxID_ANY, [{size, {250, -1}}]),
wxBoxSizer:add(ManualSizer, ArgsCtrl),
wxBoxSizer:addSpacer(ManualSizer, ?SPACER_SMALL),
NodeLabel = wxStaticText:new(ManualPanel, ?wxID_ANY, "Node name: "),
wxBoxSizer:add(ManualSizer, NodeLabel),
NodeName = wxTextCtrl:new(ManualPanel, ?wxID_ANY, [{size, {250, -1}}]),
wxBoxSizer:add(ManualSizer, NodeName),
Index = wxChoice:getSelection(FunChoice),
{_, _, Arity} = wxChoice:getClientData(FunChoice, Index),
wxTextCtrl:enable(ArgsCtrl, [{enable, Arity > 0}]),
Replay Radio
ReplayRadio = wxRadioButton:new(Dialog, ?wxID_ANY, "Replay"),
wxFlexGridSizer:add(Grid, ReplayRadio, [{flag, ?wxALIGN_CENTER_VERTICAL}]),
Replay Panel
ReplayPanel = wxPanel:new(Dialog),
wxFlexGridSizer:add(Grid, ReplayPanel, [{flag, ?wxEXPAND}]),
ReplaySizer = wxBoxSizer:new(?wxHORIZONTAL),
wxPanel:setSizer(ReplayPanel, ReplaySizer),
BasePath = cauder:get_path(),
TracePath = filename:join(BasePath, "trace"),
PickerPath =
case filelib:is_dir(TracePath) of
true -> TracePath;
false -> BasePath
end,
PickerOpts = [
{message, "Select a log folder"},
{style, ?wxDIRP_DIR_MUST_EXIST bor ?wxDIRP_USE_TEXTCTRL}
],
TracePicker = wxDirPickerCtrl:new(ReplayPanel, ?wxID_ANY, [{path, PickerPath} | PickerOpts]),
wxBoxSizer:add(ReplaySizer, TracePicker, [{proportion, 1}, {flag, ?wxEXPAND}]),
wxDirPickerCtrl:setTextCtrlGrowable(TracePicker),
%% -----
Separator = wxStaticLine:new(Dialog, [{style, ?wxLI_HORIZONTAL}]),
wxBoxSizer:add(Content, Separator, [{flag, ?wxEXPAND}]),
%% ----- Buttons ----- %%
ReturnPid = self(),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Content, Buttons, [{flag, ?wxALIGN_RIGHT bor ?wxALL}, {border, ?SPACER_LARGE}]),
StartButton = wxButton:new(Dialog, ?wxID_OK, [{label, "Start"}]),
wxBoxSizer:add(Buttons, StartButton),
Callback =
fun(_, _) ->
case wxRadioButton:getValue(ManualRadio) of
true ->
{M1, F1, A1} = wxChoice:getClientData(FunChoice, wxChoice:getSelection(FunChoice)),
case cauder_utils:string_to_expressions(wxTextCtrl:getValue(ArgsCtrl)) of
error ->
Message = ?DIALOG_BadArgs_Message,
Options = [{caption, ?DIALOG_BadArgs_Title}, {style, ?wxICON_ERROR}],
wxMessageDialog:showModal(wxMessageDialog:new(Dialog, Message, Options));
Args ->
case length(Args) of
A1 ->
N1 = wxTextCtrl:getValue(NodeName),
case cauder_utils:check_node_name(N1) of
ok ->
ReturnPid ! {manual, {list_to_atom(N1), M1, F1, Args}};
not_provided ->
ReturnPid ! {manual, {'nonode@nohost', M1, F1, Args}};
error ->
Message = io_lib:format(?DIALOG_StartSession_NodeName_Message, []),
Options = [
{caption, ?DIALOG_StartSession_NodeName_Title},
{style, ?wxICON_WARNING}
],
wxMessageDialog:showModal(wxMessageDialog:new(Dialog, Message, Options))
end;
Count ->
Message = io_lib:format(?DIALOG_StartSession_ArgCount_Message, [A1, Count]),
Options = [
{caption, ?DIALOG_StartSession_ArgCount_Title},
{style, ?wxICON_WARNING}
],
wxMessageDialog:showModal(wxMessageDialog:new(Dialog, Message, Options))
end
end;
false ->
ReturnPid ! {replay, wxDirPickerCtrl:getPath(TracePicker)}
end
end,
wxButton:connect(StartButton, command_button_clicked, [{callback, Callback}]),
wxBoxSizer:addSpacer(Buttons, ?SPACER_MEDIUM),
CancelButton = wxButton:new(Dialog, ?wxID_CANCEL, [{label, "Cancel"}]),
wxBoxSizer:add(Buttons, CancelButton),
wxButton:connect(CancelButton, command_button_clicked, [{callback, fun(_, _) -> ReturnPid ! false end}]),
%% -----
event_handler_entry_point(FunChoice, ArgsCtrl),
event_handler_start_mode(#{ManualRadio => ManualPanel, ReplayRadio => ReplayPanel}),
wxWindow:enable(ReplayPanel, [{enable, false}]),
%% -----
wxDialog:fit(Dialog),
wxDialog:show(Dialog),
receive
Return ->
wxDialog:destroy(Dialog),
Return
end.
event_handler_entry_point(Choice, TextCtrl) ->
Callback =
fun(_, _) ->
Index = wxChoice:getSelection(Choice),
{_, _, Arity} = wxChoice:getClientData(Choice, Index),
wxTextCtrl:enable(TextCtrl, [{enable, Arity > 0}])
end,
wxChoice:connect(Choice, command_choice_selected, [{callback, Callback}]).
event_handler_start_mode(RadioPanels) ->
lists:foreach(
fun(Radio) ->
{ThisPanel, OtherPanels} = maps:take(Radio, RadioPanels),
Callback =
fun(_, _) ->
wxWindow:enable(ThisPanel, [{enable, true}]),
lists:foreach(fun(Panel) -> wxWindow:enable(Panel, [{enable, false}]) end, maps:values(OtherPanels))
end,
wxRadioButton:connect(Radio, command_radiobutton_selected, [{callback, Callback}])
end,
maps:keys(RadioPanels)
).
%%------------------------------------------------------------------------------
%% @doc Shows a dialog warning the user that s/he is about to stop the session,
%% loosing any unsaved data.
-spec stop_session(Parent) -> Result when
Parent :: wxWindow:wxWindow(),
Result :: boolean().
stop_session(Parent) ->
Options = [{style, ?wxICON_EXCLAMATION bor ?wxYES_NO bor ?wxNO_DEFAULT}, {caption, ?DIALOG_StopSession_Title}],
Dialog = wxMessageDialog:new(Parent, ?DIALOG_StopSession_Message, Options),
case wxDialog:showModal(Dialog) of
?wxID_YES -> true;
_ -> false
end.
%%------------------------------------------------------------------------------
%% @doc Shows a dialog that allows the user to change the value of the given
%% binding.
-spec edit_binding(Parent, Binding) -> NewBinding | cancel when
Parent :: wxWindow:wxWindow(),
Binding :: cauder_process:binding(),
NewBinding :: cauder_process:binding().
edit_binding(Parent, {Key, Value}) ->
Dialog = wxDialog:new(Parent, ?wxID_ANY, "Edit binding"),
Content = wxBoxSizer:new(?wxVERTICAL),
wxDialog:setSizer(Dialog, Content),
%% ----- Input ----- %%
Input = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Content, Input, [{flag, ?wxEXPAND bor ?wxALL}, {border, ?SPACER_LARGE}]),
%% Name
NameSizer = wxBoxSizer:new(?wxVERTICAL),
wxBoxSizer:add(Input, NameSizer, [{proportion, 1}]),
NameStatic = wxStaticText:new(Dialog, ?wxID_ANY, "Name"),
wxBoxSizer:add(NameSizer, NameStatic),
wxBoxSizer:addSpacer(NameSizer, ?SPACER_SMALL),
NameText = wxTextCtrl:new(Dialog, ?wxID_ANY, [{value, atom_to_list(Key)}, {style, ?wxTE_READONLY}]),
wxBoxSizer:add(NameSizer, NameText, [{flag, ?wxEXPAND}]),
%% -----
wxBoxSizer:addSpacer(Input, ?SPACER_MEDIUM),
%% Value
ValueSizer = wxBoxSizer:new(?wxVERTICAL),
wxBoxSizer:add(Input, ValueSizer, [{proportion, 2}]),
ValueStatic = wxStaticText:new(Dialog, ?wxID_ANY, "Value"),
wxBoxSizer:add(ValueSizer, ValueStatic),
wxBoxSizer:addSpacer(ValueSizer, ?SPACER_SMALL),
ValueText = wxTextCtrl:new(Dialog, ?wxID_ANY, [{value, io_lib:format("~p", [Value])}]),
wxBoxSizer:add(ValueSizer, ValueText, [{flag, ?wxEXPAND}]),
%% -----
Separator = wxStaticLine:new(Dialog, [{style, ?wxLI_HORIZONTAL}]),
wxBoxSizer:add(Content, Separator, [{flag, ?wxEXPAND}]),
%% ----- Buttons ----- %%
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Content, Buttons, [{flag, ?wxALIGN_RIGHT bor ?wxALL}, {border, ?SPACER_LARGE}]),
SaveButton = wxButton:new(Dialog, ?wxID_OK, [{label, "Save"}]),
wxBoxSizer:add(Buttons, SaveButton),
wxBoxSizer:addSpacer(Buttons, ?SPACER_MEDIUM),
CancelButton = wxButton:new(Dialog, ?wxID_CANCEL, [{label, "Cancel"}]),
wxBoxSizer:add(Buttons, CancelButton),
%% -----
wxDialog:fit(Dialog),
case wxDialog:showModal(Dialog) of
?wxID_OK ->
Str = wxTextCtrl:getValue(ValueText),
case cauder_utils:string_to_expressions(Str) of
[{value, _, NewValue}] -> {Key, NewValue};
_ -> cancel
end;
_ ->
cancel
end.
%%------------------------------------------------------------------------------
%% @doc Shows a dialog that allows the user to choose a messages from a lists of
%% messages.
-spec choose_message(Parent, {Receiver, Messages}) -> {ok, MessageId} | cancel when
Parent :: wxWindow:wxWindow(),
Receiver :: cauder_process:id(),
Messages :: [cauder_message:message()],
MessageId :: cauder_message:uid().
choose_message(Parent, {Receiver, Messages}) ->
Dialog = wxDialog:new(Parent, ?wxID_ANY, "Choose a message"),
Sizer = wxBoxSizer:new(?wxVERTICAL),
wxDialog:setSizer(Dialog, Sizer),
%% ----- Content ----- %%
Content = wxBoxSizer:new(?wxVERTICAL),
wxBoxSizer:add(Sizer, Content, [{flag, ?wxEXPAND bor ?wxALL}, {border, ?SPACER_LARGE}]),
HeaderText = wxStaticText:new(
Dialog,
?wxID_ANY,
io_lib:format("Choose the message to be received by process ~p.", [Receiver])
),
wxBoxSizer:add(Content, HeaderText, [{proportion, 0}]),
%% -----
wxBoxSizer:addSpacer(Content, ?SPACER_LARGE),
%% -----
MessageList = wxListCtrl:new(Dialog, [{style, ?wxLC_REPORT bor ?wxLC_SINGLE_SEL}]),
wxBoxSizer:add(Content, MessageList, [{proportion, 1}, {flag, ?wxEXPAND}]),
Item = wxListItem:new(),
Font = wxFont:new(9, ?wxTELETYPE, ?wxNORMAL, ?wxNORMAL),
wxListItem:setText(Item, "UID"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 0, Item),
wxListItem:setText(Item, "Value"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 1, Item),
wxListItem:setText(Item, "Source"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 2, Item),
wxListItem:setText(Item, "Destination"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 3, Item),
wxListItem:destroy(Item),
wxListCtrl:setColumnWidth(MessageList, 0, 50),
wxListCtrl:setColumnWidth(MessageList, 1, 200),
wxListCtrl:setColumnWidth(MessageList, 2, 75),
wxListCtrl:setColumnWidth(MessageList, 3, 75),
lists:foldl(
fun(#message{uid = Uid, src = Src, dst = Dst, val = Val}, Row) ->
wxListCtrl:insertItem(MessageList, Row, ""),
wxListCtrl:setItemFont(MessageList, Row, Font),
wxListCtrl:setItem(MessageList, Row, 0, cauder_pp:to_string(Uid)),
wxListCtrl:setItem(MessageList, Row, 1, cauder_pp:to_string(Val)),
wxListCtrl:setItem(MessageList, Row, 2, cauder_pp:to_string(Src)),
wxListCtrl:setItem(MessageList, Row, 3, cauder_pp:to_string(Dst)),
Row + 1
end,
0,
Messages
),
%% -----
Separator = wxStaticLine:new(Dialog, [{style, ?wxLI_HORIZONTAL}]),
wxBoxSizer:add(Sizer, Separator, [{flag, ?wxEXPAND}]),
%% ----- Buttons ----- %%
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Sizer, Buttons, [{flag, ?wxALIGN_RIGHT bor ?wxALL}, {border, ?SPACER_LARGE}]),
ReceiveButton = wxButton:new(Dialog, ?wxID_OK, [{label, "Receive"}]),
wxButton:disable(ReceiveButton),
wxBoxSizer:add(Buttons, ReceiveButton),
wxBoxSizer:addSpacer(Buttons, ?SPACER_MEDIUM),
CancelButton = wxButton:new(Dialog, ?wxID_CANCEL, [{label, "Cancel"}]),
wxBoxSizer:add(Buttons, CancelButton),
%% -----
ItemFocusedCallback =
fun(#wx{event = #wxList{itemIndex = Idx}}, _) ->
wxButton:enable(ReceiveButton, [{enable, Idx =/= ?wxNOT_FOUND}])
end,
ItemActivatedCallback =
fun(#wx{event = #wxList{itemIndex = Idx}}, _) when Idx =/= ?wxNOT_FOUND ->
wxDialog:endModal(Dialog, ?wxID_OK)
end,
wxListCtrl:connect(MessageList, command_list_item_focused, [{callback, ItemFocusedCallback}]),
wxListCtrl:connect(MessageList, command_list_item_activated, [{callback, ItemActivatedCallback}]),
wxDialog:fit(Dialog),
case wxDialog:showModal(Dialog) of
?wxID_OK ->
Idx = wxListCtrl:getNextItem(MessageList, -1, [{state, ?wxLIST_STATE_SELECTED}]),
Message = lists:nth(Idx + 1, Messages),
{ok, Message#message.uid};
_ ->
cancel
end.
%%------------------------------------------------------------------------------
@doc If the given list of files has more than one file , or any unsupported
%% file, a dialog will be shown to inform the user.
-spec drop_files(Parent, Files) -> {ok, File} | false when
Parent :: wxWindow:wxWindow(),
Files :: [unicode:chardata()],
File :: unicode:chardata().
drop_files(Parent, Files) ->
{ErlFiles, NonErlFiles} = lists:partition(fun(File) -> filename:extension(File) =:= ".erl" end, Files),
case NonErlFiles =/= [] of
true ->
Options = [{style, ?wxICON_ERROR bor ?wxOK}, {caption, ?DIALOG_DropFiles_Unsupported_Title}],
Dialog = wxMessageDialog:new(Parent, ?DIALOG_DropFiles_Unsupported_Message, Options),
wxMessageDialog:showModal(Dialog),
false;
false ->
case ErlFiles of
[File] ->
{ok, File};
_ ->
Dialog = wxSingleChoiceDialog:new(
Parent,
?DIALOG_DropFiles_Multiple_Message,
?DIALOG_DropFiles_Multiple_Title,
ErlFiles
),
case wxSingleChoiceDialog:showModal(Dialog) of
?wxID_OK -> {ok, wxSingleChoiceDialog:getStringSelection(Dialog)};
_ -> false
end
end
end.
%%------------------------------------------------------------------------------
%% @doc Shows a dialog with some basic information about CauDEr.
-spec about(Parent :: wxWindow:wxWindow()) -> ok.
about(Parent) ->
Caption = "About " ++ ?APP_NAME,
Dialog = wxMessageDialog:new(Parent, ?DIALOG_About, [{style, ?wxOK}, {caption, Caption}]),
wxDialog:showModal(Dialog),
wxWindow:destroy(Dialog).
| null | https://raw.githubusercontent.com/mistupv/cauder/c9bfb72a4aed70979e53f4b3ca4a085a19b6c195/src/cauder_wx_dialog.erl | erlang | API
TODO Remove
------------------------------------------------------------------------------
@doc Shows a dialog where the use can choose the execution mode, with the
required information in each case.
----- Content ----- %%
-----
----- Buttons ----- %%
-----
-----
------------------------------------------------------------------------------
@doc Shows a dialog warning the user that s/he is about to stop the session,
loosing any unsaved data.
------------------------------------------------------------------------------
@doc Shows a dialog that allows the user to change the value of the given
binding.
----- Input ----- %%
Name
-----
Value
-----
----- Buttons ----- %%
-----
------------------------------------------------------------------------------
@doc Shows a dialog that allows the user to choose a messages from a lists of
messages.
----- Content ----- %%
-----
-----
-----
----- Buttons ----- %%
-----
------------------------------------------------------------------------------
file, a dialog will be shown to inform the user.
------------------------------------------------------------------------------
@doc Shows a dialog with some basic information about CauDEr. | -module(cauder_wx_dialog).
-export([start_session/2, stop_session/1]).
-export([edit_binding/2]).
-export([choose_message/2]).
-export([drop_files/2]).
-export([about/1]).
-elvis([{elvis_style, nesting_level, #{ignore => [cauder_wx_dialog, start_session, 2]}}]).
-include("cauder.hrl").
-include("cauder_message.hrl").
-include("cauder_wx.hrl").
-include_lib("wx/include/wx.hrl").
-spec start_session(Parent, EntryPoints) ->
{manual, {Node, Module, Function, Args}} | {replay, TracePath} | false
when
Parent :: wxWindow:wxWindow(),
EntryPoints :: [mfa()],
Node :: node(),
Module :: module(),
Function :: atom(),
Args :: cauder_syntax:af_args(),
TracePath :: file:filename().
start_session(Parent, MFAs) ->
Dialog = wxDialog:new(Parent, ?wxID_ANY, ?DIALOG_StartSession_Title),
Content = wxBoxSizer:new(?wxVERTICAL),
wxDialog:setSizer(Dialog, Content),
Grid = wxFlexGridSizer:new(2, 2, ?SPACER_LARGE, ?SPACER_MEDIUM),
wxBoxSizer:add(Content, Grid, [{flag, ?wxEXPAND bor ?wxALL}, {border, ?SPACER_LARGE}]),
Manual Radio
ManualRadio = wxRadioButton:new(Dialog, ?wxID_ANY, "Manual"),
wxFlexGridSizer:add(Grid, ManualRadio, [{flag, ?wxALIGN_CENTER_VERTICAL}]),
wxRadioButton:setValue(ManualRadio, true),
Manual Panel
ManualPanel = wxPanel:new(Dialog),
wxFlexGridSizer:add(Grid, ManualPanel),
ManualSizer = wxBoxSizer:new(?wxHORIZONTAL),
wxPanel:setSizer(ManualPanel, ManualSizer),
FunChoice = wxChoice:new(ManualPanel, ?wxID_ANY, [{size, {250, -1}}]),
wxBoxSizer:add(ManualSizer, FunChoice),
lists:foreach(
fun({M, F, A} = MFA) -> wxChoice:append(FunChoice, io_lib:format("~p:~p/~b", [M, F, A]), MFA) end,
MFAs
),
case lists:keyfind(start, 2, MFAs) of
{M, F, A} ->
wxChoice:setStringSelection(FunChoice, io_lib:format("~p:~p/~b", [M, F, A]));
false ->
case lists:keyfind(main, 2, MFAs) of
{M, F, A} -> wxChoice:setStringSelection(FunChoice, io_lib:format("~p:~p/~b", [M, F, A]));
false -> wxChoice:setSelection(FunChoice, 0)
end
end,
wxBoxSizer:addSpacer(ManualSizer, ?SPACER_SMALL),
ArgsLabel = wxStaticText:new(ManualPanel, ?wxID_ANY, "Arguments: "),
wxBoxSizer:add(ManualSizer, ArgsLabel),
ArgsCtrl = wxTextCtrl:new(ManualPanel, ?wxID_ANY, [{size, {250, -1}}]),
wxBoxSizer:add(ManualSizer, ArgsCtrl),
wxBoxSizer:addSpacer(ManualSizer, ?SPACER_SMALL),
NodeLabel = wxStaticText:new(ManualPanel, ?wxID_ANY, "Node name: "),
wxBoxSizer:add(ManualSizer, NodeLabel),
NodeName = wxTextCtrl:new(ManualPanel, ?wxID_ANY, [{size, {250, -1}}]),
wxBoxSizer:add(ManualSizer, NodeName),
Index = wxChoice:getSelection(FunChoice),
{_, _, Arity} = wxChoice:getClientData(FunChoice, Index),
wxTextCtrl:enable(ArgsCtrl, [{enable, Arity > 0}]),
Replay Radio
ReplayRadio = wxRadioButton:new(Dialog, ?wxID_ANY, "Replay"),
wxFlexGridSizer:add(Grid, ReplayRadio, [{flag, ?wxALIGN_CENTER_VERTICAL}]),
Replay Panel
ReplayPanel = wxPanel:new(Dialog),
wxFlexGridSizer:add(Grid, ReplayPanel, [{flag, ?wxEXPAND}]),
ReplaySizer = wxBoxSizer:new(?wxHORIZONTAL),
wxPanel:setSizer(ReplayPanel, ReplaySizer),
BasePath = cauder:get_path(),
TracePath = filename:join(BasePath, "trace"),
PickerPath =
case filelib:is_dir(TracePath) of
true -> TracePath;
false -> BasePath
end,
PickerOpts = [
{message, "Select a log folder"},
{style, ?wxDIRP_DIR_MUST_EXIST bor ?wxDIRP_USE_TEXTCTRL}
],
TracePicker = wxDirPickerCtrl:new(ReplayPanel, ?wxID_ANY, [{path, PickerPath} | PickerOpts]),
wxBoxSizer:add(ReplaySizer, TracePicker, [{proportion, 1}, {flag, ?wxEXPAND}]),
wxDirPickerCtrl:setTextCtrlGrowable(TracePicker),
Separator = wxStaticLine:new(Dialog, [{style, ?wxLI_HORIZONTAL}]),
wxBoxSizer:add(Content, Separator, [{flag, ?wxEXPAND}]),
ReturnPid = self(),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Content, Buttons, [{flag, ?wxALIGN_RIGHT bor ?wxALL}, {border, ?SPACER_LARGE}]),
StartButton = wxButton:new(Dialog, ?wxID_OK, [{label, "Start"}]),
wxBoxSizer:add(Buttons, StartButton),
Callback =
fun(_, _) ->
case wxRadioButton:getValue(ManualRadio) of
true ->
{M1, F1, A1} = wxChoice:getClientData(FunChoice, wxChoice:getSelection(FunChoice)),
case cauder_utils:string_to_expressions(wxTextCtrl:getValue(ArgsCtrl)) of
error ->
Message = ?DIALOG_BadArgs_Message,
Options = [{caption, ?DIALOG_BadArgs_Title}, {style, ?wxICON_ERROR}],
wxMessageDialog:showModal(wxMessageDialog:new(Dialog, Message, Options));
Args ->
case length(Args) of
A1 ->
N1 = wxTextCtrl:getValue(NodeName),
case cauder_utils:check_node_name(N1) of
ok ->
ReturnPid ! {manual, {list_to_atom(N1), M1, F1, Args}};
not_provided ->
ReturnPid ! {manual, {'nonode@nohost', M1, F1, Args}};
error ->
Message = io_lib:format(?DIALOG_StartSession_NodeName_Message, []),
Options = [
{caption, ?DIALOG_StartSession_NodeName_Title},
{style, ?wxICON_WARNING}
],
wxMessageDialog:showModal(wxMessageDialog:new(Dialog, Message, Options))
end;
Count ->
Message = io_lib:format(?DIALOG_StartSession_ArgCount_Message, [A1, Count]),
Options = [
{caption, ?DIALOG_StartSession_ArgCount_Title},
{style, ?wxICON_WARNING}
],
wxMessageDialog:showModal(wxMessageDialog:new(Dialog, Message, Options))
end
end;
false ->
ReturnPid ! {replay, wxDirPickerCtrl:getPath(TracePicker)}
end
end,
wxButton:connect(StartButton, command_button_clicked, [{callback, Callback}]),
wxBoxSizer:addSpacer(Buttons, ?SPACER_MEDIUM),
CancelButton = wxButton:new(Dialog, ?wxID_CANCEL, [{label, "Cancel"}]),
wxBoxSizer:add(Buttons, CancelButton),
wxButton:connect(CancelButton, command_button_clicked, [{callback, fun(_, _) -> ReturnPid ! false end}]),
event_handler_entry_point(FunChoice, ArgsCtrl),
event_handler_start_mode(#{ManualRadio => ManualPanel, ReplayRadio => ReplayPanel}),
wxWindow:enable(ReplayPanel, [{enable, false}]),
wxDialog:fit(Dialog),
wxDialog:show(Dialog),
receive
Return ->
wxDialog:destroy(Dialog),
Return
end.
event_handler_entry_point(Choice, TextCtrl) ->
Callback =
fun(_, _) ->
Index = wxChoice:getSelection(Choice),
{_, _, Arity} = wxChoice:getClientData(Choice, Index),
wxTextCtrl:enable(TextCtrl, [{enable, Arity > 0}])
end,
wxChoice:connect(Choice, command_choice_selected, [{callback, Callback}]).
event_handler_start_mode(RadioPanels) ->
lists:foreach(
fun(Radio) ->
{ThisPanel, OtherPanels} = maps:take(Radio, RadioPanels),
Callback =
fun(_, _) ->
wxWindow:enable(ThisPanel, [{enable, true}]),
lists:foreach(fun(Panel) -> wxWindow:enable(Panel, [{enable, false}]) end, maps:values(OtherPanels))
end,
wxRadioButton:connect(Radio, command_radiobutton_selected, [{callback, Callback}])
end,
maps:keys(RadioPanels)
).
-spec stop_session(Parent) -> Result when
Parent :: wxWindow:wxWindow(),
Result :: boolean().
stop_session(Parent) ->
Options = [{style, ?wxICON_EXCLAMATION bor ?wxYES_NO bor ?wxNO_DEFAULT}, {caption, ?DIALOG_StopSession_Title}],
Dialog = wxMessageDialog:new(Parent, ?DIALOG_StopSession_Message, Options),
case wxDialog:showModal(Dialog) of
?wxID_YES -> true;
_ -> false
end.
-spec edit_binding(Parent, Binding) -> NewBinding | cancel when
Parent :: wxWindow:wxWindow(),
Binding :: cauder_process:binding(),
NewBinding :: cauder_process:binding().
edit_binding(Parent, {Key, Value}) ->
Dialog = wxDialog:new(Parent, ?wxID_ANY, "Edit binding"),
Content = wxBoxSizer:new(?wxVERTICAL),
wxDialog:setSizer(Dialog, Content),
Input = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Content, Input, [{flag, ?wxEXPAND bor ?wxALL}, {border, ?SPACER_LARGE}]),
NameSizer = wxBoxSizer:new(?wxVERTICAL),
wxBoxSizer:add(Input, NameSizer, [{proportion, 1}]),
NameStatic = wxStaticText:new(Dialog, ?wxID_ANY, "Name"),
wxBoxSizer:add(NameSizer, NameStatic),
wxBoxSizer:addSpacer(NameSizer, ?SPACER_SMALL),
NameText = wxTextCtrl:new(Dialog, ?wxID_ANY, [{value, atom_to_list(Key)}, {style, ?wxTE_READONLY}]),
wxBoxSizer:add(NameSizer, NameText, [{flag, ?wxEXPAND}]),
wxBoxSizer:addSpacer(Input, ?SPACER_MEDIUM),
ValueSizer = wxBoxSizer:new(?wxVERTICAL),
wxBoxSizer:add(Input, ValueSizer, [{proportion, 2}]),
ValueStatic = wxStaticText:new(Dialog, ?wxID_ANY, "Value"),
wxBoxSizer:add(ValueSizer, ValueStatic),
wxBoxSizer:addSpacer(ValueSizer, ?SPACER_SMALL),
ValueText = wxTextCtrl:new(Dialog, ?wxID_ANY, [{value, io_lib:format("~p", [Value])}]),
wxBoxSizer:add(ValueSizer, ValueText, [{flag, ?wxEXPAND}]),
Separator = wxStaticLine:new(Dialog, [{style, ?wxLI_HORIZONTAL}]),
wxBoxSizer:add(Content, Separator, [{flag, ?wxEXPAND}]),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Content, Buttons, [{flag, ?wxALIGN_RIGHT bor ?wxALL}, {border, ?SPACER_LARGE}]),
SaveButton = wxButton:new(Dialog, ?wxID_OK, [{label, "Save"}]),
wxBoxSizer:add(Buttons, SaveButton),
wxBoxSizer:addSpacer(Buttons, ?SPACER_MEDIUM),
CancelButton = wxButton:new(Dialog, ?wxID_CANCEL, [{label, "Cancel"}]),
wxBoxSizer:add(Buttons, CancelButton),
wxDialog:fit(Dialog),
case wxDialog:showModal(Dialog) of
?wxID_OK ->
Str = wxTextCtrl:getValue(ValueText),
case cauder_utils:string_to_expressions(Str) of
[{value, _, NewValue}] -> {Key, NewValue};
_ -> cancel
end;
_ ->
cancel
end.
-spec choose_message(Parent, {Receiver, Messages}) -> {ok, MessageId} | cancel when
Parent :: wxWindow:wxWindow(),
Receiver :: cauder_process:id(),
Messages :: [cauder_message:message()],
MessageId :: cauder_message:uid().
choose_message(Parent, {Receiver, Messages}) ->
Dialog = wxDialog:new(Parent, ?wxID_ANY, "Choose a message"),
Sizer = wxBoxSizer:new(?wxVERTICAL),
wxDialog:setSizer(Dialog, Sizer),
Content = wxBoxSizer:new(?wxVERTICAL),
wxBoxSizer:add(Sizer, Content, [{flag, ?wxEXPAND bor ?wxALL}, {border, ?SPACER_LARGE}]),
HeaderText = wxStaticText:new(
Dialog,
?wxID_ANY,
io_lib:format("Choose the message to be received by process ~p.", [Receiver])
),
wxBoxSizer:add(Content, HeaderText, [{proportion, 0}]),
wxBoxSizer:addSpacer(Content, ?SPACER_LARGE),
MessageList = wxListCtrl:new(Dialog, [{style, ?wxLC_REPORT bor ?wxLC_SINGLE_SEL}]),
wxBoxSizer:add(Content, MessageList, [{proportion, 1}, {flag, ?wxEXPAND}]),
Item = wxListItem:new(),
Font = wxFont:new(9, ?wxTELETYPE, ?wxNORMAL, ?wxNORMAL),
wxListItem:setText(Item, "UID"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 0, Item),
wxListItem:setText(Item, "Value"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 1, Item),
wxListItem:setText(Item, "Source"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 2, Item),
wxListItem:setText(Item, "Destination"),
wxListItem:setFont(Item, Font),
wxListCtrl:insertColumn(MessageList, 3, Item),
wxListItem:destroy(Item),
wxListCtrl:setColumnWidth(MessageList, 0, 50),
wxListCtrl:setColumnWidth(MessageList, 1, 200),
wxListCtrl:setColumnWidth(MessageList, 2, 75),
wxListCtrl:setColumnWidth(MessageList, 3, 75),
lists:foldl(
fun(#message{uid = Uid, src = Src, dst = Dst, val = Val}, Row) ->
wxListCtrl:insertItem(MessageList, Row, ""),
wxListCtrl:setItemFont(MessageList, Row, Font),
wxListCtrl:setItem(MessageList, Row, 0, cauder_pp:to_string(Uid)),
wxListCtrl:setItem(MessageList, Row, 1, cauder_pp:to_string(Val)),
wxListCtrl:setItem(MessageList, Row, 2, cauder_pp:to_string(Src)),
wxListCtrl:setItem(MessageList, Row, 3, cauder_pp:to_string(Dst)),
Row + 1
end,
0,
Messages
),
Separator = wxStaticLine:new(Dialog, [{style, ?wxLI_HORIZONTAL}]),
wxBoxSizer:add(Sizer, Separator, [{flag, ?wxEXPAND}]),
Buttons = wxBoxSizer:new(?wxHORIZONTAL),
wxBoxSizer:add(Sizer, Buttons, [{flag, ?wxALIGN_RIGHT bor ?wxALL}, {border, ?SPACER_LARGE}]),
ReceiveButton = wxButton:new(Dialog, ?wxID_OK, [{label, "Receive"}]),
wxButton:disable(ReceiveButton),
wxBoxSizer:add(Buttons, ReceiveButton),
wxBoxSizer:addSpacer(Buttons, ?SPACER_MEDIUM),
CancelButton = wxButton:new(Dialog, ?wxID_CANCEL, [{label, "Cancel"}]),
wxBoxSizer:add(Buttons, CancelButton),
ItemFocusedCallback =
fun(#wx{event = #wxList{itemIndex = Idx}}, _) ->
wxButton:enable(ReceiveButton, [{enable, Idx =/= ?wxNOT_FOUND}])
end,
ItemActivatedCallback =
fun(#wx{event = #wxList{itemIndex = Idx}}, _) when Idx =/= ?wxNOT_FOUND ->
wxDialog:endModal(Dialog, ?wxID_OK)
end,
wxListCtrl:connect(MessageList, command_list_item_focused, [{callback, ItemFocusedCallback}]),
wxListCtrl:connect(MessageList, command_list_item_activated, [{callback, ItemActivatedCallback}]),
wxDialog:fit(Dialog),
case wxDialog:showModal(Dialog) of
?wxID_OK ->
Idx = wxListCtrl:getNextItem(MessageList, -1, [{state, ?wxLIST_STATE_SELECTED}]),
Message = lists:nth(Idx + 1, Messages),
{ok, Message#message.uid};
_ ->
cancel
end.
@doc If the given list of files has more than one file , or any unsupported
-spec drop_files(Parent, Files) -> {ok, File} | false when
Parent :: wxWindow:wxWindow(),
Files :: [unicode:chardata()],
File :: unicode:chardata().
drop_files(Parent, Files) ->
{ErlFiles, NonErlFiles} = lists:partition(fun(File) -> filename:extension(File) =:= ".erl" end, Files),
case NonErlFiles =/= [] of
true ->
Options = [{style, ?wxICON_ERROR bor ?wxOK}, {caption, ?DIALOG_DropFiles_Unsupported_Title}],
Dialog = wxMessageDialog:new(Parent, ?DIALOG_DropFiles_Unsupported_Message, Options),
wxMessageDialog:showModal(Dialog),
false;
false ->
case ErlFiles of
[File] ->
{ok, File};
_ ->
Dialog = wxSingleChoiceDialog:new(
Parent,
?DIALOG_DropFiles_Multiple_Message,
?DIALOG_DropFiles_Multiple_Title,
ErlFiles
),
case wxSingleChoiceDialog:showModal(Dialog) of
?wxID_OK -> {ok, wxSingleChoiceDialog:getStringSelection(Dialog)};
_ -> false
end
end
end.
-spec about(Parent :: wxWindow:wxWindow()) -> ok.
about(Parent) ->
Caption = "About " ++ ?APP_NAME,
Dialog = wxMessageDialog:new(Parent, ?DIALOG_About, [{style, ?wxOK}, {caption, Caption}]),
wxDialog:showModal(Dialog),
wxWindow:destroy(Dialog).
|
dbef2f228c85cff1be3994a3931bbafd7abc6d9e6843ae839727ce1bb71daeb5 | vadimbakaev/flatmap.io | DevelMain.hs | -- | Running your app inside GHCi.
--
-- This option provides significantly faster code reload compared to
@yesod devel@. However , you do not get automatic code reload
-- (which may be a benefit, depending on your perspective). To use this:
--
1 . Start up GHCi
--
-- $ stack ghci h-map:lib --no-load --work-dir .stack-work-devel
--
2 . Load this module
--
-- > :l app/DevelMain.hs
--
3 . Run @update@
--
-- > DevelMain.update
--
4 . Your app should now be running , you can connect at :3000
--
5 . Make changes to your code
--
6 . After saving your changes , reload by running :
--
-- > :r
-- > DevelMain.update
--
-- You can also call @DevelMain.shutdown@ to stop the app
--
-- There is more information about this approach,
-- on the wiki:
--
-- WARNING: GHCi does not notice changes made to your template files.
-- If you change a template, you'll need to either exit GHCi and reload,
or manually @touch@ another Haskell module .
module DevelMain where
import Prelude
import Application (getApplicationRepl, shutdownApp)
import Control.Monad ((>=>))
import Control.Concurrent
import Data.IORef
import Foreign.Store
import Network.Wai.Handler.Warp
import GHC.Word
-- | Start or restart the server.
is from foreign - store .
-- A Store holds onto some data across ghci reloads
update :: IO ()
update = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
-- no server running
Nothing -> do
done <- storeAction doneStore newEmptyMVar
tid <- start done
_ <- storeAction (Store tidStoreNum) (newIORef tid)
return ()
-- server is already running
Just tidStore -> restartAppInNewThread tidStore
where
doneStore :: Store (MVar ())
doneStore = Store 0
shut the server down with killThread and wait for the done signal
restartAppInNewThread :: Store (IORef ThreadId) -> IO ()
restartAppInNewThread tidStore = modifyStoredIORef tidStore $ \tid -> do
killThread tid
withStore doneStore takeMVar
readStore doneStore >>= start
-- | Start the server in a separate thread.
start :: MVar () -- ^ Written to when the thread is killed.
-> IO ThreadId
start done = do
(port, site, app) <- getApplicationRepl
forkFinally
(runSettings (setPort port defaultSettings) app)
-- Note that this implies concurrency
-- between shutdownApp and the next app that is starting.
-- Normally this should be fine
(\_ -> putMVar done () >> shutdownApp site)
-- | kill the server
shutdown :: IO ()
shutdown = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
-- no server running
Nothing -> putStrLn "no Yesod app running"
Just tidStore -> do
withStore tidStore $ readIORef >=> killThread
putStrLn "Yesod app is shutdown"
tidStoreNum :: Word32
tidStoreNum = 1
modifyStoredIORef :: Store (IORef a) -> (a -> IO a) -> IO ()
modifyStoredIORef store f = withStore store $ \ref -> do
v <- readIORef ref
f v >>= writeIORef ref
| null | https://raw.githubusercontent.com/vadimbakaev/flatmap.io/766069a8b1317a1e5a4546f3358d04c3c901f693/app/DevelMain.hs | haskell | | Running your app inside GHCi.
This option provides significantly faster code reload compared to
(which may be a benefit, depending on your perspective). To use this:
$ stack ghci h-map:lib --no-load --work-dir .stack-work-devel
> :l app/DevelMain.hs
> DevelMain.update
> :r
> DevelMain.update
You can also call @DevelMain.shutdown@ to stop the app
There is more information about this approach,
on the wiki:
WARNING: GHCi does not notice changes made to your template files.
If you change a template, you'll need to either exit GHCi and reload,
| Start or restart the server.
A Store holds onto some data across ghci reloads
no server running
server is already running
| Start the server in a separate thread.
^ Written to when the thread is killed.
Note that this implies concurrency
between shutdownApp and the next app that is starting.
Normally this should be fine
| kill the server
no server running | @yesod devel@. However , you do not get automatic code reload
1 . Start up GHCi
2 . Load this module
3 . Run @update@
4 . Your app should now be running , you can connect at :3000
5 . Make changes to your code
6 . After saving your changes , reload by running :
or manually @touch@ another Haskell module .
module DevelMain where
import Prelude
import Application (getApplicationRepl, shutdownApp)
import Control.Monad ((>=>))
import Control.Concurrent
import Data.IORef
import Foreign.Store
import Network.Wai.Handler.Warp
import GHC.Word
is from foreign - store .
update :: IO ()
update = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
Nothing -> do
done <- storeAction doneStore newEmptyMVar
tid <- start done
_ <- storeAction (Store tidStoreNum) (newIORef tid)
return ()
Just tidStore -> restartAppInNewThread tidStore
where
doneStore :: Store (MVar ())
doneStore = Store 0
shut the server down with killThread and wait for the done signal
restartAppInNewThread :: Store (IORef ThreadId) -> IO ()
restartAppInNewThread tidStore = modifyStoredIORef tidStore $ \tid -> do
killThread tid
withStore doneStore takeMVar
readStore doneStore >>= start
-> IO ThreadId
start done = do
(port, site, app) <- getApplicationRepl
forkFinally
(runSettings (setPort port defaultSettings) app)
(\_ -> putMVar done () >> shutdownApp site)
shutdown :: IO ()
shutdown = do
mtidStore <- lookupStore tidStoreNum
case mtidStore of
Nothing -> putStrLn "no Yesod app running"
Just tidStore -> do
withStore tidStore $ readIORef >=> killThread
putStrLn "Yesod app is shutdown"
tidStoreNum :: Word32
tidStoreNum = 1
modifyStoredIORef :: Store (IORef a) -> (a -> IO a) -> IO ()
modifyStoredIORef store f = withStore store $ \ref -> do
v <- readIORef ref
f v >>= writeIORef ref
|
1c9ff05cc18791ace508586c39ef91ccfda87c761b85d14884d31ff17bcbf7f7 | rowangithub/DOrder | 16_tacas06.ml |
* From " A Practical and Complete Approach to Predicate Refinement " by
* From "A Practical and Complete Approach to Predicate Refinement" by McMillan TACAS'06
*)
let rec loop x y (i:int) (j:int) =
if (x <> 0) then
loop (x-1) (y-1) i j
else if (i = j) then assert (y = 0)
else ()
let main i j =
let x = i in
let y = j in
loop x y i j
let _ = main 10 10
let _ = main 9 9
let _ = main 3 (-3)
let _ = main 0 3 | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/folprograms/hola/16_tacas06.ml | ocaml |
* From " A Practical and Complete Approach to Predicate Refinement " by
* From "A Practical and Complete Approach to Predicate Refinement" by McMillan TACAS'06
*)
let rec loop x y (i:int) (j:int) =
if (x <> 0) then
loop (x-1) (y-1) i j
else if (i = j) then assert (y = 0)
else ()
let main i j =
let x = i in
let y = j in
loop x y i j
let _ = main 10 10
let _ = main 9 9
let _ = main 3 (-3)
let _ = main 0 3 | |
e88e7b6b4f086d664789e377d23f8968e731cdb6e22b1586b0c3a39f4f940474 | ivanjovanovic/sicp | e-2.2.scm | Exercise 2.2 .
;
; Consider the problem of representing line segments in a plane. Each segment is
; represented as a pair of points: a starting point and an ending point. Define a constructor
; make-segment and selectors start-segment and end-segment that define the representation of
; segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x
; coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors
; x-point and y-point that define this representation. Finally, using your selectors and constructors,
; define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint
; (the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures,
; you'll need a way to print points:
; needing average procedure
(load "../common.scm")
(define (print-point p)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")")
(newline))
; In the terms of wishful thinking we start by designing higher levels
of abstraction first , so we do not deal with details of implementation
; yet and just implement them when needed.
(define (make-segment sp ep)
(cons sp ep))
(define (start-segment s)
(car s))
(define (end-segment s)
(cdr s))
; Now we need points in fact
(define (make-point x y)
(cons x y))
(define (x-point p)
(car p))
(define (y-point p)
(cdr p))
(define start (make-point 0 0))
(define end (make-point 2 2))
; (print-point start)
; (print-point end)
; now we calculate midpoint which itself is a point with calculated
; coordinates. It receives segment as param
(define (mid-point s)
(make-point
(average (x-point (car s)) (x-point (cdr s)))
(average (y-point (car s)) (y-point (cdr s)))))
; (print-point (mid-point (make-segment start end)))
| null | https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/2.1/e-2.2.scm | scheme |
Consider the problem of representing line segments in a plane. Each segment is
represented as a pair of points: a starting point and an ending point. Define a constructor
make-segment and selectors start-segment and end-segment that define the representation of
segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x
coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors
x-point and y-point that define this representation. Finally, using your selectors and constructors,
define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint
(the point whose coordinates are the average of the coordinates of the endpoints). To try your procedures,
you'll need a way to print points:
needing average procedure
In the terms of wishful thinking we start by designing higher levels
yet and just implement them when needed.
Now we need points in fact
(print-point start)
(print-point end)
now we calculate midpoint which itself is a point with calculated
coordinates. It receives segment as param
(print-point (mid-point (make-segment start end))) | Exercise 2.2 .
(load "../common.scm")
(define (print-point p)
(display "(")
(display (x-point p))
(display ",")
(display (y-point p))
(display ")")
(newline))
of abstraction first , so we do not deal with details of implementation
(define (make-segment sp ep)
(cons sp ep))
(define (start-segment s)
(car s))
(define (end-segment s)
(cdr s))
(define (make-point x y)
(cons x y))
(define (x-point p)
(car p))
(define (y-point p)
(cdr p))
(define start (make-point 0 0))
(define end (make-point 2 2))
(define (mid-point s)
(make-point
(average (x-point (car s)) (x-point (cdr s)))
(average (y-point (car s)) (y-point (cdr s)))))
|
3a9dbfdb6281f783676431f2c8bd21fd57c05baab2025d4652020097487d87fd | byorgey/AoC | 18Fused.hs | # LANGUAGE FlexibleContexts #
import Control.Arrow
import Text.Parsec hiding (State)
import Text.Parsec.Expr
import Text.Parsec.Language (emptyDef)
import Text.Parsec.String
import qualified Text.Parsec.Token as T
main = interact $
lines >>> applyAll [solveA,solveB] >>> map show >>> unlines
------------------------------------------------------------
t = T.makeTokenParser emptyDef
int = T.integer t
parens = T.parens t
sym = T.symbol t
expr :: [[String]] -> Parser Integer
expr ops = e
where
e = buildExpressionParser opTable term
opTable = map (map (\op -> Infix (evalOp op <$ sym op) AssocLeft)) ops
term = int <|> parens e
evalOp "+" = (+)
evalOp "*" = (*)
------------------------------------------------------------
solveA, solveB :: [String] -> Integer
solveA = solveWith [["+","*"]]
solveB = solveWith [["+"], ["*"]]
solveWith ops = map (readParser (expr ops)) >>> sum
------------------------------------------------------------
applyAll :: [a -> b] -> a -> [b]
applyAll fs a = map ($ a) fs
readParser p = parse p "" >>> either undefined id
| null | https://raw.githubusercontent.com/byorgey/AoC/30eb51eb41af9ca86b05de598a3a96d25bd428e3/2020/18/18Fused.hs | haskell | ----------------------------------------------------------
----------------------------------------------------------
---------------------------------------------------------- | # LANGUAGE FlexibleContexts #
import Control.Arrow
import Text.Parsec hiding (State)
import Text.Parsec.Expr
import Text.Parsec.Language (emptyDef)
import Text.Parsec.String
import qualified Text.Parsec.Token as T
main = interact $
lines >>> applyAll [solveA,solveB] >>> map show >>> unlines
t = T.makeTokenParser emptyDef
int = T.integer t
parens = T.parens t
sym = T.symbol t
expr :: [[String]] -> Parser Integer
expr ops = e
where
e = buildExpressionParser opTable term
opTable = map (map (\op -> Infix (evalOp op <$ sym op) AssocLeft)) ops
term = int <|> parens e
evalOp "+" = (+)
evalOp "*" = (*)
solveA, solveB :: [String] -> Integer
solveA = solveWith [["+","*"]]
solveB = solveWith [["+"], ["*"]]
solveWith ops = map (readParser (expr ops)) >>> sum
applyAll :: [a -> b] -> a -> [b]
applyAll fs a = map ($ a) fs
readParser p = parse p "" >>> either undefined id
|
77ef08519af590340aa5445d02df4dfb53781557d4d5ec377ff22f4c58039a2d | Simre1/haskell-game | NonDet.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveFunctor #-}
# LANGUAGE NoPolyKinds #
# OPTIONS_HADDOCK not - home #
module Polysemy.Internal.NonDet where
------------------------------------------------------------------------------
-- | An effect corresponding to the 'Control.Applicative.Alternative' typeclass.
data NonDet m a
= Empty
| Choose (m a) (m a)
| null | https://raw.githubusercontent.com/Simre1/haskell-game/272a0674157aedc7b0e0ee00da8d3a464903dc67/polysemy/src/Polysemy/Internal/NonDet.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveFunctor #
----------------------------------------------------------------------------
| An effect corresponding to the 'Control.Applicative.Alternative' typeclass. | # LANGUAGE NoPolyKinds #
# OPTIONS_HADDOCK not - home #
module Polysemy.Internal.NonDet where
data NonDet m a
= Empty
| Choose (m a) (m a)
|
bf245c5830e32fe2d0f7c5df9545279b8c7a4fb60600d63a909cab1977496f96 | b1412/clojure-web-admin | excel.clj | (ns clojure-web.common.excel
(:require
[clojure-web.metadata-kit :refer [has-feature?]]
[clojure-web.db.entity
:refer
[get-all-columns-with-comment]]
[excel-templates.build :refer [render-to-file]]
[taoensso.timbre :as log]
[korma.core :refer [select]]))
(defn to-excel-data [entity-data columns]
(->> entity-data
(mapv (apply juxt (map keyword columns)))))
(defn export-file [entity]
(let [entity-data (select entity)
columns (->> (get-all-columns-with-comment (:table entity))
(filter (partial has-feature? :exportable))
(map (comp name :column-name))
(reduce conj []))
excel-data (to-excel-data entity-data columns)]
(log/info excel-data)
(render-to-file
"entity-template.xlsx"
(str "/tmp/" (:table entity) ".xlsx")
{"Entity" {0 [columns]
1 excel-data}})))
(defn export-excel-template [entity]
(let [entity-data (select entity)
columns (->> (get-all-columns-with-comment (:table entity))
(filter (partial has-feature? :importable))
(map (comp name :column-name))
(reduce conj []))]
(render-to-file
"empty.xlsx"
(str "/tmp/" (:table entity) "-template.xlsx")
{"Entity" {0 [columns]}})))
| null | https://raw.githubusercontent.com/b1412/clojure-web-admin/018161dcdb364cc168d6f5a56ceb798005a0701f/src/clj/clojure_web/common/excel.clj | clojure | (ns clojure-web.common.excel
(:require
[clojure-web.metadata-kit :refer [has-feature?]]
[clojure-web.db.entity
:refer
[get-all-columns-with-comment]]
[excel-templates.build :refer [render-to-file]]
[taoensso.timbre :as log]
[korma.core :refer [select]]))
(defn to-excel-data [entity-data columns]
(->> entity-data
(mapv (apply juxt (map keyword columns)))))
(defn export-file [entity]
(let [entity-data (select entity)
columns (->> (get-all-columns-with-comment (:table entity))
(filter (partial has-feature? :exportable))
(map (comp name :column-name))
(reduce conj []))
excel-data (to-excel-data entity-data columns)]
(log/info excel-data)
(render-to-file
"entity-template.xlsx"
(str "/tmp/" (:table entity) ".xlsx")
{"Entity" {0 [columns]
1 excel-data}})))
(defn export-excel-template [entity]
(let [entity-data (select entity)
columns (->> (get-all-columns-with-comment (:table entity))
(filter (partial has-feature? :importable))
(map (comp name :column-name))
(reduce conj []))]
(render-to-file
"empty.xlsx"
(str "/tmp/" (:table entity) "-template.xlsx")
{"Entity" {0 [columns]}})))
| |
4e9da48f935d19084bcb152c619f3fd1e22eaf4b657e3ac72d28f14e84b9edde | nikita-volkov/hasql-cursor-query | Transactions.hs | module Hasql.CursorQuery.Transactions
(
cursorQuery,
)
where
import Hasql.CursorQuery.Private.Transactions
| null | https://raw.githubusercontent.com/nikita-volkov/hasql-cursor-query/d249b02abac2ee8b77d4e0bd90f7a5d8c5161f83/library/Hasql/CursorQuery/Transactions.hs | haskell | module Hasql.CursorQuery.Transactions
(
cursorQuery,
)
where
import Hasql.CursorQuery.Private.Transactions
| |
9c07d9a419983d38d15b0e5bcf556be76d58f7adf769d0020d8b0f05b4419215 | SuYi1995/game_server | util.erl | %%%-------------------------------------------------------------------
%%% @author sy
( C ) 2019 , < COMPANY >
%%% @doc
%%% 通用工具模块
%%% @end
Created : 30 . 9月 2019 10:47
%%%-------------------------------------------------------------------
-module(util).
-include("common.hrl").
%% 数据库辅助相关
-export([
batch_insert/5,
batch_insert/6,
batch_insert/7,
insert_values/4,
insert_values/5,
insert_values/6,
format_values/2
]).
%% 列表 [lists, proplists]
-export([
prop_get_value/2,
prop_get_value/3,
prop_get_value/4,
prop_get_keys/1,
prop_delete/2,
prop_store/2,
prop_store/3,
list_rand/1,
list_rand_n/2,
merge_list/2,
multi_item_list/3,
acc_attr_list/2,
acc_attr_list/3,
max_attr_list/2
]).
-compile(export_all).
%% ----------------------------------------------------------
%% 数据处理相关
%% ----------------------------------------------------------
%% @doc 将record转换为相应的tuple
eg . # user_id{platform_id = 0 , server_id = 0 , = 45 } - > { 0 , 0 , 45 }
record_to_tuple(Record, RecordDefine) ->
[RecordDefine | ListData] = erlang:tuple_to_list(Record),
erlang:list_to_tuple(ListData).
%% @doc 将tuple转换为相应的record
eg . { 0 , 0 , 45 } - > # user_id{platform_id = 0 , server_id = 0 , = 45 }
tuple_to_record(List, RecordDefine) ->
erlang:list_to_tuple([RecordDefine | erlang:tuple_to_list(List)]).
%% @doc 将record转换为相应的list
eg . # user_id{platform_id = 0 , server_id = 0 , = 45 } - > [ 0 , 0 , 45 ]
record_to_list(Record, RecordDefine) ->
[RecordDefine | ListData] = erlang:tuple_to_list(Record),
ListData.
%% @doc 将record转换为相应的list
eg . # user_id{platform_id = 0 , server_id = 0 , = 45 } - > [ { 1 , 0 } , { 2 , 0 } , { 3 , 45 } ]
record_to_list2(Record, RecordDefine) ->
[RecordDefine | ListData] = erlang:tuple_to_list(Record),
record_to_list3(ListData, 1, []).
record_to_list3([], _Index, ResList) -> ResList;
record_to_list3([Key|L], Index, ResList) ->
record_to_list3(L, Index + 1, [{Index, Key}|ResList]).
%% @doc 将list转换为相应的record
eg . [ 0 , 0 , 45 ] - > # user_id{platform_id = 0 , server_id = 0 , = 45 }
list_to_record(List, RecordDefine) ->
erlang:list_to_tuple([RecordDefine | List]).
%% @doc 将二维List转为一维Tuple
[ [ 1,2 ] , [ 1,2 ] ] - > [ { 1 , 2 } , { 1 , 2 } ]
list_to_tuple(List) when erlang:is_list(List) ->
lists:map(fun(A) ->
if
erlang:is_list(A) -> erlang:list_to_tuple(A);
erlang:is_tuple(A) -> A;
true -> {A}
end
end, List);
list_to_tuple(List) when erlang:is_tuple(List) ->
lists:map(fun(A) ->
if
erlang:is_list(A) -> erlang:list_to_tuple(A);
erlang:is_tuple(A) -> A;
true -> {A}
end
end, erlang:tuple_to_list(List));
list_to_tuple(List) -> List.
% @doc 合并两个列表,相同键的值相加
% 短的列表放在前面
% @spec L1 = L2 :: {term(), numeric()};
merge_list([], L2) -> L2;
merge_list([{K, V1} | RestL1], L2) ->
NewL2 = case lists:keytake(K, 1, L2) of
{value, {K, V2}, L3} -> [{K, V1 + V2} | L3];
_ -> [{K, V1} | L2]
end,
merge_list(RestL1, NewL2);
merge_list([{K, V1, V2} | RestL1], L2) ->
NewL2 = case lists:keytake(K, 1, L2) of
{value, {K, OldV1, OldV2}, L3} -> [{K, V1 + OldV1, V2 + OldV2} | L3];
_ -> [{K, V1, V2} | L2]
end,
merge_list(RestL1, NewL2).
%% 物品倍数
multi_item_list([], ItemList, _Multi) ->
ItemList;
multi_item_list([{ID, Count}|List], ItemList, Multi) ->
case lists:keyfind(ID, 1, ItemList) of
false ->
multi_item_list(List, [{ID, util:floor(Count * Multi)}|ItemList], Multi);
{ID, Old} ->
ItemList1 = lists:keydelete(ID, 1, ItemList),
multi_item_list(List, [{ID, util:floor(Count * Multi + Old)}|ItemList1], Multi)
end.
%% @doc 结构值系数加成
%% @param:: Record 结构体
%% Factor 加成系数
mul_record(Record, Factor) ->
Size = erlang:tuple_size(Record),
mul_record(Record, Factor, 2, Size).
mul_record(Record, Factor, Size, Size) when is_number(Factor) ->
NewValue = trunc(element(Size, Record) * Factor),
setelement(Size, Record, NewValue);
mul_record(Record, Factor, Index, Size) when is_number(Factor) ->
NewValue = trunc(element(Index, Record) * Factor),
AttrNew = setelement(Index, Record, NewValue),
mul_record(AttrNew, Factor, Index + 1, Size).
%% @doc 两个结构值相加
%% @param:: Record 结构体
add_record(Record1, Record2) ->
Size = erlang:tuple_size(Record1),
add_record(Record1, Record2, 2, Size).
add_record(Record1, Record2, Size, Size) ->
NewValue = element(Size, Record1) + element(Size, Record2),
setelement(Size, Record1, NewValue);
add_record(Record1, Record2, Index, Size) ->
NewValue = element(Index, Record1) + element(Index, Record2),
AttrNew = setelement(Index, Record1, NewValue),
add_record(AttrNew, Record2, Index + 1, Size).
%% @doc 通用结构键值对更新
update_record([], Record) -> Record;
update_record([Args|L], Record) ->
RecordN = update_record2(Args, Record),
update_record(L, RecordN).
update_record2({Key, Val}, Record) ->
setelement(Key, Record, Val).
%% @doc 获取区间配置
get_range_config(Zones, Value) ->
get_range_config(Zones, Value, undefined).
get_range_config([], _V, Default) -> Default;
get_range_config([{L, H, C} | T], V, Default) ->
case V >= L andalso (V =< H orelse H =:= -1) of
true -> C;
_ -> get_range_config(T, V, Default)
end.
%% @doc 过滤掉元组列表中某个元素相同的列表
eg . L=[{1,2},{2,2},{3,1 } ] . list_filter(L , 2 ) - > [ { 1,2},{3,1 } ]
list_filter(List, N) ->
list_filter_helper(List, N, [], []).
list_filter_helper([H | T], N, ResultList, KeyList) ->
Key = element(N, H),
case lists:member(Key, KeyList) of
true -> list_filter_helper(T, N, ResultList, KeyList);
false -> list_filter_helper(T, N, [H | ResultList], [Key | KeyList])
end;
list_filter_helper([], _, ResultList, _) -> ResultList.
%% @doc 随机打乱list元素顺序
list_shuffle([]) ->
[];
list_shuffle(List) ->
Len = length(List),
List1 = [{util:rand(1, Len + 10000), X} || X <- List],
List2 = lists:sort(List1),
[E || {_, E} <- List2].
shuffle_list_n([], N) when is_integer(N) -> [];
shuffle_list_n(L, 0) when is_list(L) -> [];
shuffle_list_n(L, N) when is_list(L), is_integer(N), N >= 0 ->
Len = erlang:length(L),
lists:sublist([X || {_, X} <- lists:sort([{rand:uniform(Len), E} || E <- L])], N).
%% @doc 根据下标替换list元素值
list_replace(Index, NewElem, List) ->
list_replace_helper(List, Index, NewElem, 1, []).
list_replace_helper([], _Index, _NewElem, _CurIndex, NewList) ->
NewList;
list_replace_helper([H | T], Index, NewElem, CurIndex, NewList) ->
if Index =:= CurIndex ->
list_replace_helper(T, Index, NewElem, CurIndex + 1, NewList ++ [NewElem]);
true ->
list_replace_helper(T, Index, NewElem, CurIndex + 1, NewList ++ [H])
end.
%% @doc 根据list的元素值获得下标
list_get_index(Elem, List) ->
list_get_index_helper(List, Elem, 0).
list_get_index_helper([], _Elem, _Index) -> 0;
list_get_index_helper([H | T], Elem, Index) ->
if
H =:= Elem -> Index + 1;
true -> list_get_index_helper(T, Elem, Index + 1)
end.
%% @doc 根据list的元素值获得下标(加强版)
@param : : ( Elem , N , List ) , List为元组列表,N为元组中第N个元素等于Elem
%% @return:: {0,null} | {Index, H}
list_get_index_ex(Elem, N, List) when is_list(List), is_integer(N) ->
list_get_index_ex(Elem, N, List, 0);
list_get_index_ex(_, _, _) -> {0, null}.
list_get_index_ex(_Elem, _N, [], _) -> {0, null};
list_get_index_ex(Elem, N, [H | _], Index) when element(N, H) =:= Elem -> {Index + 1, H};
list_get_index_ex(Elem, N, [_ | L], Index) -> list_get_index_ex(Elem, N, L, Index + 1).
%% @doc 多个列表数值相加,结果以第一个列表的长度为准
lists_add([ResultList]) -> ResultList;
lists_add([List1, List2 | T]) ->
ResultList = lists_add_helper(List1, List2, []),
lists_add([ResultList | T]).
lists_add_helper([], _List2, ResultList) ->
lists:reverse(ResultList);
lists_add_helper(List1, [], ResultList) ->
lists:reverse(ResultList) ++ List1;
lists_add_helper([H1 | T1], [H2 | T2], ResultList) ->
lists_add_helper(T1, T2, [H1 + H2 | ResultList]).
%% @doc 比较函数
cmp([]) ->
true;
cmp([{Ka, Kb} | T]) ->
if
Ka > Kb -> true;
Ka < Kb -> false;
true -> cmp(T)
end.
%% @doc 扩展版lists:min/1
@param : : ( List , N ) , List为元组列表,N为元组中第N个元素
min_ex([H | T], N) -> min_ex(T, H, N).
min_ex([H | T], Min, N) when element(N, H) < element(N, Min) -> min_ex(T, H, N);
min_ex([_ | T], Min, N) -> min_ex(T, Min, N);
min_ex([], Min, _) -> Min.
@doc 扩展版lists :
@param : ( List , N ) , List为元组列表,N为元组中第N个元素
max_ex([H | T], N) -> max_ex(T, H, N);
max_ex([], _N) -> 0.
max_ex([H | T], Max, N) when element(N, H) > element(N, Max) -> max_ex(T, H, N);
max_ex([_ | T], Max, N) -> max_ex(T, Max, N);
max_ex([], Max, _) -> Max.
@doc 扩展版lists :
@param : : ( List , N ) , List为元组列表,N为元组中第N个元素 , Record为列表为空时调用者预期返回的内容
keymax([H | T], N, Record) -> keymax(T, H, N, Record);
keymax([], _N, Record) -> Record.
keymax([H | T], Max, N, Record) when element(N, H) > element(N, Max) -> keymax(T, H, N, Record);
keymax([_ | T], Max, N, Record) -> keymax(T, Max, N, Record);
keymax([], Max, _, _) -> Max.
@doc
@param : : ( List , N ) , List为元组列表,N为元组中第N个元素
is_all_same([H | T], N) -> is_all_same(T, H, N).
is_all_same([H | T], Min, N) when element(N, H) =:= element(N, Min) -> is_all_same(T, H, N);
is_all_same(L, _, _) when L =/= [] -> false;
is_all_same([], _, _) -> true.
%% @doc 列表中某元素的总和
sum_ex(L, N) -> sum_ex(L, 0, N).
sum_ex([H | T], Sum, N) -> sum_ex(T, Sum + element(N, H), N);
sum_ex([], Sum, _) -> Sum.
%% 扩展的map函数
map_ex(_Fun, [], _Arg) ->
[];
map_ex(Fun, [H | T], Arg) ->
[Fun(H, Arg) | map_ex(Fun, T, Arg)].
@doc 截取列表的第Begin个到第End个
sublist(L, Begin, End) ->
sublist(L, Begin, End, {1, []}).
sublist([], _Begin, _End, {_NowNth, RetL}) ->
lists:reverse(RetL);
sublist([_ | _L], _Begin, End, {NowNth, RetL}) when NowNth > End ->
lists:reverse(RetL);
sublist([Item | L], Begin, End, {NowNth, RetL}) when Begin =< NowNth andalso NowNth =< End ->
sublist(L, Begin, End, {NowNth + 1, [Item | RetL]});
sublist([_ | L], Begin, End, {NowNth, RetL}) ->
sublist(L, Begin, End, {NowNth + 1, RetL}).
%% @doc 分割列表
split_list(N, List) when length(List) =< N ->
{List, []};
split_list(N, List) ->
lists:split(N, List).
%% @doc 随机分割列表
rand_split_list(N, List) when length(List) =< N ->
{List, []};
rand_split_list(N, List) ->
rand_split_list(N, List, []).
rand_split_list(0, List, Acc) ->
{Acc, List};
rand_split_list(N, List, Acc) ->
I = list_rand(List),
NList = List -- [I],
NAcc = [I | Acc],
rand_split_list(N - 1, NList, NAcc).
%% @doc 多倍列表
list_multiple(N, List) ->
lists:flatten(lists:duplicate(N, List)).
acc_attr_list(List, Count) ->
acc_attr_list(List, [], Count).
acc_attr_list([], List, _Count) -> List;
acc_attr_list([{Type, Value}|T], List, Count) ->
AddValue = util:floor(Value * Count),
case lists:keyfind(Type, 1, List) of
false ->
acc_attr_list(T, [{Type, AddValue}|List], Count);
{Type, Old} ->
List1 = lists:keydelete(Type, 1, List),
acc_attr_list(T, [{Type, AddValue + Old}|List1], Count)
end.
max_attr_list(List, MaxList) ->
max_attr_list(List, MaxList, []).
max_attr_list([], _MaxList, Acc) -> lists:reverse(Acc);
max_attr_list([{Type, Value}|T], MaxList, Acc) ->
case lists:keyfind(Type, 1, MaxList) of
false ->
max_attr_list(T, MaxList, Acc);
{Type, Max} ->
max_attr_list(T, MaxList, [{Type, min(Value, Max)}|Acc])
end.
%% @doc 列表循环操作
list_handle(F, Data, List, Place) ->
case List of
[H | T] ->
case F(H, Data, Place) of
{ok, Data2} ->
list_handle(F, Data2, T, Place);
Error ->
Error
end;
[] ->
{ok, Data}
end.
%% @doc 列表循环函数
list_handle(F, Data, List) ->
case List of
[H | T] ->
case F(H, Data) of
{ok, Data2} ->
list_handle(F, Data2, T);
Error ->
Error
end;
[] ->
{ok, Data}
end.
%% ----------------------------------------------------------
%% 随机函数相关
%% ----------------------------------------------------------
%% @doc 随机取出list元素
list_rand([]) -> null;
list_rand(List) ->
Len = length(List),
Index = rand(1, Len),
lists:nth(Index, List).
@doc 随机从列表中选n个元素
%% @return:: null | List
list_rand_n([], _PickNum) -> [];
list_rand_n(List, PickNum) ->
list_rand_n(List, PickNum, []).
list_rand_n([], _PickNum, AccList) -> AccList;
list_rand_n(_List, 0, AccList) -> AccList;
list_rand_n(List, PickNum, AccList) ->
PickOne = list_rand(List),
LeftList = List -- [PickOne],
list_rand_n(LeftList, PickNum - 1, [PickOne | AccList]).
%% @doc 查找匹配机率的值
find_ratio([], _, _) -> [];
find_ratio([{N, R} | _], S, Ra) when Ra > S andalso Ra =< (S + R) -> N;
find_ratio([{_, R} | T], S, Ra) -> find_ratio(T, (S + R), Ra).
%% @doc 依据权重,从元组列表中随机挑选N个元素,返回被抽中的元组列表,不放回抽取
@Param : : Tuples : 元组列表([{权重 , ... } , ... ] 等类似格式 )
Index : 权重所在的位置(如上例则是1 )
PickNum : 随机抽出的次数
rand_by_weight(Tuples, Index, PickNum) when PickNum >= 0 ->
rand_n_by_weight(Tuples, Index, PickNum, []).
rand_n_by_weight(_Tuples, _Index, 0, Ret) -> Ret;
rand_n_by_weight([], _Index, _PickNum, Ret) -> Ret;
rand_n_by_weight(Tuples, Index, PickNum, Ret) ->
PickOne = rand_by_weight(Tuples, Index),
LeftTuples = lists:delete(PickOne, Tuples),
rand_n_by_weight(LeftTuples, Index, PickNum - 1, [PickOne | Ret]).
@doc 依据权重,从元组列表中随机挑选一个元素,返回被抽中的元组 ,
%% 如果没有对应的元素,则抛出异常
%% @param:: Index 权重所在的位置
%% @return:: Tuple
rand_by_weight([], _Index) ->
error(badargs);
rand_by_weight(List, Index) ->
Sum = lists:sum([weight_index(Tuple, Index) || Tuple <- List]),
P = rand(1, Sum),
rand_one_by_weight(List, Index, P).
rand_one_by_weight([Tuple], _, _) -> Tuple;
rand_one_by_weight([Tuple | T], Index, P) ->
case weight_index(Tuple, Index) of
Weight when P =< Weight -> Tuple;
Weight -> rand_one_by_weight(T, Index, P - Weight)
end.
weight_index(Tuple, Index) when is_tuple(Tuple) ->
element(Index, Tuple);
weight_index(Map, Key) when is_map(Map) ->
maps:get(Key, Map).
从累加的概率中随机一个
rand_list_one([], _Rand) -> error(badargs);
rand_list_one([{Value, Rate}|T], Rand) ->
if Rate >= Rand ->
Value;
true ->
rand_list_one(T, Rand)
end;
rand_list_one([{Value1, Value2, Rate}|T], Rand) ->
if Rate >= Rand ->
{Value1, Value2};
true ->
rand_list_one(T, Rand)
end.
%% ----------------------------------------------------------
%% 操作工具相关
%% ----------------------------------------------------------
%% @doc FOR循环
for(Max, Max, F) -> F(Max);
for(I, Max, F) ->
F(I),
for(I + 1, Max, F).
@doc 带返回状态的for循环
%% @return {ok, State}
for(Max, Min, _F, State) when Min < Max -> {ok, State};
for(Max, Max, F, State) -> F(Max, State);
for(I, Max, F, State) -> {ok, NewState} = F(I, State), for(I + 1, Max, F, NewState).
在List中的每两个元素之间插入一个分隔符
implode(_S, []) ->
[<<>>];
implode(S, L) when is_list(L) ->
implode(S, L, []).
implode(_S, [H], NList) ->
lists:reverse([type:object_to_list(H) | NList]);
implode(S, [H | T], NList) ->
L = [type:object_to_list(H) | NList],
implode(S, T, [S | L]).
%% @doc 分割字符串为列表
explode(S, B) ->
re:split(B, S, [{return, list}]).
explode(S, B, int) ->
[list_to_integer(Str) || Str <- explode(S, B), length(Str) > 0].
gen_n(0, []) ->
[];
gen_n(N, List) when N > 0, is_list(List), List =/= [] ->
gen_n(N, List, []);
gen_n(_N, _List) ->
[].
gen_n(0, _List, Acc) ->
Acc;
gen_n(N, List, Acc) when is_list(Acc) ->
Item = list_rand(List),
gen_n(N - 1, List, [Item | Acc]).
%% @doc proplists:get_value/2
prop_get_value(Key, List) ->
prop_get_value(Key, List, undefined).
prop_get_value(Key, List, Def) ->
case lists:keyfind(Key, 1, List) of
{Key, Val} -> Val;
_ -> Def
end.
prop_get_value(Key, Pos, List, Def) ->
case lists:keyfind(Key, Pos, List) of
{Key, Val} -> Val;
_ -> Def
end.
@doc proplists : get_keys/1
prop_get_keys(List) ->
[K || {K, _V} <- List].
%% @doc proplists:delete/2
prop_delete(K, List) ->
lists:keydelete(K, 1, List).
%% @doc
prop_store({K, V}, List) ->
prop_store(K, V, List).
prop_store(K, V, List) ->
lists:keystore(K, 1, List, {K, V}).
%% @doc
prop_increase(K, List) ->
prop_increase(K, List, 1).
prop_increase(K, List, Incl) ->
case prop_get_value(K, List, 0) of
V when is_integer(V) ->
prop_store(K, V + Incl, List);
_ ->
List
end.
@doc 产生一个介于Min到Max之间的随机整数
rand(Same, Same) -> Same;
rand(Min, Max) when Max < Min -> 0;
rand(Min, Max) ->
%% 以保证不同进程都可取得不同的种子
case get("rand_seed") of
undefined ->
rand:seed(exs1024),
put("rand_seed", 1);
_ ->
skip
end,
M = Min - 1,
rand:uniform(Max - M) + M.
%% @doc 向上取整
ceil(X) ->
T = trunc(X),
case X =:= T of
true -> T;
false -> T + 1
end.
@doc 向下取整
floor(X) ->
T = trunc(X),
case X < T of
true -> max(T - 1, 0);
_ -> T
end.
%% @doc 获取客户端ip
get_ip(Socket) ->
case inet:peername(Socket) of
{ok, {Ip, _Port}} -> Ip;
{error, _Reason} -> {0, 0, 0, 0}
end.
doc 角度和cos的转换,cos(60 ' ) = 0.5
angle_to_float(Angle) ->
math:cos(math:pi() * Angle / 180).
%% @doc 分页取数据
%% @param:: Data: 所有数据(列表)
Page : 第几页数据(大于总页数则默认最后页 )
PageNum :
@return : : { 总条数 , 当前页 , 当前页数据 }
page_data(List, Page, Count) ->
Len = length(List),
Start = max(Page - 1, 0) * Count + 1,
if Start > Len ->
{Len, Page, []};
true ->
{Len, Page, lists:sublist(List, Start, Count)}
end.
%% ----------------------------------------------------------
%% 字符文本操作
%% ----------------------------------------------------------
%% @doc 转换成HEX格式的md5
md5(S) ->
lists:flatten([io_lib:format("~2.16.0b", [N]) || N <- binary_to_list(erlang:md5(S))]).
%% @doc 转换成HEX格式的hmac
hmac(Key, Msg) ->
crypto:hmac(sha, list_to_binary(Key), list_to_binary(Msg)).
%% @doc 转换成HEX格式的hmac
hmac_hex(Key, Msg) ->
<<Mac:160/integer>> = crypto:hmac(sha, list_to_binary(Key), list_to_binary(Msg)),
lists:flatten(io_lib:format("~40.16.0b", [Mac])).
filter_text_gm(Text) when is_bitstring(Text) ->
Text;
filter_text_gm(Text) when is_list(Text) ->
list_to_bitstring(Text).
%% @doc 敏感词检测
%% @param:: Text: 字符串 ==> 字符宽度,1汉字=2单位长度,1数字字母=1单位长度
@return : : true 存在关键词
%% false 不存在关键词
string_width(String) ->
string_width(String, 0).
string_width([], Len) ->
Len;
string_width([H | T], Len) ->
case H > 255 of
true ->
string_width(T, Len + 2);
false ->
string_width(T, Len + 1)
end.
%% @doc 长度合法性检查
check_length(Item, LenLimit) ->
check_length(Item, 1, LenLimit).
check_length(Item, MinLen, MaxLen) ->
case unicode:characters_to_list(list_to_binary(Item)) of
UnicodeList when is_list(UnicodeList) ->
Len = string_width(UnicodeList),
Len =< MaxLen andalso Len >= MinLen;
_ ->
false
end.
@doc IP元组转字符
ip2bin(IP) when is_list(IP) ->
case inet:parse_address(IP) of
{ok, _IP} -> ip2bin(_IP);
_ -> "256.256.256.256"
end;
ip2bin({A, B, C, D}) ->
[integer_to_list(A), ".", integer_to_list(B), ".", integer_to_list(C), ".", integer_to_list(D)];
ip2bin(_) ->
"256.256.256.256".
%% @doc 过滤掉字符串中的特殊字符
filter_string(String, CharList) ->
case is_list(String) of
true ->
filter_string_helper(String, CharList, []);
false when is_binary(String) ->
ResultString = filter_string_helper(binary_to_list(String), CharList, []),
list_to_binary(ResultString);
false ->
String
end.
filter_string_helper([], _CharList, ResultString) ->
ResultString;
filter_string_helper([H | T], CharList, ResultString) ->
case lists:member(H, CharList) of
true -> filter_string_helper(T, CharList, ResultString);
false -> filter_string_helper(T, CharList, ResultString ++ [H])
end.
%% @doc 跳过编码为4个字节的字符
escape_unicode([H | T]) ->
if
H band 16#F8 =:= 16#F0 ->
if
length(T) >= 3 ->
escape_unicode(lists:nthtail(3, T));
true -> []
end;
true ->
[H | escape_unicode(T)]
end;
escape_unicode([]) ->
[].
@doc 转义数据库varchar
escape_varchar(S) ->
S1 = escape_unicode(S),
R = re:replace(S1, "[\\\\|-|;|,|.|/|\\(|\\)|\\[|\\]|}|{|%|\\@|*|!|'|\"]", "", [global, {return, binary}]),
erlang:binary_to_list(R).
@doc 转义数据库varchar
escape_name(S) ->
escape_unicode(string:strip(S)).
%% @doc 用于聊天检测
calc_string_compare(A, B) ->
AWordDict = word_dict(unicode:characters_to_list(type:object_to_binary(A))),
BWordDict = word_dict(unicode:characters_to_list(type:object_to_binary(B))),
Dict = merge_dict(AWordDict, BWordDict),
F = fun(_K, {V1, V2}, {DenominatorAcc, Sqdoc1Acc, Sqdoc2Acc}) ->
{DenominatorAcc + V1 * V2
, Sqdoc1Acc + V1 * V1
, Sqdoc2Acc + V2 * V2
}
end,
{Denominator, Sqdoc1, Sqdoc2} = dict:fold(F, {0, 0, 0}, Dict),
case Sqdoc1 =:= 0 orelse Sqdoc2 =:= 0 of
true -> 0;
false -> Denominator / math:sqrt(Sqdoc1 * Sqdoc2)
end.
merge_dict(D1, D2) ->
F1 = fun(_K, V) -> {V, 0} end,
D1T = dict:map(F1, D1),
F2 = fun(K, V, Dict) ->
case dict:find(K, D1T) of
error -> dict:store(K, {0, V}, Dict);
{ok, {V1, 0}} -> dict:store(K, {V1, V}, Dict);
_ -> Dict
end
end,
D2T = dict:fold(F2, D1T, D2),
D2T.
%% @doc 取字(连续数字、连续字符当作一个字)
A - Z 65 - 90
a - z 97 - 122
0 - 9 48 - 57
word_dict(L) -> word__(L, [], dict:new()).
word__([A | L], Word, WordDict) when (A >= 65 andalso A =< 90) orelse
(A >= 97 andalso A =< 122) orelse
(A >= 48 andalso A =< 57) ->
word__(L, [A | Word], WordDict);
word__([I | L], [], WordDict) ->
word__(L, [], dict:update_counter([I], 1, WordDict));
word__([I | L], Word, WordDict) ->
WordDict1 = dict:update_counter(Word, 1, WordDict),
WordDict2 = dict:update_counter([I], 1, WordDict1),
word__(L, [], WordDict2);
word__([], [], WordList) ->
WordList;
word__([], Word, WordDict) ->
dict:update_counter(Word, 1, WordDict).
%% @doc 截取字符串
string_sub(Str, Start) ->
Unicode = unicode:characters_to_list(Str),
unicode:characters_to_binary(lists:sublist(Unicode, Start)).
string_sub(Str, Start, Len) ->
Unicode = unicode:characters_to_list(Str),
unicode:characters_to_binary(lists:sublist(Unicode, Start, Len)).
%% @doc 安全检查格式化字符串
safe_format(Fmt, Args) when is_list(Args) ->
F = fun(A) -> ?iif(is_list(A) =:= true, list_to_binary(A), A) end,
ArgsN = lists:map(F, Args),
case catch lists:flatten(io_lib:format(Fmt, ArgsN)) of
Val when is_list(Val) orelse is_binary(Val) ->
Val;
_ ->
Fmt
end.
%% @doc 除去名字前面的平台号
trip_name(Name) when is_binary(Name) ->
trip_name(erlang:binary_to_list(Name));
trip_name(Name) when is_list(Name) ->
string:sub_string(Name, string:chr(Name, $.) + 1).
%% -----------------------------------------------------------------------------
%% dict相关
%% -----------------------------------------------------------------------------
dict_find(Key, Dict) ->
dict_find(Key, Dict, undefined).
dict_find(Key, Dict, Default) ->
case dict:find(Key, Dict) of
{ok, V} -> V;
_ -> Default
end.
dict_find2(Key, Dict, Default) ->
case dict:find(Key, Dict) of
{ok, V} -> {true, V};
_ -> {false, Default}
end.
%% ----------------------------------------------------------
%% 定时器相关
%% ----------------------------------------------------------
%% 取消定时器
cancel_timer(Timer) ->
case is_reference(Timer) of
true ->
erlang:cancel_timer(Timer);
false ->
skip
end,
[].
cancel_timer(Ref, Event) when is_reference(Ref) ->
case erlang:cancel_timer(Ref) of
fasle ->
receive Event -> 0
after 0 -> false
end;
RemainingTime -> RemainingTime
end;
cancel_timer(_Ref, _Event) ->
false.
%% ----------------------------------------------------------
%% ETS相关
%% ----------------------------------------------------------
%% @doc 获取键值
get_ets(Table, Key) ->
case ets:lookup(Table, Key) of
[{Key, Val}] -> Val;
_ -> undefined
end.
get_ets(Table, Key, Def) ->
case ets:lookup(Table, Key) of
[{Key, Val}] -> Val;
_ -> Def
end.
%% @doc 存储键值
put_ets(Table, Key, Value) ->
ets:insert(Table, {Key, Value}).
%% @doc 删除键值
del_ets(Table, Key) ->
ets:delete(Table, Key).
%% @doc 清空表
cls_ets(Table) ->
ets:delete_all_objects(Table).
%% ----------------------------------------------------------
%% 数据库辅助
%% ----------------------------------------------------------
%% @doc 批量插入 [可控制]
batch_insert(PoolFlag, 0, Fmt1, Fmt2, List) ->
insert_values(PoolFlag, Fmt1, Fmt2, List);
batch_insert(_PoolFlag, _Size, _Fmt1, _Fmt2, []) ->
ok;
batch_insert(PoolFlag, Size, Fmt1, Fmt2, List) ->
{Batch, Left} = split_list(Size, List),
insert_values(PoolFlag, Fmt1, Fmt2, Batch),
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Left).
batch_insert(PoolFlag, 0, Fmt1, Fmt2, Fun, List) ->
insert_values(PoolFlag, Fmt1, Fmt2, Fun, List);
batch_insert(_PoolFlag, _Size, _Fmt1, _Fmt2, _Fun, []) ->
ok;
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Fun, List)
when is_integer(Size), Size > 0, ?VALID_STR(Fmt1), ?VALID_STR(Fmt2), is_function(Fun, 1), is_list(List) ->
{Batch, Left} = split_list(Size, List),
insert_values(PoolFlag, Fmt1, Fmt2, Fun, Batch),
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Fun, Left).
batch_insert(PoolFlag, 0, Fmt1, Fmt2, Args, Fun, List) -> %% 一次性插入
insert_values(PoolFlag, Fmt1, Fmt2, Args, Fun, List);
batch_insert(_PoolFlag, _Size, _Fmt1, _Fmt2, _Args, _Fun, []) ->
ok;
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Args, Fun, List)
when is_integer(Size), Size > 0, ?VALID_STR(Fmt1), ?VALID_STR(Fmt2), is_list(Args), is_function(Fun, 1), is_list(List) ->
{Batch, Left} = split_list(Size, List),
insert_values(PoolFlag, Fmt1, Fmt2, Args, Fun, Batch),
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Args, Fun, Left).
@doc 批量插入 [ ]
insert_values(_PoolFlag, _Fmt1, _Fmt2, []) ->
ok;
insert_values(PoolFlag, Fmt1, Fmt2, List) ->
insert_values2(PoolFlag, Fmt1, Fmt2, [], List).
insert_values(PoolFlag, Fmt1, Fmt2, Fun, List) when is_function(Fun, 1), is_list(List) ->
insert_values(PoolFlag, Fmt1, Fmt2, [], Fun, List);
insert_values(PoolFlag, Fmt1, Fmt2, Args, List) when is_list(Args) ->
insert_values2(PoolFlag, Fmt1, Fmt2, Args, List).
insert_values(PoolFlag, Fmt1, Fmt2, Args, Fun, List) when is_list(Args), is_function(Fun, 1), is_list(List) ->
RankList = lists:map(Fun, List),
insert_values2(PoolFlag, Fmt1, Fmt2, Args, RankList).
insert_values2(_PoolFlag, _Fmt1, _Fmt2, _Args, []) ->
ok;
insert_values2(PoolFlag, Fmt1, Fmt2, Args, List) ->
Values = format_values(Fmt2, List),
SQL = io_lib:format(Fmt1, Args ++ [Values]),
?DB:execute(PoolFlag, SQL),
ok.
%% @doc
format_values(Temp, List) ->
FinList = format_values(List, Temp, []),
implode(",", FinList, []).
format_values([], _Temp, Acc) ->
lists:reverse(Acc);
format_values([L | T], Temp, Acc) ->
F = io_lib:format(Temp, L),
format_values(T, Temp, [F | Acc]).
%% -----------------------------------------------------------------------------
%% supervisor
%% -----------------------------------------------------------------------------
sup_info_child(Sup, Info) ->
[Pid ! Info || Pid <- sup_children_pid(Sup)].
sup_children_pid(Sup) ->
case catch supervisor:which_children(Sup) of
List when is_list(List) ->
[Child || {_Id, Child, _Type, _Modules} <- List];
_ ->
[]
end.
%% ----------------------------------------------------------
%% 系统分析工具
%% ----------------------------------------------------------
process_infos() ->
filelib:ensure_dir("../logs/"),
File = "../logs/processes_infos.log",
{ok, Fd} = file:open(File, [write, raw, binary, append]),
Fun = fun(Pi) ->
Info = io_lib:format("=>~p \n\n", [Pi]),
case filelib:is_file(File) of
true ->
file:write(Fd, Info);
false ->
file:close(Fd),
{ok, NewFd} = file:open(File, [write, raw, binary, append]),
file:write(NewFd, Info)
end,
timer:sleep(20)
end,
[Fun(erlang:process_info(P)) || P <- erlang:processes()].
process_infos(Pid, Type) ->
filelib:ensure_dir("../logs/"),
File = "../logs/processes_infos.log",
{ok, Fd} = file:open(File, [write, raw, binary, append]),
Fun = fun(Pi) ->
NewPi = case Type of
messages ->
{messages, SendList} = Pi,
lists:foldl(fun({TType, Content}, CmdList) ->
case TType of
send ->
<<_A:16, Cmd:32, _Left/binary>> = Content,
case lists:keyfind(Cmd, 1, CmdList) of
false -> [{Cmd, 1} | CmdList];
{_, CNum} -> lists:keyreplace(Cmd, 1, CmdList, {Cmd, CNum + 1})
end;
_ -> [{TType, Content} | CmdList]
end
end, [], SendList);
_ ->
Pi
end,
Info = io_lib:format("=>~p \n\n", [NewPi]),
case filelib:is_file(File) of
true ->
file:write(Fd, Info);
false ->
file:close(Fd),
{ok, NewFd} = file:open(File, [write, raw, binary, append]),
file:write(NewFd, Info)
end
end,
PInfo = erlang:process_info(Pid, Type),
Fun(PInfo). | null | https://raw.githubusercontent.com/SuYi1995/game_server/b9a8574589075a1264c3d1f9a564d6d2ea8ae574/src/util/util.erl | erlang | -------------------------------------------------------------------
@author sy
@doc
通用工具模块
@end
-------------------------------------------------------------------
数据库辅助相关
列表 [lists, proplists]
----------------------------------------------------------
数据处理相关
----------------------------------------------------------
@doc 将record转换为相应的tuple
@doc 将tuple转换为相应的record
@doc 将record转换为相应的list
@doc 将record转换为相应的list
@doc 将list转换为相应的record
@doc 将二维List转为一维Tuple
@doc 合并两个列表,相同键的值相加
短的列表放在前面
@spec L1 = L2 :: {term(), numeric()};
物品倍数
@doc 结构值系数加成
@param:: Record 结构体
Factor 加成系数
@doc 两个结构值相加
@param:: Record 结构体
@doc 通用结构键值对更新
@doc 获取区间配置
@doc 过滤掉元组列表中某个元素相同的列表
@doc 随机打乱list元素顺序
@doc 根据下标替换list元素值
@doc 根据list的元素值获得下标
@doc 根据list的元素值获得下标(加强版)
@return:: {0,null} | {Index, H}
@doc 多个列表数值相加,结果以第一个列表的长度为准
@doc 比较函数
@doc 扩展版lists:min/1
@doc 列表中某元素的总和
扩展的map函数
@doc 分割列表
@doc 随机分割列表
@doc 多倍列表
@doc 列表循环操作
@doc 列表循环函数
----------------------------------------------------------
随机函数相关
----------------------------------------------------------
@doc 随机取出list元素
@return:: null | List
@doc 查找匹配机率的值
@doc 依据权重,从元组列表中随机挑选N个元素,返回被抽中的元组列表,不放回抽取
如果没有对应的元素,则抛出异常
@param:: Index 权重所在的位置
@return:: Tuple
----------------------------------------------------------
操作工具相关
----------------------------------------------------------
@doc FOR循环
@return {ok, State}
@doc 分割字符串为列表
@doc proplists:get_value/2
@doc proplists:delete/2
@doc
@doc
以保证不同进程都可取得不同的种子
@doc 向上取整
@doc 获取客户端ip
@doc 分页取数据
@param:: Data: 所有数据(列表)
----------------------------------------------------------
字符文本操作
----------------------------------------------------------
@doc 转换成HEX格式的md5
@doc 转换成HEX格式的hmac
@doc 转换成HEX格式的hmac
@doc 敏感词检测
@param:: Text: 字符串 ==> 字符宽度,1汉字=2单位长度,1数字字母=1单位长度
false 不存在关键词
@doc 长度合法性检查
@doc 过滤掉字符串中的特殊字符
@doc 跳过编码为4个字节的字符
@doc 用于聊天检测
@doc 取字(连续数字、连续字符当作一个字)
@doc 截取字符串
@doc 安全检查格式化字符串
@doc 除去名字前面的平台号
-----------------------------------------------------------------------------
dict相关
-----------------------------------------------------------------------------
----------------------------------------------------------
定时器相关
----------------------------------------------------------
取消定时器
----------------------------------------------------------
ETS相关
----------------------------------------------------------
@doc 获取键值
@doc 存储键值
@doc 删除键值
@doc 清空表
----------------------------------------------------------
数据库辅助
----------------------------------------------------------
@doc 批量插入 [可控制]
一次性插入
@doc
-----------------------------------------------------------------------------
supervisor
-----------------------------------------------------------------------------
----------------------------------------------------------
系统分析工具
---------------------------------------------------------- | ( C ) 2019 , < COMPANY >
Created : 30 . 9月 2019 10:47
-module(util).
-include("common.hrl").
-export([
batch_insert/5,
batch_insert/6,
batch_insert/7,
insert_values/4,
insert_values/5,
insert_values/6,
format_values/2
]).
-export([
prop_get_value/2,
prop_get_value/3,
prop_get_value/4,
prop_get_keys/1,
prop_delete/2,
prop_store/2,
prop_store/3,
list_rand/1,
list_rand_n/2,
merge_list/2,
multi_item_list/3,
acc_attr_list/2,
acc_attr_list/3,
max_attr_list/2
]).
-compile(export_all).
eg . # user_id{platform_id = 0 , server_id = 0 , = 45 } - > { 0 , 0 , 45 }
record_to_tuple(Record, RecordDefine) ->
[RecordDefine | ListData] = erlang:tuple_to_list(Record),
erlang:list_to_tuple(ListData).
eg . { 0 , 0 , 45 } - > # user_id{platform_id = 0 , server_id = 0 , = 45 }
tuple_to_record(List, RecordDefine) ->
erlang:list_to_tuple([RecordDefine | erlang:tuple_to_list(List)]).
eg . # user_id{platform_id = 0 , server_id = 0 , = 45 } - > [ 0 , 0 , 45 ]
record_to_list(Record, RecordDefine) ->
[RecordDefine | ListData] = erlang:tuple_to_list(Record),
ListData.
eg . # user_id{platform_id = 0 , server_id = 0 , = 45 } - > [ { 1 , 0 } , { 2 , 0 } , { 3 , 45 } ]
record_to_list2(Record, RecordDefine) ->
[RecordDefine | ListData] = erlang:tuple_to_list(Record),
record_to_list3(ListData, 1, []).
record_to_list3([], _Index, ResList) -> ResList;
record_to_list3([Key|L], Index, ResList) ->
record_to_list3(L, Index + 1, [{Index, Key}|ResList]).
eg . [ 0 , 0 , 45 ] - > # user_id{platform_id = 0 , server_id = 0 , = 45 }
list_to_record(List, RecordDefine) ->
erlang:list_to_tuple([RecordDefine | List]).
[ [ 1,2 ] , [ 1,2 ] ] - > [ { 1 , 2 } , { 1 , 2 } ]
list_to_tuple(List) when erlang:is_list(List) ->
lists:map(fun(A) ->
if
erlang:is_list(A) -> erlang:list_to_tuple(A);
erlang:is_tuple(A) -> A;
true -> {A}
end
end, List);
list_to_tuple(List) when erlang:is_tuple(List) ->
lists:map(fun(A) ->
if
erlang:is_list(A) -> erlang:list_to_tuple(A);
erlang:is_tuple(A) -> A;
true -> {A}
end
end, erlang:tuple_to_list(List));
list_to_tuple(List) -> List.
merge_list([], L2) -> L2;
merge_list([{K, V1} | RestL1], L2) ->
NewL2 = case lists:keytake(K, 1, L2) of
{value, {K, V2}, L3} -> [{K, V1 + V2} | L3];
_ -> [{K, V1} | L2]
end,
merge_list(RestL1, NewL2);
merge_list([{K, V1, V2} | RestL1], L2) ->
NewL2 = case lists:keytake(K, 1, L2) of
{value, {K, OldV1, OldV2}, L3} -> [{K, V1 + OldV1, V2 + OldV2} | L3];
_ -> [{K, V1, V2} | L2]
end,
merge_list(RestL1, NewL2).
multi_item_list([], ItemList, _Multi) ->
ItemList;
multi_item_list([{ID, Count}|List], ItemList, Multi) ->
case lists:keyfind(ID, 1, ItemList) of
false ->
multi_item_list(List, [{ID, util:floor(Count * Multi)}|ItemList], Multi);
{ID, Old} ->
ItemList1 = lists:keydelete(ID, 1, ItemList),
multi_item_list(List, [{ID, util:floor(Count * Multi + Old)}|ItemList1], Multi)
end.
mul_record(Record, Factor) ->
Size = erlang:tuple_size(Record),
mul_record(Record, Factor, 2, Size).
mul_record(Record, Factor, Size, Size) when is_number(Factor) ->
NewValue = trunc(element(Size, Record) * Factor),
setelement(Size, Record, NewValue);
mul_record(Record, Factor, Index, Size) when is_number(Factor) ->
NewValue = trunc(element(Index, Record) * Factor),
AttrNew = setelement(Index, Record, NewValue),
mul_record(AttrNew, Factor, Index + 1, Size).
add_record(Record1, Record2) ->
Size = erlang:tuple_size(Record1),
add_record(Record1, Record2, 2, Size).
add_record(Record1, Record2, Size, Size) ->
NewValue = element(Size, Record1) + element(Size, Record2),
setelement(Size, Record1, NewValue);
add_record(Record1, Record2, Index, Size) ->
NewValue = element(Index, Record1) + element(Index, Record2),
AttrNew = setelement(Index, Record1, NewValue),
add_record(AttrNew, Record2, Index + 1, Size).
update_record([], Record) -> Record;
update_record([Args|L], Record) ->
RecordN = update_record2(Args, Record),
update_record(L, RecordN).
update_record2({Key, Val}, Record) ->
setelement(Key, Record, Val).
get_range_config(Zones, Value) ->
get_range_config(Zones, Value, undefined).
get_range_config([], _V, Default) -> Default;
get_range_config([{L, H, C} | T], V, Default) ->
case V >= L andalso (V =< H orelse H =:= -1) of
true -> C;
_ -> get_range_config(T, V, Default)
end.
eg . L=[{1,2},{2,2},{3,1 } ] . list_filter(L , 2 ) - > [ { 1,2},{3,1 } ]
list_filter(List, N) ->
list_filter_helper(List, N, [], []).
list_filter_helper([H | T], N, ResultList, KeyList) ->
Key = element(N, H),
case lists:member(Key, KeyList) of
true -> list_filter_helper(T, N, ResultList, KeyList);
false -> list_filter_helper(T, N, [H | ResultList], [Key | KeyList])
end;
list_filter_helper([], _, ResultList, _) -> ResultList.
list_shuffle([]) ->
[];
list_shuffle(List) ->
Len = length(List),
List1 = [{util:rand(1, Len + 10000), X} || X <- List],
List2 = lists:sort(List1),
[E || {_, E} <- List2].
shuffle_list_n([], N) when is_integer(N) -> [];
shuffle_list_n(L, 0) when is_list(L) -> [];
shuffle_list_n(L, N) when is_list(L), is_integer(N), N >= 0 ->
Len = erlang:length(L),
lists:sublist([X || {_, X} <- lists:sort([{rand:uniform(Len), E} || E <- L])], N).
list_replace(Index, NewElem, List) ->
list_replace_helper(List, Index, NewElem, 1, []).
list_replace_helper([], _Index, _NewElem, _CurIndex, NewList) ->
NewList;
list_replace_helper([H | T], Index, NewElem, CurIndex, NewList) ->
if Index =:= CurIndex ->
list_replace_helper(T, Index, NewElem, CurIndex + 1, NewList ++ [NewElem]);
true ->
list_replace_helper(T, Index, NewElem, CurIndex + 1, NewList ++ [H])
end.
list_get_index(Elem, List) ->
list_get_index_helper(List, Elem, 0).
list_get_index_helper([], _Elem, _Index) -> 0;
list_get_index_helper([H | T], Elem, Index) ->
if
H =:= Elem -> Index + 1;
true -> list_get_index_helper(T, Elem, Index + 1)
end.
@param : : ( Elem , N , List ) , List为元组列表,N为元组中第N个元素等于Elem
list_get_index_ex(Elem, N, List) when is_list(List), is_integer(N) ->
list_get_index_ex(Elem, N, List, 0);
list_get_index_ex(_, _, _) -> {0, null}.
list_get_index_ex(_Elem, _N, [], _) -> {0, null};
list_get_index_ex(Elem, N, [H | _], Index) when element(N, H) =:= Elem -> {Index + 1, H};
list_get_index_ex(Elem, N, [_ | L], Index) -> list_get_index_ex(Elem, N, L, Index + 1).
lists_add([ResultList]) -> ResultList;
lists_add([List1, List2 | T]) ->
ResultList = lists_add_helper(List1, List2, []),
lists_add([ResultList | T]).
lists_add_helper([], _List2, ResultList) ->
lists:reverse(ResultList);
lists_add_helper(List1, [], ResultList) ->
lists:reverse(ResultList) ++ List1;
lists_add_helper([H1 | T1], [H2 | T2], ResultList) ->
lists_add_helper(T1, T2, [H1 + H2 | ResultList]).
cmp([]) ->
true;
cmp([{Ka, Kb} | T]) ->
if
Ka > Kb -> true;
Ka < Kb -> false;
true -> cmp(T)
end.
@param : : ( List , N ) , List为元组列表,N为元组中第N个元素
min_ex([H | T], N) -> min_ex(T, H, N).
min_ex([H | T], Min, N) when element(N, H) < element(N, Min) -> min_ex(T, H, N);
min_ex([_ | T], Min, N) -> min_ex(T, Min, N);
min_ex([], Min, _) -> Min.
@doc 扩展版lists :
@param : ( List , N ) , List为元组列表,N为元组中第N个元素
max_ex([H | T], N) -> max_ex(T, H, N);
max_ex([], _N) -> 0.
max_ex([H | T], Max, N) when element(N, H) > element(N, Max) -> max_ex(T, H, N);
max_ex([_ | T], Max, N) -> max_ex(T, Max, N);
max_ex([], Max, _) -> Max.
@doc 扩展版lists :
@param : : ( List , N ) , List为元组列表,N为元组中第N个元素 , Record为列表为空时调用者预期返回的内容
keymax([H | T], N, Record) -> keymax(T, H, N, Record);
keymax([], _N, Record) -> Record.
keymax([H | T], Max, N, Record) when element(N, H) > element(N, Max) -> keymax(T, H, N, Record);
keymax([_ | T], Max, N, Record) -> keymax(T, Max, N, Record);
keymax([], Max, _, _) -> Max.
@doc
@param : : ( List , N ) , List为元组列表,N为元组中第N个元素
is_all_same([H | T], N) -> is_all_same(T, H, N).
is_all_same([H | T], Min, N) when element(N, H) =:= element(N, Min) -> is_all_same(T, H, N);
is_all_same(L, _, _) when L =/= [] -> false;
is_all_same([], _, _) -> true.
sum_ex(L, N) -> sum_ex(L, 0, N).
sum_ex([H | T], Sum, N) -> sum_ex(T, Sum + element(N, H), N);
sum_ex([], Sum, _) -> Sum.
map_ex(_Fun, [], _Arg) ->
[];
map_ex(Fun, [H | T], Arg) ->
[Fun(H, Arg) | map_ex(Fun, T, Arg)].
@doc 截取列表的第Begin个到第End个
sublist(L, Begin, End) ->
sublist(L, Begin, End, {1, []}).
sublist([], _Begin, _End, {_NowNth, RetL}) ->
lists:reverse(RetL);
sublist([_ | _L], _Begin, End, {NowNth, RetL}) when NowNth > End ->
lists:reverse(RetL);
sublist([Item | L], Begin, End, {NowNth, RetL}) when Begin =< NowNth andalso NowNth =< End ->
sublist(L, Begin, End, {NowNth + 1, [Item | RetL]});
sublist([_ | L], Begin, End, {NowNth, RetL}) ->
sublist(L, Begin, End, {NowNth + 1, RetL}).
split_list(N, List) when length(List) =< N ->
{List, []};
split_list(N, List) ->
lists:split(N, List).
rand_split_list(N, List) when length(List) =< N ->
{List, []};
rand_split_list(N, List) ->
rand_split_list(N, List, []).
rand_split_list(0, List, Acc) ->
{Acc, List};
rand_split_list(N, List, Acc) ->
I = list_rand(List),
NList = List -- [I],
NAcc = [I | Acc],
rand_split_list(N - 1, NList, NAcc).
list_multiple(N, List) ->
lists:flatten(lists:duplicate(N, List)).
acc_attr_list(List, Count) ->
acc_attr_list(List, [], Count).
acc_attr_list([], List, _Count) -> List;
acc_attr_list([{Type, Value}|T], List, Count) ->
AddValue = util:floor(Value * Count),
case lists:keyfind(Type, 1, List) of
false ->
acc_attr_list(T, [{Type, AddValue}|List], Count);
{Type, Old} ->
List1 = lists:keydelete(Type, 1, List),
acc_attr_list(T, [{Type, AddValue + Old}|List1], Count)
end.
max_attr_list(List, MaxList) ->
max_attr_list(List, MaxList, []).
max_attr_list([], _MaxList, Acc) -> lists:reverse(Acc);
max_attr_list([{Type, Value}|T], MaxList, Acc) ->
case lists:keyfind(Type, 1, MaxList) of
false ->
max_attr_list(T, MaxList, Acc);
{Type, Max} ->
max_attr_list(T, MaxList, [{Type, min(Value, Max)}|Acc])
end.
list_handle(F, Data, List, Place) ->
case List of
[H | T] ->
case F(H, Data, Place) of
{ok, Data2} ->
list_handle(F, Data2, T, Place);
Error ->
Error
end;
[] ->
{ok, Data}
end.
list_handle(F, Data, List) ->
case List of
[H | T] ->
case F(H, Data) of
{ok, Data2} ->
list_handle(F, Data2, T);
Error ->
Error
end;
[] ->
{ok, Data}
end.
list_rand([]) -> null;
list_rand(List) ->
Len = length(List),
Index = rand(1, Len),
lists:nth(Index, List).
@doc 随机从列表中选n个元素
list_rand_n([], _PickNum) -> [];
list_rand_n(List, PickNum) ->
list_rand_n(List, PickNum, []).
list_rand_n([], _PickNum, AccList) -> AccList;
list_rand_n(_List, 0, AccList) -> AccList;
list_rand_n(List, PickNum, AccList) ->
PickOne = list_rand(List),
LeftList = List -- [PickOne],
list_rand_n(LeftList, PickNum - 1, [PickOne | AccList]).
find_ratio([], _, _) -> [];
find_ratio([{N, R} | _], S, Ra) when Ra > S andalso Ra =< (S + R) -> N;
find_ratio([{_, R} | T], S, Ra) -> find_ratio(T, (S + R), Ra).
@Param : : Tuples : 元组列表([{权重 , ... } , ... ] 等类似格式 )
Index : 权重所在的位置(如上例则是1 )
PickNum : 随机抽出的次数
rand_by_weight(Tuples, Index, PickNum) when PickNum >= 0 ->
rand_n_by_weight(Tuples, Index, PickNum, []).
rand_n_by_weight(_Tuples, _Index, 0, Ret) -> Ret;
rand_n_by_weight([], _Index, _PickNum, Ret) -> Ret;
rand_n_by_weight(Tuples, Index, PickNum, Ret) ->
PickOne = rand_by_weight(Tuples, Index),
LeftTuples = lists:delete(PickOne, Tuples),
rand_n_by_weight(LeftTuples, Index, PickNum - 1, [PickOne | Ret]).
@doc 依据权重,从元组列表中随机挑选一个元素,返回被抽中的元组 ,
rand_by_weight([], _Index) ->
error(badargs);
rand_by_weight(List, Index) ->
Sum = lists:sum([weight_index(Tuple, Index) || Tuple <- List]),
P = rand(1, Sum),
rand_one_by_weight(List, Index, P).
rand_one_by_weight([Tuple], _, _) -> Tuple;
rand_one_by_weight([Tuple | T], Index, P) ->
case weight_index(Tuple, Index) of
Weight when P =< Weight -> Tuple;
Weight -> rand_one_by_weight(T, Index, P - Weight)
end.
weight_index(Tuple, Index) when is_tuple(Tuple) ->
element(Index, Tuple);
weight_index(Map, Key) when is_map(Map) ->
maps:get(Key, Map).
从累加的概率中随机一个
rand_list_one([], _Rand) -> error(badargs);
rand_list_one([{Value, Rate}|T], Rand) ->
if Rate >= Rand ->
Value;
true ->
rand_list_one(T, Rand)
end;
rand_list_one([{Value1, Value2, Rate}|T], Rand) ->
if Rate >= Rand ->
{Value1, Value2};
true ->
rand_list_one(T, Rand)
end.
for(Max, Max, F) -> F(Max);
for(I, Max, F) ->
F(I),
for(I + 1, Max, F).
@doc 带返回状态的for循环
for(Max, Min, _F, State) when Min < Max -> {ok, State};
for(Max, Max, F, State) -> F(Max, State);
for(I, Max, F, State) -> {ok, NewState} = F(I, State), for(I + 1, Max, F, NewState).
在List中的每两个元素之间插入一个分隔符
implode(_S, []) ->
[<<>>];
implode(S, L) when is_list(L) ->
implode(S, L, []).
implode(_S, [H], NList) ->
lists:reverse([type:object_to_list(H) | NList]);
implode(S, [H | T], NList) ->
L = [type:object_to_list(H) | NList],
implode(S, T, [S | L]).
explode(S, B) ->
re:split(B, S, [{return, list}]).
explode(S, B, int) ->
[list_to_integer(Str) || Str <- explode(S, B), length(Str) > 0].
gen_n(0, []) ->
[];
gen_n(N, List) when N > 0, is_list(List), List =/= [] ->
gen_n(N, List, []);
gen_n(_N, _List) ->
[].
gen_n(0, _List, Acc) ->
Acc;
gen_n(N, List, Acc) when is_list(Acc) ->
Item = list_rand(List),
gen_n(N - 1, List, [Item | Acc]).
prop_get_value(Key, List) ->
prop_get_value(Key, List, undefined).
prop_get_value(Key, List, Def) ->
case lists:keyfind(Key, 1, List) of
{Key, Val} -> Val;
_ -> Def
end.
prop_get_value(Key, Pos, List, Def) ->
case lists:keyfind(Key, Pos, List) of
{Key, Val} -> Val;
_ -> Def
end.
@doc proplists : get_keys/1
prop_get_keys(List) ->
[K || {K, _V} <- List].
prop_delete(K, List) ->
lists:keydelete(K, 1, List).
prop_store({K, V}, List) ->
prop_store(K, V, List).
prop_store(K, V, List) ->
lists:keystore(K, 1, List, {K, V}).
prop_increase(K, List) ->
prop_increase(K, List, 1).
prop_increase(K, List, Incl) ->
case prop_get_value(K, List, 0) of
V when is_integer(V) ->
prop_store(K, V + Incl, List);
_ ->
List
end.
@doc 产生一个介于Min到Max之间的随机整数
rand(Same, Same) -> Same;
rand(Min, Max) when Max < Min -> 0;
rand(Min, Max) ->
case get("rand_seed") of
undefined ->
rand:seed(exs1024),
put("rand_seed", 1);
_ ->
skip
end,
M = Min - 1,
rand:uniform(Max - M) + M.
ceil(X) ->
T = trunc(X),
case X =:= T of
true -> T;
false -> T + 1
end.
@doc 向下取整
floor(X) ->
T = trunc(X),
case X < T of
true -> max(T - 1, 0);
_ -> T
end.
get_ip(Socket) ->
case inet:peername(Socket) of
{ok, {Ip, _Port}} -> Ip;
{error, _Reason} -> {0, 0, 0, 0}
end.
doc 角度和cos的转换,cos(60 ' ) = 0.5
angle_to_float(Angle) ->
math:cos(math:pi() * Angle / 180).
Page : 第几页数据(大于总页数则默认最后页 )
PageNum :
@return : : { 总条数 , 当前页 , 当前页数据 }
page_data(List, Page, Count) ->
Len = length(List),
Start = max(Page - 1, 0) * Count + 1,
if Start > Len ->
{Len, Page, []};
true ->
{Len, Page, lists:sublist(List, Start, Count)}
end.
md5(S) ->
lists:flatten([io_lib:format("~2.16.0b", [N]) || N <- binary_to_list(erlang:md5(S))]).
hmac(Key, Msg) ->
crypto:hmac(sha, list_to_binary(Key), list_to_binary(Msg)).
hmac_hex(Key, Msg) ->
<<Mac:160/integer>> = crypto:hmac(sha, list_to_binary(Key), list_to_binary(Msg)),
lists:flatten(io_lib:format("~40.16.0b", [Mac])).
filter_text_gm(Text) when is_bitstring(Text) ->
Text;
filter_text_gm(Text) when is_list(Text) ->
list_to_bitstring(Text).
@return : : true 存在关键词
string_width(String) ->
string_width(String, 0).
string_width([], Len) ->
Len;
string_width([H | T], Len) ->
case H > 255 of
true ->
string_width(T, Len + 2);
false ->
string_width(T, Len + 1)
end.
check_length(Item, LenLimit) ->
check_length(Item, 1, LenLimit).
check_length(Item, MinLen, MaxLen) ->
case unicode:characters_to_list(list_to_binary(Item)) of
UnicodeList when is_list(UnicodeList) ->
Len = string_width(UnicodeList),
Len =< MaxLen andalso Len >= MinLen;
_ ->
false
end.
@doc IP元组转字符
ip2bin(IP) when is_list(IP) ->
case inet:parse_address(IP) of
{ok, _IP} -> ip2bin(_IP);
_ -> "256.256.256.256"
end;
ip2bin({A, B, C, D}) ->
[integer_to_list(A), ".", integer_to_list(B), ".", integer_to_list(C), ".", integer_to_list(D)];
ip2bin(_) ->
"256.256.256.256".
filter_string(String, CharList) ->
case is_list(String) of
true ->
filter_string_helper(String, CharList, []);
false when is_binary(String) ->
ResultString = filter_string_helper(binary_to_list(String), CharList, []),
list_to_binary(ResultString);
false ->
String
end.
filter_string_helper([], _CharList, ResultString) ->
ResultString;
filter_string_helper([H | T], CharList, ResultString) ->
case lists:member(H, CharList) of
true -> filter_string_helper(T, CharList, ResultString);
false -> filter_string_helper(T, CharList, ResultString ++ [H])
end.
escape_unicode([H | T]) ->
if
H band 16#F8 =:= 16#F0 ->
if
length(T) >= 3 ->
escape_unicode(lists:nthtail(3, T));
true -> []
end;
true ->
[H | escape_unicode(T)]
end;
escape_unicode([]) ->
[].
@doc 转义数据库varchar
escape_varchar(S) ->
S1 = escape_unicode(S),
R = re:replace(S1, "[\\\\|-|;|,|.|/|\\(|\\)|\\[|\\]|}|{|%|\\@|*|!|'|\"]", "", [global, {return, binary}]),
erlang:binary_to_list(R).
@doc 转义数据库varchar
escape_name(S) ->
escape_unicode(string:strip(S)).
calc_string_compare(A, B) ->
AWordDict = word_dict(unicode:characters_to_list(type:object_to_binary(A))),
BWordDict = word_dict(unicode:characters_to_list(type:object_to_binary(B))),
Dict = merge_dict(AWordDict, BWordDict),
F = fun(_K, {V1, V2}, {DenominatorAcc, Sqdoc1Acc, Sqdoc2Acc}) ->
{DenominatorAcc + V1 * V2
, Sqdoc1Acc + V1 * V1
, Sqdoc2Acc + V2 * V2
}
end,
{Denominator, Sqdoc1, Sqdoc2} = dict:fold(F, {0, 0, 0}, Dict),
case Sqdoc1 =:= 0 orelse Sqdoc2 =:= 0 of
true -> 0;
false -> Denominator / math:sqrt(Sqdoc1 * Sqdoc2)
end.
merge_dict(D1, D2) ->
F1 = fun(_K, V) -> {V, 0} end,
D1T = dict:map(F1, D1),
F2 = fun(K, V, Dict) ->
case dict:find(K, D1T) of
error -> dict:store(K, {0, V}, Dict);
{ok, {V1, 0}} -> dict:store(K, {V1, V}, Dict);
_ -> Dict
end
end,
D2T = dict:fold(F2, D1T, D2),
D2T.
A - Z 65 - 90
a - z 97 - 122
0 - 9 48 - 57
word_dict(L) -> word__(L, [], dict:new()).
word__([A | L], Word, WordDict) when (A >= 65 andalso A =< 90) orelse
(A >= 97 andalso A =< 122) orelse
(A >= 48 andalso A =< 57) ->
word__(L, [A | Word], WordDict);
word__([I | L], [], WordDict) ->
word__(L, [], dict:update_counter([I], 1, WordDict));
word__([I | L], Word, WordDict) ->
WordDict1 = dict:update_counter(Word, 1, WordDict),
WordDict2 = dict:update_counter([I], 1, WordDict1),
word__(L, [], WordDict2);
word__([], [], WordList) ->
WordList;
word__([], Word, WordDict) ->
dict:update_counter(Word, 1, WordDict).
string_sub(Str, Start) ->
Unicode = unicode:characters_to_list(Str),
unicode:characters_to_binary(lists:sublist(Unicode, Start)).
string_sub(Str, Start, Len) ->
Unicode = unicode:characters_to_list(Str),
unicode:characters_to_binary(lists:sublist(Unicode, Start, Len)).
safe_format(Fmt, Args) when is_list(Args) ->
F = fun(A) -> ?iif(is_list(A) =:= true, list_to_binary(A), A) end,
ArgsN = lists:map(F, Args),
case catch lists:flatten(io_lib:format(Fmt, ArgsN)) of
Val when is_list(Val) orelse is_binary(Val) ->
Val;
_ ->
Fmt
end.
trip_name(Name) when is_binary(Name) ->
trip_name(erlang:binary_to_list(Name));
trip_name(Name) when is_list(Name) ->
string:sub_string(Name, string:chr(Name, $.) + 1).
dict_find(Key, Dict) ->
dict_find(Key, Dict, undefined).
dict_find(Key, Dict, Default) ->
case dict:find(Key, Dict) of
{ok, V} -> V;
_ -> Default
end.
dict_find2(Key, Dict, Default) ->
case dict:find(Key, Dict) of
{ok, V} -> {true, V};
_ -> {false, Default}
end.
cancel_timer(Timer) ->
case is_reference(Timer) of
true ->
erlang:cancel_timer(Timer);
false ->
skip
end,
[].
cancel_timer(Ref, Event) when is_reference(Ref) ->
case erlang:cancel_timer(Ref) of
fasle ->
receive Event -> 0
after 0 -> false
end;
RemainingTime -> RemainingTime
end;
cancel_timer(_Ref, _Event) ->
false.
get_ets(Table, Key) ->
case ets:lookup(Table, Key) of
[{Key, Val}] -> Val;
_ -> undefined
end.
get_ets(Table, Key, Def) ->
case ets:lookup(Table, Key) of
[{Key, Val}] -> Val;
_ -> Def
end.
put_ets(Table, Key, Value) ->
ets:insert(Table, {Key, Value}).
del_ets(Table, Key) ->
ets:delete(Table, Key).
cls_ets(Table) ->
ets:delete_all_objects(Table).
batch_insert(PoolFlag, 0, Fmt1, Fmt2, List) ->
insert_values(PoolFlag, Fmt1, Fmt2, List);
batch_insert(_PoolFlag, _Size, _Fmt1, _Fmt2, []) ->
ok;
batch_insert(PoolFlag, Size, Fmt1, Fmt2, List) ->
{Batch, Left} = split_list(Size, List),
insert_values(PoolFlag, Fmt1, Fmt2, Batch),
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Left).
batch_insert(PoolFlag, 0, Fmt1, Fmt2, Fun, List) ->
insert_values(PoolFlag, Fmt1, Fmt2, Fun, List);
batch_insert(_PoolFlag, _Size, _Fmt1, _Fmt2, _Fun, []) ->
ok;
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Fun, List)
when is_integer(Size), Size > 0, ?VALID_STR(Fmt1), ?VALID_STR(Fmt2), is_function(Fun, 1), is_list(List) ->
{Batch, Left} = split_list(Size, List),
insert_values(PoolFlag, Fmt1, Fmt2, Fun, Batch),
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Fun, Left).
insert_values(PoolFlag, Fmt1, Fmt2, Args, Fun, List);
batch_insert(_PoolFlag, _Size, _Fmt1, _Fmt2, _Args, _Fun, []) ->
ok;
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Args, Fun, List)
when is_integer(Size), Size > 0, ?VALID_STR(Fmt1), ?VALID_STR(Fmt2), is_list(Args), is_function(Fun, 1), is_list(List) ->
{Batch, Left} = split_list(Size, List),
insert_values(PoolFlag, Fmt1, Fmt2, Args, Fun, Batch),
batch_insert(PoolFlag, Size, Fmt1, Fmt2, Args, Fun, Left).
@doc 批量插入 [ ]
insert_values(_PoolFlag, _Fmt1, _Fmt2, []) ->
ok;
insert_values(PoolFlag, Fmt1, Fmt2, List) ->
insert_values2(PoolFlag, Fmt1, Fmt2, [], List).
insert_values(PoolFlag, Fmt1, Fmt2, Fun, List) when is_function(Fun, 1), is_list(List) ->
insert_values(PoolFlag, Fmt1, Fmt2, [], Fun, List);
insert_values(PoolFlag, Fmt1, Fmt2, Args, List) when is_list(Args) ->
insert_values2(PoolFlag, Fmt1, Fmt2, Args, List).
insert_values(PoolFlag, Fmt1, Fmt2, Args, Fun, List) when is_list(Args), is_function(Fun, 1), is_list(List) ->
RankList = lists:map(Fun, List),
insert_values2(PoolFlag, Fmt1, Fmt2, Args, RankList).
insert_values2(_PoolFlag, _Fmt1, _Fmt2, _Args, []) ->
ok;
insert_values2(PoolFlag, Fmt1, Fmt2, Args, List) ->
Values = format_values(Fmt2, List),
SQL = io_lib:format(Fmt1, Args ++ [Values]),
?DB:execute(PoolFlag, SQL),
ok.
format_values(Temp, List) ->
FinList = format_values(List, Temp, []),
implode(",", FinList, []).
format_values([], _Temp, Acc) ->
lists:reverse(Acc);
format_values([L | T], Temp, Acc) ->
F = io_lib:format(Temp, L),
format_values(T, Temp, [F | Acc]).
sup_info_child(Sup, Info) ->
[Pid ! Info || Pid <- sup_children_pid(Sup)].
sup_children_pid(Sup) ->
case catch supervisor:which_children(Sup) of
List when is_list(List) ->
[Child || {_Id, Child, _Type, _Modules} <- List];
_ ->
[]
end.
process_infos() ->
filelib:ensure_dir("../logs/"),
File = "../logs/processes_infos.log",
{ok, Fd} = file:open(File, [write, raw, binary, append]),
Fun = fun(Pi) ->
Info = io_lib:format("=>~p \n\n", [Pi]),
case filelib:is_file(File) of
true ->
file:write(Fd, Info);
false ->
file:close(Fd),
{ok, NewFd} = file:open(File, [write, raw, binary, append]),
file:write(NewFd, Info)
end,
timer:sleep(20)
end,
[Fun(erlang:process_info(P)) || P <- erlang:processes()].
process_infos(Pid, Type) ->
filelib:ensure_dir("../logs/"),
File = "../logs/processes_infos.log",
{ok, Fd} = file:open(File, [write, raw, binary, append]),
Fun = fun(Pi) ->
NewPi = case Type of
messages ->
{messages, SendList} = Pi,
lists:foldl(fun({TType, Content}, CmdList) ->
case TType of
send ->
<<_A:16, Cmd:32, _Left/binary>> = Content,
case lists:keyfind(Cmd, 1, CmdList) of
false -> [{Cmd, 1} | CmdList];
{_, CNum} -> lists:keyreplace(Cmd, 1, CmdList, {Cmd, CNum + 1})
end;
_ -> [{TType, Content} | CmdList]
end
end, [], SendList);
_ ->
Pi
end,
Info = io_lib:format("=>~p \n\n", [NewPi]),
case filelib:is_file(File) of
true ->
file:write(Fd, Info);
false ->
file:close(Fd),
{ok, NewFd} = file:open(File, [write, raw, binary, append]),
file:write(NewFd, Info)
end
end,
PInfo = erlang:process_info(Pid, Type),
Fun(PInfo). |
97e93e33bb2e270bf8df4592487b54276551920ca9f30550835415d208d680ee | srid/ema | Spec.hs | module Main where
-- | Filler module so cabal will be happy that there's a main-is
main :: IO ()
main = pure ()
| null | https://raw.githubusercontent.com/srid/ema/61faae56aa0f3c6ca815f344684cc566f6341662/ema-generics/test/type-errors/Spec.hs | haskell | | Filler module so cabal will be happy that there's a main-is | module Main where
main :: IO ()
main = pure ()
|
49a71a26293a6e9de0ec3966fbceec81ca06ee3a86b2f1ccd23024d691edaa12 | stumpwm/stumpwm-contrib | package.lisp | package.lisp
(defpackage #:swm-pomodoro
(:use #:cl #:stumpwm)
(:export #:*bell-sound-file*
#:*sound-play-command*))
(in-package :swm-pomodoro)
(defvar status-message nil
"Status message for dashboard, as well as for StumpWM modeline
when `notifications` are on.")
(defvar notifications-loaded
(when (member "notifications" (asdf:already-loaded-systems)
:test #'string-equal) t)
"True when StumpWM-Contrib `Notifications` module is loaded.")
(defvar *bell-sound-file* #p"~/Music/bell.wav"
"When set to a sound file pathname, that sound will be played
at the end of each pomodoro.")
(defvar *sound-play-command* "aplay"
"System command to play sounds.")
(defparameter *pomodoro-duration* 1500
"Default duration of one pomodoro = 25 * 60 seconds.")
(defparameter *pomodoros-scored* 0
"Counter of finished pomodoros in a series.")
(defparameter *pomodoro-timer* nil
"The pomodoro timer clock object.")
(defun update-status-message ()
(when notifications-loaded
(notifications:notifications-delete status-message))
(setf status-message (timer-status))
(when notifications-loaded
(notifications:notifications-add status-message)))
(defun finish-timer ()
"Score Pomodoro."
(sb-ext:unschedule-timer *pomodoro-timer*)
(incf *pomodoros-scored*)
(update-status-message)
(stumpwm:message
"+1 (`) Pomodoro Scored!~%~a" status-message)
(ring-the-bell))
(setf *pomodoro-timer*
(sb-ext:make-timer #'swm-pomodoro::finish-timer
:name :pomodoro-timer))
(defun reset-scored ()
"Reset finished pomodoros series counter to 0."
(setf *pomodoros-scored* 0)
(update-status-message))
(defun ring-the-bell ()
"Play the *BELL-SOUND-FILE* if exists."
(when (probe-file *bell-sound-file*)
(uiop:run-program
(format nil "~a ~a" *sound-play-command* (namestring *bell-sound-file*)))))
(defun notify-break ()
"Say what kind of break you deserve."
(if (= *pomodoros-scored* 0)
"^[^3Work harder!^]"
(if (= 0 (mod *pomodoros-scored* 4))
"^[^7^B[_])^2 15+ min!^]"
"^[^2^B<-> 5 min^]")))
(defun many-scored ()
"See how many have I scored."
(format nil "^[^1^B(`)^6 ~a^]" *pomodoros-scored*))
(defun timer-status ()
"Print the status of the timer."
(if (sb-ext:timer-scheduled-p *pomodoro-timer*)
"^[^1^B(`)^n in progress...^]"
(format nil "~a : ~a"
(many-scored) (notify-break))))
(stumpwm:defcommand pomodoro-status () ()
(update-status-message)
(stumpwm:message status-message))
(stumpwm:defcommand pomodoro-reset () ()
"Reset global pomodoros series."
(reset-scored)
(stumpwm:message "Pomodoros series reset."))
(stumpwm:defcommand pomodoro-start-timer () ()
(when (not (sb-ext:timer-scheduled-p *pomodoro-timer*))
(sb-ext:schedule-timer *pomodoro-timer* *pomodoro-duration*)
(stumpwm:message "Pomodoro timer set."))
(update-status-message))
(stumpwm:defcommand pomodoro-cancel-timer () ()
(sb-ext:unschedule-timer *pomodoro-timer*)
(stumpwm:message "^1(7)^n Pomodoro timer cancelled!")
(update-status-message))
| null | https://raw.githubusercontent.com/stumpwm/stumpwm-contrib/c4cad24328502d8f2973db62f67c9788852c821c/util/pomodoro/package.lisp | lisp | package.lisp
(defpackage #:swm-pomodoro
(:use #:cl #:stumpwm)
(:export #:*bell-sound-file*
#:*sound-play-command*))
(in-package :swm-pomodoro)
(defvar status-message nil
"Status message for dashboard, as well as for StumpWM modeline
when `notifications` are on.")
(defvar notifications-loaded
(when (member "notifications" (asdf:already-loaded-systems)
:test #'string-equal) t)
"True when StumpWM-Contrib `Notifications` module is loaded.")
(defvar *bell-sound-file* #p"~/Music/bell.wav"
"When set to a sound file pathname, that sound will be played
at the end of each pomodoro.")
(defvar *sound-play-command* "aplay"
"System command to play sounds.")
(defparameter *pomodoro-duration* 1500
"Default duration of one pomodoro = 25 * 60 seconds.")
(defparameter *pomodoros-scored* 0
"Counter of finished pomodoros in a series.")
(defparameter *pomodoro-timer* nil
"The pomodoro timer clock object.")
(defun update-status-message ()
(when notifications-loaded
(notifications:notifications-delete status-message))
(setf status-message (timer-status))
(when notifications-loaded
(notifications:notifications-add status-message)))
(defun finish-timer ()
"Score Pomodoro."
(sb-ext:unschedule-timer *pomodoro-timer*)
(incf *pomodoros-scored*)
(update-status-message)
(stumpwm:message
"+1 (`) Pomodoro Scored!~%~a" status-message)
(ring-the-bell))
(setf *pomodoro-timer*
(sb-ext:make-timer #'swm-pomodoro::finish-timer
:name :pomodoro-timer))
(defun reset-scored ()
"Reset finished pomodoros series counter to 0."
(setf *pomodoros-scored* 0)
(update-status-message))
(defun ring-the-bell ()
"Play the *BELL-SOUND-FILE* if exists."
(when (probe-file *bell-sound-file*)
(uiop:run-program
(format nil "~a ~a" *sound-play-command* (namestring *bell-sound-file*)))))
(defun notify-break ()
"Say what kind of break you deserve."
(if (= *pomodoros-scored* 0)
"^[^3Work harder!^]"
(if (= 0 (mod *pomodoros-scored* 4))
"^[^7^B[_])^2 15+ min!^]"
"^[^2^B<-> 5 min^]")))
(defun many-scored ()
"See how many have I scored."
(format nil "^[^1^B(`)^6 ~a^]" *pomodoros-scored*))
(defun timer-status ()
"Print the status of the timer."
(if (sb-ext:timer-scheduled-p *pomodoro-timer*)
"^[^1^B(`)^n in progress...^]"
(format nil "~a : ~a"
(many-scored) (notify-break))))
(stumpwm:defcommand pomodoro-status () ()
(update-status-message)
(stumpwm:message status-message))
(stumpwm:defcommand pomodoro-reset () ()
"Reset global pomodoros series."
(reset-scored)
(stumpwm:message "Pomodoros series reset."))
(stumpwm:defcommand pomodoro-start-timer () ()
(when (not (sb-ext:timer-scheduled-p *pomodoro-timer*))
(sb-ext:schedule-timer *pomodoro-timer* *pomodoro-duration*)
(stumpwm:message "Pomodoro timer set."))
(update-status-message))
(stumpwm:defcommand pomodoro-cancel-timer () ()
(sb-ext:unschedule-timer *pomodoro-timer*)
(stumpwm:message "^1(7)^n Pomodoro timer cancelled!")
(update-status-message))
| |
50c44491f1014346ecc3a04ca356b85f3dead289874e771290e2cf93f08fde84 | mflatt/sirmail | pref.rkt | (module pref mzscheme
(require mzlib/class
framework
mred
mzlib/list
mzlib/string
mzlib/etc
net/head)
;; IMPORTANT! All preferences operations outside this
;; file should go through the following exports.
;; DO NOT use preferences:... elsewhere.
(provide get-pref put-pref
show-pref-dialog
add-preferences-menu-items)
(define (string-or-false? x) (or (not x) (string? x)))
(define (ip-string? x) (and (string? x)
(positive? (string-length x))))
(define (abs-path-or-false? x)
(or (not x)
(and (path? x) (absolute-path? x))))
(define (un/marshall-path pref)
(preferences:set-un/marshall pref
(lambda (x)
(if (path? x)
(path->bytes x)
x))
(lambda (x)
(cond
[(bytes? x) (bytes->path x) ]
[(not x) x]
[else 'badvalue]))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Preference Definitions ;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(preferences:set-default 'sirmail:mail-from "SirMail User <>" string?)
(preferences:set-default 'sirmail:username "username" string?)
(preferences:set-default 'sirmail:password #f string-or-false?)
(preferences:set-default 'sirmail:default-to-domain "racket-lang.org" ip-string?)
(preferences:set-default 'sirmail:imap-server "imap.racket-lang.org" ip-string?)
(preferences:set-default 'sirmail:use-ssl? #f boolean?)
(preferences:set-default 'sirmail:server-certificate #f abs-path-or-false?)
(preferences:set-default 'sirmail:smtp-server "sendmail.racket-lang.org" ip-string?)
(preferences:set-default 'sirmail:local-directory
(build-path (find-system-path 'home-dir)
"SirMail")
(lambda (x)
(and (path? x)
(absolute-path? x))))
(un/marshall-path 'sirmail:local-directory)
(preferences:set-default 'sirmail:sent-directory
(build-path (find-system-path 'home-dir)
"SentMail")
(lambda (x)
(or (not x)
(and (path? x)
(absolute-path? x)))))
(un/marshall-path 'sirmail:sent-directory)
(preferences:set-default 'sirmail:root-mailbox-folder #f string-or-false?)
(preferences:set-default 'sirmail:archive-mailbox-folder #f string-or-false?)
(preferences:set-default 'sirmail:trash-mailbox-folder "INBOX.Trash" string-or-false?)
(preferences:set-default 'sirmail:initial-sort 'id
(lambda (x) (memq x '(id date subject from))))
(preferences:set-default 'sirmail:biff-delay
60
(lambda (x)
(or (not x)
(and (number? x)
(exact? x)
(integer? x)
(positive? x)))))
(preferences:set-default 'sirmail:warn-download-size 32000
(lambda (x) (or (not x) (and (number? x) (real? x)))))
(preferences:set-default 'sirmail:external-composer 'xemacs
(lambda (x) (memq x '(xemacs gnu-emacs))))
(preferences:set-default 'sirmail:use-extenal-composer? #f boolean?)
(preferences:set-default 'sirmail:show-urls? #t boolean?)
(preferences:set-default 'sirmail:show-gc-icon #f boolean?)
(preferences:set-default 'sirmail:show-memory-use? #t boolean?)
(preferences:set-default 'sirmail:always-happy #f boolean?)
(preferences:set-default 'sirmail:wrap-lines #f boolean?)
(preferences:set-default 'sirmail:prefer-text #t boolean?)
(preferences:set-default 'sirmail:show-html-images? #f boolean?)
(preferences:set-default 'sirmail:aliases-file
(build-path (find-system-path 'home-dir) ".sirmail.aliases")
abs-path-or-false?)
(un/marshall-path 'sirmail:aliases-file)
(preferences:set-default 'sirmail:auto-file-table-file (build-path (find-system-path 'home-dir) ".sirmail.auto-file")
abs-path-or-false?)
(un/marshall-path 'sirmail:auto-file-table-file)
(preferences:set-default 'sirmail:self-addresses null
(lambda (x) (and (list? x) (andmap string? x))))
(preferences:set-default 'sirmail:fields-to-show '("From" "To" "CC" "Subject" "Date" "X-Mailer" "X-Uptime")
(lambda (x) (and (list? x) (andmap string? x))))
(preferences:set-default 'sirmail:bcc #f
(λ (x) (or (not x) (string? x))))
(preferences:set-default 'sirmail:x-mailer-header #t boolean?)
(preferences:set-default 'sirmail:message-columns 80 exact-positive-integer?)
(preferences:set-default 'sirmail:mailbox-init-message 'last
(lambda (x) (or (eq? x 'first) (eq? x 'last))))
(preferences:set-default 'sirmail:folder-window-can-refresh? #t boolean?)
(preferences:set-default 'sirmail:send-by-discarding? #f boolean?) ; useful only for tests or demos
(let ([fw 560]
[fh 600])
(let-values ([(display-width display-height) (get-display-size)])
(preferences:set-default 'sirmail:frame-width
(min display-height fh)
(lambda (x) (and (number? x) (<= 0 x 32768))))
(preferences:set-default 'sirmail:frame-height
(min display-width fw)
(lambda (x) (and (number? x) (<= 0 x 32768))))))
(define (xywh-okay? n)
(and (number? n)
(<= 0 n 10000)))
(preferences:set-default 'sirmail:folder-window-w 200 xywh-okay?)
(preferences:set-default 'sirmail:folder-window-h 400 xywh-okay?)
(preferences:set-default 'sirmail:folder-window-x 0 xywh-okay?)
(preferences:set-default 'sirmail:folder-window-y 0 xywh-okay?)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Preference Manager ; ;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define prefs-eventspace (make-eventspace))
(define (in-preferences-eventspace thunk)
(let ([val #f]
[s (make-semaphore)])
(parameterize ([current-eventspace prefs-eventspace])
(queue-callback
(lambda ()
(with-handlers ([void (lambda (x)
;; Assume all raised values are exns
(set! val x))])
(set! val (thunk)))
(semaphore-post s))))
(semaphore-wait s)
(if (exn? val)
(raise val)
val)))
(define (get-pref id)
(in-preferences-eventspace (lambda ()
(preferences:get id))))
(define (put-pref id val)
(in-preferences-eventspace (lambda ()
(preferences:set id val))))
(define (add-preferences-menu-items edit-menu)
(make-object separator-menu-item% edit-menu)
(make-object menu-item% "Preferences" edit-menu
(lambda (x y) (in-preferences-eventspace preferences:show-dialog))))
(define (show-pref-dialog)
(in-preferences-eventspace
(lambda ()
(preferences:show-dialog)
(yield 'wait))))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Preference Dialog ; ;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define needs-check null)
(define (set-hilite e on?)
(send e change-style
(send (make-object style-delta%) set-delta-background (if on? "yellow" "white"))
0 (send e last-position)))
;; make-text-field : string panel number symbol boolean
;; ((union #f string) (union #f top-level-window<%>) string -> boolean)
;; (any -> string)
;; (string -> any)
;; [ (union #f string) ]
;; -> void
;; sets up a text field for a preference
The 3rd - to - last argument checks the validity of the field content . If
;; a string is provided, then a top-level-window<%> is also provded, and
;; the checking function should tell the user why the field-value string
;; is bad if it is bad.
the last two arguments convert between the string representation ( as shown in the text field )
;; and the preferences's actual Scheme value.
(define make-text-field
(opt-lambda (label panel width-num pref optional? check-value val->str str->val [post-label #f])
(define p0 (and (or optional? post-label)
(instantiate horizontal-panel% (panel) [stretchable-height #f])))
(define e (and optional?
(make-object check-box% label p0
(lambda (c e)
(let ([on? (send c get-value)])
(send t enable on?)
(if on?
(t-cb t e)
(begin
;; remove all need-check registrations, if any:
(let loop ()
(let ([a (assq t needs-check)])
(when a
(set! needs-check (remq a needs-check))
(loop))))
(preferences:set pref #f))))))))
(define t-cb (lambda (t e)
(let* ([s (send t get-value)])
(if (check-value #f #f s)
(preferences:set pref (str->val s))
(begin
(set! needs-check (cons (list t label check-value) needs-check))
(set-hilite (send t get-editor) #t))))))
(define t (make-object text-field%
(if optional? #f label)
(or p0 panel)
t-cb
(make-string width-num #\X)))
(when post-label
(send t stretchable-width #f)
(make-object message% post-label p0))
(send t set-value (let ([v (preferences:get pref)])
(if v
(val->str v)
"")))
(when optional?
(send e set-value (preferences:get pref)))
(when e
(send t enable (send e get-value)))
(preferences:add-callback pref (lambda (name val)
(set-hilite (send t get-editor) #f)
(when e
(send e set-value val)
(send t enable val))
(when val
(let ([sval (val->str val)])
(unless (equal? sval (send t get-value))
(send t set-value sval))))))
(or p0 t)))
(define (check-unsaved-pref?)
(and (andmap (lambda (a)
((caddr a) (cadr a) (send (car a) get-top-level-window) (send (car a) get-value)))
needs-check)
(begin
(set! needs-check null)
#t)))
(define make-file/directory-button
(lambda (dir? button-label parent pref enabler)
(define p0 (and enabler
(instantiate horizontal-panel% (parent) [stretchable-height #f])))
(define e (and enabler
(make-object check-box% enabler p0
(lambda (c e)
(let ([on? (send c get-value)])
(send p enable on?)
(preferences:set
pref
(and on?
(string->path (send field get-value)))))))))
(define p (instantiate horizontal-panel% ((or p0 parent))
[stretchable-height #f]))
(define (set-it v)
(preferences:set pref v))
(define field (make-object text-field% button-label p
;; For now, just counteract edits:
(lambda (t e)
(send field set-value (path->string (preferences:get pref))))
(path->string
(or (preferences:get pref)
(current-directory)))))
(when e
(send e set-value (preferences:get pref))
(send p enable (send e get-value)))
(preferences:add-callback pref (lambda (name val)
(when e
(send e set-value val)
(send p enable val))
(when val
(send field set-value (path->string val)))))
(make-object button% "Set..." p (lambda (b e)
(let ([v ((if dir? get-directory get-file)
(or enabler button-label))])
(when v
(set-it v)))))
p0))
(define make-boolean
(opt-lambda (label p pref [extra-action void])
(define c
(make-object check-box% label p (lambda (c e)
(let ([v (send c get-value)])
(extra-action v)
(preferences:set pref v)))))
(send c set-value (preferences:get pref))
(preferences:add-callback pref (lambda (name val)
(send c set-value val)))))
(define (is-host-address? s)
(regexp-match "^([-a-zA-Z0-9]+[.])*[-a-zA-Z0-9]+$" s))
(define (is-host-address+port? s)
(or (is-host-address? s)
(let ([m (regexp-match "^(.*):([0-9]+)$" s)])
(and m
(<= 1 (string->number (caddr m)) 65535)
(is-host-address? (cadr m))))))
(define (is-host-address+port+user? s)
(or (is-host-address+port? s)
(let ([m (regexp-match "^(?:[-+a-zA-Z0-9_.]+)@(.*)$" s)])
(and m
(is-host-address+port? (cadr m))))))
(define (is-host-address+port+user+type? s)
(or (is-host-address+port+user? s)
(let ([m (regexp-match "^(?:ssl|tls|tcp):(.*)$" s)])
(and m
(is-host-address+port+user? (cadr m))))))
(define (is-host-address+port+user+type-list? s)
(let ([l (regexp-split ", *" s)])
(andmap is-host-address+port+user+type? l)))
(define (check-address ok? who tl s port-ok? multi?)
(or (ok? s)
(begin
(when who
(message-box
"Preference Error"
(format (string-append
"The ~a value must be a~a host IP address~a~a~a.\n"
"An IP address is an string containing a combination of "
"period (.), dash (-), A-Z, a-Z, and 0-9. "
"Also the period cannot appear at the very beginning or end.\n"
"~a"
"You provided\n\n ~a\n\nwhich is not legal.")
who
(if multi? " comma-separated list of" "")
(if multi? " es" "")
(if (and multi? port-ok?) " each" "")
(if port-ok? " with an optional port number" "")
(if port-ok?
(string-append
"An optional port number is specified by adding a "
"colon (:) followed by a number between 1 and 65535.\n")
"")
s)
tl
'(ok stop)))
#f)))
(define (check-host-address who tl s)
(check-address is-host-address? who tl s #f #f))
(define (check-host-address/port who tl s)
(check-address is-host-address+port? who tl s #t #f))
(define (check-host-address/port/user/type/multi who tl s)
(check-address is-host-address+port+user+type-list? who tl s #t #t))
;; check-biff-delay : (union #f string) (union #f parent) string -> boolean
;; checks to see if the string in the biff delay field makes
sense as an exact integer between 1 and 3600
(define (check-biff-delay who tl s)
(let ([n (string->number s)])
(or (and (number? n)
(integer? n)
(exact? n)
(<= 1 n 3600))
(begin
(when who
(message-box
"Preference Error"
(format (string-append
"The biff delay must be an exact integer between 1 and 3600.\n"
"You provided:\n"
" ~a")
s)
tl
'(ok stop)))
#f))))
;; check-message-size : (union #f string) (union #f parent) string -> boolean
;; checks to see if the string in the download-max-size field makes
;; sense as an exact positive integer
(define (check-message-size who tl s)
(let ([n (string->number s)])
(or (and (number? n)
(integer? n)
(exact? n)
(positive? n))
(begin
(when who
(message-box
"Preference Error"
(format (string-append
"The message size must be an exact, positive integer.\n"
"You provided:\n"
" ~a")
s)
tl
'(ok stop)))
#f))))
(define (check-user-address who tl s)
(with-handlers ([exn:fail?
(lambda (x)
(when who
(message-box
"Preference Error"
(format "The ~a value you provided is not a legal mail address: ~a"
who s)
tl
'(ok stop)))
#f)])
(unless (= 1 (length (extract-addresses s 'all)))
(error "multiple addresses"))
#t))
(define (check-simple-user-address who tl s)
(and (check-user-address who tl s)
(car (extract-addresses s 'address))))
(define (check-id who tl s) #t)
(define (make-text-list label parent pref check-item)
(let ([p (make-object group-box-panel% label parent)])
(define l (make-object list-box% #f (or (preferences:get pref) null) p
(lambda (l e)
(send delete enable (pair? (send l get-selections))))
'(multiple)))
(define hp (instantiate horizontal-panel% (p)
[stretchable-height #f]
[alignment '(center center)]))
(define add (make-object button% "Add" hp (lambda (b e)
(let loop ([init ""])
(let ([v (get-text-from-user (format "Add to ~a" label)
(format "Add to ~a" label)
(send parent get-top-level-window)
init)])
(when v
(let ([revised (check-item (format "item for ~a" label)
(send b get-top-level-window) v)])
(if revised
(begin
(send l append (if (string? revised) revised v))
(set-prefs))
(loop v)))))))))
(define delete (make-object button% "Delete" hp (lambda (b e)
(let ([d (send l get-selections)])
(for-each (lambda (i)
(send l delete i))
(sort d >))
(set-prefs)))))
(define (set-prefs)
(send delete enable (pair? (send l get-selections)))
(preferences:set
pref
(let ([n (send l get-number)])
(let loop ([i 0])
(if (= i n)
null
(cons (send l get-string i)
(loop (add1 i))))))))
(send delete enable #f)
(preferences:add-callback pref (lambda (name val)
(send l clear)
(for-each (lambda (i)
(send l append i))
val)
(send delete enable (pair? (send l get-selections)))))))
(define (make-addresses-preferences-panel parent)
(let ([p (instantiate vertical-panel% (parent))])
(make-text-field "Mail From" p 20 'sirmail:mail-from #f check-user-address (lambda (x) x) (lambda (x) x))
(make-text-field "SMTP Server" p 20 'sirmail:smtp-server #f check-host-address/port/user/type/multi
(lambda (x) x) (lambda (x) x))
(make-file/directory-button #t #f p
'sirmail:sent-directory
"Save Sent Files")
(make-text-field "Default \"To\" domain" p 20 'sirmail:default-to-domain #f check-host-address (lambda (x) x) (lambda (x) x))
(make-text-field "BCC line" p 20 'sirmail:bcc #t void (lambda (x) x) (lambda (x) x))
(make-file/directory-button #f #f p
'sirmail:aliases-file
"Aliases File")
(make-text-list "Self Addresses" p 'sirmail:self-addresses check-simple-user-address)
(make-boolean "Enable compose-with-Emacs" p 'sirmail:use-extenal-composer?)
p))
(define (make-mbox-preferences-panel parent)
(let ([p (instantiate vertical-panel% (parent)
(alignment '(left center)))])
(make-text-field "Username" p 10 'sirmail:username #f check-id (lambda (x) x) (lambda (x) x))
(let ([sp (instantiate group-box-panel% ("IMAP Server" p)
[alignment '(left center)])]
[cert #f])
(make-text-field "Server" sp 20 'sirmail:imap-server #f check-host-address/port (lambda (x) x) (lambda (x) x))
(make-boolean "Encrypt connection using SSL" sp 'sirmail:use-ssl?
(lambda (on?) (send cert enable on?)))
(set! cert (make-file/directory-button #f #f sp
'sirmail:server-certificate
"Verify SSL with certificates"))
(make-text-field "Archive folder" sp 20 'sirmail:archive-mailbox-folder #t void (lambda (x) x) (lambda (x) x))
(make-text-field "Trash folder" sp 20 'sirmail:trash-mailbox-folder #t void (lambda (x) x) (lambda (x) x))
(make-text-field "Folder list root" sp 20 'sirmail:root-mailbox-folder #t void (lambda (x) x) (lambda (x) x))
(send cert enable (preferences:get 'sirmail:use-ssl?)))
(make-file/directory-button #t "Local directory" p
'sirmail:local-directory
#f)
(make-text-field "Check mail every" p 5 'sirmail:biff-delay #t check-biff-delay number->string string->number
"seconds")
(make-text-field "Verify download of messages larger than" p 10
'sirmail:warn-download-size #t
check-message-size number->string string->number
"bytes")
(make-file/directory-button #f #f p
'sirmail:auto-file-table-file
"Auto-file table file")
(make-boolean "Show GC icon" p 'sirmail:show-gc-icon)
(make-boolean "Always happy to get mail" p 'sirmail:always-happy)
(make-text-list "Shown Header Fields" p 'sirmail:fields-to-show void)
p))
(in-preferences-eventspace
(lambda ()
(preferences:add-panel "Reading" make-mbox-preferences-panel)
(preferences:add-panel "Sending" make-addresses-preferences-panel)
(preferences:add-editor-checkbox-panel)
(preferences:add-can-close-dialog-callback check-unsaved-pref?))))
| null | https://raw.githubusercontent.com/mflatt/sirmail/5a08636d126ea04b5c903ab42a6e7eb2b143d864/sirmail/pref.rkt | racket | IMPORTANT! All preferences operations outside this
file should go through the following exports.
DO NOT use preferences:... elsewhere.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Preference Definitions ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
useful only for tests or demos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Assume all raised values are exns
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
make-text-field : string panel number symbol boolean
((union #f string) (union #f top-level-window<%>) string -> boolean)
(any -> string)
(string -> any)
[ (union #f string) ]
-> void
sets up a text field for a preference
a string is provided, then a top-level-window<%> is also provded, and
the checking function should tell the user why the field-value string
is bad if it is bad.
and the preferences's actual Scheme value.
remove all need-check registrations, if any:
For now, just counteract edits:
check-biff-delay : (union #f string) (union #f parent) string -> boolean
checks to see if the string in the biff delay field makes
check-message-size : (union #f string) (union #f parent) string -> boolean
checks to see if the string in the download-max-size field makes
sense as an exact positive integer | (module pref mzscheme
(require mzlib/class
framework
mred
mzlib/list
mzlib/string
mzlib/etc
net/head)
(provide get-pref put-pref
show-pref-dialog
add-preferences-menu-items)
(define (string-or-false? x) (or (not x) (string? x)))
(define (ip-string? x) (and (string? x)
(positive? (string-length x))))
(define (abs-path-or-false? x)
(or (not x)
(and (path? x) (absolute-path? x))))
(define (un/marshall-path pref)
(preferences:set-un/marshall pref
(lambda (x)
(if (path? x)
(path->bytes x)
x))
(lambda (x)
(cond
[(bytes? x) (bytes->path x) ]
[(not x) x]
[else 'badvalue]))))
(preferences:set-default 'sirmail:mail-from "SirMail User <>" string?)
(preferences:set-default 'sirmail:username "username" string?)
(preferences:set-default 'sirmail:password #f string-or-false?)
(preferences:set-default 'sirmail:default-to-domain "racket-lang.org" ip-string?)
(preferences:set-default 'sirmail:imap-server "imap.racket-lang.org" ip-string?)
(preferences:set-default 'sirmail:use-ssl? #f boolean?)
(preferences:set-default 'sirmail:server-certificate #f abs-path-or-false?)
(preferences:set-default 'sirmail:smtp-server "sendmail.racket-lang.org" ip-string?)
(preferences:set-default 'sirmail:local-directory
(build-path (find-system-path 'home-dir)
"SirMail")
(lambda (x)
(and (path? x)
(absolute-path? x))))
(un/marshall-path 'sirmail:local-directory)
(preferences:set-default 'sirmail:sent-directory
(build-path (find-system-path 'home-dir)
"SentMail")
(lambda (x)
(or (not x)
(and (path? x)
(absolute-path? x)))))
(un/marshall-path 'sirmail:sent-directory)
(preferences:set-default 'sirmail:root-mailbox-folder #f string-or-false?)
(preferences:set-default 'sirmail:archive-mailbox-folder #f string-or-false?)
(preferences:set-default 'sirmail:trash-mailbox-folder "INBOX.Trash" string-or-false?)
(preferences:set-default 'sirmail:initial-sort 'id
(lambda (x) (memq x '(id date subject from))))
(preferences:set-default 'sirmail:biff-delay
60
(lambda (x)
(or (not x)
(and (number? x)
(exact? x)
(integer? x)
(positive? x)))))
(preferences:set-default 'sirmail:warn-download-size 32000
(lambda (x) (or (not x) (and (number? x) (real? x)))))
(preferences:set-default 'sirmail:external-composer 'xemacs
(lambda (x) (memq x '(xemacs gnu-emacs))))
(preferences:set-default 'sirmail:use-extenal-composer? #f boolean?)
(preferences:set-default 'sirmail:show-urls? #t boolean?)
(preferences:set-default 'sirmail:show-gc-icon #f boolean?)
(preferences:set-default 'sirmail:show-memory-use? #t boolean?)
(preferences:set-default 'sirmail:always-happy #f boolean?)
(preferences:set-default 'sirmail:wrap-lines #f boolean?)
(preferences:set-default 'sirmail:prefer-text #t boolean?)
(preferences:set-default 'sirmail:show-html-images? #f boolean?)
(preferences:set-default 'sirmail:aliases-file
(build-path (find-system-path 'home-dir) ".sirmail.aliases")
abs-path-or-false?)
(un/marshall-path 'sirmail:aliases-file)
(preferences:set-default 'sirmail:auto-file-table-file (build-path (find-system-path 'home-dir) ".sirmail.auto-file")
abs-path-or-false?)
(un/marshall-path 'sirmail:auto-file-table-file)
(preferences:set-default 'sirmail:self-addresses null
(lambda (x) (and (list? x) (andmap string? x))))
(preferences:set-default 'sirmail:fields-to-show '("From" "To" "CC" "Subject" "Date" "X-Mailer" "X-Uptime")
(lambda (x) (and (list? x) (andmap string? x))))
(preferences:set-default 'sirmail:bcc #f
(λ (x) (or (not x) (string? x))))
(preferences:set-default 'sirmail:x-mailer-header #t boolean?)
(preferences:set-default 'sirmail:message-columns 80 exact-positive-integer?)
(preferences:set-default 'sirmail:mailbox-init-message 'last
(lambda (x) (or (eq? x 'first) (eq? x 'last))))
(preferences:set-default 'sirmail:folder-window-can-refresh? #t boolean?)
(let ([fw 560]
[fh 600])
(let-values ([(display-width display-height) (get-display-size)])
(preferences:set-default 'sirmail:frame-width
(min display-height fh)
(lambda (x) (and (number? x) (<= 0 x 32768))))
(preferences:set-default 'sirmail:frame-height
(min display-width fw)
(lambda (x) (and (number? x) (<= 0 x 32768))))))
(define (xywh-okay? n)
(and (number? n)
(<= 0 n 10000)))
(preferences:set-default 'sirmail:folder-window-w 200 xywh-okay?)
(preferences:set-default 'sirmail:folder-window-h 400 xywh-okay?)
(preferences:set-default 'sirmail:folder-window-x 0 xywh-okay?)
(preferences:set-default 'sirmail:folder-window-y 0 xywh-okay?)
(define prefs-eventspace (make-eventspace))
(define (in-preferences-eventspace thunk)
(let ([val #f]
[s (make-semaphore)])
(parameterize ([current-eventspace prefs-eventspace])
(queue-callback
(lambda ()
(with-handlers ([void (lambda (x)
(set! val x))])
(set! val (thunk)))
(semaphore-post s))))
(semaphore-wait s)
(if (exn? val)
(raise val)
val)))
(define (get-pref id)
(in-preferences-eventspace (lambda ()
(preferences:get id))))
(define (put-pref id val)
(in-preferences-eventspace (lambda ()
(preferences:set id val))))
(define (add-preferences-menu-items edit-menu)
(make-object separator-menu-item% edit-menu)
(make-object menu-item% "Preferences" edit-menu
(lambda (x y) (in-preferences-eventspace preferences:show-dialog))))
(define (show-pref-dialog)
(in-preferences-eventspace
(lambda ()
(preferences:show-dialog)
(yield 'wait))))
(define needs-check null)
(define (set-hilite e on?)
(send e change-style
(send (make-object style-delta%) set-delta-background (if on? "yellow" "white"))
0 (send e last-position)))
The 3rd - to - last argument checks the validity of the field content . If
the last two arguments convert between the string representation ( as shown in the text field )
(define make-text-field
(opt-lambda (label panel width-num pref optional? check-value val->str str->val [post-label #f])
(define p0 (and (or optional? post-label)
(instantiate horizontal-panel% (panel) [stretchable-height #f])))
(define e (and optional?
(make-object check-box% label p0
(lambda (c e)
(let ([on? (send c get-value)])
(send t enable on?)
(if on?
(t-cb t e)
(begin
(let loop ()
(let ([a (assq t needs-check)])
(when a
(set! needs-check (remq a needs-check))
(loop))))
(preferences:set pref #f))))))))
(define t-cb (lambda (t e)
(let* ([s (send t get-value)])
(if (check-value #f #f s)
(preferences:set pref (str->val s))
(begin
(set! needs-check (cons (list t label check-value) needs-check))
(set-hilite (send t get-editor) #t))))))
(define t (make-object text-field%
(if optional? #f label)
(or p0 panel)
t-cb
(make-string width-num #\X)))
(when post-label
(send t stretchable-width #f)
(make-object message% post-label p0))
(send t set-value (let ([v (preferences:get pref)])
(if v
(val->str v)
"")))
(when optional?
(send e set-value (preferences:get pref)))
(when e
(send t enable (send e get-value)))
(preferences:add-callback pref (lambda (name val)
(set-hilite (send t get-editor) #f)
(when e
(send e set-value val)
(send t enable val))
(when val
(let ([sval (val->str val)])
(unless (equal? sval (send t get-value))
(send t set-value sval))))))
(or p0 t)))
(define (check-unsaved-pref?)
(and (andmap (lambda (a)
((caddr a) (cadr a) (send (car a) get-top-level-window) (send (car a) get-value)))
needs-check)
(begin
(set! needs-check null)
#t)))
(define make-file/directory-button
(lambda (dir? button-label parent pref enabler)
(define p0 (and enabler
(instantiate horizontal-panel% (parent) [stretchable-height #f])))
(define e (and enabler
(make-object check-box% enabler p0
(lambda (c e)
(let ([on? (send c get-value)])
(send p enable on?)
(preferences:set
pref
(and on?
(string->path (send field get-value)))))))))
(define p (instantiate horizontal-panel% ((or p0 parent))
[stretchable-height #f]))
(define (set-it v)
(preferences:set pref v))
(define field (make-object text-field% button-label p
(lambda (t e)
(send field set-value (path->string (preferences:get pref))))
(path->string
(or (preferences:get pref)
(current-directory)))))
(when e
(send e set-value (preferences:get pref))
(send p enable (send e get-value)))
(preferences:add-callback pref (lambda (name val)
(when e
(send e set-value val)
(send p enable val))
(when val
(send field set-value (path->string val)))))
(make-object button% "Set..." p (lambda (b e)
(let ([v ((if dir? get-directory get-file)
(or enabler button-label))])
(when v
(set-it v)))))
p0))
(define make-boolean
(opt-lambda (label p pref [extra-action void])
(define c
(make-object check-box% label p (lambda (c e)
(let ([v (send c get-value)])
(extra-action v)
(preferences:set pref v)))))
(send c set-value (preferences:get pref))
(preferences:add-callback pref (lambda (name val)
(send c set-value val)))))
(define (is-host-address? s)
(regexp-match "^([-a-zA-Z0-9]+[.])*[-a-zA-Z0-9]+$" s))
(define (is-host-address+port? s)
(or (is-host-address? s)
(let ([m (regexp-match "^(.*):([0-9]+)$" s)])
(and m
(<= 1 (string->number (caddr m)) 65535)
(is-host-address? (cadr m))))))
(define (is-host-address+port+user? s)
(or (is-host-address+port? s)
(let ([m (regexp-match "^(?:[-+a-zA-Z0-9_.]+)@(.*)$" s)])
(and m
(is-host-address+port? (cadr m))))))
(define (is-host-address+port+user+type? s)
(or (is-host-address+port+user? s)
(let ([m (regexp-match "^(?:ssl|tls|tcp):(.*)$" s)])
(and m
(is-host-address+port+user? (cadr m))))))
(define (is-host-address+port+user+type-list? s)
(let ([l (regexp-split ", *" s)])
(andmap is-host-address+port+user+type? l)))
(define (check-address ok? who tl s port-ok? multi?)
(or (ok? s)
(begin
(when who
(message-box
"Preference Error"
(format (string-append
"The ~a value must be a~a host IP address~a~a~a.\n"
"An IP address is an string containing a combination of "
"period (.), dash (-), A-Z, a-Z, and 0-9. "
"Also the period cannot appear at the very beginning or end.\n"
"~a"
"You provided\n\n ~a\n\nwhich is not legal.")
who
(if multi? " comma-separated list of" "")
(if multi? " es" "")
(if (and multi? port-ok?) " each" "")
(if port-ok? " with an optional port number" "")
(if port-ok?
(string-append
"An optional port number is specified by adding a "
"colon (:) followed by a number between 1 and 65535.\n")
"")
s)
tl
'(ok stop)))
#f)))
(define (check-host-address who tl s)
(check-address is-host-address? who tl s #f #f))
(define (check-host-address/port who tl s)
(check-address is-host-address+port? who tl s #t #f))
(define (check-host-address/port/user/type/multi who tl s)
(check-address is-host-address+port+user+type-list? who tl s #t #t))
sense as an exact integer between 1 and 3600
(define (check-biff-delay who tl s)
(let ([n (string->number s)])
(or (and (number? n)
(integer? n)
(exact? n)
(<= 1 n 3600))
(begin
(when who
(message-box
"Preference Error"
(format (string-append
"The biff delay must be an exact integer between 1 and 3600.\n"
"You provided:\n"
" ~a")
s)
tl
'(ok stop)))
#f))))
(define (check-message-size who tl s)
(let ([n (string->number s)])
(or (and (number? n)
(integer? n)
(exact? n)
(positive? n))
(begin
(when who
(message-box
"Preference Error"
(format (string-append
"The message size must be an exact, positive integer.\n"
"You provided:\n"
" ~a")
s)
tl
'(ok stop)))
#f))))
(define (check-user-address who tl s)
(with-handlers ([exn:fail?
(lambda (x)
(when who
(message-box
"Preference Error"
(format "The ~a value you provided is not a legal mail address: ~a"
who s)
tl
'(ok stop)))
#f)])
(unless (= 1 (length (extract-addresses s 'all)))
(error "multiple addresses"))
#t))
(define (check-simple-user-address who tl s)
(and (check-user-address who tl s)
(car (extract-addresses s 'address))))
(define (check-id who tl s) #t)
(define (make-text-list label parent pref check-item)
(let ([p (make-object group-box-panel% label parent)])
(define l (make-object list-box% #f (or (preferences:get pref) null) p
(lambda (l e)
(send delete enable (pair? (send l get-selections))))
'(multiple)))
(define hp (instantiate horizontal-panel% (p)
[stretchable-height #f]
[alignment '(center center)]))
(define add (make-object button% "Add" hp (lambda (b e)
(let loop ([init ""])
(let ([v (get-text-from-user (format "Add to ~a" label)
(format "Add to ~a" label)
(send parent get-top-level-window)
init)])
(when v
(let ([revised (check-item (format "item for ~a" label)
(send b get-top-level-window) v)])
(if revised
(begin
(send l append (if (string? revised) revised v))
(set-prefs))
(loop v)))))))))
(define delete (make-object button% "Delete" hp (lambda (b e)
(let ([d (send l get-selections)])
(for-each (lambda (i)
(send l delete i))
(sort d >))
(set-prefs)))))
(define (set-prefs)
(send delete enable (pair? (send l get-selections)))
(preferences:set
pref
(let ([n (send l get-number)])
(let loop ([i 0])
(if (= i n)
null
(cons (send l get-string i)
(loop (add1 i))))))))
(send delete enable #f)
(preferences:add-callback pref (lambda (name val)
(send l clear)
(for-each (lambda (i)
(send l append i))
val)
(send delete enable (pair? (send l get-selections)))))))
(define (make-addresses-preferences-panel parent)
(let ([p (instantiate vertical-panel% (parent))])
(make-text-field "Mail From" p 20 'sirmail:mail-from #f check-user-address (lambda (x) x) (lambda (x) x))
(make-text-field "SMTP Server" p 20 'sirmail:smtp-server #f check-host-address/port/user/type/multi
(lambda (x) x) (lambda (x) x))
(make-file/directory-button #t #f p
'sirmail:sent-directory
"Save Sent Files")
(make-text-field "Default \"To\" domain" p 20 'sirmail:default-to-domain #f check-host-address (lambda (x) x) (lambda (x) x))
(make-text-field "BCC line" p 20 'sirmail:bcc #t void (lambda (x) x) (lambda (x) x))
(make-file/directory-button #f #f p
'sirmail:aliases-file
"Aliases File")
(make-text-list "Self Addresses" p 'sirmail:self-addresses check-simple-user-address)
(make-boolean "Enable compose-with-Emacs" p 'sirmail:use-extenal-composer?)
p))
(define (make-mbox-preferences-panel parent)
(let ([p (instantiate vertical-panel% (parent)
(alignment '(left center)))])
(make-text-field "Username" p 10 'sirmail:username #f check-id (lambda (x) x) (lambda (x) x))
(let ([sp (instantiate group-box-panel% ("IMAP Server" p)
[alignment '(left center)])]
[cert #f])
(make-text-field "Server" sp 20 'sirmail:imap-server #f check-host-address/port (lambda (x) x) (lambda (x) x))
(make-boolean "Encrypt connection using SSL" sp 'sirmail:use-ssl?
(lambda (on?) (send cert enable on?)))
(set! cert (make-file/directory-button #f #f sp
'sirmail:server-certificate
"Verify SSL with certificates"))
(make-text-field "Archive folder" sp 20 'sirmail:archive-mailbox-folder #t void (lambda (x) x) (lambda (x) x))
(make-text-field "Trash folder" sp 20 'sirmail:trash-mailbox-folder #t void (lambda (x) x) (lambda (x) x))
(make-text-field "Folder list root" sp 20 'sirmail:root-mailbox-folder #t void (lambda (x) x) (lambda (x) x))
(send cert enable (preferences:get 'sirmail:use-ssl?)))
(make-file/directory-button #t "Local directory" p
'sirmail:local-directory
#f)
(make-text-field "Check mail every" p 5 'sirmail:biff-delay #t check-biff-delay number->string string->number
"seconds")
(make-text-field "Verify download of messages larger than" p 10
'sirmail:warn-download-size #t
check-message-size number->string string->number
"bytes")
(make-file/directory-button #f #f p
'sirmail:auto-file-table-file
"Auto-file table file")
(make-boolean "Show GC icon" p 'sirmail:show-gc-icon)
(make-boolean "Always happy to get mail" p 'sirmail:always-happy)
(make-text-list "Shown Header Fields" p 'sirmail:fields-to-show void)
p))
(in-preferences-eventspace
(lambda ()
(preferences:add-panel "Reading" make-mbox-preferences-panel)
(preferences:add-panel "Sending" make-addresses-preferences-panel)
(preferences:add-editor-checkbox-panel)
(preferences:add-can-close-dialog-callback check-unsaved-pref?))))
|
1da16886f96726dccca9b4fe5619ac4c48ed44cd1332f5d4a19a218b2a1c1654 | clojure-interop/java-jdk | MultiScrollBarUI.clj | (ns javax.swing.plaf.multi.MultiScrollBarUI
"A multiplexing UI used to combine ScrollBarUIs.
This file was automatically generated by AutoMulti."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.plaf.multi MultiScrollBarUI]))
(defn ->multi-scroll-bar-ui
"Constructor."
(^MultiScrollBarUI []
(new MultiScrollBarUI )))
(defn *create-ui
"Returns a multiplexing UI instance if any of the auxiliary
LookAndFeels supports this UI. Otherwise, just returns the
UI object obtained from the default LookAndFeel.
a - `javax.swing.JComponent`
returns: `javax.swing.plaf.ComponentUI`"
(^javax.swing.plaf.ComponentUI [^javax.swing.JComponent a]
(MultiScrollBarUI/createUI a)))
(defn install-ui
"Invokes the installUI method on each UI handled by this object.
a - the component where this UI delegate is being installed - `javax.swing.JComponent`"
([^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.installUI a))))
(defn get-minimum-size
"Invokes the getMinimumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getMinimumSize a))))
(defn get-maximum-size
"Invokes the getMaximumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getMaximumSize a))))
(defn get-accessible-child
"Invokes the getAccessibleChild method on each UI handled by this object.
a - `javax.swing.JComponent`
b - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `javax.accessibility.Accessible`"
(^javax.accessibility.Accessible [^MultiScrollBarUI this ^javax.swing.JComponent a ^Integer b]
(-> this (.getAccessibleChild a b))))
(defn get-u-is
"Returns the list of UIs associated with this multiplexing UI. This
allows processing of the UIs by an application aware of multiplexing
UIs on components.
returns: `javax.swing.plaf.ComponentUI[]`"
([^MultiScrollBarUI this]
(-> this (.getUIs))))
(defn uninstall-ui
"Invokes the uninstallUI method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.uninstallUI a))))
(defn contains
"Invokes the contains method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
b - the x coordinate of the point - `int`
c - the y coordinate of the point - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `boolean`"
(^Boolean [^MultiScrollBarUI this ^javax.swing.JComponent a ^Integer b ^Integer c]
(-> this (.contains a b c))))
(defn update
"Invokes the update method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiScrollBarUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.update a b))))
(defn get-accessible-children-count
"Invokes the getAccessibleChildrenCount method on each UI handled by this object.
a - `javax.swing.JComponent`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `int`"
(^Integer [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getAccessibleChildrenCount a))))
(defn paint
"Invokes the paint method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiScrollBarUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.paint a b))))
(defn get-preferred-size
"Invokes the getPreferredSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getPreferredSize a))))
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/plaf/multi/MultiScrollBarUI.clj | clojure | (ns javax.swing.plaf.multi.MultiScrollBarUI
"A multiplexing UI used to combine ScrollBarUIs.
This file was automatically generated by AutoMulti."
(:refer-clojure :only [require comment defn ->])
(:import [javax.swing.plaf.multi MultiScrollBarUI]))
(defn ->multi-scroll-bar-ui
"Constructor."
(^MultiScrollBarUI []
(new MultiScrollBarUI )))
(defn *create-ui
"Returns a multiplexing UI instance if any of the auxiliary
LookAndFeels supports this UI. Otherwise, just returns the
UI object obtained from the default LookAndFeel.
a - `javax.swing.JComponent`
returns: `javax.swing.plaf.ComponentUI`"
(^javax.swing.plaf.ComponentUI [^javax.swing.JComponent a]
(MultiScrollBarUI/createUI a)))
(defn install-ui
"Invokes the installUI method on each UI handled by this object.
a - the component where this UI delegate is being installed - `javax.swing.JComponent`"
([^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.installUI a))))
(defn get-minimum-size
"Invokes the getMinimumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getMinimumSize a))))
(defn get-maximum-size
"Invokes the getMaximumSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getMaximumSize a))))
(defn get-accessible-child
"Invokes the getAccessibleChild method on each UI handled by this object.
a - `javax.swing.JComponent`
b - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `javax.accessibility.Accessible`"
(^javax.accessibility.Accessible [^MultiScrollBarUI this ^javax.swing.JComponent a ^Integer b]
(-> this (.getAccessibleChild a b))))
(defn get-u-is
"Returns the list of UIs associated with this multiplexing UI. This
allows processing of the UIs by an application aware of multiplexing
UIs on components.
returns: `javax.swing.plaf.ComponentUI[]`"
([^MultiScrollBarUI this]
(-> this (.getUIs))))
(defn uninstall-ui
"Invokes the uninstallUI method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.uninstallUI a))))
(defn contains
"Invokes the contains method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
b - the x coordinate of the point - `int`
c - the y coordinate of the point - `int`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `boolean`"
(^Boolean [^MultiScrollBarUI this ^javax.swing.JComponent a ^Integer b ^Integer c]
(-> this (.contains a b c))))
(defn update
"Invokes the update method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiScrollBarUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.update a b))))
(defn get-accessible-children-count
"Invokes the getAccessibleChildrenCount method on each UI handled by this object.
a - `javax.swing.JComponent`
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `int`"
(^Integer [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getAccessibleChildrenCount a))))
(defn paint
"Invokes the paint method on each UI handled by this object.
a - the Graphics context in which to paint - `java.awt.Graphics`
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` "
([^MultiScrollBarUI this ^java.awt.Graphics a ^javax.swing.JComponent b]
(-> this (.paint a b))))
(defn get-preferred-size
"Invokes the getPreferredSize method on each UI handled by this object.
this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . JComponent `
returns: the value obtained from the first UI, which is
the UI obtained from the default LookAndFeel - `java.awt.Dimension`"
(^java.awt.Dimension [^MultiScrollBarUI this ^javax.swing.JComponent a]
(-> this (.getPreferredSize a))))
| |
6d508c9eaa0ce471e4bd0ddbe0aa7bee3ce31953985f3e3521a52b5e895a9134 | haskell/vector | sum-ratio.hs | import qualified Data.Vector as U
import Data.Ratio
main = print . U.sum $ U.replicate (100000000 :: Int) (1 % 2 :: Rational)
| null | https://raw.githubusercontent.com/haskell/vector/4c87e88f07aad166c6ae2ccb94fa539fbdd99a91/old-testsuite/microsuite/sum-ratio.hs | haskell | import qualified Data.Vector as U
import Data.Ratio
main = print . U.sum $ U.replicate (100000000 :: Int) (1 % 2 :: Rational)
| |
295f1182ad44a04e2ef794381620047d73bb3a14c4149417df64034493545751 | S8A/htdp-exercises | ex187.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-abbr-reader.ss" "lang")((modname ex187) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
(define-struct gp [name score])
A GamePlayer is a structure :
; (make-gp String Number)
interpretation ( make - gp p s ) represents player who
; scored a maximum of s points
(define pa3 (make-gp "a" 3))
(define pb2 (make-gp "b" 2))
(define pc1 (make-gp "c" 1))
(define pd12 (make-gp "d" 12))
(define pe20 (make-gp "e" 20))
(define pf5 (make-gp "f" 5))
(define pg6 (make-gp "g" 6))
(define ph4 (make-gp "h" 4))
A ListOfGamePlayers ( LGP ) is one of :
; - '()
- ( cons GamePlayer LGP )
LGP - > LGP
; sorts a list of game players by their score in descending order
(define (sort-players> lgp)
(cond
[(empty? lgp) '()]
[else
(insert (first lgp) (sort-players> (rest lgp)))]))
(check-expect (sort-players> (list pa3 pb2 pc1))
(list pa3 pb2 pc1))
(check-expect (sort-players> (list pc1 pb2 pa3))
(list pa3 pb2 pc1))
(check-expect (sort-players> (list pd12 pe20 pf5))
(list pe20 pd12 pf5))
GamePlayer LGP - > LGP
; inserts player p into the sorted list of players
(define (insert p lgp)
(cond
[(empty? lgp) (list p)]
[else
(if (gp-score>= p (first lgp))
(cons p lgp)
(cons (first lgp) (insert p (rest lgp))))]))
(check-expect (insert pf5 '()) (list pf5))
(check-expect (insert pf5 (list pg6)) (list pg6 pf5))
(check-expect (insert pf5 (list ph4)) (list pf5 ph4))
(check-expect (insert pd12 (list pe20 pf5))
(list pe20 pd12 pf5))
GamePlayer GamePlayer - > Boolean
; is player A's score greater than or equal to player B's
(define (gp-score>= a b)
(>= (gp-score a) (gp-score b)))
(check-expect (gp-score>= pf5 pg6) #false)
(check-expect (gp-score>= pe20 pd12) #true)
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex187.rkt | racket | about the language level of this file in a form that our tools can easily process.
(make-gp String Number)
scored a maximum of s points
- '()
sorts a list of game players by their score in descending order
inserts player p into the sorted list of players
is player A's score greater than or equal to player B's | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex187) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f)))
(define-struct gp [name score])
A GamePlayer is a structure :
interpretation ( make - gp p s ) represents player who
(define pa3 (make-gp "a" 3))
(define pb2 (make-gp "b" 2))
(define pc1 (make-gp "c" 1))
(define pd12 (make-gp "d" 12))
(define pe20 (make-gp "e" 20))
(define pf5 (make-gp "f" 5))
(define pg6 (make-gp "g" 6))
(define ph4 (make-gp "h" 4))
A ListOfGamePlayers ( LGP ) is one of :
- ( cons GamePlayer LGP )
LGP - > LGP
(define (sort-players> lgp)
(cond
[(empty? lgp) '()]
[else
(insert (first lgp) (sort-players> (rest lgp)))]))
(check-expect (sort-players> (list pa3 pb2 pc1))
(list pa3 pb2 pc1))
(check-expect (sort-players> (list pc1 pb2 pa3))
(list pa3 pb2 pc1))
(check-expect (sort-players> (list pd12 pe20 pf5))
(list pe20 pd12 pf5))
GamePlayer LGP - > LGP
(define (insert p lgp)
(cond
[(empty? lgp) (list p)]
[else
(if (gp-score>= p (first lgp))
(cons p lgp)
(cons (first lgp) (insert p (rest lgp))))]))
(check-expect (insert pf5 '()) (list pf5))
(check-expect (insert pf5 (list pg6)) (list pg6 pf5))
(check-expect (insert pf5 (list ph4)) (list pf5 ph4))
(check-expect (insert pd12 (list pe20 pf5))
(list pe20 pd12 pf5))
GamePlayer GamePlayer - > Boolean
(define (gp-score>= a b)
(>= (gp-score a) (gp-score b)))
(check-expect (gp-score>= pf5 pg6) #false)
(check-expect (gp-score>= pe20 pd12) #true)
|
43823b7c566ecd48188172db548ae18616a0f241d059e0a9937fcc56cceeb072 | hammerlab/biokepi | hisat.ml | open Biokepi_run_environment
open Common
module Remove = Workflow_utilities.Remove
module Configuration = struct
type t = {
name : string;
version : [`V_0_1_6_beta | `V_2_0_2_beta];
}
let to_json {name; version}: Yojson.Basic.json =
`Assoc [
"name", `String name;
"version",
(match version with
|`V_0_1_6_beta -> `String "V_0_1_6_beta"
|`V_2_0_2_beta -> `String "V_2_0_2_beta");
]
let default_v1 = {name = "default_v1"; version = `V_0_1_6_beta}
let default_v2 = {name = "default_v2"; version = `V_2_0_2_beta}
let get_tool t =
let open Machine.Tool.Default in
match t.version with
|`V_0_1_6_beta -> hisat
|`V_2_0_2_beta -> hisat2
let name t = t.name
end
let index
~reference_build
~index_prefix
~configuration
~(run_with : Machine.t) =
let open KEDSL in
let reference_fasta =
Machine.get_reference_genome run_with reference_build
|> Reference_genome.fasta in
let result_dir = Filename.dirname index_prefix in
let version = configuration.Configuration.version in
let hisat_tool =
Machine.get_tool run_with (Configuration.get_tool configuration) in
let build_binary =
match version with
| `V_0_1_6_beta -> "hisat-build"
| `V_2_0_2_beta -> "hisat2-build"
in
let name =
sprintf "%s-%s" build_binary (Filename.basename reference_fasta#product#path) in
let first_index_file =
match version with
| `V_0_1_6_beta -> sprintf "%s.1.bt2" index_prefix
| `V_2_0_2_beta -> sprintf "%s.1.ht2" index_prefix
in
workflow_node ~name
(single_file ~host:(Machine.(as_host run_with)) first_index_file)
~edges:[
on_failure_activate (Remove.directory ~run_with result_dir);
depends_on reference_fasta;
depends_on Machine.Tool.(ensure hisat_tool);
]
~tags:[Target_tags.aligner]
~make:(Machine.run_big_program run_with ~name
~self_ids:["hisat"; "index"]
Program.(
Machine.Tool.(init hisat_tool)
&& shf "mkdir %s" result_dir
&& shf "%s %s %s"
build_binary
reference_fasta#product#path
index_prefix
))
let align
~reference_build
~configuration
~fastq
~(result_prefix:string)
~(run_with : Machine.t)
() =
let open KEDSL in
let reference_fasta =
Machine.get_reference_genome run_with reference_build
|> Reference_genome.fasta in
let reference_dir = (Filename.dirname reference_fasta#product#path) in
let version = configuration.Configuration.version in
let hisat_binary =
match version with
| `V_0_1_6_beta -> "hisat"
| `V_2_0_2_beta -> "hisat2"
in
let index_dir = sprintf "%s/%s-index/" reference_dir hisat_binary in
let index_prefix = index_dir // (sprintf "%s-index" hisat_binary) in
let in_work_dir =
Program.shf "cd %s" Filename.(quote (dirname result_prefix)) in
let hisat_tool =
Machine.get_tool run_with (Configuration.get_tool configuration) in
let hisat_index = index ~index_prefix ~reference_build ~run_with ~configuration in
let result = sprintf "%s.sam" result_prefix in
let r1_path, r2_path_opt = fastq#product#paths in
let name = sprintf "%s-rna-align-%s" hisat_binary (Filename.basename r1_path) in
let processors = Machine.max_processors run_with in
let hisat_base_command = sprintf
"%s \
-p %d \
-x %s \
-S %s"
hisat_binary
processors
(Filename.quote index_prefix)
(Filename.quote result)
in
let base_hisat_target ~hisat_command =
workflow_node ~name
(single_file
~host:(Machine.(as_host run_with))
result)
~edges:[
on_failure_activate (Remove.file ~run_with result);
depends_on reference_fasta;
depends_on hisat_index;
depends_on fastq;
depends_on Machine.Tool.(ensure hisat_tool);
]
~tags:[Target_tags.aligner]
~make:(Machine.run_big_program run_with ~processors ~name
~self_ids:["hisat"; "align"]
Program.(
Machine.Tool.(init hisat_tool)
&& in_work_dir
&& sh hisat_command
))
in
match r2_path_opt with
| Some read2 ->
let hisat_command =
String.concat ~sep:" " [
hisat_base_command;
"-1"; (Filename.quote r1_path);
"-2"; (Filename.quote read2);
] in
base_hisat_target ~hisat_command
| None ->
let hisat_command = String.concat ~sep:" " [
hisat_base_command;
"-U"; (Filename.quote r1_path);
] in
base_hisat_target ~hisat_command
| null | https://raw.githubusercontent.com/hammerlab/biokepi/d64eb2c891b41bda3444445cd2adf4e3251725d4/src/bfx_tools/hisat.ml | ocaml | open Biokepi_run_environment
open Common
module Remove = Workflow_utilities.Remove
module Configuration = struct
type t = {
name : string;
version : [`V_0_1_6_beta | `V_2_0_2_beta];
}
let to_json {name; version}: Yojson.Basic.json =
`Assoc [
"name", `String name;
"version",
(match version with
|`V_0_1_6_beta -> `String "V_0_1_6_beta"
|`V_2_0_2_beta -> `String "V_2_0_2_beta");
]
let default_v1 = {name = "default_v1"; version = `V_0_1_6_beta}
let default_v2 = {name = "default_v2"; version = `V_2_0_2_beta}
let get_tool t =
let open Machine.Tool.Default in
match t.version with
|`V_0_1_6_beta -> hisat
|`V_2_0_2_beta -> hisat2
let name t = t.name
end
let index
~reference_build
~index_prefix
~configuration
~(run_with : Machine.t) =
let open KEDSL in
let reference_fasta =
Machine.get_reference_genome run_with reference_build
|> Reference_genome.fasta in
let result_dir = Filename.dirname index_prefix in
let version = configuration.Configuration.version in
let hisat_tool =
Machine.get_tool run_with (Configuration.get_tool configuration) in
let build_binary =
match version with
| `V_0_1_6_beta -> "hisat-build"
| `V_2_0_2_beta -> "hisat2-build"
in
let name =
sprintf "%s-%s" build_binary (Filename.basename reference_fasta#product#path) in
let first_index_file =
match version with
| `V_0_1_6_beta -> sprintf "%s.1.bt2" index_prefix
| `V_2_0_2_beta -> sprintf "%s.1.ht2" index_prefix
in
workflow_node ~name
(single_file ~host:(Machine.(as_host run_with)) first_index_file)
~edges:[
on_failure_activate (Remove.directory ~run_with result_dir);
depends_on reference_fasta;
depends_on Machine.Tool.(ensure hisat_tool);
]
~tags:[Target_tags.aligner]
~make:(Machine.run_big_program run_with ~name
~self_ids:["hisat"; "index"]
Program.(
Machine.Tool.(init hisat_tool)
&& shf "mkdir %s" result_dir
&& shf "%s %s %s"
build_binary
reference_fasta#product#path
index_prefix
))
let align
~reference_build
~configuration
~fastq
~(result_prefix:string)
~(run_with : Machine.t)
() =
let open KEDSL in
let reference_fasta =
Machine.get_reference_genome run_with reference_build
|> Reference_genome.fasta in
let reference_dir = (Filename.dirname reference_fasta#product#path) in
let version = configuration.Configuration.version in
let hisat_binary =
match version with
| `V_0_1_6_beta -> "hisat"
| `V_2_0_2_beta -> "hisat2"
in
let index_dir = sprintf "%s/%s-index/" reference_dir hisat_binary in
let index_prefix = index_dir // (sprintf "%s-index" hisat_binary) in
let in_work_dir =
Program.shf "cd %s" Filename.(quote (dirname result_prefix)) in
let hisat_tool =
Machine.get_tool run_with (Configuration.get_tool configuration) in
let hisat_index = index ~index_prefix ~reference_build ~run_with ~configuration in
let result = sprintf "%s.sam" result_prefix in
let r1_path, r2_path_opt = fastq#product#paths in
let name = sprintf "%s-rna-align-%s" hisat_binary (Filename.basename r1_path) in
let processors = Machine.max_processors run_with in
let hisat_base_command = sprintf
"%s \
-p %d \
-x %s \
-S %s"
hisat_binary
processors
(Filename.quote index_prefix)
(Filename.quote result)
in
let base_hisat_target ~hisat_command =
workflow_node ~name
(single_file
~host:(Machine.(as_host run_with))
result)
~edges:[
on_failure_activate (Remove.file ~run_with result);
depends_on reference_fasta;
depends_on hisat_index;
depends_on fastq;
depends_on Machine.Tool.(ensure hisat_tool);
]
~tags:[Target_tags.aligner]
~make:(Machine.run_big_program run_with ~processors ~name
~self_ids:["hisat"; "align"]
Program.(
Machine.Tool.(init hisat_tool)
&& in_work_dir
&& sh hisat_command
))
in
match r2_path_opt with
| Some read2 ->
let hisat_command =
String.concat ~sep:" " [
hisat_base_command;
"-1"; (Filename.quote r1_path);
"-2"; (Filename.quote read2);
] in
base_hisat_target ~hisat_command
| None ->
let hisat_command = String.concat ~sep:" " [
hisat_base_command;
"-U"; (Filename.quote r1_path);
] in
base_hisat_target ~hisat_command
| |
e9600e620a4e940abb909517b982473cad6831a98210ca56c677ba66629128ad | DavidAlphaFox/RabbitMQ | crashing_queues.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(crashing_queues).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-include_lib("amqp_client/include/amqp_client.hrl").
-import(rabbit_test_util, [set_ha_policy/3, a2b/1]).
-import(rabbit_misc, [pget/2]).
crashing_unmirrored_with() -> [cluster_ab].
crashing_unmirrored([CfgA, CfgB]) ->
A = pget(node, CfgA),
ChA = pget(channel, CfgA),
ConnB = pget(connection, CfgB),
amqp_channel:call(ChA, #'confirm.select'{}),
test_queue_failure(A, ChA, ConnB, 1, 0,
#'queue.declare'{queue = <<"test">>, durable = true}),
test_queue_failure(A, ChA, ConnB, 0, 0,
#'queue.declare'{queue = <<"test">>, durable = false}),
ok.
crashing_mirrored_with() -> [cluster_ab, ha_policy_all].
crashing_mirrored([CfgA, CfgB]) ->
A = pget(node, CfgA),
ChA = pget(channel, CfgA),
ConnB = pget(connection, CfgB),
amqp_channel:call(ChA, #'confirm.select'{}),
test_queue_failure(A, ChA, ConnB, 2, 1,
#'queue.declare'{queue = <<"test">>, durable = true}),
test_queue_failure(A, ChA, ConnB, 2, 1,
#'queue.declare'{queue = <<"test">>, durable = false}),
ok.
test_queue_failure(Node, Ch, RaceConn, MsgCount, SlaveCount, Decl) ->
#'queue.declare_ok'{queue = QName} = amqp_channel:call(Ch, Decl),
publish(Ch, QName, transient),
publish(Ch, QName, durable),
Racer = spawn_declare_racer(RaceConn, Decl),
kill_queue(Node, QName),
assert_message_count(MsgCount, Ch, QName),
assert_slave_count(SlaveCount, Node, QName),
stop_declare_racer(Racer),
amqp_channel:call(Ch, #'queue.delete'{queue = QName}).
give_up_after_repeated_crashes_with() -> [cluster_ab].
give_up_after_repeated_crashes([CfgA, CfgB]) ->
A = pget(node, CfgA),
ChA = pget(channel, CfgA),
ChB = pget(channel, CfgB),
QName = <<"test">>,
amqp_channel:call(ChA, #'confirm.select'{}),
amqp_channel:call(ChA, #'queue.declare'{queue = QName,
durable = true}),
await_state(A, QName, running),
publish(ChA, QName, durable),
kill_queue_hard(A, QName),
{'EXIT', _} = (catch amqp_channel:call(
ChA, #'queue.declare'{queue = QName,
durable = true})),
await_state(A, QName, crashed),
amqp_channel:call(ChB, #'queue.delete'{queue = QName}),
amqp_channel:call(ChB, #'queue.declare'{queue = QName,
durable = true}),
await_state(A, QName, running),
%% Since it's convenient, also test absent queue status here.
rabbit_test_configs:stop_node(CfgB),
await_state(A, QName, down),
ok.
publish(Ch, QName, DelMode) ->
Publish = #'basic.publish'{exchange = <<>>, routing_key = QName},
Msg = #amqp_msg{props = #'P_basic'{delivery_mode = del_mode(DelMode)}},
amqp_channel:cast(Ch, Publish, Msg),
amqp_channel:wait_for_confirms(Ch).
del_mode(transient) -> 1;
del_mode(durable) -> 2.
spawn_declare_racer(Conn, Decl) ->
Self = self(),
spawn_link(fun() -> declare_racer_loop(Self, Conn, Decl) end).
stop_declare_racer(Pid) ->
Pid ! stop,
MRef = erlang:monitor(process, Pid),
receive
{'DOWN', MRef, process, Pid, _} -> ok
end.
declare_racer_loop(Parent, Conn, Decl) ->
receive
stop -> unlink(Parent)
after 0 ->
%% Catch here because we might happen to catch the queue
%% while it is in the middle of recovering and thus
%% explode with NOT_FOUND because crashed. Doesn't matter,
%% we are only in this loop to try to fool the recovery
%% code anyway.
try
case amqp_connection:open_channel(Conn) of
{ok, Ch} -> amqp_channel:call(Ch, Decl);
closing -> ok
end
catch
exit:_ ->
ok
end,
declare_racer_loop(Parent, Conn, Decl)
end.
await_state(Node, QName, State) ->
await_state(Node, QName, State, 30000).
await_state(Node, QName, State, Time) ->
case state(Node, QName) of
State ->
ok;
Other ->
case Time of
0 -> exit({timeout_awaiting_state, State, Other});
_ -> timer:sleep(100),
await_state(Node, QName, State, Time - 100)
end
end.
state(Node, QName) ->
V = <<"/">>,
Res = rabbit_misc:r(V, queue, QName),
[[{name, Res},
{state, State}]] =
rpc:call(Node, rabbit_amqqueue, info_all, [V, [name, state]]),
State.
kill_queue_hard(Node, QName) ->
case kill_queue(Node, QName) of
crashed -> ok;
_NewPid -> timer:sleep(100),
kill_queue_hard(Node, QName)
end.
kill_queue(Node, QName) ->
Pid1 = queue_pid(Node, QName),
exit(Pid1, boom),
await_new_pid(Node, QName, Pid1).
queue_pid(Node, QName) ->
#amqqueue{pid = QPid,
state = State} = lookup(Node, QName),
case State of
crashed -> case sup_child(Node, rabbit_amqqueue_sup_sup) of
{ok, _} -> QPid; %% restarting
{error, no_child} -> crashed %% given up
end;
_ -> QPid
end.
sup_child(Node, Sup) ->
case rpc:call(Node, supervisor2, which_children, [Sup]) of
[{_, Child, _, _}] -> {ok, Child};
[] -> {error, no_child};
{badrpc, {'EXIT', {noproc, _}}} -> {error, no_sup}
end.
lookup(Node, QName) ->
{ok, Q} = rpc:call(Node, rabbit_amqqueue, lookup,
[rabbit_misc:r(<<"/">>, queue, QName)]),
Q.
await_new_pid(Node, QName, OldPid) ->
case queue_pid(Node, QName) of
OldPid -> timer:sleep(10),
await_new_pid(Node, QName, OldPid);
New -> New
end.
assert_message_count(Count, Ch, QName) ->
#'queue.declare_ok'{message_count = Count} =
amqp_channel:call(Ch, #'queue.declare'{queue = QName,
passive = true}).
assert_slave_count(Count, Node, QName) ->
Q = lookup(Node, QName),
[{_, Pids}] = rpc:call(Node, rabbit_amqqueue, info, [Q, [slave_pids]]),
RealCount = case Pids of
'' -> 0;
_ -> length(Pids)
end,
case RealCount of
Count ->
ok;
_ when RealCount < Count ->
timer:sleep(10),
assert_slave_count(Count, Node, QName);
_ ->
exit({too_many_slaves, Count, RealCount})
end.
| null | https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/rabbitmq-test/test/src/crashing_queues.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.
Since it's convenient, also test absent queue status here.
Catch here because we might happen to catch the queue
while it is in the middle of recovering and thus
explode with NOT_FOUND because crashed. Doesn't matter,
we are only in this loop to try to fool the recovery
code anyway.
restarting
given up | 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(crashing_queues).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-include_lib("amqp_client/include/amqp_client.hrl").
-import(rabbit_test_util, [set_ha_policy/3, a2b/1]).
-import(rabbit_misc, [pget/2]).
crashing_unmirrored_with() -> [cluster_ab].
crashing_unmirrored([CfgA, CfgB]) ->
A = pget(node, CfgA),
ChA = pget(channel, CfgA),
ConnB = pget(connection, CfgB),
amqp_channel:call(ChA, #'confirm.select'{}),
test_queue_failure(A, ChA, ConnB, 1, 0,
#'queue.declare'{queue = <<"test">>, durable = true}),
test_queue_failure(A, ChA, ConnB, 0, 0,
#'queue.declare'{queue = <<"test">>, durable = false}),
ok.
crashing_mirrored_with() -> [cluster_ab, ha_policy_all].
crashing_mirrored([CfgA, CfgB]) ->
A = pget(node, CfgA),
ChA = pget(channel, CfgA),
ConnB = pget(connection, CfgB),
amqp_channel:call(ChA, #'confirm.select'{}),
test_queue_failure(A, ChA, ConnB, 2, 1,
#'queue.declare'{queue = <<"test">>, durable = true}),
test_queue_failure(A, ChA, ConnB, 2, 1,
#'queue.declare'{queue = <<"test">>, durable = false}),
ok.
test_queue_failure(Node, Ch, RaceConn, MsgCount, SlaveCount, Decl) ->
#'queue.declare_ok'{queue = QName} = amqp_channel:call(Ch, Decl),
publish(Ch, QName, transient),
publish(Ch, QName, durable),
Racer = spawn_declare_racer(RaceConn, Decl),
kill_queue(Node, QName),
assert_message_count(MsgCount, Ch, QName),
assert_slave_count(SlaveCount, Node, QName),
stop_declare_racer(Racer),
amqp_channel:call(Ch, #'queue.delete'{queue = QName}).
give_up_after_repeated_crashes_with() -> [cluster_ab].
give_up_after_repeated_crashes([CfgA, CfgB]) ->
A = pget(node, CfgA),
ChA = pget(channel, CfgA),
ChB = pget(channel, CfgB),
QName = <<"test">>,
amqp_channel:call(ChA, #'confirm.select'{}),
amqp_channel:call(ChA, #'queue.declare'{queue = QName,
durable = true}),
await_state(A, QName, running),
publish(ChA, QName, durable),
kill_queue_hard(A, QName),
{'EXIT', _} = (catch amqp_channel:call(
ChA, #'queue.declare'{queue = QName,
durable = true})),
await_state(A, QName, crashed),
amqp_channel:call(ChB, #'queue.delete'{queue = QName}),
amqp_channel:call(ChB, #'queue.declare'{queue = QName,
durable = true}),
await_state(A, QName, running),
rabbit_test_configs:stop_node(CfgB),
await_state(A, QName, down),
ok.
publish(Ch, QName, DelMode) ->
Publish = #'basic.publish'{exchange = <<>>, routing_key = QName},
Msg = #amqp_msg{props = #'P_basic'{delivery_mode = del_mode(DelMode)}},
amqp_channel:cast(Ch, Publish, Msg),
amqp_channel:wait_for_confirms(Ch).
del_mode(transient) -> 1;
del_mode(durable) -> 2.
spawn_declare_racer(Conn, Decl) ->
Self = self(),
spawn_link(fun() -> declare_racer_loop(Self, Conn, Decl) end).
stop_declare_racer(Pid) ->
Pid ! stop,
MRef = erlang:monitor(process, Pid),
receive
{'DOWN', MRef, process, Pid, _} -> ok
end.
declare_racer_loop(Parent, Conn, Decl) ->
receive
stop -> unlink(Parent)
after 0 ->
try
case amqp_connection:open_channel(Conn) of
{ok, Ch} -> amqp_channel:call(Ch, Decl);
closing -> ok
end
catch
exit:_ ->
ok
end,
declare_racer_loop(Parent, Conn, Decl)
end.
await_state(Node, QName, State) ->
await_state(Node, QName, State, 30000).
await_state(Node, QName, State, Time) ->
case state(Node, QName) of
State ->
ok;
Other ->
case Time of
0 -> exit({timeout_awaiting_state, State, Other});
_ -> timer:sleep(100),
await_state(Node, QName, State, Time - 100)
end
end.
state(Node, QName) ->
V = <<"/">>,
Res = rabbit_misc:r(V, queue, QName),
[[{name, Res},
{state, State}]] =
rpc:call(Node, rabbit_amqqueue, info_all, [V, [name, state]]),
State.
kill_queue_hard(Node, QName) ->
case kill_queue(Node, QName) of
crashed -> ok;
_NewPid -> timer:sleep(100),
kill_queue_hard(Node, QName)
end.
kill_queue(Node, QName) ->
Pid1 = queue_pid(Node, QName),
exit(Pid1, boom),
await_new_pid(Node, QName, Pid1).
queue_pid(Node, QName) ->
#amqqueue{pid = QPid,
state = State} = lookup(Node, QName),
case State of
crashed -> case sup_child(Node, rabbit_amqqueue_sup_sup) of
end;
_ -> QPid
end.
sup_child(Node, Sup) ->
case rpc:call(Node, supervisor2, which_children, [Sup]) of
[{_, Child, _, _}] -> {ok, Child};
[] -> {error, no_child};
{badrpc, {'EXIT', {noproc, _}}} -> {error, no_sup}
end.
lookup(Node, QName) ->
{ok, Q} = rpc:call(Node, rabbit_amqqueue, lookup,
[rabbit_misc:r(<<"/">>, queue, QName)]),
Q.
await_new_pid(Node, QName, OldPid) ->
case queue_pid(Node, QName) of
OldPid -> timer:sleep(10),
await_new_pid(Node, QName, OldPid);
New -> New
end.
assert_message_count(Count, Ch, QName) ->
#'queue.declare_ok'{message_count = Count} =
amqp_channel:call(Ch, #'queue.declare'{queue = QName,
passive = true}).
assert_slave_count(Count, Node, QName) ->
Q = lookup(Node, QName),
[{_, Pids}] = rpc:call(Node, rabbit_amqqueue, info, [Q, [slave_pids]]),
RealCount = case Pids of
'' -> 0;
_ -> length(Pids)
end,
case RealCount of
Count ->
ok;
_ when RealCount < Count ->
timer:sleep(10),
assert_slave_count(Count, Node, QName);
_ ->
exit({too_many_slaves, Count, RealCount})
end.
|
164dc0183402356ad0cc3617cf4a4cbbe9571fb00f62b895bc0e8798b26f1af5 | Leapsight/plum_db | plum_db_partitions_sup.erl | %% =============================================================================
%% plum_db_partitions_sup.erl -
%%
Copyright ( c ) 2017 - 2021 Leapsight . All rights reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%% =============================================================================
-module(plum_db_partitions_sup).
-behaviour(supervisor).
-export([get_db_info/1]).
-export([set_db_info/2]).
-export([start_link/0]).
-export([init/1]).
%% =============================================================================
%% API
%% =============================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
get_db_info(ServerRef) ->
ets:lookup_element(?MODULE, ServerRef, 2).
set_db_info(ServerRef, Data) ->
true = ets:insert(?MODULE, {ServerRef, Data}),
ok.
%% =============================================================================
%% SUPERVISOR CALLBACKS
%% =============================================================================
init([]) ->
RestartStrategy = {one_for_one, 5, 60},
Children = [
#{
id => plum_db_partition_sup:name(Id),
start => {
plum_db_partition_sup,
start_link,
[Id]
},
restart => permanent,
shutdown => infinity,
type => supervisor,
modules => [plum_db_partition_sup]
}
|| Id <- plum_db:partitions()
],
ok = setup_db_info_tab(),
{ok, {RestartStrategy, Children}}.
setup_db_info_tab() ->
EtsOpts = [
named_table,
public,
set,
{read_concurrency, true}
],
{ok, ?MODULE} = plum_db_table_owner:add(?MODULE, EtsOpts),
ok. | null | https://raw.githubusercontent.com/Leapsight/plum_db/76f4d5113ed26cce4b38ce504f6965a2bcda95ed/src/plum_db_partitions_sup.erl | erlang | =============================================================================
plum_db_partitions_sup.erl -
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.
=============================================================================
=============================================================================
API
=============================================================================
=============================================================================
SUPERVISOR CALLBACKS
============================================================================= | Copyright ( c ) 2017 - 2021 Leapsight . 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(plum_db_partitions_sup).
-behaviour(supervisor).
-export([get_db_info/1]).
-export([set_db_info/2]).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
get_db_info(ServerRef) ->
ets:lookup_element(?MODULE, ServerRef, 2).
set_db_info(ServerRef, Data) ->
true = ets:insert(?MODULE, {ServerRef, Data}),
ok.
init([]) ->
RestartStrategy = {one_for_one, 5, 60},
Children = [
#{
id => plum_db_partition_sup:name(Id),
start => {
plum_db_partition_sup,
start_link,
[Id]
},
restart => permanent,
shutdown => infinity,
type => supervisor,
modules => [plum_db_partition_sup]
}
|| Id <- plum_db:partitions()
],
ok = setup_db_info_tab(),
{ok, {RestartStrategy, Children}}.
setup_db_info_tab() ->
EtsOpts = [
named_table,
public,
set,
{read_concurrency, true}
],
{ok, ?MODULE} = plum_db_table_owner:add(?MODULE, EtsOpts),
ok. |
50cc25c57edfd6519629b061c1c794c5f0a56ead7c4c2c68d988122a64b86ed3 | onyx-platform/onyx | entry.clj | (ns onyx.log.entry)
(defn create-log-entry [kw args]
{:fn kw :args args})
| null | https://raw.githubusercontent.com/onyx-platform/onyx/74f9ae58cdbcfcb1163464595f1e6ae6444c9782/src/onyx/log/entry.clj | clojure | (ns onyx.log.entry)
(defn create-log-entry [kw args]
{:fn kw :args args})
| |
e29033bea3e98da7da95e2bad1768046c9a7fcc39e73bf2f56f5b98469cd6144 | OCamlPro/OCamlPro-OCaml-Branch | odoc_ast.ml | (***********************************************************************)
(* OCamldoc *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(** Analysis of implementation files. *)
open Misc
open Asttypes
open Types
open Typedtree
let print_DEBUG3 s = print_string s ; print_newline ();;
let print_DEBUG s = print_string s ; print_newline ();;
type typedtree = (Typedtree.structure * Typedtree.module_coercion)
module Name = Odoc_name
open Odoc_parameter
open Odoc_value
open Odoc_type
open Odoc_exception
open Odoc_class
open Odoc_module
open Odoc_types
(** This variable contains the regular expression representing a blank.*)
let blank = "[ \010\013\009\012']"
(** This variable contains the regular expression representing a blank but not a '\n'.*)
let simple_blank = "[ \013\009\012]"
* This module is used to search for structure items by name in a Typedtree.structure .
One function creates two hash tables , which can then be used to search for elements .
Class elements do not use tables .
One function creates two hash tables, which can then be used to search for elements.
Class elements do not use tables.
*)
module Typedtree_search =
struct
type ele =
| M of string
| MT of string
| T of string
| C of string
| CT of string
| E of string
| ER of string
| P of string
| IM of string
type tab = (ele, Typedtree.structure_item) Hashtbl.t
type tab_values = (Odoc_module.Name.t, Typedtree.pattern * Typedtree.expression) Hashtbl.t
let iter_val_pattern = function
| Typedtree.Tpat_any -> None
| Typedtree.Tpat_var name -> Some (Name.from_ident name)
| Typedtree.Tpat_tuple _ -> None (* A VOIR quand on traitera les tuples *)
| _ -> None
let add_to_hashes table table_values tt =
match tt with
| Typedtree.Tstr_module (ident, _) ->
Hashtbl.add table (M (Name.from_ident ident)) tt
| Typedtree.Tstr_recmodule mods ->
List.iter
(fun (ident,mod_expr) ->
Hashtbl.add table (M (Name.from_ident ident))
(Typedtree.Tstr_module (ident,mod_expr))
)
mods
| Typedtree.Tstr_modtype (ident, _) ->
Hashtbl.add table (MT (Name.from_ident ident)) tt
| Typedtree.Tstr_exception (ident, _) ->
Hashtbl.add table (E (Name.from_ident ident)) tt
| Typedtree.Tstr_exn_rebind (ident, _) ->
Hashtbl.add table (ER (Name.from_ident ident)) tt
| Typedtree.Tstr_type ident_type_decl_list ->
List.iter
(fun (id, e) ->
Hashtbl.add table (T (Name.from_ident id))
(Typedtree.Tstr_type [(id,e)]))
ident_type_decl_list
| Typedtree.Tstr_class info_list ->
List.iter
(fun ((id,_,_,_,_) as ci) ->
Hashtbl.add table (C (Name.from_ident id))
(Typedtree.Tstr_class [ci]))
info_list
| Typedtree.Tstr_cltype info_list ->
List.iter
(fun ((id,_) as ci) ->
Hashtbl.add table
(CT (Name.from_ident id))
(Typedtree.Tstr_cltype [ci]))
info_list
| Typedtree.Tstr_value (_, pat_exp_list) ->
List.iter
(fun (pat,exp) ->
match iter_val_pattern pat.Typedtree.pat_desc with
None -> ()
| Some n -> Hashtbl.add table_values n (pat,exp)
)
pat_exp_list
| Typedtree.Tstr_primitive (ident, _) ->
Hashtbl.add table (P (Name.from_ident ident)) tt
| Typedtree.Tstr_open _ -> ()
| Typedtree.Tstr_include _ -> ()
| Typedtree.Tstr_eval _ -> ()
let tables typedtree =
let t = Hashtbl.create 13 in
let t_values = Hashtbl.create 13 in
List.iter (add_to_hashes t t_values) typedtree;
(t, t_values)
let search_module table name =
match Hashtbl.find table (M name) with
(Typedtree.Tstr_module (_, module_expr)) -> module_expr
| _ -> assert false
let search_module_type table name =
match Hashtbl.find table (MT name) with
| (Typedtree.Tstr_modtype (_, module_type)) -> module_type
| _ -> assert false
let search_exception table name =
match Hashtbl.find table (E name) with
| (Typedtree.Tstr_exception (_, excep_decl)) -> excep_decl
| _ -> assert false
let search_exception_rebind table name =
match Hashtbl.find table (ER name) with
| (Typedtree.Tstr_exn_rebind (_, p)) -> p
| _ -> assert false
let search_type_declaration table name =
match Hashtbl.find table (T name) with
| (Typedtree.Tstr_type [(_,decl)]) -> decl
| _ -> assert false
let search_class_exp table name =
match Hashtbl.find table (C name) with
| (Typedtree.Tstr_class [(_,_,_,ce,_)]) ->
(
try
let type_decl = search_type_declaration table name in
(ce, type_decl.Types.type_params)
with
Not_found ->
(ce, [])
)
| _ -> assert false
let search_class_type_declaration table name =
match Hashtbl.find table (CT name) with
| (Typedtree.Tstr_cltype [(_,cltype_decl)]) -> cltype_decl
| _ -> assert false
let search_value table name = Hashtbl.find table name
let search_primitive table name =
match Hashtbl.find table (P name) with
Tstr_primitive (ident, val_desc) -> val_desc.Types.val_type
| _ -> assert false
let get_nth_inherit_class_expr cls n =
let rec iter cpt = function
| [] ->
raise Not_found
| Typedtree.Cf_inher (clexp, _, _) :: q ->
if n = cpt then clexp else iter (cpt+1) q
| _ :: q ->
iter cpt q
in
iter 0 cls.Typedtree.cl_field
let search_attribute_type cls name =
let rec iter = function
| [] ->
raise Not_found
| Typedtree.Cf_val (_, ident, Some exp, _) :: q
when Name.from_ident ident = name ->
exp.Typedtree.exp_type
| _ :: q ->
iter q
in
iter cls.Typedtree.cl_field
let class_sig_of_cltype_decl =
let rec iter = function
Types.Tcty_constr (_, _, cty) -> iter cty
| Types.Tcty_signature s -> s
| Types.Tcty_fun (_,_, cty) -> iter cty
in
fun ct_decl -> iter ct_decl.Types.clty_type
let search_virtual_attribute_type table ctname name =
let ct_decl = search_class_type_declaration table ctname in
let cls_sig = class_sig_of_cltype_decl ct_decl in
let (_,_,texp) = Types.Vars.find name cls_sig.cty_vars in
texp
let search_method_expression cls name =
let rec iter = function
| [] ->
raise Not_found
| Typedtree.Cf_meth (label, exp) :: q when label = name ->
exp
| _ :: q ->
iter q
in
iter cls.Typedtree.cl_field
end
module Analyser =
functor (My_ir : Odoc_sig.Info_retriever) ->
struct
module Sig = Odoc_sig.Analyser (My_ir)
(** This variable is used to load a file as a string and retrieve characters from it.*)
let file = Sig.file
(** The name of the analysed file. *)
let file_name = Sig.file_name
* This function takes two indexes ( start and end ) and return the string
corresponding to the indexes in the file global variable . The function
prepare_file must have been called to fill the file global variable .
corresponding to the indexes in the file global variable. The function
prepare_file must have been called to fill the file global variable.*)
let get_string_of_file = Sig.get_string_of_file
(** This function loads the given file in the file global variable.
and sets file_name.*)
let prepare_file = Sig.prepare_file
(** The function used to get the comments in a class. *)
let get_comments_in_class = Sig.get_comments_in_class
(** The function used to get the comments in a module. *)
let get_comments_in_module = Sig.get_comments_in_module
(** This function takes a parameter pattern and builds the
corresponding [parameter] structure. The f_desc function
is used to retrieve a parameter description, if any, from
a parameter name.
*)
let tt_param_info_from_pattern env f_desc pat =
let rec iter_pattern pat =
match pat.pat_desc with
Typedtree.Tpat_var ident ->
let name = Name.from_ident ident in
Simple_name { sn_name = name ;
sn_text = f_desc name ;
sn_type = Odoc_env.subst_type env pat.pat_type
}
| Typedtree.Tpat_alias (pat, _) ->
iter_pattern pat
| Typedtree.Tpat_tuple patlist ->
Tuple
(List.map iter_pattern patlist,
Odoc_env.subst_type env pat.pat_type)
| Typedtree.Tpat_construct (cons_desc, _) when
(* we give a name to the parameter only if it unit *)
(match cons_desc.cstr_res.desc with
Tconstr (p, _, _) ->
Path.same p Predef.path_unit
| _ ->
false)
->
(* a () argument, it never has description *)
Simple_name { sn_name = "()" ;
sn_text = None ;
sn_type = Odoc_env.subst_type env pat.pat_type
}
| _ ->
(* implicit pattern matching -> anonymous parameter *)
Simple_name { sn_name = "()" ;
sn_text = None ;
sn_type = Odoc_env.subst_type env pat.pat_type
}
in
iter_pattern pat
(** Analysis of the parameter of a function. Return a list of t_parameter created from
the (pattern, expression) structures encountered. *)
let rec tt_analyse_function_parameters env current_comment_opt pat_exp_list =
match pat_exp_list with
[] ->
(* This case means we have a 'function' without pattern, that's impossible *)
raise (Failure "tt_analyse_function_parameters: 'function' without pattern")
| (pattern_param, exp) :: second_ele :: q ->
(* implicit pattern matching -> anonymous parameter and no more parameter *)
(* A VOIR : le label ? *)
let parameter = Odoc_parameter.Tuple ([], Odoc_env.subst_type env pattern_param.pat_type) in
[ parameter ]
| (pattern_param, func_body) :: [] ->
let parameter =
tt_param_info_from_pattern
env
(Odoc_parameter.desc_from_info_opt current_comment_opt)
pattern_param
in
(* For optional parameters with a default value, a special treatment is required *)
(* we look if the name of the parameter we just add is "*opt*", which means
that there is a let param_name = ... in ... just right now *)
let (p, next_exp) =
match parameter with
Simple_name { sn_name = "*opt*" } ->
(
(
match func_body.exp_desc with
Typedtree.Texp_let (_, ({pat_desc = Typedtree.Tpat_var id } , exp) :: _, func_body2) ->
let name = Name.from_ident id in
let new_param = Simple_name
{ sn_name = name ;
sn_text = Odoc_parameter.desc_from_info_opt current_comment_opt name ;
sn_type = Odoc_env.subst_type env exp.exp_type
}
in
(new_param, func_body2)
| _ ->
print_DEBUG3 "Pas le bon filtre pour le parametre optionnel avec valeur par defaut.";
(parameter, func_body)
)
)
| _ ->
(parameter, func_body)
in
(* continue if the body is still a function *)
match next_exp.exp_desc with
Texp_function (pat_exp_list, _) ->
p :: (tt_analyse_function_parameters env current_comment_opt pat_exp_list)
| _ ->
(* something else ; no more parameter *)
[ p ]
(** Analysis of a Tstr_value from the typedtree. Create and return a list of [t_value].
@raise Failure if an error occurs.*)
let tt_analyse_value env current_module_name comment_opt loc pat_exp rec_flag =
let (pat, exp) = pat_exp in
match (pat.pat_desc, exp.exp_desc) with
(Typedtree.Tpat_var ident, Typedtree.Texp_function (pat_exp_list2, partial)) ->
(* a new function is defined *)
let name_pre = Name.from_ident ident in
let name = Name.parens_if_infix name_pre in
let complete_name = Name.concat current_module_name name in
(* create the value *)
let new_value = {
val_name = complete_name ;
val_info = comment_opt ;
val_type = Odoc_env.subst_type env pat.Typedtree.pat_type ;
val_recursive = rec_flag = Asttypes.Recursive ;
val_parameters = tt_analyse_function_parameters env comment_opt pat_exp_list2 ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
[ new_value ]
| (Typedtree.Tpat_var ident, _) ->
(* a new value is defined *)
let name_pre = Name.from_ident ident in
let name = Name.parens_if_infix name_pre in
let complete_name = Name.concat current_module_name name in
let new_value = {
val_name = complete_name ;
val_info = comment_opt ;
val_type = Odoc_env.subst_type env pat.Typedtree.pat_type ;
val_recursive = rec_flag = Asttypes.Recursive ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
[ new_value ]
| (Typedtree.Tpat_tuple lpat, _) ->
(* new identifiers are defined *)
(* A VOIR : by now we don't accept to have global variables defined in tuples *)
[]
| _ ->
(* something else, we don't care ? A VOIR *)
[]
(** This function takes a Typedtree.class_expr and returns a string which can stand for the class name.
The name can be "object ... end" if the class expression is not an ident or a class constraint or a class apply. *)
let rec tt_name_of_class_expr clexp =
(
match clexp . Typedtree.cl_desc with
Tclass_ident _ - > prerr_endline " Tclass_ident "
| Tclass_structure _ - > prerr_endline " Tclass_structure "
| Tclass_fun _ - > prerr_endline " Tclass_fun "
| Tclass_apply _ - > prerr_endline " Tclass_apply "
| Tclass_let _ - > prerr_endline " Tclass_let "
| Tclass_constraint _ - > prerr_endline " Tclass_constraint "
) ;
(
match clexp.Typedtree.cl_desc with
Tclass_ident _ -> prerr_endline "Tclass_ident"
| Tclass_structure _ -> prerr_endline "Tclass_structure"
| Tclass_fun _ -> prerr_endline "Tclass_fun"
| Tclass_apply _ -> prerr_endline "Tclass_apply"
| Tclass_let _ -> prerr_endline "Tclass_let"
| Tclass_constraint _ -> prerr_endline "Tclass_constraint"
);
*)
match clexp.Typedtree.cl_desc with
Typedtree.Tclass_ident p -> Name.from_path p
| Typedtree.Tclass_constraint (class_expr, _, _, _)
| Typedtree.Tclass_apply (class_expr, _) -> tt_name_of_class_expr class_expr
(*
| Typedtree.Tclass_fun (_, _, class_expr, _) -> tt_name_of_class_expr class_expr
| Typedtree.Tclass_let (_,_,_, class_expr) -> tt_name_of_class_expr class_expr
*)
| _ -> Odoc_messages.object_end
* Analysis of a method expression to get the method parameters .
@param first indicates if we 're analysing the method for
the first time ; in that case we must not keep the first parameter ,
which is " self- * " , the object itself .
@param first indicates if we're analysing the method for
the first time ; in that case we must not keep the first parameter,
which is "self-*", the object itself.
*)
let rec tt_analyse_method_expression env current_method_name comment_opt ?(first=true) exp =
match exp.Typedtree.exp_desc with
Typedtree.Texp_function (pat_exp_list, _) ->
(
match pat_exp_list with
[] ->
(* it is not a function since there are no parameters *)
(* we can't get here normally *)
raise (Failure (Odoc_messages.bad_tree^" "^(Odoc_messages.method_without_param current_method_name)))
| l ->
match l with
[] ->
cas impossible , on l'a filtré avant
assert false
| (pattern_param, exp) :: second_ele :: q ->
(* implicit pattern matching -> anonymous parameter *)
Note : We ca n't match this pattern if it is the first call to the function .
let new_param = Simple_name
{ sn_name = "??" ; sn_text = None;
sn_type = Odoc_env.subst_type env pattern_param.Typedtree.pat_type }
in
[ new_param ]
| (pattern_param, body) :: [] ->
if this is the first call to the function , this is the first parameter and we skip it
if not first then
(
let parameter =
tt_param_info_from_pattern
env
(Odoc_parameter.desc_from_info_opt comment_opt)
pattern_param
in
(* For optional parameters with a default value, a special treatment is required. *)
(* We look if the name of the parameter we just add is "*opt*", which means
that there is a let param_name = ... in ... just right now. *)
let (current_param, next_exp) =
match parameter with
Simple_name { sn_name = "*opt*"} ->
(
(
match body.exp_desc with
Typedtree.Texp_let (_, ({pat_desc = Typedtree.Tpat_var id } , exp) :: _, body2) ->
let name = Name.from_ident id in
let new_param = Simple_name
{ sn_name = name ;
sn_text = Odoc_parameter.desc_from_info_opt comment_opt name ;
sn_type = Odoc_env.subst_type env exp.Typedtree.exp_type ;
}
in
(new_param, body2)
| _ ->
print_DEBUG3 "Pas le bon filtre pour le parametre optionnel avec valeur par defaut.";
(parameter, body)
)
)
| _ ->
(* no *opt* parameter, we add the parameter then continue *)
(parameter, body)
in
current_param :: (tt_analyse_method_expression env current_method_name comment_opt ~first: false next_exp)
)
else
tt_analyse_method_expression env current_method_name comment_opt ~first: false body
)
| _ ->
(* no more parameter *)
[]
* Analysis of a [ Parsetree.class_struture ] and a [ Typedtree.class_structure ] to get a couple
( inherited classes , class elements ) .
(inherited classes, class elements). *)
let analyse_class_structure env current_class_name tt_class_sig last_pos pos_limit p_cls tt_cls table =
let rec iter acc_inher acc_fields last_pos = function
| [] ->
let s = get_string_of_file last_pos pos_limit in
let (_, ele_coms) = My_ir.all_special !file_name s in
let ele_comments =
List.fold_left
(fun acc -> fun sc ->
match sc.Odoc_types.i_desc with
None ->
acc
| Some t ->
acc @ [Class_comment t])
[]
ele_coms
in
(acc_inher, acc_fields @ ele_comments)
| (Parsetree.Pcf_inher (_, p_clexp, _)) :: q ->
let tt_clexp =
let n = List.length acc_inher in
try Typedtree_search.get_nth_inherit_class_expr tt_cls n
with Not_found ->
raise (Failure (
Odoc_messages.inherit_classexp_not_found_in_typedtree n))
in
let (info_opt, ele_comments) =
get_comments_in_class last_pos
p_clexp.Parsetree.pcl_loc.Location.loc_start.Lexing.pos_cnum
in
let text_opt =
match info_opt with None -> None
| Some i -> i.Odoc_types.i_desc in
let name = tt_name_of_class_expr tt_clexp in
let inher =
{
ic_name = Odoc_env.full_class_or_class_type_name env name ;
ic_class = None ;
ic_text = text_opt ;
}
in
iter (acc_inher @ [ inher ]) (acc_fields @ ele_comments)
p_clexp.Parsetree.pcl_loc.Location.loc_end.Lexing.pos_cnum
q
| ((Parsetree.Pcf_val (label, mutable_flag, _, _, loc) |
Parsetree.Pcf_valvirt (label, mutable_flag, _, loc) ) as x) :: q ->
let virt = match x with Parsetree.Pcf_val _ -> false | _ -> true in
let complete_name = Name.concat current_class_name label in
let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
let type_exp =
try
if virt then
Typedtree_search.search_virtual_attribute_type table
(Name.simple current_class_name) label
else
Typedtree_search.search_attribute_type tt_cls label
with Not_found ->
raise (Failure (Odoc_messages.attribute_not_found_in_typedtree complete_name))
in
let att =
{
att_value = { val_name = complete_name ;
val_info = info_opt ;
val_type = Odoc_env.subst_type env type_exp ;
val_recursive = false ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
} ;
att_mutable = mutable_flag = Asttypes.Mutable ;
att_virtual = virt ;
}
in
iter acc_inher (acc_fields @ ele_comments @ [ Class_attribute att ]) loc.Location.loc_end.Lexing.pos_cnum q
| (Parsetree.Pcf_virt (label, private_flag, _, loc)) :: q ->
let complete_name = Name.concat current_class_name label in
let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
let met_type =
try Odoc_sig.Signature_search.search_method_type label tt_class_sig
with Not_found -> raise (Failure (Odoc_messages.method_type_not_found current_class_name label))
in
let real_type =
match met_type.Types.desc with
Tarrow (_, _, t, _) ->
t
| _ ->
(* ?!? : not an arrow type ! return the original type *)
met_type
in
let met =
{
met_value = { val_name = complete_name ;
val_info = info_opt ;
val_type = Odoc_env.subst_type env real_type ;
val_recursive = false ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
} ;
met_private = private_flag = Asttypes.Private ;
met_virtual = true ;
}
in
(* update the parameter description *)
Odoc_value.update_value_parameters_text met.met_value;
iter acc_inher (acc_fields @ ele_comments @ [ Class_method met ]) loc.Location.loc_end.Lexing.pos_cnum q
| (Parsetree.Pcf_meth (label, private_flag, _, _, loc)) :: q ->
let complete_name = Name.concat current_class_name label in
let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
let exp =
try Typedtree_search.search_method_expression tt_cls label
with Not_found -> raise (Failure (Odoc_messages.method_not_found_in_typedtree complete_name))
in
let real_type =
match exp.exp_type.desc with
Tarrow (_, _, t,_) ->
t
| _ ->
(* ?!? : not an arrow type ! return the original type *)
exp.Typedtree.exp_type
in
let met =
{
met_value = { val_name = complete_name ;
val_info = info_opt ;
val_type = Odoc_env.subst_type env real_type ;
val_recursive = false ;
val_parameters = tt_analyse_method_expression env complete_name info_opt exp ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
} ;
met_private = private_flag = Asttypes.Private ;
met_virtual = false ;
}
in
(* update the parameter description *)
Odoc_value.update_value_parameters_text met.met_value;
iter acc_inher (acc_fields @ ele_comments @ [ Class_method met ]) loc.Location.loc_end.Lexing.pos_cnum q
| Parsetree.Pcf_cstr (_, _, loc) :: q ->
(* don't give a $*%@ ! *)
iter acc_inher acc_fields loc.Location.loc_end.Lexing.pos_cnum q
| Parsetree.Pcf_let (_, _, loc) :: q ->
(* don't give a $*%@ ! *)
iter acc_inher acc_fields loc.Location.loc_end.Lexing.pos_cnum q
| (Parsetree.Pcf_init exp) :: q ->
iter acc_inher acc_fields exp.Parsetree.pexp_loc.Location.loc_end.Lexing.pos_cnum q
in
iter [] [] last_pos (snd p_cls)
* Analysis of a [ Parsetree.class_expr ] and a [ Typedtree.class_expr ] to get a a couple ( class parameters , class kind ) .
let rec analyse_class_kind env current_class_name comment_opt last_pos p_class_expr tt_class_exp table =
match (p_class_expr.Parsetree.pcl_desc, tt_class_exp.Typedtree.cl_desc) with
(Parsetree.Pcl_constr (lid, _), tt_class_exp_desc ) ->
let name =
match tt_class_exp_desc with
Typedtree.Tclass_ident p -> Name.from_path p
| _ ->
(* we try to get the name from the environment. *)
A VOIR : dommage qu'on n'ait pas un Tclass_ident :-( même quand on a class tutu = toto
Name.from_longident lid
in
On n'a pas ici les paramètres de type sous forme ,
par contre on peut les trouver dans le class_type
par contre on peut les trouver dans le class_type *)
let params =
match tt_class_exp.Typedtree.cl_type with
Types.Tcty_constr (p2, type_exp_list, cltyp) ->
cltyp is the class type for [ type_exp_list ] p
type_exp_list
| _ ->
[]
in
([],
Class_constr
{
cco_name = Odoc_env.full_class_name env name ;
cco_class = None ;
cco_type_parameters = List.map (Odoc_env.subst_type env) params ;
} )
| (Parsetree.Pcl_structure p_class_structure, Typedtree.Tclass_structure tt_class_structure) ->
(* we need the class signature to get the type of methods in analyse_class_structure *)
let tt_class_sig =
match tt_class_exp.Typedtree.cl_type with
Types.Tcty_signature class_sig -> class_sig
| _ -> raise (Failure "analyse_class_kind: no class signature for a class structure.")
in
let (inherited_classes, class_elements) = analyse_class_structure
env
current_class_name
tt_class_sig
last_pos
p_class_expr.Parsetree.pcl_loc.Location.loc_end.Lexing.pos_cnum
p_class_structure
tt_class_structure
table
in
([],
Class_structure (inherited_classes, class_elements) )
| (Parsetree.Pcl_fun (label, expression_opt, pattern, p_class_expr2),
Typedtree.Tclass_fun (pat, ident_exp_list, tt_class_expr2, partial)) ->
(* we check that this is not an optional parameter with
a default value. In this case, we look for the good parameter pattern *)
let (parameter, next_tt_class_exp) =
match pat.Typedtree.pat_desc with
Typedtree.Tpat_var ident when Name.from_ident ident = "*opt*" ->
(
(* there must be a Tclass_let just after *)
match tt_class_expr2.Typedtree.cl_desc with
Typedtree.Tclass_let (_, ({pat_desc = Typedtree.Tpat_var id } , exp) :: _, _, tt_class_expr3) ->
let name = Name.from_ident id in
let new_param = Simple_name
{ sn_name = name ;
sn_text = Odoc_parameter.desc_from_info_opt comment_opt name ;
sn_type = Odoc_env.subst_type env exp.exp_type
}
in
(new_param, tt_class_expr3)
| _ ->
(* strange case *)
(* we create the parameter and add it to the class *)
raise (Failure "analyse_class_kind: strange case")
)
| _ ->
(* no optional parameter with default value, we create the parameter *)
let new_param =
tt_param_info_from_pattern
env
(Odoc_parameter.desc_from_info_opt comment_opt)
pat
in
(new_param, tt_class_expr2)
in
let (params, k) = analyse_class_kind
env current_class_name comment_opt last_pos p_class_expr2
next_tt_class_exp table
in
(parameter :: params, k)
| (Parsetree.Pcl_apply (p_class_expr2, _), Tclass_apply (tt_class_expr2, exp_opt_optional_list)) ->
let applied_name =
(* we want an ident, or else the class applied will appear in the form object ... end,
because if the class applied has no name, the code is kinda ugly, isn't it ? *)
match tt_class_expr2.Typedtree.cl_desc with
Typedtree.Tclass_ident p -> Name.from_path p (* A VOIR : obtenir le nom complet *)
| _ ->
A VOIR : dommage qu'on n'ait pas un Tclass_ident :-( même quand on a class tutu = toto
match p_class_expr2.Parsetree.pcl_desc with
Parsetree.Pcl_constr (lid, _) ->
(* we try to get the name from the environment. *)
Name.from_longident lid
| _ ->
Odoc_messages.object_end
in
let param_exps = List.fold_left
(fun acc -> fun (exp_opt, _) ->
match exp_opt with
None -> acc
| Some e -> acc @ [e])
[]
exp_opt_optional_list
in
let param_types = List.map (fun e -> e.Typedtree.exp_type) param_exps in
let params_code =
List.map
(fun e -> get_string_of_file
e.exp_loc.Location.loc_start.Lexing.pos_cnum
e.exp_loc.Location.loc_end.Lexing.pos_cnum)
param_exps
in
([],
Class_apply
{ capp_name = Odoc_env.full_class_name env applied_name ;
capp_class = None ;
capp_params = param_types ;
capp_params_code = params_code ;
} )
| (Parsetree.Pcl_let (_, _, p_class_expr2), Typedtree.Tclass_let (_, _, _, tt_class_expr2)) ->
(* we don't care about these lets *)
analyse_class_kind
env current_class_name comment_opt last_pos p_class_expr2
tt_class_expr2 table
| (Parsetree.Pcl_constraint (p_class_expr2, p_class_type2),
Typedtree.Tclass_constraint (tt_class_expr2, _, _, _)) ->
let (l, class_kind) = analyse_class_kind
env current_class_name comment_opt last_pos p_class_expr2
tt_class_expr2 table
in
(* A VOIR : analyse du class type ? on n'a pas toutes les infos. cf. Odoc_sig.analyse_class_type_kind *)
let class_type_kind =
(*Sig.analyse_class_type_kind
env
""
p_class_type2.Parsetree.pcty_loc.Location.loc_start.Lexing.pos_cnum
p_class_type2
tt_class_expr2.Typedtree.cl_type
*)
Class_type { cta_name = Odoc_messages.object_end ;
cta_class = None ; cta_type_parameters = [] }
in
(l, Class_constraint (class_kind, class_type_kind))
| _ ->
raise (Failure "analyse_class_kind: Parsetree and typedtree don't match.")
(** Analysis of a [Parsetree.class_declaration] and a [Typedtree.class_expr] to return a [t_class].*)
let analyse_class env current_module_name comment_opt p_class_decl tt_type_params tt_class_exp table =
let name = p_class_decl.Parsetree.pci_name in
let complete_name = Name.concat current_module_name name in
let pos_start = p_class_decl.Parsetree.pci_expr.Parsetree.pcl_loc.Location.loc_start.Lexing.pos_cnum in
let type_parameters = tt_type_params in
let virt = p_class_decl.Parsetree.pci_virt = Asttypes.Virtual in
let cltype = Odoc_env.subst_class_type env tt_class_exp.Typedtree.cl_type in
let (parameters, kind) = analyse_class_kind
env
complete_name
comment_opt
pos_start
p_class_decl.Parsetree.pci_expr
tt_class_exp
table
in
let cl =
{
cl_name = complete_name ;
cl_info = comment_opt ;
cl_type = cltype ;
cl_virtual = virt ;
cl_type_parameters = type_parameters ;
cl_kind = kind ;
cl_parameters = parameters ;
cl_loc = { loc_impl = Some (!file_name, pos_start) ; loc_inter = None } ;
}
in
cl
(** Get a name from a module expression, or "struct ... end" if the module expression
is not an ident of a constraint on an ident. *)
let rec tt_name_from_module_expr mod_expr =
match mod_expr.Typedtree.mod_desc with
Typedtree.Tmod_ident p -> Name.from_path p
| Typedtree.Tmod_constraint (m_exp, _, _) -> tt_name_from_module_expr m_exp
| Typedtree.Tmod_structure _
| Typedtree.Tmod_functor _
| Typedtree.Tmod_apply _
| Typedtree.Tmod_unpack _ ->
Odoc_messages.struct_end
(** Get the list of included modules in a module structure of a typed tree. *)
let tt_get_included_module_list tt_structure =
let f acc item =
match item with
Typedtree.Tstr_include (mod_expr, _) ->
acc @ [
A VOIR : chercher dans les modules et les module types , env ?
im_name = tt_name_from_module_expr mod_expr ;
im_module = None ;
im_info = None ;
}
]
| _ ->
acc
in
List.fold_left f [] tt_structure
(** This function takes a [module element list] of a module and replaces the "dummy" included modules with
the ones found in typed tree structure of the module. *)
let replace_dummy_included_modules module_elements included_modules =
let rec f = function
| ([], _) ->
[]
| ((Element_included_module im) :: q, (im_repl :: im_q)) ->
(Element_included_module { im_repl with im_info = im.im_info })
:: (f (q, im_q))
| ((Element_included_module im) :: q, []) ->
(Element_included_module im) :: q
| (ele :: q, l) ->
ele :: (f (q, l))
in
f (module_elements, included_modules)
(** This function removes the elements of the module which does not
belong to the given module type, if the module type is expanded
and the module has a "structure" kind. *)
let rec filter_module_with_module_type_constraint m mt =
match m.m_kind, mt with
Module_struct l, Types.Tmty_signature lsig ->
m.m_kind <- Module_struct (filter_module_elements_with_module_type_constraint l lsig);
m.m_type <- mt;
| _ -> ()
(** This function removes the elements of the module type which does not
belong to the given module type, if the module type is expanded
and the module type has a "structure" kind. *)
and filter_module_type_with_module_type_constraint mtyp mt =
match mtyp.mt_kind, mt with
Some Module_type_struct l, Types.Tmty_signature lsig ->
mtyp.mt_kind <- Some (Module_type_struct (filter_module_elements_with_module_type_constraint l lsig));
mtyp.mt_type <- Some mt;
| _ -> ()
and filter_module_elements_with_module_type_constraint l lsig =
let pred ele =
let f = match ele with
Element_module m ->
(function
Types.Tsig_module (ident,t,_) ->
let n1 = Name.simple m.m_name
and n2 = Ident.name ident in
(
match n1 = n2 with
true -> filter_module_with_module_type_constraint m t; true
| false -> false
)
| _ -> false)
| Element_module_type mt ->
(function
Types.Tsig_modtype (ident,Types.Tmodtype_manifest t) ->
let n1 = Name.simple mt.mt_name
and n2 = Ident.name ident in
(
match n1 = n2 with
true -> filter_module_type_with_module_type_constraint mt t; true
| false -> false
)
| _ -> false)
| Element_value v ->
(function
Types.Tsig_value (ident,_) ->
let n1 = Name.simple v.val_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_type t ->
(function
Types.Tsig_type (ident,_,_) ->
(* A VOIR: il est possible que le détail du type soit caché *)
let n1 = Name.simple t.ty_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_exception e ->
(function
Types.Tsig_exception (ident,_) ->
let n1 = Name.simple e.ex_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_class c ->
(function
Types.Tsig_class (ident,_,_) ->
let n1 = Name.simple c.cl_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_class_type ct ->
(function
Types.Tsig_cltype (ident,_,_) ->
let n1 = Name.simple ct.clt_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_module_comment _ -> fun _ -> true
| Element_included_module _ -> fun _ -> true
in
List.exists f lsig
in
List.filter pred l
(** Analysis of a parse tree structure with a typed tree, to return module elements.*)
let rec analyse_structure env current_module_name last_pos pos_limit parsetree typedtree =
print_DEBUG "Odoc_ast:analyse_struture";
let (table, table_values) = Typedtree_search.tables typedtree in
let rec iter env last_pos = function
[] ->
let s = get_string_of_file last_pos pos_limit in
let (_, ele_coms) = My_ir.all_special !file_name s in
let ele_comments =
List.fold_left
(fun acc -> fun sc ->
match sc.Odoc_types.i_desc with
None ->
acc
| Some t ->
acc @ [Element_module_comment t])
[]
ele_coms
in
ele_comments
| item :: q ->
let (comment_opt, ele_comments) =
get_comments_in_module last_pos item.Parsetree.pstr_loc.Location.loc_start.Lexing.pos_cnum
in
let pos_limit2 =
match q with
[] -> pos_limit
| item2 :: _ -> item2.Parsetree.pstr_loc.Location.loc_start.Lexing.pos_cnum
in
let (maybe_more, new_env, elements) = analyse_structure_item
env
current_module_name
item.Parsetree.pstr_loc
pos_limit2
comment_opt
item.Parsetree.pstr_desc
typedtree
table
table_values
in
ele_comments @ elements @ (iter new_env (item.Parsetree.pstr_loc.Location.loc_end.Lexing.pos_cnum + maybe_more) q)
in
iter env last_pos parsetree
(** Analysis of a parse tree structure item to obtain a new environment and a list of elements.*)
and analyse_structure_item env current_module_name loc pos_limit comment_opt parsetree_item_desc typedtree
table table_values =
print_DEBUG "Odoc_ast:analyse_struture_item";
match parsetree_item_desc with
Parsetree.Pstr_eval _ ->
(* don't care *)
(0, env, [])
| Parsetree.Pstr_value (rec_flag, pat_exp_list) ->
of rec_flag * ( pattern * expression ) list
(* For each value, look for the value name, then look in the
typedtree for the corresponding information,
at last analyse this information to build the value *)
let rec iter_pat = function
| Parsetree.Ppat_any -> None
| Parsetree.Ppat_var name -> Some name
| Parsetree.Ppat_tuple _ -> None (* A VOIR quand on traitera les tuples *)
| Parsetree.Ppat_constraint (pat, _) -> iter_pat pat.Parsetree.ppat_desc
| _ -> None
in
let rec iter ?(first=false) last_pos acc_env acc p_e_list =
match p_e_list with
[] ->
(acc_env, acc)
| (pat, exp) :: q ->
let value_name_opt = iter_pat pat.Parsetree.ppat_desc in
let new_last_pos = exp.Parsetree.pexp_loc.Location.loc_end.Lexing.pos_cnum in
match value_name_opt with
None ->
iter new_last_pos acc_env acc q
| Some name ->
try
let pat_exp = Typedtree_search.search_value table_values name in
let (info_opt, ele_comments) =
we already have the optional comment for the first value .
if first then
(comment_opt, [])
else
get_comments_in_module
last_pos
pat.Parsetree.ppat_loc.Location.loc_start.Lexing.pos_cnum
in
let l_values = tt_analyse_value
env
current_module_name
info_opt
loc
pat_exp
rec_flag
in
let new_env = List.fold_left
(fun e -> fun v ->
Odoc_env.add_value e v.val_name
)
acc_env
l_values
in
let l_ele = List.map (fun v -> Element_value v) l_values in
iter
new_last_pos
new_env
(acc @ ele_comments @ l_ele)
q
with
Not_found ->
iter new_last_pos acc_env acc q
in
let (new_env, l_ele) = iter ~first: true loc.Location.loc_start.Lexing.pos_cnum env [] pat_exp_list in
(0, new_env, l_ele)
| Parsetree.Pstr_primitive (name_pre, val_desc) ->
(* of string * value_description *)
print_DEBUG ("Parsetree.Pstr_primitive ("^name_pre^", ["^(String.concat ", " val_desc.Parsetree.pval_prim)^"]");
let typ = Typedtree_search.search_primitive table name_pre in
let name = Name.parens_if_infix name_pre in
let complete_name = Name.concat current_module_name name in
let new_value = {
val_name = complete_name ;
val_info = comment_opt ;
val_type = Odoc_env.subst_type env typ ;
val_recursive = false ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
let new_env = Odoc_env.add_value env new_value.val_name in
(0, new_env, [Element_value new_value])
| Parsetree.Pstr_type name_typedecl_list ->
(* of (string * type_declaration) list *)
(* we start by extending the environment *)
let new_env =
List.fold_left
(fun acc_env -> fun (name, _) ->
let complete_name = Name.concat current_module_name name in
Odoc_env.add_type acc_env complete_name
)
env
name_typedecl_list
in
let rec f ?(first=false) maybe_more_acc last_pos name_type_decl_list =
match name_type_decl_list with
[] -> (maybe_more_acc, [])
| (name, type_decl) :: q ->
let complete_name = Name.concat current_module_name name in
let loc_start = type_decl.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = type_decl.Parsetree.ptype_loc.Location.loc_end.Lexing.pos_cnum in
let pos_limit2 =
match q with
[] -> pos_limit
| (_, td) :: _ -> td.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum
in
let (maybe_more, name_comment_list) =
Sig.name_comment_from_type_kind
loc_end
pos_limit2
type_decl.Parsetree.ptype_kind
in
let tt_type_decl =
try Typedtree_search.search_type_declaration table name
with Not_found -> raise (Failure (Odoc_messages.type_not_found_in_typedtree complete_name))
in
the comment for the first type was already retrieved
if first then
(comment_opt , [])
else
get_comments_in_module last_pos loc_start
in
let kind = Sig.get_type_kind
new_env name_comment_list
tt_type_decl.Types.type_kind
in
let new_end = loc_end + maybe_more in
let t =
{
ty_name = complete_name ;
ty_info = com_opt ;
ty_parameters =
List.map2
(fun p (co,cn,_) ->
(Odoc_env.subst_type new_env p,
co, cn)
)
tt_type_decl.Types.type_params
tt_type_decl.Types.type_variance ;
ty_kind = kind ;
ty_private = tt_type_decl.Types.type_private;
ty_manifest =
(match tt_type_decl.Types.type_manifest with
None -> None
| Some t -> Some (Odoc_env.subst_type new_env t));
ty_loc = { loc_impl = Some (!file_name, loc_start) ; loc_inter = None } ;
ty_code =
(
if !Odoc_global.keep_code then
Some (get_string_of_file loc_start new_end)
else
None
) ;
}
in
let (maybe_more2, info_after_opt) =
My_ir.just_after_special
!file_name
(get_string_of_file new_end pos_limit2)
in
t.ty_info <- Sig.merge_infos t.ty_info info_after_opt ;
let (maybe_more3, eles) = f (maybe_more + maybe_more2) (new_end + maybe_more2) q in
(maybe_more3, ele_comments @ ((Element_type t) :: eles))
in
let (maybe_more, eles) = f ~first: true 0 loc.Location.loc_start.Lexing.pos_cnum name_typedecl_list in
(maybe_more, new_env, eles)
| Parsetree.Pstr_exception (name, excep_decl) ->
(* a new exception is defined *)
let complete_name = Name.concat current_module_name name in
(* we get the exception declaration in the typed tree *)
let tt_excep_decl =
try Typedtree_search.search_exception table name
with Not_found ->
raise (Failure (Odoc_messages.exception_not_found_in_typedtree complete_name))
in
let new_env = Odoc_env.add_exception env complete_name in
let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
let new_ex =
{
ex_name = complete_name ;
ex_info = comment_opt ;
ex_args = List.map (Odoc_env.subst_type new_env) tt_excep_decl ;
ex_alias = None ;
ex_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
ex_code =
(
if !Odoc_global.keep_code then
Some (get_string_of_file loc_start loc_end)
else
None
) ;
}
in
(0, new_env, [ Element_exception new_ex ])
| Parsetree.Pstr_exn_rebind (name, _) ->
(* a new exception is defined *)
let complete_name = Name.concat current_module_name name in
(* we get the exception rebind in the typed tree *)
let tt_path =
try Typedtree_search.search_exception_rebind table name
with Not_found ->
raise (Failure (Odoc_messages.exception_not_found_in_typedtree complete_name))
in
let new_env = Odoc_env.add_exception env complete_name in
let new_ex =
{
ex_name = complete_name ;
ex_info = comment_opt ;
ex_args = [] ;
ex_alias = Some { ea_name = (Odoc_env.full_exception_name env (Name.from_path tt_path)) ;
ea_ex = None ; } ;
ex_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
ex_code = None ;
}
in
(0, new_env, [ Element_exception new_ex ])
| Parsetree.Pstr_module (name, module_expr) ->
(
(* of string * module_expr *)
try
let tt_module_expr = Typedtree_search.search_module table name in
let new_module_pre = analyse_module
env
current_module_name
name
comment_opt
module_expr
tt_module_expr
in
let code =
if !Odoc_global.keep_code then
let loc = module_expr.Parsetree.pmod_loc in
let st = loc.Location.loc_start.Lexing.pos_cnum in
let en = loc.Location.loc_end.Lexing.pos_cnum in
Some (get_string_of_file st en)
else
None
in
let new_module =
{ new_module_pre with m_code = code }
in
let new_env = Odoc_env.add_module env new_module.m_name in
let new_env2 =
match new_module.m_type with
A VOIR : ? dans ce cas , on aurait pas la signature
Types.Tmty_signature s ->
Odoc_env.add_signature new_env new_module.m_name
~rel: (Name.simple new_module.m_name) s
| _ ->
new_env
in
(0, new_env2, [ Element_module new_module ])
with
Not_found ->
let complete_name = Name.concat current_module_name name in
raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
)
| Parsetree.Pstr_recmodule mods ->
A VOIR ICI pb : pas de lien avec les module type
dans les contraintes sur les modules
dans les contraintes sur les modules *)
let new_env =
List.fold_left
(fun acc_env (name, _, mod_exp) ->
let complete_name = Name.concat current_module_name name in
let e = Odoc_env.add_module acc_env complete_name in
let tt_mod_exp =
try Typedtree_search.search_module table name
with Not_found -> raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
in
let new_module = analyse_module
e
current_module_name
name
None
mod_exp
tt_mod_exp
in
match new_module.m_type with
Types.Tmty_signature s ->
Odoc_env.add_signature e new_module.m_name
~rel: (Name.simple new_module.m_name) s
| _ ->
e
)
env
mods
in
let rec f ?(first=false) last_pos name_mod_exp_list =
match name_mod_exp_list with
[] -> []
| (name, _, mod_exp) :: q ->
let complete_name = Name.concat current_module_name name in
let loc_start = mod_exp.Parsetree.pmod_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = mod_exp.Parsetree.pmod_loc.Location.loc_end.Lexing.pos_cnum in
let tt_mod_exp =
try Typedtree_search.search_module table name
with Not_found -> raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
in
the comment for the first type was already retrieved
if first then
(comment_opt, [])
else
get_comments_in_module last_pos loc_start
in
let new_module = analyse_module
new_env
current_module_name
name
com_opt
mod_exp
tt_mod_exp
in
let eles = f loc_end q in
ele_comments @ ((Element_module new_module) :: eles)
in
let eles = f ~first: true loc.Location.loc_start.Lexing.pos_cnum mods in
(0, new_env, eles)
| Parsetree.Pstr_modtype (name, modtype) ->
let complete_name = Name.concat current_module_name name in
let tt_module_type =
try Typedtree_search.search_module_type table name
with Not_found ->
raise (Failure (Odoc_messages.module_type_not_found_in_typedtree complete_name))
in
let kind = Sig.analyse_module_type_kind env complete_name
modtype tt_module_type
in
let mt =
{
mt_name = complete_name ;
mt_info = comment_opt ;
mt_type = Some tt_module_type ;
mt_is_interface = false ;
mt_file = !file_name ;
mt_kind = Some kind ;
mt_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
let new_env = Odoc_env.add_module_type env mt.mt_name in
let new_env2 =
match tt_module_type with
A VOIR : ? dans ce cas , on n'aurait pas la signature
Types.Tmty_signature s ->
Odoc_env.add_signature new_env mt.mt_name ~rel: (Name.simple mt.mt_name) s
| _ ->
new_env
in
(0, new_env2, [ Element_module_type mt ])
| Parsetree.Pstr_open longident ->
(* A VOIR : enrichir l'environnement quand open ? *)
let ele_comments = match comment_opt with
None -> []
| Some i ->
match i.i_desc with
None -> []
| Some t -> [Element_module_comment t]
in
(0, env, ele_comments)
| Parsetree.Pstr_class class_decl_list ->
(* we start by extending the environment *)
let new_env =
List.fold_left
(fun acc_env -> fun class_decl ->
let complete_name = Name.concat current_module_name class_decl.Parsetree.pci_name in
Odoc_env.add_class acc_env complete_name
)
env
class_decl_list
in
let rec f ?(first=false) last_pos class_decl_list =
match class_decl_list with
[] ->
[]
| class_decl :: q ->
let (tt_class_exp, tt_type_params) =
try Typedtree_search.search_class_exp table class_decl.Parsetree.pci_name
with Not_found ->
let complete_name = Name.concat current_module_name class_decl.Parsetree.pci_name in
raise (Failure (Odoc_messages.class_not_found_in_typedtree complete_name))
in
let (com_opt, ele_comments) =
if first then
(comment_opt, [])
else
get_comments_in_module last_pos class_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
in
let last_pos2 = class_decl.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
let new_class = analyse_class
new_env
current_module_name
com_opt
class_decl
tt_type_params
tt_class_exp
table
in
ele_comments @ ((Element_class new_class) :: (f last_pos2 q))
in
(0, new_env, f ~first: true loc.Location.loc_start.Lexing.pos_cnum class_decl_list)
| Parsetree.Pstr_class_type class_type_decl_list ->
(* we start by extending the environment *)
let new_env =
List.fold_left
(fun acc_env -> fun class_type_decl ->
let complete_name = Name.concat current_module_name class_type_decl.Parsetree.pci_name in
Odoc_env.add_class_type acc_env complete_name
)
env
class_type_decl_list
in
let rec f ?(first=false) last_pos class_type_decl_list =
match class_type_decl_list with
[] ->
[]
| class_type_decl :: q ->
let name = class_type_decl.Parsetree.pci_name in
let complete_name = Name.concat current_module_name name in
let virt = class_type_decl.Parsetree.pci_virt = Asttypes.Virtual in
let tt_cltype_declaration =
try Typedtree_search.search_class_type_declaration table name
with Not_found ->
raise (Failure (Odoc_messages.class_type_not_found_in_typedtree complete_name))
in
let type_params = tt_cltype_declaration.Types.clty_params in
let kind = Sig.analyse_class_type_kind
new_env
complete_name
class_type_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
class_type_decl.Parsetree.pci_expr
tt_cltype_declaration.Types.clty_type
in
let (com_opt, ele_comments) =
if first then
(comment_opt, [])
else
get_comments_in_module last_pos class_type_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
in
let last_pos2 = class_type_decl.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
let new_ele =
Element_class_type
{
clt_name = complete_name ;
clt_info = com_opt ;
clt_type = Odoc_env.subst_class_type env tt_cltype_declaration.Types.clty_type ;
clt_type_parameters = List.map (Odoc_env.subst_type new_env) type_params ;
clt_virtual = virt ;
clt_kind = kind ;
clt_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ;
loc_inter = None } ;
}
in
ele_comments @ (new_ele :: (f last_pos2 q))
in
(0, new_env, f ~first: true loc.Location.loc_start.Lexing.pos_cnum class_type_decl_list)
| Parsetree.Pstr_include module_expr ->
(* we add a dummy included module which will be replaced by a correct
one at the end of the module analysis,
to use the Path.t of the included modules in the typdtree. *)
let im =
{
im_name = "dummy" ;
im_module = None ;
im_info = comment_opt ;
}
in
(0, env, [ Element_included_module im ]) (* A VOIR : étendre l'environnement ? avec quoi ? *)
(** Analysis of a [Parsetree.module_expr] and a name to return a [t_module].*)
and analyse_module env current_module_name module_name comment_opt p_module_expr tt_module_expr =
let complete_name = Name.concat current_module_name module_name in
let pos_start = p_module_expr.Parsetree.pmod_loc.Location.loc_start.Lexing.pos_cnum in
let pos_end = p_module_expr.Parsetree.pmod_loc.Location.loc_end.Lexing.pos_cnum in
let modtype =
(* A VOIR : Odoc_env.subst_module_type env ? *)
tt_module_expr.Typedtree.mod_type
in
let m_code_intf =
match p_module_expr.Parsetree.pmod_desc with
Parsetree.Pmod_constraint (_, pmodule_type) ->
let loc_start = pmodule_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = pmodule_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
Some (get_string_of_file loc_start loc_end)
| _ ->
None
in
let m_base =
{
m_name = complete_name ;
m_type = modtype ;
m_info = comment_opt ;
m_is_interface = false ;
m_file = !file_name ;
m_kind = Module_struct [] ;
m_loc = { loc_impl = Some (!file_name, pos_start) ; loc_inter = None } ;
m_top_deps = [] ;
m_code = None ; (* code is set by the caller, after the module is created *)
m_code_intf = m_code_intf ;
m_text_only = false ;
}
in
match (p_module_expr.Parsetree.pmod_desc, tt_module_expr.Typedtree.mod_desc) with
(Parsetree.Pmod_ident longident, Typedtree.Tmod_ident path) ->
let alias_name = Odoc_env.full_module_name env (Name.from_path path) in
{ m_base with m_kind = Module_alias { ma_name = alias_name ;
ma_module = None ; } }
| (Parsetree.Pmod_structure p_structure, Typedtree.Tmod_structure tt_structure) ->
let elements = analyse_structure env complete_name pos_start pos_end p_structure tt_structure in
(* we must complete the included modules *)
let included_modules_from_tt = tt_get_included_module_list tt_structure in
let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
{ m_base with m_kind = Module_struct elements2 }
| (Parsetree.Pmod_functor (_, pmodule_type, p_module_expr2),
Typedtree.Tmod_functor (ident, mtyp, tt_module_expr2)) ->
let loc_start = pmodule_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = pmodule_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
let mp_type_code = get_string_of_file loc_start loc_end in
print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
let mp_name = Name.from_ident ident in
let mp_kind = Sig.analyse_module_type_kind env
current_module_name pmodule_type mtyp
in
let param =
{
mp_name = mp_name ;
mp_type = Odoc_env.subst_module_type env mtyp ;
mp_type_code = mp_type_code ;
mp_kind = mp_kind ;
}
in
let dummy_complete_name = (*Name.concat "__"*) param.mp_name in
(* TODO: A VOIR CE __ *)
let new_env = Odoc_env.add_module env dummy_complete_name in
let m_base2 = analyse_module
new_env
current_module_name
module_name
None
p_module_expr2
tt_module_expr2
in
let kind = m_base2.m_kind in
{ m_base with m_kind = Module_functor (param, kind) }
| (Parsetree.Pmod_apply (p_module_expr1, p_module_expr2),
Typedtree.Tmod_apply (tt_module_expr1, tt_module_expr2, _))
| (Parsetree.Pmod_apply (p_module_expr1, p_module_expr2),
Typedtree.Tmod_constraint
({ Typedtree.mod_desc = Typedtree.Tmod_apply (tt_module_expr1, tt_module_expr2, _)},
_, _)
) ->
let m1 = analyse_module
env
current_module_name
module_name
None
p_module_expr1
tt_module_expr1
in
let m2 = analyse_module
env
current_module_name
module_name
None
p_module_expr2
tt_module_expr2
in
{ m_base with m_kind = Module_apply (m1.m_kind, m2.m_kind) }
| (Parsetree.Pmod_constraint (p_module_expr2, p_modtype),
Typedtree.Tmod_constraint (tt_module_expr2, tt_modtype, _)) ->
print_DEBUG ("Odoc_ast: case Parsetree.Pmod_constraint + Typedtree.Tmod_constraint "^module_name);
let m_base2 = analyse_module
env
current_module_name
module_name
None
p_module_expr2
tt_module_expr2
in
let mtkind = Sig.analyse_module_type_kind env
(Name.concat current_module_name "??")
p_modtype tt_modtype
in
let tt_modtype = Odoc_env.subst_module_type env tt_modtype in
if !Odoc_global.filter_with_module_constraints then
filter_module_with_module_type_constraint m_base2 tt_modtype;
{
m_base with
m_type = tt_modtype ;
m_kind = Module_constraint (m_base2.m_kind, mtkind) ;
}
| (Parsetree.Pmod_structure p_structure,
Typedtree.Tmod_constraint
({ Typedtree.mod_desc = Typedtree.Tmod_structure tt_structure},
tt_modtype, _)
) ->
(* needed for recursive modules *)
print_DEBUG ("Odoc_ast: case Parsetree.Pmod_structure + Typedtree.Tmod_constraint "^module_name);
let elements = analyse_structure env complete_name pos_start pos_end p_structure tt_structure in
(* we must complete the included modules *)
let included_modules_from_tt = tt_get_included_module_list tt_structure in
let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
{ m_base with
m_type = Odoc_env.subst_module_type env tt_modtype ;
m_kind = Module_struct elements2 ;
}
| (Parsetree.Pmod_unpack (p_exp),
Typedtree.Tmod_unpack (t_exp, tt_modtype)) ->
print_DEBUG ("Odoc_ast: case Parsetree.Pmod_unpack + Typedtree.Tmod_unpack "^module_name);
let code =
let loc = p_module_expr.Parsetree.pmod_loc in
let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
let exp_loc = p_exp.Parsetree.pexp_loc in
let exp_loc_end = exp_loc.Location.loc_end.Lexing.pos_cnum in
let s = get_string_of_file exp_loc_end loc_end in
Printf.sprintf "(val ...%s" s
in
let name = Odoc_env.full_module_type_name env ( Name.from_path ( fst pkg_type ) ) in
let name =
match tt_modtype with
| Tmty_ident p ->
Odoc_env.full_module_type_name env (Name.from_path p)
| _ -> ""
in
let alias = { mta_name = name ; mta_module = None } in
{ m_base with
m_type = Odoc_env.subst_module_type env tt_modtype ;
m_kind = Module_unpack (code, alias) ;
}
| (parsetree, typedtree) ->
(*DEBUG*)let s_parse =
(*DEBUG*) match parsetree with
(*DEBUG*) Parsetree.Pmod_ident _ -> "Pmod_ident"
(*DEBUG*) | Parsetree.Pmod_structure _ -> "Pmod_structure"
(*DEBUG*) | Parsetree.Pmod_functor _ -> "Pmod_functor"
(*DEBUG*) | Parsetree.Pmod_apply _ -> "Pmod_apply"
(*DEBUG*) | Parsetree.Pmod_constraint _ -> "Pmod_constraint"
(*DEBUG*) | Parsetree.Pmod_unpack _ -> "Pmod_unpack"
(*DEBUG*)in
(*DEBUG*)let s_typed =
(*DEBUG*) match typedtree with
(*DEBUG*) Typedtree.Tmod_ident _ -> "Tmod_ident"
(*DEBUG*) | Typedtree.Tmod_structure _ -> "Tmod_structure"
(*DEBUG*) | Typedtree.Tmod_functor _ -> "Tmod_functor"
(*DEBUG*) | Typedtree.Tmod_apply _ -> "Tmod_apply"
(*DEBUG*) | Typedtree.Tmod_constraint _ -> "Tmod_constraint"
(*DEBUG*) | Typedtree.Tmod_unpack _ -> "Tmod_unpack"
(*DEBUG*)in
(*DEBUG*)let code = get_string_of_file pos_start pos_end in
print_DEBUG (Printf.sprintf "code=%s\ns_parse=%s\ns_typed=%s\n" code s_parse s_typed);
raise (Failure "analyse_module: parsetree and typedtree don't match.")
let analyse_typed_tree source_file input_file
(parsetree : Parsetree.structure) (typedtree : typedtree) =
let (tree_structure, _) = typedtree in
let complete_source_file =
try
let curdir = Sys.getcwd () in
let (dirname, basename) = (Filename.dirname source_file, Filename.basename source_file) in
Sys.chdir dirname ;
let complete = Filename.concat (Sys.getcwd ()) basename in
Sys.chdir curdir ;
complete
with
Sys_error s ->
prerr_endline s ;
incr Odoc_global.errors ;
source_file
in
prepare_file complete_source_file input_file;
(* We create the t_module for this file. *)
let mod_name = String.capitalize (Filename.basename (Filename.chop_extension source_file)) in
let (len,info_opt) = My_ir.first_special !file_name !file in
(* we must complete the included modules *)
let elements = analyse_structure Odoc_env.empty mod_name len (String.length !file) parsetree tree_structure in
let included_modules_from_tt = tt_get_included_module_list tree_structure in
let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
let kind = Module_struct elements2 in
{
m_name = mod_name ;
m_type = Types.Tmty_signature [] ;
m_info = info_opt ;
m_is_interface = false ;
m_file = !file_name ;
m_kind = kind ;
m_loc = { loc_impl = Some (!file_name, 0) ; loc_inter = None } ;
m_top_deps = [] ;
m_code = (if !Odoc_global.keep_code then Some !file else None) ;
m_code_intf = None ;
m_text_only = false ;
}
end
| null | https://raw.githubusercontent.com/OCamlPro/OCamlPro-OCaml-Branch/3a522985649389f89dac73e655d562c54f0456a5/inline-more/ocamldoc/odoc_ast.ml | ocaml | *********************************************************************
OCamldoc
*********************************************************************
* Analysis of implementation files.
* This variable contains the regular expression representing a blank.
* This variable contains the regular expression representing a blank but not a '\n'.
A VOIR quand on traitera les tuples
* This variable is used to load a file as a string and retrieve characters from it.
* The name of the analysed file.
* This function loads the given file in the file global variable.
and sets file_name.
* The function used to get the comments in a class.
* The function used to get the comments in a module.
* This function takes a parameter pattern and builds the
corresponding [parameter] structure. The f_desc function
is used to retrieve a parameter description, if any, from
a parameter name.
we give a name to the parameter only if it unit
a () argument, it never has description
implicit pattern matching -> anonymous parameter
* Analysis of the parameter of a function. Return a list of t_parameter created from
the (pattern, expression) structures encountered.
This case means we have a 'function' without pattern, that's impossible
implicit pattern matching -> anonymous parameter and no more parameter
A VOIR : le label ?
For optional parameters with a default value, a special treatment is required
we look if the name of the parameter we just add is "*opt*", which means
that there is a let param_name = ... in ... just right now
continue if the body is still a function
something else ; no more parameter
* Analysis of a Tstr_value from the typedtree. Create and return a list of [t_value].
@raise Failure if an error occurs.
a new function is defined
create the value
a new value is defined
new identifiers are defined
A VOIR : by now we don't accept to have global variables defined in tuples
something else, we don't care ? A VOIR
* This function takes a Typedtree.class_expr and returns a string which can stand for the class name.
The name can be "object ... end" if the class expression is not an ident or a class constraint or a class apply.
| Typedtree.Tclass_fun (_, _, class_expr, _) -> tt_name_of_class_expr class_expr
| Typedtree.Tclass_let (_,_,_, class_expr) -> tt_name_of_class_expr class_expr
it is not a function since there are no parameters
we can't get here normally
implicit pattern matching -> anonymous parameter
For optional parameters with a default value, a special treatment is required.
We look if the name of the parameter we just add is "*opt*", which means
that there is a let param_name = ... in ... just right now.
no *opt* parameter, we add the parameter then continue
no more parameter
?!? : not an arrow type ! return the original type
update the parameter description
?!? : not an arrow type ! return the original type
update the parameter description
don't give a $*%@ !
don't give a $*%@ !
we try to get the name from the environment.
we need the class signature to get the type of methods in analyse_class_structure
we check that this is not an optional parameter with
a default value. In this case, we look for the good parameter pattern
there must be a Tclass_let just after
strange case
we create the parameter and add it to the class
no optional parameter with default value, we create the parameter
we want an ident, or else the class applied will appear in the form object ... end,
because if the class applied has no name, the code is kinda ugly, isn't it ?
A VOIR : obtenir le nom complet
we try to get the name from the environment.
we don't care about these lets
A VOIR : analyse du class type ? on n'a pas toutes les infos. cf. Odoc_sig.analyse_class_type_kind
Sig.analyse_class_type_kind
env
""
p_class_type2.Parsetree.pcty_loc.Location.loc_start.Lexing.pos_cnum
p_class_type2
tt_class_expr2.Typedtree.cl_type
* Analysis of a [Parsetree.class_declaration] and a [Typedtree.class_expr] to return a [t_class].
* Get a name from a module expression, or "struct ... end" if the module expression
is not an ident of a constraint on an ident.
* Get the list of included modules in a module structure of a typed tree.
* This function takes a [module element list] of a module and replaces the "dummy" included modules with
the ones found in typed tree structure of the module.
* This function removes the elements of the module which does not
belong to the given module type, if the module type is expanded
and the module has a "structure" kind.
* This function removes the elements of the module type which does not
belong to the given module type, if the module type is expanded
and the module type has a "structure" kind.
A VOIR: il est possible que le détail du type soit caché
* Analysis of a parse tree structure with a typed tree, to return module elements.
* Analysis of a parse tree structure item to obtain a new environment and a list of elements.
don't care
For each value, look for the value name, then look in the
typedtree for the corresponding information,
at last analyse this information to build the value
A VOIR quand on traitera les tuples
of string * value_description
of (string * type_declaration) list
we start by extending the environment
a new exception is defined
we get the exception declaration in the typed tree
a new exception is defined
we get the exception rebind in the typed tree
of string * module_expr
A VOIR : enrichir l'environnement quand open ?
we start by extending the environment
we start by extending the environment
we add a dummy included module which will be replaced by a correct
one at the end of the module analysis,
to use the Path.t of the included modules in the typdtree.
A VOIR : étendre l'environnement ? avec quoi ?
* Analysis of a [Parsetree.module_expr] and a name to return a [t_module].
A VOIR : Odoc_env.subst_module_type env ?
code is set by the caller, after the module is created
we must complete the included modules
Name.concat "__"
TODO: A VOIR CE __
needed for recursive modules
we must complete the included modules
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
DEBUG
We create the t_module for this file.
we must complete the included modules | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Misc
open Asttypes
open Types
open Typedtree
let print_DEBUG3 s = print_string s ; print_newline ();;
let print_DEBUG s = print_string s ; print_newline ();;
type typedtree = (Typedtree.structure * Typedtree.module_coercion)
module Name = Odoc_name
open Odoc_parameter
open Odoc_value
open Odoc_type
open Odoc_exception
open Odoc_class
open Odoc_module
open Odoc_types
let blank = "[ \010\013\009\012']"
let simple_blank = "[ \013\009\012]"
* This module is used to search for structure items by name in a Typedtree.structure .
One function creates two hash tables , which can then be used to search for elements .
Class elements do not use tables .
One function creates two hash tables, which can then be used to search for elements.
Class elements do not use tables.
*)
module Typedtree_search =
struct
type ele =
| M of string
| MT of string
| T of string
| C of string
| CT of string
| E of string
| ER of string
| P of string
| IM of string
type tab = (ele, Typedtree.structure_item) Hashtbl.t
type tab_values = (Odoc_module.Name.t, Typedtree.pattern * Typedtree.expression) Hashtbl.t
let iter_val_pattern = function
| Typedtree.Tpat_any -> None
| Typedtree.Tpat_var name -> Some (Name.from_ident name)
| _ -> None
let add_to_hashes table table_values tt =
match tt with
| Typedtree.Tstr_module (ident, _) ->
Hashtbl.add table (M (Name.from_ident ident)) tt
| Typedtree.Tstr_recmodule mods ->
List.iter
(fun (ident,mod_expr) ->
Hashtbl.add table (M (Name.from_ident ident))
(Typedtree.Tstr_module (ident,mod_expr))
)
mods
| Typedtree.Tstr_modtype (ident, _) ->
Hashtbl.add table (MT (Name.from_ident ident)) tt
| Typedtree.Tstr_exception (ident, _) ->
Hashtbl.add table (E (Name.from_ident ident)) tt
| Typedtree.Tstr_exn_rebind (ident, _) ->
Hashtbl.add table (ER (Name.from_ident ident)) tt
| Typedtree.Tstr_type ident_type_decl_list ->
List.iter
(fun (id, e) ->
Hashtbl.add table (T (Name.from_ident id))
(Typedtree.Tstr_type [(id,e)]))
ident_type_decl_list
| Typedtree.Tstr_class info_list ->
List.iter
(fun ((id,_,_,_,_) as ci) ->
Hashtbl.add table (C (Name.from_ident id))
(Typedtree.Tstr_class [ci]))
info_list
| Typedtree.Tstr_cltype info_list ->
List.iter
(fun ((id,_) as ci) ->
Hashtbl.add table
(CT (Name.from_ident id))
(Typedtree.Tstr_cltype [ci]))
info_list
| Typedtree.Tstr_value (_, pat_exp_list) ->
List.iter
(fun (pat,exp) ->
match iter_val_pattern pat.Typedtree.pat_desc with
None -> ()
| Some n -> Hashtbl.add table_values n (pat,exp)
)
pat_exp_list
| Typedtree.Tstr_primitive (ident, _) ->
Hashtbl.add table (P (Name.from_ident ident)) tt
| Typedtree.Tstr_open _ -> ()
| Typedtree.Tstr_include _ -> ()
| Typedtree.Tstr_eval _ -> ()
let tables typedtree =
let t = Hashtbl.create 13 in
let t_values = Hashtbl.create 13 in
List.iter (add_to_hashes t t_values) typedtree;
(t, t_values)
let search_module table name =
match Hashtbl.find table (M name) with
(Typedtree.Tstr_module (_, module_expr)) -> module_expr
| _ -> assert false
let search_module_type table name =
match Hashtbl.find table (MT name) with
| (Typedtree.Tstr_modtype (_, module_type)) -> module_type
| _ -> assert false
let search_exception table name =
match Hashtbl.find table (E name) with
| (Typedtree.Tstr_exception (_, excep_decl)) -> excep_decl
| _ -> assert false
let search_exception_rebind table name =
match Hashtbl.find table (ER name) with
| (Typedtree.Tstr_exn_rebind (_, p)) -> p
| _ -> assert false
let search_type_declaration table name =
match Hashtbl.find table (T name) with
| (Typedtree.Tstr_type [(_,decl)]) -> decl
| _ -> assert false
let search_class_exp table name =
match Hashtbl.find table (C name) with
| (Typedtree.Tstr_class [(_,_,_,ce,_)]) ->
(
try
let type_decl = search_type_declaration table name in
(ce, type_decl.Types.type_params)
with
Not_found ->
(ce, [])
)
| _ -> assert false
let search_class_type_declaration table name =
match Hashtbl.find table (CT name) with
| (Typedtree.Tstr_cltype [(_,cltype_decl)]) -> cltype_decl
| _ -> assert false
let search_value table name = Hashtbl.find table name
let search_primitive table name =
match Hashtbl.find table (P name) with
Tstr_primitive (ident, val_desc) -> val_desc.Types.val_type
| _ -> assert false
let get_nth_inherit_class_expr cls n =
let rec iter cpt = function
| [] ->
raise Not_found
| Typedtree.Cf_inher (clexp, _, _) :: q ->
if n = cpt then clexp else iter (cpt+1) q
| _ :: q ->
iter cpt q
in
iter 0 cls.Typedtree.cl_field
let search_attribute_type cls name =
let rec iter = function
| [] ->
raise Not_found
| Typedtree.Cf_val (_, ident, Some exp, _) :: q
when Name.from_ident ident = name ->
exp.Typedtree.exp_type
| _ :: q ->
iter q
in
iter cls.Typedtree.cl_field
let class_sig_of_cltype_decl =
let rec iter = function
Types.Tcty_constr (_, _, cty) -> iter cty
| Types.Tcty_signature s -> s
| Types.Tcty_fun (_,_, cty) -> iter cty
in
fun ct_decl -> iter ct_decl.Types.clty_type
let search_virtual_attribute_type table ctname name =
let ct_decl = search_class_type_declaration table ctname in
let cls_sig = class_sig_of_cltype_decl ct_decl in
let (_,_,texp) = Types.Vars.find name cls_sig.cty_vars in
texp
let search_method_expression cls name =
let rec iter = function
| [] ->
raise Not_found
| Typedtree.Cf_meth (label, exp) :: q when label = name ->
exp
| _ :: q ->
iter q
in
iter cls.Typedtree.cl_field
end
module Analyser =
functor (My_ir : Odoc_sig.Info_retriever) ->
struct
module Sig = Odoc_sig.Analyser (My_ir)
let file = Sig.file
let file_name = Sig.file_name
* This function takes two indexes ( start and end ) and return the string
corresponding to the indexes in the file global variable . The function
prepare_file must have been called to fill the file global variable .
corresponding to the indexes in the file global variable. The function
prepare_file must have been called to fill the file global variable.*)
let get_string_of_file = Sig.get_string_of_file
let prepare_file = Sig.prepare_file
let get_comments_in_class = Sig.get_comments_in_class
let get_comments_in_module = Sig.get_comments_in_module
let tt_param_info_from_pattern env f_desc pat =
let rec iter_pattern pat =
match pat.pat_desc with
Typedtree.Tpat_var ident ->
let name = Name.from_ident ident in
Simple_name { sn_name = name ;
sn_text = f_desc name ;
sn_type = Odoc_env.subst_type env pat.pat_type
}
| Typedtree.Tpat_alias (pat, _) ->
iter_pattern pat
| Typedtree.Tpat_tuple patlist ->
Tuple
(List.map iter_pattern patlist,
Odoc_env.subst_type env pat.pat_type)
| Typedtree.Tpat_construct (cons_desc, _) when
(match cons_desc.cstr_res.desc with
Tconstr (p, _, _) ->
Path.same p Predef.path_unit
| _ ->
false)
->
Simple_name { sn_name = "()" ;
sn_text = None ;
sn_type = Odoc_env.subst_type env pat.pat_type
}
| _ ->
Simple_name { sn_name = "()" ;
sn_text = None ;
sn_type = Odoc_env.subst_type env pat.pat_type
}
in
iter_pattern pat
let rec tt_analyse_function_parameters env current_comment_opt pat_exp_list =
match pat_exp_list with
[] ->
raise (Failure "tt_analyse_function_parameters: 'function' without pattern")
| (pattern_param, exp) :: second_ele :: q ->
let parameter = Odoc_parameter.Tuple ([], Odoc_env.subst_type env pattern_param.pat_type) in
[ parameter ]
| (pattern_param, func_body) :: [] ->
let parameter =
tt_param_info_from_pattern
env
(Odoc_parameter.desc_from_info_opt current_comment_opt)
pattern_param
in
let (p, next_exp) =
match parameter with
Simple_name { sn_name = "*opt*" } ->
(
(
match func_body.exp_desc with
Typedtree.Texp_let (_, ({pat_desc = Typedtree.Tpat_var id } , exp) :: _, func_body2) ->
let name = Name.from_ident id in
let new_param = Simple_name
{ sn_name = name ;
sn_text = Odoc_parameter.desc_from_info_opt current_comment_opt name ;
sn_type = Odoc_env.subst_type env exp.exp_type
}
in
(new_param, func_body2)
| _ ->
print_DEBUG3 "Pas le bon filtre pour le parametre optionnel avec valeur par defaut.";
(parameter, func_body)
)
)
| _ ->
(parameter, func_body)
in
match next_exp.exp_desc with
Texp_function (pat_exp_list, _) ->
p :: (tt_analyse_function_parameters env current_comment_opt pat_exp_list)
| _ ->
[ p ]
let tt_analyse_value env current_module_name comment_opt loc pat_exp rec_flag =
let (pat, exp) = pat_exp in
match (pat.pat_desc, exp.exp_desc) with
(Typedtree.Tpat_var ident, Typedtree.Texp_function (pat_exp_list2, partial)) ->
let name_pre = Name.from_ident ident in
let name = Name.parens_if_infix name_pre in
let complete_name = Name.concat current_module_name name in
let new_value = {
val_name = complete_name ;
val_info = comment_opt ;
val_type = Odoc_env.subst_type env pat.Typedtree.pat_type ;
val_recursive = rec_flag = Asttypes.Recursive ;
val_parameters = tt_analyse_function_parameters env comment_opt pat_exp_list2 ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
[ new_value ]
| (Typedtree.Tpat_var ident, _) ->
let name_pre = Name.from_ident ident in
let name = Name.parens_if_infix name_pre in
let complete_name = Name.concat current_module_name name in
let new_value = {
val_name = complete_name ;
val_info = comment_opt ;
val_type = Odoc_env.subst_type env pat.Typedtree.pat_type ;
val_recursive = rec_flag = Asttypes.Recursive ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
[ new_value ]
| (Typedtree.Tpat_tuple lpat, _) ->
[]
| _ ->
[]
let rec tt_name_of_class_expr clexp =
(
match clexp . Typedtree.cl_desc with
Tclass_ident _ - > prerr_endline " Tclass_ident "
| Tclass_structure _ - > prerr_endline " Tclass_structure "
| Tclass_fun _ - > prerr_endline " Tclass_fun "
| Tclass_apply _ - > prerr_endline " Tclass_apply "
| Tclass_let _ - > prerr_endline " Tclass_let "
| Tclass_constraint _ - > prerr_endline " Tclass_constraint "
) ;
(
match clexp.Typedtree.cl_desc with
Tclass_ident _ -> prerr_endline "Tclass_ident"
| Tclass_structure _ -> prerr_endline "Tclass_structure"
| Tclass_fun _ -> prerr_endline "Tclass_fun"
| Tclass_apply _ -> prerr_endline "Tclass_apply"
| Tclass_let _ -> prerr_endline "Tclass_let"
| Tclass_constraint _ -> prerr_endline "Tclass_constraint"
);
*)
match clexp.Typedtree.cl_desc with
Typedtree.Tclass_ident p -> Name.from_path p
| Typedtree.Tclass_constraint (class_expr, _, _, _)
| Typedtree.Tclass_apply (class_expr, _) -> tt_name_of_class_expr class_expr
| _ -> Odoc_messages.object_end
* Analysis of a method expression to get the method parameters .
@param first indicates if we 're analysing the method for
the first time ; in that case we must not keep the first parameter ,
which is " self- * " , the object itself .
@param first indicates if we're analysing the method for
the first time ; in that case we must not keep the first parameter,
which is "self-*", the object itself.
*)
let rec tt_analyse_method_expression env current_method_name comment_opt ?(first=true) exp =
match exp.Typedtree.exp_desc with
Typedtree.Texp_function (pat_exp_list, _) ->
(
match pat_exp_list with
[] ->
raise (Failure (Odoc_messages.bad_tree^" "^(Odoc_messages.method_without_param current_method_name)))
| l ->
match l with
[] ->
cas impossible , on l'a filtré avant
assert false
| (pattern_param, exp) :: second_ele :: q ->
Note : We ca n't match this pattern if it is the first call to the function .
let new_param = Simple_name
{ sn_name = "??" ; sn_text = None;
sn_type = Odoc_env.subst_type env pattern_param.Typedtree.pat_type }
in
[ new_param ]
| (pattern_param, body) :: [] ->
if this is the first call to the function , this is the first parameter and we skip it
if not first then
(
let parameter =
tt_param_info_from_pattern
env
(Odoc_parameter.desc_from_info_opt comment_opt)
pattern_param
in
let (current_param, next_exp) =
match parameter with
Simple_name { sn_name = "*opt*"} ->
(
(
match body.exp_desc with
Typedtree.Texp_let (_, ({pat_desc = Typedtree.Tpat_var id } , exp) :: _, body2) ->
let name = Name.from_ident id in
let new_param = Simple_name
{ sn_name = name ;
sn_text = Odoc_parameter.desc_from_info_opt comment_opt name ;
sn_type = Odoc_env.subst_type env exp.Typedtree.exp_type ;
}
in
(new_param, body2)
| _ ->
print_DEBUG3 "Pas le bon filtre pour le parametre optionnel avec valeur par defaut.";
(parameter, body)
)
)
| _ ->
(parameter, body)
in
current_param :: (tt_analyse_method_expression env current_method_name comment_opt ~first: false next_exp)
)
else
tt_analyse_method_expression env current_method_name comment_opt ~first: false body
)
| _ ->
[]
* Analysis of a [ Parsetree.class_struture ] and a [ Typedtree.class_structure ] to get a couple
( inherited classes , class elements ) .
(inherited classes, class elements). *)
let analyse_class_structure env current_class_name tt_class_sig last_pos pos_limit p_cls tt_cls table =
let rec iter acc_inher acc_fields last_pos = function
| [] ->
let s = get_string_of_file last_pos pos_limit in
let (_, ele_coms) = My_ir.all_special !file_name s in
let ele_comments =
List.fold_left
(fun acc -> fun sc ->
match sc.Odoc_types.i_desc with
None ->
acc
| Some t ->
acc @ [Class_comment t])
[]
ele_coms
in
(acc_inher, acc_fields @ ele_comments)
| (Parsetree.Pcf_inher (_, p_clexp, _)) :: q ->
let tt_clexp =
let n = List.length acc_inher in
try Typedtree_search.get_nth_inherit_class_expr tt_cls n
with Not_found ->
raise (Failure (
Odoc_messages.inherit_classexp_not_found_in_typedtree n))
in
let (info_opt, ele_comments) =
get_comments_in_class last_pos
p_clexp.Parsetree.pcl_loc.Location.loc_start.Lexing.pos_cnum
in
let text_opt =
match info_opt with None -> None
| Some i -> i.Odoc_types.i_desc in
let name = tt_name_of_class_expr tt_clexp in
let inher =
{
ic_name = Odoc_env.full_class_or_class_type_name env name ;
ic_class = None ;
ic_text = text_opt ;
}
in
iter (acc_inher @ [ inher ]) (acc_fields @ ele_comments)
p_clexp.Parsetree.pcl_loc.Location.loc_end.Lexing.pos_cnum
q
| ((Parsetree.Pcf_val (label, mutable_flag, _, _, loc) |
Parsetree.Pcf_valvirt (label, mutable_flag, _, loc) ) as x) :: q ->
let virt = match x with Parsetree.Pcf_val _ -> false | _ -> true in
let complete_name = Name.concat current_class_name label in
let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
let type_exp =
try
if virt then
Typedtree_search.search_virtual_attribute_type table
(Name.simple current_class_name) label
else
Typedtree_search.search_attribute_type tt_cls label
with Not_found ->
raise (Failure (Odoc_messages.attribute_not_found_in_typedtree complete_name))
in
let att =
{
att_value = { val_name = complete_name ;
val_info = info_opt ;
val_type = Odoc_env.subst_type env type_exp ;
val_recursive = false ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
} ;
att_mutable = mutable_flag = Asttypes.Mutable ;
att_virtual = virt ;
}
in
iter acc_inher (acc_fields @ ele_comments @ [ Class_attribute att ]) loc.Location.loc_end.Lexing.pos_cnum q
| (Parsetree.Pcf_virt (label, private_flag, _, loc)) :: q ->
let complete_name = Name.concat current_class_name label in
let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
let met_type =
try Odoc_sig.Signature_search.search_method_type label tt_class_sig
with Not_found -> raise (Failure (Odoc_messages.method_type_not_found current_class_name label))
in
let real_type =
match met_type.Types.desc with
Tarrow (_, _, t, _) ->
t
| _ ->
met_type
in
let met =
{
met_value = { val_name = complete_name ;
val_info = info_opt ;
val_type = Odoc_env.subst_type env real_type ;
val_recursive = false ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
} ;
met_private = private_flag = Asttypes.Private ;
met_virtual = true ;
}
in
Odoc_value.update_value_parameters_text met.met_value;
iter acc_inher (acc_fields @ ele_comments @ [ Class_method met ]) loc.Location.loc_end.Lexing.pos_cnum q
| (Parsetree.Pcf_meth (label, private_flag, _, _, loc)) :: q ->
let complete_name = Name.concat current_class_name label in
let (info_opt, ele_comments) = get_comments_in_class last_pos loc.Location.loc_start.Lexing.pos_cnum in
let exp =
try Typedtree_search.search_method_expression tt_cls label
with Not_found -> raise (Failure (Odoc_messages.method_not_found_in_typedtree complete_name))
in
let real_type =
match exp.exp_type.desc with
Tarrow (_, _, t,_) ->
t
| _ ->
exp.Typedtree.exp_type
in
let met =
{
met_value = { val_name = complete_name ;
val_info = info_opt ;
val_type = Odoc_env.subst_type env real_type ;
val_recursive = false ;
val_parameters = tt_analyse_method_expression env complete_name info_opt exp ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
} ;
met_private = private_flag = Asttypes.Private ;
met_virtual = false ;
}
in
Odoc_value.update_value_parameters_text met.met_value;
iter acc_inher (acc_fields @ ele_comments @ [ Class_method met ]) loc.Location.loc_end.Lexing.pos_cnum q
| Parsetree.Pcf_cstr (_, _, loc) :: q ->
iter acc_inher acc_fields loc.Location.loc_end.Lexing.pos_cnum q
| Parsetree.Pcf_let (_, _, loc) :: q ->
iter acc_inher acc_fields loc.Location.loc_end.Lexing.pos_cnum q
| (Parsetree.Pcf_init exp) :: q ->
iter acc_inher acc_fields exp.Parsetree.pexp_loc.Location.loc_end.Lexing.pos_cnum q
in
iter [] [] last_pos (snd p_cls)
* Analysis of a [ Parsetree.class_expr ] and a [ Typedtree.class_expr ] to get a a couple ( class parameters , class kind ) .
let rec analyse_class_kind env current_class_name comment_opt last_pos p_class_expr tt_class_exp table =
match (p_class_expr.Parsetree.pcl_desc, tt_class_exp.Typedtree.cl_desc) with
(Parsetree.Pcl_constr (lid, _), tt_class_exp_desc ) ->
let name =
match tt_class_exp_desc with
Typedtree.Tclass_ident p -> Name.from_path p
| _ ->
A VOIR : dommage qu'on n'ait pas un Tclass_ident :-( même quand on a class tutu = toto
Name.from_longident lid
in
On n'a pas ici les paramètres de type sous forme ,
par contre on peut les trouver dans le class_type
par contre on peut les trouver dans le class_type *)
let params =
match tt_class_exp.Typedtree.cl_type with
Types.Tcty_constr (p2, type_exp_list, cltyp) ->
cltyp is the class type for [ type_exp_list ] p
type_exp_list
| _ ->
[]
in
([],
Class_constr
{
cco_name = Odoc_env.full_class_name env name ;
cco_class = None ;
cco_type_parameters = List.map (Odoc_env.subst_type env) params ;
} )
| (Parsetree.Pcl_structure p_class_structure, Typedtree.Tclass_structure tt_class_structure) ->
let tt_class_sig =
match tt_class_exp.Typedtree.cl_type with
Types.Tcty_signature class_sig -> class_sig
| _ -> raise (Failure "analyse_class_kind: no class signature for a class structure.")
in
let (inherited_classes, class_elements) = analyse_class_structure
env
current_class_name
tt_class_sig
last_pos
p_class_expr.Parsetree.pcl_loc.Location.loc_end.Lexing.pos_cnum
p_class_structure
tt_class_structure
table
in
([],
Class_structure (inherited_classes, class_elements) )
| (Parsetree.Pcl_fun (label, expression_opt, pattern, p_class_expr2),
Typedtree.Tclass_fun (pat, ident_exp_list, tt_class_expr2, partial)) ->
let (parameter, next_tt_class_exp) =
match pat.Typedtree.pat_desc with
Typedtree.Tpat_var ident when Name.from_ident ident = "*opt*" ->
(
match tt_class_expr2.Typedtree.cl_desc with
Typedtree.Tclass_let (_, ({pat_desc = Typedtree.Tpat_var id } , exp) :: _, _, tt_class_expr3) ->
let name = Name.from_ident id in
let new_param = Simple_name
{ sn_name = name ;
sn_text = Odoc_parameter.desc_from_info_opt comment_opt name ;
sn_type = Odoc_env.subst_type env exp.exp_type
}
in
(new_param, tt_class_expr3)
| _ ->
raise (Failure "analyse_class_kind: strange case")
)
| _ ->
let new_param =
tt_param_info_from_pattern
env
(Odoc_parameter.desc_from_info_opt comment_opt)
pat
in
(new_param, tt_class_expr2)
in
let (params, k) = analyse_class_kind
env current_class_name comment_opt last_pos p_class_expr2
next_tt_class_exp table
in
(parameter :: params, k)
| (Parsetree.Pcl_apply (p_class_expr2, _), Tclass_apply (tt_class_expr2, exp_opt_optional_list)) ->
let applied_name =
match tt_class_expr2.Typedtree.cl_desc with
| _ ->
A VOIR : dommage qu'on n'ait pas un Tclass_ident :-( même quand on a class tutu = toto
match p_class_expr2.Parsetree.pcl_desc with
Parsetree.Pcl_constr (lid, _) ->
Name.from_longident lid
| _ ->
Odoc_messages.object_end
in
let param_exps = List.fold_left
(fun acc -> fun (exp_opt, _) ->
match exp_opt with
None -> acc
| Some e -> acc @ [e])
[]
exp_opt_optional_list
in
let param_types = List.map (fun e -> e.Typedtree.exp_type) param_exps in
let params_code =
List.map
(fun e -> get_string_of_file
e.exp_loc.Location.loc_start.Lexing.pos_cnum
e.exp_loc.Location.loc_end.Lexing.pos_cnum)
param_exps
in
([],
Class_apply
{ capp_name = Odoc_env.full_class_name env applied_name ;
capp_class = None ;
capp_params = param_types ;
capp_params_code = params_code ;
} )
| (Parsetree.Pcl_let (_, _, p_class_expr2), Typedtree.Tclass_let (_, _, _, tt_class_expr2)) ->
analyse_class_kind
env current_class_name comment_opt last_pos p_class_expr2
tt_class_expr2 table
| (Parsetree.Pcl_constraint (p_class_expr2, p_class_type2),
Typedtree.Tclass_constraint (tt_class_expr2, _, _, _)) ->
let (l, class_kind) = analyse_class_kind
env current_class_name comment_opt last_pos p_class_expr2
tt_class_expr2 table
in
let class_type_kind =
Class_type { cta_name = Odoc_messages.object_end ;
cta_class = None ; cta_type_parameters = [] }
in
(l, Class_constraint (class_kind, class_type_kind))
| _ ->
raise (Failure "analyse_class_kind: Parsetree and typedtree don't match.")
let analyse_class env current_module_name comment_opt p_class_decl tt_type_params tt_class_exp table =
let name = p_class_decl.Parsetree.pci_name in
let complete_name = Name.concat current_module_name name in
let pos_start = p_class_decl.Parsetree.pci_expr.Parsetree.pcl_loc.Location.loc_start.Lexing.pos_cnum in
let type_parameters = tt_type_params in
let virt = p_class_decl.Parsetree.pci_virt = Asttypes.Virtual in
let cltype = Odoc_env.subst_class_type env tt_class_exp.Typedtree.cl_type in
let (parameters, kind) = analyse_class_kind
env
complete_name
comment_opt
pos_start
p_class_decl.Parsetree.pci_expr
tt_class_exp
table
in
let cl =
{
cl_name = complete_name ;
cl_info = comment_opt ;
cl_type = cltype ;
cl_virtual = virt ;
cl_type_parameters = type_parameters ;
cl_kind = kind ;
cl_parameters = parameters ;
cl_loc = { loc_impl = Some (!file_name, pos_start) ; loc_inter = None } ;
}
in
cl
let rec tt_name_from_module_expr mod_expr =
match mod_expr.Typedtree.mod_desc with
Typedtree.Tmod_ident p -> Name.from_path p
| Typedtree.Tmod_constraint (m_exp, _, _) -> tt_name_from_module_expr m_exp
| Typedtree.Tmod_structure _
| Typedtree.Tmod_functor _
| Typedtree.Tmod_apply _
| Typedtree.Tmod_unpack _ ->
Odoc_messages.struct_end
let tt_get_included_module_list tt_structure =
let f acc item =
match item with
Typedtree.Tstr_include (mod_expr, _) ->
acc @ [
A VOIR : chercher dans les modules et les module types , env ?
im_name = tt_name_from_module_expr mod_expr ;
im_module = None ;
im_info = None ;
}
]
| _ ->
acc
in
List.fold_left f [] tt_structure
let replace_dummy_included_modules module_elements included_modules =
let rec f = function
| ([], _) ->
[]
| ((Element_included_module im) :: q, (im_repl :: im_q)) ->
(Element_included_module { im_repl with im_info = im.im_info })
:: (f (q, im_q))
| ((Element_included_module im) :: q, []) ->
(Element_included_module im) :: q
| (ele :: q, l) ->
ele :: (f (q, l))
in
f (module_elements, included_modules)
let rec filter_module_with_module_type_constraint m mt =
match m.m_kind, mt with
Module_struct l, Types.Tmty_signature lsig ->
m.m_kind <- Module_struct (filter_module_elements_with_module_type_constraint l lsig);
m.m_type <- mt;
| _ -> ()
and filter_module_type_with_module_type_constraint mtyp mt =
match mtyp.mt_kind, mt with
Some Module_type_struct l, Types.Tmty_signature lsig ->
mtyp.mt_kind <- Some (Module_type_struct (filter_module_elements_with_module_type_constraint l lsig));
mtyp.mt_type <- Some mt;
| _ -> ()
and filter_module_elements_with_module_type_constraint l lsig =
let pred ele =
let f = match ele with
Element_module m ->
(function
Types.Tsig_module (ident,t,_) ->
let n1 = Name.simple m.m_name
and n2 = Ident.name ident in
(
match n1 = n2 with
true -> filter_module_with_module_type_constraint m t; true
| false -> false
)
| _ -> false)
| Element_module_type mt ->
(function
Types.Tsig_modtype (ident,Types.Tmodtype_manifest t) ->
let n1 = Name.simple mt.mt_name
and n2 = Ident.name ident in
(
match n1 = n2 with
true -> filter_module_type_with_module_type_constraint mt t; true
| false -> false
)
| _ -> false)
| Element_value v ->
(function
Types.Tsig_value (ident,_) ->
let n1 = Name.simple v.val_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_type t ->
(function
Types.Tsig_type (ident,_,_) ->
let n1 = Name.simple t.ty_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_exception e ->
(function
Types.Tsig_exception (ident,_) ->
let n1 = Name.simple e.ex_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_class c ->
(function
Types.Tsig_class (ident,_,_) ->
let n1 = Name.simple c.cl_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_class_type ct ->
(function
Types.Tsig_cltype (ident,_,_) ->
let n1 = Name.simple ct.clt_name
and n2 = Ident.name ident in
n1 = n2
| _ -> false)
| Element_module_comment _ -> fun _ -> true
| Element_included_module _ -> fun _ -> true
in
List.exists f lsig
in
List.filter pred l
let rec analyse_structure env current_module_name last_pos pos_limit parsetree typedtree =
print_DEBUG "Odoc_ast:analyse_struture";
let (table, table_values) = Typedtree_search.tables typedtree in
let rec iter env last_pos = function
[] ->
let s = get_string_of_file last_pos pos_limit in
let (_, ele_coms) = My_ir.all_special !file_name s in
let ele_comments =
List.fold_left
(fun acc -> fun sc ->
match sc.Odoc_types.i_desc with
None ->
acc
| Some t ->
acc @ [Element_module_comment t])
[]
ele_coms
in
ele_comments
| item :: q ->
let (comment_opt, ele_comments) =
get_comments_in_module last_pos item.Parsetree.pstr_loc.Location.loc_start.Lexing.pos_cnum
in
let pos_limit2 =
match q with
[] -> pos_limit
| item2 :: _ -> item2.Parsetree.pstr_loc.Location.loc_start.Lexing.pos_cnum
in
let (maybe_more, new_env, elements) = analyse_structure_item
env
current_module_name
item.Parsetree.pstr_loc
pos_limit2
comment_opt
item.Parsetree.pstr_desc
typedtree
table
table_values
in
ele_comments @ elements @ (iter new_env (item.Parsetree.pstr_loc.Location.loc_end.Lexing.pos_cnum + maybe_more) q)
in
iter env last_pos parsetree
and analyse_structure_item env current_module_name loc pos_limit comment_opt parsetree_item_desc typedtree
table table_values =
print_DEBUG "Odoc_ast:analyse_struture_item";
match parsetree_item_desc with
Parsetree.Pstr_eval _ ->
(0, env, [])
| Parsetree.Pstr_value (rec_flag, pat_exp_list) ->
of rec_flag * ( pattern * expression ) list
let rec iter_pat = function
| Parsetree.Ppat_any -> None
| Parsetree.Ppat_var name -> Some name
| Parsetree.Ppat_constraint (pat, _) -> iter_pat pat.Parsetree.ppat_desc
| _ -> None
in
let rec iter ?(first=false) last_pos acc_env acc p_e_list =
match p_e_list with
[] ->
(acc_env, acc)
| (pat, exp) :: q ->
let value_name_opt = iter_pat pat.Parsetree.ppat_desc in
let new_last_pos = exp.Parsetree.pexp_loc.Location.loc_end.Lexing.pos_cnum in
match value_name_opt with
None ->
iter new_last_pos acc_env acc q
| Some name ->
try
let pat_exp = Typedtree_search.search_value table_values name in
let (info_opt, ele_comments) =
we already have the optional comment for the first value .
if first then
(comment_opt, [])
else
get_comments_in_module
last_pos
pat.Parsetree.ppat_loc.Location.loc_start.Lexing.pos_cnum
in
let l_values = tt_analyse_value
env
current_module_name
info_opt
loc
pat_exp
rec_flag
in
let new_env = List.fold_left
(fun e -> fun v ->
Odoc_env.add_value e v.val_name
)
acc_env
l_values
in
let l_ele = List.map (fun v -> Element_value v) l_values in
iter
new_last_pos
new_env
(acc @ ele_comments @ l_ele)
q
with
Not_found ->
iter new_last_pos acc_env acc q
in
let (new_env, l_ele) = iter ~first: true loc.Location.loc_start.Lexing.pos_cnum env [] pat_exp_list in
(0, new_env, l_ele)
| Parsetree.Pstr_primitive (name_pre, val_desc) ->
print_DEBUG ("Parsetree.Pstr_primitive ("^name_pre^", ["^(String.concat ", " val_desc.Parsetree.pval_prim)^"]");
let typ = Typedtree_search.search_primitive table name_pre in
let name = Name.parens_if_infix name_pre in
let complete_name = Name.concat current_module_name name in
let new_value = {
val_name = complete_name ;
val_info = comment_opt ;
val_type = Odoc_env.subst_type env typ ;
val_recursive = false ;
val_parameters = [] ;
val_code = Some (get_string_of_file loc.Location.loc_start.Lexing.pos_cnum loc.Location.loc_end.Lexing.pos_cnum) ;
val_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
let new_env = Odoc_env.add_value env new_value.val_name in
(0, new_env, [Element_value new_value])
| Parsetree.Pstr_type name_typedecl_list ->
let new_env =
List.fold_left
(fun acc_env -> fun (name, _) ->
let complete_name = Name.concat current_module_name name in
Odoc_env.add_type acc_env complete_name
)
env
name_typedecl_list
in
let rec f ?(first=false) maybe_more_acc last_pos name_type_decl_list =
match name_type_decl_list with
[] -> (maybe_more_acc, [])
| (name, type_decl) :: q ->
let complete_name = Name.concat current_module_name name in
let loc_start = type_decl.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = type_decl.Parsetree.ptype_loc.Location.loc_end.Lexing.pos_cnum in
let pos_limit2 =
match q with
[] -> pos_limit
| (_, td) :: _ -> td.Parsetree.ptype_loc.Location.loc_start.Lexing.pos_cnum
in
let (maybe_more, name_comment_list) =
Sig.name_comment_from_type_kind
loc_end
pos_limit2
type_decl.Parsetree.ptype_kind
in
let tt_type_decl =
try Typedtree_search.search_type_declaration table name
with Not_found -> raise (Failure (Odoc_messages.type_not_found_in_typedtree complete_name))
in
the comment for the first type was already retrieved
if first then
(comment_opt , [])
else
get_comments_in_module last_pos loc_start
in
let kind = Sig.get_type_kind
new_env name_comment_list
tt_type_decl.Types.type_kind
in
let new_end = loc_end + maybe_more in
let t =
{
ty_name = complete_name ;
ty_info = com_opt ;
ty_parameters =
List.map2
(fun p (co,cn,_) ->
(Odoc_env.subst_type new_env p,
co, cn)
)
tt_type_decl.Types.type_params
tt_type_decl.Types.type_variance ;
ty_kind = kind ;
ty_private = tt_type_decl.Types.type_private;
ty_manifest =
(match tt_type_decl.Types.type_manifest with
None -> None
| Some t -> Some (Odoc_env.subst_type new_env t));
ty_loc = { loc_impl = Some (!file_name, loc_start) ; loc_inter = None } ;
ty_code =
(
if !Odoc_global.keep_code then
Some (get_string_of_file loc_start new_end)
else
None
) ;
}
in
let (maybe_more2, info_after_opt) =
My_ir.just_after_special
!file_name
(get_string_of_file new_end pos_limit2)
in
t.ty_info <- Sig.merge_infos t.ty_info info_after_opt ;
let (maybe_more3, eles) = f (maybe_more + maybe_more2) (new_end + maybe_more2) q in
(maybe_more3, ele_comments @ ((Element_type t) :: eles))
in
let (maybe_more, eles) = f ~first: true 0 loc.Location.loc_start.Lexing.pos_cnum name_typedecl_list in
(maybe_more, new_env, eles)
| Parsetree.Pstr_exception (name, excep_decl) ->
let complete_name = Name.concat current_module_name name in
let tt_excep_decl =
try Typedtree_search.search_exception table name
with Not_found ->
raise (Failure (Odoc_messages.exception_not_found_in_typedtree complete_name))
in
let new_env = Odoc_env.add_exception env complete_name in
let loc_start = loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
let new_ex =
{
ex_name = complete_name ;
ex_info = comment_opt ;
ex_args = List.map (Odoc_env.subst_type new_env) tt_excep_decl ;
ex_alias = None ;
ex_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
ex_code =
(
if !Odoc_global.keep_code then
Some (get_string_of_file loc_start loc_end)
else
None
) ;
}
in
(0, new_env, [ Element_exception new_ex ])
| Parsetree.Pstr_exn_rebind (name, _) ->
let complete_name = Name.concat current_module_name name in
let tt_path =
try Typedtree_search.search_exception_rebind table name
with Not_found ->
raise (Failure (Odoc_messages.exception_not_found_in_typedtree complete_name))
in
let new_env = Odoc_env.add_exception env complete_name in
let new_ex =
{
ex_name = complete_name ;
ex_info = comment_opt ;
ex_args = [] ;
ex_alias = Some { ea_name = (Odoc_env.full_exception_name env (Name.from_path tt_path)) ;
ea_ex = None ; } ;
ex_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
ex_code = None ;
}
in
(0, new_env, [ Element_exception new_ex ])
| Parsetree.Pstr_module (name, module_expr) ->
(
try
let tt_module_expr = Typedtree_search.search_module table name in
let new_module_pre = analyse_module
env
current_module_name
name
comment_opt
module_expr
tt_module_expr
in
let code =
if !Odoc_global.keep_code then
let loc = module_expr.Parsetree.pmod_loc in
let st = loc.Location.loc_start.Lexing.pos_cnum in
let en = loc.Location.loc_end.Lexing.pos_cnum in
Some (get_string_of_file st en)
else
None
in
let new_module =
{ new_module_pre with m_code = code }
in
let new_env = Odoc_env.add_module env new_module.m_name in
let new_env2 =
match new_module.m_type with
A VOIR : ? dans ce cas , on aurait pas la signature
Types.Tmty_signature s ->
Odoc_env.add_signature new_env new_module.m_name
~rel: (Name.simple new_module.m_name) s
| _ ->
new_env
in
(0, new_env2, [ Element_module new_module ])
with
Not_found ->
let complete_name = Name.concat current_module_name name in
raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
)
| Parsetree.Pstr_recmodule mods ->
A VOIR ICI pb : pas de lien avec les module type
dans les contraintes sur les modules
dans les contraintes sur les modules *)
let new_env =
List.fold_left
(fun acc_env (name, _, mod_exp) ->
let complete_name = Name.concat current_module_name name in
let e = Odoc_env.add_module acc_env complete_name in
let tt_mod_exp =
try Typedtree_search.search_module table name
with Not_found -> raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
in
let new_module = analyse_module
e
current_module_name
name
None
mod_exp
tt_mod_exp
in
match new_module.m_type with
Types.Tmty_signature s ->
Odoc_env.add_signature e new_module.m_name
~rel: (Name.simple new_module.m_name) s
| _ ->
e
)
env
mods
in
let rec f ?(first=false) last_pos name_mod_exp_list =
match name_mod_exp_list with
[] -> []
| (name, _, mod_exp) :: q ->
let complete_name = Name.concat current_module_name name in
let loc_start = mod_exp.Parsetree.pmod_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = mod_exp.Parsetree.pmod_loc.Location.loc_end.Lexing.pos_cnum in
let tt_mod_exp =
try Typedtree_search.search_module table name
with Not_found -> raise (Failure (Odoc_messages.module_not_found_in_typedtree complete_name))
in
the comment for the first type was already retrieved
if first then
(comment_opt, [])
else
get_comments_in_module last_pos loc_start
in
let new_module = analyse_module
new_env
current_module_name
name
com_opt
mod_exp
tt_mod_exp
in
let eles = f loc_end q in
ele_comments @ ((Element_module new_module) :: eles)
in
let eles = f ~first: true loc.Location.loc_start.Lexing.pos_cnum mods in
(0, new_env, eles)
| Parsetree.Pstr_modtype (name, modtype) ->
let complete_name = Name.concat current_module_name name in
let tt_module_type =
try Typedtree_search.search_module_type table name
with Not_found ->
raise (Failure (Odoc_messages.module_type_not_found_in_typedtree complete_name))
in
let kind = Sig.analyse_module_type_kind env complete_name
modtype tt_module_type
in
let mt =
{
mt_name = complete_name ;
mt_info = comment_opt ;
mt_type = Some tt_module_type ;
mt_is_interface = false ;
mt_file = !file_name ;
mt_kind = Some kind ;
mt_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ; loc_inter = None } ;
}
in
let new_env = Odoc_env.add_module_type env mt.mt_name in
let new_env2 =
match tt_module_type with
A VOIR : ? dans ce cas , on n'aurait pas la signature
Types.Tmty_signature s ->
Odoc_env.add_signature new_env mt.mt_name ~rel: (Name.simple mt.mt_name) s
| _ ->
new_env
in
(0, new_env2, [ Element_module_type mt ])
| Parsetree.Pstr_open longident ->
let ele_comments = match comment_opt with
None -> []
| Some i ->
match i.i_desc with
None -> []
| Some t -> [Element_module_comment t]
in
(0, env, ele_comments)
| Parsetree.Pstr_class class_decl_list ->
let new_env =
List.fold_left
(fun acc_env -> fun class_decl ->
let complete_name = Name.concat current_module_name class_decl.Parsetree.pci_name in
Odoc_env.add_class acc_env complete_name
)
env
class_decl_list
in
let rec f ?(first=false) last_pos class_decl_list =
match class_decl_list with
[] ->
[]
| class_decl :: q ->
let (tt_class_exp, tt_type_params) =
try Typedtree_search.search_class_exp table class_decl.Parsetree.pci_name
with Not_found ->
let complete_name = Name.concat current_module_name class_decl.Parsetree.pci_name in
raise (Failure (Odoc_messages.class_not_found_in_typedtree complete_name))
in
let (com_opt, ele_comments) =
if first then
(comment_opt, [])
else
get_comments_in_module last_pos class_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
in
let last_pos2 = class_decl.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
let new_class = analyse_class
new_env
current_module_name
com_opt
class_decl
tt_type_params
tt_class_exp
table
in
ele_comments @ ((Element_class new_class) :: (f last_pos2 q))
in
(0, new_env, f ~first: true loc.Location.loc_start.Lexing.pos_cnum class_decl_list)
| Parsetree.Pstr_class_type class_type_decl_list ->
let new_env =
List.fold_left
(fun acc_env -> fun class_type_decl ->
let complete_name = Name.concat current_module_name class_type_decl.Parsetree.pci_name in
Odoc_env.add_class_type acc_env complete_name
)
env
class_type_decl_list
in
let rec f ?(first=false) last_pos class_type_decl_list =
match class_type_decl_list with
[] ->
[]
| class_type_decl :: q ->
let name = class_type_decl.Parsetree.pci_name in
let complete_name = Name.concat current_module_name name in
let virt = class_type_decl.Parsetree.pci_virt = Asttypes.Virtual in
let tt_cltype_declaration =
try Typedtree_search.search_class_type_declaration table name
with Not_found ->
raise (Failure (Odoc_messages.class_type_not_found_in_typedtree complete_name))
in
let type_params = tt_cltype_declaration.Types.clty_params in
let kind = Sig.analyse_class_type_kind
new_env
complete_name
class_type_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
class_type_decl.Parsetree.pci_expr
tt_cltype_declaration.Types.clty_type
in
let (com_opt, ele_comments) =
if first then
(comment_opt, [])
else
get_comments_in_module last_pos class_type_decl.Parsetree.pci_loc.Location.loc_start.Lexing.pos_cnum
in
let last_pos2 = class_type_decl.Parsetree.pci_loc.Location.loc_end.Lexing.pos_cnum in
let new_ele =
Element_class_type
{
clt_name = complete_name ;
clt_info = com_opt ;
clt_type = Odoc_env.subst_class_type env tt_cltype_declaration.Types.clty_type ;
clt_type_parameters = List.map (Odoc_env.subst_type new_env) type_params ;
clt_virtual = virt ;
clt_kind = kind ;
clt_loc = { loc_impl = Some (!file_name, loc.Location.loc_start.Lexing.pos_cnum) ;
loc_inter = None } ;
}
in
ele_comments @ (new_ele :: (f last_pos2 q))
in
(0, new_env, f ~first: true loc.Location.loc_start.Lexing.pos_cnum class_type_decl_list)
| Parsetree.Pstr_include module_expr ->
let im =
{
im_name = "dummy" ;
im_module = None ;
im_info = comment_opt ;
}
in
and analyse_module env current_module_name module_name comment_opt p_module_expr tt_module_expr =
let complete_name = Name.concat current_module_name module_name in
let pos_start = p_module_expr.Parsetree.pmod_loc.Location.loc_start.Lexing.pos_cnum in
let pos_end = p_module_expr.Parsetree.pmod_loc.Location.loc_end.Lexing.pos_cnum in
let modtype =
tt_module_expr.Typedtree.mod_type
in
let m_code_intf =
match p_module_expr.Parsetree.pmod_desc with
Parsetree.Pmod_constraint (_, pmodule_type) ->
let loc_start = pmodule_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = pmodule_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
Some (get_string_of_file loc_start loc_end)
| _ ->
None
in
let m_base =
{
m_name = complete_name ;
m_type = modtype ;
m_info = comment_opt ;
m_is_interface = false ;
m_file = !file_name ;
m_kind = Module_struct [] ;
m_loc = { loc_impl = Some (!file_name, pos_start) ; loc_inter = None } ;
m_top_deps = [] ;
m_code_intf = m_code_intf ;
m_text_only = false ;
}
in
match (p_module_expr.Parsetree.pmod_desc, tt_module_expr.Typedtree.mod_desc) with
(Parsetree.Pmod_ident longident, Typedtree.Tmod_ident path) ->
let alias_name = Odoc_env.full_module_name env (Name.from_path path) in
{ m_base with m_kind = Module_alias { ma_name = alias_name ;
ma_module = None ; } }
| (Parsetree.Pmod_structure p_structure, Typedtree.Tmod_structure tt_structure) ->
let elements = analyse_structure env complete_name pos_start pos_end p_structure tt_structure in
let included_modules_from_tt = tt_get_included_module_list tt_structure in
let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
{ m_base with m_kind = Module_struct elements2 }
| (Parsetree.Pmod_functor (_, pmodule_type, p_module_expr2),
Typedtree.Tmod_functor (ident, mtyp, tt_module_expr2)) ->
let loc_start = pmodule_type.Parsetree.pmty_loc.Location.loc_start.Lexing.pos_cnum in
let loc_end = pmodule_type.Parsetree.pmty_loc.Location.loc_end.Lexing.pos_cnum in
let mp_type_code = get_string_of_file loc_start loc_end in
print_DEBUG (Printf.sprintf "mp_type_code=%s" mp_type_code);
let mp_name = Name.from_ident ident in
let mp_kind = Sig.analyse_module_type_kind env
current_module_name pmodule_type mtyp
in
let param =
{
mp_name = mp_name ;
mp_type = Odoc_env.subst_module_type env mtyp ;
mp_type_code = mp_type_code ;
mp_kind = mp_kind ;
}
in
let new_env = Odoc_env.add_module env dummy_complete_name in
let m_base2 = analyse_module
new_env
current_module_name
module_name
None
p_module_expr2
tt_module_expr2
in
let kind = m_base2.m_kind in
{ m_base with m_kind = Module_functor (param, kind) }
| (Parsetree.Pmod_apply (p_module_expr1, p_module_expr2),
Typedtree.Tmod_apply (tt_module_expr1, tt_module_expr2, _))
| (Parsetree.Pmod_apply (p_module_expr1, p_module_expr2),
Typedtree.Tmod_constraint
({ Typedtree.mod_desc = Typedtree.Tmod_apply (tt_module_expr1, tt_module_expr2, _)},
_, _)
) ->
let m1 = analyse_module
env
current_module_name
module_name
None
p_module_expr1
tt_module_expr1
in
let m2 = analyse_module
env
current_module_name
module_name
None
p_module_expr2
tt_module_expr2
in
{ m_base with m_kind = Module_apply (m1.m_kind, m2.m_kind) }
| (Parsetree.Pmod_constraint (p_module_expr2, p_modtype),
Typedtree.Tmod_constraint (tt_module_expr2, tt_modtype, _)) ->
print_DEBUG ("Odoc_ast: case Parsetree.Pmod_constraint + Typedtree.Tmod_constraint "^module_name);
let m_base2 = analyse_module
env
current_module_name
module_name
None
p_module_expr2
tt_module_expr2
in
let mtkind = Sig.analyse_module_type_kind env
(Name.concat current_module_name "??")
p_modtype tt_modtype
in
let tt_modtype = Odoc_env.subst_module_type env tt_modtype in
if !Odoc_global.filter_with_module_constraints then
filter_module_with_module_type_constraint m_base2 tt_modtype;
{
m_base with
m_type = tt_modtype ;
m_kind = Module_constraint (m_base2.m_kind, mtkind) ;
}
| (Parsetree.Pmod_structure p_structure,
Typedtree.Tmod_constraint
({ Typedtree.mod_desc = Typedtree.Tmod_structure tt_structure},
tt_modtype, _)
) ->
print_DEBUG ("Odoc_ast: case Parsetree.Pmod_structure + Typedtree.Tmod_constraint "^module_name);
let elements = analyse_structure env complete_name pos_start pos_end p_structure tt_structure in
let included_modules_from_tt = tt_get_included_module_list tt_structure in
let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
{ m_base with
m_type = Odoc_env.subst_module_type env tt_modtype ;
m_kind = Module_struct elements2 ;
}
| (Parsetree.Pmod_unpack (p_exp),
Typedtree.Tmod_unpack (t_exp, tt_modtype)) ->
print_DEBUG ("Odoc_ast: case Parsetree.Pmod_unpack + Typedtree.Tmod_unpack "^module_name);
let code =
let loc = p_module_expr.Parsetree.pmod_loc in
let loc_end = loc.Location.loc_end.Lexing.pos_cnum in
let exp_loc = p_exp.Parsetree.pexp_loc in
let exp_loc_end = exp_loc.Location.loc_end.Lexing.pos_cnum in
let s = get_string_of_file exp_loc_end loc_end in
Printf.sprintf "(val ...%s" s
in
let name = Odoc_env.full_module_type_name env ( Name.from_path ( fst pkg_type ) ) in
let name =
match tt_modtype with
| Tmty_ident p ->
Odoc_env.full_module_type_name env (Name.from_path p)
| _ -> ""
in
let alias = { mta_name = name ; mta_module = None } in
{ m_base with
m_type = Odoc_env.subst_module_type env tt_modtype ;
m_kind = Module_unpack (code, alias) ;
}
| (parsetree, typedtree) ->
print_DEBUG (Printf.sprintf "code=%s\ns_parse=%s\ns_typed=%s\n" code s_parse s_typed);
raise (Failure "analyse_module: parsetree and typedtree don't match.")
let analyse_typed_tree source_file input_file
(parsetree : Parsetree.structure) (typedtree : typedtree) =
let (tree_structure, _) = typedtree in
let complete_source_file =
try
let curdir = Sys.getcwd () in
let (dirname, basename) = (Filename.dirname source_file, Filename.basename source_file) in
Sys.chdir dirname ;
let complete = Filename.concat (Sys.getcwd ()) basename in
Sys.chdir curdir ;
complete
with
Sys_error s ->
prerr_endline s ;
incr Odoc_global.errors ;
source_file
in
prepare_file complete_source_file input_file;
let mod_name = String.capitalize (Filename.basename (Filename.chop_extension source_file)) in
let (len,info_opt) = My_ir.first_special !file_name !file in
let elements = analyse_structure Odoc_env.empty mod_name len (String.length !file) parsetree tree_structure in
let included_modules_from_tt = tt_get_included_module_list tree_structure in
let elements2 = replace_dummy_included_modules elements included_modules_from_tt in
let kind = Module_struct elements2 in
{
m_name = mod_name ;
m_type = Types.Tmty_signature [] ;
m_info = info_opt ;
m_is_interface = false ;
m_file = !file_name ;
m_kind = kind ;
m_loc = { loc_impl = Some (!file_name, 0) ; loc_inter = None } ;
m_top_deps = [] ;
m_code = (if !Odoc_global.keep_code then Some !file else None) ;
m_code_intf = None ;
m_text_only = false ;
}
end
|
b03e400268177d9b899aa90288cfebd07eabd9221cef13c4ba2f3d2c5b19d614 | Elzair/nazghul | special.scm | ;;----------------------------------------------------------------------------
Special -- one - off stuff that needs to be kern - loaded and does n't really fit
;; anywhere else.
;;----------------------------------------------------------------------------
(kern-mk-sprite-set 'ss_special 32 32 3 3 0 0 "gfx/special.png")
(kern-mk-sprite 's_gold_skull ss_special 1 0 #f 0)
(kern-mk-sprite 's_power_core ss_special 1 1 #f 0)
;;----------------------------------------------------------------------------
generator -- procedure invoked by a step trigger to create
Angriss 's Lair . Should return true iff it triggers to remove the step
;; generator that invokes it.
;;----------------------------------------------------------------------------
(define angriss-lair-loc (list 'p_shard 89 70))
(define (mk-angriss-lair kbeing)
(if (eqv? kbeing
(kern-get-player))
(begin
(kern-log-msg "You find the entrance to Angriss's Lair!")
(kern-place-set-subplace p_angriss_lair
(eval-loc angriss-lair-loc))
(kern-map-set-dirty)
#t)
#f))
;; ----------------------------------------------------------------------------
The 's note
;; ----------------------------------------------------------------------------
(mk-reusable-item
't_warritrix_orders "Military Orders" s_lexicon norm
(lambda (klexicon kuser)
(kern-ui-page-text
"Orders to the Warritrix"
"Ever faithful servant of Glasdrin,"
"we suspect a coven of the Accursed are hiding"
"in the deeps of the Lost Halls. Proceed at"
"once to investigate. Leave no cavern"
"unexplored.\n"
"--Commander Jeffries\n"
"P.S. These orders are to be destroyed."
)))
Kraken lakes kraken trigger
(define (spawn-kraken-lakes-sea-serpent kbeing)
(kern-log-msg "Your disturb something in the water...")
(kern-obj-put-at (spawn-npc 'kraken 8) (mk-loc p_deepness 31 34))
(kern-obj-put-at (spawn-npc 'kraken 8) (mk-loc p_deepness 32 35))
(kern-obj-put-at (spawn-npc 'kraken 8) (mk-loc p_deepness 30 29))
#t)
;; Locations referred to more than once
(define the-mans-hideout-loc (list 'p_shard 92 10))
(define lost-halls-loc (list 'p_shard 39 75))
;; Power core for voidship
(mk-quest-obj-type 't_power_core "ancient power core" s_power_core layer-item obj-ifc)
Luximene begins the game as , when defeated he drops his skull ,
which can be used with the Necromancer to summon his shade .
(mk-quest-obj-type 't_lich_skull "King Luximenes skull" s_gold_skull layer-item obj-ifc)
;; grow -- trigger hook fx to create items (eg, growing reagents, hence the name)
(define (grow-trig ktrig ktype-tag dice)
(println "grow-trig")
(println " ktrig=" ktrig)
(println " ktype-tag=" ktype-tag)
(println " dice=" dice)
(kern-obj-put-at (kern-mk-obj (eval ktype-tag) (kern-dice-roll
dice))
(kern-obj-get-location ktrig)))
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/template/lib/special.scm | scheme | ----------------------------------------------------------------------------
anywhere else.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
generator that invokes it.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Locations referred to more than once
Power core for voidship
grow -- trigger hook fx to create items (eg, growing reagents, hence the name) | Special -- one - off stuff that needs to be kern - loaded and does n't really fit
(kern-mk-sprite-set 'ss_special 32 32 3 3 0 0 "gfx/special.png")
(kern-mk-sprite 's_gold_skull ss_special 1 0 #f 0)
(kern-mk-sprite 's_power_core ss_special 1 1 #f 0)
generator -- procedure invoked by a step trigger to create
Angriss 's Lair . Should return true iff it triggers to remove the step
(define angriss-lair-loc (list 'p_shard 89 70))
(define (mk-angriss-lair kbeing)
(if (eqv? kbeing
(kern-get-player))
(begin
(kern-log-msg "You find the entrance to Angriss's Lair!")
(kern-place-set-subplace p_angriss_lair
(eval-loc angriss-lair-loc))
(kern-map-set-dirty)
#t)
#f))
The 's note
(mk-reusable-item
't_warritrix_orders "Military Orders" s_lexicon norm
(lambda (klexicon kuser)
(kern-ui-page-text
"Orders to the Warritrix"
"Ever faithful servant of Glasdrin,"
"we suspect a coven of the Accursed are hiding"
"in the deeps of the Lost Halls. Proceed at"
"once to investigate. Leave no cavern"
"unexplored.\n"
"--Commander Jeffries\n"
"P.S. These orders are to be destroyed."
)))
Kraken lakes kraken trigger
(define (spawn-kraken-lakes-sea-serpent kbeing)
(kern-log-msg "Your disturb something in the water...")
(kern-obj-put-at (spawn-npc 'kraken 8) (mk-loc p_deepness 31 34))
(kern-obj-put-at (spawn-npc 'kraken 8) (mk-loc p_deepness 32 35))
(kern-obj-put-at (spawn-npc 'kraken 8) (mk-loc p_deepness 30 29))
#t)
(define the-mans-hideout-loc (list 'p_shard 92 10))
(define lost-halls-loc (list 'p_shard 39 75))
(mk-quest-obj-type 't_power_core "ancient power core" s_power_core layer-item obj-ifc)
Luximene begins the game as , when defeated he drops his skull ,
which can be used with the Necromancer to summon his shade .
(mk-quest-obj-type 't_lich_skull "King Luximenes skull" s_gold_skull layer-item obj-ifc)
(define (grow-trig ktrig ktype-tag dice)
(println "grow-trig")
(println " ktrig=" ktrig)
(println " ktype-tag=" ktype-tag)
(println " dice=" dice)
(kern-obj-put-at (kern-mk-obj (eval ktype-tag) (kern-dice-roll
dice))
(kern-obj-get-location ktrig)))
|
a1ccfd78e25a54be0e30f33639349843a7cd1233276f8be6d029a6d01bd4bd8f | scverif/scverif | ilexport.mli | (* Copyright 2019 - NXP *)
SPDX - License - Identifier : BSD-3 - Clause - Clear WITH modifications
val serialize_mvcheck: Scv.scvcheckkind -> Ileval.state -> Ileval.initial -> Il.macro -> unit
val serialize_mvprog: Ileval.state -> Ileval.initial -> Il.macro -> unit
| null | https://raw.githubusercontent.com/scverif/scverif/307a17b61a2286fb7009d434825f9245caebfddc/src/ilexport.mli | ocaml | Copyright 2019 - NXP | SPDX - License - Identifier : BSD-3 - Clause - Clear WITH modifications
val serialize_mvcheck: Scv.scvcheckkind -> Ileval.state -> Ileval.initial -> Il.macro -> unit
val serialize_mvprog: Ileval.state -> Ileval.initial -> Il.macro -> unit
|
0c6d1cdff01f242e9d2a6ff08201ae8869179df446a08454eda816a3a8bebcb5 | gbwey/predicate-typed | doctests.hs | import Test.DocTest
main :: IO ()
main = doctest ["src","-XNoStarIsType"]
--main = doctest ["src","--verbose","-XNoStarIsType"]
stack exec doctest -- " src / Predicate.hs "
-- stack exec doctest -- src
| null | https://raw.githubusercontent.com/gbwey/predicate-typed/51f8d51f662722e1109d2ff35644aea1e0371b42/doctest/doctests.hs | haskell | main = doctest ["src","--verbose","-XNoStarIsType"]
" src / Predicate.hs "
stack exec doctest -- src | import Test.DocTest
main :: IO ()
main = doctest ["src","-XNoStarIsType"]
|
6a8517bc8ce650ab75de2e3768b5f44843e667e4f6af437016eba201bc46dd04 | EveryTian/Haskell-Codewars | reversed-strings.hs | -strings
module Solution where
solution :: String -> String
solution = reverse
| null | https://raw.githubusercontent.com/EveryTian/Haskell-Codewars/dc48d95c676ce1a59f697d07672acb6d4722893b/8kyu/reversed-strings.hs | haskell | -strings
module Solution where
solution :: String -> String
solution = reverse
| |
18d159e0246402e15dada2d3cd31eb1c0c9ca90f4ca8a5d47f205549c67777d1 | opencog/opencog | getChildren.scm | ;; Returning children associated with current target.
(define getChildren
(BindLink
(VariableList
(TypedVariableLink
(VariableNode "$relationshipNode")
(TypeChoice
(TypeNode "DefinedLinguisticRelationshipNode")
(TypeNode "PrepositionalRelationshipNode")
)
)
(VariableNode "$target")
(VariableNode "$child")
)
(AndLink
(ListLink
(AnchorNode "CurrentTarget")
(VariableNode "$target")
)
(EvaluationLink
(VariableNode "$relationshipNode")
(ListLink
(VariableNode "$target")
(VariableNode "$child")
)
)
)
(ListLink
(AnchorNode "CurrentResult")
(VariableNode "$child")
)
)
)
| null | https://raw.githubusercontent.com/opencog/opencog/53f2c2c8e26160e3321b399250afb0e3dbc64d4c/opencog/nlp/anaphora/rules/getChildren.scm | scheme | Returning children associated with current target. |
(define getChildren
(BindLink
(VariableList
(TypedVariableLink
(VariableNode "$relationshipNode")
(TypeChoice
(TypeNode "DefinedLinguisticRelationshipNode")
(TypeNode "PrepositionalRelationshipNode")
)
)
(VariableNode "$target")
(VariableNode "$child")
)
(AndLink
(ListLink
(AnchorNode "CurrentTarget")
(VariableNode "$target")
)
(EvaluationLink
(VariableNode "$relationshipNode")
(ListLink
(VariableNode "$target")
(VariableNode "$child")
)
)
)
(ListLink
(AnchorNode "CurrentResult")
(VariableNode "$child")
)
)
)
|
5d4f7fb3730ece5adef4b1c9d18d12d6271772809c534dcf6a8556b10aa378e7 | monadfix/ormolu-live | PprColour.hs | module PprColour where
import GhcPrelude
import Data.Maybe (fromMaybe)
import Util (OverridingBool(..), split)
import Data.Semigroup as Semi
-- | A colour\/style for use with 'coloured'.
newtype PprColour = PprColour { renderColour :: String }
instance Semi.Semigroup PprColour where
PprColour s1 <> PprColour s2 = PprColour (s1 <> s2)
-- | Allow colours to be combined (e.g. bold + red);
-- In case of conflict, right side takes precedence.
instance Monoid PprColour where
mempty = PprColour mempty
mappend = (<>)
renderColourAfresh :: PprColour -> String
renderColourAfresh c = renderColour (colReset `mappend` c)
colCustom :: String -> PprColour
colCustom "" = mempty
colCustom s = PprColour ("\27[" ++ s ++ "m")
colReset :: PprColour
colReset = colCustom "0"
colBold :: PprColour
colBold = colCustom ";1"
colBlackFg :: PprColour
colBlackFg = colCustom "30"
colRedFg :: PprColour
colRedFg = colCustom "31"
colGreenFg :: PprColour
colGreenFg = colCustom "32"
colYellowFg :: PprColour
colYellowFg = colCustom "33"
colBlueFg :: PprColour
colBlueFg = colCustom "34"
colMagentaFg :: PprColour
colMagentaFg = colCustom "35"
colCyanFg :: PprColour
colCyanFg = colCustom "36"
colWhiteFg :: PprColour
colWhiteFg = colCustom "37"
data Scheme =
Scheme
{ sHeader :: PprColour
, sMessage :: PprColour
, sWarning :: PprColour
, sError :: PprColour
, sFatal :: PprColour
, sMargin :: PprColour
}
defaultScheme :: Scheme
defaultScheme =
Scheme
{ sHeader = mempty
, sMessage = colBold
, sWarning = colBold `mappend` colMagentaFg
, sError = colBold `mappend` colRedFg
, sFatal = colBold `mappend` colRedFg
, sMargin = colBold `mappend` colBlueFg
}
-- | Parse the colour scheme from a string (presumably from the @GHC_COLORS@
-- environment variable).
parseScheme :: String -> (OverridingBool, Scheme) -> (OverridingBool, Scheme)
parseScheme "always" (_, cs) = (Always, cs)
parseScheme "auto" (_, cs) = (Auto, cs)
parseScheme "never" (_, cs) = (Never, cs)
parseScheme input (b, cs) =
( b
, Scheme
{ sHeader = fromMaybe (sHeader cs) (lookup "header" table)
, sMessage = fromMaybe (sMessage cs) (lookup "message" table)
, sWarning = fromMaybe (sWarning cs) (lookup "warning" table)
, sError = fromMaybe (sError cs) (lookup "error" table)
, sFatal = fromMaybe (sFatal cs) (lookup "fatal" table)
, sMargin = fromMaybe (sMargin cs) (lookup "margin" table)
}
)
where
table = do
w <- split ':' input
let (k, v') = break (== '=') w
case v' of
'=' : v -> return (k, colCustom v)
_ -> []
| null | https://raw.githubusercontent.com/monadfix/ormolu-live/d8ae72ef168b98a8d179d642f70352c88b3ac226/ghc-lib-parser-8.10.1.20200412/compiler/utils/PprColour.hs | haskell | | A colour\/style for use with 'coloured'.
| Allow colours to be combined (e.g. bold + red);
In case of conflict, right side takes precedence.
| Parse the colour scheme from a string (presumably from the @GHC_COLORS@
environment variable). | module PprColour where
import GhcPrelude
import Data.Maybe (fromMaybe)
import Util (OverridingBool(..), split)
import Data.Semigroup as Semi
newtype PprColour = PprColour { renderColour :: String }
instance Semi.Semigroup PprColour where
PprColour s1 <> PprColour s2 = PprColour (s1 <> s2)
instance Monoid PprColour where
mempty = PprColour mempty
mappend = (<>)
renderColourAfresh :: PprColour -> String
renderColourAfresh c = renderColour (colReset `mappend` c)
colCustom :: String -> PprColour
colCustom "" = mempty
colCustom s = PprColour ("\27[" ++ s ++ "m")
colReset :: PprColour
colReset = colCustom "0"
colBold :: PprColour
colBold = colCustom ";1"
colBlackFg :: PprColour
colBlackFg = colCustom "30"
colRedFg :: PprColour
colRedFg = colCustom "31"
colGreenFg :: PprColour
colGreenFg = colCustom "32"
colYellowFg :: PprColour
colYellowFg = colCustom "33"
colBlueFg :: PprColour
colBlueFg = colCustom "34"
colMagentaFg :: PprColour
colMagentaFg = colCustom "35"
colCyanFg :: PprColour
colCyanFg = colCustom "36"
colWhiteFg :: PprColour
colWhiteFg = colCustom "37"
data Scheme =
Scheme
{ sHeader :: PprColour
, sMessage :: PprColour
, sWarning :: PprColour
, sError :: PprColour
, sFatal :: PprColour
, sMargin :: PprColour
}
defaultScheme :: Scheme
defaultScheme =
Scheme
{ sHeader = mempty
, sMessage = colBold
, sWarning = colBold `mappend` colMagentaFg
, sError = colBold `mappend` colRedFg
, sFatal = colBold `mappend` colRedFg
, sMargin = colBold `mappend` colBlueFg
}
parseScheme :: String -> (OverridingBool, Scheme) -> (OverridingBool, Scheme)
parseScheme "always" (_, cs) = (Always, cs)
parseScheme "auto" (_, cs) = (Auto, cs)
parseScheme "never" (_, cs) = (Never, cs)
parseScheme input (b, cs) =
( b
, Scheme
{ sHeader = fromMaybe (sHeader cs) (lookup "header" table)
, sMessage = fromMaybe (sMessage cs) (lookup "message" table)
, sWarning = fromMaybe (sWarning cs) (lookup "warning" table)
, sError = fromMaybe (sError cs) (lookup "error" table)
, sFatal = fromMaybe (sFatal cs) (lookup "fatal" table)
, sMargin = fromMaybe (sMargin cs) (lookup "margin" table)
}
)
where
table = do
w <- split ':' input
let (k, v') = break (== '=') w
case v' of
'=' : v -> return (k, colCustom v)
_ -> []
|
cb2d5bc42d4c074c0c6f393209aca37d1fbdf1b54fd50a99419b776e2c1310d0 | clojure-garden/clojure-garden | subs.cljs | (ns platform.ui.components.footer.subs
(:require
[clojure.string :as str]
[platform.ui.utils.string :refer [format]]
[re-frame.core :as rf]))
(rf/reg-sub
::copyright
(fn [_ _]
"© 2021 Freshcode LTD. All rights reserved."))
(rf/reg-sub
::version
:<- [:app/build-meta]
(fn [{:keys [version git-sha git-url]}]
{:link (-> git-url
(str/replace ".git" "/releases/tag/%s")
(format version))
:label (format "v%s-%s" version git-sha)}))
| null | https://raw.githubusercontent.com/clojure-garden/clojure-garden/9c58ce33f91aeab5f7bd0d16647ecc450ba8967f/modules/frontend/src/platform/ui/components/footer/subs.cljs | clojure | (ns platform.ui.components.footer.subs
(:require
[clojure.string :as str]
[platform.ui.utils.string :refer [format]]
[re-frame.core :as rf]))
(rf/reg-sub
::copyright
(fn [_ _]
"© 2021 Freshcode LTD. All rights reserved."))
(rf/reg-sub
::version
:<- [:app/build-meta]
(fn [{:keys [version git-sha git-url]}]
{:link (-> git-url
(str/replace ".git" "/releases/tag/%s")
(format version))
:label (format "v%s-%s" version git-sha)}))
| |
af6eb561c62630f060dc3cc2e20e1c2663e6369aa7680d7cbd49ebb7ac0800af | informatimago/lisp | package-fun.lisp | -*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE : package.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; See defpackage documentation string.
;;;;
< XACH > < > ,
< PJB > < >
MODIFICATIONS
2012 - 04 - 03 < PJB > Completed corrections to pass package ansi - tests .
2012 - 03 - 30 < PJB > Added checks , made the API conforming to CL .
2012 - 03 - 30 < PJB > Added this header ; Removed " Z " prefix to CL
;;;; symbol names; shadowed and exported them.
;;;;
make - load - form for packages should probably return two forms , since
;;;; packages can have circular dependencies.
;;;;
;;;; Are missing some standard restarts to correct
conflicts . ( choosing one or the other symbol , doing the same
;;;; for all conflicts, etc).
;;;;
;;;;LEGAL
Copyright ( c ) 2012 < > , All Rights Reserved
Copyright ( c ) 2012 < > , All Rights Reserved
;;;;
;;;; Redistribution and use in source and binary forms, with or without
;;;; modification, are permitted provided that the following conditions
;;;; are met:
;;;;
;;;; * Redistributions of source code must retain the above copyright
;;;; notice, this list of conditions and the following disclaimer.
;;;;
;;;; * Redistributions in binary form must reproduce the above
;;;; copyright notice, this list of conditions and the following
;;;; disclaimer in the documentation and/or other materials
;;;; provided with the distribution.
;;;;
;;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
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.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(cl:in-package "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.PACKAGE")
;;; Symbol internal management
(defgeneric sym-pack (sym))
(defgeneric (setf sym-pack) (pack sym))
(defgeneric make-constant (symbol value))
Sym tables
(defgeneric make-sym-table ())
(defgeneric tget (sym-name table))
(defgeneric tput (sym table))
(defgeneric tremove (sym table))
(defgeneric tmember (sym table))
(defgeneric tmap-syms (fun table))
(defgeneric tmembers (table))
;;; Pack management
(defgeneric present-table (pack))
(defgeneric shadowing-table (pack))
(defgeneric external-table (pack))
(defgeneric accessiblep (sym pack))
(defgeneric externalp (sym pack))
(defgeneric shadowingp (sym pack))
(defgeneric presentp (sym pack))
(defgeneric check-import-conflict (sym pack))
(defgeneric check-inherit-conflict (used-pack using-pack))
(defgeneric check-export-conflict (sym pack))
(defgeneric check-unintern-conflict (sym-name pack))
(defgeneric zimport-without-checks (sym pack))
(defgeneric zunintern-without-checks (sym pack))
(defgeneric (setf used-packs) (used-packs pack))
(defgeneric (setf used-by-packs) (used-by-packs pack))
Clone of the CL symbol / package interface
(defgeneric make-symbol (sym-name)
(:documentation "
DO: Make a new symbol
URL: <>
"))
(defgeneric symbol-name (sym)
(:documentation "
RETURN: the name of the symbol.
URL: <>
"))
(defgeneric symbol-package (sym)
(:documentation "
RETURN: the home package of the symbol.
URL: <>
"))
(defgeneric make-package (pack-name &key nicknames use)
(:documentation "
DO: Make a new package.
URL: <>
"))
(defgeneric find-package (pack-name)
(:documentation "
RETURN: The package designated by PACK-NAME, or NIL if none.
URL: <>
"))
(defgeneric delete-package (pack-name)
(:documentation "
DO: Delete the package.
URL: <>
"))
(defgeneric find-symbol (sym-name &optional pack)
(:documentation "
RETURN: the symbol named SYM-NAME in the package PACK, if found and a status keyword.
URL: <>
"))
(defgeneric import (symbols &optional pack)
(:documentation "
DO: Import the symbols into the package.
URL: <>
"))
(defgeneric intern (sym-name &optional pack)
(:documentation "
DO: Intern the symbol name in the package.
URL: <>
"))
(defgeneric shadow (symbol-names &optional pack)
(:documentation "
DO: Shadow the designated symbols.
URL: <>
"))
(defgeneric shadowing-import (symbols &optional pack)
(:documentation "
DO: Shadow and import the designated symbols.
URL: <>
"))
(defgeneric export (sym &optional pack)
(:documentation "
DO: Export the designated symbols from the package.
URL: <>
"))
(defgeneric unexport (sym &optional pack)
(:documentation "
DO: Unexport the designated symbols from the package.
URL: <>
"))
(defgeneric unintern (sym &optional pack)
(:documentation "
DO: Unintern the designated symbols from the package.
URL: <>
"))
(defgeneric use-package (pack &optional using-pack)
(:documentation "
DO: Make the USING-PACK use the package PACK.
URL: <>
"))
(defgeneric unuse-package (pack &optional using-pack)
(:documentation "
DO: Make the USING-PACK unuse the package PACK
URL: <>
"))
(defgeneric package-name (pack)
(:documentation "
RETURN: The package name.
URL: <>
"))
(defgeneric package-use-list (pack)
(:documentation "
RETURN: The list of packages used by PACK.
URL: <>
"))
(defgeneric package-used-by-list (pack)
(:documentation "
RETURN: The list of packages that use PACK.
URL: <>
"))
(defgeneric package-shadowing-symbols (pack)
(:documentation "
RETURN: The list of shadowing symbols of the package.
URL: <>
"))
(defgeneric find-all-symbols (name)
(:documentation "
RETURN: The list of all symbols named NAME in all packages.
URL: <>
"))
(defgeneric rename-package (package new-name &optional new-nicknames)
(:documentation "
DO: Rename the package giving it the NEW-NAME and NEW-NICKNAMES.
URL: <>
"))
;;; Variables
(defparameter *keyword-package* nil)
(defparameter *common-lisp-package* nil)
(defparameter *common-lisp-user-package* nil)
(defvar *package* nil
"
The current package.
URL: <>
")
;;; Conditions
(define-condition simple-error-mixin (condition)
((format-control :initarg :format-control :reader format-control
:initform "Simple error.")
(format-arguments :initarg :format-arguments :reader format-arguments
:initform '()))
(:report (lambda (condition stream)
(format stream "~?"
(format-control condition)
(format-arguments condition)))))
(define-condition simple-program-error (simple-error-mixin program-error)
())
(define-condition simple-type-error (simple-error-mixin type-error)
())
(define-condition print-not-readable (error)
((object :initarg :object :reader print-not-readable-object
:initform (error "Missing :object initarg.")))
(:report (lambda (condition stream)
(let ((*print-readably* nil)
(*print-circle* t)
(*print-length* 4)
(*print-level* 4))
(format stream "The object ~S is not printable readably."
(print-not-readable-object condition))))))
(defgeneric package-error-package (package-error)
(:documentation "
RETURN: The package in error.
URL: <>
"))
(define-condition package-error (error)
((package :initarg :package :reader package-error-package))
(:report (lambda (condition stream)
(format stream "Package error with ~A" (package-error-package condition))))
(:documentation "
The type package-error consists of error conditions related to operations on packages.
URL: <>
"))
(define-condition simple-package-error (package-error simple-error-mixin)
())
(define-condition package-exists-error (simple-package-error)
()
(:documentation "The error condition signaling that a package with the same name already exists."))
(define-condition package-does-not-exist-error (simple-package-error)
()
(:documentation "The error condition signaling that no package with that name exists."))
(defgeneric symbol-conflict-existing-symbol (error)
(:documentation "RETURN: The existing symbol in conflict."))
(defgeneric symbol-conflict-imported-symbol (error)
(:documentation "RETURN: The imported symbol in conflict."))
(define-condition symbol-conflict-error (simple-package-error)
((existing-symbol :initarg :existing-symbol :reader symbol-conflict-existing-symbol)
(imported-symbol :initarg :imported-symbol :reader symbol-conflict-imported-symbol))
(:report (lambda (condition stream)
(format stream "The would-be imported symbol ~S conflicts with the existing symbol ~S in the package ~S"
(symbol-conflict-imported-symbol condition)
(symbol-conflict-existing-symbol condition)
(package-name (package-error-package condition)))))
(:documentation "The error condition signaling a symbol conflict."))
(define-condition symbol-does-not-exist-error (simple-package-error)
((symbol-name :initarg :symbol-name :reader symbol-does-not-exist-symbol-name))
(:report (lambda (condition stream)
(format stream "There exists no symbol named ~S in the package ~S"
(symbol-does-not-exist-symbol-name condition)
(package-name (package-error-package condition))))))
(define-condition symbol-inaccessible-error (simple-package-error)
((symbol :initarg :symbol :reader symbol-inaccessible-symbol))
(:report (lambda (condition stream)
(format stream "~S is not accessible in ~S"
(symbol-inaccessible-symbol condition)
(package-name (package-error-package condition))))))
(defun query-string ()
(format *query-io* "Enter a new string: ")
(finish-output *query-io*)
(list (read-line *query-io*)))
(defun query-symbol ()
(list (loop
:for sym = (progn
(format *query-io* "Enter a new symbol (current package is ~A): "
(package-name *package*))
(finish-output *query-io*)
(read *query-io*))
:until (symbolp sym)
:finally (return sym))))
(defun query-package-name ()
(format *query-io* "Enter a package name (string or symbol): ")
(finish-output *query-io*)
(list (read *query-io*)))
(defun query-package-nickname ()
(format *query-io* "Enter a package nickname (string or symbol): ")
(finish-output *query-io*)
(list (read *query-io*)))
;;; Implementation of syms
(defgeneric symbol-plist (symbol)
(:documentation "
RETURN: The plist of the symbol.
URL: <>
"))
(defgeneric symbol-value (symbol)
(:documentation "
RETURN: The value of the symbol.
URL: <>
"))
(defgeneric symbol-function (symbol)
(:documentation "
RETURN: The function of the symbol.
URL: <>
"))
(defclass symbol ()
((name
:initarg :name
:reader symbol-name)
(pack
:initarg :pack
:reader symbol-package
:accessor sym-pack)
(plist
:initarg :plist
:initform nil
:accessor symbol-plist)
(value
:initarg :value
:accessor symbol-value)
(function
:initarg :function
:accessor symbol-function)
(constantp
:initarg :constantp
:initform nil
:accessor symbol-constantp))
(:default-initargs
:pack nil)
(:documentation "
The symbol class.
URL: <>
"))
(defgeneric symbolp (object)
(:method ((object t)) nil)
(:method ((object symbol)) t)
(:documentation "
RETURN: Whether the object is a symbol.
URL: <>
"))
(defgeneric boundp (object)
(:method ((object t))
(error 'type-error :datum object :expected-type 'symbol))
(:method ((object symbol))
(slot-boundp object 'value))
(:documentation "
RETURN: Whether the symbol is bound to a value.
URL: <>
"))
(defgeneric fboundp (object)
(:method ((object t))
(error 'type-error :datum object :expected-type 'symbol))
(:method ((object symbol))
(slot-boundp object 'function))
(:documentation "
RETURN: Whether the symbol is fbound to a function.
URL: <>
"))
(defclass keyword (symbol)
()
(:documentation "
The keyword class.
URL: <>
"))
(defgeneric keywordp (object)
(:method ((object t)) nil)
(:method ((object keyword)) t)
(:documentation "
RETURN: Whether the object is a keyword.
URL: <>
"))
(defmethod make-symbol (sym-name)
(make-instance 'symbol :name (copy-seq sym-name)))
(defmethod make-load-form ((sym symbol) &optional environment)
(declare (ignore environment))
`(intern ,(symbol-name sym) ,(package-name (symbol-package sym))))
(defun constituentp (ch first-character-p &optional (readtable *readtable*))
(multiple-value-bind (macro-character-p non-terminating-p) (get-macro-character ch readtable)
(or (not macro-character-p)
(and (not first-character-p)
non-terminating-p))))
(defun specialp (ch &optional (readtable *readtable*))
(declare (ignore readtable))
(find ch #(#\Space #\: #\| #\\
#\Newline #\Tab #\Linefeed #\Return #\Page)))
(defun parses-as-a-number-p (string &key (start 0) (end nil) (base *read-base*))
;; integer ::= [sign] digit+
;; integer ::= [sign] decimal-digit+ decimal-point
;; ratio ::= [sign] {decimal-digit}+ '/' {decimal-digit}+
;; float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ exponent
;; float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+
;; float ::= [sign] {decimal-digit}+ exponent
;; float ::= [sign] {decimal-digit}+ decimal-point {decimal-digit}* exponent
;; exponent ::= exponent-marker [sign] {digit}+
We may ignore ratio starting with # \ # since that 's excluded by .
;; ratio ::= [#b|#o|#x|#{decimal-digit}+r] [sign] digit+ '/' digit+
(loop
:with end = (or end (length string))
:with i = start
:with state = :opt-sign
:for ch = (and (< i end) (aref string i))
:while (< i end)
:do (ecase state
(:opt-sign (case ch ((#\+ #\-) (incf i)))
(setf state :unknown0))
(:unknown0 (if (<= base 10)
(cond
((digit-char-p ch base) (incf i) (setf state :unknown1))
((digit-char-p ch 10) (incf i) (setf state :decimal))
(t (case ch
((#\.) (incf i) (setf state :float0))
(otherwise (return nil)))))
(cond
((digit-char-p ch 10) (incf i) (setf state :unknown1))
((digit-char-p ch base) (incf i) (setf state :integer))
(t (case ch
((#\.) (incf i) (setf state :float0))
(otherwise (return nil)))))))
(:unknown1 (if (<= base 10)
(cond
((digit-char-p ch base) (incf i) (setf state :unknown1))
((digit-char-p ch 10) (incf i) (setf state :decimal))
(t (case ch
((#\/) (incf i) (setf state :ratio0))
((#\.) (incf i) (setf state :dot))
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(cond
((digit-char-p ch 10) (incf i) (setf state :unknown1))
((digit-char-p ch base) (incf i) (setf state :integer))
(t (case ch
((#\/) (incf i) (setf state :ratio0))
((#\.) (incf i) (setf state :dot))
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))))
(:integer (if (digit-char-p ch base)
(incf i)
(return nil)))
(:decimal (if (digit-char-p ch 10)
(incf i)
(case ch
((#\/) (incf i) (setf state :ratio0))
((#\.) (incf i) (setf state :dot))
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(:dot (if (digit-char-p ch 10)
(progn (incf i) (setf state :float))
(case ch
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(:ratio0 (if (digit-char-p ch 10)
(progn (incf i) (setf state :ratio))
(return nil)))
(:ratio (if (digit-char-p ch 10)
(incf i)
(return nil)))
(:float0 (if (digit-char-p ch 10)
(progn (incf i) (setf state :float))
(return nil)))
(:float (if (digit-char-p ch 10)
(incf i)
(case ch
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(:float-expo/opt-sign (case ch ((#\+ #\-) (incf i)))
(setf state :float-expo0))
(:float-expo0 (if (digit-char-p ch 10)
(progn (incf i) (setf state :float-expo))
(return nil)))
(:float-expo (if (digit-char-p ch 10)
(incf i)
(return nil))))
:finally (return (case state
((:unknown1 :integer :dot :ratio :float :float-expo) t)
(otherwise nil)))))
(defun needs-escape-p (symbol-name)
"Whether the symbol name needs to be escaped."
(cond
((string= "" symbol-name) t)
((or *print-readably* *print-escape*)
(or (notevery (let ((first-character-p t))
(lambda (ch)
(prog1 (and (not (specialp ch))
(constituentp ch first-character-p))
(setf first-character-p nil))))
symbol-name)
;; Parses as a number integer, decimal, ratio or float.
(parses-as-a-number-p symbol-name :base *print-base*)))
(t
nil)))
(defun mixed-case-p (string)
"Whether the string contains both lower case and upper case letters."
(and (some (lambda (ch) (and (alpha-char-p ch) (upper-case-p ch))) string)
(some (lambda (ch) (and (alpha-char-p ch) (lower-case-p ch))) string)))
(defun prepare-symbol-name (sname)
(cond
((needs-escape-p sname)
(with-output-to-string (*standard-output*)
(loop
:for ch :across sname
:initially (princ "|")
:do (if (char= #\| ch) (princ "\\|") (princ ch))
:finally (princ "|"))))
(t
(let ((transform
(if *print-escape*
(ecase (readtable-case *readtable*)
(:upcase (lambda (ch)
(if (both-case-p ch)
(if (lower-case-p ch)
(format nil "\\~C" ch)
ch)
ch)))
(:downcase (lambda (ch)
(if (both-case-p ch)
(if (upper-case-p ch)
(format nil "\\~C" ch)
ch))))
(:preserve (function identity))
(:invert (function identity)))
(ecase (readtable-case *readtable*)
(:upcase (let ((start-word t))
(lambda (ch)
(prog1 (if (both-case-p ch)
(if (upper-case-p ch)
(ecase *print-case*
(:upcase ch)
(:downcase (char-downcase ch))
(:capitalize (if start-word
(char-upcase ch)
(char-downcase ch))))
ch)
ch)
(if (alphanumericp ch)
(setf start-word nil)
(setf start-word t))))))
(:downcase (let ((start-word t))
(lambda (ch)
(prog1 (if (both-case-p ch)
(if (lower-case-p ch)
(ecase *print-case*
(:upcase (char-upcase ch))
(:downcase ch)
(:capitalize (if start-word
(char-upcase ch)
(char-downcase ch))))
ch)
ch)
(if (alphanumericp ch)
(setf start-word nil)
(setf start-word t))))))
(:preserve (function identity))
(:invert (if (mixed-case-p sname)
(function identity)
(lambda (ch)
(cond
((not (both-case-p ch)) ch)
((upper-case-p ch) (char-downcase ch))
((lower-case-p ch) (char-upcase ch))
(t ch)))))))))
(with-output-to-string (*standard-output*)
(loop
:for ch :across sname
:do (princ (funcall transform ch))))))))
(defmethod print-object ((sym symbol) stream)
(let ((*print-readably* t))
(flet ((print-it ()
(let ((pack (symbol-package sym)))
(cond ((null pack)
(format stream "~:[~;#:~]~A"
(or *print-readably* (and *print-escape* *print-gensym*))
(prepare-symbol-name (symbol-name sym))))
((eql pack *keyword-package*)
(format stream ":~A"
(prepare-symbol-name (symbol-name sym))))
((or (eq pack *package*)
(eq sym (find-symbol (symbol-name sym) *package*)))
(format stream "~A" (prepare-symbol-name (symbol-name sym))))
(t
(format stream "~A~:[::~;:~]~A"
(prepare-symbol-name (package-name pack))
(externalp sym pack)
(prepare-symbol-name (symbol-name sym))))))))
(if *print-readably*
(print-it)
(progn
(format stream "#<~S " 'symbol)
(print-it)
(format stream ">")))))
sym)
(defmethod make-constant (symbol value)
(declare (ignorable value))
(setf (symbol-value symbol) value
(symbol-constantp symbol) t)
symbol)
;;; Implementation of sym-tables
(defclass sym-table ()
((name-table
:initarg :name-table
:reader name-table))
(:default-initargs
:name-table (make-hash-table :test 'equal)))
(defmethod make-sym-table ()
(make-instance 'sym-table))
(defmethod tget (sym-name table)
(values (gethash sym-name (name-table table))))
(defmethod tmember (sym table)
(let ((entry (tget (symbol-name sym) table)))
(eq entry sym)))
(defmethod tput (sym table)
(setf (gethash (symbol-name sym) (name-table table)) sym))
(defmethod tremove (sym table)
(remhash (symbol-name sym) (name-table table)))
(defmethod tmap-syms (fun table)
(maphash (lambda (sym-name sym)
(declare (ignore sym-name))
(funcall fun sym))
(name-table table)))
(defmethod tmembers (table)
(let ((members '()))
(tmap-syms (lambda (sym)
(push sym members))
table)
members))
;;; Implementation of packs & CL clone interface
(defparameter *packs* (make-hash-table :test 'equal))
(defun list-all-packages ()
"
RETURN: A fresh list of all registered packages.
URL: <>
"
(let ((packages '()))
(maphash (lambda (k v) (declare (ignore k)) (pushnew v packages)) *packs*)
packages))
(defgeneric package-documentation (package)
(:documentation "RETURN: The documentation string of the package."))
(defgeneric package-nicknames (package)
(:documentation "RETURN: The list of nicknames of the package."))
(defclass package ()
((name
:initarg :name
:reader package-name
:writer (setf name))
(external-table
:initarg :external-table
:reader external-table)
(present-table
:initarg :present-table
:reader present-table)
(shadowing-table
:initarg :shadowing-table
:reader shadowing-table)
(used-packs
:initarg :used-packs
:reader package-use-list
:writer (setf used-packs))
(used-by-packs
:initarg :used-by-packs
:reader package-used-by-list
:writer (setf used-by-packs))
(nicknames
:initarg :nicknames
:reader package-nicknames
:writer (setf nicknames))
(documentation
:initarg :documentation
:initform nil
:accessor package-documentation))
(:default-initargs
:name (error "A package name is required")
:external-table (make-sym-table)
:present-table (make-sym-table)
:shadowing-table (make-sym-table)
:used-packs nil
:used-by-packs nil)
(:documentation "
The package class.
URL: <>
"))
(defmacro define-normalize-package-methods (name &key (if-package-does-not-exist :replace) (type-error nil))
`(progn
,@ (when type-error
`((defmethod ,name ((name t)) (error 'simple-type-error
:datum name
:expected-type 'package-designator
:format-control "~S called with a non ~S: ~S"
:format-arguments (list ',name 'package-designator name)))))
(defmethod ,name ((name string)) (,name (normalize-package-designator name :if-package-does-not-exist ,if-package-does-not-exist)))
(defmethod ,name ((name character)) (,name (normalize-package-designator name :if-package-does-not-exist ,if-package-does-not-exist)))
(defmethod ,name ((name cl:symbol)) (,name (normalize-package-designator name :if-package-does-not-exist ,if-package-does-not-exist)))
(defmethod ,name ((name symbol)) (,name (normalize-package-designator (symbol-name name) :if-package-does-not-exist ,if-package-does-not-exist)))))
(define-normalize-package-methods package-name :type-error t)
(define-normalize-package-methods package-use-list :type-error t)
(define-normalize-package-methods package-used-by-list :type-error t)
(define-normalize-package-methods package-nicknames :type-error t)
(define-normalize-package-methods package-shadowing-symbols)
(defgeneric packagep (package)
(:method ((object t)) nil)
(:method ((package package)) t)
(:documentation "
RETURN: Whether the object is a package.
URL: <>
"))
(defmethod print-object ((pack package) stream)
(if *print-readably*
(error 'print-not-readable :object pack)
(format stream "#<~S ~S>" 'package (package-name pack)))
pack)
(defmethod package-shadowing-symbols (pack)
(tmembers (shadowing-table pack)))
(defmethod accessiblep (sym pack)
(let ((existing-sym (find-symbol (symbol-name sym) pack)))
(eq existing-sym sym)))
(defmethod externalp (sym pack)
(tmember sym (external-table pack)))
(defmethod shadowingp (sym pack)
(tmember sym (shadowing-table pack)))
(defmethod presentp (sym pack)
(tmember sym (present-table pack)))
(defun ensure-list (object)
(if (listp object)
object
(list object)))
(deftype string-designator ()
'(or string character symbol cl:symbol))
(defun normalize-string-designator (object &key (if-not-a-string-designator :error))
(check-type if-not-a-string-designator (member nil :error :ignore :replace :ignore-or-replace))
(typecase object
(string object)
(character (string object))
(cl:symbol (string object))
(symbol (symbol-name object))
(otherwise
(case if-not-a-string-designator
((:error) (error 'type-error
:datum object
:expected-type 'string-designator))
((nil) nil)
((:ignore :replace :ignore-or-replace)
(restart-case (error 'type-error
:datum object
:expected-type 'string-designator)
(ignore ()
:test (lambda (condition)
(declare (ignore condition))
(member if-not-a-string-designator '(:ignore :ignore-or-replace)))
:report "Ignore it."
nil)
(read-a-new-string-designator (new-string)
:test (lambda (condition)
(declare (ignore condition))
(member if-not-a-string-designator '(:replace :ignore-or-replace)))
:interactive query-string
:report "Enter a string"
(normalize-string-designator
new-string
:if-not-a-string-designator if-not-a-string-designator))))))))
(defun normalize-weak-designator-of-list-of-string-designator (object)
(mapcan (lambda (nickname)
(ensure-list (normalize-string-designator
nickname
:if-not-a-string-designator :ignore-or-replace)))
(ensure-list object)))
(deftype package-designator ()
'(or package string-designator))
(defun normalize-package-designator (object &key
(if-package-does-not-exist :string)
(if-package-exists :package)
(if-not-a-package-designator :error))
"
Normalize the given PACKAGE-DESIGNATOR. Objects of type
PACKAGE-DESIGNATOR are either PACKAGE or objects of type
STRING-DESIGNATOR.
RETURN: either NIL, a STRING designating a non-existent package, or an
existing PACKAGE.
IF-NOT-A-PACKAGE-DESIGNATOR The default is :ERROR.
NIL If the OBJECT is not a PACKAGE-DESIGNATOR
then return NIL.
:ERROR If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR.
:IGNORE If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR, with an IGNORE
restart that when chosen returns NIL.
:REPLACE If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR, with a replace
restart that when chosen let the user
input another PACKAGE-DESIGNATOR.
:IGNORE-OR-REPLACE If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR, with the two
previous restarts.
If the object is a PACKAGE-DESIGNATOR, then the results depends on the
following parameters and whether the designated package exists or not.
IF-PACKAGE-DOES-NOT-EXIST The default is :STRING
NIL If the OBJECT designates a PACKAGE that
doesn't exist then return NIL.
:STRING If the OBJECT designates a PACKAGE that
doesn't exist then (it would be a
STRING-DESIGNATOR) return the designated
STRING.
:ERROR If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR.
:IGNORE If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR with an
IGNORE restart that when chosen returns
NIL.
:REPLACE If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR with a
replace restart that when chosen let the
user input another PACKAGE-DESIGNATOR.
:IGNORE-OR-REPLACE If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR with the two
previous restarts.
IF-PACKAGE-EXISTS The default is :PACKAGE
:PACKAGE If the OBJECT designates a PACKAGE that
does exist then return the designated
PACKAGE.
:STRING If the OBJECT designates a PACKAGE that
does exist then return the designated
package name.
:ERROR If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR.
:IGNORE If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR with an IGNORE
restart that when chosen returns NIL.
:REPLACE If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR with a replace
restart that when chosen let the user
input another PACKAGE-DESIGNATOR.
:IGNORE-OR-REPLACE If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR with the two previous
restarts.
"
(check-type if-not-a-package-designator (member :error :ignore :replace :ignore-or-replace nil))
(check-type if-package-does-not-exist (member :error :ignore :replace :ignore-or-replace :string nil))
(check-type if-package-exists (member :error :ignore :replace :ignore-or-replace :string :package))
(flet ((retry-string-designator (restarts condition &rest arguments)
(check-type restarts (member :ignore :replace :ignore-or-replace))
(restart-case (apply (function error) condition arguments)
(ignore ()
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:ignore :ignore-or-replace)))
:report "Ignore it."
nil)
(read-a-new-package-designator (new-package)
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:replace :ignore-or-replace)))
:interactive query-package-name
:report "Enter a package name"
(normalize-package-designator
new-package
:if-not-a-package-designator if-not-a-package-designator
:if-package-does-not-exist if-package-does-not-exist
:if-package-exists if-package-exists))))
(retry-package-designator (restarts condition &rest arguments)
(check-type restarts (member :ignore :replace :ignore-or-replace))
(restart-case (apply (function error) condition arguments)
(ignore ()
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:ignore :ignore-or-replace)))
:report "Ignore it."
nil)
(read-a-new-package-designator (new-package)
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:replace :ignore-or-replace)))
:interactive query-package-name
:report "Enter a package name"
(normalize-package-designator
new-package
:if-not-a-package-designator if-not-a-package-designator
:if-package-does-not-exist if-package-does-not-exist
:if-package-exists if-package-exists)))))
(typecase object
(string-designator
(let* ((normalized (normalize-string-designator object))
(package (find-package normalized)))
(if package
(normalize-package-designator package :if-package-exists if-package-exists)
(case if-package-does-not-exist
((nil) nil)
((:string) normalized)
((:error) (error
'package-does-not-exist-error
:package normalized
:format-control "There is no package named ~S"
:format-arguments (list normalized)))
((:ignore :replace :ignore-or-replace)
(retry-package-designator if-package-does-not-exist
'package-does-not-exist-error
:package normalized
:format-control "There is no package named ~S"
:format-arguments (list normalized)))))))
(package
(case if-package-exists
((:package) object)
((:string) (package-name object))
((:error) (error
'package-exists-error
:package object
:format-control "There is already a package named ~S"
:format-arguments (list (package-name object))))
((:ignore :replace :ignore-or-replace)
(retry-package-designator if-package-exists
'package-exists-error
:package object
:format-control "There is already a package named ~S"
:format-arguments (list (package-name object))))))
(otherwise
(case if-not-a-package-designator
((nil) nil)
((:error) (error 'type-error
:datum object
:expected-type 'package-designator))
((:ignore :replace :ignore-or-replace)
(retry-string-designator if-not-a-package-designator
'type-error
:datum object
:expected-type 'package-designator)))))))
(defun make-package-iterator (packages symbol-types)
(let ((packages (mapcan (lambda (package-designator)
(list (normalize-package-designator
package-designator :if-package-does-not-exist :ignore-or-replace)))
(ensure-list packages)))
(package nil)
(stypes nil)
(stype nil)
(symbols '()))
(labels ((iterator ()
(cond
(symbols (let ((sym (pop symbols)))
(values t
sym
(cond
((externalp sym package) :external)
((eq stype :inherited) stype)
(t :internal))
package)))
(stypes (setf stype (pop stypes))
(ecase stype
((:internal)
(tmap-syms (lambda (sym)
(unless (externalp sym package)
(push sym symbols)))
(present-table package)))
((:external)
(tmap-syms (lambda (sym) (push sym symbols))
(external-table package)))
((:inherited)
(dolist (pack (package-use-list package))
(tmap-syms (lambda (sym)
(let ((shadow (find-symbol (symbol-name sym) package)))
(unless (and shadow
(shadowingp shadow package)
(not (eq sym shadow)))
(push sym symbols))))
(external-table (find-package pack)))))
((:present)
(tmap-syms (lambda (sym) (push sym symbols))
(present-table package)))
((:shadowing)
(tmap-syms (lambda (sym) (push sym symbols))
(shadowing-table package))))
(iterator))
(packages (setf package (pop packages)
stypes symbol-types)
(iterator))
(t nil))))
(function iterator))))
(defmethod check-import-conflict (sym pack)
(let ((existing-sym (find-symbol (symbol-name sym) pack)))
(if (and existing-sym (not (eq existing-sym sym)))
(restart-case (error 'symbol-conflict-error
:package pack
:format-control "Conflict: importing ~A into ~A conflicts with ~A"
:format-arguments (list sym pack existing-sym)
:existing-symbol existing-sym
:imported-symbol sym)
(enter-new-name (new-symbol)
:interactive query-symbol
:report "Enter a new symbol, instead"
(check-import-conflict new-symbol pack))
(ignore-symbol ()
:report (lambda (stream) (format stream "Ignore the symbol ~S" sym))
(values nil nil)))
(values sym t))))
(defmacro zdo-external-symbols ((var pack) &body body)
`(tmap-syms (lambda (,var)
,@body)
(external-table ,pack)))
(defmethod check-inherit-conflict (used-pack using-pack)
(zdo-external-symbols (inherited-sym used-pack)
(let ((existing-sym (find-symbol (symbol-name inherited-sym)
using-pack)))
(when (and existing-sym
(not (eq inherited-sym existing-sym))
(not (shadowingp existing-sym using-pack)))
(error "Conflict: Inheriting ~A from ~A conflicts with ~A in ~A"
inherited-sym
used-pack
existing-sym
using-pack)))))
(defmethod check-export-conflict (sym pack)
(let ((sym-name (symbol-name sym)))
(dolist (using-pack (package-used-by-list pack))
(let ((existing-sym (find-symbol sym-name using-pack)))
(when (and existing-sym
(not (member existing-sym (package-shadowing-symbols using-pack))))
(unless (eq existing-sym sym)
(error "Conflict: exporting ~A conflicts with ~A in ~A"
sym existing-sym using-pack)))))))
(defmethod check-unintern-conflict (sym pack)
(let ((sym-name (symbol-name sym))
(first-existing-sym nil))
(dolist (used-pack (package-use-list pack))
(let ((existing-sym (find-symbol sym-name used-pack)))
(when existing-sym
(if first-existing-sym
(unless (eq existing-sym first-existing-sym)
(error "Conflict: uninterning ~A would lead to conflict ~
between ~A and ~A"
sym first-existing-sym existing-sym))
(setf first-existing-sym existing-sym)))))))
(defmethod zimport-without-checks (sym pack)
(tput sym (present-table pack))
(unless (symbol-package sym)
(setf (sym-pack sym) pack)))
(defmethod zunintern-without-checks (sym pack)
(tremove sym (external-table pack))
(tremove sym (shadowing-table pack))
(tremove sym (present-table pack))
(when (eq (symbol-package sym) pack)
(setf (sym-pack sym) nil)))
(defun check-new-names (pack-name nicknames &key renaming-package)
(loop
:with result = '()
:for name :in (cons pack-name nicknames)
:do (loop
:for pack = (find-package name)
:while (if renaming-package
(and pack (not (eq pack renaming-package)))
pack)
:do (restart-case (error 'package-exists-error
:package name
:format-control "A package named ~S already exists"
:format-arguments (list name))
(enter-new-name (new-name)
:test (lambda (condition) (declare (ignore condition)) (eq name pack-name))
:interactive query-package-name
:report "Enter a new package name, instead"
(setf name new-name))
(enter-new-name (new-name)
:test (lambda (condition) (declare (ignore condition)) (not (eq name pack-name)))
:report "Enter a new package nickname, instead"
:interactive query-package-nickname
(setf name new-name))
(ignore-nickname ()
:test (lambda (condition) (declare (ignore condition)) (not (eq name pack-name)))
:report (lambda (stream) (format stream "Ignore the nickname ~S" name))
(return)))
:finally (push name result))
:finally (let ((result (nreverse result)))
(return (values (car result) (cdr result))))))
(defmethod make-package (pack-name &key (nicknames '()) (use '()))
(let ((pack-name (normalize-string-designator pack-name :if-not-a-string-designator :replace))
(nicknames (normalize-weak-designator-of-list-of-string-designator nicknames))
(use (mapcan (lambda (package-designator)
(list (normalize-package-designator
package-designator :if-package-does-not-exist :ignore-or-replace)))
use)))
(multiple-value-setq (pack-name nicknames) (check-new-names pack-name nicknames))
(let ((package (make-instance 'package
:name (copy-seq pack-name)
:nicknames (mapcar (function copy-seq) nicknames))))
(dolist (upack use)
(use-package upack package))
(dolist (name (cons pack-name nicknames) package)
(setf (gethash name *packs*) package)))))
(defmethod find-package (pack-name)
(etypecase pack-name
(string-designator
(values (gethash (normalize-string-designator pack-name) *packs*)))
(package pack-name)))
(defmethod delete-package (pack)
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :replace)))
(when (and pack (package-name pack))
(dolist (used (package-used-by-list pack))
(unuse-package pack used))
(dolist (puse (package-use-list pack))
(unuse-package puse pack))
(do-symbols (sym pack)
(when (eq (symbol-package sym) pack)
(zunintern-without-checks sym pack)))
(dolist (name (cons (package-name pack) (package-nicknames pack)))
(remhash name *packs*))
(setf (name pack) nil)
pack)))
(defmethod find-symbol (sym-name &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :replace))
sym)
(cond ((setf sym (tget sym-name (external-table pack)))
(values sym :external))
((setf sym (tget sym-name (shadowing-table pack)))
(values sym :internal))
((setf sym (some (lambda (used-pack)
(tget sym-name (external-table used-pack)))
(package-use-list pack)))
(values sym :inherited))
((setf sym (tget sym-name (present-table pack)))
(values sym :internal))
(t
(values nil nil)))))
(defmethod import (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-import (sym)
(check-type sym symbol)
(multiple-value-bind (sym good) (check-import-conflict sym pack)
(when (and good (not (presentp sym pack)))
(if (and (null (symbol-package sym))
(eql pack *keyword-package*))
(progn
(zimport-without-checks sym pack)
(change-class sym 'keyword)
(make-constant sym sym)
(export sym pack))
(zimport-without-checks sym pack))))))
(mapc (function do-import) (ensure-list symbols)))
t))
(defmethod intern (sym-name &optional (pack *package*))
(check-type sym-name string)
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(multiple-value-bind (sym status) (find-symbol sym-name pack)
(if status
(values sym status)
(values (let ((sym (make-symbol sym-name)))
(import sym pack)
(when (eql pack *keyword-package*)
(change-class sym 'keyword)
(make-constant sym sym)
(export sym pack))
sym)
nil)))))
(defmethod shadow (symbol-names &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-shadow (sym-name)
(let ((sym (tget sym-name (present-table pack))))
(unless sym
(setf sym (make-symbol sym-name))
(zimport-without-checks sym pack))
(tput sym (shadowing-table pack)))))
(mapc (function do-shadow)
(normalize-weak-designator-of-list-of-string-designator symbol-names)))
t))
(defmethod shadowing-import (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-shadowing-import (sym)
(check-type sym symbol)
(let ((sym-name (symbol-name sym)))
(multiple-value-bind (existing-sym type) (find-symbol sym-name pack)
(case type
((nil :inherited)
(zimport-without-checks sym pack))
((:external :internal)
(unless (eq existing-sym sym)
(zunintern-without-checks existing-sym pack)
(import sym pack))))
(tput sym (shadowing-table pack))))))
(mapc (function do-shadowing-import) (ensure-list symbols))
t)))
(defmethod export (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-export (sym)
(check-type sym symbol)
(unless (accessiblep sym pack)
(error 'symbol-inaccessible-error :package pack :symbol sym))
(check-export-conflict sym pack)
(unless (presentp sym pack)
(import sym pack))
(tput sym (external-table pack))))
(mapc (function do-export) (ensure-list symbols))
t)))
(defmethod unexport (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-unexport (sym)
(check-type sym symbol)
(unless (accessiblep sym pack)
(error 'symbol-inaccessible-error :package pack :symbol sym))
(tremove sym (external-table pack))))
(mapc (function do-unexport) (ensure-list symbols))
t)))
(defmethod unintern (sym &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(when (accessiblep sym pack)
(check-unintern-conflict sym pack)
(zunintern-without-checks sym pack)
t)))
(defmethod use-package (packs &optional (using-pack *package*))
(let ((using-pack (normalize-package-designator using-pack :if-package-does-not-exist :error)))
(dolist (pack (ensure-list packs) t)
(let* ((pack (normalize-package-designator pack :if-package-does-not-exist :error))
(use-list (package-use-list using-pack)))
(unless (member pack use-list)
(check-inherit-conflict pack using-pack)
(setf (used-packs using-pack) (cons pack use-list))
(setf (used-by-packs pack) (cons using-pack (package-used-by-list pack))))))))
(defmethod unuse-package (packs &optional (using-pack *package*))
(let ((using-pack (normalize-package-designator using-pack :if-package-does-not-exist :error)))
(dolist (pack (ensure-list packs) t)
(let ((pack (normalize-package-designator pack :if-package-does-not-exist :error)))
(setf (used-packs using-pack) (remove pack (package-use-list using-pack)))
(setf (used-by-packs pack) (remove using-pack (package-used-by-list pack)))))))
(defmethod find-all-symbols (name)
(let ((name (normalize-string-designator name))
(symbols '()))
(dolist (pack (list-all-packages) (delete-duplicates symbols))
(multiple-value-bind (sym found) (find-symbol name pack)
(when found
(push sym symbols))))))
(defmethod rename-package (package new-name &optional new-nicknames)
(let ((package (normalize-package-designator
package :if-package-does-not-exist :error))
(new-name (normalize-string-designator new-name))
(new-nicknames (normalize-weak-designator-of-list-of-string-designator new-nicknames)))
(multiple-value-setq (new-name new-nicknames) (check-new-names new-name new-nicknames
:renaming-package package))
;; remove old names:
(dolist (name (cons (package-name package) (package-nicknames package)))
(remhash name *packs*))
;; set new names:
(setf (name package) (copy-seq new-name)
(nicknames package) (mapcar (function copy-seq) new-nicknames))
(dolist (name (cons new-name new-nicknames) package)
(setf (gethash name *packs*) package))))
(defun check-disjoints (shadows shadowing-import-froms import-froms
interns exports)
(loop
:for sets :in (list (append (list shadows interns)
(mapcar (function second) import-froms)
(mapcar (function second) shadowing-import-froms))
(list interns exports))
:do (loop
:for lefts :on sets
:for left = (first lefts)
:while (rest lefts)
:do (loop
:for rights :on (rest lefts)
:for right = (first rights)
:for inter = (intersection left right :test (function string=))
:do (when inter
(flet ((set-name (set)
(let ((name (cdr (assoc set (list (cons shadows :shadow)
(cons interns :intern)
(cons exports :export))))))
(or name
(let ((name (first (find set shadowing-import-froms :key (function rest)))))
(when name (list :shadowing-import-from name)))
(let ((name (first (find set import-froms :key (function rest)))))
(when name (list :import-from name)))))))
(error 'simple-program-error
:format-control "Symbol names in common between ~S and ~S: ~S"
:format-arguments (list (set-name left) (set-name right) inter)))))))
nil)
(defun %define-package (name shadows shadowing-imports
uses imports interns exports
documentation nicknames)
(flet ((find-symbols (import-package names option)
(mapcan (lambda (name)
(multiple-value-bind (symbol status) (find-symbol name import-package)
(if (null status)
(progn
(cerror (format nil "Ignore (~S ~~*~~S ~~*~~S)" option)
'symbol-does-not-exist-error
:package import-package
:symbol-name name)
'())
(list symbol))))
names)))
(let ((package (find-package name)))
(if package
(let ((unuse-list (set-difference (mapcar (lambda (np) (if (stringp np) np (package-name np)))
(package-use-list package))
uses :test (function string=))))
(rename-package package name nicknames)
(unuse-package unuse-list package))
(setf package (make-package name :nicknames nicknames :use '())))
(setf (package-documentation package) documentation)
1 . : shadow and : shadowing - import - from .
(shadow shadows package)
(loop
:for (import-package symbols) :in shadowing-imports
:do (shadowing-import (find-symbols import-package symbols
:shadowing-import-from)
package))
2 . : use .
(use-package uses package)
3 . : import - from and : intern .
(loop
:for (import-package symbols) :in imports
:do (import (find-symbols import-package symbols
:import-from)
package))
(dolist (name interns)
(intern name package))
4 . : export .
(export (mapcar (lambda (name) (intern name package)) exports) package)
package)))
(defun classify-per-package (symbols)
(let ((table (make-hash-table))
(result '()))
(dolist (sym symbols)
(push (symbol-name sym) (gethash (symbol-package sym) table '())))
;; should do the same as defpackage/extract-from above.
(maphash (lambda (k v) (push (list k v) result)) table)
result))
;; (set-equal (package-shadowing-symbols p)
( reduce ' union ( cons ( package - shadow - list p )
( mapcar ' rest ( package - shadowing - import - list p ) ) ) ) )
(defgeneric package-shadow-list (package))
(defmethod package-shadow-list (package)
"Return the list of shadowed symbols (but not shadowing-imported ones)"
(remove package (package-shadowing-symbols package)
:test-not (function eql)
:key (function symbol-package)))
(defgeneric package-shadowing-import-list (package))
(defmethod package-shadowing-import-list (package)
"Return a list of lists of shadowing-imports.
Each sublist contains the package followed by its imported symbols."
(classify-per-package (remove package (package-shadowing-symbols package)
:key (function symbol-package))))
;; NOTE: we don't know where the imported symbols were taken from, we
;; only know their home package. If they were imported from a
;; package that used them, or that imported them, then we won't
;; remember it, and will import them directly from their home.
;; This is probably not good.
(defgeneric package-import-from-list (package))
(defmethod package-import-from-list (package)
(let ((symbols '()))
(with-package-iterator (it package :present)
(loop
(multiple-value-bind (got-it symbol kind home) (it)
(declare (ignore kind))
(if got-it
(unless (eq home package) (push symbol symbols))
(return (classify-per-package symbols))))))))
(defgeneric package-symbols (package))
(defmethod package-symbols (package)
(let ((result '()))
(with-package-iterator (it package :present)
(loop
(multiple-value-bind (got-it symbol kind home) (it)
(declare (ignore kind))
(if got-it
(when (eq home package) (push symbol result))
(return result)))))))
(defgeneric package-export-list (package))
(defmethod package-export-list (package)
(let ((result '()))
(with-package-iterator (it package :external)
(loop
(multiple-value-bind (got-it symbol kind home) (it)
(declare (ignore kind home))
(if got-it
(push symbol result)
(return result)))))))
(defmethod make-load-form ((pack package) &optional environment)
(declare (ignore environment))
`(%define-package ',(package-name pack)
',(mapcar (function symbol-name) (package-shadow-list pack))
',(package-shadowing-import-list pack)
',(mapcar (function package-name) (package-use-list pack))
',(package-import-from-list pack)
',(mapcar (function symbol-name) (package-symbols pack))
',(mapcar (function symbol-name) (package-export-list pack))
',(package-documentation pack)
',(package-nicknames pack)))
(defmacro in-package (name)
"
DO: Sets the current *package* to the package designated by NAME.
URL: <>
"
(let ((name (normalize-string-designator name)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(let ((new-package (normalize-package-designator
,name :if-package-does-not-exist :ignore-or-replace)))
(when new-package
(setf *package* new-package))))))
;; To test:
;; (cl-user::cd #P"~/src/lisp/implementations/ansi-tests/") (mapc 'delete-file (directory "*.lx*")) (load "zpack-load.lsp")
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/common-lisp/lisp-reader/package-fun.lisp | lisp | coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
See defpackage documentation string.
Removed " Z " prefix to CL
symbol names; shadowed and exported them.
packages can have circular dependencies.
Are missing some standard restarts to correct
for all conflicts, etc).
LEGAL
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**************************************************************************
Symbol internal management
Pack management
Variables
Conditions
Implementation of syms
integer ::= [sign] digit+
integer ::= [sign] decimal-digit+ decimal-point
ratio ::= [sign] {decimal-digit}+ '/' {decimal-digit}+
float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ exponent
float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+
float ::= [sign] {decimal-digit}+ exponent
float ::= [sign] {decimal-digit}+ decimal-point {decimal-digit}* exponent
exponent ::= exponent-marker [sign] {digit}+
ratio ::= [#b|#o|#x|#{decimal-digit}+r] [sign] digit+ '/' digit+
Parses as a number integer, decimal, ratio or float.
Implementation of sym-tables
Implementation of packs & CL clone interface
remove old names:
set new names:
should do the same as defpackage/extract-from above.
(set-equal (package-shadowing-symbols p)
NOTE: we don't know where the imported symbols were taken from, we
only know their home package. If they were imported from a
package that used them, or that imported them, then we won't
remember it, and will import them directly from their home.
This is probably not good.
To test:
(cl-user::cd #P"~/src/lisp/implementations/ansi-tests/") (mapc 'delete-file (directory "*.lx*")) (load "zpack-load.lsp")
THE END ;;;; | FILE : package.lisp
USER - INTERFACE :
< XACH > < > ,
< PJB > < >
MODIFICATIONS
2012 - 04 - 03 < PJB > Completed corrections to pass package ansi - tests .
2012 - 03 - 30 < PJB > Added checks , made the API conforming to CL .
make - load - form for packages should probably return two forms , since
conflicts . ( choosing one or the other symbol , doing the same
Copyright ( c ) 2012 < > , All Rights Reserved
Copyright ( c ) 2012 < > , All Rights Reserved
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(cl:in-package "COM.INFORMATIMAGO.COMMON-LISP.LISP-READER.PACKAGE")
(defgeneric sym-pack (sym))
(defgeneric (setf sym-pack) (pack sym))
(defgeneric make-constant (symbol value))
Sym tables
(defgeneric make-sym-table ())
(defgeneric tget (sym-name table))
(defgeneric tput (sym table))
(defgeneric tremove (sym table))
(defgeneric tmember (sym table))
(defgeneric tmap-syms (fun table))
(defgeneric tmembers (table))
(defgeneric present-table (pack))
(defgeneric shadowing-table (pack))
(defgeneric external-table (pack))
(defgeneric accessiblep (sym pack))
(defgeneric externalp (sym pack))
(defgeneric shadowingp (sym pack))
(defgeneric presentp (sym pack))
(defgeneric check-import-conflict (sym pack))
(defgeneric check-inherit-conflict (used-pack using-pack))
(defgeneric check-export-conflict (sym pack))
(defgeneric check-unintern-conflict (sym-name pack))
(defgeneric zimport-without-checks (sym pack))
(defgeneric zunintern-without-checks (sym pack))
(defgeneric (setf used-packs) (used-packs pack))
(defgeneric (setf used-by-packs) (used-by-packs pack))
Clone of the CL symbol / package interface
(defgeneric make-symbol (sym-name)
(:documentation "
DO: Make a new symbol
URL: <>
"))
(defgeneric symbol-name (sym)
(:documentation "
RETURN: the name of the symbol.
URL: <>
"))
(defgeneric symbol-package (sym)
(:documentation "
RETURN: the home package of the symbol.
URL: <>
"))
(defgeneric make-package (pack-name &key nicknames use)
(:documentation "
DO: Make a new package.
URL: <>
"))
(defgeneric find-package (pack-name)
(:documentation "
RETURN: The package designated by PACK-NAME, or NIL if none.
URL: <>
"))
(defgeneric delete-package (pack-name)
(:documentation "
DO: Delete the package.
URL: <>
"))
(defgeneric find-symbol (sym-name &optional pack)
(:documentation "
RETURN: the symbol named SYM-NAME in the package PACK, if found and a status keyword.
URL: <>
"))
(defgeneric import (symbols &optional pack)
(:documentation "
DO: Import the symbols into the package.
URL: <>
"))
(defgeneric intern (sym-name &optional pack)
(:documentation "
DO: Intern the symbol name in the package.
URL: <>
"))
(defgeneric shadow (symbol-names &optional pack)
(:documentation "
DO: Shadow the designated symbols.
URL: <>
"))
(defgeneric shadowing-import (symbols &optional pack)
(:documentation "
DO: Shadow and import the designated symbols.
URL: <>
"))
(defgeneric export (sym &optional pack)
(:documentation "
DO: Export the designated symbols from the package.
URL: <>
"))
(defgeneric unexport (sym &optional pack)
(:documentation "
DO: Unexport the designated symbols from the package.
URL: <>
"))
(defgeneric unintern (sym &optional pack)
(:documentation "
DO: Unintern the designated symbols from the package.
URL: <>
"))
(defgeneric use-package (pack &optional using-pack)
(:documentation "
DO: Make the USING-PACK use the package PACK.
URL: <>
"))
(defgeneric unuse-package (pack &optional using-pack)
(:documentation "
DO: Make the USING-PACK unuse the package PACK
URL: <>
"))
(defgeneric package-name (pack)
(:documentation "
RETURN: The package name.
URL: <>
"))
(defgeneric package-use-list (pack)
(:documentation "
RETURN: The list of packages used by PACK.
URL: <>
"))
(defgeneric package-used-by-list (pack)
(:documentation "
RETURN: The list of packages that use PACK.
URL: <>
"))
(defgeneric package-shadowing-symbols (pack)
(:documentation "
RETURN: The list of shadowing symbols of the package.
URL: <>
"))
(defgeneric find-all-symbols (name)
(:documentation "
RETURN: The list of all symbols named NAME in all packages.
URL: <>
"))
(defgeneric rename-package (package new-name &optional new-nicknames)
(:documentation "
DO: Rename the package giving it the NEW-NAME and NEW-NICKNAMES.
URL: <>
"))
(defparameter *keyword-package* nil)
(defparameter *common-lisp-package* nil)
(defparameter *common-lisp-user-package* nil)
(defvar *package* nil
"
The current package.
URL: <>
")
(define-condition simple-error-mixin (condition)
((format-control :initarg :format-control :reader format-control
:initform "Simple error.")
(format-arguments :initarg :format-arguments :reader format-arguments
:initform '()))
(:report (lambda (condition stream)
(format stream "~?"
(format-control condition)
(format-arguments condition)))))
(define-condition simple-program-error (simple-error-mixin program-error)
())
(define-condition simple-type-error (simple-error-mixin type-error)
())
(define-condition print-not-readable (error)
((object :initarg :object :reader print-not-readable-object
:initform (error "Missing :object initarg.")))
(:report (lambda (condition stream)
(let ((*print-readably* nil)
(*print-circle* t)
(*print-length* 4)
(*print-level* 4))
(format stream "The object ~S is not printable readably."
(print-not-readable-object condition))))))
(defgeneric package-error-package (package-error)
(:documentation "
RETURN: The package in error.
URL: <>
"))
(define-condition package-error (error)
((package :initarg :package :reader package-error-package))
(:report (lambda (condition stream)
(format stream "Package error with ~A" (package-error-package condition))))
(:documentation "
The type package-error consists of error conditions related to operations on packages.
URL: <>
"))
(define-condition simple-package-error (package-error simple-error-mixin)
())
(define-condition package-exists-error (simple-package-error)
()
(:documentation "The error condition signaling that a package with the same name already exists."))
(define-condition package-does-not-exist-error (simple-package-error)
()
(:documentation "The error condition signaling that no package with that name exists."))
(defgeneric symbol-conflict-existing-symbol (error)
(:documentation "RETURN: The existing symbol in conflict."))
(defgeneric symbol-conflict-imported-symbol (error)
(:documentation "RETURN: The imported symbol in conflict."))
(define-condition symbol-conflict-error (simple-package-error)
((existing-symbol :initarg :existing-symbol :reader symbol-conflict-existing-symbol)
(imported-symbol :initarg :imported-symbol :reader symbol-conflict-imported-symbol))
(:report (lambda (condition stream)
(format stream "The would-be imported symbol ~S conflicts with the existing symbol ~S in the package ~S"
(symbol-conflict-imported-symbol condition)
(symbol-conflict-existing-symbol condition)
(package-name (package-error-package condition)))))
(:documentation "The error condition signaling a symbol conflict."))
(define-condition symbol-does-not-exist-error (simple-package-error)
((symbol-name :initarg :symbol-name :reader symbol-does-not-exist-symbol-name))
(:report (lambda (condition stream)
(format stream "There exists no symbol named ~S in the package ~S"
(symbol-does-not-exist-symbol-name condition)
(package-name (package-error-package condition))))))
(define-condition symbol-inaccessible-error (simple-package-error)
((symbol :initarg :symbol :reader symbol-inaccessible-symbol))
(:report (lambda (condition stream)
(format stream "~S is not accessible in ~S"
(symbol-inaccessible-symbol condition)
(package-name (package-error-package condition))))))
(defun query-string ()
(format *query-io* "Enter a new string: ")
(finish-output *query-io*)
(list (read-line *query-io*)))
(defun query-symbol ()
(list (loop
:for sym = (progn
(format *query-io* "Enter a new symbol (current package is ~A): "
(package-name *package*))
(finish-output *query-io*)
(read *query-io*))
:until (symbolp sym)
:finally (return sym))))
(defun query-package-name ()
(format *query-io* "Enter a package name (string or symbol): ")
(finish-output *query-io*)
(list (read *query-io*)))
(defun query-package-nickname ()
(format *query-io* "Enter a package nickname (string or symbol): ")
(finish-output *query-io*)
(list (read *query-io*)))
(defgeneric symbol-plist (symbol)
(:documentation "
RETURN: The plist of the symbol.
URL: <>
"))
(defgeneric symbol-value (symbol)
(:documentation "
RETURN: The value of the symbol.
URL: <>
"))
(defgeneric symbol-function (symbol)
(:documentation "
RETURN: The function of the symbol.
URL: <>
"))
(defclass symbol ()
((name
:initarg :name
:reader symbol-name)
(pack
:initarg :pack
:reader symbol-package
:accessor sym-pack)
(plist
:initarg :plist
:initform nil
:accessor symbol-plist)
(value
:initarg :value
:accessor symbol-value)
(function
:initarg :function
:accessor symbol-function)
(constantp
:initarg :constantp
:initform nil
:accessor symbol-constantp))
(:default-initargs
:pack nil)
(:documentation "
The symbol class.
URL: <>
"))
(defgeneric symbolp (object)
(:method ((object t)) nil)
(:method ((object symbol)) t)
(:documentation "
RETURN: Whether the object is a symbol.
URL: <>
"))
(defgeneric boundp (object)
(:method ((object t))
(error 'type-error :datum object :expected-type 'symbol))
(:method ((object symbol))
(slot-boundp object 'value))
(:documentation "
RETURN: Whether the symbol is bound to a value.
URL: <>
"))
(defgeneric fboundp (object)
(:method ((object t))
(error 'type-error :datum object :expected-type 'symbol))
(:method ((object symbol))
(slot-boundp object 'function))
(:documentation "
RETURN: Whether the symbol is fbound to a function.
URL: <>
"))
(defclass keyword (symbol)
()
(:documentation "
The keyword class.
URL: <>
"))
(defgeneric keywordp (object)
(:method ((object t)) nil)
(:method ((object keyword)) t)
(:documentation "
RETURN: Whether the object is a keyword.
URL: <>
"))
(defmethod make-symbol (sym-name)
(make-instance 'symbol :name (copy-seq sym-name)))
(defmethod make-load-form ((sym symbol) &optional environment)
(declare (ignore environment))
`(intern ,(symbol-name sym) ,(package-name (symbol-package sym))))
(defun constituentp (ch first-character-p &optional (readtable *readtable*))
(multiple-value-bind (macro-character-p non-terminating-p) (get-macro-character ch readtable)
(or (not macro-character-p)
(and (not first-character-p)
non-terminating-p))))
(defun specialp (ch &optional (readtable *readtable*))
(declare (ignore readtable))
(find ch #(#\Space #\: #\| #\\
#\Newline #\Tab #\Linefeed #\Return #\Page)))
(defun parses-as-a-number-p (string &key (start 0) (end nil) (base *read-base*))
We may ignore ratio starting with # \ # since that 's excluded by .
(loop
:with end = (or end (length string))
:with i = start
:with state = :opt-sign
:for ch = (and (< i end) (aref string i))
:while (< i end)
:do (ecase state
(:opt-sign (case ch ((#\+ #\-) (incf i)))
(setf state :unknown0))
(:unknown0 (if (<= base 10)
(cond
((digit-char-p ch base) (incf i) (setf state :unknown1))
((digit-char-p ch 10) (incf i) (setf state :decimal))
(t (case ch
((#\.) (incf i) (setf state :float0))
(otherwise (return nil)))))
(cond
((digit-char-p ch 10) (incf i) (setf state :unknown1))
((digit-char-p ch base) (incf i) (setf state :integer))
(t (case ch
((#\.) (incf i) (setf state :float0))
(otherwise (return nil)))))))
(:unknown1 (if (<= base 10)
(cond
((digit-char-p ch base) (incf i) (setf state :unknown1))
((digit-char-p ch 10) (incf i) (setf state :decimal))
(t (case ch
((#\/) (incf i) (setf state :ratio0))
((#\.) (incf i) (setf state :dot))
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(cond
((digit-char-p ch 10) (incf i) (setf state :unknown1))
((digit-char-p ch base) (incf i) (setf state :integer))
(t (case ch
((#\/) (incf i) (setf state :ratio0))
((#\.) (incf i) (setf state :dot))
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))))
(:integer (if (digit-char-p ch base)
(incf i)
(return nil)))
(:decimal (if (digit-char-p ch 10)
(incf i)
(case ch
((#\/) (incf i) (setf state :ratio0))
((#\.) (incf i) (setf state :dot))
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(:dot (if (digit-char-p ch 10)
(progn (incf i) (setf state :float))
(case ch
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(:ratio0 (if (digit-char-p ch 10)
(progn (incf i) (setf state :ratio))
(return nil)))
(:ratio (if (digit-char-p ch 10)
(incf i)
(return nil)))
(:float0 (if (digit-char-p ch 10)
(progn (incf i) (setf state :float))
(return nil)))
(:float (if (digit-char-p ch 10)
(incf i)
(case ch
((#\D #\d #\E #\e #\F #\f #\L #\l #\S #\s)
(incf i) (setf state :float-expo/opt-sign))
(otherwise (return nil)))))
(:float-expo/opt-sign (case ch ((#\+ #\-) (incf i)))
(setf state :float-expo0))
(:float-expo0 (if (digit-char-p ch 10)
(progn (incf i) (setf state :float-expo))
(return nil)))
(:float-expo (if (digit-char-p ch 10)
(incf i)
(return nil))))
:finally (return (case state
((:unknown1 :integer :dot :ratio :float :float-expo) t)
(otherwise nil)))))
(defun needs-escape-p (symbol-name)
"Whether the symbol name needs to be escaped."
(cond
((string= "" symbol-name) t)
((or *print-readably* *print-escape*)
(or (notevery (let ((first-character-p t))
(lambda (ch)
(prog1 (and (not (specialp ch))
(constituentp ch first-character-p))
(setf first-character-p nil))))
symbol-name)
(parses-as-a-number-p symbol-name :base *print-base*)))
(t
nil)))
(defun mixed-case-p (string)
"Whether the string contains both lower case and upper case letters."
(and (some (lambda (ch) (and (alpha-char-p ch) (upper-case-p ch))) string)
(some (lambda (ch) (and (alpha-char-p ch) (lower-case-p ch))) string)))
(defun prepare-symbol-name (sname)
(cond
((needs-escape-p sname)
(with-output-to-string (*standard-output*)
(loop
:for ch :across sname
:initially (princ "|")
:do (if (char= #\| ch) (princ "\\|") (princ ch))
:finally (princ "|"))))
(t
(let ((transform
(if *print-escape*
(ecase (readtable-case *readtable*)
(:upcase (lambda (ch)
(if (both-case-p ch)
(if (lower-case-p ch)
(format nil "\\~C" ch)
ch)
ch)))
(:downcase (lambda (ch)
(if (both-case-p ch)
(if (upper-case-p ch)
(format nil "\\~C" ch)
ch))))
(:preserve (function identity))
(:invert (function identity)))
(ecase (readtable-case *readtable*)
(:upcase (let ((start-word t))
(lambda (ch)
(prog1 (if (both-case-p ch)
(if (upper-case-p ch)
(ecase *print-case*
(:upcase ch)
(:downcase (char-downcase ch))
(:capitalize (if start-word
(char-upcase ch)
(char-downcase ch))))
ch)
ch)
(if (alphanumericp ch)
(setf start-word nil)
(setf start-word t))))))
(:downcase (let ((start-word t))
(lambda (ch)
(prog1 (if (both-case-p ch)
(if (lower-case-p ch)
(ecase *print-case*
(:upcase (char-upcase ch))
(:downcase ch)
(:capitalize (if start-word
(char-upcase ch)
(char-downcase ch))))
ch)
ch)
(if (alphanumericp ch)
(setf start-word nil)
(setf start-word t))))))
(:preserve (function identity))
(:invert (if (mixed-case-p sname)
(function identity)
(lambda (ch)
(cond
((not (both-case-p ch)) ch)
((upper-case-p ch) (char-downcase ch))
((lower-case-p ch) (char-upcase ch))
(t ch)))))))))
(with-output-to-string (*standard-output*)
(loop
:for ch :across sname
:do (princ (funcall transform ch))))))))
(defmethod print-object ((sym symbol) stream)
(let ((*print-readably* t))
(flet ((print-it ()
(let ((pack (symbol-package sym)))
(cond ((null pack)
(format stream "~:[~;#:~]~A"
(or *print-readably* (and *print-escape* *print-gensym*))
(prepare-symbol-name (symbol-name sym))))
((eql pack *keyword-package*)
(format stream ":~A"
(prepare-symbol-name (symbol-name sym))))
((or (eq pack *package*)
(eq sym (find-symbol (symbol-name sym) *package*)))
(format stream "~A" (prepare-symbol-name (symbol-name sym))))
(t
(format stream "~A~:[::~;:~]~A"
(prepare-symbol-name (package-name pack))
(externalp sym pack)
(prepare-symbol-name (symbol-name sym))))))))
(if *print-readably*
(print-it)
(progn
(format stream "#<~S " 'symbol)
(print-it)
(format stream ">")))))
sym)
(defmethod make-constant (symbol value)
(declare (ignorable value))
(setf (symbol-value symbol) value
(symbol-constantp symbol) t)
symbol)
(defclass sym-table ()
((name-table
:initarg :name-table
:reader name-table))
(:default-initargs
:name-table (make-hash-table :test 'equal)))
(defmethod make-sym-table ()
(make-instance 'sym-table))
(defmethod tget (sym-name table)
(values (gethash sym-name (name-table table))))
(defmethod tmember (sym table)
(let ((entry (tget (symbol-name sym) table)))
(eq entry sym)))
(defmethod tput (sym table)
(setf (gethash (symbol-name sym) (name-table table)) sym))
(defmethod tremove (sym table)
(remhash (symbol-name sym) (name-table table)))
(defmethod tmap-syms (fun table)
(maphash (lambda (sym-name sym)
(declare (ignore sym-name))
(funcall fun sym))
(name-table table)))
(defmethod tmembers (table)
(let ((members '()))
(tmap-syms (lambda (sym)
(push sym members))
table)
members))
(defparameter *packs* (make-hash-table :test 'equal))
(defun list-all-packages ()
"
RETURN: A fresh list of all registered packages.
URL: <>
"
(let ((packages '()))
(maphash (lambda (k v) (declare (ignore k)) (pushnew v packages)) *packs*)
packages))
(defgeneric package-documentation (package)
(:documentation "RETURN: The documentation string of the package."))
(defgeneric package-nicknames (package)
(:documentation "RETURN: The list of nicknames of the package."))
(defclass package ()
((name
:initarg :name
:reader package-name
:writer (setf name))
(external-table
:initarg :external-table
:reader external-table)
(present-table
:initarg :present-table
:reader present-table)
(shadowing-table
:initarg :shadowing-table
:reader shadowing-table)
(used-packs
:initarg :used-packs
:reader package-use-list
:writer (setf used-packs))
(used-by-packs
:initarg :used-by-packs
:reader package-used-by-list
:writer (setf used-by-packs))
(nicknames
:initarg :nicknames
:reader package-nicknames
:writer (setf nicknames))
(documentation
:initarg :documentation
:initform nil
:accessor package-documentation))
(:default-initargs
:name (error "A package name is required")
:external-table (make-sym-table)
:present-table (make-sym-table)
:shadowing-table (make-sym-table)
:used-packs nil
:used-by-packs nil)
(:documentation "
The package class.
URL: <>
"))
(defmacro define-normalize-package-methods (name &key (if-package-does-not-exist :replace) (type-error nil))
`(progn
,@ (when type-error
`((defmethod ,name ((name t)) (error 'simple-type-error
:datum name
:expected-type 'package-designator
:format-control "~S called with a non ~S: ~S"
:format-arguments (list ',name 'package-designator name)))))
(defmethod ,name ((name string)) (,name (normalize-package-designator name :if-package-does-not-exist ,if-package-does-not-exist)))
(defmethod ,name ((name character)) (,name (normalize-package-designator name :if-package-does-not-exist ,if-package-does-not-exist)))
(defmethod ,name ((name cl:symbol)) (,name (normalize-package-designator name :if-package-does-not-exist ,if-package-does-not-exist)))
(defmethod ,name ((name symbol)) (,name (normalize-package-designator (symbol-name name) :if-package-does-not-exist ,if-package-does-not-exist)))))
(define-normalize-package-methods package-name :type-error t)
(define-normalize-package-methods package-use-list :type-error t)
(define-normalize-package-methods package-used-by-list :type-error t)
(define-normalize-package-methods package-nicknames :type-error t)
(define-normalize-package-methods package-shadowing-symbols)
(defgeneric packagep (package)
(:method ((object t)) nil)
(:method ((package package)) t)
(:documentation "
RETURN: Whether the object is a package.
URL: <>
"))
(defmethod print-object ((pack package) stream)
(if *print-readably*
(error 'print-not-readable :object pack)
(format stream "#<~S ~S>" 'package (package-name pack)))
pack)
(defmethod package-shadowing-symbols (pack)
(tmembers (shadowing-table pack)))
(defmethod accessiblep (sym pack)
(let ((existing-sym (find-symbol (symbol-name sym) pack)))
(eq existing-sym sym)))
(defmethod externalp (sym pack)
(tmember sym (external-table pack)))
(defmethod shadowingp (sym pack)
(tmember sym (shadowing-table pack)))
(defmethod presentp (sym pack)
(tmember sym (present-table pack)))
(defun ensure-list (object)
(if (listp object)
object
(list object)))
(deftype string-designator ()
'(or string character symbol cl:symbol))
(defun normalize-string-designator (object &key (if-not-a-string-designator :error))
(check-type if-not-a-string-designator (member nil :error :ignore :replace :ignore-or-replace))
(typecase object
(string object)
(character (string object))
(cl:symbol (string object))
(symbol (symbol-name object))
(otherwise
(case if-not-a-string-designator
((:error) (error 'type-error
:datum object
:expected-type 'string-designator))
((nil) nil)
((:ignore :replace :ignore-or-replace)
(restart-case (error 'type-error
:datum object
:expected-type 'string-designator)
(ignore ()
:test (lambda (condition)
(declare (ignore condition))
(member if-not-a-string-designator '(:ignore :ignore-or-replace)))
:report "Ignore it."
nil)
(read-a-new-string-designator (new-string)
:test (lambda (condition)
(declare (ignore condition))
(member if-not-a-string-designator '(:replace :ignore-or-replace)))
:interactive query-string
:report "Enter a string"
(normalize-string-designator
new-string
:if-not-a-string-designator if-not-a-string-designator))))))))
(defun normalize-weak-designator-of-list-of-string-designator (object)
(mapcan (lambda (nickname)
(ensure-list (normalize-string-designator
nickname
:if-not-a-string-designator :ignore-or-replace)))
(ensure-list object)))
(deftype package-designator ()
'(or package string-designator))
(defun normalize-package-designator (object &key
(if-package-does-not-exist :string)
(if-package-exists :package)
(if-not-a-package-designator :error))
"
Normalize the given PACKAGE-DESIGNATOR. Objects of type
PACKAGE-DESIGNATOR are either PACKAGE or objects of type
STRING-DESIGNATOR.
RETURN: either NIL, a STRING designating a non-existent package, or an
existing PACKAGE.
IF-NOT-A-PACKAGE-DESIGNATOR The default is :ERROR.
NIL If the OBJECT is not a PACKAGE-DESIGNATOR
then return NIL.
:ERROR If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR.
:IGNORE If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR, with an IGNORE
restart that when chosen returns NIL.
:REPLACE If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR, with a replace
restart that when chosen let the user
input another PACKAGE-DESIGNATOR.
:IGNORE-OR-REPLACE If the OBJECT is not a PACKAGE-DESIGNATOR
then signal a TYPE-ERROR, with the two
previous restarts.
If the object is a PACKAGE-DESIGNATOR, then the results depends on the
following parameters and whether the designated package exists or not.
IF-PACKAGE-DOES-NOT-EXIST The default is :STRING
NIL If the OBJECT designates a PACKAGE that
doesn't exist then return NIL.
:STRING If the OBJECT designates a PACKAGE that
doesn't exist then (it would be a
STRING-DESIGNATOR) return the designated
STRING.
:ERROR If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR.
:IGNORE If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR with an
IGNORE restart that when chosen returns
NIL.
:REPLACE If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR with a
replace restart that when chosen let the
user input another PACKAGE-DESIGNATOR.
:IGNORE-OR-REPLACE If the OBJECT designates a PACKAGE that
doesn't exist then signal a
PACKAGE-DOES-NOT-EXIST-ERROR with the two
previous restarts.
IF-PACKAGE-EXISTS The default is :PACKAGE
:PACKAGE If the OBJECT designates a PACKAGE that
does exist then return the designated
PACKAGE.
:STRING If the OBJECT designates a PACKAGE that
does exist then return the designated
package name.
:ERROR If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR.
:IGNORE If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR with an IGNORE
restart that when chosen returns NIL.
:REPLACE If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR with a replace
restart that when chosen let the user
input another PACKAGE-DESIGNATOR.
:IGNORE-OR-REPLACE If the OBJECT designates a PACKAGE that
does exist then signal a
PACKAGE-EXISTS-ERROR with the two previous
restarts.
"
(check-type if-not-a-package-designator (member :error :ignore :replace :ignore-or-replace nil))
(check-type if-package-does-not-exist (member :error :ignore :replace :ignore-or-replace :string nil))
(check-type if-package-exists (member :error :ignore :replace :ignore-or-replace :string :package))
(flet ((retry-string-designator (restarts condition &rest arguments)
(check-type restarts (member :ignore :replace :ignore-or-replace))
(restart-case (apply (function error) condition arguments)
(ignore ()
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:ignore :ignore-or-replace)))
:report "Ignore it."
nil)
(read-a-new-package-designator (new-package)
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:replace :ignore-or-replace)))
:interactive query-package-name
:report "Enter a package name"
(normalize-package-designator
new-package
:if-not-a-package-designator if-not-a-package-designator
:if-package-does-not-exist if-package-does-not-exist
:if-package-exists if-package-exists))))
(retry-package-designator (restarts condition &rest arguments)
(check-type restarts (member :ignore :replace :ignore-or-replace))
(restart-case (apply (function error) condition arguments)
(ignore ()
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:ignore :ignore-or-replace)))
:report "Ignore it."
nil)
(read-a-new-package-designator (new-package)
:test (lambda (condition)
(declare (ignore condition))
(member restarts '(:replace :ignore-or-replace)))
:interactive query-package-name
:report "Enter a package name"
(normalize-package-designator
new-package
:if-not-a-package-designator if-not-a-package-designator
:if-package-does-not-exist if-package-does-not-exist
:if-package-exists if-package-exists)))))
(typecase object
(string-designator
(let* ((normalized (normalize-string-designator object))
(package (find-package normalized)))
(if package
(normalize-package-designator package :if-package-exists if-package-exists)
(case if-package-does-not-exist
((nil) nil)
((:string) normalized)
((:error) (error
'package-does-not-exist-error
:package normalized
:format-control "There is no package named ~S"
:format-arguments (list normalized)))
((:ignore :replace :ignore-or-replace)
(retry-package-designator if-package-does-not-exist
'package-does-not-exist-error
:package normalized
:format-control "There is no package named ~S"
:format-arguments (list normalized)))))))
(package
(case if-package-exists
((:package) object)
((:string) (package-name object))
((:error) (error
'package-exists-error
:package object
:format-control "There is already a package named ~S"
:format-arguments (list (package-name object))))
((:ignore :replace :ignore-or-replace)
(retry-package-designator if-package-exists
'package-exists-error
:package object
:format-control "There is already a package named ~S"
:format-arguments (list (package-name object))))))
(otherwise
(case if-not-a-package-designator
((nil) nil)
((:error) (error 'type-error
:datum object
:expected-type 'package-designator))
((:ignore :replace :ignore-or-replace)
(retry-string-designator if-not-a-package-designator
'type-error
:datum object
:expected-type 'package-designator)))))))
(defun make-package-iterator (packages symbol-types)
(let ((packages (mapcan (lambda (package-designator)
(list (normalize-package-designator
package-designator :if-package-does-not-exist :ignore-or-replace)))
(ensure-list packages)))
(package nil)
(stypes nil)
(stype nil)
(symbols '()))
(labels ((iterator ()
(cond
(symbols (let ((sym (pop symbols)))
(values t
sym
(cond
((externalp sym package) :external)
((eq stype :inherited) stype)
(t :internal))
package)))
(stypes (setf stype (pop stypes))
(ecase stype
((:internal)
(tmap-syms (lambda (sym)
(unless (externalp sym package)
(push sym symbols)))
(present-table package)))
((:external)
(tmap-syms (lambda (sym) (push sym symbols))
(external-table package)))
((:inherited)
(dolist (pack (package-use-list package))
(tmap-syms (lambda (sym)
(let ((shadow (find-symbol (symbol-name sym) package)))
(unless (and shadow
(shadowingp shadow package)
(not (eq sym shadow)))
(push sym symbols))))
(external-table (find-package pack)))))
((:present)
(tmap-syms (lambda (sym) (push sym symbols))
(present-table package)))
((:shadowing)
(tmap-syms (lambda (sym) (push sym symbols))
(shadowing-table package))))
(iterator))
(packages (setf package (pop packages)
stypes symbol-types)
(iterator))
(t nil))))
(function iterator))))
(defmethod check-import-conflict (sym pack)
(let ((existing-sym (find-symbol (symbol-name sym) pack)))
(if (and existing-sym (not (eq existing-sym sym)))
(restart-case (error 'symbol-conflict-error
:package pack
:format-control "Conflict: importing ~A into ~A conflicts with ~A"
:format-arguments (list sym pack existing-sym)
:existing-symbol existing-sym
:imported-symbol sym)
(enter-new-name (new-symbol)
:interactive query-symbol
:report "Enter a new symbol, instead"
(check-import-conflict new-symbol pack))
(ignore-symbol ()
:report (lambda (stream) (format stream "Ignore the symbol ~S" sym))
(values nil nil)))
(values sym t))))
(defmacro zdo-external-symbols ((var pack) &body body)
`(tmap-syms (lambda (,var)
,@body)
(external-table ,pack)))
(defmethod check-inherit-conflict (used-pack using-pack)
(zdo-external-symbols (inherited-sym used-pack)
(let ((existing-sym (find-symbol (symbol-name inherited-sym)
using-pack)))
(when (and existing-sym
(not (eq inherited-sym existing-sym))
(not (shadowingp existing-sym using-pack)))
(error "Conflict: Inheriting ~A from ~A conflicts with ~A in ~A"
inherited-sym
used-pack
existing-sym
using-pack)))))
(defmethod check-export-conflict (sym pack)
(let ((sym-name (symbol-name sym)))
(dolist (using-pack (package-used-by-list pack))
(let ((existing-sym (find-symbol sym-name using-pack)))
(when (and existing-sym
(not (member existing-sym (package-shadowing-symbols using-pack))))
(unless (eq existing-sym sym)
(error "Conflict: exporting ~A conflicts with ~A in ~A"
sym existing-sym using-pack)))))))
(defmethod check-unintern-conflict (sym pack)
(let ((sym-name (symbol-name sym))
(first-existing-sym nil))
(dolist (used-pack (package-use-list pack))
(let ((existing-sym (find-symbol sym-name used-pack)))
(when existing-sym
(if first-existing-sym
(unless (eq existing-sym first-existing-sym)
(error "Conflict: uninterning ~A would lead to conflict ~
between ~A and ~A"
sym first-existing-sym existing-sym))
(setf first-existing-sym existing-sym)))))))
(defmethod zimport-without-checks (sym pack)
(tput sym (present-table pack))
(unless (symbol-package sym)
(setf (sym-pack sym) pack)))
(defmethod zunintern-without-checks (sym pack)
(tremove sym (external-table pack))
(tremove sym (shadowing-table pack))
(tremove sym (present-table pack))
(when (eq (symbol-package sym) pack)
(setf (sym-pack sym) nil)))
(defun check-new-names (pack-name nicknames &key renaming-package)
(loop
:with result = '()
:for name :in (cons pack-name nicknames)
:do (loop
:for pack = (find-package name)
:while (if renaming-package
(and pack (not (eq pack renaming-package)))
pack)
:do (restart-case (error 'package-exists-error
:package name
:format-control "A package named ~S already exists"
:format-arguments (list name))
(enter-new-name (new-name)
:test (lambda (condition) (declare (ignore condition)) (eq name pack-name))
:interactive query-package-name
:report "Enter a new package name, instead"
(setf name new-name))
(enter-new-name (new-name)
:test (lambda (condition) (declare (ignore condition)) (not (eq name pack-name)))
:report "Enter a new package nickname, instead"
:interactive query-package-nickname
(setf name new-name))
(ignore-nickname ()
:test (lambda (condition) (declare (ignore condition)) (not (eq name pack-name)))
:report (lambda (stream) (format stream "Ignore the nickname ~S" name))
(return)))
:finally (push name result))
:finally (let ((result (nreverse result)))
(return (values (car result) (cdr result))))))
(defmethod make-package (pack-name &key (nicknames '()) (use '()))
(let ((pack-name (normalize-string-designator pack-name :if-not-a-string-designator :replace))
(nicknames (normalize-weak-designator-of-list-of-string-designator nicknames))
(use (mapcan (lambda (package-designator)
(list (normalize-package-designator
package-designator :if-package-does-not-exist :ignore-or-replace)))
use)))
(multiple-value-setq (pack-name nicknames) (check-new-names pack-name nicknames))
(let ((package (make-instance 'package
:name (copy-seq pack-name)
:nicknames (mapcar (function copy-seq) nicknames))))
(dolist (upack use)
(use-package upack package))
(dolist (name (cons pack-name nicknames) package)
(setf (gethash name *packs*) package)))))
(defmethod find-package (pack-name)
(etypecase pack-name
(string-designator
(values (gethash (normalize-string-designator pack-name) *packs*)))
(package pack-name)))
(defmethod delete-package (pack)
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :replace)))
(when (and pack (package-name pack))
(dolist (used (package-used-by-list pack))
(unuse-package pack used))
(dolist (puse (package-use-list pack))
(unuse-package puse pack))
(do-symbols (sym pack)
(when (eq (symbol-package sym) pack)
(zunintern-without-checks sym pack)))
(dolist (name (cons (package-name pack) (package-nicknames pack)))
(remhash name *packs*))
(setf (name pack) nil)
pack)))
(defmethod find-symbol (sym-name &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :replace))
sym)
(cond ((setf sym (tget sym-name (external-table pack)))
(values sym :external))
((setf sym (tget sym-name (shadowing-table pack)))
(values sym :internal))
((setf sym (some (lambda (used-pack)
(tget sym-name (external-table used-pack)))
(package-use-list pack)))
(values sym :inherited))
((setf sym (tget sym-name (present-table pack)))
(values sym :internal))
(t
(values nil nil)))))
(defmethod import (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-import (sym)
(check-type sym symbol)
(multiple-value-bind (sym good) (check-import-conflict sym pack)
(when (and good (not (presentp sym pack)))
(if (and (null (symbol-package sym))
(eql pack *keyword-package*))
(progn
(zimport-without-checks sym pack)
(change-class sym 'keyword)
(make-constant sym sym)
(export sym pack))
(zimport-without-checks sym pack))))))
(mapc (function do-import) (ensure-list symbols)))
t))
(defmethod intern (sym-name &optional (pack *package*))
(check-type sym-name string)
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(multiple-value-bind (sym status) (find-symbol sym-name pack)
(if status
(values sym status)
(values (let ((sym (make-symbol sym-name)))
(import sym pack)
(when (eql pack *keyword-package*)
(change-class sym 'keyword)
(make-constant sym sym)
(export sym pack))
sym)
nil)))))
(defmethod shadow (symbol-names &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-shadow (sym-name)
(let ((sym (tget sym-name (present-table pack))))
(unless sym
(setf sym (make-symbol sym-name))
(zimport-without-checks sym pack))
(tput sym (shadowing-table pack)))))
(mapc (function do-shadow)
(normalize-weak-designator-of-list-of-string-designator symbol-names)))
t))
(defmethod shadowing-import (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-shadowing-import (sym)
(check-type sym symbol)
(let ((sym-name (symbol-name sym)))
(multiple-value-bind (existing-sym type) (find-symbol sym-name pack)
(case type
((nil :inherited)
(zimport-without-checks sym pack))
((:external :internal)
(unless (eq existing-sym sym)
(zunintern-without-checks existing-sym pack)
(import sym pack))))
(tput sym (shadowing-table pack))))))
(mapc (function do-shadowing-import) (ensure-list symbols))
t)))
(defmethod export (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-export (sym)
(check-type sym symbol)
(unless (accessiblep sym pack)
(error 'symbol-inaccessible-error :package pack :symbol sym))
(check-export-conflict sym pack)
(unless (presentp sym pack)
(import sym pack))
(tput sym (external-table pack))))
(mapc (function do-export) (ensure-list symbols))
t)))
(defmethod unexport (symbols &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(flet ((do-unexport (sym)
(check-type sym symbol)
(unless (accessiblep sym pack)
(error 'symbol-inaccessible-error :package pack :symbol sym))
(tremove sym (external-table pack))))
(mapc (function do-unexport) (ensure-list symbols))
t)))
(defmethod unintern (sym &optional (pack *package*))
(let ((pack (normalize-package-designator
pack :if-package-does-not-exist :error)))
(when (accessiblep sym pack)
(check-unintern-conflict sym pack)
(zunintern-without-checks sym pack)
t)))
(defmethod use-package (packs &optional (using-pack *package*))
(let ((using-pack (normalize-package-designator using-pack :if-package-does-not-exist :error)))
(dolist (pack (ensure-list packs) t)
(let* ((pack (normalize-package-designator pack :if-package-does-not-exist :error))
(use-list (package-use-list using-pack)))
(unless (member pack use-list)
(check-inherit-conflict pack using-pack)
(setf (used-packs using-pack) (cons pack use-list))
(setf (used-by-packs pack) (cons using-pack (package-used-by-list pack))))))))
(defmethod unuse-package (packs &optional (using-pack *package*))
(let ((using-pack (normalize-package-designator using-pack :if-package-does-not-exist :error)))
(dolist (pack (ensure-list packs) t)
(let ((pack (normalize-package-designator pack :if-package-does-not-exist :error)))
(setf (used-packs using-pack) (remove pack (package-use-list using-pack)))
(setf (used-by-packs pack) (remove using-pack (package-used-by-list pack)))))))
(defmethod find-all-symbols (name)
(let ((name (normalize-string-designator name))
(symbols '()))
(dolist (pack (list-all-packages) (delete-duplicates symbols))
(multiple-value-bind (sym found) (find-symbol name pack)
(when found
(push sym symbols))))))
(defmethod rename-package (package new-name &optional new-nicknames)
(let ((package (normalize-package-designator
package :if-package-does-not-exist :error))
(new-name (normalize-string-designator new-name))
(new-nicknames (normalize-weak-designator-of-list-of-string-designator new-nicknames)))
(multiple-value-setq (new-name new-nicknames) (check-new-names new-name new-nicknames
:renaming-package package))
(dolist (name (cons (package-name package) (package-nicknames package)))
(remhash name *packs*))
(setf (name package) (copy-seq new-name)
(nicknames package) (mapcar (function copy-seq) new-nicknames))
(dolist (name (cons new-name new-nicknames) package)
(setf (gethash name *packs*) package))))
(defun check-disjoints (shadows shadowing-import-froms import-froms
interns exports)
(loop
:for sets :in (list (append (list shadows interns)
(mapcar (function second) import-froms)
(mapcar (function second) shadowing-import-froms))
(list interns exports))
:do (loop
:for lefts :on sets
:for left = (first lefts)
:while (rest lefts)
:do (loop
:for rights :on (rest lefts)
:for right = (first rights)
:for inter = (intersection left right :test (function string=))
:do (when inter
(flet ((set-name (set)
(let ((name (cdr (assoc set (list (cons shadows :shadow)
(cons interns :intern)
(cons exports :export))))))
(or name
(let ((name (first (find set shadowing-import-froms :key (function rest)))))
(when name (list :shadowing-import-from name)))
(let ((name (first (find set import-froms :key (function rest)))))
(when name (list :import-from name)))))))
(error 'simple-program-error
:format-control "Symbol names in common between ~S and ~S: ~S"
:format-arguments (list (set-name left) (set-name right) inter)))))))
nil)
(defun %define-package (name shadows shadowing-imports
uses imports interns exports
documentation nicknames)
(flet ((find-symbols (import-package names option)
(mapcan (lambda (name)
(multiple-value-bind (symbol status) (find-symbol name import-package)
(if (null status)
(progn
(cerror (format nil "Ignore (~S ~~*~~S ~~*~~S)" option)
'symbol-does-not-exist-error
:package import-package
:symbol-name name)
'())
(list symbol))))
names)))
(let ((package (find-package name)))
(if package
(let ((unuse-list (set-difference (mapcar (lambda (np) (if (stringp np) np (package-name np)))
(package-use-list package))
uses :test (function string=))))
(rename-package package name nicknames)
(unuse-package unuse-list package))
(setf package (make-package name :nicknames nicknames :use '())))
(setf (package-documentation package) documentation)
1 . : shadow and : shadowing - import - from .
(shadow shadows package)
(loop
:for (import-package symbols) :in shadowing-imports
:do (shadowing-import (find-symbols import-package symbols
:shadowing-import-from)
package))
2 . : use .
(use-package uses package)
3 . : import - from and : intern .
(loop
:for (import-package symbols) :in imports
:do (import (find-symbols import-package symbols
:import-from)
package))
(dolist (name interns)
(intern name package))
4 . : export .
(export (mapcar (lambda (name) (intern name package)) exports) package)
package)))
(defun classify-per-package (symbols)
(let ((table (make-hash-table))
(result '()))
(dolist (sym symbols)
(push (symbol-name sym) (gethash (symbol-package sym) table '())))
(maphash (lambda (k v) (push (list k v) result)) table)
result))
( reduce ' union ( cons ( package - shadow - list p )
( mapcar ' rest ( package - shadowing - import - list p ) ) ) ) )
(defgeneric package-shadow-list (package))
(defmethod package-shadow-list (package)
"Return the list of shadowed symbols (but not shadowing-imported ones)"
(remove package (package-shadowing-symbols package)
:test-not (function eql)
:key (function symbol-package)))
(defgeneric package-shadowing-import-list (package))
(defmethod package-shadowing-import-list (package)
"Return a list of lists of shadowing-imports.
Each sublist contains the package followed by its imported symbols."
(classify-per-package (remove package (package-shadowing-symbols package)
:key (function symbol-package))))
(defgeneric package-import-from-list (package))
(defmethod package-import-from-list (package)
(let ((symbols '()))
(with-package-iterator (it package :present)
(loop
(multiple-value-bind (got-it symbol kind home) (it)
(declare (ignore kind))
(if got-it
(unless (eq home package) (push symbol symbols))
(return (classify-per-package symbols))))))))
(defgeneric package-symbols (package))
(defmethod package-symbols (package)
(let ((result '()))
(with-package-iterator (it package :present)
(loop
(multiple-value-bind (got-it symbol kind home) (it)
(declare (ignore kind))
(if got-it
(when (eq home package) (push symbol result))
(return result)))))))
(defgeneric package-export-list (package))
(defmethod package-export-list (package)
(let ((result '()))
(with-package-iterator (it package :external)
(loop
(multiple-value-bind (got-it symbol kind home) (it)
(declare (ignore kind home))
(if got-it
(push symbol result)
(return result)))))))
(defmethod make-load-form ((pack package) &optional environment)
(declare (ignore environment))
`(%define-package ',(package-name pack)
',(mapcar (function symbol-name) (package-shadow-list pack))
',(package-shadowing-import-list pack)
',(mapcar (function package-name) (package-use-list pack))
',(package-import-from-list pack)
',(mapcar (function symbol-name) (package-symbols pack))
',(mapcar (function symbol-name) (package-export-list pack))
',(package-documentation pack)
',(package-nicknames pack)))
(defmacro in-package (name)
"
DO: Sets the current *package* to the package designated by NAME.
URL: <>
"
(let ((name (normalize-string-designator name)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(let ((new-package (normalize-package-designator
,name :if-package-does-not-exist :ignore-or-replace)))
(when new-package
(setf *package* new-package))))))
|
68cbc6543615f4c2152cd9ad67605e5ded60f53bfba19ba9151aa3384dcc2700 | bvaugon/ocapic | display.ml | (*************************************************************************)
(* *)
(* OCaPIC *)
(* *)
(* *)
This file is distributed under the terms of the CeCILL license .
(* See file ../../LICENSE-en. *)
(* *)
(*************************************************************************)
open Pic;;
open Types;;
set_bit IRCF1;;
set_bit IRCF0;;
set_bit PLLEN;;
module Disp = Lcd.Connect (
struct
let bus_size = Lcd.Eight
let e = LATA0
let rs = LATA1
let rw = LATA3
let bus = PORTB
end
);;
open Disp;;
init ();;
config ();;
let string_of_size s =
match s with
| Minus -> "."
| Small -> "\161"
| Medium -> "o"
| Big -> "\219"
;;
let string_of_column c =
let s = Bytes.create 1 in
Bytes.set s 0 (char_of_int ((int_of_char 'A') + c));
Bytes.unsafe_to_string s
;;
let string_of_line l =
let s = Bytes.create 1 in
Bytes.set s 0 (char_of_int ((int_of_char '1') + l));
Bytes.unsafe_to_string s
;;
let write_action a =
clear ();
home ();
match a with
| Add (g, i, j) ->
if g.color = White then print_string "W" else print_string "B";
print_string (string_of_size g.size);
print_string " in ";
print_string (string_of_column i);
print_string (string_of_line j);
| Move (i, j, k, l) ->
print_string (string_of_column i);
print_string (string_of_line j);
print_string " -> ";
print_string (string_of_column k);
print_string (string_of_line l);
| Nothing -> invalid_arg "write_action"
;;
let write_string_at l c s =
moveto l c;
print_string s;
;;
let write_string s =
clear ();
home ();
print_string s;
;;
| null | https://raw.githubusercontent.com/bvaugon/ocapic/a14cd9ec3f5022aeb5fe2264d595d7e8f1ddf58a/tests/goblet/display.ml | ocaml | ***********************************************************************
OCaPIC
See file ../../LICENSE-en.
*********************************************************************** |
This file is distributed under the terms of the CeCILL license .
open Pic;;
open Types;;
set_bit IRCF1;;
set_bit IRCF0;;
set_bit PLLEN;;
module Disp = Lcd.Connect (
struct
let bus_size = Lcd.Eight
let e = LATA0
let rs = LATA1
let rw = LATA3
let bus = PORTB
end
);;
open Disp;;
init ();;
config ();;
let string_of_size s =
match s with
| Minus -> "."
| Small -> "\161"
| Medium -> "o"
| Big -> "\219"
;;
let string_of_column c =
let s = Bytes.create 1 in
Bytes.set s 0 (char_of_int ((int_of_char 'A') + c));
Bytes.unsafe_to_string s
;;
let string_of_line l =
let s = Bytes.create 1 in
Bytes.set s 0 (char_of_int ((int_of_char '1') + l));
Bytes.unsafe_to_string s
;;
let write_action a =
clear ();
home ();
match a with
| Add (g, i, j) ->
if g.color = White then print_string "W" else print_string "B";
print_string (string_of_size g.size);
print_string " in ";
print_string (string_of_column i);
print_string (string_of_line j);
| Move (i, j, k, l) ->
print_string (string_of_column i);
print_string (string_of_line j);
print_string " -> ";
print_string (string_of_column k);
print_string (string_of_line l);
| Nothing -> invalid_arg "write_action"
;;
let write_string_at l c s =
moveto l c;
print_string s;
;;
let write_string s =
clear ();
home ();
print_string s;
;;
|
040770b997d02f5999a15d17003ef1f0db920b337c74376788891650523e93a9 | bytekid/mkbtt | slDebug.ml | type verbosity_t =
QUIET | INFO | DEBUG | TRACE;;
let verbosity = ref QUIET;;
let parse_verbosity = function
"quiet" | "0" -> QUIET
| "info" | "1" -> INFO
| "debug" | "2" | "" -> DEBUG
| "trace" | "3" -> TRACE
| x -> failwith ("Unable to parse debug level: " ^ x)
;;
let set_verbosity s =
verbosity := (parse_verbosity s)
;;
let should_display msg_level =
match msg_level,(!verbosity) with
QUIET,_ -> true
| INFO,QUIET -> false
| INFO,_ -> true
| DEBUG,QUIET | DEBUG,INFO -> false
| DEBUG,_ -> true
| TRACE,TRACE -> true
| TRACE,_ -> false
;;
let display_fun level =
match level with
INFO -> print_endline
| _ -> prerr_endline
;;
let maybe_debug level msg =
if should_display level then
let print = display_fun level in
print msg
;;
let debug_if level b msg =
if b then maybe_debug level msg
;;
let debug_l level f =
if should_display level then
let print = display_fun level in
print (Lazy.force f)
;;
let debug_if_l level b f =
if b then debug_l level f
;;
let alert msg = maybe_debug QUIET msg;;
let error msg = maybe_debug QUIET ("ERROR:\n" ^ msg);;
let info msg = maybe_debug INFO msg;;
let debug msg = debug_l DEBUG msg;;
let trace msg = debug_l TRACE msg;;
| null | https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/mkbtt/slothrop/slDebug.ml | ocaml | type verbosity_t =
QUIET | INFO | DEBUG | TRACE;;
let verbosity = ref QUIET;;
let parse_verbosity = function
"quiet" | "0" -> QUIET
| "info" | "1" -> INFO
| "debug" | "2" | "" -> DEBUG
| "trace" | "3" -> TRACE
| x -> failwith ("Unable to parse debug level: " ^ x)
;;
let set_verbosity s =
verbosity := (parse_verbosity s)
;;
let should_display msg_level =
match msg_level,(!verbosity) with
QUIET,_ -> true
| INFO,QUIET -> false
| INFO,_ -> true
| DEBUG,QUIET | DEBUG,INFO -> false
| DEBUG,_ -> true
| TRACE,TRACE -> true
| TRACE,_ -> false
;;
let display_fun level =
match level with
INFO -> print_endline
| _ -> prerr_endline
;;
let maybe_debug level msg =
if should_display level then
let print = display_fun level in
print msg
;;
let debug_if level b msg =
if b then maybe_debug level msg
;;
let debug_l level f =
if should_display level then
let print = display_fun level in
print (Lazy.force f)
;;
let debug_if_l level b f =
if b then debug_l level f
;;
let alert msg = maybe_debug QUIET msg;;
let error msg = maybe_debug QUIET ("ERROR:\n" ^ msg);;
let info msg = maybe_debug INFO msg;;
let debug msg = debug_l DEBUG msg;;
let trace msg = debug_l TRACE msg;;
| |
32a2e7d436a3e94fc0839e61fa1e10c167e9183ea82cd09f42024d549606ffb3 | herd/herdtools7 | RISCVArch_jingle.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2019 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
include Arch.MakeArch(struct
open RISCVBase
include Arch.MakeCommon(RISCVBase)
let match_const k k' subs = match k with
| MetaConst.Meta k -> add_subs [Cst (k,k')] subs
| MetaConst.Int k -> if k=k' then Some subs else None
let match_2r subs r1 r2 r1' r2' =
match_reg r1 r1' subs >>> match_reg r2 r2'
let match_const_2r subs k r1 r2 k' r1' r2' =
match_const k k' subs >>> fun subs -> match_2r subs r1 r2 r1' r2'
let match_3r subs r1 r2 r3 r1' r2' r3' =
match_2r subs r1 r2 r1' r2' >>> match_reg r3 r3'
let match_instr subs pattern instr = match pattern,instr with
| OpI (op,r1,r2,k),OpI(op',r1',r2',k') when op=op' ->
match_const_2r subs k r1 r2 k' r1' r2'
| OpIW (op,r1,r2,k),OpIW(op',r1',r2',k') when op=op' ->
match_const_2r subs k r1 r2 k' r1' r2'
| Op (op,r1,r2,r3),Op(op',r1',r2',r3') when op=op' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| OpW (op,r1,r2,r3),OpW(op',r1',r2',r3') when op=op' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| J lbl,J lbl' ->
add_subs [Lab (lbl,lbl')] subs
| Bcc (c,r1,r2,lbl),Bcc (c',r1',r2',lbl') when c=c' ->
add_subs
[Lab (lbl,lbl'); Reg (sr_name r1,r1'); Reg (sr_name r2,r2');]
subs
| Load (w,s,m,r1,i,r2),Load (w',s',m',r1',i',r2')
when w=w' && s=s' && m=m' && i=i' ->
match_2r subs r1 r2 r1' r2'
| Store (w,m,r1,i,r2),Store (w',m',r1',i',r2')
when w=w' && m=m' && i=i' ->
match_2r subs r1 r2 r1' r2'
| LoadReserve (w,m,r1,r2),LoadReserve (w',m',r1',r2')
when w=w' && m=m' ->
match_2r subs r1 r2 r1' r2'
| StoreConditional (w,m,r1,r2,r3),StoreConditional (w',m',r1',r2',r3')
when w=w' && m=m' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| Amo (op,w,m,r1,r2,r3),Amo (op',w',m',r1',r2',r3')
when op=op' && w=w' && m=m' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| FenceIns b,FenceIns b'
when b=b' -> Some subs
| _,_ -> None
let expl_instr subs =
let conv_reg = conv_reg subs
and find_lab = find_lab subs
and find_cst = find_cst subs in
function
| OpI (op,r1,r2,k) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
find_cst k >! fun k ->
OpI (op,r1,r2,k)
| OpIW (op,r1,r2,k) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
find_cst k >! fun k ->
OpIW (op,r1,r2,k)
| Op (op,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
Op (op,r1,r2,r3)
| OpW (op,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
OpW (op,r1,r2,r3)
| J lbl->
find_lab lbl >! fun lbl -> J lbl
| Bcc (c,r1,r2,lbl) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
find_lab lbl >! fun lbl ->
Bcc (c,r1,r2,lbl)
| Load (w,s,m,r1,i,r2) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >! fun r2 ->
Load (w,s,m,r1,i,r2)
| Store (w,m,r1,i,r2) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >! fun r2 ->
Store (w,m,r1,i,r2)
| LoadReserve (w,m,r1,r2) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >! fun r2 ->
LoadReserve (w,m,r1,r2)
| StoreConditional (w,m,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
StoreConditional (w,m,r1,r2,r3)
| Amo (op,w,m,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
Amo (op,w,m,r1,r2,r3)
| INop|FenceIns _ as i -> unitT i
end)
| null | https://raw.githubusercontent.com/herd/herdtools7/b86aec8db64f8812e19468893deb1cdf5bbcfb83/jingle/RISCVArch_jingle.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
************************************************************************** | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2019 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
include Arch.MakeArch(struct
open RISCVBase
include Arch.MakeCommon(RISCVBase)
let match_const k k' subs = match k with
| MetaConst.Meta k -> add_subs [Cst (k,k')] subs
| MetaConst.Int k -> if k=k' then Some subs else None
let match_2r subs r1 r2 r1' r2' =
match_reg r1 r1' subs >>> match_reg r2 r2'
let match_const_2r subs k r1 r2 k' r1' r2' =
match_const k k' subs >>> fun subs -> match_2r subs r1 r2 r1' r2'
let match_3r subs r1 r2 r3 r1' r2' r3' =
match_2r subs r1 r2 r1' r2' >>> match_reg r3 r3'
let match_instr subs pattern instr = match pattern,instr with
| OpI (op,r1,r2,k),OpI(op',r1',r2',k') when op=op' ->
match_const_2r subs k r1 r2 k' r1' r2'
| OpIW (op,r1,r2,k),OpIW(op',r1',r2',k') when op=op' ->
match_const_2r subs k r1 r2 k' r1' r2'
| Op (op,r1,r2,r3),Op(op',r1',r2',r3') when op=op' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| OpW (op,r1,r2,r3),OpW(op',r1',r2',r3') when op=op' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| J lbl,J lbl' ->
add_subs [Lab (lbl,lbl')] subs
| Bcc (c,r1,r2,lbl),Bcc (c',r1',r2',lbl') when c=c' ->
add_subs
[Lab (lbl,lbl'); Reg (sr_name r1,r1'); Reg (sr_name r2,r2');]
subs
| Load (w,s,m,r1,i,r2),Load (w',s',m',r1',i',r2')
when w=w' && s=s' && m=m' && i=i' ->
match_2r subs r1 r2 r1' r2'
| Store (w,m,r1,i,r2),Store (w',m',r1',i',r2')
when w=w' && m=m' && i=i' ->
match_2r subs r1 r2 r1' r2'
| LoadReserve (w,m,r1,r2),LoadReserve (w',m',r1',r2')
when w=w' && m=m' ->
match_2r subs r1 r2 r1' r2'
| StoreConditional (w,m,r1,r2,r3),StoreConditional (w',m',r1',r2',r3')
when w=w' && m=m' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| Amo (op,w,m,r1,r2,r3),Amo (op',w',m',r1',r2',r3')
when op=op' && w=w' && m=m' ->
match_3r subs r1 r2 r3 r1' r2' r3'
| FenceIns b,FenceIns b'
when b=b' -> Some subs
| _,_ -> None
let expl_instr subs =
let conv_reg = conv_reg subs
and find_lab = find_lab subs
and find_cst = find_cst subs in
function
| OpI (op,r1,r2,k) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
find_cst k >! fun k ->
OpI (op,r1,r2,k)
| OpIW (op,r1,r2,k) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
find_cst k >! fun k ->
OpIW (op,r1,r2,k)
| Op (op,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
Op (op,r1,r2,r3)
| OpW (op,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
OpW (op,r1,r2,r3)
| J lbl->
find_lab lbl >! fun lbl -> J lbl
| Bcc (c,r1,r2,lbl) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
find_lab lbl >! fun lbl ->
Bcc (c,r1,r2,lbl)
| Load (w,s,m,r1,i,r2) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >! fun r2 ->
Load (w,s,m,r1,i,r2)
| Store (w,m,r1,i,r2) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >! fun r2 ->
Store (w,m,r1,i,r2)
| LoadReserve (w,m,r1,r2) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >! fun r2 ->
LoadReserve (w,m,r1,r2)
| StoreConditional (w,m,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
StoreConditional (w,m,r1,r2,r3)
| Amo (op,w,m,r1,r2,r3) ->
conv_reg r1 >> fun r1 ->
conv_reg r2 >> fun r2 ->
conv_reg r3 >! fun r3 ->
Amo (op,w,m,r1,r2,r3)
| INop|FenceIns _ as i -> unitT i
end)
|
4045f399ed83628f9a12c150e8ab44a56be160f544305682f47465ea46c0c835 | babashka/nbb | example.cljs | (ns script
(:require ["chalk$default" :as chalk]
["console$log" :as log]))
Combine styled and normal strings
(log (chalk/blue "hello") (str " world" (chalk/red "!")))
;; Compose multiple styles using the chainable API
(log (chalk/blue.bgRed.bold "Hello world!"))
;; Pass in multiple arguments
(log (chalk/blue "Hello" "World!" "Foo" "bar" "biz" "baz"))
Nest styles
(log (chalk/red "Hello" (str (chalk/underline.bgBlue "world") "!")))
| null | https://raw.githubusercontent.com/babashka/nbb/4d06aa142a5fb5baac48a8ad8e611d672f779b5f/examples/chalk/example.cljs | clojure | Compose multiple styles using the chainable API
Pass in multiple arguments | (ns script
(:require ["chalk$default" :as chalk]
["console$log" :as log]))
Combine styled and normal strings
(log (chalk/blue "hello") (str " world" (chalk/red "!")))
(log (chalk/blue.bgRed.bold "Hello world!"))
(log (chalk/blue "Hello" "World!" "Foo" "bar" "biz" "baz"))
Nest styles
(log (chalk/red "Hello" (str (chalk/underline.bgBlue "world") "!")))
|
0106e8a664718161f9f9a4f76c82c789e3a3fa1a54fe5a1ab05784e89a01f4ea | johnwhitington/ocamli | exercise07.ml | let rec for_all f l =
match l with
[] -> true
| h::t -> f h && for_all f t
| null | https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/OCaml%20from%20the%20Very%20Beginning/Chapter%206/exercise07.ml | ocaml | let rec for_all f l =
match l with
[] -> true
| h::t -> f h && for_all f t
| |
4a8ecfee5ad63479a546ca711b9056608936614c3b341ea3f3e70a4463d3db7e | cofree-coffee/cofree-bot | Env.hs | | Subroutine for fetching Client Session data from the Environment .
module Options.Env
( fromEnv,
readEnv,
)
where
--------------------------------------------------------------------------------
import Data.Functor.Barbie
import Data.Functor.Compose
import Data.Text (Text)
import Data.Text qualified as Text
import Options.Types
import System.Environment (lookupEnv)
--------------------------------------------------------------------------------
readEnv :: (Text -> a) -> String -> (IO `Compose` Maybe) a
readEnv cstr envKey = Compose $ fmap (cstr . Text.pack) <$> lookupEnv envKey
fromEnv :: IO (ClientSessionF Maybe)
fromEnv =
bsequence $
ClientSessionF
{ matrixServer = readEnv MatrixServer "COFREE_BOT_MATRIX_SERVER",
matrixToken = readEnv MatrixToken "COFREE_BOT_MATRIX_TOKEN"
}
| null | https://raw.githubusercontent.com/cofree-coffee/cofree-bot/2466a444f17c560bfbadcad328f8a8c08d8da896/cofree-bot/src/Options/Env.hs | haskell | ------------------------------------------------------------------------------
------------------------------------------------------------------------------ | | Subroutine for fetching Client Session data from the Environment .
module Options.Env
( fromEnv,
readEnv,
)
where
import Data.Functor.Barbie
import Data.Functor.Compose
import Data.Text (Text)
import Data.Text qualified as Text
import Options.Types
import System.Environment (lookupEnv)
readEnv :: (Text -> a) -> String -> (IO `Compose` Maybe) a
readEnv cstr envKey = Compose $ fmap (cstr . Text.pack) <$> lookupEnv envKey
fromEnv :: IO (ClientSessionF Maybe)
fromEnv =
bsequence $
ClientSessionF
{ matrixServer = readEnv MatrixServer "COFREE_BOT_MATRIX_SERVER",
matrixToken = readEnv MatrixToken "COFREE_BOT_MATRIX_TOKEN"
}
|
5337dfd4568702a9841bfc19e1976273dc648e821ec0d85a8c6b079de6b64e33 | W-Net-AI/LISP-CV | package.lisp | ;;; -*- mode: lisp; indent-tabs: nil -*-
(defpackage :gc
(:nicknames #:gc #:t)
(:use #:cffi #:common-lisp #:swank #:trivial-garbage #:lisp-executable)
(:shadow #:abs)
(:export
Macros
#:alloc
Interop
#:c-string-to-string
#:c-string
CFFI
#:alloc
;; Vectors
#:vector-char
#:make-vector-char
#:c-arr-to-vec-char
#:seq-to-vec-char
#:vec-char-to-c-arr
#:vec-char-length
#:vec-char-to-lisp-list
#:vec-char-to-lisp-vec
#:make-vector-dmatch
#:vector-dmatch
#:c-arr-to-vec-dmatch
#:seq-to-vec-dmatch
#:vec-dmatch-to-c-arr
#:vec-dmatch-length
#:vec-dmatch-to-lisp-list
#:vec-dmatch-to-lisp-vec
#:make-vector-double
#:vector-double
#:c-arr-to-vec-double
#:seq-to-vec-double
#:vec-double-to-c-arr
#:vec-double-length
#:vec-double-to-lisp-list
#:vec-double-to-lisp-vec
#:make-vector-float
#:vector-float
#:c-arr-to-vec-float
#:seq-to-vec-float
#:vec-float-to-c-arr
#:vec-float-length
#:vec-float-to-lisp-list
#:vec-float-to-lisp-vec
#:make-vector-int
#:vector-int
#:c-arr-to-vec-int
#:seq-to-vec-int
#:vec-int-to-c-arr
#:vec-int-length
#:vec-int-to-lisp-list
#:vec-int-to-lisp-vec
#:make-vector-key-point
#:vector-key-point
#:c-arr-to-vec-key-point
#:seq-to-vec-key-point
#:vec-key-point-to-c-arr
#:vec-key-point-length
#:vec-key-point-to-lisp-list
#:vec-key-point-to-lisp-vec
#:make-vector-mat
#:vector-mat
#:c-arr-to-vec-mat
#:seq-to-vec-mat
#:vec-mat-to-c-arr
#:vec-mat-length
#:vec-mat-to-lisp-list
#:vec-mat-to-lisp-vec
#:make-vector-point
#:vector-point
#:c-arr-to-vec-point
#:seq-to-vec-point
#:vec-point-to-c-arr
#:vec-point-length
#:vec-point-to-lisp-list
#:vec-point-to-lisp-vec
#:make-vector-point-2f
#:vector-point-2f
#:c-arr-to-vec-point-2f
#:seq-to-vec-point-2f
#:vec-point-2f-to-c-arr
#:vec-point-2f-length
#:vec-point-2f-to-lisp-list
#:vec-point-2f-to-lisp-vec
#:make-vector-rect
#:vector-rect
#:c-arr-to-vec-rect
#:seq-to-vec-rect
#:vec-rect-to-c-arr
#:vec-rect-length
#:vec-rect-to-lisp-list
#:vec-rect-to-lisp-vec
#:make-vector-uchar
#:vector-uchar
#:c-arr-to-vec-uchar
#:seq-to-vec-uchar
#:vec-uchar-to-c-arr
#:vec-uchar-length
#:vec-uchar-to-lisp-list
#:vec-uchar-to-lisp-vec
#:make-vector-vec-2b
#:vector-vec-2b
#:c-arr-to-vec-vec-2b
#:seq-to-vec-vec-2b
#:vec-vec-2b-to-c-arr
#:vec-vec-2b-length
#:vec-vec-2b-to-lisp-list
#:vec-vec-2b-to-lisp-vec
#:make-vector-vec-3b
#:vector-vec-3b
#:c-arr-to-vec-vec-3b
#:seq-to-vec-vec-3b
#:vec-vec-3b-to-c-arr
#:vec-vec-3b-length
#:vec-vec-3b-to-lisp-list
#:vec-vec-3b-to-lisp-vec
#:make-vector-vec-4b
#:vector-vec-4b
#:c-arr-to-vec-vec-4b
#:seq-to-vec-vec-4b
#:vec-vec-4b-to-c-arr
#:vec-vec-4b-length
#:vec-vec-4b-to-lisp-list
#:vec-vec-4b-to-lisp-vec
#:make-vector-vec-2d
#:vector-vec-2d
#:c-arr-to-vec-vec-2d
#:seq-to-vec-vec-2d
#:vec-vec-2d-to-c-arr
#:vec-vec-2d-length
#:vec-vec-2d-to-lisp-list
#:vec-vec-2d-to-lisp-vec
#:make-vector-vec-3d
#:vector-vec-3d
#:c-arr-to-vec-vec-3d
#:seq-to-vec-vec-3d
#:vec-vec-3d-to-c-arr
#:vec-vec-3d-length
#:vec-vec-3d-to-lisp-list
#:vec-vec-3d-to-lisp-vec
#:make-vector-vec-4d
#:vector-vec-4d
#:c-arr-to-vec-vec-4d
#:seq-to-vec-vec-4d
#:vec-vec-4d-to-c-arr
#:vec-vec-4d-length
#:vec-vec-4d-to-lisp-list
#:vec-vec-4d-to-lisp-vec
#:make-vector-vec-6d
#:vector-vec-6d
#:c-arr-to-vec-vec-6d
#:seq-to-vec-vec-6d
#:vec-vec-6d-to-c-arr
#:vec-vec-6d-length
#:vec-vec-6d-to-lisp-list
#:vec-vec-6d-to-lisp-vec
#:make-vector-vec-2f
#:vector-vec-2f
#:c-arr-to-vec-vec-2f
#:seq-to-vec-vec-2f
#:vec-vec-2f-to-c-arr
#:vec-vec-2f-length
#:vec-vec-2f-to-lisp-list
#:vec-vec-2f-to-lisp-vec
#:make-vector-vec-3f
#:vector-vec-3f
#:c-arr-to-vec-vec-3f
#:seq-to-vec-vec-3f
#:vec-vec-3f-to-c-arr
#:vec-vec-3f-length
#:vec-vec-3f-to-lisp-list
#:vec-vec-3f-to-lisp-vec
#:make-vector-vec-4f
#:vector-vec-4f
#:c-arr-to-vec-vec-4f
#:seq-to-vec-vec-4f
#:vec-vec-4f-to-c-arr
#:vec-vec-4f-length
#:vec-vec-4f-to-lisp-list
#:vec-vec-4f-to-lisp-vec
#:make-vector-vec-6f
#:vector-vec-6f
#:c-arr-to-vec-vec-6f
#:seq-to-vec-vec-6f
#:vec-vec-6f-to-c-arr
#:vec-vec-6f-length
#:vec-vec-6f-to-lisp-list
#:vec-vec-6f-to-lisp-vec
#:make-vector-vec-2i
#:vector-vec-2i
#:c-arr-to-vec-vec-2i
#:seq-to-vec-vec-2i
#:vec-vec-2i-to-c-arr
#:vec-vec-2i-length
#:vec-vec-2i-to-lisp-list
#:vec-vec-2i-to-lisp-vec
#:make-vector-vec-3i
#:vector-vec-3i
#:c-arr-to-vec-vec-3i
#:seq-to-vec-vec-3i
#:vec-vec-3i-to-c-arr
#:vec-vec-3i-length
#:vec-vec-3i-to-lisp-list
#:vec-vec-3i-to-lisp-vec
#:make-vector-vec-4i
#:vector-vec-4i
#:c-arr-to-vec-vec-4i
#:seq-to-vec-vec-4i
#:vec-vec-4i-to-c-arr
#:vec-vec-4i-length
#:vec-vec-4i-to-lisp-list
#:vec-vec-4i-to-lisp-vec
#:make-vector-vec-6i
#:vector-vec-6i
#:c-arr-to-vec-vec-6i
#:seq-to-vec-vec-6i
#:vec-vec-6i-to-c-arr
#:vec-vec-6i-length
#:vec-vec-6i-to-lisp-list
#:vec-vec-6i-to-lisp-vec
#:make-vector-vec-8i
#:vector-vec-8i
#:c-arr-to-vec-vec-8i
#:seq-to-vec-vec-8i
#:vec-vec-8i-to-c-arr
#:vec-vec-8i-length
#:vec-vec-8i-to-lisp-list
#:vec-vec-8i-to-lisp-vec
#:make-vector-vec-2s
#:vector-vec-2s
#:c-arr-to-vec-vec-2s
#:seq-to-vec-vec-2s
#:vec-vec-2s-to-c-arr
#:vec-vec-2s-length
#:vec-vec-2s-to-lisp-list
#:vec-vec-2s-to-lisp-vec
#:make-vector-vec-3s
#:vector-vec-3s
#:c-arr-to-vec-vec-3s
#:seq-to-vec-vec-3s
#:vec-vec-3s-to-c-arr
#:vec-vec-3s-length
#:vec-vec-3s-to-lisp-list
#:vec-vec-3s-to-lisp-vec
#:make-vector-vec-4s
#:vector-vec-4s
#:c-arr-to-vec-vec-4s
#:seq-to-vec-vec-4s
#:vec-vec-4s-to-c-arr
#:vec-vec-4s-length
#:vec-vec-4s-to-lisp-list
#:vec-vec-4s-to-lisp-vec
#:make-vector-vec-2w
#:vector-vec-2w
#:c-arr-to-vec-vec-2w
#:seq-to-vec-vec-2w
#:vec-vec-2w-to-c-arr
#:vec-vec-2w-length
#:vec-vec-2w-to-lisp-list
#:vec-vec-2w-to-lisp-vec
#:make-vector-vec-3w
#:vector-vec-3w
#:c-arr-to-vec-vec-3w
#:seq-to-vec-vec-3w
#:vec-vec-3w-to-c-arr
#:vec-vec-3w-length
#:vec-vec-3w-to-lisp-list
#:vec-vec-3w-to-lisp-vec
#:make-vector-vec-4w
#:vector-vec-4w
#:c-arr-to-vec-vec-4w
#:seq-to-vec-vec-4w
#:vec-vec-4w-to-c-arr
#:vec-vec-4w-length
#:vec-vec-4w-to-lisp-list
#:vec-vec-4w-to-lisp-vec
;; DEFGENERIC
#:clone
#:mean
#:size
;;; Functions and methods used to
;;; re-import shadowed symbols.
#:abs
;; core - Basic Structures
#:<<
#:>>
#:add
#:adjust-roi
#:br
#:clone
#:col-range
#:create-mat-typed
#:create-mat-with-data
#:create-mat-with-element
#:create-mat-with-range
#:create-mat-with-value
#:diag
#:div
#:dmatch
#:force
#:inv
#:key-point
#:make-dmatch
#:make-key-point
#:make-mat
#:make-point
#:make-point-2d
#:make-point-2f
#:make-point-3d
#:make-point-3f
#:make-point-3i
#:make-range
#:make-range-all
#:make-rect
#:make-rotated-rect
#:make-scalar
#:make-scalar-all
#:make-size
#:make-term-criteria
#:make-vec-2b
#:make-vec-3b
#:make-vec-4b
#:make-vec-2d
#:make-vec-3d
#:make-vec-4d
#:make-vec-6d
#:make-vec-2f
#:make-vec-3f
#:make-vec-4f
#:make-vec-6f
#:make-vec-2i
#:make-vec-3i
#:make-vec-4i
#:make-vec-6i
#:make-vec-8i
#:make-vec-2s
#:make-vec-3s
#:make-vec-4s
#:make-vec-2w
#:make-vec-3w
#:make-vec-4w
#:mat
#:mat-dot
#:mat-expr-t
#:mat-eye
#:mat-ones
#:mat-size
#:mat-type
#:mat-zeros
#:mul
#:point
#:point-2d
#:point-2f
#:point-3d
#:point-3f
#:point-3i
#:promote
#:range
#:range-all
#:rect
#:rect-br
#:rect-tl
#:rect-size
#:reshape
#:reshape-rows
#:roi
#:rotated-rect
#:row
#:row-range
#:scale
#:scalar
#:scalar-all
#:size
#:size-from-point
#:sub
#:term-criteria
#:tl
#:trace*
#:vec-2b
#:vec-3b
#:vec-4b
#:vec-2d
#:vec-3d
#:vec-4d
#:vec-6d
#:vec-2f
#:vec-3f
#:vec-4f
#:vec-6f
#:vec-2i
#:vec-3i
#:vec-4i
#:vec-6i
#:vec-8i
#:vec-2s
#:vec-3s
#:vec-4s
#:vec-2w
#:vec-3w
#:vec-4w
;; core - Dynamic Structures
;; core - Operations on Arrays
#:back-project
#:eigenvalues
#:eigenvectors
#:inv
#:make-pca
#:make-rng
#:pca
#:pca-back-project
#:pca-eigenvalues
#:pca-eigenvectors
#:pca-mean
#:pca-project
#:project
#:rng
#:sum
;; core - Drawing Functions
#:bgr
#:make-bgr
#:make-rgb
#:rgb
;; core - XML/YAML Persistence
#:file-storage
#:make-file-storage
core - Utility and System Functions and Macros
;; imgproc - Image Filtering
#:make-morphology-default-border-value
#:morphology-default-border-value
#:get-structuring-element
;; imgproc - Geometric Image Transformations
#:get-affine-transform
#:get-perspective-transform
#:get-rotation-matrix-2d
;; imgproc - Miscellaneous Image Transformations
imgproc - Histograms
;; imgproc - Structural Analysis and Shape Descriptors
imgproc - Motion Analysis and Object Tracking
#:phase-correlate
imgproc - Feature Detection
;; imgproc - Object Detection
;; highgui - User Interface
;; highgui - Reading and Writing Images and Video
#:imdecode
#:imread
#:make-video-capture
#:make-video-writer
#:video-capture
#:video-writer
highgui - Qt New Functions
;; calib3d - Camera Calibration and 3D Reconstruction
#:find-homography
;; features2d - Feature Detection and Description
#:brisk
#:make-brisk
;; features2d - Common Interfaces of Feature Detectors
;; features2d - Common Interfaces of Descriptor Extractors
;; features2d - Common Interfaces of Descriptor Matchers
#:bf-matcher
#:flann-based-matcher
#:make-bf-matcher
#:make-flann-based-matcher
;;; features2d - Drawing Function of Keypoints and Matches
#:draw-matches
;;; objdetect - Cascade Classification
#:cascade-classifier
#:cascade-classifier-load
#:make-cascade-classifier
;;; ml - LISP-CV specific
#:make-training-matrix
;;; ml - Normal Bayes Classifier
#:make-normal-bayes-classifier
#:normal-bayes-classifier
#:normal-bayes-classifier-predict
;;; ml - K-Nearest Neighbors
#:k-nearest
#:k-nearest-find-nearest
#:make-k-nearest
ml - Support Vector Machines
#:make-svm
#:make-svm-params
#:svm
#:svm-params
;;; ml - Decision Trees
#:d-tree
#:d-tree-params
#:make-d-tree
#:make-d-tree-params
ml - Neural Networks
#:ann-mlp
#:ann-mlp-train-params
#:make-ann-mlp
#:make-ann-mlp-train-params
;;; nonfree - Feature Detection and Description
#:make-surf
#:surf
;;; contrib - ColorMaps in OpenCV
#:apply-color-map
))
| null | https://raw.githubusercontent.com/W-Net-AI/LISP-CV/10d5c7c1a6fa026de488ca89a28e8a5c519ff8f2/gc/package.lisp | lisp | -*- mode: lisp; indent-tabs: nil -*-
Vectors
DEFGENERIC
Functions and methods used to
re-import shadowed symbols.
core - Basic Structures
core - Dynamic Structures
core - Operations on Arrays
core - Drawing Functions
core - XML/YAML Persistence
imgproc - Image Filtering
imgproc - Geometric Image Transformations
imgproc - Miscellaneous Image Transformations
imgproc - Structural Analysis and Shape Descriptors
imgproc - Object Detection
highgui - User Interface
highgui - Reading and Writing Images and Video
calib3d - Camera Calibration and 3D Reconstruction
features2d - Feature Detection and Description
features2d - Common Interfaces of Feature Detectors
features2d - Common Interfaces of Descriptor Extractors
features2d - Common Interfaces of Descriptor Matchers
features2d - Drawing Function of Keypoints and Matches
objdetect - Cascade Classification
ml - LISP-CV specific
ml - Normal Bayes Classifier
ml - K-Nearest Neighbors
ml - Decision Trees
nonfree - Feature Detection and Description
contrib - ColorMaps in OpenCV |
(defpackage :gc
(:nicknames #:gc #:t)
(:use #:cffi #:common-lisp #:swank #:trivial-garbage #:lisp-executable)
(:shadow #:abs)
(:export
Macros
#:alloc
Interop
#:c-string-to-string
#:c-string
CFFI
#:alloc
#:vector-char
#:make-vector-char
#:c-arr-to-vec-char
#:seq-to-vec-char
#:vec-char-to-c-arr
#:vec-char-length
#:vec-char-to-lisp-list
#:vec-char-to-lisp-vec
#:make-vector-dmatch
#:vector-dmatch
#:c-arr-to-vec-dmatch
#:seq-to-vec-dmatch
#:vec-dmatch-to-c-arr
#:vec-dmatch-length
#:vec-dmatch-to-lisp-list
#:vec-dmatch-to-lisp-vec
#:make-vector-double
#:vector-double
#:c-arr-to-vec-double
#:seq-to-vec-double
#:vec-double-to-c-arr
#:vec-double-length
#:vec-double-to-lisp-list
#:vec-double-to-lisp-vec
#:make-vector-float
#:vector-float
#:c-arr-to-vec-float
#:seq-to-vec-float
#:vec-float-to-c-arr
#:vec-float-length
#:vec-float-to-lisp-list
#:vec-float-to-lisp-vec
#:make-vector-int
#:vector-int
#:c-arr-to-vec-int
#:seq-to-vec-int
#:vec-int-to-c-arr
#:vec-int-length
#:vec-int-to-lisp-list
#:vec-int-to-lisp-vec
#:make-vector-key-point
#:vector-key-point
#:c-arr-to-vec-key-point
#:seq-to-vec-key-point
#:vec-key-point-to-c-arr
#:vec-key-point-length
#:vec-key-point-to-lisp-list
#:vec-key-point-to-lisp-vec
#:make-vector-mat
#:vector-mat
#:c-arr-to-vec-mat
#:seq-to-vec-mat
#:vec-mat-to-c-arr
#:vec-mat-length
#:vec-mat-to-lisp-list
#:vec-mat-to-lisp-vec
#:make-vector-point
#:vector-point
#:c-arr-to-vec-point
#:seq-to-vec-point
#:vec-point-to-c-arr
#:vec-point-length
#:vec-point-to-lisp-list
#:vec-point-to-lisp-vec
#:make-vector-point-2f
#:vector-point-2f
#:c-arr-to-vec-point-2f
#:seq-to-vec-point-2f
#:vec-point-2f-to-c-arr
#:vec-point-2f-length
#:vec-point-2f-to-lisp-list
#:vec-point-2f-to-lisp-vec
#:make-vector-rect
#:vector-rect
#:c-arr-to-vec-rect
#:seq-to-vec-rect
#:vec-rect-to-c-arr
#:vec-rect-length
#:vec-rect-to-lisp-list
#:vec-rect-to-lisp-vec
#:make-vector-uchar
#:vector-uchar
#:c-arr-to-vec-uchar
#:seq-to-vec-uchar
#:vec-uchar-to-c-arr
#:vec-uchar-length
#:vec-uchar-to-lisp-list
#:vec-uchar-to-lisp-vec
#:make-vector-vec-2b
#:vector-vec-2b
#:c-arr-to-vec-vec-2b
#:seq-to-vec-vec-2b
#:vec-vec-2b-to-c-arr
#:vec-vec-2b-length
#:vec-vec-2b-to-lisp-list
#:vec-vec-2b-to-lisp-vec
#:make-vector-vec-3b
#:vector-vec-3b
#:c-arr-to-vec-vec-3b
#:seq-to-vec-vec-3b
#:vec-vec-3b-to-c-arr
#:vec-vec-3b-length
#:vec-vec-3b-to-lisp-list
#:vec-vec-3b-to-lisp-vec
#:make-vector-vec-4b
#:vector-vec-4b
#:c-arr-to-vec-vec-4b
#:seq-to-vec-vec-4b
#:vec-vec-4b-to-c-arr
#:vec-vec-4b-length
#:vec-vec-4b-to-lisp-list
#:vec-vec-4b-to-lisp-vec
#:make-vector-vec-2d
#:vector-vec-2d
#:c-arr-to-vec-vec-2d
#:seq-to-vec-vec-2d
#:vec-vec-2d-to-c-arr
#:vec-vec-2d-length
#:vec-vec-2d-to-lisp-list
#:vec-vec-2d-to-lisp-vec
#:make-vector-vec-3d
#:vector-vec-3d
#:c-arr-to-vec-vec-3d
#:seq-to-vec-vec-3d
#:vec-vec-3d-to-c-arr
#:vec-vec-3d-length
#:vec-vec-3d-to-lisp-list
#:vec-vec-3d-to-lisp-vec
#:make-vector-vec-4d
#:vector-vec-4d
#:c-arr-to-vec-vec-4d
#:seq-to-vec-vec-4d
#:vec-vec-4d-to-c-arr
#:vec-vec-4d-length
#:vec-vec-4d-to-lisp-list
#:vec-vec-4d-to-lisp-vec
#:make-vector-vec-6d
#:vector-vec-6d
#:c-arr-to-vec-vec-6d
#:seq-to-vec-vec-6d
#:vec-vec-6d-to-c-arr
#:vec-vec-6d-length
#:vec-vec-6d-to-lisp-list
#:vec-vec-6d-to-lisp-vec
#:make-vector-vec-2f
#:vector-vec-2f
#:c-arr-to-vec-vec-2f
#:seq-to-vec-vec-2f
#:vec-vec-2f-to-c-arr
#:vec-vec-2f-length
#:vec-vec-2f-to-lisp-list
#:vec-vec-2f-to-lisp-vec
#:make-vector-vec-3f
#:vector-vec-3f
#:c-arr-to-vec-vec-3f
#:seq-to-vec-vec-3f
#:vec-vec-3f-to-c-arr
#:vec-vec-3f-length
#:vec-vec-3f-to-lisp-list
#:vec-vec-3f-to-lisp-vec
#:make-vector-vec-4f
#:vector-vec-4f
#:c-arr-to-vec-vec-4f
#:seq-to-vec-vec-4f
#:vec-vec-4f-to-c-arr
#:vec-vec-4f-length
#:vec-vec-4f-to-lisp-list
#:vec-vec-4f-to-lisp-vec
#:make-vector-vec-6f
#:vector-vec-6f
#:c-arr-to-vec-vec-6f
#:seq-to-vec-vec-6f
#:vec-vec-6f-to-c-arr
#:vec-vec-6f-length
#:vec-vec-6f-to-lisp-list
#:vec-vec-6f-to-lisp-vec
#:make-vector-vec-2i
#:vector-vec-2i
#:c-arr-to-vec-vec-2i
#:seq-to-vec-vec-2i
#:vec-vec-2i-to-c-arr
#:vec-vec-2i-length
#:vec-vec-2i-to-lisp-list
#:vec-vec-2i-to-lisp-vec
#:make-vector-vec-3i
#:vector-vec-3i
#:c-arr-to-vec-vec-3i
#:seq-to-vec-vec-3i
#:vec-vec-3i-to-c-arr
#:vec-vec-3i-length
#:vec-vec-3i-to-lisp-list
#:vec-vec-3i-to-lisp-vec
#:make-vector-vec-4i
#:vector-vec-4i
#:c-arr-to-vec-vec-4i
#:seq-to-vec-vec-4i
#:vec-vec-4i-to-c-arr
#:vec-vec-4i-length
#:vec-vec-4i-to-lisp-list
#:vec-vec-4i-to-lisp-vec
#:make-vector-vec-6i
#:vector-vec-6i
#:c-arr-to-vec-vec-6i
#:seq-to-vec-vec-6i
#:vec-vec-6i-to-c-arr
#:vec-vec-6i-length
#:vec-vec-6i-to-lisp-list
#:vec-vec-6i-to-lisp-vec
#:make-vector-vec-8i
#:vector-vec-8i
#:c-arr-to-vec-vec-8i
#:seq-to-vec-vec-8i
#:vec-vec-8i-to-c-arr
#:vec-vec-8i-length
#:vec-vec-8i-to-lisp-list
#:vec-vec-8i-to-lisp-vec
#:make-vector-vec-2s
#:vector-vec-2s
#:c-arr-to-vec-vec-2s
#:seq-to-vec-vec-2s
#:vec-vec-2s-to-c-arr
#:vec-vec-2s-length
#:vec-vec-2s-to-lisp-list
#:vec-vec-2s-to-lisp-vec
#:make-vector-vec-3s
#:vector-vec-3s
#:c-arr-to-vec-vec-3s
#:seq-to-vec-vec-3s
#:vec-vec-3s-to-c-arr
#:vec-vec-3s-length
#:vec-vec-3s-to-lisp-list
#:vec-vec-3s-to-lisp-vec
#:make-vector-vec-4s
#:vector-vec-4s
#:c-arr-to-vec-vec-4s
#:seq-to-vec-vec-4s
#:vec-vec-4s-to-c-arr
#:vec-vec-4s-length
#:vec-vec-4s-to-lisp-list
#:vec-vec-4s-to-lisp-vec
#:make-vector-vec-2w
#:vector-vec-2w
#:c-arr-to-vec-vec-2w
#:seq-to-vec-vec-2w
#:vec-vec-2w-to-c-arr
#:vec-vec-2w-length
#:vec-vec-2w-to-lisp-list
#:vec-vec-2w-to-lisp-vec
#:make-vector-vec-3w
#:vector-vec-3w
#:c-arr-to-vec-vec-3w
#:seq-to-vec-vec-3w
#:vec-vec-3w-to-c-arr
#:vec-vec-3w-length
#:vec-vec-3w-to-lisp-list
#:vec-vec-3w-to-lisp-vec
#:make-vector-vec-4w
#:vector-vec-4w
#:c-arr-to-vec-vec-4w
#:seq-to-vec-vec-4w
#:vec-vec-4w-to-c-arr
#:vec-vec-4w-length
#:vec-vec-4w-to-lisp-list
#:vec-vec-4w-to-lisp-vec
#:clone
#:mean
#:size
#:abs
#:<<
#:>>
#:add
#:adjust-roi
#:br
#:clone
#:col-range
#:create-mat-typed
#:create-mat-with-data
#:create-mat-with-element
#:create-mat-with-range
#:create-mat-with-value
#:diag
#:div
#:dmatch
#:force
#:inv
#:key-point
#:make-dmatch
#:make-key-point
#:make-mat
#:make-point
#:make-point-2d
#:make-point-2f
#:make-point-3d
#:make-point-3f
#:make-point-3i
#:make-range
#:make-range-all
#:make-rect
#:make-rotated-rect
#:make-scalar
#:make-scalar-all
#:make-size
#:make-term-criteria
#:make-vec-2b
#:make-vec-3b
#:make-vec-4b
#:make-vec-2d
#:make-vec-3d
#:make-vec-4d
#:make-vec-6d
#:make-vec-2f
#:make-vec-3f
#:make-vec-4f
#:make-vec-6f
#:make-vec-2i
#:make-vec-3i
#:make-vec-4i
#:make-vec-6i
#:make-vec-8i
#:make-vec-2s
#:make-vec-3s
#:make-vec-4s
#:make-vec-2w
#:make-vec-3w
#:make-vec-4w
#:mat
#:mat-dot
#:mat-expr-t
#:mat-eye
#:mat-ones
#:mat-size
#:mat-type
#:mat-zeros
#:mul
#:point
#:point-2d
#:point-2f
#:point-3d
#:point-3f
#:point-3i
#:promote
#:range
#:range-all
#:rect
#:rect-br
#:rect-tl
#:rect-size
#:reshape
#:reshape-rows
#:roi
#:rotated-rect
#:row
#:row-range
#:scale
#:scalar
#:scalar-all
#:size
#:size-from-point
#:sub
#:term-criteria
#:tl
#:trace*
#:vec-2b
#:vec-3b
#:vec-4b
#:vec-2d
#:vec-3d
#:vec-4d
#:vec-6d
#:vec-2f
#:vec-3f
#:vec-4f
#:vec-6f
#:vec-2i
#:vec-3i
#:vec-4i
#:vec-6i
#:vec-8i
#:vec-2s
#:vec-3s
#:vec-4s
#:vec-2w
#:vec-3w
#:vec-4w
#:back-project
#:eigenvalues
#:eigenvectors
#:inv
#:make-pca
#:make-rng
#:pca
#:pca-back-project
#:pca-eigenvalues
#:pca-eigenvectors
#:pca-mean
#:pca-project
#:project
#:rng
#:sum
#:bgr
#:make-bgr
#:make-rgb
#:rgb
#:file-storage
#:make-file-storage
core - Utility and System Functions and Macros
#:make-morphology-default-border-value
#:morphology-default-border-value
#:get-structuring-element
#:get-affine-transform
#:get-perspective-transform
#:get-rotation-matrix-2d
imgproc - Histograms
imgproc - Motion Analysis and Object Tracking
#:phase-correlate
imgproc - Feature Detection
#:imdecode
#:imread
#:make-video-capture
#:make-video-writer
#:video-capture
#:video-writer
highgui - Qt New Functions
#:find-homography
#:brisk
#:make-brisk
#:bf-matcher
#:flann-based-matcher
#:make-bf-matcher
#:make-flann-based-matcher
#:draw-matches
#:cascade-classifier
#:cascade-classifier-load
#:make-cascade-classifier
#:make-training-matrix
#:make-normal-bayes-classifier
#:normal-bayes-classifier
#:normal-bayes-classifier-predict
#:k-nearest
#:k-nearest-find-nearest
#:make-k-nearest
ml - Support Vector Machines
#:make-svm
#:make-svm-params
#:svm
#:svm-params
#:d-tree
#:d-tree-params
#:make-d-tree
#:make-d-tree-params
ml - Neural Networks
#:ann-mlp
#:ann-mlp-train-params
#:make-ann-mlp
#:make-ann-mlp-train-params
#:make-surf
#:surf
#:apply-color-map
))
|
23f35b13eaf38eec7f30e1865845cff3f97374101971b451c3a1cfe63a521562 | tisnik/clojure-examples | core_test.clj | (ns enlive7.core-test
(:require [clojure.test :refer :all]
[enlive7.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/enlive7/test/enlive7/core_test.clj | clojure | (ns enlive7.core-test
(:require [clojure.test :refer :all]
[enlive7.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| |
42cbce7b78c0022b200a4e15bb57e6a86934106ec464c66b6683628b64b5a12f | ahrefs/atd | json.mli | (**
Mapping from ATD to JSON
*)
type ocaml_adapter = {
normalize : string;
restore : string;
}
* Association between languages and for that language .
The specification of each json adapter is language - specific .
The specification of each json adapter is language-specific. *)
type json_adapter = {
ocaml_adapter : ocaml_adapter option;
(** A module implementing [normalize] and [restore]. *)
java_adapter : string option;
(** tbd *)
}
val no_adapter : json_adapter
type json_float =
| Float of int option (* max decimal places *)
| Int
type json_list = Array | Object
type json_variant = { json_cons : string }
type json_field = {
json_fname : string; (* <json name=...> *)
json_unwrapped : bool;
}
type json_record = {
{ ... } < >
json_record_adapter : json_adapter;
}
type json_sum = {
json_sum_adapter : json_adapter;
json_open_enum : bool;
json_lowercase_tags : bool;
}
(** The different kinds of ATD nodes with their json-specific options. *)
type json_repr =
| Abstract
| Bool
| Cell
| Def
| External
| Field of json_field
| Float of json_float
| Int
| List of json_list
| Nullable
| Option
| Record of json_record
| String
| Sum of json_sum
| Tuple
| Unit
| Variant of json_variant
| Wrap
val annot_schema_json : Annot.schema
val get_json_list : Annot.t -> json_list
val get_json_float : Annot.t -> json_float
val get_json_cons : string -> Annot.t -> string
val get_json_fname : string -> Annot.t -> string
val get_json_record : Annot.t -> json_record
val get_json_sum : Annot.t -> json_sum
| null | https://raw.githubusercontent.com/ahrefs/atd/e9cccc28aaeca9926be49682101653ae3960d8f2/atd/src/json.mli | ocaml | *
Mapping from ATD to JSON
* A module implementing [normalize] and [restore].
* tbd
max decimal places
<json name=...>
* The different kinds of ATD nodes with their json-specific options. |
type ocaml_adapter = {
normalize : string;
restore : string;
}
* Association between languages and for that language .
The specification of each json adapter is language - specific .
The specification of each json adapter is language-specific. *)
type json_adapter = {
ocaml_adapter : ocaml_adapter option;
java_adapter : string option;
}
val no_adapter : json_adapter
type json_float =
| Int
type json_list = Array | Object
type json_variant = { json_cons : string }
type json_field = {
json_unwrapped : bool;
}
type json_record = {
{ ... } < >
json_record_adapter : json_adapter;
}
type json_sum = {
json_sum_adapter : json_adapter;
json_open_enum : bool;
json_lowercase_tags : bool;
}
type json_repr =
| Abstract
| Bool
| Cell
| Def
| External
| Field of json_field
| Float of json_float
| Int
| List of json_list
| Nullable
| Option
| Record of json_record
| String
| Sum of json_sum
| Tuple
| Unit
| Variant of json_variant
| Wrap
val annot_schema_json : Annot.schema
val get_json_list : Annot.t -> json_list
val get_json_float : Annot.t -> json_float
val get_json_cons : string -> Annot.t -> string
val get_json_fname : string -> Annot.t -> string
val get_json_record : Annot.t -> json_record
val get_json_sum : Annot.t -> json_sum
|
24561eb30d395feddc4070c560e64c9e8587b916fcdecfce9db087b9ed3eee24 | ocaml/odoc | link.ml | Second round of resolution tackles references and forward paths
open Odoc_model
open Lang
module Id = Paths.Identifier
module Opt = struct
let map f = function Some x -> Some (f x) | None -> None
end
(** Equivalent to {!Comment.synopsis}. *)
let synopsis_from_comment (docs : Component.CComment.docs) =
match docs with
| ({ value = #Comment.nestable_block_element; _ } as e) :: _ ->
Only the first element is considered .
Comment.synopsis [ e ]
| _ -> None
let synopsis_of_module env (m : Component.Module.t) =
let open Utils.ResultMonad in
match synopsis_from_comment m.doc with
| Some _ as s -> s
| None -> (
let rec handle_expansion : Tools.expansion -> _ = function
| Functor (_, expr) -> (
match
Tools.expansion_of_module_type_expr ~mark_substituted:true env
expr
with
| Ok e -> handle_expansion e
| Error _ as e -> e)
| Signature sg -> Ok sg
in
(* If there is no doc, look at the expansion. *)
match Tools.expansion_of_module env m >>= handle_expansion with
| Ok sg -> synopsis_from_comment (Component.extract_signature_doc sg)
| Error _ -> None)
let ambiguous_label_warning label_name labels =
let pp_label_loc fmt (`Label (_, x)) =
Location_.pp_span_start fmt x.Component.Label.location
in
Lookup_failures.report_warning
"@[<2>Label '%s' is ambiguous. The other occurences are:@ %a@]" label_name
(Format.pp_print_list ~pp_sep:Format.pp_force_newline pp_label_loc)
labels
(** Raise a warning when a label explicitly set by the user collides. This
warning triggers even if one of the colliding labels have been automatically
generated. *)
let check_ambiguous_label ~loc env
( attrs,
({ Odoc_model.Paths.Identifier.iv = `Label (_, label_name); _ } as id),
_ ) =
if attrs.Comment.heading_label_explicit then
(* Looking for an identical identifier but a different location. *)
let conflicting (`Label (id', comp)) =
Id.equal id id'
&& not (Location_.span_equal comp.Component.Label.location loc)
in
let label_name = Names.LabelName.to_string label_name in
match Env.lookup_by_name Env.s_label label_name env with
| Ok lbl when conflicting lbl -> ambiguous_label_warning label_name [ lbl ]
| Error (`Ambiguous (hd, tl)) -> (
match List.filter conflicting (hd :: tl) with
| [] -> ()
| xs -> ambiguous_label_warning label_name xs)
| Ok _ | Error `Not_found -> ()
exception Loop
let rec is_forward : Paths.Path.Module.t -> bool = function
| `Resolved _ -> false
| `Root _ -> false
| `Forward _ -> true
| `Identifier _ -> false
| `Dot (p, _) -> is_forward p
| `Apply (p1, p2) -> is_forward p1 || is_forward p2
let rec should_reresolve : Paths.Path.Resolved.t -> bool =
fun p ->
let open Paths.Path.Resolved in
match p with
| `Identifier _ -> false
| `Subst (x, y) -> should_reresolve (x :> t) || should_reresolve (y :> t)
| `Hidden p -> should_reresolve (p :> t)
| `Canonical (x, y) ->
should_reresolve (x :> t) || should_resolve (y :> Paths.Path.t)
| `CanonicalModuleType (x, y) ->
should_reresolve (x :> t) || should_resolve (y :> Paths.Path.t)
| `CanonicalType (x, y) ->
should_reresolve (x :> t) || should_resolve (y :> Paths.Path.t)
| `Apply (x, y) ->
should_reresolve (x :> t) || should_reresolve (y :> Paths.Path.Resolved.t)
| `SubstT (x, y) -> should_reresolve (x :> t) || should_reresolve (y :> t)
| `Alias (y, x) ->
should_resolve (x :> Paths.Path.t) || should_reresolve (y :> t)
| `AliasModuleType (x, y) ->
should_reresolve (x :> t) || should_reresolve (y :> t)
| `Type (p, _)
| `Class (p, _)
| `ClassType (p, _)
| `ModuleType (p, _)
| `Module (p, _) ->
should_reresolve (p :> t)
| `OpaqueModule m -> should_reresolve (m :> t)
| `OpaqueModuleType m -> should_reresolve (m :> t)
and should_resolve : Paths.Path.t -> bool =
fun p -> match p with `Resolved p -> should_reresolve p | _ -> true
let type_path : Env.t -> Paths.Path.Type.t -> Paths.Path.Type.t =
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(type_path (empty ()) p) in
match cp with
| `Resolved p ->
let result = Tools.reresolve_type env p in
`Resolved Lang_of.(Path.resolved_type (empty ()) result)
| _ -> (
match Tools.resolve_type_path env cp with
| Ok p' ->
let result = Tools.reresolve_type env p' in
`Resolved Lang_of.(Path.resolved_type (empty ()) result)
| Error e ->
Errors.report ~what:(`Type_path cp) ~tools_error:e `Lookup;
p)
let class_type_path : Env.t -> Paths.Path.ClassType.t -> Paths.Path.ClassType.t
=
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(class_type_path (empty ()) p) in
match cp with
| `Resolved p ->
let result = Tools.reresolve_class_type env p in
`Resolved Lang_of.(Path.resolved_class_type (empty ()) result)
| _ -> (
match Tools.resolve_class_type_path env cp with
| Ok p' ->
let result = Tools.reresolve_class_type env p' in
`Resolved Lang_of.(Path.resolved_class_type (empty ()) result)
| Error e ->
Errors.report ~what:(`Class_type_path cp) ~tools_error:e `Lookup;
p)
and module_type_path :
Env.t -> Paths.Path.ModuleType.t -> Paths.Path.ModuleType.t =
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(module_type_path (empty ()) p) in
match cp with
| `Resolved p ->
let result = Tools.reresolve_module_type env p in
`Resolved Lang_of.(Path.resolved_module_type (empty ()) result)
| _ -> (
match Tools.resolve_module_type_path env cp with
| Ok p' ->
let result = Tools.reresolve_module_type env p' in
`Resolved Lang_of.(Path.resolved_module_type (empty ()) result)
| Error e ->
Errors.report ~what:(`Module_type_path cp) ~tools_error:e `Resolve;
p)
and module_path : Env.t -> Paths.Path.Module.t -> Paths.Path.Module.t =
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(module_path (empty ()) p) in
match cp with
| `Resolved p ->
let after = Tools.reresolve_module env p in
`Resolved Lang_of.(Path.resolved_module (empty ()) after)
| _ -> (
match Tools.resolve_module_path env cp with
| Ok p' ->
let result = Tools.reresolve_module env p' in
`Resolved Lang_of.(Path.resolved_module (empty ()) result)
| Error _ when is_forward p -> p
| Error e ->
Errors.report ~what:(`Module_path cp) ~tools_error:e `Resolve;
p)
let rec comment_inline_element :
loc:_ -> Env.t -> Comment.inline_element -> Comment.inline_element =
fun ~loc:_ env x ->
match x with
| `Styled (s, ls) ->
`Styled (s, List.map (with_location (comment_inline_element env)) ls)
| `Reference (r, content) as orig -> (
match Ref_tools.resolve_reference env r |> Error.raise_warnings with
| Ok x ->
let content =
(* In case of labels, use the heading text as reference text if
it's not specified. *)
match (content, x) with
| [], `Identifier ({ iv = #Id.Label.t_pv; _ } as i) -> (
match Env.lookup_by_id Env.s_label i env with
| Some (`Label (_, lbl)) -> lbl.Component.Label.text
| None -> [])
| content, _ -> content
in
`Reference (`Resolved x, content)
| Error e ->
Errors.report ~what:(`Reference r) ~tools_error:(`Reference e)
`Resolve;
orig)
| y -> y
and paragraph env elts =
List.map (with_location (comment_inline_element env)) elts
and resolve_external_synopsis env synopsis =
let env = Env.inherit_resolver env in
paragraph env synopsis
and comment_nestable_block_element env parent ~loc:_
(x : Comment.nestable_block_element) =
match x with
| `Paragraph elts -> `Paragraph (paragraph env elts)
| (`Code_block _ | `Math_block _ | `Verbatim _) as x -> x
| `List (x, ys) ->
`List
( x,
List.rev_map (comment_nestable_block_element_list env parent) ys
|> List.rev )
| `Modules refs ->
let refs =
List.rev_map
(fun (r : Comment.module_reference) ->
match
Ref_tools.resolve_module_reference env r.module_reference
|> Error.raise_warnings
with
| Ok (r, _, m) ->
let module_synopsis =
Opt.map
(resolve_external_synopsis env)
(synopsis_of_module env m)
in
{ Comment.module_reference = `Resolved r; module_synopsis }
| Error e ->
Errors.report
~what:(`Reference (r.module_reference :> Paths.Reference.t))
~tools_error:(`Reference e) `Resolve;
r)
refs
|> List.rev
in
`Modules refs
and comment_nestable_block_element_list env parent
(xs : Comment.nestable_block_element Comment.with_location list) =
List.rev_map (with_location (comment_nestable_block_element env parent)) xs
|> List.rev
and comment_tag env parent ~loc:_ (x : Comment.tag) =
match x with
| `Deprecated content ->
`Deprecated (comment_nestable_block_element_list env parent content)
| `Param (name, content) ->
`Param (name, comment_nestable_block_element_list env parent content)
| `Raise (name, content) ->
`Raise (name, comment_nestable_block_element_list env parent content)
| `Return content ->
`Return (comment_nestable_block_element_list env parent content)
| `See (kind, target, content) ->
`See (kind, target, comment_nestable_block_element_list env parent content)
| `Before (version, content) ->
`Before (version, comment_nestable_block_element_list env parent content)
| `Author _ | `Since _ | `Alert _ | `Version _ ->
x (* only contain primitives *)
and comment_block_element env parent ~loc (x : Comment.block_element) =
match x with
| #Comment.nestable_block_element as x ->
(comment_nestable_block_element env parent ~loc x
:> Comment.block_element)
| `Heading h as x ->
check_ambiguous_label ~loc env h;
x
| `Tag t -> `Tag (comment_tag env parent ~loc t)
and with_location :
type a.
(loc:_ -> a -> a) -> a Location_.with_location -> a Location_.with_location
=
fun fn { value; location = loc } ->
let value = Lookup_failures.with_location loc (fun () -> fn ~loc value) in
{ value; location = loc }
and comment_docs env parent d =
List.rev_map
(with_location (comment_block_element env (parent :> Id.LabelParent.t)))
d
|> List.rev
and comment env parent = function
| `Stop -> `Stop
| `Docs d -> `Docs (comment_docs env parent d)
and open_ env parent = function
| { Odoc_model__Lang.Open.doc; _ } as open_ ->
{ open_ with doc = comment_docs env parent doc }
let rec unit env t =
let open Compilation_unit in
let content =
match t.content with
| Module sg -> Module (signature env (t.id :> Id.Signature.t) sg)
| Pack _ as p -> p
in
{ t with content; linked = true }
and value_ env parent t =
let open Value in
{
t with
doc = comment_docs env parent t.doc;
type_ = type_expression env parent [] t.type_;
}
and exception_ env parent e =
let open Exception in
let res = Opt.map (type_expression env parent []) e.res in
let args = type_decl_constructor_argument env parent e.args in
let doc = comment_docs env parent e.doc in
{ e with res; args; doc }
and extension env parent t =
let open Extension in
let constructor c =
let open Constructor in
{
c with
args = type_decl_constructor_argument env parent c.args;
res = Opt.map (type_expression env parent []) c.res;
doc = comment_docs env parent c.doc;
}
in
let type_path = type_path env t.type_path in
let constructors = List.map constructor t.constructors in
let doc = comment_docs env parent t.doc in
{ t with type_path; constructors; doc }
and class_type_expr env parent =
let open ClassType in
function
| Constr (path, texps) ->
Constr (path, List.map (type_expression env parent []) texps)
| Signature s -> Signature (class_signature env parent s)
and class_type env parent c =
let open ClassType in
let doc = comment_docs env parent c.doc in
{ c with expr = class_type_expr env parent c.expr; doc }
and class_signature env parent c =
let open ClassSignature in
let env = Env.open_class_signature c env in
let map_item = function
| Method m -> Method (method_ env parent m)
| InstanceVariable i -> InstanceVariable (instance_variable env parent i)
| Constraint cst -> Constraint (constraint_ env parent cst)
| Inherit c -> Inherit (inherit_ env parent c)
| Comment c -> Comment c
in
{
self = Opt.map (type_expression env parent []) c.self;
items = List.map map_item c.items;
doc = comment_docs env parent c.doc;
}
and method_ env parent m =
let open Method in
let doc = comment_docs env parent m.doc in
{ m with type_ = type_expression env parent [] m.type_; doc }
and instance_variable env parent i =
let open InstanceVariable in
let doc = comment_docs env parent i.doc in
{ i with type_ = type_expression env parent [] i.type_; doc }
and constraint_ env parent cst =
let open ClassSignature.Constraint in
let left = type_expression env parent [] cst.left
and right = type_expression env parent [] cst.right
and doc = comment_docs env parent cst.doc in
{ left; right; doc }
and inherit_ env parent ih =
let open ClassSignature.Inherit in
let expr = class_type_expr env parent ih.expr
and doc = comment_docs env parent ih.doc in
{ expr; doc }
and class_ env parent c =
let open Class in
let rec map_decl = function
| ClassType expr -> ClassType (class_type_expr env parent expr)
| Arrow (lbl, expr, decl) ->
Arrow (lbl, type_expression env parent [] expr, map_decl decl)
in
let doc = comment_docs env parent c.doc in
{ c with type_ = map_decl c.type_; doc }
and module_substitution env parent m =
let open ModuleSubstitution in
let doc = comment_docs env parent m.doc in
{ m with manifest = module_path env m.manifest; doc }
and signature : Env.t -> Id.Signature.t -> Signature.t -> _ =
fun env id s ->
let env = Env.open_signature s env |> Env.add_docs s.doc in
let items = signature_items env id s.items
and doc = comment_docs env id s.doc in
{ s with items; doc }
and signature_items :
Env.t -> Id.Signature.t -> Signature.item list -> Signature.item list =
fun env id s ->
let open Signature in
let items, _ =
List.fold_left
(fun (items, env) item ->
let std i = (i :: items, env) in
match item with
| Module (r, m) -> std @@ Module (r, module_ env m)
| ModuleSubstitution m ->
let env' = Env.open_module_substitution m env in
(ModuleSubstitution (module_substitution env id m) :: items, env')
| Type (r, t) -> std @@ Type (r, type_decl env id t)
| TypeSubstitution t ->
let env' = Env.open_type_substitution t env in
(TypeSubstitution (type_decl env id t) :: items, env')
| ModuleType mt -> std @@ ModuleType (module_type env mt)
| ModuleTypeSubstitution mts ->
let env' = Env.open_module_type_substitution mts env in
( ModuleTypeSubstitution (module_type_substitution env mts) :: items,
env' )
| Value v -> std @@ Value (value_ env id v)
| Comment c -> std @@ Comment (comment env id c)
| TypExt t -> std @@ TypExt (extension env id t)
| Exception e -> std @@ Exception (exception_ env id e)
| Class (r, c) -> std @@ Class (r, class_ env id c)
| ClassType (r, c) -> std @@ ClassType (r, class_type env id c)
| Include i -> std @@ Include (include_ env i)
| Open o -> std @@ Open (open_ env id o))
([], env) s
in
List.rev items
and simple_expansion :
Env.t ->
Id.Signature.t ->
ModuleType.simple_expansion ->
ModuleType.simple_expansion =
fun env id m ->
match m with
| Signature sg -> Signature (signature env id sg)
| Functor (arg, sg) ->
let env' = Env.add_functor_parameter arg env in
Functor (functor_argument env arg, simple_expansion env' id sg)
and module_ : Env.t -> Module.t -> Module.t =
fun env m ->
let open Module in
let open Utils.ResultMonad in
let sg_id = (m.id :> Id.Signature.t) in
if m.hidden then m
else
let type_ = module_decl env sg_id m.type_ in
let type_ =
match type_ with
| Alias (`Resolved p, _) ->
let hidden_alias =
Paths.Path.Resolved.Module.is_hidden ~weak_canonical_test:false p
in
let self_canonical =
let i = Paths.Path.Resolved.(identifier (p :> t)) in
i = (m.id :> Paths.Identifier.t)
in
let expansion_needed = self_canonical || hidden_alias in
if expansion_needed then
let cp = Component.Of_Lang.(resolved_module_path (empty ()) p) in
match
Tools.expansion_of_module_path ~strengthen:false env
(`Resolved cp)
>>= Expand_tools.handle_expansion env (m.id :> Id.Signature.t)
with
| Ok (_, e) ->
let le = Lang_of.(simple_expansion (empty ()) sg_id e) in
Alias (`Resolved p, Some (simple_expansion env sg_id le))
| Error _ -> type_
else type_
| Alias _ | ModuleType _ -> type_
in
{ m with doc = comment_docs env sg_id m.doc; type_ }
and module_decl : Env.t -> Id.Signature.t -> Module.decl -> Module.decl =
fun env id decl ->
let open Module in
match decl with
| ModuleType expr -> ModuleType (module_type_expr env id expr)
| Alias (p, e) ->
Alias (module_path env p, Opt.map (simple_expansion env id) e)
and include_decl : Env.t -> Id.Signature.t -> Include.decl -> Include.decl =
fun env id decl ->
let open Include in
match decl with
| ModuleType expr -> ModuleType (u_module_type_expr env id expr)
| Alias p -> Alias (module_path env p)
and module_type : Env.t -> ModuleType.t -> ModuleType.t =
fun env m ->
let sg_id = (m.id :> Id.Signature.t) in
let open ModuleType in
let expr' =
match m.expr with
| None -> None
| Some expr -> Some (module_type_expr env sg_id expr)
in
(* let self_canonical =
match m.expr with
| Some (Path (`Resolved p)) when Paths.Path.Resolved.ModuleType.canonical_ident p = Some m.id ->
true
| _ -> false
in*)
let doc = comment_docs env sg_id m.doc in
{ m with expr = expr'; doc }
and module_type_substitution :
Env.t -> ModuleTypeSubstitution.t -> ModuleTypeSubstitution.t =
fun env m ->
let sg_id = (m.id :> Id.Signature.t) in
let open ModuleTypeSubstitution in
let manifest' = module_type_expr env sg_id m.manifest in
let doc = comment_docs env sg_id m.doc in
{ m with manifest = manifest'; doc }
and include_ : Env.t -> Include.t -> Include.t =
fun env i ->
let open Include in
let decl = include_decl env i.parent i.decl in
let doc = comment_docs env i.parent i.doc in
let expansion =
(* Don't call {!signature} to avoid adding the content of the expansion to
the environment, which is already done recursively by
{!Env.open_signature}. *)
let content =
(* Add context around errors from the expansion. *)
Lookup_failures.with_context
"While resolving the expansion of include at %a" Location_.pp_span_start
i.loc (fun () ->
let { content; _ } = i.expansion in
let items = signature_items env i.parent content.items
and doc = comment_docs env i.parent content.doc in
{ content with items; doc })
in
{ i.expansion with content }
in
{ i with decl; expansion; doc }
and functor_parameter_parameter :
Env.t -> FunctorParameter.parameter -> FunctorParameter.parameter =
fun env a ->
let sg_id = (a.id :> Id.Signature.t) in
let expr = module_type_expr env sg_id a.expr in
{ a with expr }
and functor_argument env a =
match a with
| FunctorParameter.Unit -> FunctorParameter.Unit
| Named arg -> Named (functor_parameter_parameter env arg)
and handle_fragments env id sg subs =
let open ModuleType in
List.fold_left
(fun (sg_res, subs) lsub ->
match (sg_res, lsub) with
| Result.Ok sg, ModuleEq (frag, decl) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_fragment env cfrag
|> Lang_of.(Path.resolved_module_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleEq (frag', module_decl env id decl) :: subs)
| Ok sg, TypeEq (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_type_fragment env cfrag
|> Lang_of.(Path.resolved_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', TypeEq (frag', type_decl_equation env id eqn) :: subs)
| Ok sg, ModuleTypeEq (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_type_fragment env cfrag
|> Lang_of.(Path.resolved_module_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleTypeEq (frag', module_type_expr env id eqn) :: subs)
| Ok sg, ModuleSubst (frag, mpath) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_fragment env cfrag
|> Lang_of.(Path.resolved_module_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleSubst (frag', module_path env mpath) :: subs)
| Ok sg, TypeSubst (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_type_fragment env cfrag
|> Lang_of.(Path.resolved_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', TypeSubst (frag', type_decl_equation env id eqn) :: subs)
| Ok sg, ModuleTypeSubst (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_type_fragment env cfrag
|> Lang_of.(Path.resolved_module_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleTypeSubst (frag', module_type_expr env id eqn) :: subs)
| (Error _ as e), lsub -> (e, lsub :: subs))
(Ok sg, []) subs
|> snd |> List.rev
and u_module_type_expr :
Env.t -> Id.Signature.t -> ModuleType.U.expr -> ModuleType.U.expr =
fun env id expr ->
match expr with
| Signature s -> Signature s
(* No need to link 'unexpanded' module type expressions that are actually expanded... *)
| Path p -> Path (module_type_path env p)
| With (subs, expr) as unresolved -> (
let cexpr = Component.Of_Lang.(u_module_type_expr (empty ()) expr) in
match
Tools.signature_of_u_module_type_expr ~mark_substituted:true env cexpr
with
| Ok sg ->
With (handle_fragments env id sg subs, u_module_type_expr env id expr)
| Error e ->
Errors.report ~what:(`Module_type_U cexpr) ~tools_error:e `Resolve;
unresolved)
| TypeOf { t_desc = StructInclude p; t_expansion } ->
TypeOf { t_desc = StructInclude (module_path env p); t_expansion }
| TypeOf { t_desc = ModPath p; t_expansion } ->
TypeOf { t_desc = ModPath (module_path env p); t_expansion }
and module_type_expr :
Env.t -> Id.Signature.t -> ModuleType.expr -> ModuleType.expr =
fun env id expr ->
let open ModuleType in
let open Utils.ResultMonad in
let do_expn cur (e : Paths.Path.ModuleType.t option) =
match (cur, e) with
| Some e, _ ->
Some (simple_expansion env (id :> Paths.Identifier.Signature.t) e)
| None, Some (`Resolved p_path) ->
let hidden_alias =
Paths.Path.Resolved.ModuleType.is_hidden ~weak_canonical_test:false
p_path
in
let self_canonical =
let i = Paths.Path.Resolved.(identifier (p_path :> t)) in
(id :> Id.t) = i
in
let expansion_needed = self_canonical || hidden_alias in
if expansion_needed then
let cp =
Component.Of_Lang.(resolved_module_type_path (empty ()) p_path)
in
match
Tools.expansion_of_module_type_expr ~mark_substituted:false env
(Path { p_path = `Resolved cp; p_expansion = None })
>>= Expand_tools.handle_expansion env (id :> Id.Signature.t)
with
| Ok (_, e) ->
let le = Lang_of.(simple_expansion (empty ()) id e) in
Some (simple_expansion env id le)
| Error _ -> None
else None
| None, _ -> None
in
match expr with
| Signature s -> Signature (signature env id s)
| Path { p_path; p_expansion } ->
let p_path = module_type_path env p_path in
Path { p_path; p_expansion = do_expn p_expansion (Some p_path) }
| With { w_substitutions; w_expansion; w_expr } as unresolved -> (
let cexpr = Component.Of_Lang.(u_module_type_expr (empty ()) w_expr) in
match
Tools.signature_of_u_module_type_expr ~mark_substituted:true env cexpr
with
| Ok sg ->
With
{
w_substitutions = handle_fragments env id sg w_substitutions;
w_expansion = do_expn w_expansion None;
w_expr = u_module_type_expr env id w_expr;
}
| Error e ->
Errors.report ~what:(`Module_type_U cexpr) ~tools_error:e `Expand;
unresolved)
| Functor (arg, res) ->
let arg' = functor_argument env arg in
let env = Env.add_functor_parameter arg env in
let res' = module_type_expr env (Paths.Identifier.Mk.result id) res in
Functor (arg', res')
| TypeOf { t_desc = StructInclude p; t_expansion } ->
TypeOf
{
t_desc = StructInclude (module_path env p);
t_expansion = do_expn t_expansion None;
}
| TypeOf { t_desc = ModPath p; t_expansion } ->
TypeOf
{
t_desc = ModPath (module_path env p);
t_expansion = do_expn t_expansion None;
}
and type_decl_representation :
Env.t ->
Id.Signature.t ->
TypeDecl.Representation.t ->
TypeDecl.Representation.t =
fun env parent r ->
let open TypeDecl.Representation in
match r with
| Variant cs -> Variant (List.map (type_decl_constructor env parent) cs)
| Record fs -> Record (List.map (type_decl_field env parent) fs)
| Extensible -> Extensible
and type_decl : Env.t -> Id.Signature.t -> TypeDecl.t -> TypeDecl.t =
fun env parent t ->
let open TypeDecl in
let equation = type_decl_equation env parent t.equation in
let doc = comment_docs env parent t.doc in
let hidden_path =
match equation.Equation.manifest with
| Some (Constr (`Resolved path, params))
when Paths.Path.Resolved.Type.is_hidden path
|| Paths.Path.Resolved.(identifier (path :> t))
= (t.id :> Paths.Identifier.t) ->
Some (path, params)
| _ -> None
in
let representation =
Opt.map (type_decl_representation env parent) t.representation
in
let default = { t with equation; doc; representation } in
match hidden_path with
| Some (p, params) -> (
let p' = Component.Of_Lang.(resolved_type_path (empty ()) p) in
match Tools.lookup_type env p' with
| Ok (`FType (_, t')) ->
let equation =
try
Expand_tools.collapse_eqns default.equation
(Lang_of.type_decl_equation (Lang_of.empty ())
(parent :> Id.Parent.t)
t'.equation)
params
with _ -> default.equation
in
{ default with equation = type_decl_equation env parent equation }
| Ok (`FClass _ | `FClassType _ | `FType_removed _) | Error _ -> default)
| None -> default
and type_decl_equation env parent t =
let open TypeDecl.Equation in
let manifest = Opt.map (type_expression env parent []) t.manifest in
let constraints =
List.map
(fun (tex1, tex2) ->
(type_expression env parent [] tex1, type_expression env parent [] tex2))
t.constraints
in
{ t with manifest; constraints }
and type_decl_field env parent f =
let open TypeDecl.Field in
let doc = comment_docs env parent f.doc in
{ f with type_ = type_expression env parent [] f.type_; doc }
and type_decl_constructor_argument env parent c =
let open TypeDecl.Constructor in
match c with
| Tuple ts -> Tuple (List.map (type_expression env parent []) ts)
| Record fs -> Record (List.map (type_decl_field env parent) fs)
and type_decl_constructor env parent c =
let open TypeDecl.Constructor in
let doc = comment_docs env parent c.doc in
let args = type_decl_constructor_argument env parent c.args in
let res = Opt.map (type_expression env parent []) c.res in
{ c with doc; args; res }
and type_expression_polyvar env parent visited v =
let open TypeExpr.Polymorphic_variant in
let constructor c =
let open Constructor in
let doc = comment_docs env parent c.doc in
{
c with
arguments = List.map (type_expression env parent visited) c.arguments;
doc;
}
in
let element = function
| Type t ->
Type
(match type_expression env parent visited t with
| Constr _ as x -> x
| _ -> t)
These have to remain
| Constructor c -> Constructor (constructor c)
in
{ v with elements = List.map element v.elements }
and type_expression_object env parent visited o =
let open TypeExpr.Object in
let method_ m =
{ m with type_ = type_expression env parent visited m.type_ }
in
let field = function
| Method m -> Method (method_ m)
| Inherit t -> Inherit (type_expression env parent visited t)
in
{ o with fields = List.map field o.fields }
and type_expression_package env parent visited p =
let open TypeExpr.Package in
let substitution (frag, t) =
let cfrag = Component.Of_Lang.(type_fragment (empty ()) frag) in
let frag' =
match cfrag with
| `Resolved f -> `Resolved (Tools.reresolve_type_fragment env f)
| _ -> cfrag
in
( Lang_of.(Path.type_fragment (empty ()) frag'),
type_expression env parent visited t )
in
{
path = module_type_path env p.path;
substitutions = List.map substitution p.substitutions;
}
and type_expression : Env.t -> Id.Signature.t -> _ -> _ =
fun env parent visited texpr ->
let open TypeExpr in
match texpr with
| Var _ | Any -> texpr
| Alias (t, str) -> Alias (type_expression env parent visited t, str)
| Arrow (lbl, t1, t2) ->
Arrow
( lbl,
type_expression env parent visited t1,
type_expression env parent visited t2 )
| Tuple ts -> Tuple (List.map (type_expression env parent visited) ts)
| Constr (path', ts') -> (
let path = type_path env path' in
let ts = List.map (type_expression env parent visited) ts' in
if not (Paths.Path.is_hidden (path :> Paths.Path.t)) then Constr (path, ts)
else
let cp = Component.Of_Lang.(type_path (empty ()) path') in
match Tools.resolve_type env ~add_canonical:true cp with
| Ok (cp', `FType (_, t)) ->
let cp' = Tools.reresolve_type env cp' in
let p = Lang_of.(Path.resolved_type (empty ()) cp') in
if List.mem p visited then raise Loop
else if Cpath.is_resolved_type_hidden cp' then
match t.Component.TypeDecl.equation with
| { manifest = Some expr; params; _ } -> (
try
let map =
List.fold_left2
(fun acc param sub ->
match param.Lang.TypeDecl.desc with
| Lang.TypeDecl.Var x -> (x, sub) :: acc
| Any -> acc)
[] params ts
in
let t' =
Expand_tools.type_expr map
Lang_of.(
type_expr (empty ()) (parent :> Id.Parent.t) expr)
in
type_expression env parent (p :: visited) t'
with
| Loop -> Constr (`Resolved p, ts)
| e ->
Format.eprintf
"Caught unexpected exception when expanding type \
declaration (%s)\n\
%!"
(Printexc.to_string e);
Constr (`Resolved p, ts))
| _ -> Constr (`Resolved p, ts)
else Constr (`Resolved p, ts)
| Ok (cp', (`FClass _ | `FClassType _)) ->
let p = Lang_of.(Path.resolved_type (empty ()) cp') in
Constr (`Resolved p, ts)
| Ok (_cp, `FType_removed (_, x, _eq)) ->
(* Type variables ? *)
Lang_of.(type_expr (empty ()) (parent :> Id.Parent.t) x)
| Error _ -> Constr (path', ts))
| Polymorphic_variant v ->
Polymorphic_variant (type_expression_polyvar env parent visited v)
| Object o -> Object (type_expression_object env parent visited o)
| Class (path', ts') -> (
let path = class_type_path env path' in
let ts = List.map (type_expression env parent visited) ts' in
if not (Paths.Path.is_hidden (path :> Paths.Path.t)) then Class (path, ts)
else
let cp = Component.Of_Lang.(class_type_path (empty ()) path') in
match Tools.resolve_class_type env cp with
| Ok (cp', (`FClass _ | `FClassType _)) ->
let cp' = Tools.reresolve_class_type env cp' in
let p = Lang_of.(Path.resolved_class_type (empty ()) cp') in
Class (`Resolved p, ts)
| _ -> Class (path', ts))
| Poly (strs, t) -> Poly (strs, type_expression env parent visited t)
| Package p -> Package (type_expression_package env parent visited p)
let link ~filename x y =
Lookup_failures.catch_failures ~filename (fun () ->
if y.Lang.Compilation_unit.linked then y else unit x y)
let page env page =
let children =
List.fold_right
(fun child res ->
match Ref_tools.resolve_reference env child |> Error.raise_warnings with
| Ok r -> `Resolved r :: res
| Error _ ->
Errors.report ~what:(`Child child) `Resolve;
res)
page.Odoc_model.Lang.Page.children []
in
{
page with
Page.content = comment_docs env page.Page.name page.content;
children;
linked = true;
}
let resolve_page ~filename env p =
Lookup_failures.catch_failures ~filename (fun () ->
if p.Lang.Page.linked then p else page env p)
| null | https://raw.githubusercontent.com/ocaml/odoc/a52dd8e960f99b38162d40311a9c4512d5741d43/src/xref2/link.ml | ocaml | * Equivalent to {!Comment.synopsis}.
If there is no doc, look at the expansion.
* Raise a warning when a label explicitly set by the user collides. This
warning triggers even if one of the colliding labels have been automatically
generated.
Looking for an identical identifier but a different location.
In case of labels, use the heading text as reference text if
it's not specified.
only contain primitives
let self_canonical =
match m.expr with
| Some (Path (`Resolved p)) when Paths.Path.Resolved.ModuleType.canonical_ident p = Some m.id ->
true
| _ -> false
in
Don't call {!signature} to avoid adding the content of the expansion to
the environment, which is already done recursively by
{!Env.open_signature}.
Add context around errors from the expansion.
No need to link 'unexpanded' module type expressions that are actually expanded...
Type variables ? | Second round of resolution tackles references and forward paths
open Odoc_model
open Lang
module Id = Paths.Identifier
module Opt = struct
let map f = function Some x -> Some (f x) | None -> None
end
let synopsis_from_comment (docs : Component.CComment.docs) =
match docs with
| ({ value = #Comment.nestable_block_element; _ } as e) :: _ ->
Only the first element is considered .
Comment.synopsis [ e ]
| _ -> None
let synopsis_of_module env (m : Component.Module.t) =
let open Utils.ResultMonad in
match synopsis_from_comment m.doc with
| Some _ as s -> s
| None -> (
let rec handle_expansion : Tools.expansion -> _ = function
| Functor (_, expr) -> (
match
Tools.expansion_of_module_type_expr ~mark_substituted:true env
expr
with
| Ok e -> handle_expansion e
| Error _ as e -> e)
| Signature sg -> Ok sg
in
match Tools.expansion_of_module env m >>= handle_expansion with
| Ok sg -> synopsis_from_comment (Component.extract_signature_doc sg)
| Error _ -> None)
let ambiguous_label_warning label_name labels =
let pp_label_loc fmt (`Label (_, x)) =
Location_.pp_span_start fmt x.Component.Label.location
in
Lookup_failures.report_warning
"@[<2>Label '%s' is ambiguous. The other occurences are:@ %a@]" label_name
(Format.pp_print_list ~pp_sep:Format.pp_force_newline pp_label_loc)
labels
let check_ambiguous_label ~loc env
( attrs,
({ Odoc_model.Paths.Identifier.iv = `Label (_, label_name); _ } as id),
_ ) =
if attrs.Comment.heading_label_explicit then
let conflicting (`Label (id', comp)) =
Id.equal id id'
&& not (Location_.span_equal comp.Component.Label.location loc)
in
let label_name = Names.LabelName.to_string label_name in
match Env.lookup_by_name Env.s_label label_name env with
| Ok lbl when conflicting lbl -> ambiguous_label_warning label_name [ lbl ]
| Error (`Ambiguous (hd, tl)) -> (
match List.filter conflicting (hd :: tl) with
| [] -> ()
| xs -> ambiguous_label_warning label_name xs)
| Ok _ | Error `Not_found -> ()
exception Loop
let rec is_forward : Paths.Path.Module.t -> bool = function
| `Resolved _ -> false
| `Root _ -> false
| `Forward _ -> true
| `Identifier _ -> false
| `Dot (p, _) -> is_forward p
| `Apply (p1, p2) -> is_forward p1 || is_forward p2
let rec should_reresolve : Paths.Path.Resolved.t -> bool =
fun p ->
let open Paths.Path.Resolved in
match p with
| `Identifier _ -> false
| `Subst (x, y) -> should_reresolve (x :> t) || should_reresolve (y :> t)
| `Hidden p -> should_reresolve (p :> t)
| `Canonical (x, y) ->
should_reresolve (x :> t) || should_resolve (y :> Paths.Path.t)
| `CanonicalModuleType (x, y) ->
should_reresolve (x :> t) || should_resolve (y :> Paths.Path.t)
| `CanonicalType (x, y) ->
should_reresolve (x :> t) || should_resolve (y :> Paths.Path.t)
| `Apply (x, y) ->
should_reresolve (x :> t) || should_reresolve (y :> Paths.Path.Resolved.t)
| `SubstT (x, y) -> should_reresolve (x :> t) || should_reresolve (y :> t)
| `Alias (y, x) ->
should_resolve (x :> Paths.Path.t) || should_reresolve (y :> t)
| `AliasModuleType (x, y) ->
should_reresolve (x :> t) || should_reresolve (y :> t)
| `Type (p, _)
| `Class (p, _)
| `ClassType (p, _)
| `ModuleType (p, _)
| `Module (p, _) ->
should_reresolve (p :> t)
| `OpaqueModule m -> should_reresolve (m :> t)
| `OpaqueModuleType m -> should_reresolve (m :> t)
and should_resolve : Paths.Path.t -> bool =
fun p -> match p with `Resolved p -> should_reresolve p | _ -> true
let type_path : Env.t -> Paths.Path.Type.t -> Paths.Path.Type.t =
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(type_path (empty ()) p) in
match cp with
| `Resolved p ->
let result = Tools.reresolve_type env p in
`Resolved Lang_of.(Path.resolved_type (empty ()) result)
| _ -> (
match Tools.resolve_type_path env cp with
| Ok p' ->
let result = Tools.reresolve_type env p' in
`Resolved Lang_of.(Path.resolved_type (empty ()) result)
| Error e ->
Errors.report ~what:(`Type_path cp) ~tools_error:e `Lookup;
p)
let class_type_path : Env.t -> Paths.Path.ClassType.t -> Paths.Path.ClassType.t
=
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(class_type_path (empty ()) p) in
match cp with
| `Resolved p ->
let result = Tools.reresolve_class_type env p in
`Resolved Lang_of.(Path.resolved_class_type (empty ()) result)
| _ -> (
match Tools.resolve_class_type_path env cp with
| Ok p' ->
let result = Tools.reresolve_class_type env p' in
`Resolved Lang_of.(Path.resolved_class_type (empty ()) result)
| Error e ->
Errors.report ~what:(`Class_type_path cp) ~tools_error:e `Lookup;
p)
and module_type_path :
Env.t -> Paths.Path.ModuleType.t -> Paths.Path.ModuleType.t =
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(module_type_path (empty ()) p) in
match cp with
| `Resolved p ->
let result = Tools.reresolve_module_type env p in
`Resolved Lang_of.(Path.resolved_module_type (empty ()) result)
| _ -> (
match Tools.resolve_module_type_path env cp with
| Ok p' ->
let result = Tools.reresolve_module_type env p' in
`Resolved Lang_of.(Path.resolved_module_type (empty ()) result)
| Error e ->
Errors.report ~what:(`Module_type_path cp) ~tools_error:e `Resolve;
p)
and module_path : Env.t -> Paths.Path.Module.t -> Paths.Path.Module.t =
fun env p ->
if not (should_resolve (p :> Paths.Path.t)) then p
else
let cp = Component.Of_Lang.(module_path (empty ()) p) in
match cp with
| `Resolved p ->
let after = Tools.reresolve_module env p in
`Resolved Lang_of.(Path.resolved_module (empty ()) after)
| _ -> (
match Tools.resolve_module_path env cp with
| Ok p' ->
let result = Tools.reresolve_module env p' in
`Resolved Lang_of.(Path.resolved_module (empty ()) result)
| Error _ when is_forward p -> p
| Error e ->
Errors.report ~what:(`Module_path cp) ~tools_error:e `Resolve;
p)
let rec comment_inline_element :
loc:_ -> Env.t -> Comment.inline_element -> Comment.inline_element =
fun ~loc:_ env x ->
match x with
| `Styled (s, ls) ->
`Styled (s, List.map (with_location (comment_inline_element env)) ls)
| `Reference (r, content) as orig -> (
match Ref_tools.resolve_reference env r |> Error.raise_warnings with
| Ok x ->
let content =
match (content, x) with
| [], `Identifier ({ iv = #Id.Label.t_pv; _ } as i) -> (
match Env.lookup_by_id Env.s_label i env with
| Some (`Label (_, lbl)) -> lbl.Component.Label.text
| None -> [])
| content, _ -> content
in
`Reference (`Resolved x, content)
| Error e ->
Errors.report ~what:(`Reference r) ~tools_error:(`Reference e)
`Resolve;
orig)
| y -> y
and paragraph env elts =
List.map (with_location (comment_inline_element env)) elts
and resolve_external_synopsis env synopsis =
let env = Env.inherit_resolver env in
paragraph env synopsis
and comment_nestable_block_element env parent ~loc:_
(x : Comment.nestable_block_element) =
match x with
| `Paragraph elts -> `Paragraph (paragraph env elts)
| (`Code_block _ | `Math_block _ | `Verbatim _) as x -> x
| `List (x, ys) ->
`List
( x,
List.rev_map (comment_nestable_block_element_list env parent) ys
|> List.rev )
| `Modules refs ->
let refs =
List.rev_map
(fun (r : Comment.module_reference) ->
match
Ref_tools.resolve_module_reference env r.module_reference
|> Error.raise_warnings
with
| Ok (r, _, m) ->
let module_synopsis =
Opt.map
(resolve_external_synopsis env)
(synopsis_of_module env m)
in
{ Comment.module_reference = `Resolved r; module_synopsis }
| Error e ->
Errors.report
~what:(`Reference (r.module_reference :> Paths.Reference.t))
~tools_error:(`Reference e) `Resolve;
r)
refs
|> List.rev
in
`Modules refs
and comment_nestable_block_element_list env parent
(xs : Comment.nestable_block_element Comment.with_location list) =
List.rev_map (with_location (comment_nestable_block_element env parent)) xs
|> List.rev
and comment_tag env parent ~loc:_ (x : Comment.tag) =
match x with
| `Deprecated content ->
`Deprecated (comment_nestable_block_element_list env parent content)
| `Param (name, content) ->
`Param (name, comment_nestable_block_element_list env parent content)
| `Raise (name, content) ->
`Raise (name, comment_nestable_block_element_list env parent content)
| `Return content ->
`Return (comment_nestable_block_element_list env parent content)
| `See (kind, target, content) ->
`See (kind, target, comment_nestable_block_element_list env parent content)
| `Before (version, content) ->
`Before (version, comment_nestable_block_element_list env parent content)
| `Author _ | `Since _ | `Alert _ | `Version _ ->
and comment_block_element env parent ~loc (x : Comment.block_element) =
match x with
| #Comment.nestable_block_element as x ->
(comment_nestable_block_element env parent ~loc x
:> Comment.block_element)
| `Heading h as x ->
check_ambiguous_label ~loc env h;
x
| `Tag t -> `Tag (comment_tag env parent ~loc t)
and with_location :
type a.
(loc:_ -> a -> a) -> a Location_.with_location -> a Location_.with_location
=
fun fn { value; location = loc } ->
let value = Lookup_failures.with_location loc (fun () -> fn ~loc value) in
{ value; location = loc }
and comment_docs env parent d =
List.rev_map
(with_location (comment_block_element env (parent :> Id.LabelParent.t)))
d
|> List.rev
and comment env parent = function
| `Stop -> `Stop
| `Docs d -> `Docs (comment_docs env parent d)
and open_ env parent = function
| { Odoc_model__Lang.Open.doc; _ } as open_ ->
{ open_ with doc = comment_docs env parent doc }
let rec unit env t =
let open Compilation_unit in
let content =
match t.content with
| Module sg -> Module (signature env (t.id :> Id.Signature.t) sg)
| Pack _ as p -> p
in
{ t with content; linked = true }
and value_ env parent t =
let open Value in
{
t with
doc = comment_docs env parent t.doc;
type_ = type_expression env parent [] t.type_;
}
and exception_ env parent e =
let open Exception in
let res = Opt.map (type_expression env parent []) e.res in
let args = type_decl_constructor_argument env parent e.args in
let doc = comment_docs env parent e.doc in
{ e with res; args; doc }
and extension env parent t =
let open Extension in
let constructor c =
let open Constructor in
{
c with
args = type_decl_constructor_argument env parent c.args;
res = Opt.map (type_expression env parent []) c.res;
doc = comment_docs env parent c.doc;
}
in
let type_path = type_path env t.type_path in
let constructors = List.map constructor t.constructors in
let doc = comment_docs env parent t.doc in
{ t with type_path; constructors; doc }
and class_type_expr env parent =
let open ClassType in
function
| Constr (path, texps) ->
Constr (path, List.map (type_expression env parent []) texps)
| Signature s -> Signature (class_signature env parent s)
and class_type env parent c =
let open ClassType in
let doc = comment_docs env parent c.doc in
{ c with expr = class_type_expr env parent c.expr; doc }
and class_signature env parent c =
let open ClassSignature in
let env = Env.open_class_signature c env in
let map_item = function
| Method m -> Method (method_ env parent m)
| InstanceVariable i -> InstanceVariable (instance_variable env parent i)
| Constraint cst -> Constraint (constraint_ env parent cst)
| Inherit c -> Inherit (inherit_ env parent c)
| Comment c -> Comment c
in
{
self = Opt.map (type_expression env parent []) c.self;
items = List.map map_item c.items;
doc = comment_docs env parent c.doc;
}
and method_ env parent m =
let open Method in
let doc = comment_docs env parent m.doc in
{ m with type_ = type_expression env parent [] m.type_; doc }
and instance_variable env parent i =
let open InstanceVariable in
let doc = comment_docs env parent i.doc in
{ i with type_ = type_expression env parent [] i.type_; doc }
and constraint_ env parent cst =
let open ClassSignature.Constraint in
let left = type_expression env parent [] cst.left
and right = type_expression env parent [] cst.right
and doc = comment_docs env parent cst.doc in
{ left; right; doc }
and inherit_ env parent ih =
let open ClassSignature.Inherit in
let expr = class_type_expr env parent ih.expr
and doc = comment_docs env parent ih.doc in
{ expr; doc }
and class_ env parent c =
let open Class in
let rec map_decl = function
| ClassType expr -> ClassType (class_type_expr env parent expr)
| Arrow (lbl, expr, decl) ->
Arrow (lbl, type_expression env parent [] expr, map_decl decl)
in
let doc = comment_docs env parent c.doc in
{ c with type_ = map_decl c.type_; doc }
and module_substitution env parent m =
let open ModuleSubstitution in
let doc = comment_docs env parent m.doc in
{ m with manifest = module_path env m.manifest; doc }
and signature : Env.t -> Id.Signature.t -> Signature.t -> _ =
fun env id s ->
let env = Env.open_signature s env |> Env.add_docs s.doc in
let items = signature_items env id s.items
and doc = comment_docs env id s.doc in
{ s with items; doc }
and signature_items :
Env.t -> Id.Signature.t -> Signature.item list -> Signature.item list =
fun env id s ->
let open Signature in
let items, _ =
List.fold_left
(fun (items, env) item ->
let std i = (i :: items, env) in
match item with
| Module (r, m) -> std @@ Module (r, module_ env m)
| ModuleSubstitution m ->
let env' = Env.open_module_substitution m env in
(ModuleSubstitution (module_substitution env id m) :: items, env')
| Type (r, t) -> std @@ Type (r, type_decl env id t)
| TypeSubstitution t ->
let env' = Env.open_type_substitution t env in
(TypeSubstitution (type_decl env id t) :: items, env')
| ModuleType mt -> std @@ ModuleType (module_type env mt)
| ModuleTypeSubstitution mts ->
let env' = Env.open_module_type_substitution mts env in
( ModuleTypeSubstitution (module_type_substitution env mts) :: items,
env' )
| Value v -> std @@ Value (value_ env id v)
| Comment c -> std @@ Comment (comment env id c)
| TypExt t -> std @@ TypExt (extension env id t)
| Exception e -> std @@ Exception (exception_ env id e)
| Class (r, c) -> std @@ Class (r, class_ env id c)
| ClassType (r, c) -> std @@ ClassType (r, class_type env id c)
| Include i -> std @@ Include (include_ env i)
| Open o -> std @@ Open (open_ env id o))
([], env) s
in
List.rev items
and simple_expansion :
Env.t ->
Id.Signature.t ->
ModuleType.simple_expansion ->
ModuleType.simple_expansion =
fun env id m ->
match m with
| Signature sg -> Signature (signature env id sg)
| Functor (arg, sg) ->
let env' = Env.add_functor_parameter arg env in
Functor (functor_argument env arg, simple_expansion env' id sg)
and module_ : Env.t -> Module.t -> Module.t =
fun env m ->
let open Module in
let open Utils.ResultMonad in
let sg_id = (m.id :> Id.Signature.t) in
if m.hidden then m
else
let type_ = module_decl env sg_id m.type_ in
let type_ =
match type_ with
| Alias (`Resolved p, _) ->
let hidden_alias =
Paths.Path.Resolved.Module.is_hidden ~weak_canonical_test:false p
in
let self_canonical =
let i = Paths.Path.Resolved.(identifier (p :> t)) in
i = (m.id :> Paths.Identifier.t)
in
let expansion_needed = self_canonical || hidden_alias in
if expansion_needed then
let cp = Component.Of_Lang.(resolved_module_path (empty ()) p) in
match
Tools.expansion_of_module_path ~strengthen:false env
(`Resolved cp)
>>= Expand_tools.handle_expansion env (m.id :> Id.Signature.t)
with
| Ok (_, e) ->
let le = Lang_of.(simple_expansion (empty ()) sg_id e) in
Alias (`Resolved p, Some (simple_expansion env sg_id le))
| Error _ -> type_
else type_
| Alias _ | ModuleType _ -> type_
in
{ m with doc = comment_docs env sg_id m.doc; type_ }
and module_decl : Env.t -> Id.Signature.t -> Module.decl -> Module.decl =
fun env id decl ->
let open Module in
match decl with
| ModuleType expr -> ModuleType (module_type_expr env id expr)
| Alias (p, e) ->
Alias (module_path env p, Opt.map (simple_expansion env id) e)
and include_decl : Env.t -> Id.Signature.t -> Include.decl -> Include.decl =
fun env id decl ->
let open Include in
match decl with
| ModuleType expr -> ModuleType (u_module_type_expr env id expr)
| Alias p -> Alias (module_path env p)
and module_type : Env.t -> ModuleType.t -> ModuleType.t =
fun env m ->
let sg_id = (m.id :> Id.Signature.t) in
let open ModuleType in
let expr' =
match m.expr with
| None -> None
| Some expr -> Some (module_type_expr env sg_id expr)
in
let doc = comment_docs env sg_id m.doc in
{ m with expr = expr'; doc }
and module_type_substitution :
Env.t -> ModuleTypeSubstitution.t -> ModuleTypeSubstitution.t =
fun env m ->
let sg_id = (m.id :> Id.Signature.t) in
let open ModuleTypeSubstitution in
let manifest' = module_type_expr env sg_id m.manifest in
let doc = comment_docs env sg_id m.doc in
{ m with manifest = manifest'; doc }
and include_ : Env.t -> Include.t -> Include.t =
fun env i ->
let open Include in
let decl = include_decl env i.parent i.decl in
let doc = comment_docs env i.parent i.doc in
let expansion =
let content =
Lookup_failures.with_context
"While resolving the expansion of include at %a" Location_.pp_span_start
i.loc (fun () ->
let { content; _ } = i.expansion in
let items = signature_items env i.parent content.items
and doc = comment_docs env i.parent content.doc in
{ content with items; doc })
in
{ i.expansion with content }
in
{ i with decl; expansion; doc }
and functor_parameter_parameter :
Env.t -> FunctorParameter.parameter -> FunctorParameter.parameter =
fun env a ->
let sg_id = (a.id :> Id.Signature.t) in
let expr = module_type_expr env sg_id a.expr in
{ a with expr }
and functor_argument env a =
match a with
| FunctorParameter.Unit -> FunctorParameter.Unit
| Named arg -> Named (functor_parameter_parameter env arg)
and handle_fragments env id sg subs =
let open ModuleType in
List.fold_left
(fun (sg_res, subs) lsub ->
match (sg_res, lsub) with
| Result.Ok sg, ModuleEq (frag, decl) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_fragment env cfrag
|> Lang_of.(Path.resolved_module_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleEq (frag', module_decl env id decl) :: subs)
| Ok sg, TypeEq (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_type_fragment env cfrag
|> Lang_of.(Path.resolved_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', TypeEq (frag', type_decl_equation env id eqn) :: subs)
| Ok sg, ModuleTypeEq (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_type_fragment env cfrag
|> Lang_of.(Path.resolved_module_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleTypeEq (frag', module_type_expr env id eqn) :: subs)
| Ok sg, ModuleSubst (frag, mpath) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_fragment env cfrag
|> Lang_of.(Path.resolved_module_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleSubst (frag', module_path env mpath) :: subs)
| Ok sg, TypeSubst (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_type_fragment env cfrag
|> Lang_of.(Path.resolved_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', TypeSubst (frag', type_decl_equation env id eqn) :: subs)
| Ok sg, ModuleTypeSubst (frag, eqn) ->
let frag' =
match frag with
| `Resolved f ->
let cfrag =
Component.Of_Lang.(resolved_module_type_fragment (empty ()) f)
in
`Resolved
(Tools.reresolve_module_type_fragment env cfrag
|> Lang_of.(Path.resolved_module_type_fragment (empty ())))
| _ -> frag
in
let sg' =
Tools.fragmap ~mark_substituted:true env
Component.Of_Lang.(with_module_type_substitution (empty ()) lsub)
sg
in
(sg', ModuleTypeSubst (frag', module_type_expr env id eqn) :: subs)
| (Error _ as e), lsub -> (e, lsub :: subs))
(Ok sg, []) subs
|> snd |> List.rev
and u_module_type_expr :
Env.t -> Id.Signature.t -> ModuleType.U.expr -> ModuleType.U.expr =
fun env id expr ->
match expr with
| Signature s -> Signature s
| Path p -> Path (module_type_path env p)
| With (subs, expr) as unresolved -> (
let cexpr = Component.Of_Lang.(u_module_type_expr (empty ()) expr) in
match
Tools.signature_of_u_module_type_expr ~mark_substituted:true env cexpr
with
| Ok sg ->
With (handle_fragments env id sg subs, u_module_type_expr env id expr)
| Error e ->
Errors.report ~what:(`Module_type_U cexpr) ~tools_error:e `Resolve;
unresolved)
| TypeOf { t_desc = StructInclude p; t_expansion } ->
TypeOf { t_desc = StructInclude (module_path env p); t_expansion }
| TypeOf { t_desc = ModPath p; t_expansion } ->
TypeOf { t_desc = ModPath (module_path env p); t_expansion }
and module_type_expr :
Env.t -> Id.Signature.t -> ModuleType.expr -> ModuleType.expr =
fun env id expr ->
let open ModuleType in
let open Utils.ResultMonad in
let do_expn cur (e : Paths.Path.ModuleType.t option) =
match (cur, e) with
| Some e, _ ->
Some (simple_expansion env (id :> Paths.Identifier.Signature.t) e)
| None, Some (`Resolved p_path) ->
let hidden_alias =
Paths.Path.Resolved.ModuleType.is_hidden ~weak_canonical_test:false
p_path
in
let self_canonical =
let i = Paths.Path.Resolved.(identifier (p_path :> t)) in
(id :> Id.t) = i
in
let expansion_needed = self_canonical || hidden_alias in
if expansion_needed then
let cp =
Component.Of_Lang.(resolved_module_type_path (empty ()) p_path)
in
match
Tools.expansion_of_module_type_expr ~mark_substituted:false env
(Path { p_path = `Resolved cp; p_expansion = None })
>>= Expand_tools.handle_expansion env (id :> Id.Signature.t)
with
| Ok (_, e) ->
let le = Lang_of.(simple_expansion (empty ()) id e) in
Some (simple_expansion env id le)
| Error _ -> None
else None
| None, _ -> None
in
match expr with
| Signature s -> Signature (signature env id s)
| Path { p_path; p_expansion } ->
let p_path = module_type_path env p_path in
Path { p_path; p_expansion = do_expn p_expansion (Some p_path) }
| With { w_substitutions; w_expansion; w_expr } as unresolved -> (
let cexpr = Component.Of_Lang.(u_module_type_expr (empty ()) w_expr) in
match
Tools.signature_of_u_module_type_expr ~mark_substituted:true env cexpr
with
| Ok sg ->
With
{
w_substitutions = handle_fragments env id sg w_substitutions;
w_expansion = do_expn w_expansion None;
w_expr = u_module_type_expr env id w_expr;
}
| Error e ->
Errors.report ~what:(`Module_type_U cexpr) ~tools_error:e `Expand;
unresolved)
| Functor (arg, res) ->
let arg' = functor_argument env arg in
let env = Env.add_functor_parameter arg env in
let res' = module_type_expr env (Paths.Identifier.Mk.result id) res in
Functor (arg', res')
| TypeOf { t_desc = StructInclude p; t_expansion } ->
TypeOf
{
t_desc = StructInclude (module_path env p);
t_expansion = do_expn t_expansion None;
}
| TypeOf { t_desc = ModPath p; t_expansion } ->
TypeOf
{
t_desc = ModPath (module_path env p);
t_expansion = do_expn t_expansion None;
}
and type_decl_representation :
Env.t ->
Id.Signature.t ->
TypeDecl.Representation.t ->
TypeDecl.Representation.t =
fun env parent r ->
let open TypeDecl.Representation in
match r with
| Variant cs -> Variant (List.map (type_decl_constructor env parent) cs)
| Record fs -> Record (List.map (type_decl_field env parent) fs)
| Extensible -> Extensible
and type_decl : Env.t -> Id.Signature.t -> TypeDecl.t -> TypeDecl.t =
fun env parent t ->
let open TypeDecl in
let equation = type_decl_equation env parent t.equation in
let doc = comment_docs env parent t.doc in
let hidden_path =
match equation.Equation.manifest with
| Some (Constr (`Resolved path, params))
when Paths.Path.Resolved.Type.is_hidden path
|| Paths.Path.Resolved.(identifier (path :> t))
= (t.id :> Paths.Identifier.t) ->
Some (path, params)
| _ -> None
in
let representation =
Opt.map (type_decl_representation env parent) t.representation
in
let default = { t with equation; doc; representation } in
match hidden_path with
| Some (p, params) -> (
let p' = Component.Of_Lang.(resolved_type_path (empty ()) p) in
match Tools.lookup_type env p' with
| Ok (`FType (_, t')) ->
let equation =
try
Expand_tools.collapse_eqns default.equation
(Lang_of.type_decl_equation (Lang_of.empty ())
(parent :> Id.Parent.t)
t'.equation)
params
with _ -> default.equation
in
{ default with equation = type_decl_equation env parent equation }
| Ok (`FClass _ | `FClassType _ | `FType_removed _) | Error _ -> default)
| None -> default
and type_decl_equation env parent t =
let open TypeDecl.Equation in
let manifest = Opt.map (type_expression env parent []) t.manifest in
let constraints =
List.map
(fun (tex1, tex2) ->
(type_expression env parent [] tex1, type_expression env parent [] tex2))
t.constraints
in
{ t with manifest; constraints }
and type_decl_field env parent f =
let open TypeDecl.Field in
let doc = comment_docs env parent f.doc in
{ f with type_ = type_expression env parent [] f.type_; doc }
and type_decl_constructor_argument env parent c =
let open TypeDecl.Constructor in
match c with
| Tuple ts -> Tuple (List.map (type_expression env parent []) ts)
| Record fs -> Record (List.map (type_decl_field env parent) fs)
and type_decl_constructor env parent c =
let open TypeDecl.Constructor in
let doc = comment_docs env parent c.doc in
let args = type_decl_constructor_argument env parent c.args in
let res = Opt.map (type_expression env parent []) c.res in
{ c with doc; args; res }
and type_expression_polyvar env parent visited v =
let open TypeExpr.Polymorphic_variant in
let constructor c =
let open Constructor in
let doc = comment_docs env parent c.doc in
{
c with
arguments = List.map (type_expression env parent visited) c.arguments;
doc;
}
in
let element = function
| Type t ->
Type
(match type_expression env parent visited t with
| Constr _ as x -> x
| _ -> t)
These have to remain
| Constructor c -> Constructor (constructor c)
in
{ v with elements = List.map element v.elements }
and type_expression_object env parent visited o =
let open TypeExpr.Object in
let method_ m =
{ m with type_ = type_expression env parent visited m.type_ }
in
let field = function
| Method m -> Method (method_ m)
| Inherit t -> Inherit (type_expression env parent visited t)
in
{ o with fields = List.map field o.fields }
and type_expression_package env parent visited p =
let open TypeExpr.Package in
let substitution (frag, t) =
let cfrag = Component.Of_Lang.(type_fragment (empty ()) frag) in
let frag' =
match cfrag with
| `Resolved f -> `Resolved (Tools.reresolve_type_fragment env f)
| _ -> cfrag
in
( Lang_of.(Path.type_fragment (empty ()) frag'),
type_expression env parent visited t )
in
{
path = module_type_path env p.path;
substitutions = List.map substitution p.substitutions;
}
and type_expression : Env.t -> Id.Signature.t -> _ -> _ =
fun env parent visited texpr ->
let open TypeExpr in
match texpr with
| Var _ | Any -> texpr
| Alias (t, str) -> Alias (type_expression env parent visited t, str)
| Arrow (lbl, t1, t2) ->
Arrow
( lbl,
type_expression env parent visited t1,
type_expression env parent visited t2 )
| Tuple ts -> Tuple (List.map (type_expression env parent visited) ts)
| Constr (path', ts') -> (
let path = type_path env path' in
let ts = List.map (type_expression env parent visited) ts' in
if not (Paths.Path.is_hidden (path :> Paths.Path.t)) then Constr (path, ts)
else
let cp = Component.Of_Lang.(type_path (empty ()) path') in
match Tools.resolve_type env ~add_canonical:true cp with
| Ok (cp', `FType (_, t)) ->
let cp' = Tools.reresolve_type env cp' in
let p = Lang_of.(Path.resolved_type (empty ()) cp') in
if List.mem p visited then raise Loop
else if Cpath.is_resolved_type_hidden cp' then
match t.Component.TypeDecl.equation with
| { manifest = Some expr; params; _ } -> (
try
let map =
List.fold_left2
(fun acc param sub ->
match param.Lang.TypeDecl.desc with
| Lang.TypeDecl.Var x -> (x, sub) :: acc
| Any -> acc)
[] params ts
in
let t' =
Expand_tools.type_expr map
Lang_of.(
type_expr (empty ()) (parent :> Id.Parent.t) expr)
in
type_expression env parent (p :: visited) t'
with
| Loop -> Constr (`Resolved p, ts)
| e ->
Format.eprintf
"Caught unexpected exception when expanding type \
declaration (%s)\n\
%!"
(Printexc.to_string e);
Constr (`Resolved p, ts))
| _ -> Constr (`Resolved p, ts)
else Constr (`Resolved p, ts)
| Ok (cp', (`FClass _ | `FClassType _)) ->
let p = Lang_of.(Path.resolved_type (empty ()) cp') in
Constr (`Resolved p, ts)
| Ok (_cp, `FType_removed (_, x, _eq)) ->
Lang_of.(type_expr (empty ()) (parent :> Id.Parent.t) x)
| Error _ -> Constr (path', ts))
| Polymorphic_variant v ->
Polymorphic_variant (type_expression_polyvar env parent visited v)
| Object o -> Object (type_expression_object env parent visited o)
| Class (path', ts') -> (
let path = class_type_path env path' in
let ts = List.map (type_expression env parent visited) ts' in
if not (Paths.Path.is_hidden (path :> Paths.Path.t)) then Class (path, ts)
else
let cp = Component.Of_Lang.(class_type_path (empty ()) path') in
match Tools.resolve_class_type env cp with
| Ok (cp', (`FClass _ | `FClassType _)) ->
let cp' = Tools.reresolve_class_type env cp' in
let p = Lang_of.(Path.resolved_class_type (empty ()) cp') in
Class (`Resolved p, ts)
| _ -> Class (path', ts))
| Poly (strs, t) -> Poly (strs, type_expression env parent visited t)
| Package p -> Package (type_expression_package env parent visited p)
let link ~filename x y =
Lookup_failures.catch_failures ~filename (fun () ->
if y.Lang.Compilation_unit.linked then y else unit x y)
let page env page =
let children =
List.fold_right
(fun child res ->
match Ref_tools.resolve_reference env child |> Error.raise_warnings with
| Ok r -> `Resolved r :: res
| Error _ ->
Errors.report ~what:(`Child child) `Resolve;
res)
page.Odoc_model.Lang.Page.children []
in
{
page with
Page.content = comment_docs env page.Page.name page.content;
children;
linked = true;
}
let resolve_page ~filename env p =
Lookup_failures.catch_failures ~filename (fun () ->
if p.Lang.Page.linked then p else page env p)
|
304afd072a73325e4f0866fae497272680aaa9697abd4d32837c34404dda6a89 | HaskellZhangSong/Introduction_to_Haskell_2ed_source | Stack.hs | import Control.Monad.State
type Stack = [Int]
pop :: State Stack Int
pop = state $ \(x:xs) -> (x,xs)
peek :: State Stack Int
peek = state $ \(x:xs) -> (x,x:xs)
push :: Int -> State Stack ()
push i = state $ \xs -> ((), i:xs)
addStack :: State Stack ()
addStack = do
a1 <- pop
a2 <- pop
let a3 = a1+a2
push a3
| null | https://raw.githubusercontent.com/HaskellZhangSong/Introduction_to_Haskell_2ed_source/140c50fdccfe608fe499ecf2d8a3732f531173f5/C12/Stack.hs | haskell | import Control.Monad.State
type Stack = [Int]
pop :: State Stack Int
pop = state $ \(x:xs) -> (x,xs)
peek :: State Stack Int
peek = state $ \(x:xs) -> (x,x:xs)
push :: Int -> State Stack ()
push i = state $ \xs -> ((), i:xs)
addStack :: State Stack ()
addStack = do
a1 <- pop
a2 <- pop
let a3 = a1+a2
push a3
| |
0d3b90b52c1e3c6547fcb46a8359f388a2755632b57a6394ed6ddad8d3006351 | facebookarchive/duckling_old | finance.clj | (
"intersect (X cents)" ;
[(dim :amount-of-money) (dim :amount-of-money #(= (:unit %) "cent"))]
(compose-money %1 %2)
; #(not (:number-prefixed %)
"₩"
#"\₩|원|(?i)KRW"
{:dim :unit
:unit "KRW"}
"$"
#"\$|달러|불"
{:dim :unit
:unit "$"} ; ambiguous
"cent"
#"(?i)cents?|센[트|츠]|c|¢" ; to do:localize the corpus and rules per language
{:dim :unit
:unit "cent"}
"€"
#"€|유로|(?i)EURO?"
{:dim :unit
:unit "EUR"} ; not ambiguous
"£"
#"£|파운드|영국파운드"
{:dim :unit
:unit "£"}
"GBP"
#"(?i)GBP"
{:dim :unit
:unit "GBP"}
;Australian Dollar Currency
"AUD"
#"(?i)AUD|호주달러"
{:dim :unit
:unit "AUD"}
"USD"
#"(?i)US[D\$]"
{:dim :unit
:unit "USD"}
"PTS"
#"(?i)pta?s?"
{:dim :unit
:unit "PTS"}
Indian Currency
"INR"
#"(?i)INR|Rs(. )?|(R|r)upees?|루피|인도루피"
{:dim :unit
:unit "INR"}
;Emirates Currency
"AED"
#"(?i)AED|(D|d)irhams?"
{:dim :unit
:unit "AED"}
"unnamed currency"
#"(?i)(buck|balle|pouloute)s?"
{:dim :unit}
"<unit> <amount>"
[(dim :unit) (dim :number)]
{:dim :amount-of-money
:value (:value %2)
:unit (:unit %1)
:fields {(:unit %1) (:value %2)}}
"<amount> <unit>"
[(dim :number) (dim :unit)]
{:dim :amount-of-money
:value (:value %1)
:unit (:unit %2)
:fields {(:unit %1) (:value %2)}}
precision for " 약 $ 15 "
"about <amount-of-money>"
[#"약|대충|얼추" (dim :amount-of-money)]
(assoc %2 :precision "approximate")
precision for " $ 15 정도 "
"<amount-of-money> about"
[(dim :amount-of-money) #"정도|쯤"]
(assoc %1 :precision "approximate")
"exactly <amount-of-money>"
[#"딱|정확히" (dim :amount-of-money)]
(assoc %2 :precision "exact")
)
| null | https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/ko/rules/finance.clj | clojure |
#(not (:number-prefixed %)
ambiguous
to do:localize the corpus and rules per language
not ambiguous
Australian Dollar Currency
Emirates Currency | (
[(dim :amount-of-money) (dim :amount-of-money #(= (:unit %) "cent"))]
(compose-money %1 %2)
"₩"
#"\₩|원|(?i)KRW"
{:dim :unit
:unit "KRW"}
"$"
#"\$|달러|불"
{:dim :unit
"cent"
{:dim :unit
:unit "cent"}
"€"
#"€|유로|(?i)EURO?"
{:dim :unit
"£"
#"£|파운드|영국파운드"
{:dim :unit
:unit "£"}
"GBP"
#"(?i)GBP"
{:dim :unit
:unit "GBP"}
"AUD"
#"(?i)AUD|호주달러"
{:dim :unit
:unit "AUD"}
"USD"
#"(?i)US[D\$]"
{:dim :unit
:unit "USD"}
"PTS"
#"(?i)pta?s?"
{:dim :unit
:unit "PTS"}
Indian Currency
"INR"
#"(?i)INR|Rs(. )?|(R|r)upees?|루피|인도루피"
{:dim :unit
:unit "INR"}
"AED"
#"(?i)AED|(D|d)irhams?"
{:dim :unit
:unit "AED"}
"unnamed currency"
#"(?i)(buck|balle|pouloute)s?"
{:dim :unit}
"<unit> <amount>"
[(dim :unit) (dim :number)]
{:dim :amount-of-money
:value (:value %2)
:unit (:unit %1)
:fields {(:unit %1) (:value %2)}}
"<amount> <unit>"
[(dim :number) (dim :unit)]
{:dim :amount-of-money
:value (:value %1)
:unit (:unit %2)
:fields {(:unit %1) (:value %2)}}
precision for " 약 $ 15 "
"about <amount-of-money>"
[#"약|대충|얼추" (dim :amount-of-money)]
(assoc %2 :precision "approximate")
precision for " $ 15 정도 "
"<amount-of-money> about"
[(dim :amount-of-money) #"정도|쯤"]
(assoc %1 :precision "approximate")
"exactly <amount-of-money>"
[#"딱|정확히" (dim :amount-of-money)]
(assoc %2 :precision "exact")
)
|
80c560f1c3ca40c570189c96ced7ada6512719fea2ad75c5b66e34c5d4bc7c19 | mlemerre/l-lang | cpsllvm.ml | Copyright 2012 - 2013 .
For List.fold_left_with_index .
i \section{Module } i
s This module translates a term written in CPS representation to
LLVM instructions in SSA form .
The CPS representation stems from the paper " Compiling with
continuations , continued " by . In particular this
representation separates continuations from standard lambda
functions , which allows calling and returning from functions using
the normal stack , and allow close correspondance with the SSA form .
This module assumes that functions have no free variables ( or
continuation variables ) . Closure conversion removes free variables
from functions . Free continuation variables should never happen
when translating normal terms to CPS .
The module also assumes that the CPS values do not refer to
primitive operations , such as + , -,*,/. Previous passes must
transform calls to primitive operations to $ let x =
; and $ \eta$-expand primitive operations passed as
functions ( e.g. $ let x = f(\+)$ must have been transformed ) .
To keep things simple in this first version , no external functions
is called ( only lambdas defined in the body of the expression , and
primitive operations , can be called ) .
In addition , all data is boxed , allocated using malloc ( and never
freed ; this could be improved by using libgc ) . data would
requires to carry typing information in the CPS terms .
LLVM instructions in SSA form.
The CPS representation stems from the paper "Compiling with
continuations, continued" by Andrew Kennedy. In particular this
representation separates continuations from standard lambda
functions, which allows calling and returning from functions using
the normal stack, and allow close correspondance with the SSA form.
This module assumes that functions have no free variables (or
continuation variables). Closure conversion removes free variables
from functions. Free continuation variables should never happen
when translating normal terms to CPS.
The module also assumes that the CPS values do not refer to
primitive operations, such as +,-,*,/. Previous passes must
transform calls to primitive operations to $let x =
primitive(args)$; and $\eta$-expand primitive operations passed as
functions (e.g. $let x = f(\+)$ must have been transformed).
To keep things simple in this first version, no external functions
is called (only lambdas defined in the body of the expression, and
primitive operations, can be called).
In addition, all data is boxed, allocated using malloc (and never
freed; this could be improved by using libgc). Unboxed data would
requires to carry typing information in the CPS terms. *)
s To get an overview of the translation algorithm , the best is to
understand how the CPS concepts are mapped to the SSA concepts . In
the following , we denote by $ [ x]$ the translation of $ x$.
\begin{itemize }
\item Lambda are translated to functions with one argument and
one return value .
\item Other values ( i.e. int , floats , and tuples ) are all translated
boxed . Thus they all have a single llvm type , which is i8 * .
\item A local CPS variable $ x$ is mapped to a SSA variables ( of type
[ Llvm.llvalue ] ) . CPS variables are introduced as arguments to lambda
and continuations , and in the $ let x = ... $ form . CPS variables and
SSA variables have the same name in their respective printed
representation .
\item A CPS continuation variable $ k$ introduced by $ \lambda k. x. t$
corresponds to the return from the lambda . A call $ k(y)$ to this
continuation with a value $ y$ is translated to a " ret " instruction
returning the translation of $ y$.
\item A CPS continuation variable $ k$ introduced by $ let k(x ) = t_1 ;
t_2 $ is mapped to the SSA basic block $ [ t1]$ ( of type
[ Llvm.basicblock ] ) . The $ x$ formal argument of $ k$ corresponds to a
phi node at the start of $ [ t1]$. A call $ k ( y$ to this continuation
with a value $ y$ is translated to a " jmp " instruction to the basic
block $ [ t1]$ , that binds $ [ y]$ to the phi node at the start of
[ [ t1 ] ] .
\item A call $ f ( k , x)$ of a regular ( non - continuation ) function $ f$
with first argument being a continuation variable argument $ k$ and
second argument being a variable $ v$ is translated to a call to
$ [ f]$ with argument $ [ x]$ , followed by the translation of $ k ( r)$ ,
with $ r$ being the value returned by the call to $ f$. This is because
after calling a function in the LLVM SA , the control is returned to
the following instruction . LLVM optimization passes like simplifycfg
can optimize this if needed . Note : this allows tail call
optimizations
\url{ / docs / CodeGenerator.html#tail - calls } to take
place .
\item Primitive operations , such as $ let x = are translated to the corresponding LLVM operations .
\item A global CPS variables $ x$ is mapped to a SSA variable , but
may have additional indirection . If $ x$ is defined as a
[ Dynamic_value(term ) ] , its size can not be statically computed ; so we
allocate the space for a global variable [ s ] that contains one
pointer , and compile [ term ] as a constructor that stores the
dynamically allocated result of initialization , in [ s ] . Accesses to
[ x ] are transformed to dereferences to [ s ] . A future
" staticalization " transformation will try to maximize the amount of
static values , to avoid this indirection .
\end{itemize }
Note that the SSA representation are well - formed only if " the
definition of a variable \verb|%x| does not dominate all of its uses "
( \url{ / docs / LangRef.html#introduction } ) . The translation
from a CPS term ( without free variables ) ensures that .
understand how the CPS concepts are mapped to the SSA concepts. In
the following, we denote by $[x]$ the translation of $x$.
\begin{itemize}
\item Lambda are translated to LLVM functions with one argument and
one return value.
\item Other values (i.e. int, floats, and tuples) are all translated
boxed. Thus they all have a single llvm type, which is i8 *.
\item A local CPS variable $x$ is mapped to a SSA variables (of type
[Llvm.llvalue]). CPS variables are introduced as arguments to lambda
and continuations, and in the $let x = ... $ form. CPS variables and
SSA variables have the same name in their respective printed
representation.
\item A CPS continuation variable $k$ introduced by $\lambda k. x. t$
corresponds to the return from the lambda. A call $k(y)$ to this
continuation with a value $y$ is translated to a "ret" instruction
returning the translation of $y$.
\item A CPS continuation variable $k$ introduced by $let k(x) = t_1;
t_2$ is mapped to the SSA basic block $[t1]$ (of type
[Llvm.basicblock]). The $x$ formal argument of $k$ corresponds to a
phi node at the start of $[t1]$. A call $k( y$ to this continuation
with a value $y$ is translated to a "jmp" instruction to the basic
block $[t1]$, that binds $[y]$ to the phi node at the start of
[[t1]].
\item A call $f( k, x)$ of a regular (non-continuation) function $f$
with first argument being a continuation variable argument $k$ and
second argument being a variable $v$ is translated to a call to
$[f]$ with argument $[x]$, followed by the translation of $k( r)$,
with $r$ being the value returned by the call to $f$. This is because
after calling a function in the LLVM SA, the control is returned to
the following instruction. LLVM optimization passes like simplifycfg
can optimize this if needed. Note: this allows tail call
optimizations
\url{#tail-calls} to take
place.
\item Primitive operations, such as $let x = primitive(args)$
are translated to the corresponding LLVM operations.
\item A global CPS variables $x$ is mapped to a SSA variable, but
may have additional indirection. If $x$ is defined as a
[Dynamic_value(term)], its size cannot be statically computed; so we
allocate the space for a global variable [s] that contains one
pointer, and compile [term] as a constructor that stores the
dynamically allocated result of initialization, in [s]. Accesses to
[x] are transformed to dereferences to [s]. A future
"staticalization" transformation will try to maximize the amount of
static values, to avoid this indirection.
\end{itemize}
Note that the SSA representation are well-formed only if "the
definition of a variable \verb|%x| does not dominate all of its uses"
(\url{#introduction}). The translation
from a CPS term (without free variables) ensures that. *)
s Here is a simplified example of how the translation from CPS to
SSA works .
The CPS code :
}
let v = 3 ;
let k(x ) = k(2+x ) ;
k(11 ) \end{verbatim }
Is translated to SSA ( ignoring boxing ):
}
entry :
v = 3
n _ = 11
jmp k
k :
x = phi ( entry n _ ) ( k o _ )
m _ = 2
o _ = m _ + x
jmp k }
This shows how $ k$ is translated to a separate basic block , and the
argument $ x$ to a phi node connected to all the uses of $ k$.
SSA works.
The CPS code:
\begin{verbatim}
let v = 3;
let k(x) = k(2+x);
k(11) \end{verbatim}
Is translated to SSA (ignoring boxing):
\begin{verbatim}
entry:
v = 3
n_ = 11
jmp k
k:
x = phi (entry n_) (k o_)
m_ = 2
o_ = m_ + x
jmp k \end{verbatim}
This shows how $k$ is translated to a separate basic block, and the
argument $x$ to a phi node connected to all the uses of $k$.
*)
s If one encounters segmentation faults when changing the LLVM
related code , this may be caused by :
\begin{itemize }
\item Calling [ ] on a value which does not have the
function [ lltype ] , or [ ] with operations that do not
correspond to the lltype of the value .
\item Calling [ build_phi ] with an empty list of " incoming " .
\item Calling [ ExecutionEngine.create the_module ] before calling
[ Llvm_executionengine.initialize_native_target ( ) ] can also .
\end{itemize }
Using valgrind or gdb allows to quickly locate the problematic binding .
related code, this may be caused by:
\begin{itemize}
\item Calling [Llvm.build_call] on a value which does not have the
function [lltype], or [Llvm.build_gep] with operations that do not
correspond to the lltype of the value.
\item Calling [build_phi] with an empty list of "incoming".
\item Calling [ExecutionEngine.create the_module] before calling
[Llvm_executionengine.initialize_native_target()] can also segfault.
\end{itemize}
Using valgrind or gdb allows to quickly locate the problematic Ocaml
Llvm binding.
*)
let context = Llvm.global_context();;
(* We extend the existing, "environment" module. This allows access to
existing variables. *)
let the_module = Llvmenv.the_module;;
let void_type = Llvm.void_type context;;
let i32_type = Llvm.i32_type context;;
let i32star_type = Llvm.pointer_type i32_type;;
let anystar_type = Llvm.pointer_type (Llvm.i8_type context);;
let undef_anystar = Llvm.undef anystar_type;;
let null_anystar = Llvm.const_null anystar_type;;
(* Note: Base will be (in the future) Cps. *)
module Base = Cpsbase;;
module Var_Map = Base.Var.Var.Map;;
module Cont_var_Map = Base.Cont_var.Var.Map;;
open Base;;
(* \subsection*{Creating and accessing memory objects} *)
s These helper functions create or read - from memory object .
Currently compiles using a very simple strategy : every value is
boxed ( including integers and floats ) . This simplifies compilation a
lot : every value we create has type void * , and we cast the type
from void * according to how we use it .
does not ( yet ? ) know how to replace heap allocations with stack
allocations , so we should do that ( using an escape analysis ) . But
LLVM has passes that allow promotion of stack allocations to
register ( " mem2reg " and " scalarrepl " ) , so once this is done ( plus
passing and returning arguments in registers ) , many values should be
unboxed by the compiler ( and this would not be that inefficient ) .
Additional performances could then be obtained by monomorphizing the
code .
Currently LLVM compiles using a very simple strategy: every value is
boxed (including integers and floats). This simplifies compilation a
lot: every value we create has type void *, and we cast the type
from void * according to how we use it.
LLVM does not (yet?) know how to replace heap allocations with stack
allocations, so we should do that (using an escape analysis). But
LLVM has passes that allow promotion of stack allocations to
register ("mem2reg" and "scalarrepl"), so once this is done (plus
passing and returning arguments in registers), many values should be
unboxed by the compiler (and this would not be that inefficient).
Additional performances could then be obtained by monomorphizing the
code. *)
(*s Store [llvalue] in heap-allocated memory. *)
let build_box name llvalue builder =
let lltype = Llvm.type_of llvalue in
let pointer = Llvm.build_malloc lltype (name ^ "_uncasted") builder in
ignore(Llvm.build_store llvalue pointer builder);
Llvm.build_bitcast pointer anystar_type name builder;;
(*s Unbox a [llvalue] of type [lltype]. *)
let build_unbox name llvalue lltype builder =
let typeptr = Llvm.pointer_type lltype in
let castedptr = Llvm.build_bitcast llvalue typeptr (name ^ "_casted") builder in
Llvm.build_load castedptr name builder;;
s A n - tuple is allocated as an array of n [ anystar_type ] . Each
element of the array contains the llvalue in l.
element of the array contains the llvalue in l. *)
let build_tuple name l builder =
let length = List.length l in
let array_type = Llvm.array_type anystar_type length in
let pointer = Llvm.build_malloc array_type (name ^ "_tuple") builder in
let f elem int =
Note : the first 0 is because pointer is not the start of
the array , but a pointer to the start of the array , that
must thus be dereferenced .
the array, but a pointer to the start of the array, that
must thus be dereferenced. *)
let path = [| (Llvm.const_int i32_type 0); (Llvm.const_int i32_type int) |] in
let gep_ptr = Llvm.build_gep pointer path (name ^ "_tuple_" ^ (string_of_int int)) builder in
ignore(Llvm.build_store elem gep_ptr builder) in
List.iter_with_index f l;
Llvm.build_bitcast pointer anystar_type name builder;;
(*s Retrieve an element from a tuple. *)
let build_letproj name pointer i builder =
First we compute an acceptable LLvm type , and cast the pointer to
that type ( failure to do that makes [ ] ) .
As we try to access the ith element , we assume we are accessing
an array of size i+1 .
that type (failure to do that makes [Llvm.build_gep] segfault).
As we try to access the ith element, we assume we are accessing
an array of size i+1. *)
let array_type = Llvm.array_type anystar_type (i+1) in
let arraystar_type = Llvm.pointer_type array_type in
let cast_pointer = Llvm.build_bitcast pointer arraystar_type (name ^ "_casted") builder in
let gep_ptr = Llvm.build_gep cast_pointer [| (Llvm.const_int i32_type 0);
(Llvm.const_int i32_type i) |]
(name ^ "_gep" ^ (string_of_int i)) builder in
let result = Llvm.build_load gep_ptr name builder in
result ;;
(*s Create variants and retrieve elements from a variant. *)
module Variant:sig
open Llvm
val build:string -> llvalue -> llvalue -> llbuilder -> llvalue
val bind: string -> llvalue -> llbuilder -> (llvalue * llvalue)
end = struct
let variant_type = Llvm.struct_type context [| i32_type; anystar_type |];;
let variant_star_type = Llvm.pointer_type variant_type;;
let get_variant_ptrs name ptr builder =
let cast_pointer = Llvm.build_bitcast ptr variant_star_type (name ^ "_casted") builder in
let ptr_to_tag = Llvm.build_gep cast_pointer [| (Llvm.const_int i32_type 0);
(Llvm.const_int i32_type 0) |]
(name ^ "_tag_ptr") builder in
let tag = Llvm.build_load ptr_to_tag (name ^ "_tag") builder in
let ptr_to_value = Llvm.build_gep cast_pointer [| (Llvm.const_int i32_type 0);
(Llvm.const_int i32_type 1) |]
(name ^ "_value_ptr") builder in
(ptr_to_tag,ptr_to_value);;
(*c Note: tag is a i32bit unboxed llvalue. value is a anystar_type llvalue. *)
let build name tag value builder =
let ptr = Llvm.build_malloc variant_type (name ^ "_variant") builder in
let (ptr_to_tag, ptr_to_value) = get_variant_ptrs name ptr builder in
ignore(Llvm.build_store tag ptr_to_tag builder);
ignore(Llvm.build_store value ptr_to_value builder);
Llvm.build_bitcast ptr anystar_type name builder;;
let bind name ptr builder =
let (ptr_to_tag, ptr_to_value) = get_variant_ptrs name ptr builder in
let tag = Llvm.build_load ptr_to_tag (name ^ "_tag") builder in
let value = Llvm.build_load ptr_to_value (name ^ "_value") builder in
(tag,value) ;;
end;;
(*s Create a boolean. For now, boolean are stored as regular variants;
as they have no associated information beside the tag, the
associated value is just undef. *)
let build_boolean name value builder =
let ext_value = Llvm.build_zext_or_bitcast value i32_type (name ^ "_icmp_ext") builder in
Variant.build name ext_value undef_anystar builder;;
(*s Apply primitive operations. *)
let build_integer_binary_op name op a b builder =
let build_fn = match op with
| Constant.Ibop.Add -> Llvm.build_add
| Constant.Ibop.Sub -> Llvm.build_sub
| Constant.Ibop.Mul -> Llvm.build_mul
| Constant.Ibop.Div -> Llvm.build_udiv in
let a_unbox = (build_unbox (name ^ "_a") a i32_type builder) in
let b_unbox = (build_unbox (name ^ "_b") b i32_type builder) in
let res = build_fn a_unbox b_unbox (name ^ "_bop") builder in
build_box name res builder;;
let build_integer_comparison name op a b builder =
let llvm_pred = match op with
| Constant.Ibpred.Eq -> Llvm.Icmp.Eq
| Constant.Ibpred.Ne -> Llvm.Icmp.Ne
| Constant.Ibpred.Ugt -> Llvm.Icmp.Ugt
| Constant.Ibpred.Uge -> Llvm.Icmp.Uge
| Constant.Ibpred.Ult -> Llvm.Icmp.Ult
| Constant.Ibpred.Ule -> Llvm.Icmp.Ule
| Constant.Ibpred.Sgt -> Llvm.Icmp.Sgt
| Constant.Ibpred.Sge -> Llvm.Icmp.Sge
| Constant.Ibpred.Slt -> Llvm.Icmp.Slt
| Constant.Ibpred.Sle -> Llvm.Icmp.Sle in
let a_unbox = (build_unbox (name ^ "_a") a i32_type builder) in
let b_unbox = (build_unbox (name ^ "_b") b i32_type builder) in
let res = Llvm.build_icmp llvm_pred a_unbox b_unbox (name ^ "_icmp") builder in
build_boolean (name ^ "_boolean") res builder;;
(*s Build a call instruction, casting [caller] to a function pointer. *)
let build_call name caller callees builder =
let function_type = Llvm.pointer_type (Llvm.function_type anystar_type [| anystar_type; anystar_type |]) in
let casted_caller = Llvm.build_bitcast caller function_type (name ^ "_function") builder in
let retval = Llvm.build_call casted_caller (Array.of_list callees) (name ^"_result") builder in
retval;;
(* \subsection*{Creating and accessing basic blocks} *)
s This special value is used to ensure , via the type checker , that
compilation to never leaves a basic - block halfly built .
basic blocks should all end with a terminator instruction ; whenever
one is inserted , the function should return [ End_of_block ] . When
building non - terminator instructions , the code must continue
building the basic block .
compilation to LLVM never leaves a basic-block halfly built. LLVM
basic blocks should all end with a terminator instruction; whenever
one is inserted, the function should return [End_of_block]. When
building non-terminator instructions, the code must continue
building the basic block. *)
type termination = End_of_block;;
s This creates a new basic block in the current function .
Note that basic blocks are associated to a parent function ,
that we need to retrieve to create a new basic block .
Note that LLVM basic blocks are associated to a parent function,
that we need to retrieve to create a new basic block. *)
let new_block name builder =
let current_bb = Llvm.insertion_block builder in
let the_function = Llvm.block_parent current_bb in
let new_bb = Llvm.append_block context name the_function in
new_bb;;
s Returns [ Some(phi ) ] if the block already begins with a phi instruction ,
or [ None ] otherwise .
or [None] otherwise. *)
let begin_with_phi_node basic_block =
let pos = Llvm.instr_begin basic_block in
match pos with
| Llvm.At_end(_) -> None
| Llvm.Before(inst) ->
(match Llvm.instr_opcode inst with
| Llvm.Opcode.PHI -> Some(inst)
| _ -> None);;
(*s Create a new block with instructions set by f() in this new block,
and return it; then one can continue building instruction at the
current place. *)
let with_new_block name builder f =
let current_bb = Llvm.insertion_block builder in
let new_bb = new_block name builder in
Llvm.position_at_end new_bb builder;
f();
Llvm.position_at_end current_bb builder;
new_bb
(* Create a new, unreachable block, and return it. *)
let new_unreachable_block builder =
with_new_block "unreachable" builder (fun () -> Llvm.build_unreachable builder);;
(*i XXX: To handle conditional branch in the following, we will use a "condition"
parameter? But this won't end the block anymore. i*)
s This builds a jmp instruction to [ destination_block ] , also passing
the [ v ] value . This is achieved by setting [ v ] as an incoming value
for the phi instruction that begins [ destination_block ] . If
[ destination_block ] does not start with a phi node , then it is the
first time that [ destination_block ] is called , and we create this
phi node .
the [v] value. This is achieved by setting [v] as an incoming value
for the phi instruction that begins [destination_block]. If
[destination_block] does not start with a phi node, then it is the
first time that [destination_block] is called, and we create this
phi node. *)
let build_jmp_to_and_add_incoming destination_block v builder =
let add_incoming_to_block basic_block (value,curblock) =
match begin_with_phi_node basic_block with
| Some(phi) -> Llvm.add_incoming (value,curblock) phi
| None ->
Temporarily create a builder to build the phi instruction .
let builder = Llvm.builder_at context (Llvm.instr_begin basic_block) in
ignore(Llvm.build_phi [value,curblock] "phi" builder) in
let current_basic_block = Llvm.insertion_block builder in
add_incoming_to_block destination_block (v, current_basic_block);
ignore(Llvm.build_br destination_block builder);
End_of_block;;
s We use the following sum type to establish a distinction between :
\begin{itemize }
\item continuation variables bound with lambda : calling them
returns from the function , and the parameter [ x ] of the call [ k ( x ) ]
is returned ;
\item and continuation variables bound with : calling them
jumps to the corresponding basic block , and the parameter [ x ] of
the call [ k ( x ) ] is passed to the phi node starting this basic
block .
\end{itemize }
The CPS$\to{}$LLVM translation maps continuation variables to
[ dest_type]s .
\begin{itemize}
\item continuation variables bound with lambda: calling them
returns from the function, and the parameter [x] of the call [k( x)]
is returned;
\item and continuation variables bound with letcont: calling them
jumps to the corresponding basic block, and the parameter [x] of
the call [k( x)] is passed to the phi node starting this basic
block.
\end{itemize}
The CPS$\to{}$LLVM translation maps continuation variables to
[dest_type]s. *)
type dest_type =
| Ret
| Jmp_to of Llvm.llbasicblock
(* Corresponds to building a call to a continuation [k x], but [k]
and [x] are already translated to their corresponding [dest_type]
and [llvalue]. *)
let build_applycont k x builder =
match k with
| Ret -> ignore(Llvm.build_ret x builder); End_of_block
| Jmp_to(destination) -> build_jmp_to_and_add_incoming destination x builder;;
Some instructions , such as br and switch , takes a label
argument , while the corresponding CPS construct takes a continuation
[ k ] . Even if continuations are translated to a code label , calling a
continuation also requires to pass an argument [ x ] . This function
creates a small basic block that just calls the [ k ] with the
argument [ x ] , to be used by such instructions .
argument, while the corresponding CPS construct takes a continuation
[k]. Even if continuations are translated to a code label, calling a
continuation also requires to pass an argument [x]. This function
creates a small basic block that just calls the [k] with the
argument [x], to be used by such LLVM instructions. *)
i Note : If [ k ] is [ Ret ] , we need to create this block ( or reuse it if
it exists already ) . But if it is a [ Jmp_to ] , we could just return
the basic block , and add an incoming to the phi node corresponding
to the value of [ x ] .
But it is simpler ( and thus done now ) to always create the new
block . i
it exists already). But if it is a [Jmp_to], we could just return
the basic block, and add an incoming to the phi node corresponding
to the value of [x].
But it is simpler (and thus done now) to always create the new
block. i*)
let basic_block_that_calls name k x builder =
with_new_block name builder (fun () ->
build_applycont k x builder);;
\subsection*{Main CPS term translation }
It is important for that function names are unique .
module UniqueFunctionId = Unique.Make(struct end);;
let uniquify_name name = name ^ "_uniq" ^ (UniqueFunctionId.to_string (UniqueFunctionId.fresh()));;
The environment comprehends [ contvarmap ] , a mapping from local
continuation variables to dest_type ; [ globalvarmap ] , a mapping from
the global variables to llvalues ; [ ] , containing a mapping
from both the global and local variables to llvalues ; and
[ handle_halt ] , which explains how [ Halt ] is translated .
continuation variables to dest_type; [globalvarmap], a mapping from
the global variables to llvalues; [varmap], containing a mapping
from both the global and local variables to llvalues; and
[handle_halt], which explains how [Halt] is translated. *)
type env = { contvarmap: dest_type Cont_var_Map.t;
varmap: Llvm.llvalue Var_Map.t;
globalvarmap: Llvm.llvalue Var_Map.t;
handle_halt: handle_halt
}
This type states how a [ Halt(x ) ] CPS term must be translated :
either we return [ x ] , or we ignore [ x ] return nothing , or [ x ] is
stored in some memory region .
either we return [x], or we ignore [x] return nothing, or [x] is
stored in some memory region. *)
and handle_halt =
| Halt_returns_value
| Halt_returns_void
| Halt_stores_results_in of Llvm.llvalue
s This function builds the CPS term [ cps ] , in the current block
pointed to by [ builder ] . [ ] maps CPS variables to . [ contvarmap ] maps CPS continuation variables to values of
type [ contvar_type ] .
All the free variables or continuation variables in [ cps ] must be
in [ contvarmap ] or in [ varmap ] . [ cps ] can contain lambda , but they
must not contain any free variables or free continuation variables
( even the one in [ varmap ] and [ contvarmap ] ) . Closure conversion
deals with this . Note : previously - defined global variables are not
considered free .
pointed to by [builder]. [varmap] maps CPS variables to LLVM
llvalues. [contvarmap] maps CPS continuation variables to values of
type [contvar_type].
All the free variables or continuation variables in [cps] must be
in [contvarmap] or in [varmap]. [cps] can contain lambda, but they
must not contain any free variables or free continuation variables
(even the one in [varmap] and [contvarmap]). Closure conversion
deals with this. Note: previously-defined global variables are not
considered free. *)
let rec build_term cps env builder =
(*s These functions return a llvalue corresponding to the occurrence
of a variable or continuation variable given as an argument. *)
let translate_occurrence x =
let bound_var = Var.Occur.binding_variable x in
let llvalue =
try Var_Map.find bound_var env.varmap
with _ -> failwith ("in translate_var " ^ (Var.Occur.to_string x)) in
match Var.Var.binding_site bound_var with
(* Global dynamic values are allocated with an extra level of
indirection, so we need to unbox them. *)
| Enclosing_definition(Definition(_,Dynamic_value(_))) ->
build_unbox (Var.Occur.to_string x) llvalue anystar_type builder
Note : we could directly return constant integer here . It
seems not worth it , because should be able to deal
with them itself .
seems not worth it, because LLVM should be able to deal
with them itself. *)
| _ -> llvalue
in
let translate_cont_occurrence k =
try Cont_var_Map.find (Cont_var.Occur.binding_variable k) env.contvarmap
with _ -> failwith "in translate_cont_occurrence" in
let add_to_varmap var value = Var_Map.add var value env.varmap in
let add_to_contvarmap contvar block = Cont_var_Map.add contvar (Jmp_to block) env.contvarmap in
s Converting the term is done by inductive decomposition . There are
three kind of cases :
\begin{itemize }
\item those that only build new values ( letvalue , letproj ,
letprimop ... ) in the current basic block
\item those that return a value and end a basic block
( apply , applycont , and halt )
\item the one that build a new basic blocks ( letcont ) .
\end{itemize }
To keep the implementation simple , all values are boxed ( i.e. put
in the heap and accessed through a pointer ) , and of type " i8
* " . Pointer conversions are done according to the use of the
value .
three kind of cases:
\begin{itemize}
\item those that only build new values (letvalue, letproj,
letprimop...) in the current basic block
\item those that return a value and end a basic block
(apply, applycont, and halt)
\item the one that build a new basic blocks (letcont).
\end{itemize}
To keep the implementation simple, all values are boxed (i.e. put
in the heap and accessed through a pointer), and of llvm type "i8
*". Pointer conversions are done according to the use of the
value. *)
match Expression.get cps with
(*s For [Let_prim(x,prim,body)] we just build the new llvalue
corresponding to [prim], map it to [x], then continue building
[body]. *)
| Let_prim(x,prim,body) ->
let xname = (Var.Var.to_string x) in
let result = (match prim with
| Value( Constant(Constant.Integer i)) ->
let llvalue = Llvm.const_int i32_type i in
build_box (xname ^ "_is_const_" ^ string_of_int i) llvalue builder
| Value( Constant(Constant.Float(_) | Constant.String(_))) ->
failwith "Float and strings not yet implemented"
| Value( External( id)) ->
let llvalue = Llvmenv.lookup_global id in
Llvm.build_bitcast llvalue anystar_type ("external_" ^ id) builder
(* For now, any value is a pointer, so we compile void to
pointers; but void values should not be dereferenced, so we
can just use undef as a pointer. *)
| Value( Tuple []) ->
Llvm.undef anystar_type
| Value( Tuple(l)) ->
let llvalues = List.map translate_occurrence l in
build_tuple xname llvalues builder
| Value( Injection( i,_,value)) ->
let llvalue = translate_occurrence value in
Variant.build xname (Llvm.const_int i32_type i) llvalue builder
This build a new function , with private linkage ( since
that it can be used only by the current term ) , which
allows optimizations .
Note that [ build_function ] will use a new builder , so the
lambda can be built in parallel with the current
function . Also it will use new variables and continuation
variable maps ( with only the x parameter ) , so the lambda
expression must not contain any free variables .
that it can be used only by the current term), which
allows llvm optimizations.
Note that [build_function] will use a new builder, so the
lambda can be built in parallel with the current
function. Also it will use new variables and continuation
variable maps (with only the x parameter), so the lambda
expression must not contain any free variables. *)
| Value( Lambda(ft,k,vl,body)) -> assert(ft == No_environment);
let funname = ((Var.Var.to_string x) ^ "fun") in
Declare the function , and add it to the map , so as to
allow recursive use of the function .
TODO : Extend this to any mutually recursive value
( , Tuples , Injections ) . This is an argument for
separating let_prim(x , prim , body ) from
let_values([(x1,value1); ... (xn , ) .
FIXME : The function is build from [ env.globalvarmap ] . This
can cause issues when an inner function recursively calls
the function in which it is defined . It works currently
because the closure conversion algorithm pass the outer
function in the environment , but optimisations will break
that . One solution would be to lift the lamdba to global
scope . Another solution would be to pass the current
, but then will not be able to catch some
errors .
allow recursive use of the function.
TODO: Extend this to any mutually recursive value
(Lamdba, Tuples, Injections). This is an argument for
separating let_prim(x,prim,body) from
let_values([(x1,value1);...(xn,valuen)],body).
FIXME: The function is build from [env.globalvarmap]. This
can cause issues when an inner function recursively calls
the function in which it is defined. It works currently
because the closure conversion algorithm pass the outer
function in the environment, but optimisations will break
that. One solution would be to lift the lamdba to global
scope. Another solution would be to pass the current
varmap, but then cpsllvm will not be able to catch some
errors. *)
let the_function = declare_llvm_function funname (List.length vl) true in
let the_function = Llvm.build_bitcast the_function anystar_type (funname ^ "cast") builder in
let function_build_map = Var_Map.add x the_function env.globalvarmap in
let f = build_function funname k vl body function_build_map in
Llvm.set_linkage Llvm.Linkage.Private f;
Llvm.build_bitcast f anystar_type xname builder
(* Primitive ops are handled here. Notice that we handle the
translation of a call to a primitive operation (e.g.
+(a,b)), and not the use of a primitive as a function (e.g.
let a = +). *)
| Integer_binary_operation(op,xa,xb) ->
build_integer_binary_op xname op (translate_occurrence xa) (translate_occurrence xb) builder
| Integer_binary_predicate(pred,xa,xb) ->
build_integer_comparison xname pred (translate_occurrence xa) (translate_occurrence xb) builder
| Projection(i,x) -> build_letproj xname (translate_occurrence x) i builder
(* Expressions such as $let x = primitive$ should have been
eta-expanded into something like $let x = { (a,b) ->
primitiveop( a,b) }$ in previous compilation stage, so we
fail here. *)
| Value (Constant(c)) -> print_endline (Constant.to_string c);
failwith "ICE: primitive operations as value in LLVM translation."
)
in build_term body {env with varmap=(add_to_varmap x result)} builder
s Building new basic blocks . The algorithm first creates an
empty basic block , bound to [ k ] , then build [ body ] , then build
[ term ] ( if [ k ] is really called ) , binding [ x ] to the phi
node .
empty basic block, bound to [k], then build [body], then build
[term] (if [k] is really called), binding [x] to the phi
node. *)
An unused continuation is translated to a basic block with no
predecessor , which makes complain . So we optimize this
case .
predecessor, which makes LLVM complain. So we optimize this
case. *)
| Let_cont(k,_,_,body) when
Cont_var.Var.number_of_occurrences k == Cont_var.Var.No_occurrence ->
build_term body env builder
The general case . The tricky part is that the bindings do
not allow to create an " empty " phi node ( even if it would , in
future implementations which would not box everything we would
still have to know the type of the phi node , and that
type is not known until we have processed the jumps to that
node ) . So it is the calls to k that create or change the phi
node ; no phi node means [ k ] is never called ( so we do not
bother building it ) .
Doing the operations in this order ensures that calls to [ k ] are
processed before [ k ] is built .
not allow to create an "empty" phi node (even if it would, in
future implementations which would not box everything we would
still have to know the llvm type of the phi node, and that llvm
type is not known until we have processed the jumps to that
node). So it is the calls to k that create or change the phi
node; no phi node means [k] is never called (so we do not
bother building it).
Doing the operations in this order ensures that calls to [k] are
processed before [k] is built. *)
| Let_cont(k,x,term,body) ->
let new_bb = new_block (Cont_var.Var.to_string k) builder in
let newcvm = add_to_contvarmap k new_bb in
let End_of_block = build_term body {env with contvarmap=newcvm} builder in
Llvm.position_at_end new_bb builder;
(match begin_with_phi_node new_bb with
| None -> End_of_block
| Some(phi) -> build_term term {env with contvarmap=newcvm; varmap=add_to_varmap x phi} builder)
(*s Cases that change or create basic blocks. *)
Depending on k , applycont either returns or jumps to
| Apply_cont(k,x) ->
build_applycont (translate_cont_occurrence k) (translate_occurrence x) builder
The CPS semantics state that caller should return to k , but
LLVM SSA does not require that calls end basic blocks . So we
just build a call instruction , and then a call to [ k ] .
optimizations will eliminate the superfluous jump if needed .
LLVM SSA does not require that calls end basic blocks. So we
just build a call instruction, and then a call to [k]. LLVM
optimizations will eliminate the superfluous jump if needed. *)
| Apply(ft,func,k,args) -> assert(ft == No_environment);
let retval = build_call
(Var.Occur.to_string func)
(translate_occurrence func)
(List.map translate_occurrence args) builder in
build_applycont (translate_cont_occurrence k) retval builder
| Case(x,cases,default) ->
begin
let xval = translate_occurrence x in
let cases_nb = CaseMap.cardinal cases in
let default_bb = (match default with
| None -> new_unreachable_block builder
| Some(k) ->
basic_block_that_calls
("bb_" ^ (Cont_var.Occur.to_string k))
(translate_cont_occurrence k) xval builder) in
let (tag,value) = Variant.bind (Var.Occur.to_string x) xval builder in
let switch = Llvm.build_switch tag default_bb cases_nb builder in
CaseMap.iter (fun i k ->
Llvm.add_case switch (Llvm.const_int i32_type i)
(basic_block_that_calls
("bb_" ^ (Cont_var.Occur.to_string k))
(translate_cont_occurrence k) value builder))
cases;
End_of_block
end
| Halt(x) -> (match env.handle_halt with
| Halt_returns_void -> ignore(Llvm.build_ret_void builder)
| Halt_returns_value -> ignore(Llvm.build_ret (translate_occurrence x) builder)
| Halt_stores_results_in(llvalue) ->
Llvm.build_store (translate_occurrence x) llvalue builder;
ignore(Llvm.build_ret_void builder)
); End_of_block
(* Declare a llvm function with name [name], [numparams] parameters.
[returns] if true if the function returns a value, and false if it
returns void. *)
and declare_llvm_function name numparams returns =
match (Llvm.lookup_function name the_module) with
| Some(f) -> f
| None ->
let args_type = Array.make numparams anystar_type in
let ret_type = if returns then anystar_type else void_type in
let function_type = Llvm.function_type ret_type args_type in
let the_function = Llvm.declare_function name function_type the_module in
the_function
s The following function factorizes the creation of a function with
LLVM . It takes the following arguments :
\begin{itemize }
\item [ name ] , a string [ name ] does not need to be unique , just
informative .
\item [ params ] is [ , var ) ] if the function takes
arguments , or None otherwise .
\item ] is the CPS term representing the body of the
function to be translated .
\item [ handle_halt ] states how [ Halt(x ) ] CPS terms must be
translated .
\item [ globalvarmap ] is the mapping from global CPS variables to
llvalues .
\end{itemize }
LLVM. It takes the following arguments:
\begin{itemize}
\item [name], a string [name] does not need to be unique, just
informative.
\item [params] is [Some(cont_var,var)] if the LLvm function takes
arguments, or None otherwise.
\item [cpsbody] is the CPS term representing the body of the
function to be translated.
\item [handle_halt] states how [Halt(x)] CPS terms must be
translated.
\item [globalvarmap] is the mapping from global CPS variables to
llvalues.
\end{itemize}
*)
and created_functions = ((Hashtbl.create 47):(string, unit) Hashtbl.t)
and build_llvm_function name ~params cpsbody handle_halt globalvarmap =
It is important for that function names are unique ; but
names are used by as identifiers , so we can not uniquify them
here ; [ name ] must already be uniquifed by the caller . The
hashtable allows to check that : a name is in the hashtable iff
a function with the same name has been built .
names are used by LLVM as identifiers, so we cannot uniquify them
here; [name] must already be uniquifed by the caller. The
hashtable allows to check that: a name is in the hashtable iff
a function with the same name has been built. *)
if Hashtbl.mem created_functions name
then failwith ("Calling build_llvm_function twice with name `" ^ name ^"'")
else Hashtbl.add created_functions name ();
let numparams = match params with
| Some(_,l) -> (List.length l)
| None -> 0 in
let returns = match handle_halt with
| Halt_returns_value -> true
| Halt_stores_results_in _ | Halt_returns_void -> false in
let the_function = declare_llvm_function name numparams returns in
(* Compute the initial environment; this requires that [the_function] is created. *)
let (initial_contvarmap, initial_varmap) = match params with
| Some(k,l) -> (Cont_var_Map.singleton k Ret,
List.fold_left_with_index (fun map x i ->
Var_Map.add x (Llvm.param the_function i) map)
globalvarmap l)
| None -> (Cont_var_Map.empty, globalvarmap) in
let initial_env = { contvarmap = initial_contvarmap;
varmap = initial_varmap;
globalvarmap = globalvarmap;
handle_halt = handle_halt
} in
(* Build the function. *)
let bb = Llvm.append_block context "entry" the_function in
(* Note that we use a new builder. If OCaml supported SMP, functions
could even be built in parallel. *)
let builder = Llvm.builder context in
Llvm.position_at_end bb builder;
try
ignore(build_term cpsbody initial_env builder);
(* Prints the textual representation of the function to stderr. *)
if Log.Llvm_output.is_output Log.Debug
then Llvm.dump_value the_function
else ();
Validate the code we just generated .
Llvm_analysis.assert_valid_function the_function;
the_function
(* Normally, no exception should be thrown, be we never know. *)
with e -> Llvm.delete_function the_function; raise e
(* A function takes parameters and returns a result with "return". *)
and build_function name contparam params cpsbody globalvarmap =
build_llvm_function name ~params:(Some(contparam,params)) cpsbody Halt_returns_value globalvarmap
;;
(* Build a thunk that executes an expression when called. *)
let build_unbound_def cpsbody globalvarmap =
build_llvm_function (uniquify_name "nodef") ~params:None cpsbody Halt_returns_void globalvarmap;;
(* A definition is a global variable, plus a constructor function that
stores a value in it. The constructor is also a thunk, that stores a
result in the global variable when called.*)
let build_bound_def var cpsbody globalvarmap =
let varname = Var.Var.to_string var in
let funname = ("construct_" ^ varname) in
let the_variable = Llvm.define_global varname undef_anystar the_module in
let the_function =
build_llvm_function funname ~params:None cpsbody (Halt_stores_results_in the_variable) globalvarmap in
(the_variable, the_function)
;;
(* Build a toplevel definition. *)
let build_definition def globalvarmap =
let (Definition(visib,Dynamic_value(expr))) = def in
match visib with
(* The result of the expression is meaningful, and bound to a variable. *)
| Public(var) | Private(var) ->
let (the_variable, the_function) = build_bound_def var expr globalvarmap in
let newmap = Var_Map.add var the_variable globalvarmap in
(the_function, newmap)
(* We do not care about the result of the expression. *)
| Unused ->
let the_function = build_unbound_def expr globalvarmap in
(the_function, globalvarmap)
;;
module Stream = Extensions.Stream;;
let from_stream cps_stream =
let f state cps =
let (llvmdef, new_state) = build_definition cps state in
[llvmdef], new_state in
Stream.transformer f Base.Var.Var.Map.empty cps_stream ;;
| null | https://raw.githubusercontent.com/mlemerre/l-lang/88201e861c6cc30bb3b9510d7f55c681eded4085/src/llvm/cpsllvm.ml | ocaml | We extend the existing, "environment" module. This allows access to
existing variables.
Note: Base will be (in the future) Cps.
\subsection*{Creating and accessing memory objects}
s Store [llvalue] in heap-allocated memory.
s Unbox a [llvalue] of type [lltype].
s Retrieve an element from a tuple.
s Create variants and retrieve elements from a variant.
c Note: tag is a i32bit unboxed llvalue. value is a anystar_type llvalue.
s Create a boolean. For now, boolean are stored as regular variants;
as they have no associated information beside the tag, the
associated value is just undef.
s Apply primitive operations.
s Build a call instruction, casting [caller] to a function pointer.
\subsection*{Creating and accessing basic blocks}
s Create a new block with instructions set by f() in this new block,
and return it; then one can continue building instruction at the
current place.
Create a new, unreachable block, and return it.
i XXX: To handle conditional branch in the following, we will use a "condition"
parameter? But this won't end the block anymore. i
Corresponds to building a call to a continuation [k x], but [k]
and [x] are already translated to their corresponding [dest_type]
and [llvalue].
s These functions return a llvalue corresponding to the occurrence
of a variable or continuation variable given as an argument.
Global dynamic values are allocated with an extra level of
indirection, so we need to unbox them.
s For [Let_prim(x,prim,body)] we just build the new llvalue
corresponding to [prim], map it to [x], then continue building
[body].
For now, any value is a pointer, so we compile void to
pointers; but void values should not be dereferenced, so we
can just use undef as a pointer.
Primitive ops are handled here. Notice that we handle the
translation of a call to a primitive operation (e.g.
+(a,b)), and not the use of a primitive as a function (e.g.
let a = +).
Expressions such as $let x = primitive$ should have been
eta-expanded into something like $let x = { (a,b) ->
primitiveop( a,b) }$ in previous compilation stage, so we
fail here.
s Cases that change or create basic blocks.
Declare a llvm function with name [name], [numparams] parameters.
[returns] if true if the function returns a value, and false if it
returns void.
Compute the initial environment; this requires that [the_function] is created.
Build the function.
Note that we use a new builder. If OCaml supported SMP, functions
could even be built in parallel.
Prints the textual representation of the function to stderr.
Normally, no exception should be thrown, be we never know.
A function takes parameters and returns a result with "return".
Build a thunk that executes an expression when called.
A definition is a global variable, plus a constructor function that
stores a value in it. The constructor is also a thunk, that stores a
result in the global variable when called.
Build a toplevel definition.
The result of the expression is meaningful, and bound to a variable.
We do not care about the result of the expression. | Copyright 2012 - 2013 .
For List.fold_left_with_index .
i \section{Module } i
s This module translates a term written in CPS representation to
LLVM instructions in SSA form .
The CPS representation stems from the paper " Compiling with
continuations , continued " by . In particular this
representation separates continuations from standard lambda
functions , which allows calling and returning from functions using
the normal stack , and allow close correspondance with the SSA form .
This module assumes that functions have no free variables ( or
continuation variables ) . Closure conversion removes free variables
from functions . Free continuation variables should never happen
when translating normal terms to CPS .
The module also assumes that the CPS values do not refer to
primitive operations , such as + , -,*,/. Previous passes must
transform calls to primitive operations to $ let x =
; and $ \eta$-expand primitive operations passed as
functions ( e.g. $ let x = f(\+)$ must have been transformed ) .
To keep things simple in this first version , no external functions
is called ( only lambdas defined in the body of the expression , and
primitive operations , can be called ) .
In addition , all data is boxed , allocated using malloc ( and never
freed ; this could be improved by using libgc ) . data would
requires to carry typing information in the CPS terms .
LLVM instructions in SSA form.
The CPS representation stems from the paper "Compiling with
continuations, continued" by Andrew Kennedy. In particular this
representation separates continuations from standard lambda
functions, which allows calling and returning from functions using
the normal stack, and allow close correspondance with the SSA form.
This module assumes that functions have no free variables (or
continuation variables). Closure conversion removes free variables
from functions. Free continuation variables should never happen
when translating normal terms to CPS.
The module also assumes that the CPS values do not refer to
primitive operations, such as +,-,*,/. Previous passes must
transform calls to primitive operations to $let x =
primitive(args)$; and $\eta$-expand primitive operations passed as
functions (e.g. $let x = f(\+)$ must have been transformed).
To keep things simple in this first version, no external functions
is called (only lambdas defined in the body of the expression, and
primitive operations, can be called).
In addition, all data is boxed, allocated using malloc (and never
freed; this could be improved by using libgc). Unboxed data would
requires to carry typing information in the CPS terms. *)
s To get an overview of the translation algorithm , the best is to
understand how the CPS concepts are mapped to the SSA concepts . In
the following , we denote by $ [ x]$ the translation of $ x$.
\begin{itemize }
\item Lambda are translated to functions with one argument and
one return value .
\item Other values ( i.e. int , floats , and tuples ) are all translated
boxed . Thus they all have a single llvm type , which is i8 * .
\item A local CPS variable $ x$ is mapped to a SSA variables ( of type
[ Llvm.llvalue ] ) . CPS variables are introduced as arguments to lambda
and continuations , and in the $ let x = ... $ form . CPS variables and
SSA variables have the same name in their respective printed
representation .
\item A CPS continuation variable $ k$ introduced by $ \lambda k. x. t$
corresponds to the return from the lambda . A call $ k(y)$ to this
continuation with a value $ y$ is translated to a " ret " instruction
returning the translation of $ y$.
\item A CPS continuation variable $ k$ introduced by $ let k(x ) = t_1 ;
t_2 $ is mapped to the SSA basic block $ [ t1]$ ( of type
[ Llvm.basicblock ] ) . The $ x$ formal argument of $ k$ corresponds to a
phi node at the start of $ [ t1]$. A call $ k ( y$ to this continuation
with a value $ y$ is translated to a " jmp " instruction to the basic
block $ [ t1]$ , that binds $ [ y]$ to the phi node at the start of
[ [ t1 ] ] .
\item A call $ f ( k , x)$ of a regular ( non - continuation ) function $ f$
with first argument being a continuation variable argument $ k$ and
second argument being a variable $ v$ is translated to a call to
$ [ f]$ with argument $ [ x]$ , followed by the translation of $ k ( r)$ ,
with $ r$ being the value returned by the call to $ f$. This is because
after calling a function in the LLVM SA , the control is returned to
the following instruction . LLVM optimization passes like simplifycfg
can optimize this if needed . Note : this allows tail call
optimizations
\url{ / docs / CodeGenerator.html#tail - calls } to take
place .
\item Primitive operations , such as $ let x = are translated to the corresponding LLVM operations .
\item A global CPS variables $ x$ is mapped to a SSA variable , but
may have additional indirection . If $ x$ is defined as a
[ Dynamic_value(term ) ] , its size can not be statically computed ; so we
allocate the space for a global variable [ s ] that contains one
pointer , and compile [ term ] as a constructor that stores the
dynamically allocated result of initialization , in [ s ] . Accesses to
[ x ] are transformed to dereferences to [ s ] . A future
" staticalization " transformation will try to maximize the amount of
static values , to avoid this indirection .
\end{itemize }
Note that the SSA representation are well - formed only if " the
definition of a variable \verb|%x| does not dominate all of its uses "
( \url{ / docs / LangRef.html#introduction } ) . The translation
from a CPS term ( without free variables ) ensures that .
understand how the CPS concepts are mapped to the SSA concepts. In
the following, we denote by $[x]$ the translation of $x$.
\begin{itemize}
\item Lambda are translated to LLVM functions with one argument and
one return value.
\item Other values (i.e. int, floats, and tuples) are all translated
boxed. Thus they all have a single llvm type, which is i8 *.
\item A local CPS variable $x$ is mapped to a SSA variables (of type
[Llvm.llvalue]). CPS variables are introduced as arguments to lambda
and continuations, and in the $let x = ... $ form. CPS variables and
SSA variables have the same name in their respective printed
representation.
\item A CPS continuation variable $k$ introduced by $\lambda k. x. t$
corresponds to the return from the lambda. A call $k(y)$ to this
continuation with a value $y$ is translated to a "ret" instruction
returning the translation of $y$.
\item A CPS continuation variable $k$ introduced by $let k(x) = t_1;
t_2$ is mapped to the SSA basic block $[t1]$ (of type
[Llvm.basicblock]). The $x$ formal argument of $k$ corresponds to a
phi node at the start of $[t1]$. A call $k( y$ to this continuation
with a value $y$ is translated to a "jmp" instruction to the basic
block $[t1]$, that binds $[y]$ to the phi node at the start of
[[t1]].
\item A call $f( k, x)$ of a regular (non-continuation) function $f$
with first argument being a continuation variable argument $k$ and
second argument being a variable $v$ is translated to a call to
$[f]$ with argument $[x]$, followed by the translation of $k( r)$,
with $r$ being the value returned by the call to $f$. This is because
after calling a function in the LLVM SA, the control is returned to
the following instruction. LLVM optimization passes like simplifycfg
can optimize this if needed. Note: this allows tail call
optimizations
\url{#tail-calls} to take
place.
\item Primitive operations, such as $let x = primitive(args)$
are translated to the corresponding LLVM operations.
\item A global CPS variables $x$ is mapped to a SSA variable, but
may have additional indirection. If $x$ is defined as a
[Dynamic_value(term)], its size cannot be statically computed; so we
allocate the space for a global variable [s] that contains one
pointer, and compile [term] as a constructor that stores the
dynamically allocated result of initialization, in [s]. Accesses to
[x] are transformed to dereferences to [s]. A future
"staticalization" transformation will try to maximize the amount of
static values, to avoid this indirection.
\end{itemize}
Note that the SSA representation are well-formed only if "the
definition of a variable \verb|%x| does not dominate all of its uses"
(\url{#introduction}). The translation
from a CPS term (without free variables) ensures that. *)
s Here is a simplified example of how the translation from CPS to
SSA works .
The CPS code :
}
let v = 3 ;
let k(x ) = k(2+x ) ;
k(11 ) \end{verbatim }
Is translated to SSA ( ignoring boxing ):
}
entry :
v = 3
n _ = 11
jmp k
k :
x = phi ( entry n _ ) ( k o _ )
m _ = 2
o _ = m _ + x
jmp k }
This shows how $ k$ is translated to a separate basic block , and the
argument $ x$ to a phi node connected to all the uses of $ k$.
SSA works.
The CPS code:
\begin{verbatim}
let v = 3;
let k(x) = k(2+x);
k(11) \end{verbatim}
Is translated to SSA (ignoring boxing):
\begin{verbatim}
entry:
v = 3
n_ = 11
jmp k
k:
x = phi (entry n_) (k o_)
m_ = 2
o_ = m_ + x
jmp k \end{verbatim}
This shows how $k$ is translated to a separate basic block, and the
argument $x$ to a phi node connected to all the uses of $k$.
*)
s If one encounters segmentation faults when changing the LLVM
related code , this may be caused by :
\begin{itemize }
\item Calling [ ] on a value which does not have the
function [ lltype ] , or [ ] with operations that do not
correspond to the lltype of the value .
\item Calling [ build_phi ] with an empty list of " incoming " .
\item Calling [ ExecutionEngine.create the_module ] before calling
[ Llvm_executionengine.initialize_native_target ( ) ] can also .
\end{itemize }
Using valgrind or gdb allows to quickly locate the problematic binding .
related code, this may be caused by:
\begin{itemize}
\item Calling [Llvm.build_call] on a value which does not have the
function [lltype], or [Llvm.build_gep] with operations that do not
correspond to the lltype of the value.
\item Calling [build_phi] with an empty list of "incoming".
\item Calling [ExecutionEngine.create the_module] before calling
[Llvm_executionengine.initialize_native_target()] can also segfault.
\end{itemize}
Using valgrind or gdb allows to quickly locate the problematic Ocaml
Llvm binding.
*)
let context = Llvm.global_context();;
let the_module = Llvmenv.the_module;;
let void_type = Llvm.void_type context;;
let i32_type = Llvm.i32_type context;;
let i32star_type = Llvm.pointer_type i32_type;;
let anystar_type = Llvm.pointer_type (Llvm.i8_type context);;
let undef_anystar = Llvm.undef anystar_type;;
let null_anystar = Llvm.const_null anystar_type;;
module Base = Cpsbase;;
module Var_Map = Base.Var.Var.Map;;
module Cont_var_Map = Base.Cont_var.Var.Map;;
open Base;;
s These helper functions create or read - from memory object .
Currently compiles using a very simple strategy : every value is
boxed ( including integers and floats ) . This simplifies compilation a
lot : every value we create has type void * , and we cast the type
from void * according to how we use it .
does not ( yet ? ) know how to replace heap allocations with stack
allocations , so we should do that ( using an escape analysis ) . But
LLVM has passes that allow promotion of stack allocations to
register ( " mem2reg " and " scalarrepl " ) , so once this is done ( plus
passing and returning arguments in registers ) , many values should be
unboxed by the compiler ( and this would not be that inefficient ) .
Additional performances could then be obtained by monomorphizing the
code .
Currently LLVM compiles using a very simple strategy: every value is
boxed (including integers and floats). This simplifies compilation a
lot: every value we create has type void *, and we cast the type
from void * according to how we use it.
LLVM does not (yet?) know how to replace heap allocations with stack
allocations, so we should do that (using an escape analysis). But
LLVM has passes that allow promotion of stack allocations to
register ("mem2reg" and "scalarrepl"), so once this is done (plus
passing and returning arguments in registers), many values should be
unboxed by the compiler (and this would not be that inefficient).
Additional performances could then be obtained by monomorphizing the
code. *)
let build_box name llvalue builder =
let lltype = Llvm.type_of llvalue in
let pointer = Llvm.build_malloc lltype (name ^ "_uncasted") builder in
ignore(Llvm.build_store llvalue pointer builder);
Llvm.build_bitcast pointer anystar_type name builder;;
let build_unbox name llvalue lltype builder =
let typeptr = Llvm.pointer_type lltype in
let castedptr = Llvm.build_bitcast llvalue typeptr (name ^ "_casted") builder in
Llvm.build_load castedptr name builder;;
s A n - tuple is allocated as an array of n [ anystar_type ] . Each
element of the array contains the llvalue in l.
element of the array contains the llvalue in l. *)
let build_tuple name l builder =
let length = List.length l in
let array_type = Llvm.array_type anystar_type length in
let pointer = Llvm.build_malloc array_type (name ^ "_tuple") builder in
let f elem int =
Note : the first 0 is because pointer is not the start of
the array , but a pointer to the start of the array , that
must thus be dereferenced .
the array, but a pointer to the start of the array, that
must thus be dereferenced. *)
let path = [| (Llvm.const_int i32_type 0); (Llvm.const_int i32_type int) |] in
let gep_ptr = Llvm.build_gep pointer path (name ^ "_tuple_" ^ (string_of_int int)) builder in
ignore(Llvm.build_store elem gep_ptr builder) in
List.iter_with_index f l;
Llvm.build_bitcast pointer anystar_type name builder;;
let build_letproj name pointer i builder =
First we compute an acceptable LLvm type , and cast the pointer to
that type ( failure to do that makes [ ] ) .
As we try to access the ith element , we assume we are accessing
an array of size i+1 .
that type (failure to do that makes [Llvm.build_gep] segfault).
As we try to access the ith element, we assume we are accessing
an array of size i+1. *)
let array_type = Llvm.array_type anystar_type (i+1) in
let arraystar_type = Llvm.pointer_type array_type in
let cast_pointer = Llvm.build_bitcast pointer arraystar_type (name ^ "_casted") builder in
let gep_ptr = Llvm.build_gep cast_pointer [| (Llvm.const_int i32_type 0);
(Llvm.const_int i32_type i) |]
(name ^ "_gep" ^ (string_of_int i)) builder in
let result = Llvm.build_load gep_ptr name builder in
result ;;
module Variant:sig
open Llvm
val build:string -> llvalue -> llvalue -> llbuilder -> llvalue
val bind: string -> llvalue -> llbuilder -> (llvalue * llvalue)
end = struct
let variant_type = Llvm.struct_type context [| i32_type; anystar_type |];;
let variant_star_type = Llvm.pointer_type variant_type;;
let get_variant_ptrs name ptr builder =
let cast_pointer = Llvm.build_bitcast ptr variant_star_type (name ^ "_casted") builder in
let ptr_to_tag = Llvm.build_gep cast_pointer [| (Llvm.const_int i32_type 0);
(Llvm.const_int i32_type 0) |]
(name ^ "_tag_ptr") builder in
let tag = Llvm.build_load ptr_to_tag (name ^ "_tag") builder in
let ptr_to_value = Llvm.build_gep cast_pointer [| (Llvm.const_int i32_type 0);
(Llvm.const_int i32_type 1) |]
(name ^ "_value_ptr") builder in
(ptr_to_tag,ptr_to_value);;
let build name tag value builder =
let ptr = Llvm.build_malloc variant_type (name ^ "_variant") builder in
let (ptr_to_tag, ptr_to_value) = get_variant_ptrs name ptr builder in
ignore(Llvm.build_store tag ptr_to_tag builder);
ignore(Llvm.build_store value ptr_to_value builder);
Llvm.build_bitcast ptr anystar_type name builder;;
let bind name ptr builder =
let (ptr_to_tag, ptr_to_value) = get_variant_ptrs name ptr builder in
let tag = Llvm.build_load ptr_to_tag (name ^ "_tag") builder in
let value = Llvm.build_load ptr_to_value (name ^ "_value") builder in
(tag,value) ;;
end;;
let build_boolean name value builder =
let ext_value = Llvm.build_zext_or_bitcast value i32_type (name ^ "_icmp_ext") builder in
Variant.build name ext_value undef_anystar builder;;
let build_integer_binary_op name op a b builder =
let build_fn = match op with
| Constant.Ibop.Add -> Llvm.build_add
| Constant.Ibop.Sub -> Llvm.build_sub
| Constant.Ibop.Mul -> Llvm.build_mul
| Constant.Ibop.Div -> Llvm.build_udiv in
let a_unbox = (build_unbox (name ^ "_a") a i32_type builder) in
let b_unbox = (build_unbox (name ^ "_b") b i32_type builder) in
let res = build_fn a_unbox b_unbox (name ^ "_bop") builder in
build_box name res builder;;
let build_integer_comparison name op a b builder =
let llvm_pred = match op with
| Constant.Ibpred.Eq -> Llvm.Icmp.Eq
| Constant.Ibpred.Ne -> Llvm.Icmp.Ne
| Constant.Ibpred.Ugt -> Llvm.Icmp.Ugt
| Constant.Ibpred.Uge -> Llvm.Icmp.Uge
| Constant.Ibpred.Ult -> Llvm.Icmp.Ult
| Constant.Ibpred.Ule -> Llvm.Icmp.Ule
| Constant.Ibpred.Sgt -> Llvm.Icmp.Sgt
| Constant.Ibpred.Sge -> Llvm.Icmp.Sge
| Constant.Ibpred.Slt -> Llvm.Icmp.Slt
| Constant.Ibpred.Sle -> Llvm.Icmp.Sle in
let a_unbox = (build_unbox (name ^ "_a") a i32_type builder) in
let b_unbox = (build_unbox (name ^ "_b") b i32_type builder) in
let res = Llvm.build_icmp llvm_pred a_unbox b_unbox (name ^ "_icmp") builder in
build_boolean (name ^ "_boolean") res builder;;
let build_call name caller callees builder =
let function_type = Llvm.pointer_type (Llvm.function_type anystar_type [| anystar_type; anystar_type |]) in
let casted_caller = Llvm.build_bitcast caller function_type (name ^ "_function") builder in
let retval = Llvm.build_call casted_caller (Array.of_list callees) (name ^"_result") builder in
retval;;
s This special value is used to ensure , via the type checker , that
compilation to never leaves a basic - block halfly built .
basic blocks should all end with a terminator instruction ; whenever
one is inserted , the function should return [ End_of_block ] . When
building non - terminator instructions , the code must continue
building the basic block .
compilation to LLVM never leaves a basic-block halfly built. LLVM
basic blocks should all end with a terminator instruction; whenever
one is inserted, the function should return [End_of_block]. When
building non-terminator instructions, the code must continue
building the basic block. *)
type termination = End_of_block;;
s This creates a new basic block in the current function .
Note that basic blocks are associated to a parent function ,
that we need to retrieve to create a new basic block .
Note that LLVM basic blocks are associated to a parent function,
that we need to retrieve to create a new basic block. *)
let new_block name builder =
let current_bb = Llvm.insertion_block builder in
let the_function = Llvm.block_parent current_bb in
let new_bb = Llvm.append_block context name the_function in
new_bb;;
s Returns [ Some(phi ) ] if the block already begins with a phi instruction ,
or [ None ] otherwise .
or [None] otherwise. *)
let begin_with_phi_node basic_block =
let pos = Llvm.instr_begin basic_block in
match pos with
| Llvm.At_end(_) -> None
| Llvm.Before(inst) ->
(match Llvm.instr_opcode inst with
| Llvm.Opcode.PHI -> Some(inst)
| _ -> None);;
let with_new_block name builder f =
let current_bb = Llvm.insertion_block builder in
let new_bb = new_block name builder in
Llvm.position_at_end new_bb builder;
f();
Llvm.position_at_end current_bb builder;
new_bb
let new_unreachable_block builder =
with_new_block "unreachable" builder (fun () -> Llvm.build_unreachable builder);;
s This builds a jmp instruction to [ destination_block ] , also passing
the [ v ] value . This is achieved by setting [ v ] as an incoming value
for the phi instruction that begins [ destination_block ] . If
[ destination_block ] does not start with a phi node , then it is the
first time that [ destination_block ] is called , and we create this
phi node .
the [v] value. This is achieved by setting [v] as an incoming value
for the phi instruction that begins [destination_block]. If
[destination_block] does not start with a phi node, then it is the
first time that [destination_block] is called, and we create this
phi node. *)
let build_jmp_to_and_add_incoming destination_block v builder =
let add_incoming_to_block basic_block (value,curblock) =
match begin_with_phi_node basic_block with
| Some(phi) -> Llvm.add_incoming (value,curblock) phi
| None ->
Temporarily create a builder to build the phi instruction .
let builder = Llvm.builder_at context (Llvm.instr_begin basic_block) in
ignore(Llvm.build_phi [value,curblock] "phi" builder) in
let current_basic_block = Llvm.insertion_block builder in
add_incoming_to_block destination_block (v, current_basic_block);
ignore(Llvm.build_br destination_block builder);
End_of_block;;
s We use the following sum type to establish a distinction between :
\begin{itemize }
\item continuation variables bound with lambda : calling them
returns from the function , and the parameter [ x ] of the call [ k ( x ) ]
is returned ;
\item and continuation variables bound with : calling them
jumps to the corresponding basic block , and the parameter [ x ] of
the call [ k ( x ) ] is passed to the phi node starting this basic
block .
\end{itemize }
The CPS$\to{}$LLVM translation maps continuation variables to
[ dest_type]s .
\begin{itemize}
\item continuation variables bound with lambda: calling them
returns from the function, and the parameter [x] of the call [k( x)]
is returned;
\item and continuation variables bound with letcont: calling them
jumps to the corresponding basic block, and the parameter [x] of
the call [k( x)] is passed to the phi node starting this basic
block.
\end{itemize}
The CPS$\to{}$LLVM translation maps continuation variables to
[dest_type]s. *)
type dest_type =
| Ret
| Jmp_to of Llvm.llbasicblock
let build_applycont k x builder =
match k with
| Ret -> ignore(Llvm.build_ret x builder); End_of_block
| Jmp_to(destination) -> build_jmp_to_and_add_incoming destination x builder;;
Some instructions , such as br and switch , takes a label
argument , while the corresponding CPS construct takes a continuation
[ k ] . Even if continuations are translated to a code label , calling a
continuation also requires to pass an argument [ x ] . This function
creates a small basic block that just calls the [ k ] with the
argument [ x ] , to be used by such instructions .
argument, while the corresponding CPS construct takes a continuation
[k]. Even if continuations are translated to a code label, calling a
continuation also requires to pass an argument [x]. This function
creates a small basic block that just calls the [k] with the
argument [x], to be used by such LLVM instructions. *)
i Note : If [ k ] is [ Ret ] , we need to create this block ( or reuse it if
it exists already ) . But if it is a [ Jmp_to ] , we could just return
the basic block , and add an incoming to the phi node corresponding
to the value of [ x ] .
But it is simpler ( and thus done now ) to always create the new
block . i
it exists already). But if it is a [Jmp_to], we could just return
the basic block, and add an incoming to the phi node corresponding
to the value of [x].
But it is simpler (and thus done now) to always create the new
block. i*)
let basic_block_that_calls name k x builder =
with_new_block name builder (fun () ->
build_applycont k x builder);;
\subsection*{Main CPS term translation }
It is important for that function names are unique .
module UniqueFunctionId = Unique.Make(struct end);;
let uniquify_name name = name ^ "_uniq" ^ (UniqueFunctionId.to_string (UniqueFunctionId.fresh()));;
The environment comprehends [ contvarmap ] , a mapping from local
continuation variables to dest_type ; [ globalvarmap ] , a mapping from
the global variables to llvalues ; [ ] , containing a mapping
from both the global and local variables to llvalues ; and
[ handle_halt ] , which explains how [ Halt ] is translated .
continuation variables to dest_type; [globalvarmap], a mapping from
the global variables to llvalues; [varmap], containing a mapping
from both the global and local variables to llvalues; and
[handle_halt], which explains how [Halt] is translated. *)
type env = { contvarmap: dest_type Cont_var_Map.t;
varmap: Llvm.llvalue Var_Map.t;
globalvarmap: Llvm.llvalue Var_Map.t;
handle_halt: handle_halt
}
This type states how a [ Halt(x ) ] CPS term must be translated :
either we return [ x ] , or we ignore [ x ] return nothing , or [ x ] is
stored in some memory region .
either we return [x], or we ignore [x] return nothing, or [x] is
stored in some memory region. *)
and handle_halt =
| Halt_returns_value
| Halt_returns_void
| Halt_stores_results_in of Llvm.llvalue
s This function builds the CPS term [ cps ] , in the current block
pointed to by [ builder ] . [ ] maps CPS variables to . [ contvarmap ] maps CPS continuation variables to values of
type [ contvar_type ] .
All the free variables or continuation variables in [ cps ] must be
in [ contvarmap ] or in [ varmap ] . [ cps ] can contain lambda , but they
must not contain any free variables or free continuation variables
( even the one in [ varmap ] and [ contvarmap ] ) . Closure conversion
deals with this . Note : previously - defined global variables are not
considered free .
pointed to by [builder]. [varmap] maps CPS variables to LLVM
llvalues. [contvarmap] maps CPS continuation variables to values of
type [contvar_type].
All the free variables or continuation variables in [cps] must be
in [contvarmap] or in [varmap]. [cps] can contain lambda, but they
must not contain any free variables or free continuation variables
(even the one in [varmap] and [contvarmap]). Closure conversion
deals with this. Note: previously-defined global variables are not
considered free. *)
let rec build_term cps env builder =
let translate_occurrence x =
let bound_var = Var.Occur.binding_variable x in
let llvalue =
try Var_Map.find bound_var env.varmap
with _ -> failwith ("in translate_var " ^ (Var.Occur.to_string x)) in
match Var.Var.binding_site bound_var with
| Enclosing_definition(Definition(_,Dynamic_value(_))) ->
build_unbox (Var.Occur.to_string x) llvalue anystar_type builder
Note : we could directly return constant integer here . It
seems not worth it , because should be able to deal
with them itself .
seems not worth it, because LLVM should be able to deal
with them itself. *)
| _ -> llvalue
in
let translate_cont_occurrence k =
try Cont_var_Map.find (Cont_var.Occur.binding_variable k) env.contvarmap
with _ -> failwith "in translate_cont_occurrence" in
let add_to_varmap var value = Var_Map.add var value env.varmap in
let add_to_contvarmap contvar block = Cont_var_Map.add contvar (Jmp_to block) env.contvarmap in
s Converting the term is done by inductive decomposition . There are
three kind of cases :
\begin{itemize }
\item those that only build new values ( letvalue , letproj ,
letprimop ... ) in the current basic block
\item those that return a value and end a basic block
( apply , applycont , and halt )
\item the one that build a new basic blocks ( letcont ) .
\end{itemize }
To keep the implementation simple , all values are boxed ( i.e. put
in the heap and accessed through a pointer ) , and of type " i8
* " . Pointer conversions are done according to the use of the
value .
three kind of cases:
\begin{itemize}
\item those that only build new values (letvalue, letproj,
letprimop...) in the current basic block
\item those that return a value and end a basic block
(apply, applycont, and halt)
\item the one that build a new basic blocks (letcont).
\end{itemize}
To keep the implementation simple, all values are boxed (i.e. put
in the heap and accessed through a pointer), and of llvm type "i8
*". Pointer conversions are done according to the use of the
value. *)
match Expression.get cps with
| Let_prim(x,prim,body) ->
let xname = (Var.Var.to_string x) in
let result = (match prim with
| Value( Constant(Constant.Integer i)) ->
let llvalue = Llvm.const_int i32_type i in
build_box (xname ^ "_is_const_" ^ string_of_int i) llvalue builder
| Value( Constant(Constant.Float(_) | Constant.String(_))) ->
failwith "Float and strings not yet implemented"
| Value( External( id)) ->
let llvalue = Llvmenv.lookup_global id in
Llvm.build_bitcast llvalue anystar_type ("external_" ^ id) builder
| Value( Tuple []) ->
Llvm.undef anystar_type
| Value( Tuple(l)) ->
let llvalues = List.map translate_occurrence l in
build_tuple xname llvalues builder
| Value( Injection( i,_,value)) ->
let llvalue = translate_occurrence value in
Variant.build xname (Llvm.const_int i32_type i) llvalue builder
This build a new function , with private linkage ( since
that it can be used only by the current term ) , which
allows optimizations .
Note that [ build_function ] will use a new builder , so the
lambda can be built in parallel with the current
function . Also it will use new variables and continuation
variable maps ( with only the x parameter ) , so the lambda
expression must not contain any free variables .
that it can be used only by the current term), which
allows llvm optimizations.
Note that [build_function] will use a new builder, so the
lambda can be built in parallel with the current
function. Also it will use new variables and continuation
variable maps (with only the x parameter), so the lambda
expression must not contain any free variables. *)
| Value( Lambda(ft,k,vl,body)) -> assert(ft == No_environment);
let funname = ((Var.Var.to_string x) ^ "fun") in
Declare the function , and add it to the map , so as to
allow recursive use of the function .
TODO : Extend this to any mutually recursive value
( , Tuples , Injections ) . This is an argument for
separating let_prim(x , prim , body ) from
let_values([(x1,value1); ... (xn , ) .
FIXME : The function is build from [ env.globalvarmap ] . This
can cause issues when an inner function recursively calls
the function in which it is defined . It works currently
because the closure conversion algorithm pass the outer
function in the environment , but optimisations will break
that . One solution would be to lift the lamdba to global
scope . Another solution would be to pass the current
, but then will not be able to catch some
errors .
allow recursive use of the function.
TODO: Extend this to any mutually recursive value
(Lamdba, Tuples, Injections). This is an argument for
separating let_prim(x,prim,body) from
let_values([(x1,value1);...(xn,valuen)],body).
FIXME: The function is build from [env.globalvarmap]. This
can cause issues when an inner function recursively calls
the function in which it is defined. It works currently
because the closure conversion algorithm pass the outer
function in the environment, but optimisations will break
that. One solution would be to lift the lamdba to global
scope. Another solution would be to pass the current
varmap, but then cpsllvm will not be able to catch some
errors. *)
let the_function = declare_llvm_function funname (List.length vl) true in
let the_function = Llvm.build_bitcast the_function anystar_type (funname ^ "cast") builder in
let function_build_map = Var_Map.add x the_function env.globalvarmap in
let f = build_function funname k vl body function_build_map in
Llvm.set_linkage Llvm.Linkage.Private f;
Llvm.build_bitcast f anystar_type xname builder
| Integer_binary_operation(op,xa,xb) ->
build_integer_binary_op xname op (translate_occurrence xa) (translate_occurrence xb) builder
| Integer_binary_predicate(pred,xa,xb) ->
build_integer_comparison xname pred (translate_occurrence xa) (translate_occurrence xb) builder
| Projection(i,x) -> build_letproj xname (translate_occurrence x) i builder
| Value (Constant(c)) -> print_endline (Constant.to_string c);
failwith "ICE: primitive operations as value in LLVM translation."
)
in build_term body {env with varmap=(add_to_varmap x result)} builder
s Building new basic blocks . The algorithm first creates an
empty basic block , bound to [ k ] , then build [ body ] , then build
[ term ] ( if [ k ] is really called ) , binding [ x ] to the phi
node .
empty basic block, bound to [k], then build [body], then build
[term] (if [k] is really called), binding [x] to the phi
node. *)
An unused continuation is translated to a basic block with no
predecessor , which makes complain . So we optimize this
case .
predecessor, which makes LLVM complain. So we optimize this
case. *)
| Let_cont(k,_,_,body) when
Cont_var.Var.number_of_occurrences k == Cont_var.Var.No_occurrence ->
build_term body env builder
The general case . The tricky part is that the bindings do
not allow to create an " empty " phi node ( even if it would , in
future implementations which would not box everything we would
still have to know the type of the phi node , and that
type is not known until we have processed the jumps to that
node ) . So it is the calls to k that create or change the phi
node ; no phi node means [ k ] is never called ( so we do not
bother building it ) .
Doing the operations in this order ensures that calls to [ k ] are
processed before [ k ] is built .
not allow to create an "empty" phi node (even if it would, in
future implementations which would not box everything we would
still have to know the llvm type of the phi node, and that llvm
type is not known until we have processed the jumps to that
node). So it is the calls to k that create or change the phi
node; no phi node means [k] is never called (so we do not
bother building it).
Doing the operations in this order ensures that calls to [k] are
processed before [k] is built. *)
| Let_cont(k,x,term,body) ->
let new_bb = new_block (Cont_var.Var.to_string k) builder in
let newcvm = add_to_contvarmap k new_bb in
let End_of_block = build_term body {env with contvarmap=newcvm} builder in
Llvm.position_at_end new_bb builder;
(match begin_with_phi_node new_bb with
| None -> End_of_block
| Some(phi) -> build_term term {env with contvarmap=newcvm; varmap=add_to_varmap x phi} builder)
Depending on k , applycont either returns or jumps to
| Apply_cont(k,x) ->
build_applycont (translate_cont_occurrence k) (translate_occurrence x) builder
The CPS semantics state that caller should return to k , but
LLVM SSA does not require that calls end basic blocks . So we
just build a call instruction , and then a call to [ k ] .
optimizations will eliminate the superfluous jump if needed .
LLVM SSA does not require that calls end basic blocks. So we
just build a call instruction, and then a call to [k]. LLVM
optimizations will eliminate the superfluous jump if needed. *)
| Apply(ft,func,k,args) -> assert(ft == No_environment);
let retval = build_call
(Var.Occur.to_string func)
(translate_occurrence func)
(List.map translate_occurrence args) builder in
build_applycont (translate_cont_occurrence k) retval builder
| Case(x,cases,default) ->
begin
let xval = translate_occurrence x in
let cases_nb = CaseMap.cardinal cases in
let default_bb = (match default with
| None -> new_unreachable_block builder
| Some(k) ->
basic_block_that_calls
("bb_" ^ (Cont_var.Occur.to_string k))
(translate_cont_occurrence k) xval builder) in
let (tag,value) = Variant.bind (Var.Occur.to_string x) xval builder in
let switch = Llvm.build_switch tag default_bb cases_nb builder in
CaseMap.iter (fun i k ->
Llvm.add_case switch (Llvm.const_int i32_type i)
(basic_block_that_calls
("bb_" ^ (Cont_var.Occur.to_string k))
(translate_cont_occurrence k) value builder))
cases;
End_of_block
end
| Halt(x) -> (match env.handle_halt with
| Halt_returns_void -> ignore(Llvm.build_ret_void builder)
| Halt_returns_value -> ignore(Llvm.build_ret (translate_occurrence x) builder)
| Halt_stores_results_in(llvalue) ->
Llvm.build_store (translate_occurrence x) llvalue builder;
ignore(Llvm.build_ret_void builder)
); End_of_block
and declare_llvm_function name numparams returns =
match (Llvm.lookup_function name the_module) with
| Some(f) -> f
| None ->
let args_type = Array.make numparams anystar_type in
let ret_type = if returns then anystar_type else void_type in
let function_type = Llvm.function_type ret_type args_type in
let the_function = Llvm.declare_function name function_type the_module in
the_function
s The following function factorizes the creation of a function with
LLVM . It takes the following arguments :
\begin{itemize }
\item [ name ] , a string [ name ] does not need to be unique , just
informative .
\item [ params ] is [ , var ) ] if the function takes
arguments , or None otherwise .
\item ] is the CPS term representing the body of the
function to be translated .
\item [ handle_halt ] states how [ Halt(x ) ] CPS terms must be
translated .
\item [ globalvarmap ] is the mapping from global CPS variables to
llvalues .
\end{itemize }
LLVM. It takes the following arguments:
\begin{itemize}
\item [name], a string [name] does not need to be unique, just
informative.
\item [params] is [Some(cont_var,var)] if the LLvm function takes
arguments, or None otherwise.
\item [cpsbody] is the CPS term representing the body of the
function to be translated.
\item [handle_halt] states how [Halt(x)] CPS terms must be
translated.
\item [globalvarmap] is the mapping from global CPS variables to
llvalues.
\end{itemize}
*)
and created_functions = ((Hashtbl.create 47):(string, unit) Hashtbl.t)
and build_llvm_function name ~params cpsbody handle_halt globalvarmap =
It is important for that function names are unique ; but
names are used by as identifiers , so we can not uniquify them
here ; [ name ] must already be uniquifed by the caller . The
hashtable allows to check that : a name is in the hashtable iff
a function with the same name has been built .
names are used by LLVM as identifiers, so we cannot uniquify them
here; [name] must already be uniquifed by the caller. The
hashtable allows to check that: a name is in the hashtable iff
a function with the same name has been built. *)
if Hashtbl.mem created_functions name
then failwith ("Calling build_llvm_function twice with name `" ^ name ^"'")
else Hashtbl.add created_functions name ();
let numparams = match params with
| Some(_,l) -> (List.length l)
| None -> 0 in
let returns = match handle_halt with
| Halt_returns_value -> true
| Halt_stores_results_in _ | Halt_returns_void -> false in
let the_function = declare_llvm_function name numparams returns in
let (initial_contvarmap, initial_varmap) = match params with
| Some(k,l) -> (Cont_var_Map.singleton k Ret,
List.fold_left_with_index (fun map x i ->
Var_Map.add x (Llvm.param the_function i) map)
globalvarmap l)
| None -> (Cont_var_Map.empty, globalvarmap) in
let initial_env = { contvarmap = initial_contvarmap;
varmap = initial_varmap;
globalvarmap = globalvarmap;
handle_halt = handle_halt
} in
let bb = Llvm.append_block context "entry" the_function in
let builder = Llvm.builder context in
Llvm.position_at_end bb builder;
try
ignore(build_term cpsbody initial_env builder);
if Log.Llvm_output.is_output Log.Debug
then Llvm.dump_value the_function
else ();
Validate the code we just generated .
Llvm_analysis.assert_valid_function the_function;
the_function
with e -> Llvm.delete_function the_function; raise e
and build_function name contparam params cpsbody globalvarmap =
build_llvm_function name ~params:(Some(contparam,params)) cpsbody Halt_returns_value globalvarmap
;;
let build_unbound_def cpsbody globalvarmap =
build_llvm_function (uniquify_name "nodef") ~params:None cpsbody Halt_returns_void globalvarmap;;
let build_bound_def var cpsbody globalvarmap =
let varname = Var.Var.to_string var in
let funname = ("construct_" ^ varname) in
let the_variable = Llvm.define_global varname undef_anystar the_module in
let the_function =
build_llvm_function funname ~params:None cpsbody (Halt_stores_results_in the_variable) globalvarmap in
(the_variable, the_function)
;;
let build_definition def globalvarmap =
let (Definition(visib,Dynamic_value(expr))) = def in
match visib with
| Public(var) | Private(var) ->
let (the_variable, the_function) = build_bound_def var expr globalvarmap in
let newmap = Var_Map.add var the_variable globalvarmap in
(the_function, newmap)
| Unused ->
let the_function = build_unbound_def expr globalvarmap in
(the_function, globalvarmap)
;;
module Stream = Extensions.Stream;;
let from_stream cps_stream =
let f state cps =
let (llvmdef, new_state) = build_definition cps state in
[llvmdef], new_state in
Stream.transformer f Base.Var.Var.Map.empty cps_stream ;;
|
2b8c7e665290124c1bb80499f8c03313532c06fe3bdf824cb4e6990f7bdc27a8 | jkrivine/tl_interpreter | c.mli | (** This is an interface file. It provides the low-level APIs for writing smart contracts and interacting with the chain. *)
* The API is divided into [ Program ] , which contains Solidity - like facilities ,
and [ Chain ] , which is about submitting transactions to the chain . They
share [ Monad ] and [ Echo ] as common interfaces .
and [Chain], which is about submitting transactions to the chain. They
share [Monad] and [Echo] as common interfaces. *)
* Some of the complexity comes from the existence of two parallel implementations .
One is functional and relies on a state+exception monad . The other is imperative .
It directly modifies a state reference and uses OCaml exceptions .
The Imperative is implemented using the Functional .
One is functional and relies on a state+exception monad. The other is imperative.
It directly modifies a state reference and uses OCaml exceptions.
The Imperative is implemented using the Functional. *)
(** Generic state+exception monad *)
module type Monad = sig
(** A command to be executed in a chain environment
may return a value of type ['a]. *)
type 'a st
(** When a command [c] has no argument, it should be used as [c] in the
functional implementation, but as [c ()] in the imperative one (since
OCaml evaluates eagerly). *)
type 'a unit_st
* An identifier for a stored function that takes inputs of type [ ' a ] and outputs values of type [ ' b ] .
to the first 4 bytes of the Keccak256 of a function signature in Solidity ( except a function signature in Solidity does not specify return type ) .
Note that in Ethereum , method [ fn(int a ) ] stored at address [ ] may be completely different from [ fn(int a ) ] stored at [ 0x2 ] .
Similarly , for a given key [ k : ( ' a,'b ) code_id ] , different addresses may give different implementations of [ k ] .
Akin to the first 4 bytes of the Keccak256 of a function signature in Solidity (except a function signature in Solidity does not specify return type).
Note that in Ethereum, method [fn(int a)] stored at address [0x1] may be completely different from [fn(int a)] stored at [0x2].
Similarly, for a given key [k : ('a,'b) code_id], different addresses may give different implementations of [k]. *)
type ('a,'b) code_id
* An identifier for a value . Similar to a storage variable in Solidity , except here it 's just a key .
The difference with a [ code_id ] is that functions stored as
values can not be executed , but can be rewritten ( once a [ code_id ]
is set at an address , it can not be changed ) .
The difference with a [code_id] is that functions stored as
values cannot be executed, but can be rewritten (once a [code_id]
is set at an address, it cannot be changed). *)
type 'a data_id
(** [bind st (fun v -> st')] chains command [st] and [st'], allowing [st'] to
depend on the output of [st]. Note that in the imperative version, [bind
t1 t2 = t2 t1]. *)
val bind : 'a st -> ('a -> 'b st) -> 'b st
(** Syntactic sugar for [bind] *)
val (>>=) : 'a st -> ('a -> 'b st) -> 'b st
(** Also sugar for [bind] *)
val ( let* ) : 'a st -> ('a -> 'b st) -> 'b st
(** Syntactic sugar for [bind] with argument ignored *)
val (>>) : 'a st -> 'b st -> 'b st
(** [return v] wraps [v] in a chain command that immediately returns [v] upon
execution. *)
val return : 'a -> 'a st
* Raises an error . Can be another constructor of the state+exception monad
( in the functional implementation ) , or an actual OCaml exception ( in the
imperative implementation ) .
(in the functional implementation), or an actual OCaml exception (in the
imperative implementation). *)
val error : string -> 'a st
(** Syntactic sugar. Same as [(|?)] for ['a option], but lifted to the ['a
option st] type. *)
val (|?*) : 'a option st -> 'a -> 'a st
end
(** On-chain logging module *)
module type Echo = sig
* { 1 Base functionality }
type 'a st
type 'a unit_st
type ('a,'b) code_id
type 'a data_id
(** {1 Logging} *)
(** Echo a string
(state,context) arg important for evaluation time of F.p functions *)
val echo : string -> unit st
(** In the current context, log the data associated to the argument *)
val echo_data : 'a data_id -> unit st
(** Generic logging *)
val echo_pp : ('a, Format.formatter, unit, unit st) format4 -> 'a
(** Log the current address *)
val echo_address : Address.t -> unit st
(** Display of trace at the current code point *)
val echo_trace : unit unit_st
(** Echo the current state *)
val echo_state : unit unit_st
(** Echo the current context *)
val echo_context : unit unit_st
(** Pretty formatting for current (state,context) pair *)
val echo_env : unit unit_st
end
(** API for coding smart contracts *)
module type Program = sig
* { 1 Base functionality }
include Monad
(** {1 Stored code} *)
(** Initialize a new key for code.
If not part of a module or returned from a constructor,
the key will be private. So even proxying will be impossible.
If you want proxying to be impossible but still need the key to be accessible,
set [~internal:true].
*)
val code : ?internal:bool -> unit -> ('a,'b) code_id
* Associate chain code to a code identifier . May only be used in a constructor
val code_set : ('a,'b) code_id -> ('a -> 'b st) -> unit st
(** Return a fresh constructor with associated code. Same as using [code] with a local variable. *)
val code_private : ('a -> 'b st) -> ('a,'b) code_id st
* { 1 Stored data }
(** Initialize a new key for data.
[~pp] may specify a formatter.
More simply, [~show] may specify a printing function ([~pp] has priority).
The [string] argument will be used as the name for the data in logging facilities.
*)
val data : ?pp:(Format.formatter -> 'a -> unit) -> ?show:('a -> string) -> string -> 'a data_id
(** Initialize a new key which will not show when printing current state. *)
val data_hidden : unit -> 'a data_id
(** Same as assigning a storage variable in Solidity. *)
val data_set : 'a data_id -> 'a -> unit st
(** Same as reading a storage variable. *)
val data_get : 'a data_id -> 'a st
(** Convenience: [data_update k (fun v -> v')] sets the data associated with [k] to [v'] *)
val data_update : 'a data_id -> ('a -> 'a) -> unit st
(** Convenience: define data that will only be visible to
- constructor methods
- any inheriting contract if the key is returned by the constructor
*)
val data_private : 'a -> 'a data_id st
* { 2 Map - specific convenience functions }
(** In [map_set identifier k v], consider [identifier] as the name of some [map]. Set the value of [k] in [map] to [v] *)
val map_set : ('a,'b) MP.t data_id -> 'a -> 'b -> unit st
(** [map_remove identifier k] deletes the value associated to k *)
val map_remove : ('a,'b) MP.t data_id -> 'a -> unit st
(** Consider [identifier] as some [map]'s name. Get the value of [k] in [map] *)
val map_find : ('a,'b) MP.t data_id -> 'a -> 'b option st
(** Throws an exception with helpful [string] *)
val map_find_exns : string -> ('a,'b) MP.t data_id -> 'a -> 'b st
(** Throws a generic exceptoin *)
val map_find_exn : ('a,'b) MP.t data_id -> 'a -> 'b st
exception BadUpdate
(** Convenience update function *)
val map_update : ('a,'b) MP.t data_id -> 'a -> ?default:'b -> ('b -> 'b) -> unit st
(** {1 Admin-only stuff} *)
(** Execution at the 'root' is from the admin address.
Anything nested below that is by a user or a contract
The admin address can execute some privileged functions *)
* [ true ] iff current address is [ Address.admin ]
val is_admin : bool unit_st
* [ true ] iff current caller is [ Address.admin ]
val is_admin_caller : bool unit_st
(** Raises exception unless [is_admin] *)
val require_admin : unit unit_st
* { 1 Creating contracts }
(** Run [f] at a fresh address in a constructor context *)
val create_contract : string -> ('a -> 'b st) -> 'a -> Address.t st
(** Run [f] at a fresh address in a constructor context *)
val create_empty_contract : string -> Address.t st
(** [create_user] is synonym *)
val create_user : string -> Address.t st
* { 1 Calling contract code }
(** Get the code given by [code_id] at [address], run it at [address] *)
val call : Address.t -> ('a,'b) code_id -> 'a -> 'b st
(** Get the code given by [code_id] at [address] but run it in the current context *)
val delegatecall : Address.t -> ('a,'b) code_id -> 'a -> 'b st
(** Convenience, do a call at current address *)
val callthis : ('a,'b) code_id -> 'a -> 'b st
(** {1 Misc. } *)
(** Get current caller *)
val get_caller : Address.t unit_st
(** Get current address *)
val get_this : Address.t unit_st
(** Check boolean value, throw if false *)
val require : bool st -> unit st
(** not natively available in ethereum, included for convenience *)
val proxy : Address.t -> ?caller:Address.t -> 'a unit_st -> 'a st
(** Run the given code (only allowed in a constructor, it is used to simulate
inheritance but [inherit] is a reserved keyword, so we use [import] *)
val import : 'a unit_st -> 'a st
(** Check if a contract has an entry for key [k] *)
val responds : Address.t -> ('a,'b) code_id -> bool st
(** Time stuff, some of it admin-only *)
val time_get : int unit_st
(** {1 Logging} *)
include Echo with type 'a st := 'a st
and type 'a unit_st := 'a unit_st
and type ('a,'b) code_id := ('a,'b) code_id
and type 'a data_id := 'a data_id
end
(** API for interacting with the chain from the outside *)
module type Chain = sig
* { 1 Base functionality }
include Monad
(** {1 Transactions} *)
(** User sends a transactions. Ignore return value. Revert to previous state in case of error. *)
val tx : Address.t -> Address.t -> ('a,'b) code_id -> 'a -> unit st
(** User sends a transactions. Pass along return value. Bubble up an exception in case of error. *)
val txr : Address.t -> Address.t -> ('a,'b) code_id -> 'a -> 'b st
(** User sends a contract creation transaction *)
* In ethereum , this is just a normal tx but with address 0 as destination
val tx_create : Address.t -> string -> ('a -> 'b st) -> 'a -> Address.t st
(** [tx_proxy a c] runs commands [c] as a single transaction, originating
from [a]. Useful for executing arbitrary code from the [Chain] interface.
*)
val tx_proxy : Address.t -> 'a unit_st -> 'a st
* { 1 Time / state manipulation }
(** Change current block number. Cannot go back. *)
val time_set : int -> unit st
val time_incr : int -> unit st
(** State saving/restoring, imperative *)
val state_save : string -> unit st
val state_restore : string -> unit st
(** {1 Logging} *)
include Echo with type 'a st := 'a st
and type 'a unit_st := 'a unit_st
and type ('a,'b) code_id := ('a,'b) code_id
and type 'a data_id := 'a data_id
end
| null | https://raw.githubusercontent.com/jkrivine/tl_interpreter/c967c6578dd4491a6930c9842a0709fbc5939496/lib/c.mli | ocaml | * This is an interface file. It provides the low-level APIs for writing smart contracts and interacting with the chain.
* Generic state+exception monad
* A command to be executed in a chain environment
may return a value of type ['a].
* When a command [c] has no argument, it should be used as [c] in the
functional implementation, but as [c ()] in the imperative one (since
OCaml evaluates eagerly).
* [bind st (fun v -> st')] chains command [st] and [st'], allowing [st'] to
depend on the output of [st]. Note that in the imperative version, [bind
t1 t2 = t2 t1].
* Syntactic sugar for [bind]
* Also sugar for [bind]
* Syntactic sugar for [bind] with argument ignored
* [return v] wraps [v] in a chain command that immediately returns [v] upon
execution.
* Syntactic sugar. Same as [(|?)] for ['a option], but lifted to the ['a
option st] type.
* On-chain logging module
* {1 Logging}
* Echo a string
(state,context) arg important for evaluation time of F.p functions
* In the current context, log the data associated to the argument
* Generic logging
* Log the current address
* Display of trace at the current code point
* Echo the current state
* Echo the current context
* Pretty formatting for current (state,context) pair
* API for coding smart contracts
* {1 Stored code}
* Initialize a new key for code.
If not part of a module or returned from a constructor,
the key will be private. So even proxying will be impossible.
If you want proxying to be impossible but still need the key to be accessible,
set [~internal:true].
* Return a fresh constructor with associated code. Same as using [code] with a local variable.
* Initialize a new key for data.
[~pp] may specify a formatter.
More simply, [~show] may specify a printing function ([~pp] has priority).
The [string] argument will be used as the name for the data in logging facilities.
* Initialize a new key which will not show when printing current state.
* Same as assigning a storage variable in Solidity.
* Same as reading a storage variable.
* Convenience: [data_update k (fun v -> v')] sets the data associated with [k] to [v']
* Convenience: define data that will only be visible to
- constructor methods
- any inheriting contract if the key is returned by the constructor
* In [map_set identifier k v], consider [identifier] as the name of some [map]. Set the value of [k] in [map] to [v]
* [map_remove identifier k] deletes the value associated to k
* Consider [identifier] as some [map]'s name. Get the value of [k] in [map]
* Throws an exception with helpful [string]
* Throws a generic exceptoin
* Convenience update function
* {1 Admin-only stuff}
* Execution at the 'root' is from the admin address.
Anything nested below that is by a user or a contract
The admin address can execute some privileged functions
* Raises exception unless [is_admin]
* Run [f] at a fresh address in a constructor context
* Run [f] at a fresh address in a constructor context
* [create_user] is synonym
* Get the code given by [code_id] at [address], run it at [address]
* Get the code given by [code_id] at [address] but run it in the current context
* Convenience, do a call at current address
* {1 Misc. }
* Get current caller
* Get current address
* Check boolean value, throw if false
* not natively available in ethereum, included for convenience
* Run the given code (only allowed in a constructor, it is used to simulate
inheritance but [inherit] is a reserved keyword, so we use [import]
* Check if a contract has an entry for key [k]
* Time stuff, some of it admin-only
* {1 Logging}
* API for interacting with the chain from the outside
* {1 Transactions}
* User sends a transactions. Ignore return value. Revert to previous state in case of error.
* User sends a transactions. Pass along return value. Bubble up an exception in case of error.
* User sends a contract creation transaction
* [tx_proxy a c] runs commands [c] as a single transaction, originating
from [a]. Useful for executing arbitrary code from the [Chain] interface.
* Change current block number. Cannot go back.
* State saving/restoring, imperative
* {1 Logging} |
* The API is divided into [ Program ] , which contains Solidity - like facilities ,
and [ Chain ] , which is about submitting transactions to the chain . They
share [ Monad ] and [ Echo ] as common interfaces .
and [Chain], which is about submitting transactions to the chain. They
share [Monad] and [Echo] as common interfaces. *)
* Some of the complexity comes from the existence of two parallel implementations .
One is functional and relies on a state+exception monad . The other is imperative .
It directly modifies a state reference and uses OCaml exceptions .
The Imperative is implemented using the Functional .
One is functional and relies on a state+exception monad. The other is imperative.
It directly modifies a state reference and uses OCaml exceptions.
The Imperative is implemented using the Functional. *)
module type Monad = sig
type 'a st
type 'a unit_st
* An identifier for a stored function that takes inputs of type [ ' a ] and outputs values of type [ ' b ] .
to the first 4 bytes of the Keccak256 of a function signature in Solidity ( except a function signature in Solidity does not specify return type ) .
Note that in Ethereum , method [ fn(int a ) ] stored at address [ ] may be completely different from [ fn(int a ) ] stored at [ 0x2 ] .
Similarly , for a given key [ k : ( ' a,'b ) code_id ] , different addresses may give different implementations of [ k ] .
Akin to the first 4 bytes of the Keccak256 of a function signature in Solidity (except a function signature in Solidity does not specify return type).
Note that in Ethereum, method [fn(int a)] stored at address [0x1] may be completely different from [fn(int a)] stored at [0x2].
Similarly, for a given key [k : ('a,'b) code_id], different addresses may give different implementations of [k]. *)
type ('a,'b) code_id
* An identifier for a value . Similar to a storage variable in Solidity , except here it 's just a key .
The difference with a [ code_id ] is that functions stored as
values can not be executed , but can be rewritten ( once a [ code_id ]
is set at an address , it can not be changed ) .
The difference with a [code_id] is that functions stored as
values cannot be executed, but can be rewritten (once a [code_id]
is set at an address, it cannot be changed). *)
type 'a data_id
val bind : 'a st -> ('a -> 'b st) -> 'b st
val (>>=) : 'a st -> ('a -> 'b st) -> 'b st
val ( let* ) : 'a st -> ('a -> 'b st) -> 'b st
val (>>) : 'a st -> 'b st -> 'b st
val return : 'a -> 'a st
* Raises an error . Can be another constructor of the state+exception monad
( in the functional implementation ) , or an actual OCaml exception ( in the
imperative implementation ) .
(in the functional implementation), or an actual OCaml exception (in the
imperative implementation). *)
val error : string -> 'a st
val (|?*) : 'a option st -> 'a -> 'a st
end
module type Echo = sig
* { 1 Base functionality }
type 'a st
type 'a unit_st
type ('a,'b) code_id
type 'a data_id
val echo : string -> unit st
val echo_data : 'a data_id -> unit st
val echo_pp : ('a, Format.formatter, unit, unit st) format4 -> 'a
val echo_address : Address.t -> unit st
val echo_trace : unit unit_st
val echo_state : unit unit_st
val echo_context : unit unit_st
val echo_env : unit unit_st
end
module type Program = sig
* { 1 Base functionality }
include Monad
val code : ?internal:bool -> unit -> ('a,'b) code_id
* Associate chain code to a code identifier . May only be used in a constructor
val code_set : ('a,'b) code_id -> ('a -> 'b st) -> unit st
val code_private : ('a -> 'b st) -> ('a,'b) code_id st
* { 1 Stored data }
val data : ?pp:(Format.formatter -> 'a -> unit) -> ?show:('a -> string) -> string -> 'a data_id
val data_hidden : unit -> 'a data_id
val data_set : 'a data_id -> 'a -> unit st
val data_get : 'a data_id -> 'a st
val data_update : 'a data_id -> ('a -> 'a) -> unit st
val data_private : 'a -> 'a data_id st
* { 2 Map - specific convenience functions }
val map_set : ('a,'b) MP.t data_id -> 'a -> 'b -> unit st
val map_remove : ('a,'b) MP.t data_id -> 'a -> unit st
val map_find : ('a,'b) MP.t data_id -> 'a -> 'b option st
val map_find_exns : string -> ('a,'b) MP.t data_id -> 'a -> 'b st
val map_find_exn : ('a,'b) MP.t data_id -> 'a -> 'b st
exception BadUpdate
val map_update : ('a,'b) MP.t data_id -> 'a -> ?default:'b -> ('b -> 'b) -> unit st
* [ true ] iff current address is [ Address.admin ]
val is_admin : bool unit_st
* [ true ] iff current caller is [ Address.admin ]
val is_admin_caller : bool unit_st
val require_admin : unit unit_st
* { 1 Creating contracts }
val create_contract : string -> ('a -> 'b st) -> 'a -> Address.t st
val create_empty_contract : string -> Address.t st
val create_user : string -> Address.t st
* { 1 Calling contract code }
val call : Address.t -> ('a,'b) code_id -> 'a -> 'b st
val delegatecall : Address.t -> ('a,'b) code_id -> 'a -> 'b st
val callthis : ('a,'b) code_id -> 'a -> 'b st
val get_caller : Address.t unit_st
val get_this : Address.t unit_st
val require : bool st -> unit st
val proxy : Address.t -> ?caller:Address.t -> 'a unit_st -> 'a st
val import : 'a unit_st -> 'a st
val responds : Address.t -> ('a,'b) code_id -> bool st
val time_get : int unit_st
include Echo with type 'a st := 'a st
and type 'a unit_st := 'a unit_st
and type ('a,'b) code_id := ('a,'b) code_id
and type 'a data_id := 'a data_id
end
module type Chain = sig
* { 1 Base functionality }
include Monad
val tx : Address.t -> Address.t -> ('a,'b) code_id -> 'a -> unit st
val txr : Address.t -> Address.t -> ('a,'b) code_id -> 'a -> 'b st
* In ethereum , this is just a normal tx but with address 0 as destination
val tx_create : Address.t -> string -> ('a -> 'b st) -> 'a -> Address.t st
val tx_proxy : Address.t -> 'a unit_st -> 'a st
* { 1 Time / state manipulation }
val time_set : int -> unit st
val time_incr : int -> unit st
val state_save : string -> unit st
val state_restore : string -> unit st
include Echo with type 'a st := 'a st
and type 'a unit_st := 'a unit_st
and type ('a,'b) code_id := ('a,'b) code_id
and type 'a data_id := 'a data_id
end
|
a9bca5be6782843be5e572f4cb29d7b9f34126b0c0c2a8da7d76a9797b48b1f8 | lispnik/iup | tree.lisp | ;;; Generated from org-mode, do not edit
(eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload '("iup" "iup-controls" "uiop")))
(defpackage #:iup-examples.tree
(:use #:common-lisp)
(:export #:tree))
(in-package #:iup-examples.tree)
(defun get-dir (pathname)
(assert (uiop:directory-pathname-p pathname))
(loop for pathname in (uiop:directory* (make-pathname :name :wild :defaults pathname))
if (uiop:directory-pathname-p pathname)
collect pathname into dirs
else
collect pathname into files
finally (return (values dirs files))))
(defun fill-tree (tree id pathname)
(multiple-value-bind
(dirs files)
(get-dir pathname)
(dolist (file files)
(setf (iup:attribute tree :addleaf) (namestring file)))
(dolist (dir dirs)
(setf (iup:attribute tree :addbranch) (namestring dir)))
(setf (iup:attribute tree :title) (namestring pathname))))
(defun map-callback (handle)
(fill-tree handle 0 "/")
iup:+default+)
(defun branchopen-callback (handle id)
(setf (iup:attribute handle (format nil "DELNODE~A" id)) "CHILDREN")
(fill-tree handle id (iup:attribute handle (format nil "TITLE~A" id)))
iup:+default+)
(defun tree ()
(iup:with-iup ()
(let* ((tree (iup:tree :minsize "200x300"
:map_cb 'map-callback
:branchopen_cb 'branchopen-callback))
(dialog (iup:dialog tree :title "Tree Example")))
(iup:show dialog)
(iup:main-loop))))
#-sbcl (tree)
#+sbcl
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(tree))
| null | https://raw.githubusercontent.com/lispnik/iup/f8e5f090bae47bf8f91ac6fed41ec3bc01061186/examples/tree.lisp | lisp | Generated from org-mode, do not edit |
(eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload '("iup" "iup-controls" "uiop")))
(defpackage #:iup-examples.tree
(:use #:common-lisp)
(:export #:tree))
(in-package #:iup-examples.tree)
(defun get-dir (pathname)
(assert (uiop:directory-pathname-p pathname))
(loop for pathname in (uiop:directory* (make-pathname :name :wild :defaults pathname))
if (uiop:directory-pathname-p pathname)
collect pathname into dirs
else
collect pathname into files
finally (return (values dirs files))))
(defun fill-tree (tree id pathname)
(multiple-value-bind
(dirs files)
(get-dir pathname)
(dolist (file files)
(setf (iup:attribute tree :addleaf) (namestring file)))
(dolist (dir dirs)
(setf (iup:attribute tree :addbranch) (namestring dir)))
(setf (iup:attribute tree :title) (namestring pathname))))
(defun map-callback (handle)
(fill-tree handle 0 "/")
iup:+default+)
(defun branchopen-callback (handle id)
(setf (iup:attribute handle (format nil "DELNODE~A" id)) "CHILDREN")
(fill-tree handle id (iup:attribute handle (format nil "TITLE~A" id)))
iup:+default+)
(defun tree ()
(iup:with-iup ()
(let* ((tree (iup:tree :minsize "200x300"
:map_cb 'map-callback
:branchopen_cb 'branchopen-callback))
(dialog (iup:dialog tree :title "Tree Example")))
(iup:show dialog)
(iup:main-loop))))
#-sbcl (tree)
#+sbcl
(sb-int:with-float-traps-masked
(:divide-by-zero :invalid)
(tree))
|
11b3bcf89e6e1858f154292cd15878d4863ad80fd2616f0590a47874f2db3d1f | ocaml/Zarith | timings.ml | open Printf
(* Timing harness harness *)
let time fn arg =
let start = Sys.time() in
let rec time accu =
let qty = fn arg in
let duration = Sys.time() -. start in
let qty = float qty in
if duration >= 1.0
then duration /. (accu +. qty)
else time (accu +. qty)
in time 0.0
let time_repeat rep fn arg =
time (fun () -> for i = 1 to rep do ignore (fn arg) done; rep) ()
(* Basic arithmetic operations *)
let add (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.add x y))
done;
50_000_000
let sub (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.sub x y))
done;
50_000_000
let mul (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.mul x y))
done;
50_000_000
let div (x, y) =
for i = 1 to 10_000_000 do
ignore (Sys.opaque_identity (Z.div x y))
done;
1_000_000
let shl (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.shift_left x y))
done;
50_000_000
let big = Z.pow (Z.of_int 17) 150
let med = Z.pow (Z.of_int 3) 150
let _ =
printf "%.2e add (small, no overflow)\n%!"
(time add (Z.of_int 1, Z.of_int 2));
printf "%.2e add (small, overflow)\n%!"
(time add (Z.of_int max_int, Z.of_int 2));
printf "%.2e add (small, big)\n%!"
(time add (Z.of_int 1, big));
printf "%.2e add (big, big)\n%!"
(time add (big, big));
printf "%.2e sub (small, no overflow)\n%!"
(time sub (Z.of_int 1, Z.of_int 2));
printf "%.2e sub (small, overflow)\n%!"
(time sub (Z.of_int max_int, Z.of_int (-2)));
printf "%.2e sub (big, small)\n%!"
(time sub (big, Z.of_int 1));
printf "%.2e sub (big, big)\n%!"
(time sub (big, big));
printf "%.2e mul (small, no overflow)\n%!"
(time mul (Z.of_int 42, Z.of_int 74));
printf "%.2e mul (small, overflow)\n%!"
(time mul (Z.of_int max_int, Z.of_int 3));
printf "%.2e mul (small, big)\n%!"
(time mul (Z.of_int 3, big));
printf "%.2e mul (medium, medium)\n%!"
(time mul (med, med));
printf "%.2e mul (big, big)\n%!"
(time mul (big, big));
printf "%.2e div (small, small)\n%!"
(time div (Z.of_int 12345678, Z.of_int 443));
printf "%.2e div (big, small)\n%!"
(time div (big, Z.of_int 443));
printf "%.2e div (big, medium)\n%!"
(time div (big, med));
printf "%.2e shl (small, no overflow)\n%!"
(time shl (Z.of_int 3, 10));
printf "%.2e shl (small, overflow)\n%!"
(time shl (Z.of_int max_int, 2));
printf "%.2e shl (big)\n%!"
(time shl (big, 42))
(* Factorial *)
let rec fact_z n =
if n <= 0 then Z.one else Z.mul (Z.of_int n) (fact_z (n-1))
let _ =
printf "%.2e fact 10\n%!"
(time_repeat 1_000_000 fact_z 10);
printf "%.2e fact 40\n%!"
(time_repeat 10_000 fact_z 40);
printf "%.2e fact 200\n%!"
(time_repeat 10_000 fact_z 200)
(* Fibonacci *)
let rec fib_int n =
if n < 2 then 1 else fib_int(n-1) + fib_int(n-2)
let rec fib_natint n =
if n < 2 then 1n else Nativeint.add (fib_natint(n-1)) (fib_natint(n-2))
let rec fib_z n =
if n < 2 then Z.one else Z.add (fib_z(n-1)) (fib_z(n-2))
let fib_arg = 32
let _ =
printf "%.2e fib (int)\n%!"
(time_repeat 100 fib_int fib_arg);
printf "%.2e fib (nativeint)\n%!"
(time_repeat 100 fib_natint fib_arg);
printf "%.2e fib (Z)\n%!"
(time_repeat 100 fib_z fib_arg)
(* Takeushi *)
let rec tak_int (x, y, z) =
if x > y
then tak_int(tak_int (x-1, y, z), tak_int (y-1, z, x), tak_int (z-1, x, y))
else z
let rec tak_natint (x, y, z) =
if x > y
then tak_natint(tak_natint (Nativeint.sub x 1n, y, z),
tak_natint (Nativeint.sub y 1n, z, x),
tak_natint (Nativeint.sub z 1n, x, y))
else z
let rec tak_z (x, y, z) =
if Z.compare x y > 0
then tak_z(tak_z (Z.pred x, y, z),
tak_z (Z.pred y, z, x),
tak_z (Z.pred z, x, y))
else z
let _ =
printf "%.2e tak (int)\n%!"
(time_repeat 1000 tak_int (18,12,6));
printf "%.2e tak (nativeint)\n%!"
(time_repeat 1000 tak_natint (18n,12n,6n));
printf "%.2e tak (Z)\n%!"
(time_repeat 1000 tak_z (Z.of_int 18, Z.of_int 12, Z.of_int 6))
| null | https://raw.githubusercontent.com/ocaml/Zarith/39df015463f2797256dfb12440ed8f6c2dfd59cc/tests/timings.ml | ocaml | Timing harness harness
Basic arithmetic operations
Factorial
Fibonacci
Takeushi | open Printf
let time fn arg =
let start = Sys.time() in
let rec time accu =
let qty = fn arg in
let duration = Sys.time() -. start in
let qty = float qty in
if duration >= 1.0
then duration /. (accu +. qty)
else time (accu +. qty)
in time 0.0
let time_repeat rep fn arg =
time (fun () -> for i = 1 to rep do ignore (fn arg) done; rep) ()
let add (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.add x y))
done;
50_000_000
let sub (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.sub x y))
done;
50_000_000
let mul (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.mul x y))
done;
50_000_000
let div (x, y) =
for i = 1 to 10_000_000 do
ignore (Sys.opaque_identity (Z.div x y))
done;
1_000_000
let shl (x, y) =
for i = 1 to 50_000_000 do
ignore (Sys.opaque_identity (Z.shift_left x y))
done;
50_000_000
let big = Z.pow (Z.of_int 17) 150
let med = Z.pow (Z.of_int 3) 150
let _ =
printf "%.2e add (small, no overflow)\n%!"
(time add (Z.of_int 1, Z.of_int 2));
printf "%.2e add (small, overflow)\n%!"
(time add (Z.of_int max_int, Z.of_int 2));
printf "%.2e add (small, big)\n%!"
(time add (Z.of_int 1, big));
printf "%.2e add (big, big)\n%!"
(time add (big, big));
printf "%.2e sub (small, no overflow)\n%!"
(time sub (Z.of_int 1, Z.of_int 2));
printf "%.2e sub (small, overflow)\n%!"
(time sub (Z.of_int max_int, Z.of_int (-2)));
printf "%.2e sub (big, small)\n%!"
(time sub (big, Z.of_int 1));
printf "%.2e sub (big, big)\n%!"
(time sub (big, big));
printf "%.2e mul (small, no overflow)\n%!"
(time mul (Z.of_int 42, Z.of_int 74));
printf "%.2e mul (small, overflow)\n%!"
(time mul (Z.of_int max_int, Z.of_int 3));
printf "%.2e mul (small, big)\n%!"
(time mul (Z.of_int 3, big));
printf "%.2e mul (medium, medium)\n%!"
(time mul (med, med));
printf "%.2e mul (big, big)\n%!"
(time mul (big, big));
printf "%.2e div (small, small)\n%!"
(time div (Z.of_int 12345678, Z.of_int 443));
printf "%.2e div (big, small)\n%!"
(time div (big, Z.of_int 443));
printf "%.2e div (big, medium)\n%!"
(time div (big, med));
printf "%.2e shl (small, no overflow)\n%!"
(time shl (Z.of_int 3, 10));
printf "%.2e shl (small, overflow)\n%!"
(time shl (Z.of_int max_int, 2));
printf "%.2e shl (big)\n%!"
(time shl (big, 42))
let rec fact_z n =
if n <= 0 then Z.one else Z.mul (Z.of_int n) (fact_z (n-1))
let _ =
printf "%.2e fact 10\n%!"
(time_repeat 1_000_000 fact_z 10);
printf "%.2e fact 40\n%!"
(time_repeat 10_000 fact_z 40);
printf "%.2e fact 200\n%!"
(time_repeat 10_000 fact_z 200)
let rec fib_int n =
if n < 2 then 1 else fib_int(n-1) + fib_int(n-2)
let rec fib_natint n =
if n < 2 then 1n else Nativeint.add (fib_natint(n-1)) (fib_natint(n-2))
let rec fib_z n =
if n < 2 then Z.one else Z.add (fib_z(n-1)) (fib_z(n-2))
let fib_arg = 32
let _ =
printf "%.2e fib (int)\n%!"
(time_repeat 100 fib_int fib_arg);
printf "%.2e fib (nativeint)\n%!"
(time_repeat 100 fib_natint fib_arg);
printf "%.2e fib (Z)\n%!"
(time_repeat 100 fib_z fib_arg)
let rec tak_int (x, y, z) =
if x > y
then tak_int(tak_int (x-1, y, z), tak_int (y-1, z, x), tak_int (z-1, x, y))
else z
let rec tak_natint (x, y, z) =
if x > y
then tak_natint(tak_natint (Nativeint.sub x 1n, y, z),
tak_natint (Nativeint.sub y 1n, z, x),
tak_natint (Nativeint.sub z 1n, x, y))
else z
let rec tak_z (x, y, z) =
if Z.compare x y > 0
then tak_z(tak_z (Z.pred x, y, z),
tak_z (Z.pred y, z, x),
tak_z (Z.pred z, x, y))
else z
let _ =
printf "%.2e tak (int)\n%!"
(time_repeat 1000 tak_int (18,12,6));
printf "%.2e tak (nativeint)\n%!"
(time_repeat 1000 tak_natint (18n,12n,6n));
printf "%.2e tak (Z)\n%!"
(time_repeat 1000 tak_z (Z.of_int 18, Z.of_int 12, Z.of_int 6))
|
d57cf2063e768065a655e9fa2434ebddf70f0457340acba4224bbf108e657e91 | RichiH/git-annex | Ssh.hs | git - annex assistant webapp configurator for ssh - based remotes
-
- Copyright 2012 - 2015 < >
-
- Licensed under the GNU AGPL version 3 or higher .
-
- Copyright 2012-2015 Joey Hess <>
-
- Licensed under the GNU AGPL version 3 or higher.
-}
# LANGUAGE QuasiQuotes , TemplateHaskell , OverloadedStrings #
# LANGUAGE CPP , FlexibleContexts #
module Assistant.WebApp.Configurators.Ssh where
import Assistant.WebApp.Common
import Assistant.WebApp.Gpg
import Assistant.Ssh
import Annex.Ssh
import Assistant.WebApp.MakeRemote
import Logs.Remote
import Remote
import Types.StandardGroups
import Utility.UserInfo
import Utility.Gpg
import Types.Remote (RemoteConfig)
import Git.Types (RemoteName, fromRef)
import qualified Remote.GCrypt as GCrypt
import qualified Annex
import qualified Git.Construct
import qualified Git.Config
import qualified Git.Command
import qualified Remote.Helper.Ssh
import qualified Annex.Branch
import Annex.UUID
import Logs.UUID
import Assistant.RemoteControl
import Types.Creds
import Assistant.CredPairCache
import Annex.Path
import Utility.Tmp
import Utility.FileMode
import Utility.ThreadScheduler
import Utility.Env
import Utility.SshHost
import qualified Data.Text as T
import qualified Data.Map as M
import Network.Socket
import Data.Ord
sshConfigurator :: Widget -> Handler Html
sshConfigurator = page "Add a remote server" (Just Configuration)
data SshInput = SshInput
{ inputHostname :: Maybe Text
, inputUsername :: Maybe Text
, inputAuthMethod :: AuthMethod
, inputPassword :: Maybe Text
, inputDirectory :: Maybe Text
, inputPort :: Int
}
data AuthMethod
= Password
| CachedPassword
| ExistingSshKey
deriving (Eq, Show)
-- Is a repository a new one that's being created, or did it already exist
-- and is just being added.
data RepoStatus = NewRepo | ExistingRepo
SshInput is only used for applicative form prompting , this converts
- the result of such a form into a SshData .
- the result of such a form into a SshData. -}
mkSshData :: SshInput -> SshData
mkSshData s = SshData
{ sshHostName = fromMaybe "" $ inputHostname s
, sshUserName = inputUsername s
, sshDirectory = fromMaybe "" $ inputDirectory s
, sshRepoName = genSshRepoName
(T.unpack $ fromJust $ inputHostname s)
(maybe "" T.unpack $ inputDirectory s)
, sshPort = inputPort s
, needsPubKey = False
, sshCapabilities = [] -- untested
, sshRepoUrl = Nothing
}
mkSshInput :: SshData -> SshInput
mkSshInput s = SshInput
{ inputHostname = Just $ sshHostName s
, inputUsername = sshUserName s
, inputAuthMethod = if needsPubKey s then CachedPassword else ExistingSshKey
, inputPassword = Nothing
, inputDirectory = Just $ sshDirectory s
, inputPort = sshPort s
}
sshInputAForm :: Field Handler Text -> SshInput -> AForm Handler SshInput
sshInputAForm hostnamefield d = normalize <$> gen
where
gen = SshInput
<$> aopt check_hostname (bfs "Host name") (Just $ inputHostname d)
<*> aopt check_username (bfs "User name") (Just $ inputUsername d)
<*> areq (selectFieldList authmethods) (bfs "Authenticate with") (Just $ inputAuthMethod d)
<*> aopt passwordField (bfs "Password") Nothing
<*> aopt textField (bfs "Directory") (Just $ Just $ fromMaybe (T.pack gitAnnexAssistantDefaultDir) $ inputDirectory d)
<*> areq intField (bfs "Port") (Just $ inputPort d)
authmethods :: [(Text, AuthMethod)]
authmethods =
[ ("password", Password)
, ("existing ssh key", ExistingSshKey)
]
check_username = checkBool (all (`notElem` ("/:@ \t" :: String)) . T.unpack)
bad_username textField
bad_username = "bad user name" :: Text
#ifndef __ANDROID__
bad_hostname = "cannot resolve host name" :: Text
check_hostname = checkM (liftIO . checkdns) hostnamefield
checkdns t = do
let h = T.unpack t
let canonname = Just $ defaultHints { addrFlags = [AI_CANONNAME] }
r <- catchMaybeIO $ getAddrInfo canonname (Just h) Nothing
return $ case mapMaybe addrCanonName <$> r of
-- canonicalize input hostname if it had no dot
Just (fullname:_)
| '.' `elem` h -> Right t
| otherwise -> Right $ T.pack fullname
Just [] -> Right t
Nothing -> Left bad_hostname
#else
getAddrInfo currently broken on Android
check_hostname = hostnamefield -- unchecked
#endif
-- The directory is implicitly in home, so remove any leading ~/
normalize i = i { inputDirectory = normalizedir <$> inputDirectory i }
normalizedir dir
| "~/" `T.isPrefixOf` dir = T.drop 2 dir
| "/~/" `T.isPrefixOf` dir = T.drop 3 dir
| otherwise = dir
data ServerStatus
= UntestedServer
| UnusableServer Text -- reason why it's not usable
| ServerNeedsPubKey SshPubKey
| UsableServer [SshServerCapability]
deriving (Eq)
capabilities :: ServerStatus -> [SshServerCapability]
capabilities (UsableServer cs) = cs
capabilities _ = []
getAddSshR :: Handler Html
getAddSshR = postAddSshR
postAddSshR :: Handler Html
postAddSshR = sshConfigurator $ do
username <- liftIO $ either (const Nothing) (Just . T.pack) <$> myUserName
((result, form), enctype) <- liftH $
runFormPostNoToken $ renderBootstrap3 bootstrapFormLayout $ sshInputAForm textField $
SshInput Nothing username Password Nothing Nothing 22
case result of
FormSuccess sshinput -> do
s <- liftAssistant $ testServer sshinput
case s of
Left status -> showform form enctype status
Right (sshdata, u) -> liftH $ redirect $ ConfirmSshR sshdata u
_ -> showform form enctype UntestedServer
where
showform form enctype status = $(widgetFile "configurators/ssh/add")
sshTestModal :: Widget
sshTestModal = $(widgetFile "configurators/ssh/testmodal")
sshSetupModal :: SshData -> Widget
sshSetupModal sshdata = $(widgetFile "configurators/ssh/setupmodal")
getEnableRsyncR :: UUID -> Handler Html
getEnableRsyncR = postEnableRsyncR
postEnableRsyncR :: UUID -> Handler Html
postEnableRsyncR = enableSshRemote getsshinput enableRsyncNet enablersync
where
enablersync sshdata u = redirect $ ConfirmSshR
(sshdata { sshCapabilities = [RsyncCapable] }) u
getsshinput = parseSshUrl <=< M.lookup "rsyncurl"
This only handles repositories that are located on ssh servers ;
- ones on local drives are handled via another part of the UI .
- ones on local drives are handled via another part of the UI. -}
getEnableSshGCryptR :: UUID -> Handler Html
getEnableSshGCryptR = postEnableSshGCryptR
postEnableSshGCryptR :: UUID -> Handler Html
postEnableSshGCryptR u = whenGcryptInstalled $
enableSshRemote getsshinput enableRsyncNetGCrypt enablegcrypt u
where
enablegcrypt sshdata _ = prepSsh False sshdata $ \sshdata' ->
sshConfigurator $
checkExistingGCrypt sshdata' $
giveup "Expected to find an encrypted git repository, but did not."
getsshinput = parseSshUrl <=< M.lookup "gitrepo"
getEnableSshGitRemoteR :: UUID -> Handler Html
getEnableSshGitRemoteR = postEnableSshGitRemoteR
postEnableSshGitRemoteR :: UUID -> Handler Html
postEnableSshGitRemoteR = enableSshRemote getsshinput enableRsyncNet enablesshgitremote
where
enablesshgitremote sshdata u = redirect $ ConfirmSshR sshdata u
getsshinput = parseSshUrl <=< M.lookup "location"
{- To enable a remote that uses ssh as its transport,
- parse a config key to get its url, and display a form
- to prompt for its password.
-}
enableSshRemote :: (RemoteConfig -> Maybe SshData) -> (SshInput -> RemoteName -> Handler Html) -> (SshData -> UUID -> Handler Html) -> UUID -> Handler Html
enableSshRemote getsshdata rsyncnetsetup genericsetup u = do
m <- fromMaybe M.empty . M.lookup u <$> liftAnnex readRemoteLog
case (unmangle <$> getsshdata m, M.lookup "name" m) of
(Just sshdata, Just reponame)
| isGitLab sshdata -> enableGitLab sshdata
| otherwise -> sshConfigurator $ do
((result, form), enctype) <- liftH $
runFormPostNoToken $ renderBootstrap3 bootstrapFormLayout $
sshInputAForm textField $ mkSshInput sshdata
case result of
FormSuccess sshinput
| isRsyncNet (inputHostname sshinput) ->
void $ liftH $ rsyncnetsetup sshinput reponame
| otherwise -> do
s <- liftAssistant $ testServer sshinput
case s of
Left status -> showform form enctype status
Right (sshdata', _u) -> void $ liftH $ genericsetup
( sshdata' { sshRepoName = reponame } ) u
_ -> showform form enctype UntestedServer
_ -> redirect AddSshR
where
unmangle sshdata = sshdata
{ sshHostName = T.pack $ unMangleSshHostName $
T.unpack $ sshHostName sshdata
}
showform form enctype status = do
description <- liftAnnex $ T.pack <$> prettyUUID u
$(widgetFile "configurators/ssh/enable")
{- To deal with git-annex and possibly even git and rsync not being
- available in the remote server's PATH, when git-annex was installed
- from the standalone tarball etc, look for a ~/.ssh/git-annex-wrapper
- and if it's there, use it to run a command. -}
wrapCommand :: String -> String
wrapCommand cmd = "if [ -x " ++ commandWrapper ++ " ]; then " ++ commandWrapper ++ " " ++ cmd ++ "; else " ++ cmd ++ "; fi"
commandWrapper :: String
commandWrapper = "~/.ssh/git-annex-wrapper"
Test if we can ssh into the server , using the specified .
-
- Once logged into the server , probe to see if git - annex - shell ,
- git , and rsync are available .
-
- Note that ~/.ssh / git - annex - shell may be present , while
- git - annex - shell is not in PATH .
- Also , git and rsync may not be in PATH ; as long as the commandWrapper
- is present , assume it is able to be used to run them .
-
- Also probe to see if there is already a git repository at the location
- with either an annex - uuid or a gcrypt - id set . ( If not , returns NoUUID . )
-
- Once logged into the server, probe to see if git-annex-shell,
- git, and rsync are available.
-
- Note that ~/.ssh/git-annex-shell may be present, while
- git-annex-shell is not in PATH.
- Also, git and rsync may not be in PATH; as long as the commandWrapper
- is present, assume it is able to be used to run them.
-
- Also probe to see if there is already a git repository at the location
- with either an annex-uuid or a gcrypt-id set. (If not, returns NoUUID.)
-}
testServer :: SshInput -> Assistant (Either ServerStatus (SshData, UUID))
testServer (SshInput { inputHostname = Nothing }) = return $
Left $ UnusableServer "Please enter a host name."
testServer sshinput@(SshInput { inputHostname = Just hn }) = do
(status, u) <- probe
case capabilities status of
[] -> return $ Left status
cs -> do
let sshdata = (mkSshData sshinput)
{ needsPubKey = inputAuthMethod sshinput /= ExistingSshKey
, sshCapabilities = cs
}
return $ Right (sshdata, u)
where
probe = do
let remotecommand = shellWrap $ intercalate ";"
[ report "loggedin"
, checkcommand "git-annex-shell"
, checkcommand "git"
, checkcommand "rsync"
, checkcommand shim
, checkcommand commandWrapper
, getgitconfig (T.unpack <$> inputDirectory sshinput)
]
knownhost <- liftIO $ knownHost hn
let sshopts =
{- If this is an already known host, let
- ssh check it as usual.
- Otherwise, trust the host key. -}
[ sshOpt "StrictHostKeyChecking" $
if knownhost then "yes" else "no"
do n't read from stdin
, "-p", show (inputPort sshinput)
]
let sshhost = genSshHost
(fromJust $ inputHostname sshinput)
(inputUsername sshinput)
parsetranscript . fst <$> sshAuthTranscript sshinput sshopts sshhost remotecommand Nothing
parsetranscript s =
let cs = map snd $ filter (reported . fst)
[ ("git-annex-shell", GitAnnexShellCapable)
, (shim, GitAnnexShellCapable)
, ("git", GitCapable)
, ("rsync", RsyncCapable)
, (commandWrapper, GitCapable)
, (commandWrapper, RsyncCapable)
]
u = fromMaybe NoUUID $ headMaybe $ mapMaybe finduuid $
map (separate (== '=')) $ lines s
in if null cs
then (UnusableServer unusablereason, u)
else (UsableServer cs, u)
where
reported r = token r `isInfixOf` s
unusablereason = if reported "loggedin"
then "Neither rsync nor git-annex are installed on the server. Perhaps you should go install them?"
else T.pack $ "Failed to ssh to the server. Transcript: " ++ s
finduuid (k, v)
| k == "annex.uuid" = Just $ toUUID v
| k == GCrypt.coreGCryptId = Just $ genUUIDInNameSpace gCryptNameSpace v
| otherwise = Nothing
checkcommand c = "if which " ++ c ++ "; then " ++ report c ++ "; fi"
token r = "git-annex-probe " ++ r
report r = "echo " ++ shellEscape (token r)
shim = "~/.ssh/git-annex-shell"
getgitconfig (Just d)
| not (null d) = "cd " ++ shellEscape d ++ " && git config --list"
getgitconfig _ = "echo"
{- Runs a ssh command to set up the repository; if it fails shows
- the user the transcript, and if it succeeds, runs an action. -}
sshSetup :: SshInput -> [String] -> SshHost -> String -> Maybe String -> Handler Html -> Handler Html
sshSetup sshinput opts sshhost cmd input a = do
(transcript, ok) <- liftAssistant $ sshAuthTranscript sshinput opts sshhost cmd input
if ok
then do
liftAssistant $ expireCachedCred $ getLogin sshinput
a
else sshErr sshinput transcript
sshErr :: SshInput -> String -> Handler Html
sshErr sshinput msg
| inputAuthMethod sshinput == CachedPassword =
ifM (liftAssistant $ isNothing <$> getCachedCred (getLogin sshinput))
( sshConfigurator $
$(widgetFile "configurators/ssh/expiredpassword")
, showerr
)
| otherwise = showerr
where
showerr = sshConfigurator $
$(widgetFile "configurators/ssh/error")
Runs a ssh command , returning a transcript of its output .
-
- Depending on the SshInput , avoids using a password , or uses a
- cached password . ssh is coaxed to use git - annex as SSH_ASKPASS
- to get the password .
-
- Depending on the SshInput, avoids using a password, or uses a
- cached password. ssh is coaxed to use git-annex as SSH_ASKPASS
- to get the password.
-}
sshAuthTranscript :: SshInput -> [String] -> SshHost -> String -> (Maybe String) -> Assistant (String, Bool)
sshAuthTranscript sshinput opts sshhost cmd input = case inputAuthMethod sshinput of
ExistingSshKey -> liftIO $ go [passwordprompts 0] Nothing
CachedPassword -> setupAskPass
Password -> do
cacheCred (login, geti inputPassword) (Seconds $ 60 * 10)
setupAskPass
where
login = getLogin sshinput
geti f = maybe "" T.unpack (f sshinput)
go extraopts environ = processTranscript'
(askPass environ (proc "ssh" (extraopts ++ opts ++ [fromSshHost sshhost, cmd])))
Always provide stdin , even when empty .
(Just (fromMaybe "" input))
{- ssh will only use SSH_ASKPASS when DISPLAY is set and there
- is no controlling terminal. -}
askPass environ p = p
{ env = environ
#if MIN_VERSION_process(1,3,0)
, detach_console = True
, new_session = True
#endif
}
setupAskPass = do
program <- liftIO programPath
v <- getCachedCred login
liftIO $ case v of
Nothing -> go [passwordprompts 0] Nothing
Just pass -> withTmpFile "ssh" $ \passfile h -> do
hClose h
writeFileProtected passfile pass
environ <- getEnvironment
let environ' = addEntries
[ ("SSH_ASKPASS", program)
, (sshAskPassEnv, passfile)
, ("DISPLAY", ":0")
] environ
go [passwordprompts 1] (Just environ')
passwordprompts :: Int -> String
passwordprompts = sshOpt "NumberOfPasswordPrompts" . show
getLogin :: SshInput -> Login
getLogin sshinput = geti inputUsername ++ "@" ++ geti inputHostname
where
geti f = maybe "" T.unpack (f sshinput)
The UUID will be NoUUID when the repository does not already exist ,
- or was not a git - annex repository before .
- or was not a git-annex repository before. -}
getConfirmSshR :: SshData -> UUID -> Handler Html
getConfirmSshR sshdata u
| u == NoUUID = handlenew
| otherwise = handleexisting =<< (M.lookup u <$> liftAnnex uuidMap)
where
handlenew = sshConfigurator $ do
cmd <- liftAnnex $ gpgCmd <$> Annex.getGitConfig
secretkeys <- sortBy (comparing snd) . M.toList
<$> liftIO (secretKeys cmd)
$(widgetFile "configurators/ssh/confirm")
handleexisting Nothing = sshConfigurator $
-- Not a UUID we know, so prompt about combining.
$(widgetFile "configurators/ssh/combine")
handleexisting (Just _) = prepSsh False sshdata $ \sshdata' -> do
m <- liftAnnex readRemoteLog
case M.lookup "type" =<< M.lookup u m of
Just "gcrypt" -> combineExistingGCrypt sshdata' u
_ -> makeSshRepo ExistingRepo sshdata'
The user has confirmed they want to combine with a ssh repository ,
- which is not known to us . So it might be using .
- which is not known to us. So it might be using gcrypt. -}
getCombineSshR :: SshData -> Handler Html
getCombineSshR sshdata = prepSsh False sshdata $ \sshdata' ->
sshConfigurator $
checkExistingGCrypt sshdata' $
void $ liftH $ makeSshRepo ExistingRepo sshdata'
getRetrySshR :: SshData -> Handler ()
getRetrySshR sshdata = do
s <- liftAssistant $ testServer $ mkSshInput sshdata
redirect $ either (const $ ConfirmSshR sshdata NoUUID) (uncurry ConfirmSshR) s
{- Making a new git repository. -}
getMakeSshGitR :: SshData -> Handler Html
getMakeSshGitR sshdata = prepSsh True sshdata (makeSshRepo NewRepo)
getMakeSshRsyncR :: SshData -> Handler Html
getMakeSshRsyncR sshdata = prepSsh False (rsyncOnly sshdata) (makeSshRepo NewRepo)
rsyncOnly :: SshData -> SshData
rsyncOnly sshdata = sshdata { sshCapabilities = [RsyncCapable] }
getMakeSshGCryptR :: SshData -> RepoKey -> Handler Html
getMakeSshGCryptR sshdata NoRepoKey = whenGcryptInstalled $
withNewSecretKey $ getMakeSshGCryptR sshdata . RepoKey
getMakeSshGCryptR sshdata (RepoKey keyid) = whenGcryptInstalled $
prepSsh False sshdata $ makeGCryptRepo NewRepo keyid
{- Detect if the user entered a location with an existing, known
- gcrypt repository, and enable it. Otherwise, runs the action. -}
checkExistingGCrypt :: SshData -> Widget -> Widget
checkExistingGCrypt sshdata nope = checkGCryptRepoEncryption repourl nope nope $ do
mu <- liftAnnex $ probeGCryptRemoteUUID repourl
case mu of
Just u -> void $ liftH $
combineExistingGCrypt sshdata u
Nothing -> giveup "The location contains a gcrypt repository that is not a git-annex special remote. This is not supported."
where
repourl = genSshUrl sshdata
{- Enables an existing gcrypt special remote. -}
enableGCrypt :: SshData -> RemoteName -> Handler Html
enableGCrypt sshdata reponame = setupRemote postsetup Nothing Nothing mk
where
mk = enableSpecialRemote reponame GCrypt.remote Nothing $
M.fromList [("gitrepo", genSshUrl sshdata)]
postsetup _ = redirect DashboardR
Combining with a gcrypt repository that may not be
- known in remote.log , so probe the repo .
- known in remote.log, so probe the gcrypt repo. -}
combineExistingGCrypt :: SshData -> UUID -> Handler Html
combineExistingGCrypt sshdata u = do
reponame <- liftAnnex $ getGCryptRemoteName u repourl
enableGCrypt sshdata reponame
where
repourl = genSshUrl sshdata
{- Sets up remote repository for ssh, or directory for rsync. -}
prepSsh :: Bool -> SshData -> (SshData -> Handler Html) -> Handler Html
prepSsh needsinit sshdata a
| needsPubKey sshdata = do
(sshdata', keypair) <- liftIO $ setupSshKeyPair sshdata
prepSsh' needsinit sshdata sshdata' (Just keypair) a
| sshPort sshdata /= 22 = do
sshdata' <- liftIO $ setSshConfig sshdata []
prepSsh' needsinit sshdata sshdata' Nothing a
| otherwise = prepSsh' needsinit sshdata sshdata Nothing a
prepSsh' :: Bool -> SshData -> SshData -> Maybe SshKeyPair -> (SshData -> Handler Html) -> Handler Html
prepSsh' needsinit origsshdata sshdata keypair a
| hasCapability sshdata PushCapable = do
{- To ensure the repository is initialized, try to push the
- git-annex branch to it. Then git-annex-shell will see
- the branch and auto-initialize. -}
when needsinit $ do
void $ liftAnnex $ inRepo $ Git.Command.runBool
[ Param "push"
, Param (genSshUrl sshdata)
, Param (fromRef Annex.Branch.name)
]
a sshdata
| otherwise = sshSetup (mkSshInput origsshdata)
[ "-p", show (sshPort origsshdata)
]
(genSshHost (sshHostName origsshdata) (sshUserName origsshdata))
remoteCommand
Nothing (a sshdata)
where
remotedir = T.unpack $ sshDirectory sshdata
remoteCommand = shellWrap $ intercalate "&&" $ catMaybes
[ Just $ "mkdir -p " ++ shellEscape remotedir
, Just $ "cd " ++ shellEscape remotedir
, if rsynconly then Nothing else Just $ unwords
[ "if [ ! -d .git ]; then"
, wrapCommand "git init --bare --shared"
, "&&"
, wrapCommand "git config receive.denyNonFastforwards"
, ";fi"
]
, if needsinit then Just (wrapCommand "git annex init") else Nothing
, if needsPubKey origsshdata
then addAuthorizedKeysCommand (hasCapability origsshdata GitAnnexShellCapable) remotedir . sshPubKey <$> keypair
else Nothing
]
rsynconly = onlyCapability origsshdata RsyncCapable
makeSshRepo :: RepoStatus -> SshData -> Handler Html
makeSshRepo rs sshdata
| onlyCapability sshdata RsyncCapable = setupCloudRemote TransferGroup Nothing mk
| otherwise = makeSshRepoConnection rs mk setup
where
mk = makeSshRemote sshdata
-- Record the location of the ssh remote in the remote log, so it
-- can easily be enabled elsewhere using the webapp.
setup r = do
m <- readRemoteLog
let c = fromMaybe M.empty (M.lookup (Remote.uuid r) m)
let c' = M.insert "location" (genSshUrl sshdata) $
M.insert "type" "git" $
M.insert "name" (fromMaybe (Remote.name r) (M.lookup "name" c)) c
configSet (Remote.uuid r) c'
makeSshRepoConnection :: RepoStatus -> Annex RemoteName -> (Remote -> Annex ()) -> Handler Html
makeSshRepoConnection rs mk setup = setupRemote postsetup mgroup Nothing mk
where
mgroup = case rs of
NewRepo -> Just TransferGroup
ExistingRepo -> Nothing
postsetup r = do
liftAssistant $ sendRemoteControl RELOAD
liftAnnex $ setup r
case rs of
NewRepo -> redirect $ EditNewRepositoryR (Remote.uuid r)
ExistingRepo -> redirect DashboardR
makeGCryptRepo :: RepoStatus -> KeyId -> SshData -> Handler Html
makeGCryptRepo rs keyid sshdata = makeSshRepoConnection rs mk (const noop)
where
mk = makeGCryptRemote (sshRepoName sshdata) (genSshUrl sshdata) keyid
getAddRsyncNetR :: Handler Html
getAddRsyncNetR = postAddRsyncNetR
postAddRsyncNetR :: Handler Html
postAddRsyncNetR = do
((result, form), enctype) <- runFormPostNoToken $
renderBootstrap3 bootstrapFormLayout $ sshInputAForm hostnamefield $
SshInput Nothing Nothing Password Nothing Nothing 22
let showform status = inpage $
$(widgetFile "configurators/rsync.net/add")
case result of
FormSuccess sshinput
| isRsyncNet (inputHostname sshinput) ->
go sshinput
| otherwise ->
showform $ UnusableServer
"That is not a rsync.net host name."
_ -> showform UntestedServer
where
inpage = page "Add a Rsync.net repository" (Just Configuration)
hostnamefield = textField `withExpandableNote` ("Help", help)
help = [whamlet|
<div>
When you sign up for a Rsync.net account, you should receive an #
email from them with the host name and user name to put here.
<div>
The host name will be something like "usw-s001.rsync.net", and the #
user name something like "7491"
|]
go sshinput = do
let reponame = genSshRepoName "rsync.net"
(maybe "" T.unpack $ inputDirectory sshinput)
prepRsyncNet sshinput reponame $ \sshdata -> inpage $
checkExistingGCrypt sshdata $ do
cmd <- liftAnnex $ gpgCmd <$> Annex.getGitConfig
secretkeys <- sortBy (comparing snd) . M.toList
<$> liftIO (secretKeys cmd)
$(widgetFile "configurators/rsync.net/encrypt")
getMakeRsyncNetSharedR :: SshData -> Handler Html
getMakeRsyncNetSharedR = makeSshRepo NewRepo . rsyncOnly
{- Make a new gcrypt special remote on rsync.net. -}
getMakeRsyncNetGCryptR :: SshData -> RepoKey -> Handler Html
getMakeRsyncNetGCryptR sshdata NoRepoKey = whenGcryptInstalled $
withNewSecretKey $ getMakeRsyncNetGCryptR sshdata . RepoKey
getMakeRsyncNetGCryptR sshdata (RepoKey keyid) = whenGcryptInstalled $
sshSetup (mkSshInput sshdata) [] sshhost gitinit Nothing $
makeGCryptRepo NewRepo keyid sshdata
where
sshhost = genSshHost (sshHostName sshdata) (sshUserName sshdata)
gitinit = "git init --bare " ++ T.unpack (sshDirectory sshdata)
enableRsyncNet :: SshInput -> String -> Handler Html
enableRsyncNet sshinput reponame =
prepRsyncNet sshinput reponame $ makeSshRepo ExistingRepo . rsyncOnly
enableRsyncNetGCrypt :: SshInput -> RemoteName -> Handler Html
enableRsyncNetGCrypt sshinput reponame =
prepRsyncNet sshinput reponame $ \sshdata -> whenGcryptInstalled $
checkGCryptRepoEncryption (genSshUrl sshdata) notencrypted notinstalled $
enableGCrypt sshdata reponame
where
notencrypted = giveup "Unexpectedly found a non-encrypted git repository, instead of the expected encrypted git repository."
notinstalled = error "internal"
Prepares rsync.net ssh key and creates the directory that will be
- used on rsync.net . If successful , runs an action with its SshData .
-
- To append the ssh key to rsync.net 's authorized_keys , their
- documentation recommends a dd methodd , where the line is fed
- in to ssh over stdin .
- used on rsync.net. If successful, runs an action with its SshData.
-
- To append the ssh key to rsync.net's authorized_keys, their
- documentation recommends a dd methodd, where the line is fed
- in to ssh over stdin.
-}
prepRsyncNet :: SshInput -> String -> (SshData -> Handler Html) -> Handler Html
prepRsyncNet sshinput reponame a = do
knownhost <- liftIO $ maybe (return False) knownHost (inputHostname sshinput)
(sshdata, keypair) <- liftIO $ setupSshKeyPair $
(mkSshData sshinput)
{ sshRepoName = reponame
, needsPubKey = True
, sshCapabilities = [RsyncCapable]
}
let sshhost = genSshHost (sshHostName sshdata) (sshUserName sshdata)
let torsyncnet
| knownhost = []
| otherwise = [sshOpt "StrictHostKeyChecking" "no"]
I 'd prefer to separate commands with & & , but
- rsync.net 's shell does not support that .
- rsync.net's shell does not support that. -}
let remotecommand = intercalate ";"
[ "mkdir -p .ssh"
, "touch .ssh/authorized_keys"
, "dd of=.ssh/authorized_keys oflag=append conv=notrunc"
, "mkdir -p " ++ T.unpack (sshDirectory sshdata)
]
sshSetup sshinput torsyncnet sshhost remotecommand
(Just $ sshPubKey keypair) (a sshdata)
isRsyncNet :: Maybe Text -> Bool
isRsyncNet Nothing = False
isRsyncNet (Just host) = ".rsync.net" `T.isSuffixOf` T.toLower host
data GitLabUrl = GitLabUrl { unGitLabUrl :: Text }
badGitLabUrl :: Text
badGitLabUrl = "Bad SSH clone url. Expected something like: :yourlogin/annex.git"
parseGitLabUrl :: GitLabUrl -> Maybe SshData
parseGitLabUrl (GitLabUrl t) =
let (u, r) = separate (== '@') (T.unpack t)
(h, p) = separate (== ':') r
in if null u || null h || null p
then Nothing
else Just $ SshData
{ sshHostName = T.pack h
, sshUserName = Just (T.pack u)
, sshDirectory = T.pack p
, sshRepoName = genSshRepoName h p
, sshPort = 22
, needsPubKey = False
, sshCapabilities =
[ GitAnnexShellCapable
, GitCapable
, PushCapable
]
, sshRepoUrl = Just (T.unpack t)
}
isGitLab :: SshData -> Bool
isGitLab d = T.pack "gitlab.com" `T.isSuffixOf` (T.toLower (sshHostName d))
toGitLabUrl :: SshData -> GitLabUrl
toGitLabUrl d = GitLabUrl $ T.concat
[ fromMaybe (T.pack "git") (sshUserName d)
, T.pack "@"
, sshHostName d
, T.pack ":"
, sshDirectory d
]
Try to ssh into the gitlab server , verify we can access the repository ,
- and get the uuid of the repository , if it already has one .
-
- A repository on gitlab wo n't be initialized as a git - annex repo
- unless a git - annex branch was already pushed to it . So , if
- git - annex - shell fails to work that 's probably why ; verify if
- the server is letting us ssh in by running git send - pack
- ( in dry run mode ) .
- and get the uuid of the repository, if it already has one.
-
- A repository on gitlab won't be initialized as a git-annex repo
- unless a git-annex branch was already pushed to it. So, if
- git-annex-shell fails to work that's probably why; verify if
- the server is letting us ssh in by running git send-pack
- (in dry run mode). -}
testGitLabUrl :: GitLabUrl -> Annex (ServerStatus, Maybe SshData, UUID)
testGitLabUrl glu = case parseGitLabUrl glu of
Nothing -> return (UnusableServer badGitLabUrl, Nothing, NoUUID)
Just sshdata ->
checkor sshdata $ do
(sshdata', keypair) <- liftIO $ setupSshKeyPair sshdata
checkor sshdata' $
return (ServerNeedsPubKey (sshPubKey keypair), Just sshdata', NoUUID)
where
checkor sshdata ora = do
u <- probeuuid sshdata
if u /= NoUUID
then return (UsableServer (sshCapabilities sshdata), Just sshdata, u)
else ifM (verifysshworks sshdata)
( return (UsableServer (sshCapabilities sshdata), Just sshdata, NoUUID)
, ora
)
probeuuid sshdata = do
r <- inRepo $ Git.Construct.fromRemoteLocation (fromJust $ sshRepoUrl sshdata)
getUncachedUUID . either (const r) fst <$>
Remote.Helper.Ssh.onRemote NoConsumeStdin r
(Git.Config.fromPipe r, return (Left $ error "configlist failed"))
"configlist" [] []
verifysshworks sshdata = inRepo $ Git.Command.runBool
[ Param "send-pack"
, Param (fromJust $ sshRepoUrl sshdata)
, Param "--dry-run"
, Param "--force"
, Param (fromRef Annex.Branch.name)
]
gitLabUrlAForm :: Maybe GitLabUrl -> AForm Handler GitLabUrl
gitLabUrlAForm defval = GitLabUrl <$> areq check_input (bfs "SSH clone url") (unGitLabUrl <$> defval)
where
check_input = checkBool (isJust . parseGitLabUrl . GitLabUrl)
badGitLabUrl textField
getAddGitLabR :: Handler Html
getAddGitLabR = postAddGitLabR
postAddGitLabR :: Handler Html
postAddGitLabR = promptGitLab Nothing
promptGitLab :: Maybe GitLabUrl -> Handler Html
promptGitLab defval = sshConfigurator $ do
((result, form), enctype) <- liftH $
runFormPostNoToken $ renderBootstrap3 bootstrapFormLayout $
gitLabUrlAForm defval
case result of
FormSuccess gitlaburl -> do
(status, msshdata, u) <- liftAnnex $ testGitLabUrl gitlaburl
case (status, msshdata) of
(UsableServer _, Just sshdata) ->
liftH $ redirect $ ConfirmSshR sshdata u
_ -> showform form enctype status
_ -> showform form enctype UntestedServer
where
showform form enctype status = $(widgetFile "configurators/gitlab.com/add")
enableGitLab :: SshData -> Handler Html
enableGitLab = promptGitLab . Just . toGitLabUrl
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Assistant/WebApp/Configurators/Ssh.hs | haskell | Is a repository a new one that's being created, or did it already exist
and is just being added.
untested
canonicalize input hostname if it had no dot
unchecked
The directory is implicitly in home, so remove any leading ~/
reason why it's not usable
To enable a remote that uses ssh as its transport,
- parse a config key to get its url, and display a form
- to prompt for its password.
To deal with git-annex and possibly even git and rsync not being
- available in the remote server's PATH, when git-annex was installed
- from the standalone tarball etc, look for a ~/.ssh/git-annex-wrapper
- and if it's there, use it to run a command.
If this is an already known host, let
- ssh check it as usual.
- Otherwise, trust the host key.
Runs a ssh command to set up the repository; if it fails shows
- the user the transcript, and if it succeeds, runs an action.
ssh will only use SSH_ASKPASS when DISPLAY is set and there
- is no controlling terminal.
Not a UUID we know, so prompt about combining.
Making a new git repository.
Detect if the user entered a location with an existing, known
- gcrypt repository, and enable it. Otherwise, runs the action.
Enables an existing gcrypt special remote.
Sets up remote repository for ssh, or directory for rsync.
To ensure the repository is initialized, try to push the
- git-annex branch to it. Then git-annex-shell will see
- the branch and auto-initialize.
Record the location of the ssh remote in the remote log, so it
can easily be enabled elsewhere using the webapp.
Make a new gcrypt special remote on rsync.net. | git - annex assistant webapp configurator for ssh - based remotes
-
- Copyright 2012 - 2015 < >
-
- Licensed under the GNU AGPL version 3 or higher .
-
- Copyright 2012-2015 Joey Hess <>
-
- Licensed under the GNU AGPL version 3 or higher.
-}
# LANGUAGE QuasiQuotes , TemplateHaskell , OverloadedStrings #
# LANGUAGE CPP , FlexibleContexts #
module Assistant.WebApp.Configurators.Ssh where
import Assistant.WebApp.Common
import Assistant.WebApp.Gpg
import Assistant.Ssh
import Annex.Ssh
import Assistant.WebApp.MakeRemote
import Logs.Remote
import Remote
import Types.StandardGroups
import Utility.UserInfo
import Utility.Gpg
import Types.Remote (RemoteConfig)
import Git.Types (RemoteName, fromRef)
import qualified Remote.GCrypt as GCrypt
import qualified Annex
import qualified Git.Construct
import qualified Git.Config
import qualified Git.Command
import qualified Remote.Helper.Ssh
import qualified Annex.Branch
import Annex.UUID
import Logs.UUID
import Assistant.RemoteControl
import Types.Creds
import Assistant.CredPairCache
import Annex.Path
import Utility.Tmp
import Utility.FileMode
import Utility.ThreadScheduler
import Utility.Env
import Utility.SshHost
import qualified Data.Text as T
import qualified Data.Map as M
import Network.Socket
import Data.Ord
sshConfigurator :: Widget -> Handler Html
sshConfigurator = page "Add a remote server" (Just Configuration)
data SshInput = SshInput
{ inputHostname :: Maybe Text
, inputUsername :: Maybe Text
, inputAuthMethod :: AuthMethod
, inputPassword :: Maybe Text
, inputDirectory :: Maybe Text
, inputPort :: Int
}
data AuthMethod
= Password
| CachedPassword
| ExistingSshKey
deriving (Eq, Show)
data RepoStatus = NewRepo | ExistingRepo
SshInput is only used for applicative form prompting , this converts
- the result of such a form into a SshData .
- the result of such a form into a SshData. -}
mkSshData :: SshInput -> SshData
mkSshData s = SshData
{ sshHostName = fromMaybe "" $ inputHostname s
, sshUserName = inputUsername s
, sshDirectory = fromMaybe "" $ inputDirectory s
, sshRepoName = genSshRepoName
(T.unpack $ fromJust $ inputHostname s)
(maybe "" T.unpack $ inputDirectory s)
, sshPort = inputPort s
, needsPubKey = False
, sshRepoUrl = Nothing
}
mkSshInput :: SshData -> SshInput
mkSshInput s = SshInput
{ inputHostname = Just $ sshHostName s
, inputUsername = sshUserName s
, inputAuthMethod = if needsPubKey s then CachedPassword else ExistingSshKey
, inputPassword = Nothing
, inputDirectory = Just $ sshDirectory s
, inputPort = sshPort s
}
sshInputAForm :: Field Handler Text -> SshInput -> AForm Handler SshInput
sshInputAForm hostnamefield d = normalize <$> gen
where
gen = SshInput
<$> aopt check_hostname (bfs "Host name") (Just $ inputHostname d)
<*> aopt check_username (bfs "User name") (Just $ inputUsername d)
<*> areq (selectFieldList authmethods) (bfs "Authenticate with") (Just $ inputAuthMethod d)
<*> aopt passwordField (bfs "Password") Nothing
<*> aopt textField (bfs "Directory") (Just $ Just $ fromMaybe (T.pack gitAnnexAssistantDefaultDir) $ inputDirectory d)
<*> areq intField (bfs "Port") (Just $ inputPort d)
authmethods :: [(Text, AuthMethod)]
authmethods =
[ ("password", Password)
, ("existing ssh key", ExistingSshKey)
]
check_username = checkBool (all (`notElem` ("/:@ \t" :: String)) . T.unpack)
bad_username textField
bad_username = "bad user name" :: Text
#ifndef __ANDROID__
bad_hostname = "cannot resolve host name" :: Text
check_hostname = checkM (liftIO . checkdns) hostnamefield
checkdns t = do
let h = T.unpack t
let canonname = Just $ defaultHints { addrFlags = [AI_CANONNAME] }
r <- catchMaybeIO $ getAddrInfo canonname (Just h) Nothing
return $ case mapMaybe addrCanonName <$> r of
Just (fullname:_)
| '.' `elem` h -> Right t
| otherwise -> Right $ T.pack fullname
Just [] -> Right t
Nothing -> Left bad_hostname
#else
getAddrInfo currently broken on Android
#endif
normalize i = i { inputDirectory = normalizedir <$> inputDirectory i }
normalizedir dir
| "~/" `T.isPrefixOf` dir = T.drop 2 dir
| "/~/" `T.isPrefixOf` dir = T.drop 3 dir
| otherwise = dir
data ServerStatus
= UntestedServer
| ServerNeedsPubKey SshPubKey
| UsableServer [SshServerCapability]
deriving (Eq)
capabilities :: ServerStatus -> [SshServerCapability]
capabilities (UsableServer cs) = cs
capabilities _ = []
getAddSshR :: Handler Html
getAddSshR = postAddSshR
postAddSshR :: Handler Html
postAddSshR = sshConfigurator $ do
username <- liftIO $ either (const Nothing) (Just . T.pack) <$> myUserName
((result, form), enctype) <- liftH $
runFormPostNoToken $ renderBootstrap3 bootstrapFormLayout $ sshInputAForm textField $
SshInput Nothing username Password Nothing Nothing 22
case result of
FormSuccess sshinput -> do
s <- liftAssistant $ testServer sshinput
case s of
Left status -> showform form enctype status
Right (sshdata, u) -> liftH $ redirect $ ConfirmSshR sshdata u
_ -> showform form enctype UntestedServer
where
showform form enctype status = $(widgetFile "configurators/ssh/add")
sshTestModal :: Widget
sshTestModal = $(widgetFile "configurators/ssh/testmodal")
sshSetupModal :: SshData -> Widget
sshSetupModal sshdata = $(widgetFile "configurators/ssh/setupmodal")
getEnableRsyncR :: UUID -> Handler Html
getEnableRsyncR = postEnableRsyncR
postEnableRsyncR :: UUID -> Handler Html
postEnableRsyncR = enableSshRemote getsshinput enableRsyncNet enablersync
where
enablersync sshdata u = redirect $ ConfirmSshR
(sshdata { sshCapabilities = [RsyncCapable] }) u
getsshinput = parseSshUrl <=< M.lookup "rsyncurl"
This only handles repositories that are located on ssh servers ;
- ones on local drives are handled via another part of the UI .
- ones on local drives are handled via another part of the UI. -}
getEnableSshGCryptR :: UUID -> Handler Html
getEnableSshGCryptR = postEnableSshGCryptR
postEnableSshGCryptR :: UUID -> Handler Html
postEnableSshGCryptR u = whenGcryptInstalled $
enableSshRemote getsshinput enableRsyncNetGCrypt enablegcrypt u
where
enablegcrypt sshdata _ = prepSsh False sshdata $ \sshdata' ->
sshConfigurator $
checkExistingGCrypt sshdata' $
giveup "Expected to find an encrypted git repository, but did not."
getsshinput = parseSshUrl <=< M.lookup "gitrepo"
getEnableSshGitRemoteR :: UUID -> Handler Html
getEnableSshGitRemoteR = postEnableSshGitRemoteR
postEnableSshGitRemoteR :: UUID -> Handler Html
postEnableSshGitRemoteR = enableSshRemote getsshinput enableRsyncNet enablesshgitremote
where
enablesshgitremote sshdata u = redirect $ ConfirmSshR sshdata u
getsshinput = parseSshUrl <=< M.lookup "location"
enableSshRemote :: (RemoteConfig -> Maybe SshData) -> (SshInput -> RemoteName -> Handler Html) -> (SshData -> UUID -> Handler Html) -> UUID -> Handler Html
enableSshRemote getsshdata rsyncnetsetup genericsetup u = do
m <- fromMaybe M.empty . M.lookup u <$> liftAnnex readRemoteLog
case (unmangle <$> getsshdata m, M.lookup "name" m) of
(Just sshdata, Just reponame)
| isGitLab sshdata -> enableGitLab sshdata
| otherwise -> sshConfigurator $ do
((result, form), enctype) <- liftH $
runFormPostNoToken $ renderBootstrap3 bootstrapFormLayout $
sshInputAForm textField $ mkSshInput sshdata
case result of
FormSuccess sshinput
| isRsyncNet (inputHostname sshinput) ->
void $ liftH $ rsyncnetsetup sshinput reponame
| otherwise -> do
s <- liftAssistant $ testServer sshinput
case s of
Left status -> showform form enctype status
Right (sshdata', _u) -> void $ liftH $ genericsetup
( sshdata' { sshRepoName = reponame } ) u
_ -> showform form enctype UntestedServer
_ -> redirect AddSshR
where
unmangle sshdata = sshdata
{ sshHostName = T.pack $ unMangleSshHostName $
T.unpack $ sshHostName sshdata
}
showform form enctype status = do
description <- liftAnnex $ T.pack <$> prettyUUID u
$(widgetFile "configurators/ssh/enable")
wrapCommand :: String -> String
wrapCommand cmd = "if [ -x " ++ commandWrapper ++ " ]; then " ++ commandWrapper ++ " " ++ cmd ++ "; else " ++ cmd ++ "; fi"
commandWrapper :: String
commandWrapper = "~/.ssh/git-annex-wrapper"
Test if we can ssh into the server , using the specified .
-
- Once logged into the server , probe to see if git - annex - shell ,
- git , and rsync are available .
-
- Note that ~/.ssh / git - annex - shell may be present , while
- git - annex - shell is not in PATH .
- Also , git and rsync may not be in PATH ; as long as the commandWrapper
- is present , assume it is able to be used to run them .
-
- Also probe to see if there is already a git repository at the location
- with either an annex - uuid or a gcrypt - id set . ( If not , returns NoUUID . )
-
- Once logged into the server, probe to see if git-annex-shell,
- git, and rsync are available.
-
- Note that ~/.ssh/git-annex-shell may be present, while
- git-annex-shell is not in PATH.
- Also, git and rsync may not be in PATH; as long as the commandWrapper
- is present, assume it is able to be used to run them.
-
- Also probe to see if there is already a git repository at the location
- with either an annex-uuid or a gcrypt-id set. (If not, returns NoUUID.)
-}
testServer :: SshInput -> Assistant (Either ServerStatus (SshData, UUID))
testServer (SshInput { inputHostname = Nothing }) = return $
Left $ UnusableServer "Please enter a host name."
testServer sshinput@(SshInput { inputHostname = Just hn }) = do
(status, u) <- probe
case capabilities status of
[] -> return $ Left status
cs -> do
let sshdata = (mkSshData sshinput)
{ needsPubKey = inputAuthMethod sshinput /= ExistingSshKey
, sshCapabilities = cs
}
return $ Right (sshdata, u)
where
probe = do
let remotecommand = shellWrap $ intercalate ";"
[ report "loggedin"
, checkcommand "git-annex-shell"
, checkcommand "git"
, checkcommand "rsync"
, checkcommand shim
, checkcommand commandWrapper
, getgitconfig (T.unpack <$> inputDirectory sshinput)
]
knownhost <- liftIO $ knownHost hn
let sshopts =
[ sshOpt "StrictHostKeyChecking" $
if knownhost then "yes" else "no"
do n't read from stdin
, "-p", show (inputPort sshinput)
]
let sshhost = genSshHost
(fromJust $ inputHostname sshinput)
(inputUsername sshinput)
parsetranscript . fst <$> sshAuthTranscript sshinput sshopts sshhost remotecommand Nothing
parsetranscript s =
let cs = map snd $ filter (reported . fst)
[ ("git-annex-shell", GitAnnexShellCapable)
, (shim, GitAnnexShellCapable)
, ("git", GitCapable)
, ("rsync", RsyncCapable)
, (commandWrapper, GitCapable)
, (commandWrapper, RsyncCapable)
]
u = fromMaybe NoUUID $ headMaybe $ mapMaybe finduuid $
map (separate (== '=')) $ lines s
in if null cs
then (UnusableServer unusablereason, u)
else (UsableServer cs, u)
where
reported r = token r `isInfixOf` s
unusablereason = if reported "loggedin"
then "Neither rsync nor git-annex are installed on the server. Perhaps you should go install them?"
else T.pack $ "Failed to ssh to the server. Transcript: " ++ s
finduuid (k, v)
| k == "annex.uuid" = Just $ toUUID v
| k == GCrypt.coreGCryptId = Just $ genUUIDInNameSpace gCryptNameSpace v
| otherwise = Nothing
checkcommand c = "if which " ++ c ++ "; then " ++ report c ++ "; fi"
token r = "git-annex-probe " ++ r
report r = "echo " ++ shellEscape (token r)
shim = "~/.ssh/git-annex-shell"
getgitconfig (Just d)
| not (null d) = "cd " ++ shellEscape d ++ " && git config --list"
getgitconfig _ = "echo"
sshSetup :: SshInput -> [String] -> SshHost -> String -> Maybe String -> Handler Html -> Handler Html
sshSetup sshinput opts sshhost cmd input a = do
(transcript, ok) <- liftAssistant $ sshAuthTranscript sshinput opts sshhost cmd input
if ok
then do
liftAssistant $ expireCachedCred $ getLogin sshinput
a
else sshErr sshinput transcript
sshErr :: SshInput -> String -> Handler Html
sshErr sshinput msg
| inputAuthMethod sshinput == CachedPassword =
ifM (liftAssistant $ isNothing <$> getCachedCred (getLogin sshinput))
( sshConfigurator $
$(widgetFile "configurators/ssh/expiredpassword")
, showerr
)
| otherwise = showerr
where
showerr = sshConfigurator $
$(widgetFile "configurators/ssh/error")
Runs a ssh command , returning a transcript of its output .
-
- Depending on the SshInput , avoids using a password , or uses a
- cached password . ssh is coaxed to use git - annex as SSH_ASKPASS
- to get the password .
-
- Depending on the SshInput, avoids using a password, or uses a
- cached password. ssh is coaxed to use git-annex as SSH_ASKPASS
- to get the password.
-}
sshAuthTranscript :: SshInput -> [String] -> SshHost -> String -> (Maybe String) -> Assistant (String, Bool)
sshAuthTranscript sshinput opts sshhost cmd input = case inputAuthMethod sshinput of
ExistingSshKey -> liftIO $ go [passwordprompts 0] Nothing
CachedPassword -> setupAskPass
Password -> do
cacheCred (login, geti inputPassword) (Seconds $ 60 * 10)
setupAskPass
where
login = getLogin sshinput
geti f = maybe "" T.unpack (f sshinput)
go extraopts environ = processTranscript'
(askPass environ (proc "ssh" (extraopts ++ opts ++ [fromSshHost sshhost, cmd])))
Always provide stdin , even when empty .
(Just (fromMaybe "" input))
askPass environ p = p
{ env = environ
#if MIN_VERSION_process(1,3,0)
, detach_console = True
, new_session = True
#endif
}
setupAskPass = do
program <- liftIO programPath
v <- getCachedCred login
liftIO $ case v of
Nothing -> go [passwordprompts 0] Nothing
Just pass -> withTmpFile "ssh" $ \passfile h -> do
hClose h
writeFileProtected passfile pass
environ <- getEnvironment
let environ' = addEntries
[ ("SSH_ASKPASS", program)
, (sshAskPassEnv, passfile)
, ("DISPLAY", ":0")
] environ
go [passwordprompts 1] (Just environ')
passwordprompts :: Int -> String
passwordprompts = sshOpt "NumberOfPasswordPrompts" . show
getLogin :: SshInput -> Login
getLogin sshinput = geti inputUsername ++ "@" ++ geti inputHostname
where
geti f = maybe "" T.unpack (f sshinput)
The UUID will be NoUUID when the repository does not already exist ,
- or was not a git - annex repository before .
- or was not a git-annex repository before. -}
getConfirmSshR :: SshData -> UUID -> Handler Html
getConfirmSshR sshdata u
| u == NoUUID = handlenew
| otherwise = handleexisting =<< (M.lookup u <$> liftAnnex uuidMap)
where
handlenew = sshConfigurator $ do
cmd <- liftAnnex $ gpgCmd <$> Annex.getGitConfig
secretkeys <- sortBy (comparing snd) . M.toList
<$> liftIO (secretKeys cmd)
$(widgetFile "configurators/ssh/confirm")
handleexisting Nothing = sshConfigurator $
$(widgetFile "configurators/ssh/combine")
handleexisting (Just _) = prepSsh False sshdata $ \sshdata' -> do
m <- liftAnnex readRemoteLog
case M.lookup "type" =<< M.lookup u m of
Just "gcrypt" -> combineExistingGCrypt sshdata' u
_ -> makeSshRepo ExistingRepo sshdata'
The user has confirmed they want to combine with a ssh repository ,
- which is not known to us . So it might be using .
- which is not known to us. So it might be using gcrypt. -}
getCombineSshR :: SshData -> Handler Html
getCombineSshR sshdata = prepSsh False sshdata $ \sshdata' ->
sshConfigurator $
checkExistingGCrypt sshdata' $
void $ liftH $ makeSshRepo ExistingRepo sshdata'
getRetrySshR :: SshData -> Handler ()
getRetrySshR sshdata = do
s <- liftAssistant $ testServer $ mkSshInput sshdata
redirect $ either (const $ ConfirmSshR sshdata NoUUID) (uncurry ConfirmSshR) s
getMakeSshGitR :: SshData -> Handler Html
getMakeSshGitR sshdata = prepSsh True sshdata (makeSshRepo NewRepo)
getMakeSshRsyncR :: SshData -> Handler Html
getMakeSshRsyncR sshdata = prepSsh False (rsyncOnly sshdata) (makeSshRepo NewRepo)
rsyncOnly :: SshData -> SshData
rsyncOnly sshdata = sshdata { sshCapabilities = [RsyncCapable] }
getMakeSshGCryptR :: SshData -> RepoKey -> Handler Html
getMakeSshGCryptR sshdata NoRepoKey = whenGcryptInstalled $
withNewSecretKey $ getMakeSshGCryptR sshdata . RepoKey
getMakeSshGCryptR sshdata (RepoKey keyid) = whenGcryptInstalled $
prepSsh False sshdata $ makeGCryptRepo NewRepo keyid
checkExistingGCrypt :: SshData -> Widget -> Widget
checkExistingGCrypt sshdata nope = checkGCryptRepoEncryption repourl nope nope $ do
mu <- liftAnnex $ probeGCryptRemoteUUID repourl
case mu of
Just u -> void $ liftH $
combineExistingGCrypt sshdata u
Nothing -> giveup "The location contains a gcrypt repository that is not a git-annex special remote. This is not supported."
where
repourl = genSshUrl sshdata
enableGCrypt :: SshData -> RemoteName -> Handler Html
enableGCrypt sshdata reponame = setupRemote postsetup Nothing Nothing mk
where
mk = enableSpecialRemote reponame GCrypt.remote Nothing $
M.fromList [("gitrepo", genSshUrl sshdata)]
postsetup _ = redirect DashboardR
Combining with a gcrypt repository that may not be
- known in remote.log , so probe the repo .
- known in remote.log, so probe the gcrypt repo. -}
combineExistingGCrypt :: SshData -> UUID -> Handler Html
combineExistingGCrypt sshdata u = do
reponame <- liftAnnex $ getGCryptRemoteName u repourl
enableGCrypt sshdata reponame
where
repourl = genSshUrl sshdata
prepSsh :: Bool -> SshData -> (SshData -> Handler Html) -> Handler Html
prepSsh needsinit sshdata a
| needsPubKey sshdata = do
(sshdata', keypair) <- liftIO $ setupSshKeyPair sshdata
prepSsh' needsinit sshdata sshdata' (Just keypair) a
| sshPort sshdata /= 22 = do
sshdata' <- liftIO $ setSshConfig sshdata []
prepSsh' needsinit sshdata sshdata' Nothing a
| otherwise = prepSsh' needsinit sshdata sshdata Nothing a
prepSsh' :: Bool -> SshData -> SshData -> Maybe SshKeyPair -> (SshData -> Handler Html) -> Handler Html
prepSsh' needsinit origsshdata sshdata keypair a
| hasCapability sshdata PushCapable = do
when needsinit $ do
void $ liftAnnex $ inRepo $ Git.Command.runBool
[ Param "push"
, Param (genSshUrl sshdata)
, Param (fromRef Annex.Branch.name)
]
a sshdata
| otherwise = sshSetup (mkSshInput origsshdata)
[ "-p", show (sshPort origsshdata)
]
(genSshHost (sshHostName origsshdata) (sshUserName origsshdata))
remoteCommand
Nothing (a sshdata)
where
remotedir = T.unpack $ sshDirectory sshdata
remoteCommand = shellWrap $ intercalate "&&" $ catMaybes
[ Just $ "mkdir -p " ++ shellEscape remotedir
, Just $ "cd " ++ shellEscape remotedir
, if rsynconly then Nothing else Just $ unwords
[ "if [ ! -d .git ]; then"
, wrapCommand "git init --bare --shared"
, "&&"
, wrapCommand "git config receive.denyNonFastforwards"
, ";fi"
]
, if needsinit then Just (wrapCommand "git annex init") else Nothing
, if needsPubKey origsshdata
then addAuthorizedKeysCommand (hasCapability origsshdata GitAnnexShellCapable) remotedir . sshPubKey <$> keypair
else Nothing
]
rsynconly = onlyCapability origsshdata RsyncCapable
makeSshRepo :: RepoStatus -> SshData -> Handler Html
makeSshRepo rs sshdata
| onlyCapability sshdata RsyncCapable = setupCloudRemote TransferGroup Nothing mk
| otherwise = makeSshRepoConnection rs mk setup
where
mk = makeSshRemote sshdata
setup r = do
m <- readRemoteLog
let c = fromMaybe M.empty (M.lookup (Remote.uuid r) m)
let c' = M.insert "location" (genSshUrl sshdata) $
M.insert "type" "git" $
M.insert "name" (fromMaybe (Remote.name r) (M.lookup "name" c)) c
configSet (Remote.uuid r) c'
makeSshRepoConnection :: RepoStatus -> Annex RemoteName -> (Remote -> Annex ()) -> Handler Html
makeSshRepoConnection rs mk setup = setupRemote postsetup mgroup Nothing mk
where
mgroup = case rs of
NewRepo -> Just TransferGroup
ExistingRepo -> Nothing
postsetup r = do
liftAssistant $ sendRemoteControl RELOAD
liftAnnex $ setup r
case rs of
NewRepo -> redirect $ EditNewRepositoryR (Remote.uuid r)
ExistingRepo -> redirect DashboardR
makeGCryptRepo :: RepoStatus -> KeyId -> SshData -> Handler Html
makeGCryptRepo rs keyid sshdata = makeSshRepoConnection rs mk (const noop)
where
mk = makeGCryptRemote (sshRepoName sshdata) (genSshUrl sshdata) keyid
getAddRsyncNetR :: Handler Html
getAddRsyncNetR = postAddRsyncNetR
postAddRsyncNetR :: Handler Html
postAddRsyncNetR = do
((result, form), enctype) <- runFormPostNoToken $
renderBootstrap3 bootstrapFormLayout $ sshInputAForm hostnamefield $
SshInput Nothing Nothing Password Nothing Nothing 22
let showform status = inpage $
$(widgetFile "configurators/rsync.net/add")
case result of
FormSuccess sshinput
| isRsyncNet (inputHostname sshinput) ->
go sshinput
| otherwise ->
showform $ UnusableServer
"That is not a rsync.net host name."
_ -> showform UntestedServer
where
inpage = page "Add a Rsync.net repository" (Just Configuration)
hostnamefield = textField `withExpandableNote` ("Help", help)
help = [whamlet|
<div>
When you sign up for a Rsync.net account, you should receive an #
email from them with the host name and user name to put here.
<div>
The host name will be something like "usw-s001.rsync.net", and the #
user name something like "7491"
|]
go sshinput = do
let reponame = genSshRepoName "rsync.net"
(maybe "" T.unpack $ inputDirectory sshinput)
prepRsyncNet sshinput reponame $ \sshdata -> inpage $
checkExistingGCrypt sshdata $ do
cmd <- liftAnnex $ gpgCmd <$> Annex.getGitConfig
secretkeys <- sortBy (comparing snd) . M.toList
<$> liftIO (secretKeys cmd)
$(widgetFile "configurators/rsync.net/encrypt")
getMakeRsyncNetSharedR :: SshData -> Handler Html
getMakeRsyncNetSharedR = makeSshRepo NewRepo . rsyncOnly
getMakeRsyncNetGCryptR :: SshData -> RepoKey -> Handler Html
getMakeRsyncNetGCryptR sshdata NoRepoKey = whenGcryptInstalled $
withNewSecretKey $ getMakeRsyncNetGCryptR sshdata . RepoKey
getMakeRsyncNetGCryptR sshdata (RepoKey keyid) = whenGcryptInstalled $
sshSetup (mkSshInput sshdata) [] sshhost gitinit Nothing $
makeGCryptRepo NewRepo keyid sshdata
where
sshhost = genSshHost (sshHostName sshdata) (sshUserName sshdata)
gitinit = "git init --bare " ++ T.unpack (sshDirectory sshdata)
enableRsyncNet :: SshInput -> String -> Handler Html
enableRsyncNet sshinput reponame =
prepRsyncNet sshinput reponame $ makeSshRepo ExistingRepo . rsyncOnly
enableRsyncNetGCrypt :: SshInput -> RemoteName -> Handler Html
enableRsyncNetGCrypt sshinput reponame =
prepRsyncNet sshinput reponame $ \sshdata -> whenGcryptInstalled $
checkGCryptRepoEncryption (genSshUrl sshdata) notencrypted notinstalled $
enableGCrypt sshdata reponame
where
notencrypted = giveup "Unexpectedly found a non-encrypted git repository, instead of the expected encrypted git repository."
notinstalled = error "internal"
Prepares rsync.net ssh key and creates the directory that will be
- used on rsync.net . If successful , runs an action with its SshData .
-
- To append the ssh key to rsync.net 's authorized_keys , their
- documentation recommends a dd methodd , where the line is fed
- in to ssh over stdin .
- used on rsync.net. If successful, runs an action with its SshData.
-
- To append the ssh key to rsync.net's authorized_keys, their
- documentation recommends a dd methodd, where the line is fed
- in to ssh over stdin.
-}
prepRsyncNet :: SshInput -> String -> (SshData -> Handler Html) -> Handler Html
prepRsyncNet sshinput reponame a = do
knownhost <- liftIO $ maybe (return False) knownHost (inputHostname sshinput)
(sshdata, keypair) <- liftIO $ setupSshKeyPair $
(mkSshData sshinput)
{ sshRepoName = reponame
, needsPubKey = True
, sshCapabilities = [RsyncCapable]
}
let sshhost = genSshHost (sshHostName sshdata) (sshUserName sshdata)
let torsyncnet
| knownhost = []
| otherwise = [sshOpt "StrictHostKeyChecking" "no"]
I 'd prefer to separate commands with & & , but
- rsync.net 's shell does not support that .
- rsync.net's shell does not support that. -}
let remotecommand = intercalate ";"
[ "mkdir -p .ssh"
, "touch .ssh/authorized_keys"
, "dd of=.ssh/authorized_keys oflag=append conv=notrunc"
, "mkdir -p " ++ T.unpack (sshDirectory sshdata)
]
sshSetup sshinput torsyncnet sshhost remotecommand
(Just $ sshPubKey keypair) (a sshdata)
isRsyncNet :: Maybe Text -> Bool
isRsyncNet Nothing = False
isRsyncNet (Just host) = ".rsync.net" `T.isSuffixOf` T.toLower host
data GitLabUrl = GitLabUrl { unGitLabUrl :: Text }
badGitLabUrl :: Text
badGitLabUrl = "Bad SSH clone url. Expected something like: :yourlogin/annex.git"
parseGitLabUrl :: GitLabUrl -> Maybe SshData
parseGitLabUrl (GitLabUrl t) =
let (u, r) = separate (== '@') (T.unpack t)
(h, p) = separate (== ':') r
in if null u || null h || null p
then Nothing
else Just $ SshData
{ sshHostName = T.pack h
, sshUserName = Just (T.pack u)
, sshDirectory = T.pack p
, sshRepoName = genSshRepoName h p
, sshPort = 22
, needsPubKey = False
, sshCapabilities =
[ GitAnnexShellCapable
, GitCapable
, PushCapable
]
, sshRepoUrl = Just (T.unpack t)
}
isGitLab :: SshData -> Bool
isGitLab d = T.pack "gitlab.com" `T.isSuffixOf` (T.toLower (sshHostName d))
toGitLabUrl :: SshData -> GitLabUrl
toGitLabUrl d = GitLabUrl $ T.concat
[ fromMaybe (T.pack "git") (sshUserName d)
, T.pack "@"
, sshHostName d
, T.pack ":"
, sshDirectory d
]
Try to ssh into the gitlab server , verify we can access the repository ,
- and get the uuid of the repository , if it already has one .
-
- A repository on gitlab wo n't be initialized as a git - annex repo
- unless a git - annex branch was already pushed to it . So , if
- git - annex - shell fails to work that 's probably why ; verify if
- the server is letting us ssh in by running git send - pack
- ( in dry run mode ) .
- and get the uuid of the repository, if it already has one.
-
- A repository on gitlab won't be initialized as a git-annex repo
- unless a git-annex branch was already pushed to it. So, if
- git-annex-shell fails to work that's probably why; verify if
- the server is letting us ssh in by running git send-pack
- (in dry run mode). -}
testGitLabUrl :: GitLabUrl -> Annex (ServerStatus, Maybe SshData, UUID)
testGitLabUrl glu = case parseGitLabUrl glu of
Nothing -> return (UnusableServer badGitLabUrl, Nothing, NoUUID)
Just sshdata ->
checkor sshdata $ do
(sshdata', keypair) <- liftIO $ setupSshKeyPair sshdata
checkor sshdata' $
return (ServerNeedsPubKey (sshPubKey keypair), Just sshdata', NoUUID)
where
checkor sshdata ora = do
u <- probeuuid sshdata
if u /= NoUUID
then return (UsableServer (sshCapabilities sshdata), Just sshdata, u)
else ifM (verifysshworks sshdata)
( return (UsableServer (sshCapabilities sshdata), Just sshdata, NoUUID)
, ora
)
probeuuid sshdata = do
r <- inRepo $ Git.Construct.fromRemoteLocation (fromJust $ sshRepoUrl sshdata)
getUncachedUUID . either (const r) fst <$>
Remote.Helper.Ssh.onRemote NoConsumeStdin r
(Git.Config.fromPipe r, return (Left $ error "configlist failed"))
"configlist" [] []
verifysshworks sshdata = inRepo $ Git.Command.runBool
[ Param "send-pack"
, Param (fromJust $ sshRepoUrl sshdata)
, Param "--dry-run"
, Param "--force"
, Param (fromRef Annex.Branch.name)
]
gitLabUrlAForm :: Maybe GitLabUrl -> AForm Handler GitLabUrl
gitLabUrlAForm defval = GitLabUrl <$> areq check_input (bfs "SSH clone url") (unGitLabUrl <$> defval)
where
check_input = checkBool (isJust . parseGitLabUrl . GitLabUrl)
badGitLabUrl textField
getAddGitLabR :: Handler Html
getAddGitLabR = postAddGitLabR
postAddGitLabR :: Handler Html
postAddGitLabR = promptGitLab Nothing
promptGitLab :: Maybe GitLabUrl -> Handler Html
promptGitLab defval = sshConfigurator $ do
((result, form), enctype) <- liftH $
runFormPostNoToken $ renderBootstrap3 bootstrapFormLayout $
gitLabUrlAForm defval
case result of
FormSuccess gitlaburl -> do
(status, msshdata, u) <- liftAnnex $ testGitLabUrl gitlaburl
case (status, msshdata) of
(UsableServer _, Just sshdata) ->
liftH $ redirect $ ConfirmSshR sshdata u
_ -> showform form enctype status
_ -> showform form enctype UntestedServer
where
showform form enctype status = $(widgetFile "configurators/gitlab.com/add")
enableGitLab :: SshData -> Handler Html
enableGitLab = promptGitLab . Just . toGitLabUrl
|
9fd4318a8b7e2f5707217640291b84561dc71703681e6a6ec350f16656e8e521 | facebook/flow | keywords.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.
*)
type context_node =
| Statement
| Expression
| ExpressionStatement
| BindingIdentifier
| Class
| Member
| ObjectKey
| Type
(* TODO: include `of`, `in`, and `instanceof`. We don't currently autocomplete at positions where those are valid. *)
(* true, false, and null are not included here, because we already suggest those when we have type info *)
let expression_keywords =
["async"; "await"; "class"; "delete"; "function"; "import"; "new"; "typeof"; "void"; "yield"]
let statement_keywords =
[
"break";
"case";
"catch";
"const";
"continue";
"debugger";
"declare";
"default";
"do";
"else";
"enum";
"export";
"extends";
"finally";
"for";
"if";
"implements";
"interface";
"let";
"opaque";
"return";
"static";
"switch";
"throw";
"try";
"type";
"var";
"void";
"while";
]
exception Found of context_node list
class mapper target =
object (this)
inherit [Loc.t] Flow_ast_contains_mapper.mapper as super
method loc_annot_contains_target annot = Loc.contains annot target
method private is_target = Loc.equal target
val mutable context = []
method private with_context : 'a. context_node -> (unit -> 'a) -> 'a =
fun node f ->
let old_context = context in
context <- node :: context;
let result = f () in
context <- old_context;
result
method! expression expr = this#with_context Expression (fun () -> super#expression expr)
method! statement stmt = this#with_context Statement (fun () -> super#statement stmt)
method! expression_statement loc stmt =
this#with_context ExpressionStatement (fun () -> super#expression_statement loc stmt)
method! binding_type_identifier id =
this#with_context BindingIdentifier (fun () -> super#binding_type_identifier id)
method! pattern_identifier ?kind id =
this#with_context BindingIdentifier (fun () -> super#pattern_identifier ?kind id)
method! class_ loc cls = this#with_context Class (fun () -> super#class_ loc cls)
method! member_property expr = this#with_context Member (fun () -> super#member_property expr)
method! object_key key = this#with_context ObjectKey (fun () -> super#object_key key)
method! type_ t = this#with_context Type (fun () -> super#type_ t)
method! identifier (loc, id) =
if this#is_target loc then raise (Found context);
super#identifier (loc, id)
end
let completion_item_of_keyword loc keyword =
{
ServerProt.Response.Completion.kind = Some Lsp.Completion.Keyword;
name = keyword;
labelDetail = None;
description = None;
itemDetail = None;
text_edit = Some { ServerProt.Response.newText = keyword; insert = loc; replace = loc };
additional_text_edits = [];
sort_text = Some (Printf.sprintf "%020u" 0);
preselect = false;
documentation = None;
tags = None;
log_info = "keyword";
insert_text_format = Lsp.Completion.PlainText;
}
let keywords_of_context loc context =
let keywords =
match context with
| Expression :: ExpressionStatement :: _ ->
Base.List.append expression_keywords statement_keywords
| Expression :: Member :: _ -> []
| Expression :: _ -> expression_keywords
| Statement :: _ -> statement_keywords
| _ -> []
in
Base.List.map ~f:(completion_item_of_keyword loc) keywords
let keywords_at_loc ast loc =
let mapper = new mapper loc in
try
ignore (mapper#program ast);
[]
with
| Found context -> keywords_of_context loc context
| null | https://raw.githubusercontent.com/facebook/flow/f7d50bb772462888b27b5dbf9acf7d079eb1ff5f/src/services/autocomplete/keywords.ml | ocaml | TODO: include `of`, `in`, and `instanceof`. We don't currently autocomplete at positions where those are valid.
true, false, and null are not included here, because we already suggest those when we have type info |
* 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.
*)
type context_node =
| Statement
| Expression
| ExpressionStatement
| BindingIdentifier
| Class
| Member
| ObjectKey
| Type
let expression_keywords =
["async"; "await"; "class"; "delete"; "function"; "import"; "new"; "typeof"; "void"; "yield"]
let statement_keywords =
[
"break";
"case";
"catch";
"const";
"continue";
"debugger";
"declare";
"default";
"do";
"else";
"enum";
"export";
"extends";
"finally";
"for";
"if";
"implements";
"interface";
"let";
"opaque";
"return";
"static";
"switch";
"throw";
"try";
"type";
"var";
"void";
"while";
]
exception Found of context_node list
class mapper target =
object (this)
inherit [Loc.t] Flow_ast_contains_mapper.mapper as super
method loc_annot_contains_target annot = Loc.contains annot target
method private is_target = Loc.equal target
val mutable context = []
method private with_context : 'a. context_node -> (unit -> 'a) -> 'a =
fun node f ->
let old_context = context in
context <- node :: context;
let result = f () in
context <- old_context;
result
method! expression expr = this#with_context Expression (fun () -> super#expression expr)
method! statement stmt = this#with_context Statement (fun () -> super#statement stmt)
method! expression_statement loc stmt =
this#with_context ExpressionStatement (fun () -> super#expression_statement loc stmt)
method! binding_type_identifier id =
this#with_context BindingIdentifier (fun () -> super#binding_type_identifier id)
method! pattern_identifier ?kind id =
this#with_context BindingIdentifier (fun () -> super#pattern_identifier ?kind id)
method! class_ loc cls = this#with_context Class (fun () -> super#class_ loc cls)
method! member_property expr = this#with_context Member (fun () -> super#member_property expr)
method! object_key key = this#with_context ObjectKey (fun () -> super#object_key key)
method! type_ t = this#with_context Type (fun () -> super#type_ t)
method! identifier (loc, id) =
if this#is_target loc then raise (Found context);
super#identifier (loc, id)
end
let completion_item_of_keyword loc keyword =
{
ServerProt.Response.Completion.kind = Some Lsp.Completion.Keyword;
name = keyword;
labelDetail = None;
description = None;
itemDetail = None;
text_edit = Some { ServerProt.Response.newText = keyword; insert = loc; replace = loc };
additional_text_edits = [];
sort_text = Some (Printf.sprintf "%020u" 0);
preselect = false;
documentation = None;
tags = None;
log_info = "keyword";
insert_text_format = Lsp.Completion.PlainText;
}
let keywords_of_context loc context =
let keywords =
match context with
| Expression :: ExpressionStatement :: _ ->
Base.List.append expression_keywords statement_keywords
| Expression :: Member :: _ -> []
| Expression :: _ -> expression_keywords
| Statement :: _ -> statement_keywords
| _ -> []
in
Base.List.map ~f:(completion_item_of_keyword loc) keywords
let keywords_at_loc ast loc =
let mapper = new mapper loc in
try
ignore (mapper#program ast);
[]
with
| Found context -> keywords_of_context loc context
|
86f2abb45fe4f9487b5c22c549e6aa1e3f9df9cc0b914f148822d19b8b95537c | FlowerWrong/mblog | my_fac_server.erl | %% ---
Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
%% Copyrights apply to this code. It may not be used to create training material,
%% courses, books, articles, and the like. Contact us if you are in doubt.
%% We make no guarantees that this code is fit for any purpose.
%% Visit for more book information.
%%---
-module(my_fac_server).
-export([loop/0]).
loop() ->
receive
{From, {fac, N}} ->
From ! {self(), fac(N)},
loop();
{become, Something} ->
Something()
end.
fac(0) -> 1;
fac(N) -> N * fac(N-1).
| null | https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/my_fac_server.erl | erlang | ---
Copyrights apply to this code. It may not be used to create training material,
courses, books, articles, and the like. Contact us if you are in doubt.
We make no guarantees that this code is fit for any purpose.
Visit for more book information.
--- | Excerpted from " Programming Erlang , Second Edition " ,
published by The Pragmatic Bookshelf .
-module(my_fac_server).
-export([loop/0]).
loop() ->
receive
{From, {fac, N}} ->
From ! {self(), fac(N)},
loop();
{become, Something} ->
Something()
end.
fac(0) -> 1;
fac(N) -> N * fac(N-1).
|
2da70b65546f6c0b25632861fe8930e8b586cdba6ad2f946d91fb3e386ea4f6d | tatut/clj-chrome-devtools | core.clj | (ns clj-chrome-devtools.core
(:require [clj-chrome-devtools.impl.connection :as connection]))
(def current-connection connection/current-connection)
(defn set-current-connection!
"Set the globally used current connection"
[c]
(reset! connection/current-connection c))
(def connect connection/connect)
| null | https://raw.githubusercontent.com/tatut/clj-chrome-devtools/0bb4cd7e4de7cc4a4255588fee309f688013fb09/src/clj_chrome_devtools/core.clj | clojure | (ns clj-chrome-devtools.core
(:require [clj-chrome-devtools.impl.connection :as connection]))
(def current-connection connection/current-connection)
(defn set-current-connection!
"Set the globally used current connection"
[c]
(reset! connection/current-connection c))
(def connect connection/connect)
| |
7d46b4eba2d65e113983e6cd484a31181e767064b90536502a5fa63bd2ced5f9 | atgreen/lisp-openshift | x86-64-vm.lisp | x86-64-vm.lisp -- VOP definitions SBCL
(cl:in-package :sb-vm)
(define-vop (%check-bound)
(:translate nibbles::%check-bound)
(:policy :fast-safe)
(:args (array :scs (descriptor-reg))
(bound :scs (any-reg))
(index :scs (any-reg)))
(:arg-types simple-array-unsigned-byte-8 positive-fixnum tagged-num
(:constant (member 2 4 8 16)))
(:info offset)
(:temporary (:sc any-reg) temp)
(:results (result :scs (any-reg)))
(:result-types positive-fixnum)
(:vop-var vop)
(:generator 5
(let ((error (generate-error-code vop 'invalid-array-index-error
array bound index)))
;; We want to check the conditions:
;;
;; 0 <= INDEX
INDEX < BOUND
;; 0 <= INDEX + OFFSET
;; (INDEX + OFFSET) < BOUND
;;
We can do this naively with two unsigned checks :
;;
;; INDEX <_u BOUND
;; INDEX + OFFSET <_u BOUND
;;
;; If INDEX + OFFSET <_u BOUND, though, INDEX must be less than
BOUND . We * do * need to check for 0 < = INDEX , but that has
;; already been assured by higher-level machinery.
(inst lea temp (make-ea :qword
:index index :disp (fixnumize offset)))
(inst cmp temp bound)
(inst jmp :a error)
(move result index))))
#.(flet ((frob (bitsize setterp signedp big-endian-p)
(let* ((name (funcall (if setterp
#'nibbles::byte-set-fun-name
#'nibbles::byte-ref-fun-name)
bitsize signedp big-endian-p))
(internal-name (nibbles::internalify name))
(ref-mov-insn (if (= bitsize 32)
(if big-endian-p
'mov
(if signedp 'movsxd 'movzxd))
'mov))
(result-sc (if signedp 'signed-reg 'unsigned-reg))
(result-type (if signedp 'signed-num 'unsigned-num)))
`(define-vop (,name)
(:translate ,internal-name)
(:policy :fast-safe)
(:args (vector :scs (descriptor-reg))
(index :scs (immediate unsigned-reg))
,@(when setterp
`((value* :scs (,result-sc) :target result))))
(:arg-types simple-array-unsigned-byte-8
positive-fixnum
,@(when setterp
`(,result-type)))
,@(when (and setterp big-endian-p)
`((:temporary (:sc unsigned-reg
:from (:load 0)
:to (:result 0)) temp)))
(:results (result :scs (,result-sc)))
(:result-types ,result-type)
(:generator 3
(let* ((base-disp (- (* vector-data-offset n-word-bytes)
other-pointer-lowtag))
(operand-size ,(if (= bitsize 32) :dword :qword))
,@(when setterp
'((value (reg-in-size value* operand-size))))
,@(when (and setterp big-endian-p)
'((temp (reg-in-size temp operand-size))))
(memref (sc-case index
(immediate
(make-ea operand-size :base vector
:disp (+ (tn-value index) base-disp)))
(t
(make-ea operand-size
:base vector :index index
:disp base-disp)))))
,@(when (and setterp big-endian-p)
`((inst mov temp value)
(inst bswap temp)))
,(if setterp
`(inst mov memref ,(if big-endian-p
'temp
'value))
`(inst ,ref-mov-insn
,(if (and big-endian-p (= bitsize 32))
'(reg-in-size result :dword)
'result)
memref))
,@(if setterp
'((move result value*))
(when big-endian-p
`((inst bswap
,(if (= bitsize 32)
'(reg-in-size result :dword)
'result))
,(when (and (= bitsize 32) signedp)
`(inst movsx result (reg-in-size result :dword))))))))))))
(loop for i from 0 upto #b1111
for bitsize = (if (logbitp 3 i) 32 64)
for setterp = (logbitp 2 i)
for signedp = (logbitp 1 i)
for big-endian-p = (logbitp 0 i)
collect (frob bitsize setterp signedp big-endian-p) into forms
finally (return `(progn ,@forms))))
| null | https://raw.githubusercontent.com/atgreen/lisp-openshift/40235286bd3c6a61cab9f5af883d9ed9befba849/quicklisp/dists/quicklisp/software/nibbles-20120407-git/sbcl-opt/x86-64-vm.lisp | lisp | We want to check the conditions:
0 <= INDEX
0 <= INDEX + OFFSET
(INDEX + OFFSET) < BOUND
INDEX <_u BOUND
INDEX + OFFSET <_u BOUND
If INDEX + OFFSET <_u BOUND, though, INDEX must be less than
already been assured by higher-level machinery. | x86-64-vm.lisp -- VOP definitions SBCL
(cl:in-package :sb-vm)
(define-vop (%check-bound)
(:translate nibbles::%check-bound)
(:policy :fast-safe)
(:args (array :scs (descriptor-reg))
(bound :scs (any-reg))
(index :scs (any-reg)))
(:arg-types simple-array-unsigned-byte-8 positive-fixnum tagged-num
(:constant (member 2 4 8 16)))
(:info offset)
(:temporary (:sc any-reg) temp)
(:results (result :scs (any-reg)))
(:result-types positive-fixnum)
(:vop-var vop)
(:generator 5
(let ((error (generate-error-code vop 'invalid-array-index-error
array bound index)))
INDEX < BOUND
We can do this naively with two unsigned checks :
BOUND . We * do * need to check for 0 < = INDEX , but that has
(inst lea temp (make-ea :qword
:index index :disp (fixnumize offset)))
(inst cmp temp bound)
(inst jmp :a error)
(move result index))))
#.(flet ((frob (bitsize setterp signedp big-endian-p)
(let* ((name (funcall (if setterp
#'nibbles::byte-set-fun-name
#'nibbles::byte-ref-fun-name)
bitsize signedp big-endian-p))
(internal-name (nibbles::internalify name))
(ref-mov-insn (if (= bitsize 32)
(if big-endian-p
'mov
(if signedp 'movsxd 'movzxd))
'mov))
(result-sc (if signedp 'signed-reg 'unsigned-reg))
(result-type (if signedp 'signed-num 'unsigned-num)))
`(define-vop (,name)
(:translate ,internal-name)
(:policy :fast-safe)
(:args (vector :scs (descriptor-reg))
(index :scs (immediate unsigned-reg))
,@(when setterp
`((value* :scs (,result-sc) :target result))))
(:arg-types simple-array-unsigned-byte-8
positive-fixnum
,@(when setterp
`(,result-type)))
,@(when (and setterp big-endian-p)
`((:temporary (:sc unsigned-reg
:from (:load 0)
:to (:result 0)) temp)))
(:results (result :scs (,result-sc)))
(:result-types ,result-type)
(:generator 3
(let* ((base-disp (- (* vector-data-offset n-word-bytes)
other-pointer-lowtag))
(operand-size ,(if (= bitsize 32) :dword :qword))
,@(when setterp
'((value (reg-in-size value* operand-size))))
,@(when (and setterp big-endian-p)
'((temp (reg-in-size temp operand-size))))
(memref (sc-case index
(immediate
(make-ea operand-size :base vector
:disp (+ (tn-value index) base-disp)))
(t
(make-ea operand-size
:base vector :index index
:disp base-disp)))))
,@(when (and setterp big-endian-p)
`((inst mov temp value)
(inst bswap temp)))
,(if setterp
`(inst mov memref ,(if big-endian-p
'temp
'value))
`(inst ,ref-mov-insn
,(if (and big-endian-p (= bitsize 32))
'(reg-in-size result :dword)
'result)
memref))
,@(if setterp
'((move result value*))
(when big-endian-p
`((inst bswap
,(if (= bitsize 32)
'(reg-in-size result :dword)
'result))
,(when (and (= bitsize 32) signedp)
`(inst movsx result (reg-in-size result :dword))))))))))))
(loop for i from 0 upto #b1111
for bitsize = (if (logbitp 3 i) 32 64)
for setterp = (logbitp 2 i)
for signedp = (logbitp 1 i)
for big-endian-p = (logbitp 0 i)
collect (frob bitsize setterp signedp big-endian-p) into forms
finally (return `(progn ,@forms))))
|
ebc840bdd415913ee928631d9050cbdbb8e6aae01d6f29a4d5cc39bd317ceea0 | eckyputrady/haskell-scotty-realworld-example-app | JWT.hs | module Feature.User.JWT where
import ClassyPrelude
import Platform.JWT
import Feature.Auth.Types
import Data.Has
import Jose.Jwt
import Jose.Jwa
import qualified Data.Aeson as Aeson
import Data.Time.Clock.POSIX (getPOSIXTime)
generateToken :: (JWT r m) => UserId -> m Token
generateToken userId = do
jwks <- asks $ envJwks . getter
expirationSecs <- asks $ envExpirationSecs . getter
curTime <- liftIO getPOSIXTime
let claim = JwtClaims { jwtIss = Nothing
, jwtSub = Just $ tshow userId
, jwtAud = Nothing
, jwtExp = Just $ IntDate $ curTime + fromInteger expirationSecs
, jwtNbf = Nothing
, jwtIat = Nothing
, jwtJti = Nothing
}
(Jwt jwtEncoded) <- either (\e -> error $ "Failed to encode JWT: " <> show e) id <$> encode jwks (JwsEncoding RS256) (Claims . toStrict . Aeson.encode $ claim)
return . decodeUtf8 $ jwtEncoded | null | https://raw.githubusercontent.com/eckyputrady/haskell-scotty-realworld-example-app/366a1eec021fb1bfcbc2d8e0485b59cbedba10e5/src/Feature/User/JWT.hs | haskell | module Feature.User.JWT where
import ClassyPrelude
import Platform.JWT
import Feature.Auth.Types
import Data.Has
import Jose.Jwt
import Jose.Jwa
import qualified Data.Aeson as Aeson
import Data.Time.Clock.POSIX (getPOSIXTime)
generateToken :: (JWT r m) => UserId -> m Token
generateToken userId = do
jwks <- asks $ envJwks . getter
expirationSecs <- asks $ envExpirationSecs . getter
curTime <- liftIO getPOSIXTime
let claim = JwtClaims { jwtIss = Nothing
, jwtSub = Just $ tshow userId
, jwtAud = Nothing
, jwtExp = Just $ IntDate $ curTime + fromInteger expirationSecs
, jwtNbf = Nothing
, jwtIat = Nothing
, jwtJti = Nothing
}
(Jwt jwtEncoded) <- either (\e -> error $ "Failed to encode JWT: " <> show e) id <$> encode jwks (JwsEncoding RS256) (Claims . toStrict . Aeson.encode $ claim)
return . decodeUtf8 $ jwtEncoded | |
98fedde3a14547f8f665dce6e3909369007ea35942bd0facb60137a281821aba | aptmcl/rosetta | main.rkt | #lang typed/racket/base/no-check
(require (for-syntax racket/base))
(require (for-syntax racket/syntax))
(require (for-syntax racket/list))
(require racket/math)
(require "base/coord.rkt")
(require "base/utils.rkt")
(require "base/shapes.rkt")
(require (prefix-in autocad: "autocad/backend.rkt"))
(require (prefix-in rhino: "rhinoceros/backend.rkt"))
(require (prefix-in revit: "revit/backend.rkt"))
(require (prefix-in sketchup: "sketchup/backend.rkt"))
(provide (all-defined-out))
(provide (all-from-out "base/coord.rkt"))
(provide (all-from-out "base/utils.rkt"))
(provide (all-from-out "base/shapes.rkt"))
(require "util/geometry.rkt")
(provide (all-from-out "util/geometry.rkt"))
(provide current-out-backend)
(provide current-in-backend)
(provide current-in-out-backend)
(define-type Backend String)
(define undecided : Backend "Undecided")
(define autocad : Backend (autocad:current-backend-name))
(define rhino : Backend (rhino:current-backend-name))
(define sketchup : Backend (sketchup:current-backend-name))
(define revit : Backend (revit:current-backend-name))
The current out backend is the one active at
;;a given moment, used only during shape creation
(define current-out-backend : (Parameterof (Option Backend)) (make-parameter undecided))
The current in backend is the one active at
;;a given moment, used only during shape acquisition
(define current-in-backend : (Parameterof (Option Backend)) (make-parameter undecided))
(define (current-in-out-backend [in : Backend] [out : Backend in] [op : Symbol 'none]) : Void
(current-in-backend in)
(current-out-backend out)
#| (render-backend-dir (backend-name out))
(start-backend in)
(unless (eq? in out)
(start-backend out))
(case op
[(none) (void)]
[(delete)
(delete-all-shapes)
(void)])
#;(delayed-mode)
(immediate-mode)
|#
(void))
(define (backend [b : Backend])
(current-in-out-backend b))
#|;;The realize function is called whenever we try to visualize
;;(print, in Racket terms) the delayed shape
(define default-current-print (current-print))
(define (rosetta-print value)
(default-current-print
(parameterize ((immediate-mode? #f))
(realize value))))
(provide immediate-mode)
(define (immediate-mode)
; (delayed-mode? #f)
(current-print default-current-print))
(provide delayed-mode)
(define (delayed-mode)
; (delayed-mode? #t)
(current-print rosetta-print))
;;Now, the operations that depend on the backend
|#
(provide Shape Shapes)
(define-type Shape (U autocad:Shape rhino:Shape sketchup:Shape revit:Shape))
(define-type Shapes (U autocad:Shapes rhino:Shapes sketchup:Shapes revit:Shapes))
Second , a macro for defining operations that wrap the results of the
;;backend operations
;;The most generic
(define-syntax (case-backend stx)
(syntax-case stx ()
((case-backend expr name clause ...)
(syntax/loc stx
(let ((backend expr))
(case-backend* backend name clause ...))))))
(define-syntax (case-backend* stx)
(syntax-case stx (else) ;;In the future, optimize this with a jump table
((_ b name)
(syntax/loc stx
(error 'name "Unknown backend ~a" b)))
((_ b name (else body ...))
(syntax/loc stx
(begin body ...)))
((_ b name ((backend ...) body ...) clause ...)
(syntax/loc stx
(if (or (eq? b backend) ...)
(begin body ...)
(case-backend* b name clause ...))))
((_ b name (backend body ...) clause ...)
(syntax/loc stx
(case-backend* b name ((backend) body ...) clause ...)))))
;;Using the current-out-backend
(define-syntax (case-current-backend stx)
(syntax-case stx ()
((_ name clause ...)
(syntax/loc stx
(case-backend (current-out-backend) name clause ...)))))
;;Using a shape
(define-syntax (case-shape-backend stx)
(syntax-case stx ()
((_ expr name clause ...)
(syntax/loc stx
(case-backend (shape-backend expr) name clause ...)))))
(define-syntax (delegate-backend stx)
(syntax-case stx ()
[(_ backend-expr (backend ...) (name param ...))
(with-syntax ([((backend (backend-call arg ...)) ...)
(map (lambda (backend)
(with-syntax ([backend-shape
(format-id backend
#:source backend
"~A:Shape"
(syntax-e backend))]
[backend-shapes
(format-id backend
#:source backend
"~A:Shapes"
(syntax-e backend))]
[backend-func
(format-id backend
#:source backend
"~A:~A"
(syntax-e backend)
(syntax-e #'name))])
(list backend
(if (identifier-binding #'backend-func)
(cons #'backend-func
(map (lambda (param)
(syntax-case param (: Shape Shapes Listof)
[[name : Shape . default] #'(cast name backend-shape)]
[[name : Shapes . default] #'(cast name backend-shapes)]
[[name : (Listof Shape) . default] #'(cast name backend-shapes)]
[[name : type . default] #'name]))
(syntax->list #'(param ...))))
(with-syntax ([backend backend])
#'(error (format "Operation ~A is not available in backend ~A"
'name 'backend)))))))
(syntax->list #'(backend ...)))])
(syntax/loc stx
(case-backend
backend-expr
name
[backend (backend-call arg ...)] ...)))]
[(delegate backend-expr (name param ...))
(syntax/loc stx
(delegate backend-expr (autocad rhino sketchup revit) (name param ...)))]))
(define-syntax (def-backend stx)
(syntax-case stx ()
[(_ backend-expr (name param ...))
(syntax/loc stx
(begin
(provide name)
(define (name param ...)
(delegate-backend backend-expr (name param ...)))))]
[(def (name param ...))
(syntax/loc stx
(def (current-out-backend) (name param ...)))]))
(define-syntax (def-new-shape-op stx)
(syntax-case stx ()
[(_ (name param ...))
(with-syntax ([[target : type]
(findf (lambda (param)
(syntax-case param (: Shape)
[[name : Shape] #'name]
[_ #f]))
(syntax->list #'(param ...)))])
(syntax/loc stx
(def-backend
(name param ...)
#;(shape-backend target) ;;Can't use this with the current architecture
(current-out-backend))))]))
(define-syntax (def-backend* stx)
(syntax-case stx (: *)
[(_ (name [t : type *]))
(syntax/loc stx
(define (name [t-or-ts : (U type (Listof type))] . [ts : type *])
(let ((t (if (list? t-or-ts)
(if (null? ts)
t-or-ts
(append t-or-ts ts))
(cons t-or-ts ts))))
(delegate-backend (current-out-backend) (name [t : (Listof type)])))))]))
(def-backend (empty-shape))
(def-backend (universal-shape))
(def-backend (point [position : Loc (u0)]))
(def-backend (circle [center : Loc (u0)] [radius : Real 1]))
(def-backend (arc [center : Loc (u0)] [radius : Real 1] [start-angle : Real 0] [amplitude : Real pi]))
(def-backend (ellipse [center : Loc (u0)] [radius-x : Real 1] [radius-y : Real 1]))
(def-backend (surface-circle [center : Loc (u0)] [radius : Real 1]))
(def-backend (surface-arc [center : Loc (u0)] [radius : Real 1] [start-angle : Real 0] [amplitude : Real pi]))
(def-backend (surface-ellipse [center : Loc (u0)] [radius-x : Real 1] [radius-y : Real 1]))
(def-backend* (line [pts : Loc *]))
(def-backend* (closed-line [pts : Loc *]))
(def-backend* (polygon [pts : Loc *]))
(def-backend* (spline [pts : Loc *])); (list (u0) (ux) (uy))] [v0 : (U #f Vec) #f] [v1 : (U #f Vec) #f]))
(def-backend (spline* [pts : Locs] [v0 : (U #f Vec) #f] [v1 : (U #f Vec) #f]))
(def-backend* (closed-spline [pts : Loc *]))
(def-backend (curve-closest-location [curve : Shape] [pt : Loc]))
(def-backend (curve-start-location [curve : Shape]))
(def-backend (curve-end-location [curve : Shape]))
(def-backend (curve-domain [curve : Shape]))
(def-backend (curve-frame-at [curve : Shape] [t : Real]))
(def-backend (curve-frame-at-length [curve : Shape] [t : Real]))
(def-backend (curve-length [curve : Shape]))
HACK These two functions require the default initialization on last ? but Typed Racket has a bug and prevents the use of # : forall ( A )
(: map-curve-division (All (A) (->* ((-> Loc A) Shape Integer) (Boolean) (Listof A))))
(: map-curve-length-division (All (A) (->* ((-> Loc A) Shape Integer) (Boolean) (Listof A))))
(def-backend (map-curve-division [f : (-> Loc A)] [curve : Shape] [n : Integer] [last? : Boolean #t]))
(def-backend (map-curve-length-division [f : (-> Loc A)] [curve : Shape] [n : Integer] [last? : Boolean #t]))
(def-backend* (surface-polygon [pts : Loc *]))
(def-backend (rectangle [c : Loc (u0)] [dx/c1 : (U Real Loc) 1] [dy : Real 1]))
(def-backend (surface-rectangle [c : Loc (u0)] [dx/c1 : (U Real Loc) 1] [dy : Real 1]))
(def-backend (regular-polygon [edges : Integer 3] [center : Loc (u0)] [radius : Real 1] [angle : Real 0] [inscribed? : Boolean #f]))
(def-backend (surface-regular-polygon [edges : Integer 3] [center : Loc (u0)] [radius : Real 1] [angle : Real 0] [inscribed? : Boolean #f]))
(def-backend (surface-boundary [shape : Shape]))
(def-backend (loft-curve-point [curve : Shape] [point : Shape]))
(def-backend (loft-surface-point [surface : Shape] [point : Shape]))
#;
(def-backend (loft-profiles [profiles : Shapes] [rails : Shapes] [solid? : Boolean] [ruled? : Boolean] [closed? : Boolean]))
#;#;
(def-backend (loft-curves [shapes : Shapes] [rails : Shapes]))
(def-backend (loft-surfaces [shapes : Shapes] [rails : Shapes]))
(def-backend (loft [profiles : Shapes] [rails : Shapes (list)] [ruled? : Boolean #f] [closed? : Boolean #f]))
(def-backend (loft-ruled [profiles : Shapes]))
(def-backend (irregular-pyramid [cbs : Locs (list (ux) (uy) (uxy))] [ct : Loc (uz)]))
(def-backend (regular-pyramid-frustum [edges : Integer 4] [cb : Loc (u0)] [rb : Real 1] [a : Real 0] [h/ct : (U Real Loc) 1] [rt : Real 1] [inscribed? : Boolean #f]))
(def-backend (regular-pyramid [edges : Integer 4] [cb : Loc (u0)] [rb : Real 1] [a : Real 0] [h/ct : (U Real Loc) 1] [inscribed? : Boolean #f]))
(def-backend (regular-prism [edges : Integer 4] [cb : Loc (u0)] [r : Real 1] [a : Real 0] [h/ct : (U Real Loc) 1] [inscribed? : Boolean #f]))
(def-backend (right-cuboid [cb : Loc (u0)] [width : Real 1] [height : Real 1] [h/ct : LocOrZ 1]))
(def-backend (cylinder [cb : Loc (u0)] [r : Real 1] [h/ct : LocOrZ 1]))
(def-backend (box [c : Loc (u0)] [dx/c1 : LocOrZ 1] [dy : Real (if (number? dx/c1) dx/c1 1)] [dz : Real dy]))
(def-backend (cone [cb : Loc (u0)] [r : Real 1] [h/ct : LocOrZ 1]))
(def-backend (cone-frustum [cb : Loc (u0)] [rb : Real 1] [h/ct : LocOrZ 1] [rt : Real 1]))
(def-backend (cuboid [b0 : Loc (u0)]
[b1 : Loc (+x b0 1)]
[b2 : Loc (+y b1 1)]
[b3 : Loc (+y b0 1)]
[t0 : Loc (+z b0 1)]
[t1 : Loc (+x t0 1)]
[t2 : Loc (+y t1 1)]
[t3 : Loc (+y t0 1)]))
(def-backend (sphere [c : Loc (u0)] [r : Real 1]))
(def-backend (surface-grid [ptss : (Listof (Listof Loc))] [closed-u? : Boolean #f] [closed-v? : Boolean #f]))
(def-backend (text [str : String ""] [p : Loc (u0)] [h : Real 1]))
(def-backend (text-length [str : String ""] [h : Real 1]))
(def-backend (text-centered [str : String ""] [p : Loc (u0)] [h : Real 1]))
(def-backend (torus [center : Loc (u0)] [re : Real 1] [ri : Real 1/2]))
(def-backend* (surface [profiles : Shape *]))
(def-backend (join-curves [shapes : Shapes]))
(def-backend (revolve [shape : Shape] [p : Loc (u0)] [n : Vec (vz 1)] [start-angle : Real 0] [amplitude : Real 2pi]))
(def-backend (curve? [s : Shape]))
(def-backend (surface-region? [s : Shape]))
(def-backend (extrusion [profile : Shape] [dir : VecOrZ 1]))
(def-backend (sweep [path : Shape] [profile : Shape] [rotation : Real 0] [scale : Real 1]))
(def-backend (thicken [surf : Shape] [h : Real 1]))
(def-backend (slice [shape : Shape] [p : Loc (u0)] [n : Vec (vz 1 p)]))
(def-backend (triangle-face [p0 : Loc] [p1 : Loc] [p2 : Loc]))
(def-backend (quadrangle-face [p0 : Loc] [p1 : Loc] [p2 : Loc] [p3 : Loc]))
(def-backend (move [shape : Shape] [v : Vec (vx)]))
(def-backend (rotate [shape : Shape] [a : Real pi/2] [p0 : Loc (u0)] [p1 : Loc (+z p0 1)]))
(def-backend (scale [shape : Shape] [s : Real 1] [p : Loc (u0)]))
(def-backend (mirror [shape : Shape] [p : Loc (u0)] [n : Vec (vz)] [copy? : Boolean #t]))
(def-backend (union-mirror [shape : Shape] [p : Loc (u0)] [n : Vec (vz)]))
(def-backend (bounding-box [s : Shape]))
#;
(def-backend shape-color
(case-lambda
[([shape : Shape])
(%true-color (shape-ref shape))]
[([shape : Shape] [new-color : Color])
(do-ref ([r shape])
(%true-color r new-color))
(void)]))
(def-backend (create-layer [name : String] [color : (Option Color) #f]))
(provide current-layer)
(define current-layer
(case-lambda
[()
(delegate-backend (current-out-backend) (current-layer))]
[([new-layer : Layer])
(delegate-backend (current-out-backend) (current-layer [new-layer : Layer]))]))
(provide with-current-layer)
(define-syntax (with-current-layer stx)
(syntax-case stx ()
((_ new-layer body ...)
(syntax/loc stx
(let ((old-layer (current-layer)))
(dynamic-wind
(lambda () (current-layer new-layer))
(lambda () body ...)
(lambda () (current-layer old-layer))))))))
#;
(def-backend shape-layer
(case-lambda
[([shape : Shape])
(%get-layer (%layer (shape-ref shape)))]
[([shape : Shape] [new-layer : Layer])
(do-ref ([r shape])
(%layer r new-layer))
(void)]))
(def-backend (create-material [name : String]))
#;
(def-backend shape-material
(case-lambda
[([shape : Shape])
(%material (shape-ref shape))]
[([shape : Shape] [new-material : Material])
(do-ref ([r shape])
(%material r new-material))
(void)]))
(def-backend (fast-view))
(def-backend (view [camera : (Option Loc) #f] [target : (Option Loc) #f] [lens : (Option Real) #f]))
(def-backend (view-expression))
(def-backend (view-top))
(def-backend (render-view [name : String]))
(def-backend (save-film-frame [obj : Any (void)]))
(def-backend (zoom-extents))
(def-backend (disable-update))
(def-backend (enable-update))
(def-backend (prompt-point [str : String "Select position"]))
(def-backend (prompt-integer [str : String "Integer?"]))
(def-backend (prompt-real [str : String "Real?"]))
(def-backend (prompt-shape [str : String "Select shape"]))
(def-backend (select-shape [s : Shape]))
(def-backend (select-shapes [ss : Shapes]))
(def-backend (polygonal-mass [pts : Locs] [height : Real]))
(def-backend* (union [shapes : Shape *]))
(def-backend* (intersection [shapes : Shape *]))
(def-backend* (subtraction [shapes : Shape *]))
(def-backend (current-in-backend) (all-shapes))
(def-backend (delete-all-shapes))
(def-backend (delete-shape [s : Shape]))
(def-backend (delete-shapes [s : Shapes]))
| null | https://raw.githubusercontent.com/aptmcl/rosetta/38aeafd730f93edaec7474106e84dae6d8bc1261/main.rkt | racket | a given moment, used only during shape creation
a given moment, used only during shape acquisition
(render-backend-dir (backend-name out))
(start-backend in)
(unless (eq? in out)
(start-backend out))
(case op
[(none) (void)]
[(delete)
(delete-all-shapes)
(void)])
#;(delayed-mode)
(immediate-mode)
;;The realize function is called whenever we try to visualize
;;(print, in Racket terms) the delayed shape
(define default-current-print (current-print))
(define (rosetta-print value)
(default-current-print
(parameterize ((immediate-mode? #f))
(realize value))))
(provide immediate-mode)
(define (immediate-mode)
; (delayed-mode? #f)
(current-print default-current-print))
(provide delayed-mode)
(define (delayed-mode)
; (delayed-mode? #t)
(current-print rosetta-print))
;;Now, the operations that depend on the backend
backend operations
The most generic
In the future, optimize this with a jump table
Using the current-out-backend
Using a shape
(shape-backend target) ;;Can't use this with the current architecture
(list (u0) (ux) (uy))] [v0 : (U #f Vec) #f] [v1 : (U #f Vec) #f]))
#;
| #lang typed/racket/base/no-check
(require (for-syntax racket/base))
(require (for-syntax racket/syntax))
(require (for-syntax racket/list))
(require racket/math)
(require "base/coord.rkt")
(require "base/utils.rkt")
(require "base/shapes.rkt")
(require (prefix-in autocad: "autocad/backend.rkt"))
(require (prefix-in rhino: "rhinoceros/backend.rkt"))
(require (prefix-in revit: "revit/backend.rkt"))
(require (prefix-in sketchup: "sketchup/backend.rkt"))
(provide (all-defined-out))
(provide (all-from-out "base/coord.rkt"))
(provide (all-from-out "base/utils.rkt"))
(provide (all-from-out "base/shapes.rkt"))
(require "util/geometry.rkt")
(provide (all-from-out "util/geometry.rkt"))
(provide current-out-backend)
(provide current-in-backend)
(provide current-in-out-backend)
(define-type Backend String)
(define undecided : Backend "Undecided")
(define autocad : Backend (autocad:current-backend-name))
(define rhino : Backend (rhino:current-backend-name))
(define sketchup : Backend (sketchup:current-backend-name))
(define revit : Backend (revit:current-backend-name))
The current out backend is the one active at
(define current-out-backend : (Parameterof (Option Backend)) (make-parameter undecided))
The current in backend is the one active at
(define current-in-backend : (Parameterof (Option Backend)) (make-parameter undecided))
(define (current-in-out-backend [in : Backend] [out : Backend in] [op : Symbol 'none]) : Void
(current-in-backend in)
(current-out-backend out)
(void))
(define (backend [b : Backend])
(current-in-out-backend b))
(provide Shape Shapes)
(define-type Shape (U autocad:Shape rhino:Shape sketchup:Shape revit:Shape))
(define-type Shapes (U autocad:Shapes rhino:Shapes sketchup:Shapes revit:Shapes))
Second , a macro for defining operations that wrap the results of the
(define-syntax (case-backend stx)
(syntax-case stx ()
((case-backend expr name clause ...)
(syntax/loc stx
(let ((backend expr))
(case-backend* backend name clause ...))))))
(define-syntax (case-backend* stx)
((_ b name)
(syntax/loc stx
(error 'name "Unknown backend ~a" b)))
((_ b name (else body ...))
(syntax/loc stx
(begin body ...)))
((_ b name ((backend ...) body ...) clause ...)
(syntax/loc stx
(if (or (eq? b backend) ...)
(begin body ...)
(case-backend* b name clause ...))))
((_ b name (backend body ...) clause ...)
(syntax/loc stx
(case-backend* b name ((backend) body ...) clause ...)))))
(define-syntax (case-current-backend stx)
(syntax-case stx ()
((_ name clause ...)
(syntax/loc stx
(case-backend (current-out-backend) name clause ...)))))
(define-syntax (case-shape-backend stx)
(syntax-case stx ()
((_ expr name clause ...)
(syntax/loc stx
(case-backend (shape-backend expr) name clause ...)))))
(define-syntax (delegate-backend stx)
(syntax-case stx ()
[(_ backend-expr (backend ...) (name param ...))
(with-syntax ([((backend (backend-call arg ...)) ...)
(map (lambda (backend)
(with-syntax ([backend-shape
(format-id backend
#:source backend
"~A:Shape"
(syntax-e backend))]
[backend-shapes
(format-id backend
#:source backend
"~A:Shapes"
(syntax-e backend))]
[backend-func
(format-id backend
#:source backend
"~A:~A"
(syntax-e backend)
(syntax-e #'name))])
(list backend
(if (identifier-binding #'backend-func)
(cons #'backend-func
(map (lambda (param)
(syntax-case param (: Shape Shapes Listof)
[[name : Shape . default] #'(cast name backend-shape)]
[[name : Shapes . default] #'(cast name backend-shapes)]
[[name : (Listof Shape) . default] #'(cast name backend-shapes)]
[[name : type . default] #'name]))
(syntax->list #'(param ...))))
(with-syntax ([backend backend])
#'(error (format "Operation ~A is not available in backend ~A"
'name 'backend)))))))
(syntax->list #'(backend ...)))])
(syntax/loc stx
(case-backend
backend-expr
name
[backend (backend-call arg ...)] ...)))]
[(delegate backend-expr (name param ...))
(syntax/loc stx
(delegate backend-expr (autocad rhino sketchup revit) (name param ...)))]))
(define-syntax (def-backend stx)
(syntax-case stx ()
[(_ backend-expr (name param ...))
(syntax/loc stx
(begin
(provide name)
(define (name param ...)
(delegate-backend backend-expr (name param ...)))))]
[(def (name param ...))
(syntax/loc stx
(def (current-out-backend) (name param ...)))]))
(define-syntax (def-new-shape-op stx)
(syntax-case stx ()
[(_ (name param ...))
(with-syntax ([[target : type]
(findf (lambda (param)
(syntax-case param (: Shape)
[[name : Shape] #'name]
[_ #f]))
(syntax->list #'(param ...)))])
(syntax/loc stx
(def-backend
(name param ...)
(current-out-backend))))]))
(define-syntax (def-backend* stx)
(syntax-case stx (: *)
[(_ (name [t : type *]))
(syntax/loc stx
(define (name [t-or-ts : (U type (Listof type))] . [ts : type *])
(let ((t (if (list? t-or-ts)
(if (null? ts)
t-or-ts
(append t-or-ts ts))
(cons t-or-ts ts))))
(delegate-backend (current-out-backend) (name [t : (Listof type)])))))]))
(def-backend (empty-shape))
(def-backend (universal-shape))
(def-backend (point [position : Loc (u0)]))
(def-backend (circle [center : Loc (u0)] [radius : Real 1]))
(def-backend (arc [center : Loc (u0)] [radius : Real 1] [start-angle : Real 0] [amplitude : Real pi]))
(def-backend (ellipse [center : Loc (u0)] [radius-x : Real 1] [radius-y : Real 1]))
(def-backend (surface-circle [center : Loc (u0)] [radius : Real 1]))
(def-backend (surface-arc [center : Loc (u0)] [radius : Real 1] [start-angle : Real 0] [amplitude : Real pi]))
(def-backend (surface-ellipse [center : Loc (u0)] [radius-x : Real 1] [radius-y : Real 1]))
(def-backend* (line [pts : Loc *]))
(def-backend* (closed-line [pts : Loc *]))
(def-backend* (polygon [pts : Loc *]))
(def-backend (spline* [pts : Locs] [v0 : (U #f Vec) #f] [v1 : (U #f Vec) #f]))
(def-backend* (closed-spline [pts : Loc *]))
(def-backend (curve-closest-location [curve : Shape] [pt : Loc]))
(def-backend (curve-start-location [curve : Shape]))
(def-backend (curve-end-location [curve : Shape]))
(def-backend (curve-domain [curve : Shape]))
(def-backend (curve-frame-at [curve : Shape] [t : Real]))
(def-backend (curve-frame-at-length [curve : Shape] [t : Real]))
(def-backend (curve-length [curve : Shape]))
HACK These two functions require the default initialization on last ? but Typed Racket has a bug and prevents the use of # : forall ( A )
(: map-curve-division (All (A) (->* ((-> Loc A) Shape Integer) (Boolean) (Listof A))))
(: map-curve-length-division (All (A) (->* ((-> Loc A) Shape Integer) (Boolean) (Listof A))))
(def-backend (map-curve-division [f : (-> Loc A)] [curve : Shape] [n : Integer] [last? : Boolean #t]))
(def-backend (map-curve-length-division [f : (-> Loc A)] [curve : Shape] [n : Integer] [last? : Boolean #t]))
(def-backend* (surface-polygon [pts : Loc *]))
(def-backend (rectangle [c : Loc (u0)] [dx/c1 : (U Real Loc) 1] [dy : Real 1]))
(def-backend (surface-rectangle [c : Loc (u0)] [dx/c1 : (U Real Loc) 1] [dy : Real 1]))
(def-backend (regular-polygon [edges : Integer 3] [center : Loc (u0)] [radius : Real 1] [angle : Real 0] [inscribed? : Boolean #f]))
(def-backend (surface-regular-polygon [edges : Integer 3] [center : Loc (u0)] [radius : Real 1] [angle : Real 0] [inscribed? : Boolean #f]))
(def-backend (surface-boundary [shape : Shape]))
(def-backend (loft-curve-point [curve : Shape] [point : Shape]))
(def-backend (loft-surface-point [surface : Shape] [point : Shape]))
(def-backend (loft-profiles [profiles : Shapes] [rails : Shapes] [solid? : Boolean] [ruled? : Boolean] [closed? : Boolean]))
(def-backend (loft-curves [shapes : Shapes] [rails : Shapes]))
(def-backend (loft-surfaces [shapes : Shapes] [rails : Shapes]))
(def-backend (loft [profiles : Shapes] [rails : Shapes (list)] [ruled? : Boolean #f] [closed? : Boolean #f]))
(def-backend (loft-ruled [profiles : Shapes]))
(def-backend (irregular-pyramid [cbs : Locs (list (ux) (uy) (uxy))] [ct : Loc (uz)]))
(def-backend (regular-pyramid-frustum [edges : Integer 4] [cb : Loc (u0)] [rb : Real 1] [a : Real 0] [h/ct : (U Real Loc) 1] [rt : Real 1] [inscribed? : Boolean #f]))
(def-backend (regular-pyramid [edges : Integer 4] [cb : Loc (u0)] [rb : Real 1] [a : Real 0] [h/ct : (U Real Loc) 1] [inscribed? : Boolean #f]))
(def-backend (regular-prism [edges : Integer 4] [cb : Loc (u0)] [r : Real 1] [a : Real 0] [h/ct : (U Real Loc) 1] [inscribed? : Boolean #f]))
(def-backend (right-cuboid [cb : Loc (u0)] [width : Real 1] [height : Real 1] [h/ct : LocOrZ 1]))
(def-backend (cylinder [cb : Loc (u0)] [r : Real 1] [h/ct : LocOrZ 1]))
(def-backend (box [c : Loc (u0)] [dx/c1 : LocOrZ 1] [dy : Real (if (number? dx/c1) dx/c1 1)] [dz : Real dy]))
(def-backend (cone [cb : Loc (u0)] [r : Real 1] [h/ct : LocOrZ 1]))
(def-backend (cone-frustum [cb : Loc (u0)] [rb : Real 1] [h/ct : LocOrZ 1] [rt : Real 1]))
(def-backend (cuboid [b0 : Loc (u0)]
[b1 : Loc (+x b0 1)]
[b2 : Loc (+y b1 1)]
[b3 : Loc (+y b0 1)]
[t0 : Loc (+z b0 1)]
[t1 : Loc (+x t0 1)]
[t2 : Loc (+y t1 1)]
[t3 : Loc (+y t0 1)]))
(def-backend (sphere [c : Loc (u0)] [r : Real 1]))
(def-backend (surface-grid [ptss : (Listof (Listof Loc))] [closed-u? : Boolean #f] [closed-v? : Boolean #f]))
(def-backend (text [str : String ""] [p : Loc (u0)] [h : Real 1]))
(def-backend (text-length [str : String ""] [h : Real 1]))
(def-backend (text-centered [str : String ""] [p : Loc (u0)] [h : Real 1]))
(def-backend (torus [center : Loc (u0)] [re : Real 1] [ri : Real 1/2]))
(def-backend* (surface [profiles : Shape *]))
(def-backend (join-curves [shapes : Shapes]))
(def-backend (revolve [shape : Shape] [p : Loc (u0)] [n : Vec (vz 1)] [start-angle : Real 0] [amplitude : Real 2pi]))
(def-backend (curve? [s : Shape]))
(def-backend (surface-region? [s : Shape]))
(def-backend (extrusion [profile : Shape] [dir : VecOrZ 1]))
(def-backend (sweep [path : Shape] [profile : Shape] [rotation : Real 0] [scale : Real 1]))
(def-backend (thicken [surf : Shape] [h : Real 1]))
(def-backend (slice [shape : Shape] [p : Loc (u0)] [n : Vec (vz 1 p)]))
(def-backend (triangle-face [p0 : Loc] [p1 : Loc] [p2 : Loc]))
(def-backend (quadrangle-face [p0 : Loc] [p1 : Loc] [p2 : Loc] [p3 : Loc]))
(def-backend (move [shape : Shape] [v : Vec (vx)]))
(def-backend (rotate [shape : Shape] [a : Real pi/2] [p0 : Loc (u0)] [p1 : Loc (+z p0 1)]))
(def-backend (scale [shape : Shape] [s : Real 1] [p : Loc (u0)]))
(def-backend (mirror [shape : Shape] [p : Loc (u0)] [n : Vec (vz)] [copy? : Boolean #t]))
(def-backend (union-mirror [shape : Shape] [p : Loc (u0)] [n : Vec (vz)]))
(def-backend (bounding-box [s : Shape]))
(def-backend shape-color
(case-lambda
[([shape : Shape])
(%true-color (shape-ref shape))]
[([shape : Shape] [new-color : Color])
(do-ref ([r shape])
(%true-color r new-color))
(void)]))
(def-backend (create-layer [name : String] [color : (Option Color) #f]))
(provide current-layer)
(define current-layer
(case-lambda
[()
(delegate-backend (current-out-backend) (current-layer))]
[([new-layer : Layer])
(delegate-backend (current-out-backend) (current-layer [new-layer : Layer]))]))
(provide with-current-layer)
(define-syntax (with-current-layer stx)
(syntax-case stx ()
((_ new-layer body ...)
(syntax/loc stx
(let ((old-layer (current-layer)))
(dynamic-wind
(lambda () (current-layer new-layer))
(lambda () body ...)
(lambda () (current-layer old-layer))))))))
(def-backend shape-layer
(case-lambda
[([shape : Shape])
(%get-layer (%layer (shape-ref shape)))]
[([shape : Shape] [new-layer : Layer])
(do-ref ([r shape])
(%layer r new-layer))
(void)]))
(def-backend (create-material [name : String]))
(def-backend shape-material
(case-lambda
[([shape : Shape])
(%material (shape-ref shape))]
[([shape : Shape] [new-material : Material])
(do-ref ([r shape])
(%material r new-material))
(void)]))
(def-backend (fast-view))
(def-backend (view [camera : (Option Loc) #f] [target : (Option Loc) #f] [lens : (Option Real) #f]))
(def-backend (view-expression))
(def-backend (view-top))
(def-backend (render-view [name : String]))
(def-backend (save-film-frame [obj : Any (void)]))
(def-backend (zoom-extents))
(def-backend (disable-update))
(def-backend (enable-update))
(def-backend (prompt-point [str : String "Select position"]))
(def-backend (prompt-integer [str : String "Integer?"]))
(def-backend (prompt-real [str : String "Real?"]))
(def-backend (prompt-shape [str : String "Select shape"]))
(def-backend (select-shape [s : Shape]))
(def-backend (select-shapes [ss : Shapes]))
(def-backend (polygonal-mass [pts : Locs] [height : Real]))
(def-backend* (union [shapes : Shape *]))
(def-backend* (intersection [shapes : Shape *]))
(def-backend* (subtraction [shapes : Shape *]))
(def-backend (current-in-backend) (all-shapes))
(def-backend (delete-all-shapes))
(def-backend (delete-shape [s : Shape]))
(def-backend (delete-shapes [s : Shapes]))
|
df201b752b53f82bb689e2615fdb777b53c2a39092948393262eccfa16369129 | Quid2/flat | Memory.hs | # LANGUAGE BangPatterns #
# LANGUAGE MagicHash #
# LANGUAGE TypeFamilies #
# LANGUAGE UnboxedTuples #
{- |
Memory access primitives.
Includes code from the [store-core](-core) package.
-}
module Flat.Memory
( chunksToByteString
, chunksToByteArray
, ByteArray
, pokeByteArray
, pokeByteString
, unsafeCreateUptoN'
, minusPtr
, peekByteString
)
where
import Control.Monad (foldM_, when)
import Control.Monad.Primitive (PrimMonad (..))
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as BS
import Data.Primitive.ByteArray (ByteArray, ByteArray#,
MutableByteArray (..), newByteArray,
unsafeFreezeByteArray)
import Foreign (Ptr, Word8, minusPtr, plusPtr,
withForeignPtr)
import GHC.Prim (copyAddrToByteArray#,
copyByteArrayToAddr#)
import GHC.Ptr (Ptr (..))
import GHC.Types (IO (..), Int (..))
import System.IO.Unsafe (unsafeDupablePerformIO,
unsafePerformIO)
unsafeCreateUptoN' :: Int -> (Ptr Word8 -> IO (Int, a)) -> (BS.ByteString, a)
unsafeCreateUptoN' l f = unsafeDupablePerformIO (createUptoN' l f)
# INLINE unsafeCreateUptoN ' #
createUptoN' :: Int -> (Ptr Word8 -> IO (Int, a)) -> IO (BS.ByteString, a)
createUptoN' l f = do
fp <- BS.mallocByteString l
(l', res) <- withForeignPtr fp $ \p -> f p
print ( unwords [ " Buffer allocated:",show l,"bytes , used:",show l',"bytes " ] )
when (l' > l) $ error
(unwords
["Buffer overflow, allocated:", show l, "bytes, used:", show l', "bytes"]
)
return (BS.PS fp 0 l', res) -- , minusPtr l')
# INLINE createUptoN ' #
-- |Copy bytestring to given pointer, returns new pointer
pokeByteString :: B.ByteString -> Ptr Word8 -> IO (Ptr Word8)
pokeByteString (BS.PS foreignPointer sourceOffset sourceLength) destPointer =
do
withForeignPtr foreignPointer $ \sourcePointer -> BS.memcpy
destPointer
(sourcePointer `plusPtr` sourceOffset)
sourceLength
return (destPointer `plusPtr` sourceLength)
| Create a new bytestring , copying sourceLen bytes from sourcePtr
@since 0.6
@since 0.6
-}
peekByteString ::
Ptr Word8 -- ^ sourcePtr
-> Int -- ^ sourceLen
-> BS.ByteString
peekByteString sourcePtr sourceLength = BS.unsafeCreate sourceLength $ \destPointer -> BS.memcpy destPointer sourcePtr sourceLength
|Copy to given pointer , returns new pointer
pokeByteArray :: ByteArray# -> Int -> Int -> Ptr Word8 -> IO (Ptr Word8)
pokeByteArray sourceArr sourceOffset len dest = do
copyByteArrayToAddr sourceArr sourceOffset dest len
let !dest' = dest `plusPtr` len
return dest'
# INLINE pokeByteArray #
| Wrapper around @copyByteArrayToAddr#@ primop .
--
Copied from the store - core package
copyByteArrayToAddr :: ByteArray# -> Int -> Ptr a -> Int -> IO ()
copyByteArrayToAddr arr (I# offset) (Ptr addr) (I# len) =
IO (\s -> (# copyByteArrayToAddr# arr offset addr len s, () #))
# INLINE copyByteArrayToAddr #
chunksToByteString :: (Ptr Word8, [Int]) -> BS.ByteString
chunksToByteString (sourcePtr0, lens) =
BS.unsafeCreate (sum lens) $ \destPtr0 -> foldM_
(\(destPtr, sourcePtr) sourceLength ->
BS.memcpy destPtr sourcePtr sourceLength
>> return
( destPtr `plusPtr` sourceLength
, sourcePtr `plusPtr` (sourceLength + 1)
)
)
(destPtr0, sourcePtr0)
lens
chunksToByteArray :: (Ptr Word8, [Int]) -> (ByteArray, Int)
chunksToByteArray (sourcePtr0, lens) = unsafePerformIO $ do
let len = sum lens
arr <- newByteArray len
foldM_
(\(destOff, sourcePtr) sourceLength ->
copyAddrToByteArray sourcePtr arr destOff sourceLength >> return
(destOff + sourceLength, sourcePtr `plusPtr` (sourceLength + 1))
)
(0, sourcePtr0)
lens
farr <- unsafeFreezeByteArray arr
return (farr, len)
| Wrapper around @copyAddrToByteArray#@ primop .
--
Copied from the store - core package
copyAddrToByteArray
:: Ptr a -> MutableByteArray (PrimState IO) -> Int -> Int -> IO ()
copyAddrToByteArray (Ptr addr) (MutableByteArray arr) (I# offset) (I# len) =
IO (\s -> (# copyAddrToByteArray# addr arr offset len s, () #))
# INLINE copyAddrToByteArray #
| null | https://raw.githubusercontent.com/Quid2/flat/f0a3a0139fbe34074f4b0e7223a2fc767a1b1471/src/Flat/Memory.hs | haskell | |
Memory access primitives.
Includes code from the [store-core](-core) package.
, minusPtr l')
|Copy bytestring to given pointer, returns new pointer
^ sourcePtr
^ sourceLen
| # LANGUAGE BangPatterns #
# LANGUAGE MagicHash #
# LANGUAGE TypeFamilies #
# LANGUAGE UnboxedTuples #
module Flat.Memory
( chunksToByteString
, chunksToByteArray
, ByteArray
, pokeByteArray
, pokeByteString
, unsafeCreateUptoN'
, minusPtr
, peekByteString
)
where
import Control.Monad (foldM_, when)
import Control.Monad.Primitive (PrimMonad (..))
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as BS
import Data.Primitive.ByteArray (ByteArray, ByteArray#,
MutableByteArray (..), newByteArray,
unsafeFreezeByteArray)
import Foreign (Ptr, Word8, minusPtr, plusPtr,
withForeignPtr)
import GHC.Prim (copyAddrToByteArray#,
copyByteArrayToAddr#)
import GHC.Ptr (Ptr (..))
import GHC.Types (IO (..), Int (..))
import System.IO.Unsafe (unsafeDupablePerformIO,
unsafePerformIO)
unsafeCreateUptoN' :: Int -> (Ptr Word8 -> IO (Int, a)) -> (BS.ByteString, a)
unsafeCreateUptoN' l f = unsafeDupablePerformIO (createUptoN' l f)
# INLINE unsafeCreateUptoN ' #
createUptoN' :: Int -> (Ptr Word8 -> IO (Int, a)) -> IO (BS.ByteString, a)
createUptoN' l f = do
fp <- BS.mallocByteString l
(l', res) <- withForeignPtr fp $ \p -> f p
print ( unwords [ " Buffer allocated:",show l,"bytes , used:",show l',"bytes " ] )
when (l' > l) $ error
(unwords
["Buffer overflow, allocated:", show l, "bytes, used:", show l', "bytes"]
)
# INLINE createUptoN ' #
pokeByteString :: B.ByteString -> Ptr Word8 -> IO (Ptr Word8)
pokeByteString (BS.PS foreignPointer sourceOffset sourceLength) destPointer =
do
withForeignPtr foreignPointer $ \sourcePointer -> BS.memcpy
destPointer
(sourcePointer `plusPtr` sourceOffset)
sourceLength
return (destPointer `plusPtr` sourceLength)
| Create a new bytestring , copying sourceLen bytes from sourcePtr
@since 0.6
@since 0.6
-}
peekByteString ::
-> BS.ByteString
peekByteString sourcePtr sourceLength = BS.unsafeCreate sourceLength $ \destPointer -> BS.memcpy destPointer sourcePtr sourceLength
|Copy to given pointer , returns new pointer
pokeByteArray :: ByteArray# -> Int -> Int -> Ptr Word8 -> IO (Ptr Word8)
pokeByteArray sourceArr sourceOffset len dest = do
copyByteArrayToAddr sourceArr sourceOffset dest len
let !dest' = dest `plusPtr` len
return dest'
# INLINE pokeByteArray #
| Wrapper around @copyByteArrayToAddr#@ primop .
Copied from the store - core package
copyByteArrayToAddr :: ByteArray# -> Int -> Ptr a -> Int -> IO ()
copyByteArrayToAddr arr (I# offset) (Ptr addr) (I# len) =
IO (\s -> (# copyByteArrayToAddr# arr offset addr len s, () #))
# INLINE copyByteArrayToAddr #
chunksToByteString :: (Ptr Word8, [Int]) -> BS.ByteString
chunksToByteString (sourcePtr0, lens) =
BS.unsafeCreate (sum lens) $ \destPtr0 -> foldM_
(\(destPtr, sourcePtr) sourceLength ->
BS.memcpy destPtr sourcePtr sourceLength
>> return
( destPtr `plusPtr` sourceLength
, sourcePtr `plusPtr` (sourceLength + 1)
)
)
(destPtr0, sourcePtr0)
lens
chunksToByteArray :: (Ptr Word8, [Int]) -> (ByteArray, Int)
chunksToByteArray (sourcePtr0, lens) = unsafePerformIO $ do
let len = sum lens
arr <- newByteArray len
foldM_
(\(destOff, sourcePtr) sourceLength ->
copyAddrToByteArray sourcePtr arr destOff sourceLength >> return
(destOff + sourceLength, sourcePtr `plusPtr` (sourceLength + 1))
)
(0, sourcePtr0)
lens
farr <- unsafeFreezeByteArray arr
return (farr, len)
| Wrapper around @copyAddrToByteArray#@ primop .
Copied from the store - core package
copyAddrToByteArray
:: Ptr a -> MutableByteArray (PrimState IO) -> Int -> Int -> IO ()
copyAddrToByteArray (Ptr addr) (MutableByteArray arr) (I# offset) (I# len) =
IO (\s -> (# copyAddrToByteArray# addr arr offset len s, () #))
# INLINE copyAddrToByteArray #
|
eda74d5478337e9918c73a0f9067b0d4e45d4a6e9f0bd31d3c932d8e6fb1b65d | gebi/jungerl | epp_dodger.erl | %% =====================================================================
epp_dodger - bypasses the Erlang preprocessor .
%%
Copyright ( C ) 2001
%%
%% This library is free software; you can redistribute it and/or modify
%% it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation ; either version 2 of the
%% License, or (at your option) any later version.
%%
%% This library is distributed in the hope that it will be useful, but
%% WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%% Lesser General Public License for more details.
%%
You should have received a copy of the GNU Lesser General Public
%% License along with this library; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
%%
%% Author contact:
%%
$ Id$
%%
%% =====================================================================
%%
@doc < code > epp_dodger</code > - bypasses the Erlang preprocessor .
%%
< p > This module tokenises and parses most Erlang source code without
%% expanding preprocessor directives and macro applications, as long as
%% these are syntactically "well-behaved". Because the normal parse
%% trees of the <code>erl_parse</code> module cannot represent these
things ( normally , they are expanded by the Erlang preprocessor
%% "<code>epp</code>" before the parser sees them), an extended syntax
%% tree is created, using the <code>erl_syntax</code> module.</p>
%%
%% @end
%% =====================================================================
TODO : document the quick - parse functions properly .
-module(epp_dodger).
-export([parse_file/1, quick_parse_file/1, parse/1, quick_parse/1,
parse/2, quick_parse/2, parse_form/2, quick_parse_form/2,
format_error/1]).
%% =====================================================================
@spec parse_file(File ) - > { ok , Forms } | { error , ErrorInfo }
%% File = file:filename()
%% Forms = [erl_syntax:syntaxTree()]
%% ErrorInfo = term()
%%
%% @doc Reads and parses a file. If successful, <code>{ok, Forms}</code>
%% is returned, where <code>Forms</code> is a list of abstract syntax
%% trees representing the "program forms" of the file (cf.
%% <code>erl_syntax:is_form/1</code>). Otherwise, <code>{error,
%% ErrorInfo}</code> is returned, where <code>ErrorInfo</code> is an
%% Erlang I/O ErrorInfo structure (see module <code>io</code>.)
%%
%% @see erl_syntax:is_form/1
%% @see io
parse_file(File) ->
parse_file(File, fun parse/1).
quick_parse_file(File) ->
parse_file(File, fun quick_parse/1).
parse_file(File, Parser) ->
case file:open(File, [read]) of
{ok, Dev} ->
V = Parser(Dev),
file:close(Dev),
V;
Other ->
Other
end.
%% =====================================================================
) - > { ok , Forms } | { error , ErrorInfo }
@equiv parse(IODevice , 1 )
parse(Dev) ->
parse(Dev, 1).
quick_parse(Dev) ->
quick_parse(Dev, 1).
%% =====================================================================
, StartLine ) - > { ok , Forms } | { error , ErrorInfo }
%% IODevice = pid()
%% StartLine = integer()
%% Forms = [erl_syntax:syntaxTree()]
%% ErrorInfo = term()
%%
%% @doc Reads and parses program text from an I/O stream. Characters are
%% read from <code>IODevice</code> until end-of-file; apart from this,
%% the behaviour is the same as for <code>parse_file/1</code>.
%% <code>StartLine</code> is the initial line number, which should be a
%% positive integer.
%%
%% @see parse_file/1
parse(Dev, L0) ->
parse(Dev, L0, fun parse_form/2).
quick_parse(Dev, L0) ->
parse(Dev, L0, fun quick_parse_form/2).
parse(Dev, L0, Parser) ->
parse(Dev, L0, [], Parser).
parse(Dev, L0, Fs, Parser) ->
case Parser(Dev, L0) of
{ok, none, L1} ->
parse(Dev, L1, Fs, Parser);
{ok, F, L1} ->
parse(Dev, L1, [F | Fs], Parser);
{error, R, L1} ->
parse(Dev, L1, [{error, R} | Fs], Parser);
{eof, _L1} ->
{ok, lists:reverse(Fs)}
end.
%% =====================================================================
, StartLine ) - > { ok , Form , LineNo }
%% | {eof, LineNo}
| { error , ErrorInfo , LineNo }
%% IODevice = pid()
%% StartLine = integer()
%% Form = erl_syntax:syntaxTree() | none
%% ErrorInfo = term()
%% LineNo = integer()
%%
%% @doc Reads and parses a single program form from an I/O stream.
%% Characters are read from <code>IODevice</code> until an end-of-form
%% marker is found (a period character followed by whitespace), or until
%% end-of-file; apart from this, the behaviour is similar to that of
%% <code>parse/2</code>, except that the return values also contain the
%% final line number, given that <code>StartLine</code> is the initial
%% line number, and that <code>{eof, LineNo}</code> may be returned. If
%% the scanning/parsing determines that the form should be discarded,
%% `{ok, none, LineNo}' will be returned.
%%
%% @see parse/2
parse_form(Dev, L0) ->
parse_form(Dev, L0, fun normal_parser/1).
quick_parse_form(Dev, L0) ->
parse_form(Dev, L0, fun quick_parser/1).
parse_form(Dev, L0, Parser) ->
case io:scan_erl_form(Dev, "", L0) of
{ok, Ts, L1} ->
case catch Parser(Ts) of
{'EXIT', _} ->
{error, {L1, ?MODULE, unknown}, L1};
{error, R} ->
{error, R, L1};
F ->
{ok, F, L1}
end;
Other ->
Other
end.
The standard Erlang parser stage
parse_tokens(Ts) ->
case erl_parse:parse_form(Ts) of
{ok, Form} ->
Form;
{error, R} ->
throw({error, R})
end.
%% ---------------------------------------------------------------------
%% Quick scanning/parsing - deletes macro definitions and other
%% preprocessor directives, and replaces all macro calls with atoms.
quick_parser(Ts) ->
filter_form(parse_tokens(quickscan_form(Ts))).
quickscan_form([{'-', _L}, {atom, La, define} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, undef} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, include} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, include_lib} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, ifdef} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, ifndef} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, else} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, endif} | _Ts]) ->
kill_form(La);
quickscan_form(Ts) ->
quickscan_macros(Ts).
kill_form(L) ->
[{atom, L, '?pp'}, {'(', L}, {')', L}, {'->', L}, {atom, L, kill},
{dot, L}].
quickscan_macros([{'?',_}, {atom, L, A} | Ts]) ->
A1 = list_to_atom("?" ++ atom_to_list(A)),
[{atom,L,A1} | quickscan_macros(skip_macro_args(Ts))];
quickscan_macros([{'?',_}, {var, L, A} | Ts]) ->
A1 = list_to_atom("?" ++ atom_to_list(A)),
[{atom,L,A1} | quickscan_macros(skip_macro_args(Ts))];
quickscan_macros([T | Ts]) ->
[T | quickscan_macros(Ts)];
quickscan_macros([]) ->
[].
%% Skipping to the end of a macro call, tracking open/close constructs.
skip_macro_args([{'(',_} | Ts]) ->
skip_macro_args(Ts, [')']);
skip_macro_args(Ts) ->
Ts.
skip_macro_args([{'(',_} | Ts], Es) ->
skip_macro_args(Ts, [')' | Es]);
skip_macro_args([{'{',_} | Ts], Es) ->
skip_macro_args(Ts, ['}' | Es]);
skip_macro_args([{'[',_} | Ts], Es) ->
skip_macro_args(Ts, [']' | Es]);
skip_macro_args([{'<<',_} | Ts], Es) ->
skip_macro_args(Ts, ['>>' | Es]);
skip_macro_args([{'begin',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'if',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'case',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'receive',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'try',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'cond',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{E,_} | Ts], [E]) -> %Found final close
Ts;
skip_macro_args([{E,_} | Ts], [E | Es]) -> %Found matching close
skip_macro_args(Ts, Es);
skip_macro_args([_T | Ts], Es) ->
skip_macro_args(Ts, Es);
skip_macro_args([], _Es) ->
throw({error, nonterminated_macro}).
filter_form({function, _, '?pp', _,
[{clause, _, [], [], [{atom, _, kill}]}]}) ->
none;
filter_form(T) ->
T.
%% ---------------------------------------------------------------------
%% Normal parsing - try to preserve all information
normal_parser(Ts) ->
rewrite_form(parse_tokens(scan_form(Ts))).
scan_form([{'-', _L}, {atom, La, define} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, define} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, undef} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, undef} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, include} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, include} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, include_lib} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, include_lib} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, ifdef} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, ifdef} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, ifndef} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, ifndef} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, else} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, else} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, endif} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, endif} | scan_macros(Ts)];
scan_form(Ts) ->
scan_macros(Ts).
scan_macros([{'?', L}, {atom, La, _} = A, {'(', _}, {')', _} | Ts]) ->
[{'(', L}, {atom, L, '?macro_call'}, {'(', La}, A, {')', La}, {')', La}
| scan_macros(Ts)];
scan_macros([{'?', L}, {atom, La, _} = A, {'(', _} | Ts]) ->
%% We don't try to find the closing parenthesis here
[{atom, L, '?macro_call'}, {'(', La}, A, {',', La}
| scan_macros(Ts)];
scan_macros([{'?', L}, {atom, La, _} = A | Ts]) ->
[{'(', L}, {atom, L, '?macro'}, {'(', La}, A, {')', La}, {')', La}
| scan_macros(Ts)];
scan_macros([{'?', L}, {var, Lv, _} = V, {'(', _}, {')', _} | Ts]) ->
[{'(', L}, {atom, L, '?macro_call'}, {'(', Lv}, V, {')', Lv}, {')', Lv}
| scan_macros(Ts)];
scan_macros([{'?', L}, {var, Lv, _} = V, {'(', _} | Ts]) ->
%% We don't try to find the closing parenthesis here
[{atom, L, '?macro_call'}, {'(', Lv}, V, {',', Lv}
| scan_macros(Ts)];
scan_macros([{'?', L}, {var, Lv, _} = V | Ts]) ->
[{'(', L}, {atom, L, '?macro'}, {'(', L}, V, {')', Lv}, {')', Lv}
| scan_macros(Ts)];
scan_macros([T | Ts]) ->
[T | scan_macros(Ts)];
scan_macros([]) ->
[].
rewrite_form({function, L, '?pp', _,
[{clause, _, [], [], [{call, _, A, As}]}]}) ->
erl_syntax:set_pos(erl_syntax:attribute(A, rewrite_list(As)), L);
rewrite_form({function, L, '?pp', _, [{clause, _, [], [], [A]}]}) ->
erl_syntax:set_pos(erl_syntax:attribute(A), L);
rewrite_form(T) ->
rewrite(T).
rewrite_list([T | Ts]) ->
[rewrite(T) | rewrite_list(Ts)];
rewrite_list([]) ->
[].
rewrite({call, _, {atom, L, '?macro'}, [A]}) ->
erl_syntax:set_pos(erl_syntax:macro(A), L);
rewrite({call, _, {atom, L, '?macro_call'}, [A | As]}) ->
erl_syntax:set_pos(erl_syntax:macro(A, rewrite_list(As)), L);
rewrite(Node) ->
case erl_syntax:subtrees(Node) of
[] ->
Node;
Gs ->
Node1 = erl_syntax:make_tree(erl_syntax:type(Node),
[[rewrite(T) || T <- Ts]
|| Ts <- Gs]),
erl_syntax:copy_pos(Node, Node1)
end.
%% @doc Callback function for formatting error descriptors.
( term ( ) ) - > string ( )
format_error(unknown) -> "epp_dodger: unknown error".
%% =====================================================================
| null | https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/syntax_tools/src/epp_dodger.erl | erlang | =====================================================================
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
License along with this library; if not, write to the Free Software
Author contact:
=====================================================================
expanding preprocessor directives and macro applications, as long as
these are syntactically "well-behaved". Because the normal parse
trees of the <code>erl_parse</code> module cannot represent these
"<code>epp</code>" before the parser sees them), an extended syntax
tree is created, using the <code>erl_syntax</code> module.</p>
@end
=====================================================================
=====================================================================
File = file:filename()
Forms = [erl_syntax:syntaxTree()]
ErrorInfo = term()
@doc Reads and parses a file. If successful, <code>{ok, Forms}</code>
is returned, where <code>Forms</code> is a list of abstract syntax
trees representing the "program forms" of the file (cf.
<code>erl_syntax:is_form/1</code>). Otherwise, <code>{error,
ErrorInfo}</code> is returned, where <code>ErrorInfo</code> is an
Erlang I/O ErrorInfo structure (see module <code>io</code>.)
@see erl_syntax:is_form/1
@see io
=====================================================================
=====================================================================
IODevice = pid()
StartLine = integer()
Forms = [erl_syntax:syntaxTree()]
ErrorInfo = term()
@doc Reads and parses program text from an I/O stream. Characters are
read from <code>IODevice</code> until end-of-file; apart from this,
the behaviour is the same as for <code>parse_file/1</code>.
<code>StartLine</code> is the initial line number, which should be a
positive integer.
@see parse_file/1
=====================================================================
| {eof, LineNo}
IODevice = pid()
StartLine = integer()
Form = erl_syntax:syntaxTree() | none
ErrorInfo = term()
LineNo = integer()
@doc Reads and parses a single program form from an I/O stream.
Characters are read from <code>IODevice</code> until an end-of-form
marker is found (a period character followed by whitespace), or until
end-of-file; apart from this, the behaviour is similar to that of
<code>parse/2</code>, except that the return values also contain the
final line number, given that <code>StartLine</code> is the initial
line number, and that <code>{eof, LineNo}</code> may be returned. If
the scanning/parsing determines that the form should be discarded,
`{ok, none, LineNo}' will be returned.
@see parse/2
---------------------------------------------------------------------
Quick scanning/parsing - deletes macro definitions and other
preprocessor directives, and replaces all macro calls with atoms.
Skipping to the end of a macro call, tracking open/close constructs.
Found final close
Found matching close
---------------------------------------------------------------------
Normal parsing - try to preserve all information
We don't try to find the closing parenthesis here
We don't try to find the closing parenthesis here
@doc Callback function for formatting error descriptors.
===================================================================== | epp_dodger - bypasses the Erlang preprocessor .
Copyright ( C ) 2001
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA
$ Id$
@doc < code > epp_dodger</code > - bypasses the Erlang preprocessor .
< p > This module tokenises and parses most Erlang source code without
things ( normally , they are expanded by the Erlang preprocessor
TODO : document the quick - parse functions properly .
-module(epp_dodger).
-export([parse_file/1, quick_parse_file/1, parse/1, quick_parse/1,
parse/2, quick_parse/2, parse_form/2, quick_parse_form/2,
format_error/1]).
@spec parse_file(File ) - > { ok , Forms } | { error , ErrorInfo }
parse_file(File) ->
parse_file(File, fun parse/1).
quick_parse_file(File) ->
parse_file(File, fun quick_parse/1).
parse_file(File, Parser) ->
case file:open(File, [read]) of
{ok, Dev} ->
V = Parser(Dev),
file:close(Dev),
V;
Other ->
Other
end.
) - > { ok , Forms } | { error , ErrorInfo }
@equiv parse(IODevice , 1 )
parse(Dev) ->
parse(Dev, 1).
quick_parse(Dev) ->
quick_parse(Dev, 1).
, StartLine ) - > { ok , Forms } | { error , ErrorInfo }
parse(Dev, L0) ->
parse(Dev, L0, fun parse_form/2).
quick_parse(Dev, L0) ->
parse(Dev, L0, fun quick_parse_form/2).
parse(Dev, L0, Parser) ->
parse(Dev, L0, [], Parser).
parse(Dev, L0, Fs, Parser) ->
case Parser(Dev, L0) of
{ok, none, L1} ->
parse(Dev, L1, Fs, Parser);
{ok, F, L1} ->
parse(Dev, L1, [F | Fs], Parser);
{error, R, L1} ->
parse(Dev, L1, [{error, R} | Fs], Parser);
{eof, _L1} ->
{ok, lists:reverse(Fs)}
end.
, StartLine ) - > { ok , Form , LineNo }
| { error , ErrorInfo , LineNo }
parse_form(Dev, L0) ->
parse_form(Dev, L0, fun normal_parser/1).
quick_parse_form(Dev, L0) ->
parse_form(Dev, L0, fun quick_parser/1).
parse_form(Dev, L0, Parser) ->
case io:scan_erl_form(Dev, "", L0) of
{ok, Ts, L1} ->
case catch Parser(Ts) of
{'EXIT', _} ->
{error, {L1, ?MODULE, unknown}, L1};
{error, R} ->
{error, R, L1};
F ->
{ok, F, L1}
end;
Other ->
Other
end.
The standard Erlang parser stage
parse_tokens(Ts) ->
case erl_parse:parse_form(Ts) of
{ok, Form} ->
Form;
{error, R} ->
throw({error, R})
end.
quick_parser(Ts) ->
filter_form(parse_tokens(quickscan_form(Ts))).
quickscan_form([{'-', _L}, {atom, La, define} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, undef} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, include} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, include_lib} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, ifdef} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, ifndef} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, else} | _Ts]) ->
kill_form(La);
quickscan_form([{'-', _L}, {atom, La, endif} | _Ts]) ->
kill_form(La);
quickscan_form(Ts) ->
quickscan_macros(Ts).
kill_form(L) ->
[{atom, L, '?pp'}, {'(', L}, {')', L}, {'->', L}, {atom, L, kill},
{dot, L}].
quickscan_macros([{'?',_}, {atom, L, A} | Ts]) ->
A1 = list_to_atom("?" ++ atom_to_list(A)),
[{atom,L,A1} | quickscan_macros(skip_macro_args(Ts))];
quickscan_macros([{'?',_}, {var, L, A} | Ts]) ->
A1 = list_to_atom("?" ++ atom_to_list(A)),
[{atom,L,A1} | quickscan_macros(skip_macro_args(Ts))];
quickscan_macros([T | Ts]) ->
[T | quickscan_macros(Ts)];
quickscan_macros([]) ->
[].
skip_macro_args([{'(',_} | Ts]) ->
skip_macro_args(Ts, [')']);
skip_macro_args(Ts) ->
Ts.
skip_macro_args([{'(',_} | Ts], Es) ->
skip_macro_args(Ts, [')' | Es]);
skip_macro_args([{'{',_} | Ts], Es) ->
skip_macro_args(Ts, ['}' | Es]);
skip_macro_args([{'[',_} | Ts], Es) ->
skip_macro_args(Ts, [']' | Es]);
skip_macro_args([{'<<',_} | Ts], Es) ->
skip_macro_args(Ts, ['>>' | Es]);
skip_macro_args([{'begin',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'if',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'case',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'receive',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'try',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
skip_macro_args([{'cond',_} | Ts], Es) ->
skip_macro_args(Ts, ['end' | Es]);
Ts;
skip_macro_args(Ts, Es);
skip_macro_args([_T | Ts], Es) ->
skip_macro_args(Ts, Es);
skip_macro_args([], _Es) ->
throw({error, nonterminated_macro}).
filter_form({function, _, '?pp', _,
[{clause, _, [], [], [{atom, _, kill}]}]}) ->
none;
filter_form(T) ->
T.
normal_parser(Ts) ->
rewrite_form(parse_tokens(scan_form(Ts))).
scan_form([{'-', _L}, {atom, La, define} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, define} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, undef} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, undef} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, include} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, include} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, include_lib} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, include_lib} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, ifdef} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, ifdef} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, ifndef} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, ifndef} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, else} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, else} | scan_macros(Ts)];
scan_form([{'-', _L}, {atom, La, endif} | Ts]) ->
[{atom, La, '?pp'}, {'(', La}, {')', La}, {'->', La},
{atom, La, endif} | scan_macros(Ts)];
scan_form(Ts) ->
scan_macros(Ts).
scan_macros([{'?', L}, {atom, La, _} = A, {'(', _}, {')', _} | Ts]) ->
[{'(', L}, {atom, L, '?macro_call'}, {'(', La}, A, {')', La}, {')', La}
| scan_macros(Ts)];
scan_macros([{'?', L}, {atom, La, _} = A, {'(', _} | Ts]) ->
[{atom, L, '?macro_call'}, {'(', La}, A, {',', La}
| scan_macros(Ts)];
scan_macros([{'?', L}, {atom, La, _} = A | Ts]) ->
[{'(', L}, {atom, L, '?macro'}, {'(', La}, A, {')', La}, {')', La}
| scan_macros(Ts)];
scan_macros([{'?', L}, {var, Lv, _} = V, {'(', _}, {')', _} | Ts]) ->
[{'(', L}, {atom, L, '?macro_call'}, {'(', Lv}, V, {')', Lv}, {')', Lv}
| scan_macros(Ts)];
scan_macros([{'?', L}, {var, Lv, _} = V, {'(', _} | Ts]) ->
[{atom, L, '?macro_call'}, {'(', Lv}, V, {',', Lv}
| scan_macros(Ts)];
scan_macros([{'?', L}, {var, Lv, _} = V | Ts]) ->
[{'(', L}, {atom, L, '?macro'}, {'(', L}, V, {')', Lv}, {')', Lv}
| scan_macros(Ts)];
scan_macros([T | Ts]) ->
[T | scan_macros(Ts)];
scan_macros([]) ->
[].
rewrite_form({function, L, '?pp', _,
[{clause, _, [], [], [{call, _, A, As}]}]}) ->
erl_syntax:set_pos(erl_syntax:attribute(A, rewrite_list(As)), L);
rewrite_form({function, L, '?pp', _, [{clause, _, [], [], [A]}]}) ->
erl_syntax:set_pos(erl_syntax:attribute(A), L);
rewrite_form(T) ->
rewrite(T).
rewrite_list([T | Ts]) ->
[rewrite(T) | rewrite_list(Ts)];
rewrite_list([]) ->
[].
rewrite({call, _, {atom, L, '?macro'}, [A]}) ->
erl_syntax:set_pos(erl_syntax:macro(A), L);
rewrite({call, _, {atom, L, '?macro_call'}, [A | As]}) ->
erl_syntax:set_pos(erl_syntax:macro(A, rewrite_list(As)), L);
rewrite(Node) ->
case erl_syntax:subtrees(Node) of
[] ->
Node;
Gs ->
Node1 = erl_syntax:make_tree(erl_syntax:type(Node),
[[rewrite(T) || T <- Ts]
|| Ts <- Gs]),
erl_syntax:copy_pos(Node, Node1)
end.
( term ( ) ) - > string ( )
format_error(unknown) -> "epp_dodger: unknown error".
|
37259a86690ab563af47946d46f735287a5dcaf1bdae28c7025ed043140e9d17 | lindenbaum/hinterface | Epmd.hs | {-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# HLINT ignore "Use camelCase" #-}
module Foreign.Erlang.Epmd
( -- * List registered nodes
epmdNames,
NamesResponse (..),
-- * Looking up nodes
lookupNode,
-- * Registering nodes
registerNode,
NodeRegistration (nr_creation),
mkTestingNodeRegistration,
)
where
import Util . IOExtra
import Control.Monad (when)
import Control.Monad.Logger
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy.Char8 as CL
import Data.Maybe
import Foreign.Erlang.NodeData
import Network.BufferedSocket
import UnliftIO
import UnliftIO.Resource
import Util.Binary
import Util.BufferedIOx
import Util.IOExtra (logInfoShow)
import Util.Socket
import Data.Text (Text)
import qualified Data.Text.Encoding as Text
--------------------------------------------------------------------------------
epmdPort :: Word16
epmdPort = 4369
--------------------------------------------------------------------------------
names_req, port_please2_req, port_please2_resp, alive2_req, alive2_resp :: Word8
names_req = 110
port_please2_req = 122
port_please2_resp = 119
alive2_req = 120
alive2_resp = 121
--------------------------------------------------------------------------------
data NamesRequest = NamesRequest
deriving (Eq, Show)
instance Binary NamesRequest where
put _ =
putWithLength16be $
putWord8 names_req
get = undefined
data NodeInfo = NodeInfo String Word16
deriving (Eq, Show)
data NamesResponse = NamesResponse Word16 [NodeInfo]
deriving (Eq, Show)
instance Binary NamesResponse where
put _ = undefined
get = do
epmdPortNo <- getWord32be
NamesResponse
(fromIntegral epmdPortNo)
. mapMaybe nodeInfo
. CL.lines
<$> getRemainingLazyByteString
where
nodeInfo :: CL.ByteString -> Maybe NodeInfo
nodeInfo cl = do
["name", name, "at", "port", portString] <- Just $ CL.split ' ' cl
(port, "") <- CL.readInt portString
return $ NodeInfo (CL.unpack name) (fromIntegral port)
-- | List all registered nodes
epmdNames ::
(MonadUnliftIO m, MonadResource m, MonadLoggerIO m) =>
-- | hostname
Text ->
m NamesResponse
epmdNames hostName = withBufferedSocket hostName (sendRequest NamesRequest)
--------------------------------------------------------------------------------
newtype LookupNodeRequest = LookupNodeRequest Text
deriving (Eq, Show)
instance Binary LookupNodeRequest where
put (LookupNodeRequest alive) =
putWithLength16be $ do
putWord8 port_please2_req
putByteString (Text.encodeUtf8 alive)
get = undefined
newtype LookupNodeResponse = LookupNodeResponse {fromLookupNodeResponse :: Maybe NodeData}
deriving (Eq, Show)
instance Binary LookupNodeResponse where
put _ = undefined
get =
LookupNodeResponse <$> do
matchWord8 port_please2_resp
result <- getWord8
if result > 0
then return Nothing
else Just <$> get
-- | Lookup a node
lookupNode ::
(MonadUnliftIO m, MonadResource m, MonadLoggerIO m) =>
-- | alive
Text ->
-- | hostname
Text ->
m (Maybe NodeData)
lookupNode alive hostName =
fromLookupNodeResponse
<$> withBufferedSocket
hostName
( sendRequest
(LookupNodeRequest alive)
)
--------------------------------------------------------------------------------
newtype RegisterNodeRequest = RegisterNodeRequest NodeData
deriving (Eq, Show)
instance Binary RegisterNodeRequest where
put (RegisterNodeRequest node) =
putWithLength16be $ do
putWord8 alive2_req
put node
get = undefined
newtype RegisterNodeResponse = RegisterNodeResponse (Maybe Word16)
deriving (Eq, Show)
instance Binary RegisterNodeResponse where
put _ = undefined
get =
RegisterNodeResponse <$> do
matchWord8 alive2_resp
result <- getWord8
if result > 0
then return Nothing
else Just <$> getWord16be
newtype NodeRegistration = NodeRegistration {nr_creation :: Word16}
newtype NodeAlreadyRegistered = NodeAlreadyRegistered NodeData
deriving (Show)
instance Exception NodeAlreadyRegistered
-- | Register a node with an epmd; as long as the TCP connection is open, the
-- registration is considered valid.
registerNode ::
(MonadResource m, MonadLoggerIO m, MonadUnliftIO m) =>
-- | node
NodeData ->
-- | hostName
Text ->
-- | action to execute while the TCP connection is alive
(NodeRegistration -> m a) ->
m a
registerNode node hostName action =
withBufferedSocket hostName go
where
go sock = do
r@(RegisterNodeResponse mr) <-
sendRequest
(RegisterNodeRequest node)
sock
logInfoShow r
when (isNothing mr) (throwIO (NodeAlreadyRegistered node))
action (NodeRegistration (fromJust mr))
mkTestingNodeRegistration :: Word16 -> NodeRegistration
mkTestingNodeRegistration = NodeRegistration
sendRequest ::
(MonadLoggerIO m, MonadUnliftIO m, MonadIO m, BufferedIOx s, Binary a, Binary b) =>
a ->
s ->
m b
sendRequest req sock = do
runPutBuffered sock req
runGetBuffered sock
withBufferedSocket ::
(MonadIO m, MonadUnliftIO m) =>
-- | hostName
Text ->
(BufferedSocket -> m b) ->
m b
withBufferedSocket hostName =
bracket (liftIO $ connectBufferedSocket hostName) (liftIO . closeBuffered)
connectBufferedSocket ::
(MonadIO m) =>
-- | hostName
Text ->
m BufferedSocket
connectBufferedSocket hostName =
liftIO $
connectSocket hostName epmdPort >>= makeBuffered
| null | https://raw.githubusercontent.com/lindenbaum/hinterface/e49810b5984486cebad6fa06dba0f2c7f2bfd2fa/src/Foreign/Erlang/Epmd.hs | haskell | # OPTIONS_GHC -Wno-unrecognised-pragmas #
# HLINT ignore "Use camelCase" #
* List registered nodes
* Looking up nodes
* Registering nodes
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| List all registered nodes
| hostname
------------------------------------------------------------------------------
| Lookup a node
| alive
| hostname
------------------------------------------------------------------------------
| Register a node with an epmd; as long as the TCP connection is open, the
registration is considered valid.
| node
| hostName
| action to execute while the TCP connection is alive
| hostName
| hostName |
module Foreign.Erlang.Epmd
epmdNames,
NamesResponse (..),
lookupNode,
registerNode,
NodeRegistration (nr_creation),
mkTestingNodeRegistration,
)
where
import Util . IOExtra
import Control.Monad (when)
import Control.Monad.Logger
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy.Char8 as CL
import Data.Maybe
import Foreign.Erlang.NodeData
import Network.BufferedSocket
import UnliftIO
import UnliftIO.Resource
import Util.Binary
import Util.BufferedIOx
import Util.IOExtra (logInfoShow)
import Util.Socket
import Data.Text (Text)
import qualified Data.Text.Encoding as Text
epmdPort :: Word16
epmdPort = 4369
names_req, port_please2_req, port_please2_resp, alive2_req, alive2_resp :: Word8
names_req = 110
port_please2_req = 122
port_please2_resp = 119
alive2_req = 120
alive2_resp = 121
data NamesRequest = NamesRequest
deriving (Eq, Show)
instance Binary NamesRequest where
put _ =
putWithLength16be $
putWord8 names_req
get = undefined
data NodeInfo = NodeInfo String Word16
deriving (Eq, Show)
data NamesResponse = NamesResponse Word16 [NodeInfo]
deriving (Eq, Show)
instance Binary NamesResponse where
put _ = undefined
get = do
epmdPortNo <- getWord32be
NamesResponse
(fromIntegral epmdPortNo)
. mapMaybe nodeInfo
. CL.lines
<$> getRemainingLazyByteString
where
nodeInfo :: CL.ByteString -> Maybe NodeInfo
nodeInfo cl = do
["name", name, "at", "port", portString] <- Just $ CL.split ' ' cl
(port, "") <- CL.readInt portString
return $ NodeInfo (CL.unpack name) (fromIntegral port)
epmdNames ::
(MonadUnliftIO m, MonadResource m, MonadLoggerIO m) =>
Text ->
m NamesResponse
epmdNames hostName = withBufferedSocket hostName (sendRequest NamesRequest)
newtype LookupNodeRequest = LookupNodeRequest Text
deriving (Eq, Show)
instance Binary LookupNodeRequest where
put (LookupNodeRequest alive) =
putWithLength16be $ do
putWord8 port_please2_req
putByteString (Text.encodeUtf8 alive)
get = undefined
newtype LookupNodeResponse = LookupNodeResponse {fromLookupNodeResponse :: Maybe NodeData}
deriving (Eq, Show)
instance Binary LookupNodeResponse where
put _ = undefined
get =
LookupNodeResponse <$> do
matchWord8 port_please2_resp
result <- getWord8
if result > 0
then return Nothing
else Just <$> get
lookupNode ::
(MonadUnliftIO m, MonadResource m, MonadLoggerIO m) =>
Text ->
Text ->
m (Maybe NodeData)
lookupNode alive hostName =
fromLookupNodeResponse
<$> withBufferedSocket
hostName
( sendRequest
(LookupNodeRequest alive)
)
newtype RegisterNodeRequest = RegisterNodeRequest NodeData
deriving (Eq, Show)
instance Binary RegisterNodeRequest where
put (RegisterNodeRequest node) =
putWithLength16be $ do
putWord8 alive2_req
put node
get = undefined
newtype RegisterNodeResponse = RegisterNodeResponse (Maybe Word16)
deriving (Eq, Show)
instance Binary RegisterNodeResponse where
put _ = undefined
get =
RegisterNodeResponse <$> do
matchWord8 alive2_resp
result <- getWord8
if result > 0
then return Nothing
else Just <$> getWord16be
newtype NodeRegistration = NodeRegistration {nr_creation :: Word16}
newtype NodeAlreadyRegistered = NodeAlreadyRegistered NodeData
deriving (Show)
instance Exception NodeAlreadyRegistered
registerNode ::
(MonadResource m, MonadLoggerIO m, MonadUnliftIO m) =>
NodeData ->
Text ->
(NodeRegistration -> m a) ->
m a
registerNode node hostName action =
withBufferedSocket hostName go
where
go sock = do
r@(RegisterNodeResponse mr) <-
sendRequest
(RegisterNodeRequest node)
sock
logInfoShow r
when (isNothing mr) (throwIO (NodeAlreadyRegistered node))
action (NodeRegistration (fromJust mr))
mkTestingNodeRegistration :: Word16 -> NodeRegistration
mkTestingNodeRegistration = NodeRegistration
sendRequest ::
(MonadLoggerIO m, MonadUnliftIO m, MonadIO m, BufferedIOx s, Binary a, Binary b) =>
a ->
s ->
m b
sendRequest req sock = do
runPutBuffered sock req
runGetBuffered sock
withBufferedSocket ::
(MonadIO m, MonadUnliftIO m) =>
Text ->
(BufferedSocket -> m b) ->
m b
withBufferedSocket hostName =
bracket (liftIO $ connectBufferedSocket hostName) (liftIO . closeBuffered)
connectBufferedSocket ::
(MonadIO m) =>
Text ->
m BufferedSocket
connectBufferedSocket hostName =
liftIO $
connectSocket hostName epmdPort >>= makeBuffered
|
3e7dd5910aaf2e3e9bd3bc44582fd643a9b8d95684274eb07725e04554fea2b8 | ekmett/guanxi | Vec.hs | # language BlockArguments #
{-# language TupleSections #-}
# language PatternSynonyms #
module Vec where
import Control.Monad.Primitive
import Control.Monad.ST
import Data.Bits
import Data.Primitive.Types
import Data.Primitive.PrimArray
import Data.Primitive.MutVar
import Ref
-- transient
data Vec s a = Vec {-# unpack #-} !Int {-# unpack #-} !(MutablePrimArray s a)
-- non-backtracking writes by default
newtype s a = ( MVar s ( Slab s a ) )
pattern DEFAULT_SIZE :: Int
pattern DEFAULT_SIZE = 4
newVec_ :: (PrimMonad m, Prim a) => m (Vec (PrimState m) a)
newVec_ = newVec DEFAULT_SIZE
newVec :: (PrimMonad m, Prim a) => Int -> m (Vec (PrimState m) a)
newVec n = stToPrim do Vec 0 <$> newPrimArray n
{-# inline newVec #-}
addVec :: (PrimMonad m, Prim a) => a -> Vec (PrimState m) a -> m (Int, Vec (PrimState m) a)
addVec a (Vec i pa) = stToPrim do
n <- getSizeofMutablePrimArray pa
if i < n then do
writePrimArray pa i a
return (i, Vec (i+1) pa)
else do
pa' <- resizeMutablePrimArray pa (n*2)
writePrimArray pa' i a
return (i, Vec (i+1) pa')
# inline addVec #
subVec :: (PrimMonad m, Prim a) => Vec (PrimState m) a -> m (Vec (PrimState m) a)
subVec (Vec i pa) = stToPrim do
n <- getSizeofMutablePrimArray pa
let n' = unsafeShiftR n 2
if i >= n' then return $ Vec (i-1) pa
else Vec (i-1) <$> resizeMutablePrimArray pa (n*2)
readVec :: (PrimMonad m, Prim a) => Vec (PrimState m) a -> Int -> m a
readVec (Vec _ pa) i = readPrimArray pa i
# inline readVec #
-- doesn't change shape
writeVec :: (PrimMonad m, Prim a) => Vec (PrimState m) a -> Int -> a -> m ()
writeVec (Vec _ pa) i a = writePrimArray pa i a
{-# inline writeVec #-}
sizeVec :: Vec s a -> Int
sizeVec (Vec i _ ) = i
{-# inline sizeVec #-}
-- this would play the role of std::vector, non-transient non-thread-safe version
newtype Vector s a = Vector (MutVar s (Vec s a))
newVector :: (PrimMonad m, Prim a) => Int -> m (Vector (PrimState m) a)
newVector n = stToPrim do
v <- newVec n
Vector <$> newMutVar v
# inline newVector #
-- not thread safe
nonAtomicModifyVector :: PrimMonad m => Vector (PrimState m) a -> (Vec (PrimState m) a -> ST (PrimState m) (r, Vec (PrimState m) a)) -> m r
nonAtomicModifyVector (Vector ref) k = stToPrim do
v <- readMutVar ref
(r, v') <- k v
r <$ writeMutVar ref v'
# inline nonAtomicModifyVector #
modifyVector :: PrimMonad m => Vector (PrimState m) a -> (Vec (PrimState m) a -> ST (PrimState m) (Vec (PrimState m) a)) -> m ()
modifyVector (Vector ref) k = stToPrim $ (readMutVar ref >>= k) >>= writeMutVar ref
# inline modifyVector #
addVector :: (PrimMonad m, Prim a) => a -> Vector (PrimState m) a -> m Int
addVector a v = nonAtomicModifyVector v \vec -> addVec a vec
# inline addVector #
subVector :: (PrimMonad m, Prim a) => Vector (PrimState m) a -> m ()
subVector v = modifyVector v subVec
# inline subVector #
readVector :: (PrimMonad m, Prim a) => Vector (PrimState m) a -> Int -> m a
readVector (Vector ref) i = readMutVar ref >>= \(Vec _ pa) -> readPrimArray pa i
# inline readVector #
writeVector :: (PrimMonad m, Prim a) => Vector (PrimState m) a -> Int -> a -> m ()
writeVector (Vector ref) i a = readMutVar ref >>= \vec -> writeVec vec i a
# inline writeVector #
sizeVector :: PrimMonad m => Vector (PrimState m) a -> m Int
sizeVector (Vector ref) = stToPrim $ sizeVec <$> readMutVar ref
# inline sizeVector #
-- safe backtracking operations:
--
-- newVector
-- readVector
-- addBackVector
-- writeBackVector
-- sizeVector
addBackVector :: (MonadRef m, Prim a) => a -> Vector (PrimState m) a -> m Int
addBackVector a v = unwind (,()) (\_->subVector v) $ stToPrim $ addVector a v
# inline addBackVector #
writeBackVector :: (MonadRef m, Prim a) => Vector (PrimState m) a -> Int -> a -> m a -- returns old value
writeBackVector v@(Vector ref) i a = unwind (\x -> (x,x)) (writeVector v i) $ do
vec <- readMutVar ref
old <- readVec vec i
old <$ writeVec vec i a
{-# inline writeBackVector #-}
| null | https://raw.githubusercontent.com/ekmett/guanxi/e267f4210a9c10d0091371ea9b028b7d6fa8b9f3/src/Vec.hs | haskell | # language TupleSections #
transient
# unpack #
# unpack #
non-backtracking writes by default
# inline newVec #
doesn't change shape
# inline writeVec #
# inline sizeVec #
this would play the role of std::vector, non-transient non-thread-safe version
not thread safe
safe backtracking operations:
newVector
readVector
addBackVector
writeBackVector
sizeVector
returns old value
# inline writeBackVector # | # language BlockArguments #
# language PatternSynonyms #
module Vec where
import Control.Monad.Primitive
import Control.Monad.ST
import Data.Bits
import Data.Primitive.Types
import Data.Primitive.PrimArray
import Data.Primitive.MutVar
import Ref
newtype s a = ( MVar s ( Slab s a ) )
pattern DEFAULT_SIZE :: Int
pattern DEFAULT_SIZE = 4
newVec_ :: (PrimMonad m, Prim a) => m (Vec (PrimState m) a)
newVec_ = newVec DEFAULT_SIZE
newVec :: (PrimMonad m, Prim a) => Int -> m (Vec (PrimState m) a)
newVec n = stToPrim do Vec 0 <$> newPrimArray n
addVec :: (PrimMonad m, Prim a) => a -> Vec (PrimState m) a -> m (Int, Vec (PrimState m) a)
addVec a (Vec i pa) = stToPrim do
n <- getSizeofMutablePrimArray pa
if i < n then do
writePrimArray pa i a
return (i, Vec (i+1) pa)
else do
pa' <- resizeMutablePrimArray pa (n*2)
writePrimArray pa' i a
return (i, Vec (i+1) pa')
# inline addVec #
subVec :: (PrimMonad m, Prim a) => Vec (PrimState m) a -> m (Vec (PrimState m) a)
subVec (Vec i pa) = stToPrim do
n <- getSizeofMutablePrimArray pa
let n' = unsafeShiftR n 2
if i >= n' then return $ Vec (i-1) pa
else Vec (i-1) <$> resizeMutablePrimArray pa (n*2)
readVec :: (PrimMonad m, Prim a) => Vec (PrimState m) a -> Int -> m a
readVec (Vec _ pa) i = readPrimArray pa i
# inline readVec #
writeVec :: (PrimMonad m, Prim a) => Vec (PrimState m) a -> Int -> a -> m ()
writeVec (Vec _ pa) i a = writePrimArray pa i a
sizeVec :: Vec s a -> Int
sizeVec (Vec i _ ) = i
newtype Vector s a = Vector (MutVar s (Vec s a))
newVector :: (PrimMonad m, Prim a) => Int -> m (Vector (PrimState m) a)
newVector n = stToPrim do
v <- newVec n
Vector <$> newMutVar v
# inline newVector #
nonAtomicModifyVector :: PrimMonad m => Vector (PrimState m) a -> (Vec (PrimState m) a -> ST (PrimState m) (r, Vec (PrimState m) a)) -> m r
nonAtomicModifyVector (Vector ref) k = stToPrim do
v <- readMutVar ref
(r, v') <- k v
r <$ writeMutVar ref v'
# inline nonAtomicModifyVector #
modifyVector :: PrimMonad m => Vector (PrimState m) a -> (Vec (PrimState m) a -> ST (PrimState m) (Vec (PrimState m) a)) -> m ()
modifyVector (Vector ref) k = stToPrim $ (readMutVar ref >>= k) >>= writeMutVar ref
# inline modifyVector #
addVector :: (PrimMonad m, Prim a) => a -> Vector (PrimState m) a -> m Int
addVector a v = nonAtomicModifyVector v \vec -> addVec a vec
# inline addVector #
subVector :: (PrimMonad m, Prim a) => Vector (PrimState m) a -> m ()
subVector v = modifyVector v subVec
# inline subVector #
readVector :: (PrimMonad m, Prim a) => Vector (PrimState m) a -> Int -> m a
readVector (Vector ref) i = readMutVar ref >>= \(Vec _ pa) -> readPrimArray pa i
# inline readVector #
writeVector :: (PrimMonad m, Prim a) => Vector (PrimState m) a -> Int -> a -> m ()
writeVector (Vector ref) i a = readMutVar ref >>= \vec -> writeVec vec i a
# inline writeVector #
sizeVector :: PrimMonad m => Vector (PrimState m) a -> m Int
sizeVector (Vector ref) = stToPrim $ sizeVec <$> readMutVar ref
# inline sizeVector #
addBackVector :: (MonadRef m, Prim a) => a -> Vector (PrimState m) a -> m Int
addBackVector a v = unwind (,()) (\_->subVector v) $ stToPrim $ addVector a v
# inline addBackVector #
writeBackVector v@(Vector ref) i a = unwind (\x -> (x,x)) (writeVector v i) $ do
vec <- readMutVar ref
old <- readVec vec i
old <$ writeVec vec i a
|
e64cbfa1ada4a048844d201a23af12931b3bfdce4526b02a6cc1e66c237f6ef4 | emqx/emqx | emqx_gateway_schema.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_gateway_schema).
-behaviour(hocon_schema).
-dialyzer(no_return).
-dialyzer(no_match).
-dialyzer(no_contracts).
-dialyzer(no_unused).
-dialyzer(no_fail_call).
-include_lib("emqx/include/emqx_authentication.hrl").
-include_lib("hocon/include/hoconsc.hrl").
-include_lib("typerefl/include/types.hrl").
-type ip_port() :: tuple() | integer().
-type duration() :: non_neg_integer().
-type duration_s() :: non_neg_integer().
-type bytesize() :: pos_integer().
-type comma_separated_list() :: list().
-typerefl_from_string({ip_port/0, emqx_schema, to_ip_port}).
-typerefl_from_string({duration/0, emqx_schema, to_duration}).
-typerefl_from_string({duration_s/0, emqx_schema, to_duration_s}).
-typerefl_from_string({bytesize/0, emqx_schema, to_bytesize}).
-typerefl_from_string({comma_separated_list/0, emqx_schema, to_comma_separated_list}).
-reflect_type([
duration/0,
duration_s/0,
bytesize/0,
comma_separated_list/0,
ip_port/0
]).
-elvis([{elvis_style, dont_repeat_yourself, disable}]).
-export([namespace/0, roots/0, fields/1, desc/1, tags/0]).
-export([proxy_protocol_opts/0]).
namespace() -> gateway.
tags() ->
[<<"Gateway">>].
roots() -> [gateway].
fields(gateway) ->
[
{stomp,
sc(
ref(stomp),
#{
required => {false, recursively},
desc => ?DESC(stomp)
}
)},
{mqttsn,
sc(
ref(mqttsn),
#{
required => {false, recursively},
desc => ?DESC(mqttsn)
}
)},
{coap,
sc(
ref(coap),
#{
required => {false, recursively},
desc => ?DESC(coap)
}
)},
{lwm2m,
sc(
ref(lwm2m),
#{
required => {false, recursively},
desc => ?DESC(lwm2m)
}
)},
{exproto,
sc(
ref(exproto),
#{
required => {false, recursively},
desc => ?DESC(exproto)
}
)}
];
fields(stomp) ->
[
{frame, sc(ref(stomp_frame))},
{mountpoint, mountpoint()},
{listeners, sc(ref(tcp_listeners), #{desc => ?DESC(tcp_listeners)})}
] ++ gateway_common_options();
fields(stomp_frame) ->
[
{max_headers,
sc(
non_neg_integer(),
#{
default => 10,
desc => ?DESC(stom_frame_max_headers)
}
)},
{max_headers_length,
sc(
non_neg_integer(),
#{
default => 1024,
desc => ?DESC(stomp_frame_max_headers_length)
}
)},
{max_body_length,
sc(
integer(),
#{
default => 65536,
desc => ?DESC(stom_frame_max_body_length)
}
)}
];
fields(mqttsn) ->
[
{gateway_id,
sc(
integer(),
#{
default => 1,
required => true,
desc => ?DESC(mqttsn_gateway_id)
}
)},
{broadcast,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_broadcast)
}
)},
TODO : rename
{enable_qos3,
sc(
boolean(),
#{
default => true,
desc => ?DESC(mqttsn_enable_qos3)
}
)},
{subs_resume,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_subs_resume)
}
)},
{predefined,
sc(
hoconsc:array(ref(mqttsn_predefined)),
#{
default => [],
required => {false, recursively},
desc => ?DESC(mqttsn_predefined)
}
)},
{mountpoint, mountpoint()},
{listeners, sc(ref(udp_listeners), #{desc => ?DESC(udp_listeners)})}
] ++ gateway_common_options();
fields(mqttsn_predefined) ->
[
{id,
sc(integer(), #{
required => true,
desc => ?DESC(mqttsn_predefined_id)
})},
{topic,
sc(binary(), #{
required => true,
desc => ?DESC(mqttsn_predefined_topic)
})}
];
fields(coap) ->
[
{heartbeat,
sc(
duration(),
#{
default => <<"30s">>,
desc => ?DESC(coap_heartbeat)
}
)},
{connection_required,
sc(
boolean(),
#{
default => false,
desc => ?DESC(coap_connection_required)
}
)},
{notify_type,
sc(
hoconsc:enum([non, con, qos]),
#{
default => qos,
desc => ?DESC(coap_notify_type)
}
)},
{subscribe_qos,
sc(
hoconsc:enum([qos0, qos1, qos2, coap]),
#{
default => coap,
desc => ?DESC(coap_subscribe_qos)
}
)},
{publish_qos,
sc(
hoconsc:enum([qos0, qos1, qos2, coap]),
#{
default => coap,
desc => ?DESC(coap_publish_qos)
}
)},
{mountpoint, mountpoint()},
{listeners,
sc(
ref(udp_listeners),
#{desc => ?DESC(udp_listeners)}
)}
] ++ gateway_common_options();
fields(lwm2m) ->
[
{xml_dir,
sc(
binary(),
#{
%% since this is not packaged with emqx, nor
%% present in the packages, we must let the user
%% specify it rather than creating a dynamic
%% default (especially difficult to handle when
%% generating docs).
example => <<"/etc/emqx/lwm2m_xml">>,
required => true,
desc => ?DESC(lwm2m_xml_dir)
}
)},
{lifetime_min,
sc(
duration(),
#{
default => <<"15s">>,
desc => ?DESC(lwm2m_lifetime_min)
}
)},
{lifetime_max,
sc(
duration(),
#{
default => <<"86400s">>,
desc => ?DESC(lwm2m_lifetime_max)
}
)},
{qmode_time_window,
sc(
duration_s(),
#{
default => <<"22s">>,
desc => ?DESC(lwm2m_qmode_time_window)
}
)},
%% TODO: Support config resource path
{auto_observe,
sc(
boolean(),
#{
default => false,
desc => ?DESC(lwm2m_auto_observe)
}
)},
%% FIXME: not working now
{update_msg_publish_condition,
sc(
hoconsc:enum([always, contains_object_list]),
#{
default => contains_object_list,
desc => ?DESC(lwm2m_update_msg_publish_condition)
}
)},
{translators,
sc(
ref(lwm2m_translators),
#{
required => true,
desc => ?DESC(lwm2m_translators)
}
)},
{mountpoint, mountpoint("lwm2m/${endpoint_name}/")},
{listeners, sc(ref(udp_listeners), #{desc => ?DESC(udp_listeners)})}
] ++ gateway_common_options();
fields(exproto) ->
[
{server,
sc(
ref(exproto_grpc_server),
#{
required => true,
desc => ?DESC(exproto_server)
}
)},
{handler,
sc(
ref(exproto_grpc_handler),
#{
required => true,
desc => ?DESC(exproto_handler)
}
)},
{mountpoint, mountpoint()},
{listeners, sc(ref(tcp_udp_listeners), #{desc => ?DESC(tcp_udp_listeners)})}
] ++ gateway_common_options();
fields(exproto_grpc_server) ->
[
{bind,
sc(
hoconsc:union([ip_port(), integer()]),
#{
required => true,
desc => ?DESC(exproto_grpc_server_bind)
}
)},
{ssl_options,
sc(
ref(ssl_server_opts),
#{
required => {false, recursively},
desc => ?DESC(exproto_grpc_server_ssl)
}
)}
];
fields(exproto_grpc_handler) ->
[
{address, sc(binary(), #{required => true, desc => ?DESC(exproto_grpc_handler_address)})},
{ssl_options,
sc(
ref(emqx_schema, "ssl_client_opts"),
#{
required => {false, recursively},
desc => ?DESC(exproto_grpc_handler_ssl)
}
)}
];
fields(ssl_server_opts) ->
emqx_schema:server_ssl_opts_schema(
#{
depth => 10,
reuse_sessions => true,
versions => tls_all_available
},
true
);
fields(clientinfo_override) ->
[
{username, sc(binary(), #{desc => ?DESC(gateway_common_clientinfo_override_username)})},
{password,
sc(binary(), #{
desc => ?DESC(gateway_common_clientinfo_override_password),
sensitive => true,
format => <<"password">>,
converter => fun emqx_schema:password_converter/2
})},
{clientid, sc(binary(), #{desc => ?DESC(gateway_common_clientinfo_override_clientid)})}
];
fields(lwm2m_translators) ->
[
{command,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_command),
required => true
}
)},
{response,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_response),
required => true
}
)},
{notify,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_notify),
required => true
}
)},
{register,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_register),
required => true
}
)},
{update,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_update),
required => true
}
)}
];
fields(translator) ->
[
{topic,
sc(
binary(),
#{
required => true,
desc => ?DESC(translator_topic)
}
)},
{qos,
sc(
emqx_schema:qos(),
#{
default => 0,
desc => ?DESC(translator_qos)
}
)}
];
fields(udp_listeners) ->
[
{udp, sc(map(name, ref(udp_listener)), #{desc => ?DESC(udp_listener)})},
{dtls, sc(map(name, ref(dtls_listener)), #{desc => ?DESC(dtls_listener)})}
];
fields(tcp_listeners) ->
[
{tcp, sc(map(name, ref(tcp_listener)), #{desc => ?DESC(tcp_listener)})},
{ssl, sc(map(name, ref(ssl_listener)), #{desc => ?DESC(ssl_listener)})}
];
fields(tcp_udp_listeners) ->
[
{tcp, sc(map(name, ref(tcp_listener)), #{desc => ?DESC(tcp_listener)})},
{ssl, sc(map(name, ref(ssl_listener)), #{desc => ?DESC(ssl_listener)})},
{udp, sc(map(name, ref(udp_listener)), #{desc => ?DESC(udp_listener)})},
{dtls, sc(map(name, ref(dtls_listener)), #{desc => ?DESC(dtls_listener)})}
];
fields(tcp_listener) ->
%% some special configs for tcp listener
[
{acceptors, sc(integer(), #{default => 16, desc => ?DESC(tcp_listener_acceptors)})}
] ++
tcp_opts() ++
proxy_protocol_opts() ++
common_listener_opts();
fields(ssl_listener) ->
fields(tcp_listener) ++
[
{ssl_options,
sc(
hoconsc:ref(emqx_schema, "listener_ssl_opts"),
#{desc => ?DESC(ssl_listener_options)}
)}
];
fields(udp_listener) ->
[
%% some special configs for udp listener
] ++
udp_opts() ++
common_listener_opts();
fields(dtls_listener) ->
[{acceptors, sc(integer(), #{default => 16, desc => ?DESC(dtls_listener_acceptors)})}] ++
fields(udp_listener) ++
[{dtls_options, sc(ref(dtls_opts), #{desc => ?DESC(dtls_listener_dtls_opts)})}];
fields(udp_opts) ->
[
{active_n,
sc(
integer(),
#{
default => 100,
desc => ?DESC(udp_listener_active_n)
}
)},
{recbuf, sc(bytesize(), #{desc => ?DESC(udp_listener_recbuf)})},
{sndbuf, sc(bytesize(), #{desc => ?DESC(udp_listener_sndbuf)})},
{buffer, sc(bytesize(), #{desc => ?DESC(udp_listener_buffer)})},
{reuseaddr, sc(boolean(), #{default => true, desc => ?DESC(udp_listener_reuseaddr)})}
];
fields(dtls_opts) ->
emqx_schema:server_ssl_opts_schema(
#{
depth => 10,
reuse_sessions => true,
versions => dtls_all_available
},
false
).
desc(gateway) ->
"EMQX Gateway configuration root.";
desc(stomp) ->
"The STOMP protocol gateway provides EMQX with the ability to access STOMP\n"
"(Simple (or Streaming) Text Orientated Messaging Protocol) protocol.";
desc(stomp_frame) ->
"Size limits for the STOMP frames.";
desc(mqttsn) ->
"The MQTT-SN (MQTT for Sensor Networks) protocol gateway.";
desc(mqttsn_predefined) ->
"The pre-defined topic name corresponding to the pre-defined topic\n"
"ID of N.\n\n"
"Note: the pre-defined topic ID of 0 is reserved.";
desc(coap) ->
"The CoAP protocol gateway provides EMQX with the access capability of the CoAP protocol.\n"
"It allows publishing, subscribing, and receiving messages to EMQX in accordance\n"
"with a certain defined CoAP message format.";
desc(lwm2m) ->
"The LwM2M protocol gateway.";
desc(exproto) ->
"Settings for EMQX extension protocol (exproto).";
desc(exproto_grpc_server) ->
"Settings for the exproto gRPC server.";
desc(exproto_grpc_handler) ->
"Settings for the exproto gRPC connection handler.";
desc(ssl_server_opts) ->
"SSL configuration for the server.";
desc(clientinfo_override) ->
"ClientInfo override.";
desc(lwm2m_translators) ->
"MQTT topics that correspond to LwM2M events.";
desc(translator) ->
"MQTT topic that corresponds to a particular type of event.";
desc(udp_listeners) ->
"Settings for the UDP listeners.";
desc(tcp_listeners) ->
"Settings for the TCP listeners.";
desc(tcp_udp_listeners) ->
"Settings for the listeners.";
desc(tcp_listener) ->
"Settings for the TCP listener.";
desc(ssl_listener) ->
"Settings for the SSL listener.";
desc(udp_listener) ->
"Settings for the UDP listener.";
desc(dtls_listener) ->
"Settings for the DTLS listener.";
desc(udp_opts) ->
"Settings for the UDP sockets.";
desc(dtls_opts) ->
"Settings for the DTLS protocol.";
desc(_) ->
undefined.
authentication_schema() ->
sc(
emqx_authn_schema:authenticator_type(),
#{
required => {false, recursively},
desc => ?DESC(gateway_common_authentication),
examples => emqx_authn_api:authenticator_examples()
}
).
gateway_common_options() ->
[
{enable,
sc(
boolean(),
#{
default => true,
desc => ?DESC(gateway_common_enable)
}
)},
{enable_stats,
sc(
boolean(),
#{
default => true,
desc => ?DESC(gateway_common_enable_stats)
}
)},
{idle_timeout,
sc(
duration(),
#{
default => <<"30s">>,
desc => ?DESC(gateway_common_idle_timeout)
}
)},
{clientinfo_override,
sc(
ref(clientinfo_override),
#{desc => ?DESC(gateway_common_clientinfo_override)}
)},
{?EMQX_AUTHENTICATION_CONFIG_ROOT_NAME_ATOM, authentication_schema()}
].
mountpoint() ->
mountpoint(<<"">>).
mountpoint(Default) ->
sc(
binary(),
#{
default => iolist_to_binary(Default),
desc => ?DESC(gateway_common_mountpoint)
}
).
common_listener_opts() ->
[
{enable,
sc(
boolean(),
#{
default => true,
desc => ?DESC(gateway_common_listener_enable)
}
)},
{bind,
sc(
hoconsc:union([ip_port(), integer()]),
#{desc => ?DESC(gateway_common_listener_bind)}
)},
{max_connections,
sc(
integer(),
#{
default => 1024,
desc => ?DESC(gateway_common_listener_max_connections)
}
)},
{max_conn_rate,
sc(
integer(),
#{
default => 1000,
desc => ?DESC(gateway_common_listener_max_conn_rate)
}
)},
{?EMQX_AUTHENTICATION_CONFIG_ROOT_NAME_ATOM, authentication_schema()},
{"enable_authn",
sc(
boolean(),
#{
desc => ?DESC(gateway_common_listener_enable_authn),
default => true
}
)},
{mountpoint,
sc(
binary(),
#{
default => undefined,
desc => ?DESC(gateway_common_listener_mountpoint)
}
)},
{access_rules,
sc(
hoconsc:array(string()),
#{
default => [],
desc => ?DESC(gateway_common_listener_access_rules)
}
)}
].
tcp_opts() ->
[{tcp_options, sc(ref(emqx_schema, "tcp_opts"), #{desc => ?DESC(tcp_listener_tcp_opts)})}].
udp_opts() ->
[{udp_options, sc(ref(udp_opts), #{})}].
proxy_protocol_opts() ->
[
{proxy_protocol,
sc(
boolean(),
#{
default => false,
desc => ?DESC(tcp_listener_proxy_protocol)
}
)},
{proxy_protocol_timeout,
sc(
duration(),
#{
default => <<"15s">>,
desc => ?DESC(tcp_listener_proxy_protocol_timeout)
}
)}
].
sc(Type) ->
sc(Type, #{}).
sc(Type, Meta) ->
hoconsc:mk(Type, Meta).
map(Name, Type) ->
hoconsc:map(Name, Type).
ref(StructName) ->
ref(?MODULE, StructName).
ref(Mod, Field) ->
hoconsc:ref(Mod, Field).
| null | https://raw.githubusercontent.com/emqx/emqx/969cbecf91cd71f3f4a0d83f6fa4a9f45329645e/apps/emqx_gateway/src/emqx_gateway_schema.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
since this is not packaged with emqx, nor
present in the packages, we must let the user
specify it rather than creating a dynamic
default (especially difficult to handle when
generating docs).
TODO: Support config resource path
FIXME: not working now
some special configs for tcp listener
some special configs for udp listener | Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_gateway_schema).
-behaviour(hocon_schema).
-dialyzer(no_return).
-dialyzer(no_match).
-dialyzer(no_contracts).
-dialyzer(no_unused).
-dialyzer(no_fail_call).
-include_lib("emqx/include/emqx_authentication.hrl").
-include_lib("hocon/include/hoconsc.hrl").
-include_lib("typerefl/include/types.hrl").
-type ip_port() :: tuple() | integer().
-type duration() :: non_neg_integer().
-type duration_s() :: non_neg_integer().
-type bytesize() :: pos_integer().
-type comma_separated_list() :: list().
-typerefl_from_string({ip_port/0, emqx_schema, to_ip_port}).
-typerefl_from_string({duration/0, emqx_schema, to_duration}).
-typerefl_from_string({duration_s/0, emqx_schema, to_duration_s}).
-typerefl_from_string({bytesize/0, emqx_schema, to_bytesize}).
-typerefl_from_string({comma_separated_list/0, emqx_schema, to_comma_separated_list}).
-reflect_type([
duration/0,
duration_s/0,
bytesize/0,
comma_separated_list/0,
ip_port/0
]).
-elvis([{elvis_style, dont_repeat_yourself, disable}]).
-export([namespace/0, roots/0, fields/1, desc/1, tags/0]).
-export([proxy_protocol_opts/0]).
namespace() -> gateway.
tags() ->
[<<"Gateway">>].
roots() -> [gateway].
fields(gateway) ->
[
{stomp,
sc(
ref(stomp),
#{
required => {false, recursively},
desc => ?DESC(stomp)
}
)},
{mqttsn,
sc(
ref(mqttsn),
#{
required => {false, recursively},
desc => ?DESC(mqttsn)
}
)},
{coap,
sc(
ref(coap),
#{
required => {false, recursively},
desc => ?DESC(coap)
}
)},
{lwm2m,
sc(
ref(lwm2m),
#{
required => {false, recursively},
desc => ?DESC(lwm2m)
}
)},
{exproto,
sc(
ref(exproto),
#{
required => {false, recursively},
desc => ?DESC(exproto)
}
)}
];
fields(stomp) ->
[
{frame, sc(ref(stomp_frame))},
{mountpoint, mountpoint()},
{listeners, sc(ref(tcp_listeners), #{desc => ?DESC(tcp_listeners)})}
] ++ gateway_common_options();
fields(stomp_frame) ->
[
{max_headers,
sc(
non_neg_integer(),
#{
default => 10,
desc => ?DESC(stom_frame_max_headers)
}
)},
{max_headers_length,
sc(
non_neg_integer(),
#{
default => 1024,
desc => ?DESC(stomp_frame_max_headers_length)
}
)},
{max_body_length,
sc(
integer(),
#{
default => 65536,
desc => ?DESC(stom_frame_max_body_length)
}
)}
];
fields(mqttsn) ->
[
{gateway_id,
sc(
integer(),
#{
default => 1,
required => true,
desc => ?DESC(mqttsn_gateway_id)
}
)},
{broadcast,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_broadcast)
}
)},
TODO : rename
{enable_qos3,
sc(
boolean(),
#{
default => true,
desc => ?DESC(mqttsn_enable_qos3)
}
)},
{subs_resume,
sc(
boolean(),
#{
default => false,
desc => ?DESC(mqttsn_subs_resume)
}
)},
{predefined,
sc(
hoconsc:array(ref(mqttsn_predefined)),
#{
default => [],
required => {false, recursively},
desc => ?DESC(mqttsn_predefined)
}
)},
{mountpoint, mountpoint()},
{listeners, sc(ref(udp_listeners), #{desc => ?DESC(udp_listeners)})}
] ++ gateway_common_options();
fields(mqttsn_predefined) ->
[
{id,
sc(integer(), #{
required => true,
desc => ?DESC(mqttsn_predefined_id)
})},
{topic,
sc(binary(), #{
required => true,
desc => ?DESC(mqttsn_predefined_topic)
})}
];
fields(coap) ->
[
{heartbeat,
sc(
duration(),
#{
default => <<"30s">>,
desc => ?DESC(coap_heartbeat)
}
)},
{connection_required,
sc(
boolean(),
#{
default => false,
desc => ?DESC(coap_connection_required)
}
)},
{notify_type,
sc(
hoconsc:enum([non, con, qos]),
#{
default => qos,
desc => ?DESC(coap_notify_type)
}
)},
{subscribe_qos,
sc(
hoconsc:enum([qos0, qos1, qos2, coap]),
#{
default => coap,
desc => ?DESC(coap_subscribe_qos)
}
)},
{publish_qos,
sc(
hoconsc:enum([qos0, qos1, qos2, coap]),
#{
default => coap,
desc => ?DESC(coap_publish_qos)
}
)},
{mountpoint, mountpoint()},
{listeners,
sc(
ref(udp_listeners),
#{desc => ?DESC(udp_listeners)}
)}
] ++ gateway_common_options();
fields(lwm2m) ->
[
{xml_dir,
sc(
binary(),
#{
example => <<"/etc/emqx/lwm2m_xml">>,
required => true,
desc => ?DESC(lwm2m_xml_dir)
}
)},
{lifetime_min,
sc(
duration(),
#{
default => <<"15s">>,
desc => ?DESC(lwm2m_lifetime_min)
}
)},
{lifetime_max,
sc(
duration(),
#{
default => <<"86400s">>,
desc => ?DESC(lwm2m_lifetime_max)
}
)},
{qmode_time_window,
sc(
duration_s(),
#{
default => <<"22s">>,
desc => ?DESC(lwm2m_qmode_time_window)
}
)},
{auto_observe,
sc(
boolean(),
#{
default => false,
desc => ?DESC(lwm2m_auto_observe)
}
)},
{update_msg_publish_condition,
sc(
hoconsc:enum([always, contains_object_list]),
#{
default => contains_object_list,
desc => ?DESC(lwm2m_update_msg_publish_condition)
}
)},
{translators,
sc(
ref(lwm2m_translators),
#{
required => true,
desc => ?DESC(lwm2m_translators)
}
)},
{mountpoint, mountpoint("lwm2m/${endpoint_name}/")},
{listeners, sc(ref(udp_listeners), #{desc => ?DESC(udp_listeners)})}
] ++ gateway_common_options();
fields(exproto) ->
[
{server,
sc(
ref(exproto_grpc_server),
#{
required => true,
desc => ?DESC(exproto_server)
}
)},
{handler,
sc(
ref(exproto_grpc_handler),
#{
required => true,
desc => ?DESC(exproto_handler)
}
)},
{mountpoint, mountpoint()},
{listeners, sc(ref(tcp_udp_listeners), #{desc => ?DESC(tcp_udp_listeners)})}
] ++ gateway_common_options();
fields(exproto_grpc_server) ->
[
{bind,
sc(
hoconsc:union([ip_port(), integer()]),
#{
required => true,
desc => ?DESC(exproto_grpc_server_bind)
}
)},
{ssl_options,
sc(
ref(ssl_server_opts),
#{
required => {false, recursively},
desc => ?DESC(exproto_grpc_server_ssl)
}
)}
];
fields(exproto_grpc_handler) ->
[
{address, sc(binary(), #{required => true, desc => ?DESC(exproto_grpc_handler_address)})},
{ssl_options,
sc(
ref(emqx_schema, "ssl_client_opts"),
#{
required => {false, recursively},
desc => ?DESC(exproto_grpc_handler_ssl)
}
)}
];
fields(ssl_server_opts) ->
emqx_schema:server_ssl_opts_schema(
#{
depth => 10,
reuse_sessions => true,
versions => tls_all_available
},
true
);
fields(clientinfo_override) ->
[
{username, sc(binary(), #{desc => ?DESC(gateway_common_clientinfo_override_username)})},
{password,
sc(binary(), #{
desc => ?DESC(gateway_common_clientinfo_override_password),
sensitive => true,
format => <<"password">>,
converter => fun emqx_schema:password_converter/2
})},
{clientid, sc(binary(), #{desc => ?DESC(gateway_common_clientinfo_override_clientid)})}
];
fields(lwm2m_translators) ->
[
{command,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_command),
required => true
}
)},
{response,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_response),
required => true
}
)},
{notify,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_notify),
required => true
}
)},
{register,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_register),
required => true
}
)},
{update,
sc(
ref(translator),
#{
desc => ?DESC(lwm2m_translators_update),
required => true
}
)}
];
fields(translator) ->
[
{topic,
sc(
binary(),
#{
required => true,
desc => ?DESC(translator_topic)
}
)},
{qos,
sc(
emqx_schema:qos(),
#{
default => 0,
desc => ?DESC(translator_qos)
}
)}
];
fields(udp_listeners) ->
[
{udp, sc(map(name, ref(udp_listener)), #{desc => ?DESC(udp_listener)})},
{dtls, sc(map(name, ref(dtls_listener)), #{desc => ?DESC(dtls_listener)})}
];
fields(tcp_listeners) ->
[
{tcp, sc(map(name, ref(tcp_listener)), #{desc => ?DESC(tcp_listener)})},
{ssl, sc(map(name, ref(ssl_listener)), #{desc => ?DESC(ssl_listener)})}
];
fields(tcp_udp_listeners) ->
[
{tcp, sc(map(name, ref(tcp_listener)), #{desc => ?DESC(tcp_listener)})},
{ssl, sc(map(name, ref(ssl_listener)), #{desc => ?DESC(ssl_listener)})},
{udp, sc(map(name, ref(udp_listener)), #{desc => ?DESC(udp_listener)})},
{dtls, sc(map(name, ref(dtls_listener)), #{desc => ?DESC(dtls_listener)})}
];
fields(tcp_listener) ->
[
{acceptors, sc(integer(), #{default => 16, desc => ?DESC(tcp_listener_acceptors)})}
] ++
tcp_opts() ++
proxy_protocol_opts() ++
common_listener_opts();
fields(ssl_listener) ->
fields(tcp_listener) ++
[
{ssl_options,
sc(
hoconsc:ref(emqx_schema, "listener_ssl_opts"),
#{desc => ?DESC(ssl_listener_options)}
)}
];
fields(udp_listener) ->
[
] ++
udp_opts() ++
common_listener_opts();
fields(dtls_listener) ->
[{acceptors, sc(integer(), #{default => 16, desc => ?DESC(dtls_listener_acceptors)})}] ++
fields(udp_listener) ++
[{dtls_options, sc(ref(dtls_opts), #{desc => ?DESC(dtls_listener_dtls_opts)})}];
fields(udp_opts) ->
[
{active_n,
sc(
integer(),
#{
default => 100,
desc => ?DESC(udp_listener_active_n)
}
)},
{recbuf, sc(bytesize(), #{desc => ?DESC(udp_listener_recbuf)})},
{sndbuf, sc(bytesize(), #{desc => ?DESC(udp_listener_sndbuf)})},
{buffer, sc(bytesize(), #{desc => ?DESC(udp_listener_buffer)})},
{reuseaddr, sc(boolean(), #{default => true, desc => ?DESC(udp_listener_reuseaddr)})}
];
fields(dtls_opts) ->
emqx_schema:server_ssl_opts_schema(
#{
depth => 10,
reuse_sessions => true,
versions => dtls_all_available
},
false
).
desc(gateway) ->
"EMQX Gateway configuration root.";
desc(stomp) ->
"The STOMP protocol gateway provides EMQX with the ability to access STOMP\n"
"(Simple (or Streaming) Text Orientated Messaging Protocol) protocol.";
desc(stomp_frame) ->
"Size limits for the STOMP frames.";
desc(mqttsn) ->
"The MQTT-SN (MQTT for Sensor Networks) protocol gateway.";
desc(mqttsn_predefined) ->
"The pre-defined topic name corresponding to the pre-defined topic\n"
"ID of N.\n\n"
"Note: the pre-defined topic ID of 0 is reserved.";
desc(coap) ->
"The CoAP protocol gateway provides EMQX with the access capability of the CoAP protocol.\n"
"It allows publishing, subscribing, and receiving messages to EMQX in accordance\n"
"with a certain defined CoAP message format.";
desc(lwm2m) ->
"The LwM2M protocol gateway.";
desc(exproto) ->
"Settings for EMQX extension protocol (exproto).";
desc(exproto_grpc_server) ->
"Settings for the exproto gRPC server.";
desc(exproto_grpc_handler) ->
"Settings for the exproto gRPC connection handler.";
desc(ssl_server_opts) ->
"SSL configuration for the server.";
desc(clientinfo_override) ->
"ClientInfo override.";
desc(lwm2m_translators) ->
"MQTT topics that correspond to LwM2M events.";
desc(translator) ->
"MQTT topic that corresponds to a particular type of event.";
desc(udp_listeners) ->
"Settings for the UDP listeners.";
desc(tcp_listeners) ->
"Settings for the TCP listeners.";
desc(tcp_udp_listeners) ->
"Settings for the listeners.";
desc(tcp_listener) ->
"Settings for the TCP listener.";
desc(ssl_listener) ->
"Settings for the SSL listener.";
desc(udp_listener) ->
"Settings for the UDP listener.";
desc(dtls_listener) ->
"Settings for the DTLS listener.";
desc(udp_opts) ->
"Settings for the UDP sockets.";
desc(dtls_opts) ->
"Settings for the DTLS protocol.";
desc(_) ->
undefined.
authentication_schema() ->
sc(
emqx_authn_schema:authenticator_type(),
#{
required => {false, recursively},
desc => ?DESC(gateway_common_authentication),
examples => emqx_authn_api:authenticator_examples()
}
).
gateway_common_options() ->
[
{enable,
sc(
boolean(),
#{
default => true,
desc => ?DESC(gateway_common_enable)
}
)},
{enable_stats,
sc(
boolean(),
#{
default => true,
desc => ?DESC(gateway_common_enable_stats)
}
)},
{idle_timeout,
sc(
duration(),
#{
default => <<"30s">>,
desc => ?DESC(gateway_common_idle_timeout)
}
)},
{clientinfo_override,
sc(
ref(clientinfo_override),
#{desc => ?DESC(gateway_common_clientinfo_override)}
)},
{?EMQX_AUTHENTICATION_CONFIG_ROOT_NAME_ATOM, authentication_schema()}
].
mountpoint() ->
mountpoint(<<"">>).
mountpoint(Default) ->
sc(
binary(),
#{
default => iolist_to_binary(Default),
desc => ?DESC(gateway_common_mountpoint)
}
).
common_listener_opts() ->
[
{enable,
sc(
boolean(),
#{
default => true,
desc => ?DESC(gateway_common_listener_enable)
}
)},
{bind,
sc(
hoconsc:union([ip_port(), integer()]),
#{desc => ?DESC(gateway_common_listener_bind)}
)},
{max_connections,
sc(
integer(),
#{
default => 1024,
desc => ?DESC(gateway_common_listener_max_connections)
}
)},
{max_conn_rate,
sc(
integer(),
#{
default => 1000,
desc => ?DESC(gateway_common_listener_max_conn_rate)
}
)},
{?EMQX_AUTHENTICATION_CONFIG_ROOT_NAME_ATOM, authentication_schema()},
{"enable_authn",
sc(
boolean(),
#{
desc => ?DESC(gateway_common_listener_enable_authn),
default => true
}
)},
{mountpoint,
sc(
binary(),
#{
default => undefined,
desc => ?DESC(gateway_common_listener_mountpoint)
}
)},
{access_rules,
sc(
hoconsc:array(string()),
#{
default => [],
desc => ?DESC(gateway_common_listener_access_rules)
}
)}
].
tcp_opts() ->
[{tcp_options, sc(ref(emqx_schema, "tcp_opts"), #{desc => ?DESC(tcp_listener_tcp_opts)})}].
udp_opts() ->
[{udp_options, sc(ref(udp_opts), #{})}].
proxy_protocol_opts() ->
[
{proxy_protocol,
sc(
boolean(),
#{
default => false,
desc => ?DESC(tcp_listener_proxy_protocol)
}
)},
{proxy_protocol_timeout,
sc(
duration(),
#{
default => <<"15s">>,
desc => ?DESC(tcp_listener_proxy_protocol_timeout)
}
)}
].
sc(Type) ->
sc(Type, #{}).
sc(Type, Meta) ->
hoconsc:mk(Type, Meta).
map(Name, Type) ->
hoconsc:map(Name, Type).
ref(StructName) ->
ref(?MODULE, StructName).
ref(Mod, Field) ->
hoconsc:ref(Mod, Field).
|
efa948b61054c5c386f2d46c50fa2a678bb89681eb917ac20fa0b345683297a0 | yjqww6/drcomplete | main.rkt | #lang racket/base
(provide register-drcomplete-plugin)
(define (register-drcomplete-plugin #:def def #:def-rank [def-rank 4]
#:int int #:int-rank [int-rank 4])
(log-message (current-logger)
'info
'drcomplete-plugin
""
(cons (cons def-rank def)
(cons int-rank int)))) | null | https://raw.githubusercontent.com/yjqww6/drcomplete/b3f7390149e8d006c92b8a8a4da1593da547e235/drcomplete-base/main.rkt | racket | #lang racket/base
(provide register-drcomplete-plugin)
(define (register-drcomplete-plugin #:def def #:def-rank [def-rank 4]
#:int int #:int-rank [int-rank 4])
(log-message (current-logger)
'info
'drcomplete-plugin
""
(cons (cons def-rank def)
(cons int-rank int)))) | |
c3002a3de9e367be83c12381c93c611f162facc81c55c4915ebc48c2b1778d7c | tkonolige/dbignore | Test.hs | {-# OPTIONS_GHC -Wall -fwarn-tabs #-}
# LANGUAGE CPP
, MultiParamTypeClasses
, FlexibleInstances
, FlexibleContexts
, TypeSynonymInstances
#
, MultiParamTypeClasses
, FlexibleInstances
, FlexibleContexts
, TypeSynonymInstances
#-}
----------------------------------------------------------------
~ 2011.02.12
-- |
Module : Data . Trie . Test
-- Copyright : Copyright (c) 2008--2011 wren gayle romano
-- License : BSD3
-- Maintainer :
-- Stability : provisional
Portability : semi - portable ( MPTC , ... )
--
-- Testing 'Trie's.
----------------------------------------------------------------
module Data.Trie.Test (packC2W, main) where
import qualified Data.Trie as T
import qualified Data.Trie.Convenience as TC
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S (c2w, w2c)
import qualified Test.HUnit as HU
import qualified Test.QuickCheck as QC
import qualified Test.SmallCheck as SC
import qualified Test . LazySmallCheck as LSC
-- import qualified Test.SparseCheck as PC
import Data.Monoid
import Control.Monad (liftM)
import Data.List (nubBy, sortBy)
import Data.Ord (comparing)
----------------------------------------------------------------
----------------------------------------------------------------
packC2W :: String -> S.ByteString
packC2W = S.pack . map S.c2w
vocab2trie :: [String] -> T.Trie Int
vocab2trie = T.fromList . flip zip [0..] . map packC2W
----------------------------------------------------------------
main :: IO ()
main = do
putStrLn ""
putStrLn (replicate 80 '~')
putStrLn "hunit:"
_ <- HU.runTestTT $ HU.TestList
[ test_Union
, test_Submap
, test_Insert
, test_Delete
]
putStrLn ""
putStrLn "quickcheck @ Int:"
checkQuick 500 (prop_insert :: Str -> Int -> T.Trie Int -> Bool)
checkQuick 5000 (prop_singleton :: Str -> Int -> Bool)
checkQuick 500 (prop_size_insert :: Str -> Int -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_size_delete :: Str -> Int -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_insert_delete :: Str -> Int -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_delete_lookup :: Str -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_submap1 :: Str -> T.Trie Int -> Bool)
checkQuick 500 (prop_submap2 :: Str -> T.Trie Int -> Bool)
checkQuick 500 (prop_submap3 :: Str -> T.Trie Int -> Bool)
checkQuick 500 (prop_toList :: T.Trie Int -> Bool)
checkQuick 500 (prop_fromList_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListR_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListL_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListS_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListWithConst_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListWithLConst_takes_first :: [(Str, Int)] -> Bool)
putStrLn ""
putStrLn "smallcheck @ ():" -- Beware the exponential!
checkSmall 3 (prop_insert :: Str -> () -> T.Trie () -> Bool)
checkSmall 7 (prop_singleton :: Str -> () -> Bool)
checkSmall 3 (prop_size_insert :: Str -> () -> T.Trie () -> SC.Property)
checkSmall 3 (prop_size_delete :: Str -> () -> T.Trie () -> SC.Property)
checkSmall 3 (prop_insert_delete :: Str -> () -> T.Trie () -> SC.Property)
checkSmall 3 (prop_delete_lookup :: Str -> T.Trie () -> SC.Property)
checkSmall 3 (prop_submap1 :: Str -> T.Trie () -> Bool)
checkSmall 3 (prop_submap2 :: Str -> T.Trie () -> Bool)
checkSmall 3 ( prop_submap3 : : - > T.Trie ( ) - > Bool )
-- BUG : Needs both instances of Monoid and SC.Serial ...
putStrLn " smallcheck @ Letter : "
checkSmall 4 ( prop_toList : : )
checkSmall 5 ( prop_fromList_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListR_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListL_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListS_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListWithConst_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListWithLConst_takes_first : : [ ( , Letter ) ] - > Bool )
putStrLn "smallcheck @ Letter:"
checkSmall 4 (prop_toList :: T.Trie Letter -> Bool)
checkSmall 5 (prop_fromList_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListR_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListL_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListS_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListWithConst_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListWithLConst_takes_first :: [(Str, Letter)] -> Bool)
-}
putStrLn ""
where
#ifdef __USE_QUICKCHECK_1__
checkQuick n =
QC.check (QC.defaultConfig
{ QC.configMaxTest = n
, QC.configMaxFail = 1000 `max` 10*n
})
#else
checkQuick n =
QC.quickCheckWith (QC.stdArgs
{ QC.maxSize = n
, QC.maxSuccess = n
, QC.maxDiscard = 1000 `max` 10*n
})
#endif
checkSmall d f = SC.smallCheck d f >> putStrLn ""
testEqual :: (Show a, Eq a) => String -> a -> a -> HU.Test
testEqual s a b =
HU.TestLabel s $ HU.TestCase $ HU.assertEqual "" a b
----------------------------------------------------------------
-- Because we avoid epsilons everywhere else, need to make sure 'mergeBy' gets it right
test_Union :: HU.Test
test_Union = HU.TestLabel "epsilon union"
$ HU.TestList
[ testEqual "left" (e1 `T.unionL` e2) e1
, testEqual "right" (e1 `T.unionR` e2) e2 -- meh, why not
, testEqual "unionR regression" (tLeft `T.unionR` tRight) tRightResult
, testEqual "unionL regression" (tLeft `T.unionL` tRight) tLeftResult
]
where
e1 = T.singleton S.empty (4::Int)
e2 = T.singleton S.empty (2::Int)
Regression test against bug filed by on 2010.06.10 against version 0.2.1.1 .
a, b :: S.ByteString
a = read "\"\231^\179\160Y\134Gr\158<)&\222\217#\156\""
b = read "\"\172\193\GSp\222\174GE\186\151\DC1#P\213\147\SI\""
tLeft = T.fromList [(a,1::Int),(b,0::Int)]
tRight = T.fromList [(a,2::Int)]
tRightResult = T.fromList [(a,2::Int),(b,0::Int)]
tLeftResult = T.fromList [(a,1::Int),(b,0::Int)]
----------------------------------------------------------------
test_Submap :: HU.Test
test_Submap = HU.TestLabel "submap"
$ HU.TestList
[ nullSubmap "split on arc fails" fi True
, nullSubmap "prefix of arc matches" fo False
, nullSubmap "suffix of empty fails" food True
, nullSubmap "missing branch fails" bag True
, nullSubmap "at a branch matches" ba False
]
where
t = vocab2trie ["foo", "bar", "baz"]
fi = packC2W "fi"
fo = packC2W "fo"
food = packC2W "food"
ba = packC2W "ba"
bag = packC2W "bag"
nullSubmap s q b = testEqual s (T.null $ T.submap q t) b
----------------------------------------------------------------
requires ( Trie a ) and , in case it fails , Show ( Trie a )
test_Insert :: HU.Test
test_Insert = HU.TestLabel "insert"
$ HU.TestList
[ testEqual "insertion is commutative for prefix/superfix"
(T.insert aba o $ T.insert abaissed i $ T.empty)
(T.insert abaissed i $ T.insert aba o $ T.empty)
]
where
aba = packC2W "aba"
abaissed = packC2W "abaissed"
o = 0::Int
i = 1::Int
test_Delete :: HU.Test
test_Delete = HU.TestLabel "delete"
$ HU.TestList
[ testEqual "deleting epsilon from empty trie is empty"
(T.delete epsilon T.empty) (T.empty :: T.Trie Int)
]
where
epsilon = packC2W ""
----------------------------------------------------------------
TODO : we need a better instance of Arbitrary for lists to make them longer than our smallcheck depth .
--
-- I use strings with characters picked from a very restricted subset
-- in order to have more labels with shared prefixes.
newtype Letter = Letter { unLetter :: Char }
deriving (Eq, Ord, Show)
letters :: [Char]
letters = ['a'..'m']
instance QC.Arbitrary Letter where
arbitrary = Letter `fmap` QC.elements letters
coarbitrary -- used in QCv1 , separated in QCv2
newtype Str = Str { unStr :: S.ByteString }
deriving (Eq, Ord)
instance Show Str where
show (Str s) = "Str {unStr = packC2W " ++ show s ++ " }"
instance QC.Arbitrary Str where
arbitrary = QC.sized $ \n -> do
k <- QC.choose (0,n)
s <- QC.vector k
c <- QC.arbitrary -- We only want non-empty strings.
return . Str . packC2W $ map unLetter (c:s)
coarbitrary -- used in QCv1 , separated in QCv2
instance (QC.Arbitrary a) => QC.Arbitrary (T.Trie a) where
arbitrary = QC.sized $ \n -> do
k <- QC.choose (0,n)
labels <- map unStr `fmap` QC.vector k
elems <- QC.vector k
return . T.fromList $ zip labels elems
coarbitrary -- used in QCv1 , separated in QCv2
----------------------------------------------------------------
-- cf <>
type Series a = Int - > [ a ]
instance SC.Serial Letter where
series d = take (d+1) $ map Letter letters
coseries rs d = do f <- SC.coseries rs d
return $ \c -> f (fromEnum (unLetter c) - fromEnum 'a')
instance SC.Serial Str where
series d = liftM (Str . packC2W . map unLetter)
(SC.series d :: [[Letter]])
coseries rs d = do y <- SC.alts0 rs d
f <- SC.alts2 rs d
return $ \(Str xs) ->
if S.null xs
then y
else f (Letter . S.w2c $ S.head xs)
(Str $ S.tail xs)
TODO : This instance really needs some work . The smart constructures ensure only valid values are generated , but there are redundancies and inefficiencies .
instance (Monoid a, SC.Serial a) => SC.Serial (T.Trie a) where
series = SC.cons0 T.empty
SC.\/ SC.cons3 arcHACK
SC.\/ SC.cons2 mappend
where
arcHACK (Str k) Nothing t = T.singleton k () >> t
arcHACK (Str k) (Just v) t = T.singleton k v
>>= T.unionR t . T.singleton S.empty
coseries : : Series b - > Series ( Trie a - > b )
coseries = error "coseries@Trie: not implemented"
----------------------------------------------------------------
----------------------------------------------------------------
-- | If you insert a value, you can look it up
prop_insert :: (Eq a) => Str -> a -> T.Trie a -> Bool
prop_insert (Str k) v t =
(T.lookup k . T.insert k v $ t) == Just v
-- | A singleton, is.
prop_singleton :: (Eq a) => Str -> a -> Bool
prop_singleton (Str k) v =
T.insert k v T.empty == T.singleton k v
-- | Deal with QC/SC polymorphism issues because of (==>)
would be nice here , but |b->a is undecidable , and |a->b is wrong
class CheckGuard a b where
(==>) :: Bool -> a -> b
instance (QC.Testable a) => CheckGuard a QC.Property where
(==>) = (QC.==>)
instance (SC.Testable a) => CheckGuard a SC.Property where
(==>) = (SC.==>)
prop_size_insert :: (Eq a, CheckGuard Bool b) => Str -> a -> T.Trie a -> b
prop_size_insert (Str k) v t = not (k `T.member` t) ==> (
(T.size . T.insert k v) === ((1+) . T.size)
$ t)
prop_size_delete :: (Eq a, CheckGuard Bool b) => Str -> a -> T.Trie a -> b
prop_size_delete (Str k) v t = not (k `T.member` t) ==> (
(T.size . T.delete k . T.insert k v) === T.size
$ t)
prop_insert_delete :: (Eq a, CheckGuard Bool b) => Str -> a -> T.Trie a -> b
prop_insert_delete (Str k) v t = not (k `T.member` t) ==> (
(T.delete k . T.insert k v) === id
$ t)
prop_delete_lookup :: (Eq a, CheckGuard Bool b) => Str -> T.Trie a -> b
prop_delete_lookup (Str k) t = not (k `T.member` t) ==> (
(T.lookup k . T.delete k) === const Nothing
$ t)
-- | All keys in a submap are keys in the supermap
prop_submap1 :: Str -> T.Trie a -> Bool
prop_submap1 (Str k) t =
all (`T.member` t) . T.keys . T.submap k $ t
-- | All keys in a submap have the query as a prefix
prop_submap2 :: Str -> T.Trie a -> Bool
prop_submap2 (Str k) t =
all (S.isPrefixOf k) . T.keys . T.submap k $ t
-- | All values in a submap are the same in the supermap
prop_submap3 :: (Eq a) => Str -> T.Trie a -> Bool
prop_submap3 (Str k) t =
(\q -> T.lookup q t' == T.lookup q t) `all` T.keys t'
where t' = T.submap k t
-- | Keys are ordered when converting to a list
prop_toList :: T.Trie a -> Bool
prop_toList t = ordered (T.keys t)
where ordered xs = and (zipWith (<=) xs (drop 1 xs))
_takes_first :: (Eq c) => ([(S.ByteString, c)] -> T.Trie c) -> [(Str, c)] -> Bool
_takes_first f assocs =
(T.toList . f) === (nubBy (apFst (==)) . sortBy (comparing fst))
$ map (first unStr) assocs
| ' fromList ' takes the first value for a given key
prop_fromList_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromList_takes_first = _takes_first T.fromList
| ' fromListR ' takes the first value for a given key
prop_fromListR_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListR_takes_first = _takes_first TC.fromListR
| ' fromListL ' takes the first value for a given key
prop_fromListL_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListL_takes_first = _takes_first TC.fromListL
| ' fromListS ' takes the first value for a given key
prop_fromListS_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListS_takes_first = _takes_first TC.fromListS
| @('fromListWith ' const)@ takes the first value for a given key
prop_fromListWithConst_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListWithConst_takes_first = _takes_first (TC.fromListWith const)
| @('fromListWithL ' const)@ takes the first value for a given key
prop_fromListWithLConst_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListWithLConst_takes_first = _takes_first (TC.fromListWithL const)
----------------------------------------------------------------
| Lift a function to apply to the first of pairs , retaining the second .
first :: (a -> b) -> (a,c) -> (b,c)
first f (x,y) = (f x, y)
| Lift a binary function to apply to the first of pairs , discarding seconds .
apFst :: (a -> b -> c) -> ((a,d) -> (b,e) -> c)
apFst f (x,_) (y,_) = f x y
-- | Function equality
(===) :: (Eq b) => (a -> b) -> (a -> b) -> (a -> Bool)
(===) f g x = (==) (f x) (g x)
----------------------------------------------------------------
----------------------------------------------------------- fin.
| null | https://raw.githubusercontent.com/tkonolige/dbignore/237a03f9cdc82af882e3f8ccbfd4115000a8bb1d/bytestring-trie/test/Data/Trie/Test.hs | haskell | # OPTIONS_GHC -Wall -fwarn-tabs #
--------------------------------------------------------------
|
Copyright : Copyright (c) 2008--2011 wren gayle romano
License : BSD3
Maintainer :
Stability : provisional
Testing 'Trie's.
--------------------------------------------------------------
import qualified Test.SparseCheck as PC
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
Beware the exponential!
BUG : Needs both instances of Monoid and SC.Serial ...
--------------------------------------------------------------
Because we avoid epsilons everywhere else, need to make sure 'mergeBy' gets it right
meh, why not
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
I use strings with characters picked from a very restricted subset
in order to have more labels with shared prefixes.
used in QCv1 , separated in QCv2
We only want non-empty strings.
used in QCv1 , separated in QCv2
used in QCv1 , separated in QCv2
--------------------------------------------------------------
cf <>
--------------------------------------------------------------
--------------------------------------------------------------
| If you insert a value, you can look it up
| A singleton, is.
| Deal with QC/SC polymorphism issues because of (==>)
| All keys in a submap are keys in the supermap
| All keys in a submap have the query as a prefix
| All values in a submap are the same in the supermap
| Keys are ordered when converting to a list
--------------------------------------------------------------
| Function equality
--------------------------------------------------------------
--------------------------------------------------------- fin. | # LANGUAGE CPP
, MultiParamTypeClasses
, FlexibleInstances
, FlexibleContexts
, TypeSynonymInstances
#
, MultiParamTypeClasses
, FlexibleInstances
, FlexibleContexts
, TypeSynonymInstances
#-}
~ 2011.02.12
Module : Data . Trie . Test
Portability : semi - portable ( MPTC , ... )
module Data.Trie.Test (packC2W, main) where
import qualified Data.Trie as T
import qualified Data.Trie.Convenience as TC
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S (c2w, w2c)
import qualified Test.HUnit as HU
import qualified Test.QuickCheck as QC
import qualified Test.SmallCheck as SC
import qualified Test . LazySmallCheck as LSC
import Data.Monoid
import Control.Monad (liftM)
import Data.List (nubBy, sortBy)
import Data.Ord (comparing)
packC2W :: String -> S.ByteString
packC2W = S.pack . map S.c2w
vocab2trie :: [String] -> T.Trie Int
vocab2trie = T.fromList . flip zip [0..] . map packC2W
main :: IO ()
main = do
putStrLn ""
putStrLn (replicate 80 '~')
putStrLn "hunit:"
_ <- HU.runTestTT $ HU.TestList
[ test_Union
, test_Submap
, test_Insert
, test_Delete
]
putStrLn ""
putStrLn "quickcheck @ Int:"
checkQuick 500 (prop_insert :: Str -> Int -> T.Trie Int -> Bool)
checkQuick 5000 (prop_singleton :: Str -> Int -> Bool)
checkQuick 500 (prop_size_insert :: Str -> Int -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_size_delete :: Str -> Int -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_insert_delete :: Str -> Int -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_delete_lookup :: Str -> T.Trie Int -> QC.Property)
checkQuick 500 (prop_submap1 :: Str -> T.Trie Int -> Bool)
checkQuick 500 (prop_submap2 :: Str -> T.Trie Int -> Bool)
checkQuick 500 (prop_submap3 :: Str -> T.Trie Int -> Bool)
checkQuick 500 (prop_toList :: T.Trie Int -> Bool)
checkQuick 500 (prop_fromList_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListR_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListL_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListS_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListWithConst_takes_first :: [(Str, Int)] -> Bool)
checkQuick 500 (prop_fromListWithLConst_takes_first :: [(Str, Int)] -> Bool)
putStrLn ""
checkSmall 3 (prop_insert :: Str -> () -> T.Trie () -> Bool)
checkSmall 7 (prop_singleton :: Str -> () -> Bool)
checkSmall 3 (prop_size_insert :: Str -> () -> T.Trie () -> SC.Property)
checkSmall 3 (prop_size_delete :: Str -> () -> T.Trie () -> SC.Property)
checkSmall 3 (prop_insert_delete :: Str -> () -> T.Trie () -> SC.Property)
checkSmall 3 (prop_delete_lookup :: Str -> T.Trie () -> SC.Property)
checkSmall 3 (prop_submap1 :: Str -> T.Trie () -> Bool)
checkSmall 3 (prop_submap2 :: Str -> T.Trie () -> Bool)
checkSmall 3 ( prop_submap3 : : - > T.Trie ( ) - > Bool )
putStrLn " smallcheck @ Letter : "
checkSmall 4 ( prop_toList : : )
checkSmall 5 ( prop_fromList_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListR_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListL_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListS_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListWithConst_takes_first : : [ ( , Letter ) ] - > Bool )
checkSmall 5 ( prop_fromListWithLConst_takes_first : : [ ( , Letter ) ] - > Bool )
putStrLn "smallcheck @ Letter:"
checkSmall 4 (prop_toList :: T.Trie Letter -> Bool)
checkSmall 5 (prop_fromList_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListR_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListL_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListS_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListWithConst_takes_first :: [(Str, Letter)] -> Bool)
checkSmall 5 (prop_fromListWithLConst_takes_first :: [(Str, Letter)] -> Bool)
-}
putStrLn ""
where
#ifdef __USE_QUICKCHECK_1__
checkQuick n =
QC.check (QC.defaultConfig
{ QC.configMaxTest = n
, QC.configMaxFail = 1000 `max` 10*n
})
#else
checkQuick n =
QC.quickCheckWith (QC.stdArgs
{ QC.maxSize = n
, QC.maxSuccess = n
, QC.maxDiscard = 1000 `max` 10*n
})
#endif
checkSmall d f = SC.smallCheck d f >> putStrLn ""
testEqual :: (Show a, Eq a) => String -> a -> a -> HU.Test
testEqual s a b =
HU.TestLabel s $ HU.TestCase $ HU.assertEqual "" a b
test_Union :: HU.Test
test_Union = HU.TestLabel "epsilon union"
$ HU.TestList
[ testEqual "left" (e1 `T.unionL` e2) e1
, testEqual "unionR regression" (tLeft `T.unionR` tRight) tRightResult
, testEqual "unionL regression" (tLeft `T.unionL` tRight) tLeftResult
]
where
e1 = T.singleton S.empty (4::Int)
e2 = T.singleton S.empty (2::Int)
Regression test against bug filed by on 2010.06.10 against version 0.2.1.1 .
a, b :: S.ByteString
a = read "\"\231^\179\160Y\134Gr\158<)&\222\217#\156\""
b = read "\"\172\193\GSp\222\174GE\186\151\DC1#P\213\147\SI\""
tLeft = T.fromList [(a,1::Int),(b,0::Int)]
tRight = T.fromList [(a,2::Int)]
tRightResult = T.fromList [(a,2::Int),(b,0::Int)]
tLeftResult = T.fromList [(a,1::Int),(b,0::Int)]
test_Submap :: HU.Test
test_Submap = HU.TestLabel "submap"
$ HU.TestList
[ nullSubmap "split on arc fails" fi True
, nullSubmap "prefix of arc matches" fo False
, nullSubmap "suffix of empty fails" food True
, nullSubmap "missing branch fails" bag True
, nullSubmap "at a branch matches" ba False
]
where
t = vocab2trie ["foo", "bar", "baz"]
fi = packC2W "fi"
fo = packC2W "fo"
food = packC2W "food"
ba = packC2W "ba"
bag = packC2W "bag"
nullSubmap s q b = testEqual s (T.null $ T.submap q t) b
requires ( Trie a ) and , in case it fails , Show ( Trie a )
test_Insert :: HU.Test
test_Insert = HU.TestLabel "insert"
$ HU.TestList
[ testEqual "insertion is commutative for prefix/superfix"
(T.insert aba o $ T.insert abaissed i $ T.empty)
(T.insert abaissed i $ T.insert aba o $ T.empty)
]
where
aba = packC2W "aba"
abaissed = packC2W "abaissed"
o = 0::Int
i = 1::Int
test_Delete :: HU.Test
test_Delete = HU.TestLabel "delete"
$ HU.TestList
[ testEqual "deleting epsilon from empty trie is empty"
(T.delete epsilon T.empty) (T.empty :: T.Trie Int)
]
where
epsilon = packC2W ""
TODO : we need a better instance of Arbitrary for lists to make them longer than our smallcheck depth .
newtype Letter = Letter { unLetter :: Char }
deriving (Eq, Ord, Show)
letters :: [Char]
letters = ['a'..'m']
instance QC.Arbitrary Letter where
arbitrary = Letter `fmap` QC.elements letters
newtype Str = Str { unStr :: S.ByteString }
deriving (Eq, Ord)
instance Show Str where
show (Str s) = "Str {unStr = packC2W " ++ show s ++ " }"
instance QC.Arbitrary Str where
arbitrary = QC.sized $ \n -> do
k <- QC.choose (0,n)
s <- QC.vector k
return . Str . packC2W $ map unLetter (c:s)
instance (QC.Arbitrary a) => QC.Arbitrary (T.Trie a) where
arbitrary = QC.sized $ \n -> do
k <- QC.choose (0,n)
labels <- map unStr `fmap` QC.vector k
elems <- QC.vector k
return . T.fromList $ zip labels elems
type Series a = Int - > [ a ]
instance SC.Serial Letter where
series d = take (d+1) $ map Letter letters
coseries rs d = do f <- SC.coseries rs d
return $ \c -> f (fromEnum (unLetter c) - fromEnum 'a')
instance SC.Serial Str where
series d = liftM (Str . packC2W . map unLetter)
(SC.series d :: [[Letter]])
coseries rs d = do y <- SC.alts0 rs d
f <- SC.alts2 rs d
return $ \(Str xs) ->
if S.null xs
then y
else f (Letter . S.w2c $ S.head xs)
(Str $ S.tail xs)
TODO : This instance really needs some work . The smart constructures ensure only valid values are generated , but there are redundancies and inefficiencies .
instance (Monoid a, SC.Serial a) => SC.Serial (T.Trie a) where
series = SC.cons0 T.empty
SC.\/ SC.cons3 arcHACK
SC.\/ SC.cons2 mappend
where
arcHACK (Str k) Nothing t = T.singleton k () >> t
arcHACK (Str k) (Just v) t = T.singleton k v
>>= T.unionR t . T.singleton S.empty
coseries : : Series b - > Series ( Trie a - > b )
coseries = error "coseries@Trie: not implemented"
prop_insert :: (Eq a) => Str -> a -> T.Trie a -> Bool
prop_insert (Str k) v t =
(T.lookup k . T.insert k v $ t) == Just v
prop_singleton :: (Eq a) => Str -> a -> Bool
prop_singleton (Str k) v =
T.insert k v T.empty == T.singleton k v
would be nice here , but |b->a is undecidable , and |a->b is wrong
class CheckGuard a b where
(==>) :: Bool -> a -> b
instance (QC.Testable a) => CheckGuard a QC.Property where
(==>) = (QC.==>)
instance (SC.Testable a) => CheckGuard a SC.Property where
(==>) = (SC.==>)
prop_size_insert :: (Eq a, CheckGuard Bool b) => Str -> a -> T.Trie a -> b
prop_size_insert (Str k) v t = not (k `T.member` t) ==> (
(T.size . T.insert k v) === ((1+) . T.size)
$ t)
prop_size_delete :: (Eq a, CheckGuard Bool b) => Str -> a -> T.Trie a -> b
prop_size_delete (Str k) v t = not (k `T.member` t) ==> (
(T.size . T.delete k . T.insert k v) === T.size
$ t)
prop_insert_delete :: (Eq a, CheckGuard Bool b) => Str -> a -> T.Trie a -> b
prop_insert_delete (Str k) v t = not (k `T.member` t) ==> (
(T.delete k . T.insert k v) === id
$ t)
prop_delete_lookup :: (Eq a, CheckGuard Bool b) => Str -> T.Trie a -> b
prop_delete_lookup (Str k) t = not (k `T.member` t) ==> (
(T.lookup k . T.delete k) === const Nothing
$ t)
prop_submap1 :: Str -> T.Trie a -> Bool
prop_submap1 (Str k) t =
all (`T.member` t) . T.keys . T.submap k $ t
prop_submap2 :: Str -> T.Trie a -> Bool
prop_submap2 (Str k) t =
all (S.isPrefixOf k) . T.keys . T.submap k $ t
prop_submap3 :: (Eq a) => Str -> T.Trie a -> Bool
prop_submap3 (Str k) t =
(\q -> T.lookup q t' == T.lookup q t) `all` T.keys t'
where t' = T.submap k t
prop_toList :: T.Trie a -> Bool
prop_toList t = ordered (T.keys t)
where ordered xs = and (zipWith (<=) xs (drop 1 xs))
_takes_first :: (Eq c) => ([(S.ByteString, c)] -> T.Trie c) -> [(Str, c)] -> Bool
_takes_first f assocs =
(T.toList . f) === (nubBy (apFst (==)) . sortBy (comparing fst))
$ map (first unStr) assocs
| ' fromList ' takes the first value for a given key
prop_fromList_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromList_takes_first = _takes_first T.fromList
| ' fromListR ' takes the first value for a given key
prop_fromListR_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListR_takes_first = _takes_first TC.fromListR
| ' fromListL ' takes the first value for a given key
prop_fromListL_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListL_takes_first = _takes_first TC.fromListL
| ' fromListS ' takes the first value for a given key
prop_fromListS_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListS_takes_first = _takes_first TC.fromListS
| @('fromListWith ' const)@ takes the first value for a given key
prop_fromListWithConst_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListWithConst_takes_first = _takes_first (TC.fromListWith const)
| @('fromListWithL ' const)@ takes the first value for a given key
prop_fromListWithLConst_takes_first :: (Eq a) => [(Str, a)] -> Bool
prop_fromListWithLConst_takes_first = _takes_first (TC.fromListWithL const)
| Lift a function to apply to the first of pairs , retaining the second .
first :: (a -> b) -> (a,c) -> (b,c)
first f (x,y) = (f x, y)
| Lift a binary function to apply to the first of pairs , discarding seconds .
apFst :: (a -> b -> c) -> ((a,d) -> (b,e) -> c)
apFst f (x,_) (y,_) = f x y
(===) :: (Eq b) => (a -> b) -> (a -> b) -> (a -> Bool)
(===) f g x = (==) (f x) (g x)
|
c7183d14e9829fd4881c133290a1ad4f0df45170c3a8ba7c6d58981305b5237c | johnstonskj/rml-core | data-sets.rkt | #lang racket/base
;;
;; Racket Machine Learning - Core.
;;
~ 2018 .
;;
(provide iris-data-set small-data-set)
;; ---------- Requirements
(require rml/data)
;; ---------- Implementation
(define iris-data-set
(load-data-set (path->string (collection-file-path "test/iris_training_data.csv" "rml"))
'csv
(list
(make-feature "sepal-length" #:index 0)
(make-feature "sepal-width" #:index 1)
(make-feature "petal-length" #:index 2)
(make-feature "petal-width" #:index 3)
(make-classifier "classification" #:index 4))))
(define small-data-set
(load-data-set (path->string (collection-file-path "test/simple-test.json" "rml"))
'json
(list (make-feature "height") (make-classifier "class"))))
| null | https://raw.githubusercontent.com/johnstonskj/rml-core/8f3ca8b47e552911054f2aa12b296dbf40dad637/rml/test/data-sets.rkt | racket |
Racket Machine Learning - Core.
---------- Requirements
---------- Implementation | #lang racket/base
~ 2018 .
(provide iris-data-set small-data-set)
(require rml/data)
(define iris-data-set
(load-data-set (path->string (collection-file-path "test/iris_training_data.csv" "rml"))
'csv
(list
(make-feature "sepal-length" #:index 0)
(make-feature "sepal-width" #:index 1)
(make-feature "petal-length" #:index 2)
(make-feature "petal-width" #:index 3)
(make-classifier "classification" #:index 4))))
(define small-data-set
(load-data-set (path->string (collection-file-path "test/simple-test.json" "rml"))
'json
(list (make-feature "height") (make-classifier "class"))))
|
65cc08c59f7449e3c2d9b8e0cfd903ce93b997fbc739faea3a13f86ece11553f | chameco/Hitman | project.clj | (defproject hitman "0.1.0"
:description "a clojure markdown engine"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[hiccup "1.0.4"]
[instaparse "1.2.2"]
[me.raynes/fs "1.4.4"]]
:scm {:name "git"
:url ""}
:main hitman.core)
| null | https://raw.githubusercontent.com/chameco/Hitman/8ccf13cd8ade058d204aa7c1f311e5f17793aab9/project.clj | clojure | (defproject hitman "0.1.0"
:description "a clojure markdown engine"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[hiccup "1.0.4"]
[instaparse "1.2.2"]
[me.raynes/fs "1.4.4"]]
:scm {:name "git"
:url ""}
:main hitman.core)
| |
28ccc9bd295004a6c11ae75449fe9dffea5748bb10b32a000c0ec407a14e8e0c | danieljharvey/mimsa | Main.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
module Repl.Main
( repl,
)
where
import Control.Monad.Except
import Control.Monad.Logger
import Data.Text (Text)
import qualified Data.Text as T
import Language.Mimsa.Core
import Language.Mimsa.Types.Error
import Language.Mimsa.Types.Project
import Language.Mimsa.Types.Store.RootPath
import Repl.Actions (doReplAction)
import Repl.Helpers
import Repl.Parser (replParser)
import Repl.Persistence
import Repl.ReplM
import Repl.Types
import qualified Shared.LoadProject as Shared
import System.Console.Haskeline
import System.Directory
import Text.Megaparsec
createReplConfig :: (MonadIO m) => Bool -> m ReplConfig
createReplConfig showLogs' = do
path <- liftIO getCurrentDirectory
pure $ ReplConfig (RootPath path) showLogs'
getProject :: ReplM (Error Annotation) (Project Annotation)
getProject =
do
maybeProject <- Shared.loadProject
case maybeProject of
Right prj -> do
let moduleItems = length . prjModuleStore $ prj
replOutput ("Successfully loaded project." :: Text)
replOutput $ T.pack (show moduleItems) <> " modules found"
pure prj
Left e -> do
logDebugN (prettyPrint e)
replOutput @Text "Failed to load project, have you initialised a project in this folder?"
throwError e
repl :: Bool -> IO ()
repl showLogs' = do
cfg <- createReplConfig showLogs'
_ <- runReplM cfg replLoop
pure ()
replLoop :: ReplM (Error Annotation) ()
replLoop = do
env <- getProject
_ <- doReplAction env Help
runInputT defaultSettings (loop env)
where
loop ::
Project Annotation ->
InputT (ReplM (Error Annotation)) ()
loop exprs' = do
minput <- getInputLine ":> "
case minput of
Nothing -> return ()
Just ":quit" -> return ()
Just input -> do
newEnv <- lift $ parseCommand exprs' (T.pack input)
loop newEnv
parseCommand ::
Project Annotation ->
Text ->
ReplM (Error Annotation) (Project Annotation)
parseCommand env input =
case parse replParser "<repl>" input of
Left errBundle -> do
outputErrorAsDiagnostic (ParseError input errBundle)
pure env
Right replAction -> do
newExprs <- doReplAction env replAction
_ <- mapError StoreErr (saveProject newExprs)
pure newExprs
| null | https://raw.githubusercontent.com/danieljharvey/mimsa/564c32cc28d990c9e686f63533a9e30c3736aee4/repl/repl/Repl/Main.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TypeApplications #
module Repl.Main
( repl,
)
where
import Control.Monad.Except
import Control.Monad.Logger
import Data.Text (Text)
import qualified Data.Text as T
import Language.Mimsa.Core
import Language.Mimsa.Types.Error
import Language.Mimsa.Types.Project
import Language.Mimsa.Types.Store.RootPath
import Repl.Actions (doReplAction)
import Repl.Helpers
import Repl.Parser (replParser)
import Repl.Persistence
import Repl.ReplM
import Repl.Types
import qualified Shared.LoadProject as Shared
import System.Console.Haskeline
import System.Directory
import Text.Megaparsec
createReplConfig :: (MonadIO m) => Bool -> m ReplConfig
createReplConfig showLogs' = do
path <- liftIO getCurrentDirectory
pure $ ReplConfig (RootPath path) showLogs'
getProject :: ReplM (Error Annotation) (Project Annotation)
getProject =
do
maybeProject <- Shared.loadProject
case maybeProject of
Right prj -> do
let moduleItems = length . prjModuleStore $ prj
replOutput ("Successfully loaded project." :: Text)
replOutput $ T.pack (show moduleItems) <> " modules found"
pure prj
Left e -> do
logDebugN (prettyPrint e)
replOutput @Text "Failed to load project, have you initialised a project in this folder?"
throwError e
repl :: Bool -> IO ()
repl showLogs' = do
cfg <- createReplConfig showLogs'
_ <- runReplM cfg replLoop
pure ()
replLoop :: ReplM (Error Annotation) ()
replLoop = do
env <- getProject
_ <- doReplAction env Help
runInputT defaultSettings (loop env)
where
loop ::
Project Annotation ->
InputT (ReplM (Error Annotation)) ()
loop exprs' = do
minput <- getInputLine ":> "
case minput of
Nothing -> return ()
Just ":quit" -> return ()
Just input -> do
newEnv <- lift $ parseCommand exprs' (T.pack input)
loop newEnv
parseCommand ::
Project Annotation ->
Text ->
ReplM (Error Annotation) (Project Annotation)
parseCommand env input =
case parse replParser "<repl>" input of
Left errBundle -> do
outputErrorAsDiagnostic (ParseError input errBundle)
pure env
Right replAction -> do
newExprs <- doReplAction env replAction
_ <- mapError StoreErr (saveProject newExprs)
pure newExprs
|
f9cfea9ced97907e26634e8a5bdb7b93d17cc0ca6877f300976db455a2790096 | FranklinChen/hugs98-plus-Sep2006 | Points.hs | --------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Points
Copyright : ( c ) 2002 - 2005
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
This module corresponds to section 3.3 ( Points ) of the OpenGL 1.5 specs .
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Points (
-- * Point Rasterization
pointSize,
-- * Controlling the Derived Size
pointSizeRange, pointDistanceAttenuation,
-- * Fading Points
pointFadeThresholdSize,
*
pointSmooth,
-- * Point Sprites
pointSprite,
-- * Implementation-Dependent Limits
aliasedPointSizeRange, smoothPointSizeRange, smoothPointSizeGranularity
) where
import Control.Monad ( liftM2 )
import Foreign.Marshal.Array ( withArray )
import Graphics.Rendering.OpenGL.GL.Capability (
EnableCap(CapPointSmooth,CapPointSprite), makeCapability )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLfloat, Capability )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetPointSize,GetAliasedPointSizeRange,GetSmoothPointSizeRange,
GetSmoothPointSizeGranularity,GetPointSizeMin,GetPointSizeMax,
GetPointDistanceAttenuation,GetPointFadeThresholdSize),
getFloat1, getFloat2, getFloat3 )
import Graphics.Rendering.OpenGL.GL.PointParameter (
PointParameter(..), pointParameterf, pointParameterfv )
import Graphics.Rendering.OpenGL.GL.StateVar (
GettableStateVar, makeGettableStateVar, StateVar, makeStateVar )
--------------------------------------------------------------------------------
-- | 'pointSize' contains the rasterized diameter of both aliased and
antialiased points . The initial value is 1 . Using a point size other than 1
-- has different effects, depending on whether point antialiasing is enabled
( see ' pointSmooth ' ) or point sprites are enabled ( see ' ' ) . Both
-- are initially disabled.
--
-- The specified point size is multiplied with a distance attenuation factor
-- and clamped to the specified 'pointSizeRange', and further clamped to the
-- implementation-dependent point size range to produce the derived point size
-- using
--
@ = /clamp/ ( /size/ * /sqrt/ ( 1 \/ ( /a/ + /b/ * /d/ + /c/ * /d/^2)))@
--
-- where /d/ is the eye-coordinate distance from the eye to the vertex, and /a/,
-- /b/, and /c/ are the distance attenuation coefficients (see
-- 'pointDistanceAttenuation').
--
If multisampling is disabled , the computed point size is used as the point\ 's
-- width.
--
-- If multisampling is enabled, the point may be faded by modifying the point
-- alpha value (see 'Graphics.Rendering.OpenGL.GL.PerFragment.sampleCoverage')
-- instead of allowing the point width to go below a given
-- 'pointFadeThresholdSize'. In this case, the width is further modified in
-- the following manner:
--
@ /width/ = if > = /threshold/ then /derivedSize/ else /threshold/@
--
-- The point alpha value is modified by computing:
--
@ /alpha/ = if > = /threshold/ then 1 else ( /derivedSize/ \/ /threshold/)^2@
--
-- If point antialiasing is disabled, the actual size is determined by rounding
-- the supplied size to the nearest integer. (If the rounding results in the
value 0 , it is as if the point size were 1 . ) If the rounded size is odd ,
-- then the center point (/x/, /y/) of the pixel fragment that represents
-- the point is computed as
--
-- @ (/x/, /y/) = (/floor/ /xw/ + 0.5, /floor/ /yw/ + 0.5)@
--
-- where /xw/ and /yw/ indicate window coordinates. All pixels that lie within
-- the square grid of the rounded size centered at (/x/, /y/) make up the
-- fragment. If the size is even, the center point is
--
-- @ (/x/, /y/) = (/floor/ (/xw/ + 0.5), /floor/ (/yw/ + 0.5))@
--
and the rasterized fragment\ 's centers are the half - integer window
-- coordinates within the square of the rounded size centered at (/x/, /y/). All
-- pixel fragments produced in rasterizing a nonantialiased point are assigned
-- the same associated data, that of the vertex corresponding to the point.
--
-- If antialiasing is enabled, then point rasterization produces a fragment for
-- each pixel square that intersects the region lying within the circle having
diameter equal to the current point size and centered at the point\ 's
-- (/xw/, /yw/). The coverage value for each fragment is the window coordinate
-- area of the intersection of the circular region with the corresponding pixel
-- square. This value is saved and used in the final rasterization step. The
-- data associated with each fragment is the data associated with the point
-- being rasterized.
--
-- Not all sizes are supported when point antialiasing is enabled. If an
-- unsupported size is requested, the nearest supported size is used. Only size
1 is guaranteed to be supported ; others depend on the implementation . To
-- query the range of supported sizes for antialiased points and the size
-- difference between supported sizes within the range, query
-- 'smoothPointSizeRange' and 'smoothPointSizeGranularity', respectively. For
-- aliased points, query the supported range with 'aliasedPointSizeRange'.
--
-- The point size specified when 'pointSize' is set is always returned when it
-- is queried. Clamping and rounding for aliased and antialiased points have no
-- effect on the specified value.
--
-- A non-antialiased point size may be clamped to an implementation-dependent
-- maximum. Although this maximum cannot be queried, it must be no less than the
-- maximum value for antialiased points, rounded to the nearest integer value.
--
An ' Graphics . Rendering . OpenGL.GLU.Errors . InvalidValue ' is generated if
' pointSize ' is set to a value less than or equal to zero .
--
-- An 'Graphics.Rendering.OpenGL.GLU.Errors.InvalidOperation' is generated if
-- 'pointSize' is set during
-- 'Graphics.Rendering.OpenGL.GL.BeginEnd.renderPrimitive'.
pointSize :: StateVar GLfloat
pointSize = makeStateVar (getFloat1 id GetPointSize) glPointSize
foreign import CALLCONV unsafe "glPointSize" glPointSize :: GLfloat -> IO ()
--------------------------------------------------------------------------------
-- | The range to which the derived point size is clamped, see 'pointSize'. Note
-- that the size is further clamped to the implementation-dependent limits, see
-- 'aliasedPointSizeRange' and 'smoothPointSizeRange'. The initial range is
( 0 , 1 ) .
--
An ' Graphics . Rendering . OpenGL.GLU.Errors . InvalidValue ' is generated if the
lower or upper bound of the range is set to a value less than zero . If the
-- lower bound is greater than the upper bound, the point size after clamping is
-- undefined, but no error is generated.
pointSizeRange :: StateVar (GLfloat, GLfloat)
pointSizeRange =
makeStateVar
(liftM2 (,) (getFloat1 id GetPointSizeMin) (getFloat1 id GetPointSizeMax))
(\(sizeMin, sizeMax) -> do pointParameterf PointSizeMin sizeMin
pointParameterf PointSizeMax sizeMax)
--------------------------------------------------------------------------------
| The constant , linear , and quadratic distance attenuation coefficients , see
' pointSize ' . The initial coefficients are ( 1 , 0 , 0 ) .
pointDistanceAttenuation :: StateVar (GLfloat, GLfloat, GLfloat)
pointDistanceAttenuation =
makeStateVar
(getFloat3 (,,) GetPointDistanceAttenuation)
(\(a, b, c) -> withArray [a, b, c] $
pointParameterfv PointDistanceAttenuation)
--------------------------------------------------------------------------------
-- | The threshold for alpha attenuation of points when multisampling is used,
see ' pointSize ' . The initial threshold is 1 .
--
An ' Graphics . Rendering . OpenGL.GLU.Errors . InvalidValue ' is generated if the
threshold is set to a value less than zero .
pointFadeThresholdSize :: StateVar GLfloat
pointFadeThresholdSize =
makeStateVar
(getFloat1 id GetPointFadeThresholdSize)
(pointParameterf PointFadeThresholdSize)
--------------------------------------------------------------------------------
-- | Controls whether point antialiasing is enabled. The initial state is
-- 'Graphics.Rendering.OpenGL.GL.BasicTypes.Disabled'.
pointSmooth :: StateVar Capability
pointSmooth = makeCapability CapPointSmooth
--------------------------------------------------------------------------------
-- | Controls whether point sprites are enabled. The initial state is
-- 'Graphics.Rendering.OpenGL.GL.BasicTypes.Disabled'. When point sprites are
-- enabled, the state of point antialiasing (i.e. 'pointSmooth') is ignored.
pointSprite :: StateVar Capability
pointSprite = makeCapability CapPointSprite
--------------------------------------------------------------------------------
-- | The smallest and largest supported size of aliased points.
aliasedPointSizeRange :: GettableStateVar (GLfloat, GLfloat)
aliasedPointSizeRange =
makeGettableStateVar $ getFloat2 (,) GetAliasedPointSizeRange
-- | The smallest and largest supported size of antialiased points.
smoothPointSizeRange :: GettableStateVar (GLfloat, GLfloat)
smoothPointSizeRange =
makeGettableStateVar $ getFloat2 (,) GetSmoothPointSizeRange
-- | The antialiased point size granularity, i.e. the size difference between
-- supported sizes.
smoothPointSizeGranularity :: GettableStateVar GLfloat
smoothPointSizeGranularity =
makeGettableStateVar $ getFloat1 id GetSmoothPointSizeGranularity
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/OpenGL/Graphics/Rendering/OpenGL/GL/Points.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.Rendering.OpenGL.GL.Points
License : BSD-style (see the file libraries/OpenGL/LICENSE)
Maintainer :
Stability : provisional
Portability : portable
------------------------------------------------------------------------------
* Point Rasterization
* Controlling the Derived Size
* Fading Points
* Point Sprites
* Implementation-Dependent Limits
------------------------------------------------------------------------------
| 'pointSize' contains the rasterized diameter of both aliased and
has different effects, depending on whether point antialiasing is enabled
are initially disabled.
The specified point size is multiplied with a distance attenuation factor
and clamped to the specified 'pointSizeRange', and further clamped to the
implementation-dependent point size range to produce the derived point size
using
where /d/ is the eye-coordinate distance from the eye to the vertex, and /a/,
/b/, and /c/ are the distance attenuation coefficients (see
'pointDistanceAttenuation').
width.
If multisampling is enabled, the point may be faded by modifying the point
alpha value (see 'Graphics.Rendering.OpenGL.GL.PerFragment.sampleCoverage')
instead of allowing the point width to go below a given
'pointFadeThresholdSize'. In this case, the width is further modified in
the following manner:
The point alpha value is modified by computing:
If point antialiasing is disabled, the actual size is determined by rounding
the supplied size to the nearest integer. (If the rounding results in the
then the center point (/x/, /y/) of the pixel fragment that represents
the point is computed as
@ (/x/, /y/) = (/floor/ /xw/ + 0.5, /floor/ /yw/ + 0.5)@
where /xw/ and /yw/ indicate window coordinates. All pixels that lie within
the square grid of the rounded size centered at (/x/, /y/) make up the
fragment. If the size is even, the center point is
@ (/x/, /y/) = (/floor/ (/xw/ + 0.5), /floor/ (/yw/ + 0.5))@
coordinates within the square of the rounded size centered at (/x/, /y/). All
pixel fragments produced in rasterizing a nonantialiased point are assigned
the same associated data, that of the vertex corresponding to the point.
If antialiasing is enabled, then point rasterization produces a fragment for
each pixel square that intersects the region lying within the circle having
(/xw/, /yw/). The coverage value for each fragment is the window coordinate
area of the intersection of the circular region with the corresponding pixel
square. This value is saved and used in the final rasterization step. The
data associated with each fragment is the data associated with the point
being rasterized.
Not all sizes are supported when point antialiasing is enabled. If an
unsupported size is requested, the nearest supported size is used. Only size
query the range of supported sizes for antialiased points and the size
difference between supported sizes within the range, query
'smoothPointSizeRange' and 'smoothPointSizeGranularity', respectively. For
aliased points, query the supported range with 'aliasedPointSizeRange'.
The point size specified when 'pointSize' is set is always returned when it
is queried. Clamping and rounding for aliased and antialiased points have no
effect on the specified value.
A non-antialiased point size may be clamped to an implementation-dependent
maximum. Although this maximum cannot be queried, it must be no less than the
maximum value for antialiased points, rounded to the nearest integer value.
An 'Graphics.Rendering.OpenGL.GLU.Errors.InvalidOperation' is generated if
'pointSize' is set during
'Graphics.Rendering.OpenGL.GL.BeginEnd.renderPrimitive'.
------------------------------------------------------------------------------
| The range to which the derived point size is clamped, see 'pointSize'. Note
that the size is further clamped to the implementation-dependent limits, see
'aliasedPointSizeRange' and 'smoothPointSizeRange'. The initial range is
lower bound is greater than the upper bound, the point size after clamping is
undefined, but no error is generated.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| The threshold for alpha attenuation of points when multisampling is used,
------------------------------------------------------------------------------
| Controls whether point antialiasing is enabled. The initial state is
'Graphics.Rendering.OpenGL.GL.BasicTypes.Disabled'.
------------------------------------------------------------------------------
| Controls whether point sprites are enabled. The initial state is
'Graphics.Rendering.OpenGL.GL.BasicTypes.Disabled'. When point sprites are
enabled, the state of point antialiasing (i.e. 'pointSmooth') is ignored.
------------------------------------------------------------------------------
| The smallest and largest supported size of aliased points.
| The smallest and largest supported size of antialiased points.
| The antialiased point size granularity, i.e. the size difference between
supported sizes. | Copyright : ( c ) 2002 - 2005
This module corresponds to section 3.3 ( Points ) of the OpenGL 1.5 specs .
module Graphics.Rendering.OpenGL.GL.Points (
pointSize,
pointSizeRange, pointDistanceAttenuation,
pointFadeThresholdSize,
*
pointSmooth,
pointSprite,
aliasedPointSizeRange, smoothPointSizeRange, smoothPointSizeGranularity
) where
import Control.Monad ( liftM2 )
import Foreign.Marshal.Array ( withArray )
import Graphics.Rendering.OpenGL.GL.Capability (
EnableCap(CapPointSmooth,CapPointSprite), makeCapability )
import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLfloat, Capability )
import Graphics.Rendering.OpenGL.GL.QueryUtils (
GetPName(GetPointSize,GetAliasedPointSizeRange,GetSmoothPointSizeRange,
GetSmoothPointSizeGranularity,GetPointSizeMin,GetPointSizeMax,
GetPointDistanceAttenuation,GetPointFadeThresholdSize),
getFloat1, getFloat2, getFloat3 )
import Graphics.Rendering.OpenGL.GL.PointParameter (
PointParameter(..), pointParameterf, pointParameterfv )
import Graphics.Rendering.OpenGL.GL.StateVar (
GettableStateVar, makeGettableStateVar, StateVar, makeStateVar )
antialiased points . The initial value is 1 . Using a point size other than 1
( see ' pointSmooth ' ) or point sprites are enabled ( see ' ' ) . Both
@ = /clamp/ ( /size/ * /sqrt/ ( 1 \/ ( /a/ + /b/ * /d/ + /c/ * /d/^2)))@
If multisampling is disabled , the computed point size is used as the point\ 's
@ /width/ = if > = /threshold/ then /derivedSize/ else /threshold/@
@ /alpha/ = if > = /threshold/ then 1 else ( /derivedSize/ \/ /threshold/)^2@
value 0 , it is as if the point size were 1 . ) If the rounded size is odd ,
and the rasterized fragment\ 's centers are the half - integer window
diameter equal to the current point size and centered at the point\ 's
1 is guaranteed to be supported ; others depend on the implementation . To
An ' Graphics . Rendering . OpenGL.GLU.Errors . InvalidValue ' is generated if
' pointSize ' is set to a value less than or equal to zero .
pointSize :: StateVar GLfloat
pointSize = makeStateVar (getFloat1 id GetPointSize) glPointSize
foreign import CALLCONV unsafe "glPointSize" glPointSize :: GLfloat -> IO ()
( 0 , 1 ) .
An ' Graphics . Rendering . OpenGL.GLU.Errors . InvalidValue ' is generated if the
lower or upper bound of the range is set to a value less than zero . If the
pointSizeRange :: StateVar (GLfloat, GLfloat)
pointSizeRange =
makeStateVar
(liftM2 (,) (getFloat1 id GetPointSizeMin) (getFloat1 id GetPointSizeMax))
(\(sizeMin, sizeMax) -> do pointParameterf PointSizeMin sizeMin
pointParameterf PointSizeMax sizeMax)
| The constant , linear , and quadratic distance attenuation coefficients , see
' pointSize ' . The initial coefficients are ( 1 , 0 , 0 ) .
pointDistanceAttenuation :: StateVar (GLfloat, GLfloat, GLfloat)
pointDistanceAttenuation =
makeStateVar
(getFloat3 (,,) GetPointDistanceAttenuation)
(\(a, b, c) -> withArray [a, b, c] $
pointParameterfv PointDistanceAttenuation)
see ' pointSize ' . The initial threshold is 1 .
An ' Graphics . Rendering . OpenGL.GLU.Errors . InvalidValue ' is generated if the
threshold is set to a value less than zero .
pointFadeThresholdSize :: StateVar GLfloat
pointFadeThresholdSize =
makeStateVar
(getFloat1 id GetPointFadeThresholdSize)
(pointParameterf PointFadeThresholdSize)
pointSmooth :: StateVar Capability
pointSmooth = makeCapability CapPointSmooth
pointSprite :: StateVar Capability
pointSprite = makeCapability CapPointSprite
aliasedPointSizeRange :: GettableStateVar (GLfloat, GLfloat)
aliasedPointSizeRange =
makeGettableStateVar $ getFloat2 (,) GetAliasedPointSizeRange
smoothPointSizeRange :: GettableStateVar (GLfloat, GLfloat)
smoothPointSizeRange =
makeGettableStateVar $ getFloat2 (,) GetSmoothPointSizeRange
smoothPointSizeGranularity :: GettableStateVar GLfloat
smoothPointSizeGranularity =
makeGettableStateVar $ getFloat1 id GetSmoothPointSizeGranularity
|
a901fe17eba03341efdfa17b75851a26ced9fb8afcb7bc9e0051520bbba23cd2 | samrocketman/home | strdflash.scm | (define (apply-strdflash-effect img logo-layer noisev bcolor npix scolor numframe)
(let* ( (width (car (gimp-drawable-width logo-layer)))
(height (car (gimp-drawable-height logo-layer)))
(tmpLayer)
(txtLayer)
(newLayer)
(nframe)
(cnt)
)
(gimp-context-push)
(script-fu-util-image-resize-from-layer img logo-layer)
(gimp-selection-layer-alpha logo-layer)
(gimp-selection-grow img npix)
(set! tmpLayer (car (gimp-layer-copy logo-layer FALSE)))
(gimp-image-add-layer img tmpLayer 0)
(gimp-context-set-foreground bcolor)
(gimp-edit-fill tmpLayer FOREGROUND-FILL)
(gimp-selection-layer-alpha logo-layer)
(set! txtLayer (car (gimp-image-merge-visible-layers img 0)))
(gimp-context-set-foreground scolor)
(gimp-edit-fill txtLayer FOREGROUND-FILL)
(set! nframe (- numframe 1))
(set! cnt 0)
(while (< cnt nframe)
(set! newLayer (car (gimp-layer-copy txtLayer FALSE)))
(gimp-image-add-layer img newLayer 0)
( plug - in - scatter - rgb 1 0 0 noisev 0 )
(plug-in-scatter-hsv 1 img newLayer noisev 20 0 255)
(set! cnt (+ cnt 1))
)
( plug - in - scatter - rgb 1 img txtLayer 0 0 noisev 0 )
(plug-in-scatter-hsv 1 img txtLayer noisev 20 0 255)
(gimp-selection-none img)
(gimp-context-set-foreground '(255 255 255))
(gimp-context-pop)
)
)
(define (script-fu-strdflash text size font noisev bcolor npix scolor numframe)
(let* (
(img (car (gimp-image-new 256 256 RGB)))
(text-layer (car (gimp-text-fontname img -1 0 0 text 10 0 size PIXELS font)))
)
(gimp-image-undo-disable img)
(gimp-drawable-set-name text-layer " ")
(apply-strdflash-effect img text-layer noisev bcolor npix scolor numframe)
(gimp-image-undo-enable img)
(gimp-display-new img)
)
)
(script-fu-register "script-fu-strdflash"
_"_ ..."
" "
"JamesH"
"JamesH"
"09/19/2006"
""
SF-TEXT _"Text" "The Gimp "
SF-ADJUSTMENT _"Font size (pixels)" '(52 12 1000 1 10 0 1)
SF-FONT _"Font" "Becker"
SF-ADJUSTMENT " " '(4 1 8 1 2 0 1)
SF-COLOR _" " '(252 0 252)
SF-ADJUSTMENT " " '(2 1 16 1 8 0 0)
SF-COLOR _" " '(0 192 252)
SF-ADJUSTMENT " " '(3 2 32 1 8 0 0))
(script-fu-menu-register "script-fu-strdflash"
_"<Toolbox>/Xtns/Script-Fu/Logos")
| null | https://raw.githubusercontent.com/samrocketman/home/63a8668a71dc594ea9ed76ec56bf8ca43b2a86ca/dotfiles/.gimp/scripts/strdflash.scm | scheme | (define (apply-strdflash-effect img logo-layer noisev bcolor npix scolor numframe)
(let* ( (width (car (gimp-drawable-width logo-layer)))
(height (car (gimp-drawable-height logo-layer)))
(tmpLayer)
(txtLayer)
(newLayer)
(nframe)
(cnt)
)
(gimp-context-push)
(script-fu-util-image-resize-from-layer img logo-layer)
(gimp-selection-layer-alpha logo-layer)
(gimp-selection-grow img npix)
(set! tmpLayer (car (gimp-layer-copy logo-layer FALSE)))
(gimp-image-add-layer img tmpLayer 0)
(gimp-context-set-foreground bcolor)
(gimp-edit-fill tmpLayer FOREGROUND-FILL)
(gimp-selection-layer-alpha logo-layer)
(set! txtLayer (car (gimp-image-merge-visible-layers img 0)))
(gimp-context-set-foreground scolor)
(gimp-edit-fill txtLayer FOREGROUND-FILL)
(set! nframe (- numframe 1))
(set! cnt 0)
(while (< cnt nframe)
(set! newLayer (car (gimp-layer-copy txtLayer FALSE)))
(gimp-image-add-layer img newLayer 0)
( plug - in - scatter - rgb 1 0 0 noisev 0 )
(plug-in-scatter-hsv 1 img newLayer noisev 20 0 255)
(set! cnt (+ cnt 1))
)
( plug - in - scatter - rgb 1 img txtLayer 0 0 noisev 0 )
(plug-in-scatter-hsv 1 img txtLayer noisev 20 0 255)
(gimp-selection-none img)
(gimp-context-set-foreground '(255 255 255))
(gimp-context-pop)
)
)
(define (script-fu-strdflash text size font noisev bcolor npix scolor numframe)
(let* (
(img (car (gimp-image-new 256 256 RGB)))
(text-layer (car (gimp-text-fontname img -1 0 0 text 10 0 size PIXELS font)))
)
(gimp-image-undo-disable img)
(gimp-drawable-set-name text-layer " ")
(apply-strdflash-effect img text-layer noisev bcolor npix scolor numframe)
(gimp-image-undo-enable img)
(gimp-display-new img)
)
)
(script-fu-register "script-fu-strdflash"
_"_ ..."
" "
"JamesH"
"JamesH"
"09/19/2006"
""
SF-TEXT _"Text" "The Gimp "
SF-ADJUSTMENT _"Font size (pixels)" '(52 12 1000 1 10 0 1)
SF-FONT _"Font" "Becker"
SF-ADJUSTMENT " " '(4 1 8 1 2 0 1)
SF-COLOR _" " '(252 0 252)
SF-ADJUSTMENT " " '(2 1 16 1 8 0 0)
SF-COLOR _" " '(0 192 252)
SF-ADJUSTMENT " " '(3 2 32 1 8 0 0))
(script-fu-menu-register "script-fu-strdflash"
_"<Toolbox>/Xtns/Script-Fu/Logos")
| |
f0628d0176cc046aafc1d7f487728d496d873733bc00f4f56d756dc17684e1d9 | BranchTaken/Hemlock | ordmap.mli | (** Ordered map. *)
type ('k, 'v, 'cmp) t
include MapIntf.SOrd with type ('k, 'v, 'cmp) t := ('k, 'v, 'cmp) t
(* Exposed for testing purposes only. *)
val fmt_internals: ?alt:bool -> ?width:int64
-> ('v -> (module Fmt.Formatter) -> (module Fmt.Formatter)) -> ('k, 'v, 'cmp) t
-> (module Fmt.Formatter) -> (module Fmt.Formatter)
val validate: ('k, 'v, 'cmp) t -> unit
| null | https://raw.githubusercontent.com/BranchTaken/Hemlock/a21b462fe7f70475591d2ffae185c91552bf6372/bootstrap/src/basis/ordmap.mli | ocaml | * Ordered map.
Exposed for testing purposes only. |
type ('k, 'v, 'cmp) t
include MapIntf.SOrd with type ('k, 'v, 'cmp) t := ('k, 'v, 'cmp) t
val fmt_internals: ?alt:bool -> ?width:int64
-> ('v -> (module Fmt.Formatter) -> (module Fmt.Formatter)) -> ('k, 'v, 'cmp) t
-> (module Fmt.Formatter) -> (module Fmt.Formatter)
val validate: ('k, 'v, 'cmp) t -> unit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.